Market Data

Real-Time Order Book API
for AI Agents

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.

Access Market Data โ†’ View Trading API
sub-1ms latency
BTC-PERP ยท L2 Depth ยท 20 Levels โ— LIVE
Price (USD) Size (BTC) Total
96,842.000.41239,818
96,835.501.180114,266
96,821.002.340226,562
96,810.503.890376,687
96,800.005.010484,968
Spread: $4.50 ยท Mid: $96,797.75 ยท 0.005 bps
96,795.506.221601,895
96,785.004.112397,727
96,770.502.670258,378
96,762.001.340129,580
96,750.000.78075,465

What You Get

Four market data streams, all accessible via a single WebSocket connection or REST snapshot endpoint.

โšก
Best Bid/Ask
Sub-millisecond latency. Top-of-book quote with size and implied spread in basis points. Ideal for agents placing aggressive market orders and needing real-time fill price estimates before committing.
๐Ÿ“š
Full Depth Snapshot
Up to 50 levels of bid and ask depth per market. Each level includes price and aggregate size. Updated on every change. Your agent can compute total dollar liquidity within any price range in real time.
๐Ÿ”„
Trade Flow
Every individual fill streamed as it happens: price, size, aggressor side (taker was buyer or seller), and timestamp in microseconds. Essential for detecting momentum, identifying absorption events, and computing VWAP in real time.
๐Ÿ“ก
Funding Rate
Current funding rate and next predicted funding rate for every perpetual market, updated every 8 hours. Positive funding = longs pay shorts; negative funding = shorts pay longs. Agents use this for basis trading and carry strategies.

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.

WebSocket Streaming Example

Stream live order book updates with Python's asyncio. Detect large bid walls, compute spread, and trigger alerts in real time.

wss:// api.purpleflea.com/v1/orderbook/stream?market=BTC-PERP&depth=20&api_key=YOUR_KEY
orderbook_stream.py Python ยท asyncio
# 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.

Order Book Strategies

Three strategies that AI agents can implement directly from order book data โ€” each with a distinct edge and risk profile.

โ†”๏ธ
Market Making
Spread Trading

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.

โš–๏ธ
Directional Signal
Order Book Imbalance

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.

๐ŸงŠ
Pattern Detection
Iceberg Detection

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.

Data Fields Reference

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.

<1ms
Market Data Latency
50
Depth Levels Per Side
275
Perpetual Markets
8h
Funding Rate Update Cycle
24/7
Market Hours

Complete Your Trading Stack

Order book data is most powerful when paired with execution and position management APIs.

Trading API

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 โ†’
Hyperliquid 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 โ†’
Limit Order API

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 โ†’
LangChain Integration

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 โ†’

Access Real-Time
Order Book Data

Sub-millisecond latency. 50 depth levels. 275 markets. Full trade flow. One API key covers market data and execution.

Get Your API Key โ†’ View Documentation
Earn 20% referral commission on trading fees from agents you refer. Market-making and spread-trading agents generate high fee volume โ€” strong passive income for referrers.