Order Flow Imbalance
File: python/orderflow_imbalance.py
Calculates weighted bid/ask imbalance from Binance order book depth data.
Pipeline
Binance → WebSocketFeed worker → binance_order_book.py → State → orderflow_imbalance.py → State
binance_order_book.pykeeps the BTC/USDT order book and saves its top 20 levels to State (statestore/x.examples.binance-order-book.orderbook.BTC_USDT) every 10 s. It must be running.orderflow_imbalance.pypolls that key every 2 s.- For each new book (a higher
lastUpdateId) it calculates the weighted bid/ask imbalance and saves it tostatestore/x.examples.orderflow-imbalance.BTC_USDT.
It runs as a script on your machine and only reads and writes State: no WorkManager worker, 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 order book feed
source .env
cd python
uv run binance_order_book.py
# Terminal 2: Start the imbalance script
uv run orderflow_imbalance.py
Output (on demo):
============================================================
Order Flow Imbalance — BTC_USDT
============================================================
API: context demo: api.virtufin.com:443 tls=True key=set
State source: statestore/x.examples.binance-order-book.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.