A ticker poller looks simple until you start polling faster than the API allows. This article builds a standard-library Python poller that tracks the documented IP budget for the public ticker endpoints, classifies each response by its code field, and backs off when OKX returns error 50011. The loop is the part I care about most, so the code is short enough to read in one sitting.
The endpoints and their budget
The single-instrument ticker lives at GET /api/v5/market/ticker. It needs instId, such as BTC-USDT, and it returns one record in data[0] with fields including last, bidPx, bidSz, askPx, askSz and ts. The batch endpoint, GET /api/v5/market/tickers, requires instType, with values such as SPOT, and returns a list of tickers for that type.
Both endpoints share the same documented limit: 20 requests per 2 seconds, counted per IP. The docs say each endpoint has its own limit, so I treat the budget as per endpoint and track each one separately. A budget of 20 per 2 seconds is a ceiling of ten requests per second, which sounds generous until you poll a full market list on a tight loop.
A budget, not a sleep
A fixed time.sleep(0.1) between requests looks like rate limiting, but it does not guarantee you stay within a window. Requests can bunch up after a slow response, and a sleep ignores that history. The script uses a sliding window instead. It records the monotonic timestamp of each request, drops entries older than two seconds, and waits until the oldest entry expires before sending another request.
I also keep two slots in reserve, so the effective limit is 18 per window. That margin covers clock jitter and requests that count against the budget but fail before they return. The budget is local, so it is an estimate of what OKX counts rather than an exact reading. The script does not parse any rate-limit headers, because it does not rely on any.
Classifying responses
Every response uses the standard envelope with code, msg and data. The script treats code == "0" as success and extracts data. It treats 50011 as a rate limit and retries with exponential delays. Any other code fails immediately, since repeating a bad request wastes budget you may need later.
Backoff doubles the delay after each failed attempt. The script starts at half a second and gives up after five retries. Each retry still passes through the budget, so a backoff followed by a burst cannot push you past the window.
The poller
The script is stdlib only and takes --interval and --count flags. Comments mark where the remaining budget is checked.
#!/usr/bin/env python3 """Poll OKX public ticker endpoints within a documented IP request budget.""" from __future__ import annotations import argparse import json import sys import time import urllib.error import urllib.parse import urllib.request from collections import deque BASE_URL = "https://www.okx.com" TICKER_PATH = "/api/v5/market/ticker" TICKERS_PATH = "/api/v5/market/tickers" WINDOW_SECONDS = 2.0 DOCUMENTED_LIMIT = 20 # requests per 2 seconds, per IP, per endpoint SAFETY_MARGIN = 2 # slots kept in reserve 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 class RequestBudget: """Sliding window: at most `limit` requests in any `window` seconds.""" def __init__(self, limit: int = DOCUMENTED_LIMIT - SAFETY_MARGIN, window: float = WINDOW_SECONDS) -> None: self.limit = limit self.window = window self.sent: deque[float] = deque() def _trim(self, now: float) -> None: while self.sent and now - self.sent[0] >= self.window: self.sent.popleft() def remaining(self) -> int: """Slots left in the current window, for logging.""" self._trim(time.monotonic()) return self.limit - len(self.sent) def wait_for_slot(self) -> None: while True: now = time.monotonic() self._trim(now) if len(self.sent) < self.limit: # remaining budget > 0 self.sent.append(now) return time.sleep(max(0.0, self.sent[0] + self.window - now)) def _get_json(path: str, params: dict[str, str], timeout: float = 10.0) -> dict: url = f"{BASE_URL}{path}?{urllib.parse.urlencode(params)}" request = urllib.request.Request(url, 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 code may still arrive in the envelope try: payload = json.loads(body.decode("utf-8")) except ValueError as exc: raise ApiError("bad-json", "response was not JSON") from exc if not isinstance(payload, dict): raise ApiError("bad-json", "unexpected payload shape") code = str(payload.get("code", "")) if code != "0": # success is code == "0" raise ApiError(code, str(payload.get("msg", ""))) return payload def fetch_data(budget: RequestBudget, path: str, params: dict[str, str], max_retries: int = 5, base_delay: float = 0.5) -> list[dict]: for attempt in range(max_retries + 1): budget.wait_for_slot() try: payload = _get_json(path, params) return payload.get("data") or [] except ApiError as exc: if exc.code != RATE_LIMIT_CODE or attempt == max_retries: raise delay = base_delay * (2 ** attempt) print(f"50011 on {path}, backing off {delay:.1f}s", file=sys.stderr) time.sleep(delay) raise RuntimeError("unreachable") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Poll OKX tickers within a request budget.") parser.add_argument("--inst-id", default="BTC-USDT", help="single instrument to poll") parser.add_argument("--all-spot", action="store_true", help="poll the SPOT tickers list instead of one instrument") parser.add_argument("--interval", type=float, default=1.0, help="seconds between polls") parser.add_argument("--count", type=int, default=5, help="number of polls") args = parser.parse_args(argv) budget = RequestBudget() try: for i in range(args.count): if args.all_spot: items = fetch_data(budget, TICKERS_PATH, {"instType": "SPOT"}) first = items[0] if items else {} print(f"poll {i + 1}: {len(items)} SPOT tickers, " f"first={first.get('instId', '-')} " f"budget_left={budget.remaining()}") else: items = fetch_data(budget, TICKER_PATH, {"instId": args.inst_id}) if not items: print("warning: empty data list", file=sys.stderr) else: t = items[0] print(f"{t['ts']} {t['instId']} last={t['last']} " f"bid={t['bidPx']}x{t['bidSz']} ask={t['askPx']}x{t['askSz']} " f"budget_left={budget.remaining()}") if i < args.count - 1: time.sleep(args.interval) except (ApiError, OSError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 return 0 if __name__ == "__main__": raise SystemExit(main()) Run it like this:
python3 ticker_poller.py --inst-id ETH-USDT --interval 1 --count 10 Caveats about stale snapshots
A ticker is a snapshot, and a snapshot is only as fresh as the moment it was returned. The ts field tells you when the record was generated, but I keep it as the raw string rather than converting it, because I have not verified its format against a live response. Network latency adds to the age of the data, and a backoff pause makes it worse. If your logic depends on recency, compare ts against your own clock and drop stale records.
The budget also matters for what you can conclude. Polling every second for one instrument uses a small share of the window. Polling the full SPOT list is a different job, and the budget logic will slow it down rather than fail. A slowdown is a sign the loop is working, not a bug. Finally, this poller is a logging tool. Using its output to drive orders would need far more care, starting with what happens when the feed stalls.
Where the code and the benefit fit
The UNLOCK20 code gives 20% off paid spot and futures trading fees, for maker and taker orders. Buy/Sell and Convert are not covered, and the rebate does not change your VIP level. The code must be entered at sign-up. It cannot be added to an account after it has been created. Once you are registered, the Invite perks section shows the rate attached to your account, and 0% means the code is not attached.
Keep in mind that this is a tooling walkthrough, not trading advice. The poller simply reads public data, and it does not place or manage orders.
Wrap up
For context on the company behind the program, OKX Europe Limited operates under MiCA regulation, with MFSA as its supervisor.
If you want to extend the poller, the natural next step is per-endpoint budgets with a shared logger, or a CSV writer that records ts next to the local receive time.
Check the current program terms and fee schedule for your region before you sign up.
If you want to try the code on your own account, sign up at https://okx.com/join/UNLOCK20 with referral code UNLOCK20. The link above is an affiliate link.