DEV Community

Dev Notes
Dev Notes

Posted on

A unified Python client for public crypto tickers and order books

Every major exchange will give you the top of the order book over a plain HTTP GET with no API key. They just disagree on everything else: the path, the symbol format, the JSON envelope, and even what the default depth is. I wanted one function that returns the same dataclass no matter which venue I ask, so here is the small stdlib-only client I ended up with. It covers OKX, Bybit, Binance, MEXC, and Bitget, and it keeps going when one of them refuses to talk to me.

Why "top of book" looks different everywhere

All five venues expose the same idea: best bid, best ask, and the size at each. The differences are mechanical:

Exchange Ticker path Book path Symbol style Success signal
OKX /api/v5/market/ticker /api/v5/market/books BTC-USDT code == "0"
Bybit /v5/market/tickers /v5/market/orderbook BTCUSDT retCode == 0
Binance /api/v3/ticker/bookTicker /api/v3/depth BTCUSDT object returned directly
MEXC /api/v3/ticker/bookTicker /api/v3/depth BTCUSDT object returned directly
Bitget /api/v2/spot/market/tickers /api/v2/spot/market/orderbook BTCUSDT code == "00000"

Binance and MEXC return the payload as a bare object, so there is no envelope to check. Binance errors come back with an HTTP 4xx status plus a body like {"code": -1121, "msg": "Invalid symbol."}. OKX, Bybit, and Bitget wrap everything and signal failure inside a 200-style body, so you must check the code field, not just the HTTP status.

Official docs I used:

The common structure and symbol mapper

I keep one dataclass and one canonical input, a (base, quote) pair. The mapper only needs two formats: OKX uses a dash, and the other four use the concatenated form. I'm not guessing any other formats.

from __future__ import annotations

import json
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass, field
from typing import Any

TIMEOUT = 8.0


@dataclass
class Quote:
    exchange: str
    symbol: str
    bid: float
    ask: float
    bid_size: float
    ask_size: float
    ts: int | None = None
    raw: Any = field(default=None, repr=False)


class ExchangeError(Exception):
    pass


def map_symbol(exchange: str, base: str, quote: str) -> str:
    base, quote = base.upper(), quote.upper()
    if exchange == "okx":
        return f"{base}-{quote}"
    return f"{base}{quote}"  # bybit, binance, mexc, bitget


def http_get(url: str, params: dict[str, Any]) -> Any:
    full = f"{url}?{urllib.parse.urlencode(params)}"
    req = urllib.request.Request(full, headers={"User-Agent": "unified-md/0.1"})
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as e:
        body = e.read().decode("utf-8", "replace")[:200]
        raise ExchangeError(f"HTTP {e.code} from {url}: {body}") from e
    except urllib.error.URLError as e:
        raise ExchangeError(f"network error for {url}: {e.reason}") from e
    except TimeoutError as e:
        raise ExchangeError(f"timeout for {url}") from e
Enter fullscreen mode Exit fullscreen mode

One thing I do on every HTTP error: surface the status code. You will see HTTP 451 or 403 from some networks. In my own test environment, api.binance.com returned 451 and api.bybit.com returned 403. That is an observed geo/access effect from my IP, not an official policy statement, but it is exactly why the client must degrade gracefully.

get_ticker

Each venue gets a small parser. The OKX ticker data[0] has bidPx, bidSz, askPx, askSz, and ts. Bybit spot tickers return result.list[] with bid1Price, bid1Size, ask1Price, ask1Size. Bitget returns data[] with bidPr, askPr, bidSz, askSz, ts.

For Binance I use https://data-api.binance.vision, which the official docs list as the market-data-only base (no authentication). The general base is https://api.binance.com, and the FAQ page above lists /api/v3/ticker/bookTicker and /api/v3/depth as available on the market-data-only host.

BASES = {
    "okx": "https://www.okx.com",
    "bybit": "https://api.bybit.com",
    "binance": "https://data-api.binance.vision",
    "mexc": "https://api.mexc.com",
    "bitget": "https://api.bitget.com",
}


