Dev.to WebDev 🛠 Dev 👁 2 📖 7 min read

OKX UNLOCK20 and the public REST APIs of Binance, OKX and Bybit compared

If you write a single client that talks to several exchanges, the first thing you learn is that "public market data REST" means three different things. Rate limits, pagination, response envelopes and error behaviour all

If you write a single client that talks to several exchanges, the first thing you learn is that "public market data REST" means three different things. Rate limits, pagination, response envelopes and error behaviour all differ, and a wrapper that pretends otherwise breaks at 3 a.m. Here is how Binance Spot REST, OKX v5 and Bybit v5 differ, based only on what their official docs state. This is a design comparison, not a trading signal.

Official docs I'm drawing from:

The quick comparison

Axis Binance Spot OKX v5 Bybit v5
Base URL https://api.binance.com (also api-gcp, api1 to api4); https://data-api.binance.vision for market-data-only https://www.okx.com api.bybit.com (other hostnames exist, e.g. api.bybit.kz)
Symbol format BTCUSDT BTC-USDT (instId) BTCUSDT, uppercase only
Category/type param none instType on tickers category required on tickers/orderbook
Success shape bare JSON object/array {code, msg, data}, code "0" {retCode, retMsg, result, retExtInfo, time}, retCode 0
Rate-limit basis IP request weight per endpoint, per IP 600 req / 5 s per IP, plus per-UID limits
Rate-limit signal HTTP 429, then 418 error code 50011 HTTP 403 (IP), retCode 10006 (UID)

Note that Binance's api1 to api4 hosts are described as giving better performance but less stability.

Axis 1: rate limits

Binance uses IP-based request weight, not a flat request count. Every response carries an X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter) header with the weight your IP has used so far. Limits are by IP, not API key. Weights vary by endpoint: bookTicker costs 2 for one symbol and 4 if you omit the symbol or use symbols; depth costs 5 for limit 1-100, 25 for 101-500, 50 for 501-1000, 250 for 1001-5000, and 500 for 5001-7500. exchangeInfo itself costs 20 and returns a rateLimits array (RAW_REQUESTS, REQUEST_WEIGHT, ORDERS). The docs show an example of REQUEST_WEIGHT at 6000 per 1 minute, but that is only a documented example. Read the live rateLimits array and don't hard-code it.

Break the limit and you get HTTP 429. Keep hammering after 429s and you get an automated IP ban, HTTP 418. Both carry a Retry-After header (seconds).

OKX has no single global number for public REST. Public unauthenticated limits are per IP, and each endpoint has its own limit listed in its endpoint details. For example, ticker and tickers are 20 requests per 2 seconds, books is 40 per 2 seconds, and history-candles is 20 per 2 seconds. When rejected, the error code is 50011.

Bybit documents a coarse IP limit: 600 requests within a 5-second window per IP by default, covering api.bybit.com, api.bybick.com and local hostnames such as api.bybit.kz. If you see "403, access too frequent", terminate all HTTP sessions and wait at least 10 minutes; the ban lifts automatically. Separately, a per-UID rolling-window limit returns {"retCode": 10006, "retMsg": "Too many visits!"}. Responses expose X-Bapi-Limit, X-Bapi-Limit-Status and X-Bapi-Limit-Reset-Timestamp. I won't quote a per-second quota for the tickers or orderbook endpoints, because I don't have it from the official table. Check the rate-limit page and watch the headers.

Axis 2: pagination

None of these public market endpoints is a simple "next page token" API.

Binance uses limit plus time or ID parameters. Per the general REST page, data comes back chronologically unless noted. With no startTime/endTime you get the most recent items up to the limit; with startTime you get the oldest items from that time; with endTime the most recent up to that time; with both it behaves like startTime but won't exceed endTime. Timestamps are milliseconds by default. aggTrades accepts fromId, startTime, endTime and limit (max 1000, default 500). depth has no cursor at all; you just pick a limit (max 7500).

OKX uses after/before/limit. On candles and history-candles, after returns records earlier than the requested ts and before returns records newer than it; using before alone returns the latest data. limit max is 300, default 100. On history-trades there's a type parameter: 1 = tradeId, 2 = timestamp, default 1. after returns records earlier than the tradeId or ts; before returns newer records by tradeId and the docs state "Do not support timestamp for pagination." Limit is 100 max and default.

Bybit kline uses start, end (ms) and limit in [1, 1000], default 200. The result.list comes back sorted in reverse by startTime, so newest first. I'm not going to describe a cursor for public klines, because the docs I'm working from don't list one.

