DEV Community

Dev Notes
Dev Notes

Posted on

OKX UNLOCK20 bonus order book depth logger in Python

I wanted a small tool that answers one question: what does the top of the OKX order book look like right now, and how deep does it go? This article walks through a standard-library Python script that calls the public order book depth endpoint, sets the documented sz parameter explicitly, logs the sequence ID and timestamp, computes a simple imbalance figure, and backs off when OKX returns error 50011. It is a tooling walkthrough, not trading advice.

What the endpoint returns

The public order book lives at GET /api/v5/market/books on https://www.okx.com. You pass instId, for example BTC-USDT, and optionally sz, which sets how many price levels per side come back. The docs say sz defaults to one level and can go up to 400. If you leave it alone, you only see the best bid and best ask, so the script always sends it.

Responses use the usual OKX envelope: a code string, a msg string, and a data list. A code of "0" means success. The useful part is data[0], which holds asks, bids, a ts field for when the snapshot was generated, and a seqId that identifies the current message in the sequence.

Each level is a four-element array. The first item is the price, the second is the quantity at that price, the third is a deprecated field that always shows "0", and the fourth is the number of orders resting at that price. The quantity unit depends on the instrument. For derivatives it counts contracts, while for Spot and Spot Margin it counts the base currency. Check the unit before you compare two instruments, because the numbers alone will not tell you.

Snapshots, not a stream

The docs note that the endpoint updates on a 50 ms server-side cache. It does not hand you a live feed. It returns the latest cached state, so polling faster than the refresh interval will not give you fresher data. A one-second interval is plenty for a logger. If you need every change, this REST endpoint is the wrong tool, and you should look at a streaming interface instead.

The script

The script below uses only argparse, csv, json, time, urllib, and dataclasses. It takes --inst-id and --sz, validates sz against the documented 1 to 400 range, and either prints a table or writes a CSV file.

#!/usr/bin/env python3
"""Log OKX public order book depth snapshots using only the standard library."""
from __future__ import annotations

import argparse
import csv
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass

BASE_URL = "https://www.okx.com"
BOOKS_PATH = "/api/v5/market/books"
MAX_SZ = 400        # documented maximum levels per side
DEFAULT_SZ = 1      # documented default when sz is omitted
RATE_LIMIT_CODE = "50011"


class ApiError(Exception):
    def __init__(self, code: str, msg: str) -> None:
        super().__init__(f"OKX error {code}: {msg}")
        self.code = code
        self.msg = msg


@dataclass(frozen=True)
class Level:
    price: float
    size: float
    orders: int


@dataclass(frozen=True)
class BookSnapshot:
    inst_id: str
    ts: str            # raw value from the response, not converted
    seq_id: str
    asks: list[Level]
    bids: list[Level]

    def imbalance(self) -> float:
        """(bid qty - ask qty) / (bid qty + ask qty) over the fetched levels."""
        bid_qty = sum(level.size for level in self.bids)
        ask_qty = sum(level.size for level in self.asks)
        total = bid_qty + ask_qty
        return 0.0 if total == 0 else (bid_qty - ask_qty) / total


def parse_level(row: list[str]) -> Level:
    price, size, _deprecated, orders = row
    return Level(price=float(price), size=float(size), orders=int(orders))


