DEV Community

Dev Notes
Dev Notes

Posted on

Bitget referral code BITGET101: a Python cross-exchange spread logger

I wanted a boring, cron-friendly script that tells me when the top of book on two exchanges drifts apart, without API keys and without any trading logic. This is a logger. It polls public REST endpoints, writes one CSV row per poll, and prints an alert when a threshold in basis points is crossed. Everything below uses only the standard library.

Which venues and endpoints

I picked OKX and MEXC because both have public, unauthenticated top-of-book endpoints, and I'll add Bitget as an optional third adapter.

Venue Endpoint Bid/ask fields Documented limit
OKX GET /api/v5/market/ticker?instId=BTC-USDT data[0].bidPx / askPx 20 requests per 2 seconds, per IP
MEXC GET /api/v3/ticker/bookTicker?symbol=BTCUSDT bidPrice / askPrice weight 10 on this endpoint; IPs share 300 weight per 10 seconds
Bitget GET /api/v2/spot/market/tickers?symbol=BTCUSDT data[0].bidPr / askPr 20 requests per 1 second, per IP

Docs: OKX (https://www.okx.com/docs-v5/en/), MEXC (https://www.mexc.com/api-docs/spot-v3/market-data-endpoints/symbol-order-book-ticker and https://www.mexc.com/api-docs/spot-v3/introduction), Bitget (https://www.bitget.com/docs/catalog/classic-spot-market/classic-spot-market).

Symbol formats differ (BTC-USDT on OKX, BTCUSDT elsewhere), so the script takes one canonical symbol and maps it per venue.

Defining the spread

For each venue I compute mid = (bid + ask) / 2. Then, in basis points:

  • Inside spread on a venue: (ask - bid) / mid * 10000
  • Cross A over B: (bid_a - ask_b) / mid * 10000, where mid is the average of the two mids
  • Cross B over A: (bid_b - ask_a) / mid * 10000

A positive cross value means one venue's best bid sits above the other's best ask. That is not free money. Fees on both legs, moving funds between venues, latency between two separate HTTP calls, and the size available at the top of book all eat it. Top-of-book quotes say nothing about depth. Treat this as observation only.

The script

#!/usr/bin/env python3
"""Log top-of-book spreads between two exchanges and alert on thresholds.
Public REST only, no API keys. Logger, not an execution bot."""
from __future__ import annotations

import argparse
import csv
import json
import os
import random
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

MAX_RETRIES = 5
BASE_DELAY = 1.0
TIMEOUT = 10

CSV_FIELDS = [
    "timestamp_utc", "symbol", "ex_a", "bid_a", "ask_a", "ex_b", "bid_b",
    "ask_b", "mid_a", "mid_b", "inside_spread_a_bps", "inside_spread_b_bps",
    "cross_ab_bps", "cross_ba_bps",
]


class RetryableError(Exception):
    def __init__(self, msg: str, retry_after: float | None = None):
        super().__init__(msg)
        self.retry_after = retry_after


def http_get_json(url: str) -> dict | list:
    req = urllib.request.Request(url, headers={"User-Agent": "spread-logger/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:
        if e.code in (418, 429) or e.code >= 500:
            ra = e.headers.get("Retry-After")
            raise RetryableError(f"HTTP {e.code}", float(ra) if ra else None)
        raise  # 4xx/403/451: retrying will not help, surface it
    except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
        raise RetryableError(f"network error: {e}")


def with_backoff(fn):
    """Exponential backoff + jitter, honours Retry-After, capped retries."""
    for attempt in range(MAX_RETRIES + 1):
        try:
            return fn()
        except RetryableError as e:
            if attempt == MAX_RETRIES:
                raise
            delay = e.retry_after if e.retry_after else BASE_DELAY * (2 ** attempt)
            delay += random.uniform(0, 0.5 * max(delay, 1.0))
            print(f"retry {attempt + 1}/{MAX_RETRIES} in {delay:.1f}s ({e})",
                  file=sys.stderr)
            time.sleep(delay)


# --- adapters: each returns (bid, ask) as floats ---

def okx_top(symbol: str) -> tuple[float, float]:
    inst = symbol.replace("USDT", "-USDT")  # BTCUSDT -> BTC-USDT
    url = f"https://www.okx.com/api/v5/market/ticker?instId={inst}"
    d = http_get_json(url)
    if d.get("code") == "50011":
        raise RetryableError("OKX 50011 rate limit")
    if d.get("code") != "0":
        raise ValueError(f"OKX error: {d.get('code')} {d.get('msg')}")
    row = d["data"][0]
    return float(row["bidPx"]), float(row["askPx"])


def mexc_top(symbol: str) -> tuple[float, float]:
    url = f"https://api.mexc.com/api/v3/ticker/bookTicker?symbol={symbol}"
    d = http_get_json(url)
    return float(d["bidPrice"]), float(d["askPrice"])


def bitget_top(symbol: str) -> tuple[float, float]:
    url = f"https://api.bitget.com/api/v2/spot/market/tickers?symbol={symbol}"
    d = http_get_json(url)
    if d.get("code") != "00000":
        # Check the official docs for which codes are transient.
        raise RetryableError(f"Bitget code {d.get('code')}: {d.get('msg')}")
    row = d["data"][0]
    return float(row["bidPr"]), float(row["askPr"])


ADAPTERS = {"okx": okx_top, "mexc": mexc_top, "bitget": bitget_top}


# --- maths ---

def bps(x: float) -> float:
    return x * 10_000


def compute(bid_a, ask_a, bid_b, ask_b) -> dict:
    mid_a = (bid_a + ask_a) / 2
    mid_b = (bid_b + ask_b) / 2
    ref = (mid_a + mid_b) / 2
    return {
        "mid_a": mid_a,
        "mid_b": mid_b,
        "inside_spread_a_bps": bps((ask_a - bid_a) / mid_a),
        "inside_spread_b_bps": bps((ask_b - bid_b) / mid_b),
        "cross_ab_bps": bps((bid_a - ask_b) / ref),
        "cross_ba_bps": bps((bid_b - ask_a) / ref),
    }


# --- alerting ---

def send_telegram(text: str) -> None:
    """OPTIONAL. Not required to run the script.
    FIXME: set TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID in your environment
    and implement the HTTP POST to the Telegram Bot API per its docs."""
    token = os.environ.get("TELEGRAM_BOT_TOKEN")
    chat_id = os.environ.get("TELEGRAM_CHAT_ID")
    if not token or not chat_id:
        return  # silently skip when not configured
    # FIXME: POST {chat_id, text} using urllib.request; omitted on purpose.


def check_alerts(row: dict, threshold_bps: float) -> list[str]:
    msgs = []
    for key in ("cross_ab_bps", "cross_ba_bps",
                "inside_spread_a_bps", "inside_spread_b_bps"):
        if abs(row[key]) > threshold_bps:
            msgs.append(f"{key}={row[key]:.2f} bps > {threshold_bps} bps")
    return msgs


def append_csv(path: Path, row: dict) -> None:
    new = not path.exists()
    with path.open("a", newline="") as f:
        w = csv.DictWriter(f, fieldnames=CSV_FIELDS)
        if new:
            w.writeheader()
        w.writerow(row)


def poll_once(args, cooldown_state: dict) -> None:
    a, b = args.ex_a, args.ex_b
    bid_a, ask_a = with_backoff(lambda: ADAPTERS[a](args.symbol))
    bid_b, ask_b = with_backoff(lambda: ADAPTERS[b](args.symbol))
    row = {
        "timestamp_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "symbol": args.symbol, "ex_a": a, "bid_a": bid_a, "ask_a": ask_a,
        "ex_b": b, "bid_b": bid_b, "ask_b": ask_b,
        **compute(bid_a, ask_a, bid_b, ask_b),
    }
    append_csv(Path(args.csv), {k: (round(v, 4) if isinstance(v, float) else v)
                                for k, v in row.items()})
    msgs = check_alerts(row, args.threshold_bps)
    now = time.time()
    if msgs and now - cooldown_state.get("last", 0) >= args.cooldown_seconds:
        cooldown_state["last"] = now
        text = f"[{row['timestamp_utc']}] {args.symbol} {a}/{b}: " + "; ".join(msgs)
        print("ALERT", text)
        send_telegram(text)


def main() -> None:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--symbol", default="BTCUSDT")
    p.add_argument("--ex-a", default="okx", choices=ADAPTERS)
    p.add_argument("--ex-b", default="mexc", choices=ADAPTERS)
    p.add_argument("--interval-seconds", type=float, default=30.0)
    p.add_argument("--threshold-bps", type=float, default=10.0)
    p.add_argument("--cooldown-seconds", type=float, default=300.0)
    p.add_argument("--csv", default="spreads.csv")
    p.add_argument("--once", action="store_true",
                   help="single poll, for cron")
    args = p.parse_args()

    state: dict = {}
    if args.once:
        poll_once(args, state)
        return
    while True:
        try:
            poll_once(args, state)
        except Exception as e:  # keep the loop alive, log and continue
            print(f"poll failed: {e}", file=sys.stderr)
        time.sleep(args.interval_seconds)


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

Run it once to test:

python spread_logger.py --symbol BTCUSDT --threshold-bps 5 --once
Enter fullscreen mode Exit fullscreen mode

Running it from cron

With --once there is no state between runs, so the cooldown only works in loop mode. In cron, either accept an alert per run or persist the last alert time to a file yourself. A crontab line that polls every minute:

* * * * * /usr/bin/python3 /home/me/spread_logger.py --symbol BTCUSDT --threshold-bps 10 --once --csv /home/me/spreads.csv >> /home/me/spread.log 2>&1
Enter fullscreen mode Exit fullscreen mode

One request per venue per minute is nowhere near the documented public limits. OKX's ticker endpoint allows 20 requests per 2 seconds per IP, and Bitget's tickers endpoint allows 20 per second per IP. For MEXC, the bookTicker page lists weight 10 and the introduction page describes a shared 300 weight per 10 seconds for IP-limited endpoints, so a polling interval of a few seconds still leaves a lot of headroom. If you go to MEXC's 429s, the docs say to stop sending requests, since continued violations can lead to IP bans that escalate in length. Don't tune your interval down to the limit.

Retry behaviour

The with_backoff helper retries on network errors, HTTP 429/418 and 5xx, and OKX code 50011, with exponential delay plus jitter. If the server sends Retry-After, that value is used instead of my computed delay. Retries are capped at five. Bitget returns its status in a code field where 00000 means success; I treat any other code as retryable here, which is a simplification. Check Bitget's docs for which non-success codes are really transient before relying on that.

If you add a Bybit adapter, its rate-limit failure shows up as retCode 10006 ("Too many visits!") and a 403 "access too frequent" means you should stop and wait at least 10 minutes (https://bybit-exchange.github.io/docs/v5/rate-limit). Note that in my testing, api.bybit.com returned 403 and api.binance.com returned 451 from some IPs. That's an observed geo/access caveat, not an official policy claim. Binance documents https://data-api.binance.vision for public market data only, so an adapter against /api/v3/ticker/bookTicker there is a reasonable alternative, but verify access from your own network.

Caveats worth taking seriously

  • Two calls, two moments. The venues are queried sequentially, so the snapshots are not simultaneous. Fast markets can make a cross value look real when it is just latency between calls. OKX returns a ts field you could log to check how old a quote is.
  • Clocks. The timestamp_utc is your local clock at poll time, not the exchange's. Don't use it for precise sequencing.
  • Symbol mapping. BTCUSDT versus BTC-USDT is the easy case. Quote assets and listings differ across venues, so confirm that "the same symbol" is really the same market.
  • Flapping alerts. A spread hovering around your threshold will alert repeatedly. The cooldown helps in loop mode; for cron, store the last alert timestamp.
  • Top of book only. Sizes at the best bid and ask are not considered. A wide cross on a tiny quote is noise.
  • No advice. This produces data, not trading signals.

For analysis, load the CSV into whatever you like and look at how often the cross values exceed your fee-plus-slippage estimate. That number, not a single alert, is the interesting part.

If you want an account to test market-data calls with, I use code BITGET101 (https://bonus.bitget.com/BITGET101).

Top comments (0)