Real-time order book data is the heartbeat of algorithmic trading. AI agents that read bid/ask depth, detect large walls, and track trade flow execute smarter orders โ and edge out the competition.
Four market data streams, all accessible via a single WebSocket connection or REST snapshot endpoint.
Order book data is the foundation of every advanced trading strategy. Where a price chart shows you what happened, the order book shows you what market participants are willing to do. A $2M bid wall at $96,500 BTC doesn't show up on a candle chart โ but a market data API subscriber sees it immediately and can position accordingly. Conversely, if that wall suddenly disappears without being filled, that's a signal that the buyer withdrew โ often a bearish indicator.
AI agents are uniquely suited to exploit order book data because the signal velocity is too fast for human traders. A large iceberg order โ where a buyer fills 0.5 BTC every few seconds, replenishing from a hidden reserve โ might take 15 minutes to fully manifest. A human trader would never notice. An agent streaming trade flow will detect the pattern in under 60 seconds and position accordingly.
Purple Flea's order book WebSocket delivers updates at native exchange latency, with additional normalization across all 275 supported markets so your agent speaks one unified data format regardless of underlying venue. REST snapshots are available for agents that need periodic polling rather than continuous streaming โ useful for lower-frequency strategies that don't require tick-by-tick data.
Stream live order book updates with Python's asyncio. Detect large bid walls, compute spread, and trigger alerts in real time.
# pip install purpleflea import purpleflea import asyncio client = purpleflea.MarketDataClient(api_key="YOUR_KEY") async def on_orderbook(data): best_bid = data["bids"][0] best_ask = data["asks"][0] spread = best_ask["price"] - best_bid["price"] # Alert if bid wall > $500k appears total_bid_depth = sum(b["size"] * b["price"] for b in data["bids"][:10]) if total_bid_depth > 500_000: print(f"Large bid wall detected: ${total_bid_depth:,.0f}") print(f"BTC spread: ${spread:.2f} | Mid: ${(best_bid['price']+best_ask['price'])/2:.2f}") async def main(): async with client.stream_orderbook("BTC-PERP", depth=20) as stream: async for snapshot in stream: await on_orderbook(snapshot) asyncio.run(main())
The stream_orderbook async context manager handles WebSocket connection management, automatic reconnection with exponential backoff, and message parsing. Each snapshot in the stream is a full normalized order book object containing the fields documented in the reference table below.
For agents that need to track multiple markets simultaneously, open multiple concurrent streams or use the stream_multi_orderbook(markets=["BTC-PERP","ETH-PERP","SOL-PERP"]) method which multiplexes all feeds over a single WebSocket connection.
Three strategies that AI agents can implement directly from order book data โ each with a distinct edge and risk profile.
Place limit orders at the best bid and best ask simultaneously, capturing the spread as maker on each filled side. When the spread is wide (e.g., $10 on BTC), the maker earns $10 per BTC on every round trip. This strategy requires managing inventory risk โ if the market moves directionally, one side of your book fills repeatedly and you accumulate a position.
Use the order book stream to dynamically widen or narrow your quotes based on current spread. Tighten quotes when competition is low (wide spread), pull quotes when volatility spikes above threshold. Purple Flea's limit order API supports maker-or-cancel (MOC) semantics to ensure you only ever pay maker fees.
Compute the ratio of bid depth to ask depth across the top N levels. When bid volume significantly outweighs ask volume (e.g., ratio > 3.0), there is more buying pressure in the book โ prices are more likely to move up in the short term. Conversely, a heavy ask side (ratio < 0.5) predicts downward pressure.
This signal works on horizons from seconds to minutes. Combine it with trade flow data: if the order book is bid-heavy AND recent fills are predominantly taker buys, the short-term bullish signal is confirmed. This combination gives your agent a statistically meaningful edge on sub-minute price direction.
Iceberg orders are large orders disguised as small ones โ the trader shows only a small visible size in the book and automatically replenishes after each fill. From the book, an iceberg looks like a persistent level that refills immediately after being hit.
Your agent detects icebergs by tracking trade flow at specific price levels: if a level is hit by multiple small fills in rapid succession and the visible size does not decrease, a hidden reserve is replenishing it. A large iceberg bid at a key level is bullish; a large iceberg ask is bearish. Detection logic requires correlating the order book depth stream with individual fills from the trade flow stream.
Complete field reference for the order book snapshot object returned by both the WebSocket stream and the REST snapshot endpoint.
| Field | Type | Description |
|---|---|---|
| bids | array[Level] | Sorted array of bid levels from best (highest) to worst (lowest). Each element has price (float) and size (float, aggregate quantity at this price). Up to 50 levels depending on depth parameter. |
| asks | array[Level] | Sorted array of ask levels from best (lowest) to worst (highest). Same structure as bids. The spread is asks[0].price - bids[0].price. |
| timestamp | integer | Unix timestamp in microseconds (not milliseconds) at which this snapshot was captured at the source exchange. Use this for latency measurement and time-series storage. Precision: ยฑ1 microsecond. |
| sequence | integer | Monotonically increasing sequence number for this market's feed. Gap in sequence numbers indicates a missed update โ your client should request a fresh REST snapshot to resync before continuing to process stream deltas. |
| mid_price | float | Pre-computed mid-market price: (bids[0].price + asks[0].price) / 2. Provided as a convenience field to avoid recalculation. Updated with every book change. |
| spread_bps | float | Current bid-ask spread expressed in basis points: ((asks[0].price - bids[0].price) / mid_price) * 10000. Lower spread = tighter market = cheaper for market takers. Typical BTC-PERP: 0.5โ2 bps. |
| funding_rate | float | Current 8-hour funding rate as a decimal. Positive means longs pay shorts (0.0001 = 0.01% per 8h = 10.95% APR). Updated every 8 hours. Null for non-perpetual instruments. Use for basis trading and carry strategies. |
The sequence field is critical for production agents that rely on incremental book updates (deltas) rather than full snapshots. If your agent processes a snapshot with sequence 1000 followed by a delta with sequence 1002, you've missed sequence 1001 and your local book state is corrupted. Agents should maintain a sequence validator and immediately request a fresh REST snapshot on any detected gap before resuming stream processing.
For agents that only need top-of-book data (best bid, best ask, spread) without full depth, use the lightweight ticker endpoint at GET /v1/ticker/:market โ it has lower payload size and higher update frequency, suitable for agents making tick-by-tick decisions on spread alone.
Order book data is most powerful when paired with execution and position management APIs.
Act on your order book signals. Place market and limit orders with maker-or-cancel semantics, set stop-loss triggers, and manage open positions โ all from the same API key that grants market data access.
Explore Trading API โPurple Flea's market data layer includes direct access to Hyperliquid's on-chain order book โ one of the deepest perpetuals venues in DeFi. Sub-millisecond data with on-chain settlement guarantees.
Hyperliquid Integration โOrder book strategies depend on limit orders. Purple Flea's limit order API supports post-only orders (maker-only), time-in-force controls, and iceberg order submission to hide your own large orders.
Limit Order API โWrap order book tools in your LangChain agent. A reasoning agent that can query real-time bid/ask depth and trade flow can make nuanced entry decisions rather than blindly posting market orders.
LangChain Guide โSub-millisecond latency. 50 depth levels. 275 markets. Full trade flow. One API key covers market data and execution.