def fetch_books(inst_id: str, sz: int, timeout: float = 10.0) -> BookSnapshot:
    query = urllib.parse.urlencode({"instId": inst_id, "sz": sz})
    request = urllib.request.Request(
        f"{BASE_URL}{BOOKS_PATH}?{query}",
        headers={"Accept": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            body = response.read()
    except urllib.error.HTTPError as exc:
        body = exc.read()  # the error may still arrive in the JSON envelope

    try:
        payload = json.loads(body.decode("utf-8"))
    except ValueError as exc:
        raise ApiError("bad-json", "response was not JSON") from exc

    code = str(payload.get("code", ""))
    if code != "0":
        raise ApiError(code, str(payload.get("msg", "")))

    data = payload.get("data") or []
    if not data:
        raise ApiError("empty", "no data in response")

    item = data[0]
    return BookSnapshot(
        inst_id=inst_id,
        ts=str(item["ts"]),
        seq_id=str(item["seqId"]),
        asks=[parse_level(row) for row in item["asks"]],
        bids=[parse_level(row) for row in item["bids"]],
    )


def fetch_with_backoff(
    inst_id: str, sz: int, max_retries: int = 5, base_delay: float = 0.5
) -> BookSnapshot:
    for attempt in range(max_retries + 1):
        try:
            return fetch_books(inst_id, sz)
        except ApiError as exc:
            if exc.code != RATE_LIMIT_CODE or attempt == max_retries:
                raise
            delay = base_delay * (2 ** attempt)
            print(f"50011 rate limit, retrying in {delay:.1f}s", file=sys.stderr)
            time.sleep(delay)
    raise RuntimeError("unreachable")


def print_table(snap: BookSnapshot) -> None:
    print(f"{snap.inst_id}  seqId={snap.seq_id}  ts={snap.ts}  imbalance={snap.imbalance():+.3f}")
    print(f"{'side':<5}{'rank':>5}{'price':>16}{'size':>16}{'orders':>8}")
    for side, levels in (("ask", snap.asks), ("bid", snap.bids)):
        for rank, level in enumerate(levels, start=1):
            print(f"{side:<5}{rank:>5}{level.price:>16}{level.size:>16}{level.orders:>8}")


def write_csv(path: str, snapshots: list[BookSnapshot]) -> None:
    with open(path, "w", newline="", encoding="utf-8") as handle:
        writer = csv.writer(handle)
        writer.writerow(
            ["inst_id", "seq_id", "ts", "side", "rank", "price", "size", "orders", "imbalance"]
        )
        for snap in snapshots:
            imb = f"{snap.imbalance():.6f}"
            for side, levels in (("ask", snap.asks), ("bid", snap.bids)):
                for rank, level in enumerate(levels, start=1):
                    writer.writerow([
                        snap.inst_id, snap.seq_id, snap.ts, side, rank,
                        level.price, level.size, level.orders, imb,
                    ])


def depth_type(value: str) -> int:
    sz = int(value)
    if not 1 <= sz <= MAX_SZ:
        raise argparse.ArgumentTypeError(f"--sz must be between 1 and {MAX_SZ}")
    return sz


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Log OKX order book depth snapshots.")
    parser.add_argument("--inst-id", default="BTC-USDT", help="instrument id, e.g. BTC-USDT")
    parser.add_argument("--sz", type=depth_type, default=DEFAULT_SZ, help="levels per side (1-400)")
    parser.add_argument("--count", type=int, default=3, help="number of snapshots to take")
    parser.add_argument("--interval", type=float, default=1.0, help="seconds between snapshots")
    parser.add_argument("--csv", metavar="PATH", help="write levels to CSV instead of stdout")
    args = parser.parse_args(argv)

    snapshots: list[BookSnapshot] = []
    for i in range(args.count):
        try:
            snap = fetch_with_backoff(args.inst_id, args.sz)
        except (ApiError, OSError) as exc:
            print(f"error: {exc}", file=sys.stderr)
            return 1
        snapshots.append(snap)
        if not args.csv:
            print_table(snap)
            print()
        if i < args.count - 1:
            time.sleep(args.interval)

    if args.csv:
        write_csv(args.csv, snapshots)
        print(f"wrote {len(snapshots)} snapshot(s) to {args.csv}")
    return 0


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

Run it like this:

python3 depth_logger.py --inst-id BTC-USDT --sz 10 --count 5 --csv depth.csv
Enter fullscreen mode Exit fullscreen mode

Reading the output

The imbalance column is my own readout, not something the API provides. It compares total bid quantity with total ask quantity across the levels you fetched, giving a value between -1 and 1. Positive means more size on the bid side of those levels. Keep in mind that it only covers the levels you requested. With sz set to 1, it describes the top of the book and nothing more. It is a description of a snapshot, not a forecast.

The seqId field lets you tell snapshots apart and see whether they come from the same sequence. I keep the ts value as the raw string returned by the response and do not convert it. That avoids guessing a format the script has not verified, so check the docs before you build time arithmetic on top of it.

Rate limits and 50011 backoff

The docs list the books endpoint at 40 requests per 2 seconds per IP. Public limits without authentication are counted by IP, and each endpoint has its own limit. When you exceed it, OKX returns error code 50011. The script handles that case by sleeping and retrying with exponential delays, starting at half a second and doubling each time, up to five retries. It retries only on 50011. Other errors fail immediately, because retrying a malformed request just wastes time.

A one-second polling interval is far below the documented limit for one instrument. The backoff matters more when several scripts share an IP, or when you extend the logger to poll more endpoints.

Caveats

A few limits are worth knowing before you rely on this. The snapshot reflects the server's cache, so you will not see sub-50 ms detail. A small sz gives you very little depth, and a large sz makes each response bigger. The imbalance figure depends entirely on which levels you fetched. The script reads only the documented fields, and if OKX changes the response layout, the parser will fail loudly, which I consider preferable to guessing.

Wrapping up

The script is intentionally short. If you want to extend it, the natural next steps are a longer run with a file rotation scheme, or a second instrument logged into the same CSV with a distinct inst_id.

If you already trade on OKX and want to try the program benefits, you can sign up with referral code UNLOCK20 at https://okx.com/join/UNLOCK20. The link above is an affiliate link. The code gives 20% off paid spot and futures trading fees, for both maker and taker orders. Buy/Sell and Convert are not covered, and the rebate does not change your VIP level. The code has to be entered during sign-up, because it cannot be added to an account after it is created. After you register, the Invite perks section shows your current rebate rate, and a 0% figure means the code is not attached.

Check the current program terms and fee schedule for your region before you sign up or trade.

Top comments (0)