OKX Order Book Full Depth Subscribe: The Complete Trader's Guide
Master OKX's full depth order book WebSocket feed — from connection setup to real-time data processing for smarter algorithmic trading decisions.
Master OKX's full depth order book WebSocket feed — from connection setup to real-time data processing for smarter algorithmic trading decisions.
If you've ever watched a large buy order hit the market and wondered exactly how deep the liquidity went before price moved — that's the question full depth order book data answers. OKX's WebSocket API gives you access to up to 400 price levels on each side of the book, updating tick-by-tick, for every instrument they list. That's not just useful for algorithmic traders — it's essential. Platforms like Binance and Bybit offer similar feeds, but OKX's implementation has some quirks worth understanding before you start parsing data. This guide walks through everything: connecting, subscribing, decoding the message format, and actually using the data to make better trading decisions.
Most traders are familiar with the top-of-book: best bid, best ask, spread. That's what price charts and basic tickers show. Full depth data is different — it's every resting limit order at every price level currently sitting on the exchange's matching engine. On OKX, the 'books' WebSocket channel delivers up to 400 levels on each side for spot and derivatives markets.
Why does depth matter? Consider a scenario where BTC-USDT is trading at $67,000 on OKX and you want to buy 10 BTC. Looking only at the best ask tells you the price for the first few hundred dollars worth. Full depth tells you exactly how much slippage you'll face buying 10 BTC — whether there are 200 BTC of offers stacked tightly between $67,000 and $67,050, or whether the book thins out after $67,010 and you're looking at $67,200 before you're filled. That difference is real money.
Beyond execution quality, depth data reveals intent. Large walls of limit orders at round numbers often signal institutional positioning. Sudden disappearance of bids — an order book 'flush' — can precede sharp moves. Tools like VoiceOfChain aggregate these real-time signals and translate raw depth changes into actionable alerts, so you don't have to stare at raw WebSocket streams all day. But understanding what's underneath those signals makes you a sharper trader.
OKX's public WebSocket endpoint for market data is wss://ws.okx.com:8443/ws/v5/public. No authentication needed for order book data — it's publicly available. The channel you want for full depth is 'books', which delivers a snapshot followed by incremental delta updates. For a lighter-weight feed, 'books5' gives you only the top 5 levels, and 'bbo-tbt' gives best bid/offer tick-by-tick. For serious depth analysis or algorithmic execution, you want 'books'.
import asyncio
import json
import websockets
async def subscribe_okx_full_depth(symbol: str = "BTC-USDT"):
uri = "wss://ws.okx.com:8443/ws/v5/public"
async with websockets.connect(uri) as ws:
# Subscribe to full depth (400 levels each side)
sub_msg = {
"op": "subscribe",
"args": [{"channel": "books", "instId": symbol}]
}
await ws.send(json.dumps(sub_msg))
print(f"Subscribed to {symbol} full depth feed")
async for raw in ws:
msg = json.loads(raw)
# Skip subscription confirmations
if msg.get("event") == "subscribe":
print("Subscription confirmed:", msg)
continue
action = msg.get("action") # 'snapshot' or 'update'
if not msg.get("data"):
continue
book = msg["data"][0]
asks = book.get("asks", []) # [price, qty, liquidated_orders, order_count]
bids = book.get("bids", [])
print(f"[{action}] Levels — asks: {len(asks)}, bids: {len(bids)}")
if asks:
print(f" Best ask: {asks[0][0]} @ {asks[0][1]}")
if bids:
print(f" Best bid: {bids[0][0]} @ {bids[0][1]}")
asyncio.run(subscribe_okx_full_depth())
OKX sends a full snapshot on connect, then incremental delta updates. Your application must maintain a local copy of the order book and apply each update. A level with quantity '0' means that price level has been removed from the book — don't skip these.
The first message you receive after subscribing will have 'action': 'snapshot'. This is your starting state — the full book as it exists at that moment. Every message after that will have 'action': 'update', containing only the levels that changed since the last message. Each entry in asks and bids is a four-element array: [price, size, number_of_liquidated_orders, number_of_orders]. The third and fourth elements are useful for detecting liquidation-driven book changes versus organic order flow.
class OKXOrderBook:
def __init__(self):
self.asks = {} # price -> size
self.bids = {}
def apply(self, action: str, data: dict):
if action == "snapshot":
self.asks.clear()
self.bids.clear()
for level in data.get("asks", []):
price, size = float(level[0]), float(level[1])
if size == 0:
self.asks.pop(price, None)
else:
self.asks[price] = size
for level in data.get("bids", []):
price, size = float(level[0]), float(level[1])
if size == 0:
self.bids.pop(price, None)
else:
self.bids[price] = size
def best_ask(self):
return min(self.asks) if self.asks else None
def best_bid(self):
return max(self.bids) if self.bids else None
def spread(self):
a, b = self.best_ask(), self.best_bid()
return round(a - b, 8) if a and b else None
def depth_at_bps(self, bps: float = 10):
"""Total liquidity within N basis points of mid."""
mid = (self.best_ask() + self.best_bid()) / 2
threshold = mid * (bps / 10000)
ask_depth = sum(s for p, s in self.asks.items() if p <= mid + threshold)
bid_depth = sum(s for p, s in self.bids.items() if p >= mid - threshold)
return {"ask_depth": ask_depth, "bid_depth": bid_depth}
OKX also includes a checksum in each update message. It's a CRC32 hash of the top 25 bid/ask levels concatenated as strings. Verifying this checksum catches packet loss or desync — if your checksum doesn't match, you should unsubscribe and resubscribe to get a fresh snapshot. Skipping checksum validation is fine during development, but in production it's the difference between a stable data pipeline and mystery fills.
Once you have a live, maintained order book, the interesting work begins. Most retail traders never get here because they're working from candles and indicators. Depth data opens up a completely different category of edge. Here are the strategies that become possible:
The key insight is that full depth data shifts you from reacting to price to understanding the forces about to move it. You're not reading a lagging indicator — you're watching the order queue that produces price discovery in real time.
Not all exchanges expose full depth the same way. Before committing your infrastructure to a specific feed, it's worth comparing what Binance, Bybit, OKX, and others actually offer — both in depth levels and operational overhead.
| Exchange | Max Depth Levels | Update Interval | Channel Name | Snapshot + Delta | Checksum Validation | Liquidation Order Count |
|---|---|---|---|---|---|---|
| OKX | 400 per side | Tick-by-tick | books | Yes | Yes (CRC32) | Yes |
| Binance | 5000 per side | 100ms / 1000ms | @depth | Yes | No | No |
| Bybit | 200 per side | 20ms / 100ms | orderbook.200 | Yes | Yes (CRC32) | No |
| Bitget | 150 per side | 200ms | books | Yes | No | No |
| Gate.io | 100 per side | 100ms | spot.order_book_update | Yes | No | No |
| Coinbase Advanced | 50 per side | ~5ms | level2 | Yes | No | No |
Binance technically offers the deepest feed (5000 levels), but the sheer volume of data means you need serious infrastructure to keep up at scale. OKX's 400-level feed with built-in checksums strikes a better balance for most teams — you get enough depth to model institutional positioning without drowning in updates. Bybit's 20ms update interval is among the fastest in the industry, which matters for high-frequency strategies. For mid-frequency algos and signal generation, OKX's feed is well-documented, stable, and sufficiently deep.
| Channel | Depth Levels | Use Case | Approx. Bandwidth |
|---|---|---|---|
| bbo-tbt | 1 per side | Best bid/offer, latency-sensitive strategies | Very low |
| books5 | 5 per side | Basic spread monitoring, simple market making | Low |
| books-l2-tbt | 400 per side, tick-by-tick | HFT, iceberg detection, aggressive algos | High |
| books | 400 per side, batched | Signal generation, depth analysis, mid-freq algos | Medium |
Full depth order book data from OKX is one of the most information-dense feeds available in crypto markets — and it's free. The barrier isn't access, it's knowing what to do with 800 price levels updating dozens of times per second. Start with the Python snippets above, build a stable local book with checksum validation, and focus on one signal: bid/ask imbalance near mid price. That single metric, applied cleanly, already puts you ahead of the majority of retail traders still reading 15-minute candles.
If you want pre-built signals derived from order flow data across OKX, Binance, Bybit, and other major venues, VoiceOfChain monitors depth imbalances and large order changes in real time, surfacing actionable alerts without requiring you to run your own WebSocket infrastructure. It's worth layering on top of your own analysis — especially for confirming entries when your depth signals and external flow signals align.