How AI agents interpret order books before trading
An AI agent reads an order book by fetching bid and ask levels, measuring spread and depth, and checking those values against strategy rules before trading.
- 01An AI agent must normalize venue-specific order book formats into a single internal model before it can evaluate any trading opportunity.
- 02Spread, depth, and imbalance are the three primary signals an agent extracts from bid and ask levels before deciding to trade.
- 03Slippage estimates derived from order book depth should constrain order size, because thin markets can move against the agent.
- 04Every order book snapshot the agent consumes should be logged with a timestamp and a checksum so that decisions remain auditable.
- 05Paper trading lets the agent rehearse order book parsing against live data without risking capital, but live markets can still lose money.
An AI agent interprets an order book by fetching bid and ask levels from a market data feed, sorting them into a normalized internal model, and extracting signals like spread and depth before it compares them against its strategy rules. The process repeats on every tick or poll so the agent always reasons from current liquidity. It does not see a chart or a colorized screen. It processes nested arrays of prices and quantities that represent resting orders on a venue.
What does an order book look like to an AI agent?
To the agent, an order book is a structured list of resting orders, not a visual interface. A typical feed returns two sequences: one for bids and one for asks. Each entry contains at least a price and a size, and sometimes additional metadata such as order count or update sequence numbers. Bids are arranged from highest to lowest price, while asks are arranged from lowest to highest price. The highest bid and the lowest ask form the top of book, and the gap between them is the spread.
On some venues the data arrives as a snapshot that replaces the previous state entirely. On others it arrives as a delta that adds, removes, or modifies individual rows. The agent must know which mode it is in. If it treats a delta as a snapshot, it will build a corrupted view of liquidity and may misprice its own orders. If it treats a snapshot as a delta, it will double count resting size.
Different market types add their own quirks. A stock broker may report lots rather than individual shares. A perps venue may mix funding rate metadata into the feed. An options venue may return implied volatility alongside each quote. A prediction market may express prices as percentages. The Felix API abstracts these differences so that the agent receives a single shape regardless of whether it is trading stocks, crypto, perps, options, or prediction markets. How to manage a multi-market portfolio with one agentic API discusses how that unification works across a portfolio.
How does the agent normalize raw market data?
Normalization is the step that turns venue-specific messages into an internal model the strategy can query. The agent first validates the incoming payload. It checks timestamps to reject stale snapshots, sequence numbers to detect dropped deltas, and price formatting to ensure decimals are handled consistently. If a feed includes sizes in native units, such as contracts or lots, the agent converts them into notional dollar values so that its risk calculations remain uniform. Price formatting also matters when a venue omits decimal points or uses string representations. The agent must parse these into numeric types without losing precision, because a rounding error at this stage can corrupt the entire depth map.
The agent then builds a local depth map. It inserts each bid and ask into a tree or sorted dictionary keyed by price. This structure lets the agent query the cumulative size available up to a given price level in logarithmic or constant time, depending on the implementation. The agent also computes derived values immediately upon insertion: the best bid, the best ask, the mid price, and the spread. Keeping these derived values updated on every message prevents the strategy from performing expensive scans later. Some implementations maintain a secondary index by size, which helps the agent spot large walls or iceberg orders that sit away from the top of book.
Because the agent may trade across multiple venues or market types through one API, it maintains a separate depth map per market. It tags each map with a unique identifier and a last-updated timestamp. If a feed goes silent for longer than a configured threshold, the agent marks that book as stale and pauses trading until the connection recovers. This prevents decisions based on frozen data. The threshold itself is a safety parameter; aggressive strategies might set it to one second, while slower strategies might tolerate five. The choice depends on how quickly the particular market moves.
The exact request schema is in the docs; the shape looks like this:
curl -H "Authorization: Bearer YOUR_KEY" \
"$FELIX_API_BASE/orderbook" \
-d '{"market":"EXAMPLE-USD","depth":10}'What signals does the agent extract from bids and asks?
Once the local depth map is current, the agent runs a set of signal extractors. The simplest is the spread, calculated as the best ask minus the best bid. A wide spread often indicates low liquidity or high volatility; a narrow spread suggests a competitive, liquid market. The agent compares the spread against a strategy-specific threshold because entering a position in a wide spread can erode expected edge on the first tick. Some strategies ignore the absolute spread and instead look at the spread as a percentage of the mid price, which makes comparison easier across assets with different nominal prices.
Depth is the next signal. The agent sums the size of the first N levels on each side to produce bid depth and ask depth. It may also compute depth imbalance, which is the ratio of bid depth to ask depth. Suppose the cumulative bid depth up to one percent away from the mid price is ten thousand dollars and the ask depth is two thousand dollars. The agent might interpret that as temporary buying pressure, or it might interpret it as a wall that will resist upward movement, depending on the strategy. The lookback distance matters. An agent that only looks one level deep will miss large blocks of hidden liquidity that sit slightly further away.
The agent also tracks the mid price and the weighted average price of the top few levels. On venues with low liquidity, the mid price can jitter by a large percentage on a single small order. The agent can dampen this noise by using a volume-weighted average of the top three levels instead of a simple mid. Some strategies also monitor the rate of change of depth, looking for sudden removals of liquidity that precede volatile moves. If the bid side loses fifty percent of its depth in under a second, the agent may delay entry until the book stabilizes.
Misreading these signals is a common source of error. How AI agents mishandle perpetual futures and how to prevent it explains how misinterpreting depth on leveraged markets can lead to oversized positions and unexpected liquidation risk.
How does the agent estimate execution cost and slippage?
An order book shows resting liquidity, but it does not guarantee that all of that liquidity will remain when the agent's order arrives. The agent therefore estimates slippage before it decides on size. It starts with the notional value it intends to trade, say five hundred dollars, and walks down the book from the best price until the cumulative size meets or exceeds that notional. The average fill price across those levels is the estimated execution price.
The difference between the estimated execution price and the pre-trade mid price is the expected slippage. If the agent finds that its full order would consume three price levels and the average fill is two percent away from the mid, it knows that the market is too thin for that size. It can then either reduce the order, split it into slices, or skip the trade entirely. Slicing can help if the agent is willing to wait for other participants to refresh the book, but it also exposes the strategy to adverse price movement while the order is partially resting. In some cases, the agent will compute a slippage threshold as a hard rule: if expected slippage exceeds half a percent, do not trade.
This estimation matters across all five market types. A prediction market with a wide tick size might show a two percent spread even when it is healthy, while a crypto pair might show a one basis point spread but hide most of its real depth at level five. The agent must not rely on top-of-book alone. It needs to look several levels deep, and it must refresh that view immediately before submission because liquidity can disappear in milliseconds. On options venues, the agent must also account for the fact that quoted size may represent a market maker's indicative interest rather than a firm commitment to trade at that size.
Even with a good slippage model, the agent can still lose money on execution. How spend caps and drawdown limits work for AI trading agents describes how hard limits act as a backstop when market depth evaporates faster than the model expects.
How does the agent decide whether to place an order?
Signal extraction and slippage estimation feed into a decision gate. The agent evaluates the current market state against its strategy rules. A rule might state: buy if the spread is below ten basis points, bid depth exceeds ask depth by a ratio of two to one, and the mid price is below a moving average. The agent does not act on a single signal; it combines them into a boolean condition. Complex strategies may use a scoring model instead of a hard threshold, assigning weights to each signal and entering only when the weighted score crosses a boundary. The agent recalculates this score on every book update, so it must be careful not to burn compute on irrelevant ticks.
If the condition passes, the agent calculates order size in plain US dollars. The API normalizes venue-specific contract math, so the agent can think purely in notional terms. Before it finalizes the size, it checks its own inventory. It asks whether it already holds a position in this market, whether adding to it would breach a concentration limit, and whether the trade aligns with its exit plan. An agent that enters without a planned exit is likely to hold through adverse moves. The exit plan might be a target price, a time limit, or a stop condition tied to a change in order book structure, such as a reversal in depth imbalance. Position sizing itself can be a function of the signal strength. A weak signal might warrant a quarter of the normal allocation, while a strong signal might warrant the full budget slice, as long as the hard limits permit it.
The decision gate also includes a randomization or cooldown check in some implementations. If the agent has traded the same market within the last minute, it might delay to avoid overtrading. This is especially important on low-timeframe strategies where the order book can flicker and generate noisy signals. The agent logs the final decision, the market state that produced it, and the intended order parameters. That log entry becomes the input to the safety layer, which performs its own independent checks before any network request is made.
What safety checks run before the order leaves the agent?
After the decision gate opens, the order passes through a safety layer that has no knowledge of strategy. This layer checks budget caps, position limits, and drawdown thresholds. It asks a simple question: if this order fills, will the total spent today exceed the owner's daily cap? Will the position in this market exceed the maximum allowed? Will the account drawdown breach the emergency threshold? If any answer is yes, the order is blocked.
The safety layer also checks the kill switch state. If the owner has triggered a panic halt, or if an automated circuit breaker has fired, the order dies here. The agent then flattens or cancels open orders depending on the configuration. These controls are non-custodial by construction; the owner defines the limits and the agent cannot override them or withdraw funds to an unapproved address.
Finally, the agent writes an audit record. It logs the order book snapshot that informed the decision, the signals extracted, the slippage estimate, the decision outcome, and the safety check results. Omitting any of these fields makes post-trade forensics difficult. Common audit log mistakes that hide trading agent risk covers the logging patterns that obscure what actually happened during a trade.
Paper trading lets the agent rehearse this entire pipeline against live market data without committing real capital. When the owner is ready to authorize live trading, the same pipeline runs with the same safety checks, but the orders carry real economic consequences. Trading can lose money, including everything, and no order book signal can eliminate that risk.
Frequently asked questions
The Felix API normalizes the shape of the data across all five market types, so the agent can use a single parser. The strategy may still apply different thresholds because spreads and depths vary by market type.
Polling frequency depends on the strategy timeframe. A high-frequency approach may need streaming deltas, while a slower strategy can poll every few seconds. The agent should always check timestamps to avoid acting on stale data.
Thin books increase slippage and the risk of adverse selection. The agent can reduce size, split orders, or skip the trade entirely. Hard limits and spend caps provide a safety net if the book moves unexpectedly.
The agent should mark the book as stale and pause trading until the connection recovers. Submitting orders without current book data is equivalent to trading blind and can lead to immediate losses.
A snapshot preserves the context of the decision. Without it, an owner cannot reconstruct why the agent thought the spread, depth, or imbalance justified the trade. Missing context makes risk analysis nearly impossible.
Paper trading validates parsing and signal logic against live data, but it cannot fully replicate execution slippage or market impact in thin markets. It is a necessary rehearsal step, not a guarantee of live performance.
Give your agent a key.
One key to trade stocks, crypto, perps, options, and prediction markets. Live after owner authorization.
Most people conflate trading bots and agents because both submit orders automatically, but their architectures, failure modes, and safety requirements are fundamentally different.
Starting with real money does not require a large account. The right controls let you test agentic trading with a budget you can afford to lose.