How an AI agent reads an order book for the first time
A beginner's walkthrough of how AI agents read bids, asks, and depth from a live order book, normalize the data across venues, and decide whether to trade.
- 01An AI agent reads an order book by polling or streaming bids, asks, and depth, then normalizes venue-specific formats into a single internal model.
- 02The best bid and best ask define the spread, which tells the agent the immediate cost of entry and the liquidity available at the top of the book.
- 03Depth beyond the top level reveals slippage risk; an agent must check how much size is available before it decides to trade a specific dollar amount.
- 04Safety checks like budget caps, position limits, and dollar-based order sizing should run after the agent reads the book but before it sends any order.
- 05Beginners should test book-reading logic in paper trading mode so the agent can practice parsing data and respecting guardrails without risking real capital.
An order book is a real-time list of every open buy and sell order for a given market. An AI agent reads this list to understand the current price, available liquidity, and the cost of entering or exiting a position. Before it can trade stocks, crypto, perps, options, or prediction markets through a single API, the agent must learn to parse bids, asks, and depth into a coherent picture of supply and demand. Trading can lose money, including everything, so this walkthrough explains the process step by step, starting from the raw data and ending at the safety checks that prevent a bad read from becoming a costly trade.
What is an order book and why does an agent need it?
Markets do not trade at a single fixed price. At any moment, some participants want to buy and others want to sell, and they disagree about what the asset is worth. An order book collects these intentions in two columns. One column holds bids, which are offers to buy at specific prices. The other holds asks, which are offers to sell at specific prices. Together they form a snapshot of latent demand and supply. For an AI agent, the book is the primary source of truth about current market conditions. It does not rely on delayed charts or summary statistics. It looks at the actual resting orders that it could interact with if it chose to trade. This matters because an agent that trades through one API across multiple market types needs a consistent way to interpret what it sees. Whether the underlying venue is a stock broker, a perps venue, or a prediction market, the conceptual structure is the same: buyers on one side, sellers on the other, and time priority within each price level. The book is usually sorted by price, and within each price level by time. The earliest order at a given price has priority. An agent should understand that the size displayed may not all be available instantly if other buyers or sellers are already ahead. This nuance matters when the agent is competing for scarce liquidity. The agent needs this view for two practical reasons. First, it must know the current entry price. Second, it must estimate how much its own order would move the market. A thin book with small orders near the top implies that even a modest trade could shift the price. A deep book with large orders implies more absorption. Without reading the book, an agent is effectively trading blind, guessing at prices that may no longer exist by the time its order arrives.
How does an agent connect to live market data?
Agents typically receive order book data through two paths. One path is a direct stream that pushes updates as they happen. The other is a periodic poll where the agent requests a snapshot at fixed intervals. Both methods are valid, and the choice depends on the latency requirements of the strategy and the stability of the connection. When an agent connects through MCP tools, the tool abstracts the wire format. The agent does not need to parse raw binary packets or venue-specific schemas. Instead, it calls a standardized function that returns a normalized view of the book. How MCP trading tools connect AI agents to markets in 2026 covers this plumbing in detail. For developers using the REST API, the pattern is similar: authenticate with a scoped key, request the book for a specific symbol, and receive a structured response. The exact request schema is in the docs; the shape looks like this:
curl -H "Authorization: Bearer YOUR_KEY" \
https://api.example.com/v1/book?symbol=EXAMPLE \
| jq '.bids[0], .asks[0]'The response typically contains arrays of price and size pairs. The agent maps these into its internal model, stripping venue-specific fields and converting size into a common denominator, usually a dollar value. Some venues report size in native tokens, others in lots. The middleware handles these conversions so the strategy code sees a single schema, letting one agent trade across stocks, crypto, perps, options, and prediction markets without rewriting core logic for each venue. This normalization step is critical because an agent that trades across asset classes cannot reason about one contract of a perps venue, one share at a stock broker, and one outcome lot at a prediction market in the same way. By converting everything into a unified representation, the agent keeps its decision logic clean and portable.
What do bids, asks, and spread tell the agent?
Once the agent holds a normalized book, it looks at the top level first. The highest bid is the best price anyone is willing to pay. The lowest ask is the best price anyone is willing to accept. The gap between them is the spread. A tight spread usually means that buyers and sellers agree on value and that the agent can enter or exit near the last traded price. A wide spread signals disagreement, low liquidity, or a pause in activity. The agent uses these three numbers to anchor its expectations. If it wants to buy immediately, it knows it must pay at least the best ask. If it wants to sell immediately, it must accept at most the best bid. Any strategy that assumes it can trade in the middle of the spread without waiting is making an optimistic assumption. An honest agent logic accounts for this by treating the ask as the effective buy price and the bid as the effective sell price. The agent also distinguishes between a quoted spread and an effective spread. The quoted spread is the visible gap between the best bid and best ask. The effective spread accounts for the size the agent actually wants to trade. If the agent needs to buy more than the size available at the best ask, its effective entry price will be worse than the best ask. A smart agent computes both numbers and uses the effective spread as the true cost of the trade. The spread also serves as a crude filter. Suppose an agent is scanning multiple markets for an entry signal. A market with a wide spread might be too expensive to enter on a short horizon because the round-trip cost of buying and then selling could consume a large portion of any expected move. The agent can compare spreads across venues or assets and deprioritize those where the friction is highest. It does not need to predict the future to know that crossing a wide spread twice is a heavy burden.
How does an agent use depth to size its trades?
The top of the book shows the price, but it does not show how much volume rests at that price. Depth describes the cumulative size available at each price level beyond the best bid and ask. An agent that wants to trade a hundred dollars against a book where only twenty dollars sits at the best ask will push through multiple levels. Each level is worse than the one before it. The average price the agent pays will be higher than the best ask, and the difference is slippage. To avoid surprises, the agent sums the depth on the relevant side before it commits. It checks whether the intended dollar amount fits within the first few levels or whether it would chew through the book. If the book is too thin, the agent has a few options. It can reduce its order size to match the liquidity that is actually there. It can split the order into smaller pieces and space them over time. Or it can skip the trade entirely because the execution cost would erase the edge it believes it has. The agent can also track how depth changes over time. If the best ask is refreshed with new size each time it is consumed, the agent may infer a large seller is defending that level. If bids are pulled without replacement, buyers may be retreating. These are not definitive signals, but they add context. An agent that records depth history can compare the current book against recent observations and adjust its urgency accordingly. This is where dollar-based sizing becomes important. How to start trading with dollar-based order sizing in 2026 explains why the API expresses orders in plain US dollars. The agent does not need to calculate contract multipliers or margin ratios. It simply states, 'I want to trade this many dollars.' The API then checks the book depth against that dollar amount and warns the agent if the market cannot absorb it cleanly. How position sizing keeps AI trading agents safe by design describes how this alignment between depth awareness and order size prevents runaway slippage.
What safety checks happen after the agent reads the book?
Reading the book is only the first half of the process. The second half is deciding whether the reading justifies a trade. A well-built agent does not send an order immediately after it finds a favorable bid or ask. It passes the intended trade through a set of owner-defined constraints. These constraints include a budget cap, which prevents the agent from deploying more capital than the owner allows. They include a position limit, which prevents the agent from concentrating too heavily in one direction. They include a drawdown limit, which can pause trading if recent activity has produced a string of losses. And they include a panic or kill switch, which flattens positions and revokes the key if the owner intervenes. How to control risk when an AI agent trades through MCP walks through the practical setup of these controls. The agent should also validate the book data itself. If the spread is implausibly wide, if the depth has vanished, or if the timestamp on the data is stale, the agent should reject the signal. Trading on stale or corrupted book data is a common source of unintended losses. A conservative agent treats bad data as a stop sign, not as a temporary glitch to ignore. Some owners also configure webhook alerts or a second confirmation step for orders above a certain size. Even if the agent reads the book perfectly, these rules can halt execution. This layered approach means that no single failure, whether a misread book or a logic bug, has a clear path to real losses. Finally, the agent checks its own state. Is it already holding a position in this market? Would the new order violate a self-imposed correlation rule? Does the exit plan require a specific stop level that the current book cannot support? All of these questions get answered in milliseconds before the order leaves the agent's context. The book provides the raw facts, but the guardrails determine whether those facts become an action.
How can a beginner test book reading without risking money?
Before an agent trades live capital, it should prove that it can read a book correctly and respect its constraints. Felix provides a paper trading mode for this exact purpose. In paper mode, the agent receives real market data, including live bids and asks, but its orders are simulated. The engine tracks hypothetical fills against the actual book, so the agent experiences realistic slippage and partial fills without moving the real market or risking real money. Beginners should run paper sessions long enough to cover different market conditions. A book that looks easy to read during a quiet afternoon may look very different during a volatile period. The agent should encounter wide spreads, thin depth, and rapid changes in top-of-book pricing. Each scenario tests whether the agent's parsing logic, sizing logic, and safety logic hold together. Paper trading also reveals whether the agent's data polling frequency is sufficient. An agent that reads the book once per minute may miss sudden depth changes that a faster poll would catch. Testing in paper mode lets the owner tune frequency without paying with real capital. Once the owner finds the right balance, the same settings carry over to live trading. When the owner is satisfied that the agent interprets the book consistently and that its safety checks trigger correctly, they can authorize a live key. The transition from paper to live is explicit and reversible. The owner can revoke the key, adjust the caps, or return to paper mode at any time. The goal is to make the first live trade a mundane continuation of a well-tested routine, not a leap into the unknown.
Frequently asked questions
The agent typically starts with the top few levels because they determine the immediate price and available liquidity. Reading deeper levels helps estimate slippage for larger orders, but most strategies do not need to parse the entire book to make a decision.
A thin book increases slippage and the risk of moving the price with a single order. The agent should either reduce its size, split the order, or skip the trade if the effective cost exceeds its strategy threshold.
Paper trading exposes the agent to real book dynamics, including spread changes and depth fluctuations, without risking capital. It lets the owner verify that the agent parses data correctly and respects sizing limits before authorizing live keys.
A well-configured agent checks timestamps and rejects stale data. Trading on an old snapshot can lead to orders that no longer match market reality, so the agent should treat stale books as a signal to wait rather than act.
The guardrails do not change how the agent reads the book, but they determine whether the agent is allowed to trade after it reads. Budget caps, position limits, and kill switches sit between interpretation and execution to prevent a bad reading from becoming a loss.
The agent reads through a normalized API layer that converts venue-specific formats into a single schema. This layer handles authentication, polling or streaming, and normalization so the agent can focus on decision logic.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Newcomers often treat scoped API keys like strong passwords. In practice, they are programmable contracts that limit what an agent can do, regardless of whether the agent is buggy, compromised, or hallucinating.
You can connect an LLM to real markets through one API that normalizes five asset classes and enforces safety limits you control.