Skip to content

Order Flow Imbalance Example

File: python/workmanager/orderflow_imbalance_worker.py

Calculates weighted bid/ask imbalance from Binance CLOB depth data.

Pipeline

Binance → WebSocketManager → binance_clob_example.py → State → orderflow_imbalance_worker.py → State
  1. binance_clob_example.py keeps the BTC/USDT order book and saves its top 20 levels to State (websocketmanager / x.examples.binance-clob.orderbook.BTC_USDT) every 10 s. It must be running.
  2. orderflow_imbalance_worker.py polls that key every 2 s.
  3. For each new book (a higher lastUpdateId) it calculates the weighted bid/ask imbalance and saves it to statestore / x.examples.orderflow.imbalance.BTC_USDT.

Despite the file name, it runs as a script on your machine, not as a WorkManager worker, and it opens no WebSocket connection of its own.

Imbalance Formula

For the top N price levels:

Weighted Bids  = Σ bid_price[i] × bid_qty[i]
Weighted Asks  = Σ ask_price[i] × ask_qty[i]
Imbalance      = Weighted Asks - Weighted Bids

Signal interpretation:

Condition Signal Meaning
Imbalance > 10% of asks SELLING Ask side has more liquidity — selling pressure
Imbalance < −10% of bids BUYING Bid side has more liquidity — buying pressure
Otherwise NEUTRAL Balanced order book

Running

# Terminal 1: Start the Binance CLOB feed
source .env
cd python
uv run websocketmanager/binance_clob_example.py

# Terminal 2: Start the imbalance worker
uv run workmanager/orderflow_imbalance_worker.py

Output (on demo):

============================================================
  Order Flow Imbalance Worker — BTCUSDT
============================================================

  API:              context demo: api.virtufin.com:443 tls=True key=set
  State source:     websocketmanager/x.examples.binance-clob.orderbook.BTC_USDT
  Output state:     statestore/x.examples.orderflow.imbalance.BTC_USDT
  Levels:           20

1/2  Waiting for the order book in the state store...
     ✓ Snapshot found (updateId=101296045602)

2/2  Monitoring state changes. Saving imbalance to: statestore/x.examples.orderflow.imbalance.BTC_USDT
     Press Ctrl+C to stop.

      Time        Wtd Bids        Wtd Asks     Imbalance    Spread        Signal
  ────────  ──────────────  ──────────────  ────────────  ────────  ────────────
      10.2s          34,594         378,524      +343,931      0.01    ⚠  SELLING
      20.5s          49,490         581,600      +532,111      0.01    ⚠  SELLING
      30.7s          35,847         618,370      +582,523      0.01    ⚠  SELLING

     Stopped after 35s.