Skip to content

Binance CLOB Example

File: python/websocketmanager/binance_clob_example.py

Streams BTC/USDT order book depth from Binance WebSocket API.

API Details

Property Value
WebSocket URL wss://stream.binance.com:9443/stream, then SUBSCRIBE btcusdt@depth@100ms sent with SendRaw
Authentication None (public market data)
Update frequency Every 100ms
Stream type Diff depth (depthUpdate events)
REST snapshot GET https://api.binance.com/api/v3/depth?symbol=BTCUSDT&limit=5000

What It Does

  1. Fetches the initial order book snapshot from Binance's REST API
  2. Opens a Binance connection through WebSocketManager (Connect with auto_reconnect) and subscribes to the depth stream (SendRaw)
  3. Publishes the connection's frames to x.examples.binance-clob.depth (StartPublish) and reads them back through the API gateway's pub/sub
  4. Applies each diff to the local order book; on a gap in the update ids it resyncs from a fresh snapshot (at most every 5 s)
  5. Saves the top 20 levels, best bid/ask and spread to State (websocketmanager / x.examples.binance-clob.orderbook.BTC_USDT) every 10 s, where Order Flow Imbalance reads them
  6. Disconnects on exit, also on Ctrl+C: on the shared demo cluster the connection would otherwise keep streaming

Running

source .env
cd python
uv run python websocketmanager/binance_clob_example.py

Output (on demo, [depth] lines left out):

============================================================
  Binance CLOB Example — BTCUSDT Order Book Depth
============================================================

  API:               context demo: api.virtufin.com:443 tls=True key=set
  Stream:            wss://stream.binance.com:9443/stream (btcusdt@depth@100ms)
  State key:         websocketmanager/x.examples.binance-clob.orderbook.BTC_USDT
  Topic:             x.examples.binance-clob.depth

  ✓ Snapshot loaded: 5,000 bids, 5,000 asks (updateId=101295645776)
  → Opening Binance connection...
  ✓ Connected: id=59640550-1359-4597-abac-3e1c603a0170
  ✓ Subscribed to: btcusdt@depth@100ms
  ✓ Publishing depth updates to topic: x.examples.binance-clob.depth
  ⏳ Subscribing to topic via API Gateway: x.examples.binance-clob.depth...
  ✓ Initial state saved to: websocketmanager/x.examples.binance-clob.orderbook.BTC_USDT

  Monitoring depth updates (Ctrl+C to stop)...
      Time      Best Bid      Best Ask    Spread    Lvl
  ────────  ────────────  ────────────  ────────  ─────
  ⚠  Gap detected: expected 101295645777, got 101295646576. Resetting.
  ⏳ Resyncing from a fresh snapshot...
  ✓ Snapshot loaded: 5,000 bids, 5,000 asks (updateId=101295646630)
      10.1s      83909.24      83909.25      0.01     10
      20.1s      83916.71      83916.72      0.01     20

  Stopped after 45s. Saving final state...
  ✓ Disconnect sent.

The first diff usually arrives after the REST snapshot was taken, so one resync at the start is expected.