Axis 3: response shape

Binance returns the data directly:

{"symbol": "BTCUSDT", "bidPrice": "65000.10", "bidQty": "0.5", "askPrice": "65000.20", "askQty": "0.4"}

(Illustrative values.) Errors look like {"code": -1121, "msg": "Invalid symbol."}.

OKX wraps everything in {code, msg, data} with code as the string "0" on success, and the ticker sits in data[0]. Order-book levels are 4-field arrays: price, quantity, a deprecated field that is always "0", and number of orders at that price.

Bybit uses {retCode, retMsg, result, retExtInfo, time}, with retCode 0 meaning success. Tickers are in result.list. The orderbook uses short keys: s symbol, b bids, a asks, ts, u update ID, seq, cts.

Two gotchas. Bybit requires category (spot, linear, inverse, option) on tickers and orderbook, and on kline, omitting category defaults to linear, so always pass category=spot for spot. And the symbol formats differ: BTCUSDT on Binance and Bybit, BTC-USDT on OKX.

Axis 4: error handling

Binance: 4XX means a malformed request from the sender, 403 is a WAF rule violation (it can indicate a rate-limit violation or a security block), 429 is rate limiting, 418 is the IP ban, and 5XX is an internal error. For 5XX the docs say not to assume a confirmed failure, because execution status may be unknown (mostly relevant to trading). OKX signals rate limiting inside the JSON with 50011. Bybit signals IP abuse with HTTP 403 and UID abuse with retCode 10006.

So a shared classifier has to look at both the HTTP status and a per-exchange body. Here is a small one that backs off using Retry-After when present, otherwise exponential backoff:

import json
import time
import urllib.error
import urllib.request
from typing import Any

def classify(exchange: str, status: int, body: dict[str, Any] | None) -> str:
    """Return 'ok', 'retry', 'ban', or 'fatal'."""
    body = body or {}
    if exchange == "binance":
        if status == 418:
            return "ban"
        if status == 429:
            return "retry"
        if status >= 500:
            return "retry"
        return "ok" if status == 200 else "fatal"
    if exchange == "okx":
        if str(body.get("code")) == "50011":
            return "retry"
        return "ok" if str(body.get("code")) == "0" else "fatal"
    if exchange == "bybit":
        if status == 403:
            return "ban"  # docs: wait at least 10 minutes
        if body.get("retCode") == 10006:
            return "retry"
        return "ok" if body.get("retCode") == 0 else "fatal"
    return "fatal"

def get_json(exchange: str, url: str, max_tries: int = 5) -> dict[str, Any]:
    delay = 1.0
    for attempt in range(max_tries):
        retry_after = None
        try:
            with urllib.request.urlopen(url, timeout=10) as resp:
                status, raw = resp.status, resp.read()
        except urllib.error.HTTPError as e:
            status, raw = e.code, e.read()
            retry_after = e.headers.get("Retry-After")
        try:
            body = json.loads(raw)
        except ValueError:
            body = None
        verdict = classify(exchange, status, body)
        if verdict == "ok":
            return body if isinstance(body, dict) else {"data": body}
        if verdict in ("ban", "fatal"):
            raise RuntimeError(f"{exchange}: {verdict} status={status} body={body}")
        wait = float(retry_after) if retry_after else delay
        time.sleep(wait)
        delay *= 2
    raise RuntimeError(f"{exchange}: gave up after {max_tries} tries")

if __name__ == "__main__":
    url = "https://www.okx.com/api/v5/market/ticker?instId=BTC-USDT"
    print(get_json("okx", url))

Two honest caveats about this sketch. Binance success returns a bare array for some endpoints, which is why I wrap non-dict bodies. And for Bybit, I treat a 403 as a ban and raise rather than retry, since the docs say to stop all sessions and wait at least 10 minutes. Retrying in a loop would only make it worse. Don't pretend one envelope covers all three; the classify function exists precisely because each one signals trouble differently.

Operational notes

From my own environment, api.binance.com returned HTTP 451 and api.bybit.com returned HTTP 403. That's an observed geo/access restriction from some IPs, not an official policy claim. Binance documents https://data-api.binance.vision for public market-data-only REST, and Bybit mentions local hostnames, so check which host is right for your network.

Finally, none of these limits are guaranteed constants. Binance tells you to read rateLimits live, and Bybit and OKX publish tables per endpoint that can change. Re-read the linked pages before you ship anything that polls aggressively.

If you want an account to test against OKX's public endpoints, I use the code UNLOCK20 there.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.