def get_ticker(exchange: str, base: str, quote: str) -> Quote:
    sym = map_symbol(exchange, base, quote)
    b = BASES[exchange]

    if exchange == "okx":
        j = http_get(f"{b}/api/v5/market/ticker", {"instId": sym})
        if j.get("code") != "0":
            raise ExchangeError(f"okx code={j.get('code')} msg={j.get('msg')}")
        d = j["data"][0]
        return Quote("okx", sym, float(d["bidPx"]), float(d["askPx"]),
                     float(d["bidSz"]), float(d["askSz"]), int(d["ts"]), d)

    if exchange == "bybit":
        j = http_get(f"{b}/v5/market/tickers", {"category": "spot", "symbol": sym})
        if j.get("retCode") != 0:
            raise ExchangeError(f"bybit retCode={j.get('retCode')} msg={j.get('retMsg')}")
        d = j["result"]["list"][0]
        return Quote("bybit", sym, float(d["bid1Price"]), float(d["ask1Price"]),
                     float(d["bid1Size"]), float(d["ask1Size"]), j.get("time"), d)

    if exchange in ("binance", "mexc"):
        d = http_get(f"{b}/api/v3/ticker/bookTicker", {"symbol": sym})
        if "code" in d and "bidPrice" not in d:
            raise ExchangeError(f"{exchange} code={d.get('code')} msg={d.get('msg')}")
        return Quote(exchange, sym, float(d["bidPrice"]), float(d["askPrice"]),
                     float(d["bidQty"]), float(d["askQty"]), None, d)

    if exchange == "bitget":
        j = http_get(f"{b}/api/v2/spot/market/tickers", {"symbol": sym})
        if j.get("code") != "00000":
            raise ExchangeError(f"bitget code={j.get('code')} msg={j.get('msg')}")
        d = j["data"][0]
        return Quote("bitget", sym, float(d["bidPr"]), float(d["askPr"]),
                     float(d["bidSz"]), float(d["askSz"]), int(d["ts"]), d)

    raise ValueError(f"unknown exchange {exchange}")
Enter fullscreen mode Exit fullscreen mode

Note that the Binance and MEXC bookTicker responses carry no timestamp, so ts stays None. Don't invent one; if you need it, stamp the local receive time yourself and label it as such.

get_orderbook, and the default-depth trap

The top-of-book ticker is cheap. If you want real depth, the defaults will bite you:

  • OKX /api/v5/market/books: sz is optional, max 400, and the default returns 1 level per side.
  • Bybit /v5/market/orderbook: for spot, limit is in [1, 1000] with a default of 1.
  • Binance /api/v3/depth: limit up to 7500; IP weight grows with the limit (5 for limits 1 to 100, 25 for 101 to 500, and higher beyond that).
  • MEXC /api/v3/depth: default limit 100, max 5000.
  • Bitget /api/v2/spot/market/orderbook: type defaults to step0, limit default and maximum are both 150.

So I take a depth argument and pass it explicitly everywhere. Levels normalize to [(price, size), ...].

def _levels(raw: list[list[Any]]) -> list[tuple[float, float]]:
    return [(float(x[0]), float(x[1])) for x in raw]


def get_orderbook(exchange: str, base: str, quote: str, depth: int = 5) -> dict[str, Any]:
    sym = map_symbol(exchange, base, quote)
    b = BASES[exchange]

    if exchange == "okx":
        j = http_get(f"{b}/api/v5/market/books", {"instId": sym, "sz": depth})
        if j.get("code") != "0":
            raise ExchangeError(f"okx code={j.get('code')} msg={j.get('msg')}")
        d = j["data"][0]  # asks/bids rows: [price, size, "0"(deprecated), orders]
        return {"exchange": "okx", "symbol": sym, "ts": int(d["ts"]),
                "bids": _levels(d["bids"]), "asks": _levels(d["asks"])}

    if exchange == "bybit":
        j = http_get(f"{b}/v5/market/orderbook",
                     {"category": "spot", "symbol": sym, "limit": depth})
        if j.get("retCode") != 0:
            raise ExchangeError(f"bybit retCode={j.get('retCode')} msg={j.get('retMsg')}")
        r = j["result"]
        return {"exchange": "bybit", "symbol": sym, "ts": r.get("ts"),
                "bids": _levels(r["b"]), "asks": _levels(r["a"])}

    if exchange in ("binance", "mexc"):
        d = http_get(f"{b}/api/v3/depth", {"symbol": sym, "limit": depth})
        if "bids" not in d:
            raise ExchangeError(f"{exchange} code={d.get('code')} msg={d.get('msg')}")
        return {"exchange": exchange, "symbol": sym, "ts": None,
                "bids": _levels(d["bids"]), "asks": _levels(d["asks"])}

    if exchange == "bitget":
        j = http_get(f"{b}/api/v2/spot/market/orderbook",
                     {"symbol": sym, "type": "step0", "limit": depth})
        if j.get("code") != "00000":
            raise ExchangeError(f"bitget code={j.get('code')} msg={j.get('msg')}")
        d = j["data"]
        return {"exchange": "bitget", "symbol": sym, "ts": int(d["ts"]),
                "bids": _levels(d["bids"]), "asks": _levels(d["asks"])}

    raise ValueError(f"unknown exchange {exchange}")
Enter fullscreen mode Exit fullscreen mode

OKX levels have four elements per row (price, size, a deprecated always-"0" field, order count), which is why _levels slices only the first two.

Running it across five venues

The main block loops over venues and catches ExchangeError per venue, so a 451 from one host doesn't kill the whole table.

def main() -> None:
    venues = ["okx", "bybit", "binance", "mexc", "bitget"]
    print(f"{'venue':<8}{'symbol':<10}{'bid':>14}{'ask':>14}{'bid_sz':>12}{'ask_sz':>12}")
    for v in venues:
        try:
            q = get_ticker(v, "BTC", "USDT")
            print(f"{q.exchange:<8}{q.symbol:<10}{q.bid:>14.2f}{q.ask:>14.2f}"
                  f"{q.bid_size:>12.4f}{q.ask_size:>12.4f}")
        except ExchangeError as e:
            print(f"{v:<8}FAILED: {e}")
        except (KeyError, IndexError, ValueError) as e:
            print(f"{v:<8}PARSE ERROR: {type(e).__name__}: {e}")


if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

I catch parse errors separately because a schema change is a different problem from a network failure, and I want the output to tell me which one happened.

Rate limits, at a high level

Unauthenticated public calls are limited per IP on these venues, per their docs. Exact numbers vary by endpoint, so I'll only state what the pages say:

  • OKX: the ticker endpoint is 20 requests per 2 seconds and books is 40 per 2 seconds, both per IP. Rejection returns error code 50011.
  • Bitget: tickers and orderbook are each 20 requests per second per IP.
  • Binance: limits are weight-based per IP; bookTicker for one symbol costs 2. A 429 means back off, and ignoring it leads to an HTTP 418 IP ban. Honor the Retry-After header. Read the live rateLimits array from /api/v3/exchangeInfo rather than hardcoding a number.
  • MEXC: IP-weighted endpoints share a pool per the introduction page; check the per-endpoint weight on each docs page. After a 429 you must stop sending requests.
  • Bybit: there is a documented IP cap (600 requests per 5 seconds by default) and a "403, access too frequent" ban that lasts at least 10 minutes. I did not find a market-endpoint quota in my notes, so read the X-Bapi-Limit* response headers and the official rate-limit page instead of guessing.

This client fires about five requests once, so it is nowhere near any limit. If you loop, add a sleep and respect those headers.

Caveats

A snapshot is stale the instant you receive it. OKX books update every 50 ms and the response is built from a server-side cache, so even "fresh" data has latency. Comparing quotes across venues fetched sequentially means you are comparing prices from different moments, which is fine for a dashboard and useless for anything latency-sensitive.

Geo and access errors are real. I saw HTTP 451 from api.binance.com and HTTP 403 from api.bybit.com in one environment. Binance documents data-api.binance.vision for market-data-only use, and Bybit mentions regional hostnames, so check the docs for an alternative base before assuming the code is broken.

Finally, this is market data plumbing, not a trading system and not a signal. Nothing here places orders, handles partial failures safely, or accounts for fees. Verify field names and limits against the official pages above before you depend on them, because exchanges revise these APIs.

Top comments (0)