Setup
Market Context
Every liquid financial instrument traded on an electronic venue — equities, futures, options, FX spot — executes through a limit order book (LOB). The LOB is the matching engine at the heart of modern markets. Understanding its mechanics is a prerequisite for algorithmic trading, market making, optimal execution, and any quantitative work that touches execution quality, transaction costs, or intraday price dynamics.
This module covers the Level-2 data structure of the book, order types, queue dynamics, and how the LOB generates the bid-ask spread and the microprice — the starting points for any execution model.
Conventions
- Bid: the highest price at which a buyer is willing to buy (best bid, or BBO bid).
- Ask (offer): the lowest price at which a seller is willing to sell (best ask, or BBO ask).
- Mid-price: .
- Spread: . Quoted in ticks (minimum price increments) or basis points.
- Tick size: the minimum allowed price increment . For US equities, \delta = \0.01$.
- All prices are in units of the tick unless stated otherwise.
- Time is measured in microseconds () to milliseconds () for HFT contexts; seconds to minutes for slower strategies.
The Limit Order Book Data Structure
Level-2 Architecture
The LOB is a price-ordered queue on each side. At each price level , there is a queue of resting limit orders, each with a quantity and a timestamp . The full structure:
Bid side (buyers, sorted descending by price):
Ask side (sellers, sorted ascending by price):
where is the total resting quantity at the -th level. A Level-1 snapshot contains only the best bid and ask (). A Level-2 snapshot contains multiple levels.
Price-time priority. Within each price level, orders are executed in the order they arrived. An earlier limit order at price has priority over a later limit order at the same price . A limit order at a better price (on the bid side) always has priority over any order at .
C++ LOB Data Structure
#include <map>
#include <queue>
#include <cstdint>
// A single resting limit order
struct Order {
uint64_t order_id;
double price;
int quantity; // signed: positive = buy, negative = sell
uint64_t timestamp_ns; // nanosecond timestamp
};
// A price level: ordered queue of orders at the same price
struct PriceLevel {
double price;
std::queue<Order> orders; // FIFO: front() has highest priority
int total_quantity() const {
int total = 0;
// Note: in production, maintain a running total (O(1))
auto q = orders;
while (!q.empty()) { total += q.front().quantity; q.pop(); }
return total;
}
};
// The full LOB
// Bid side: map ordered descending (highest price = best bid)
// Ask side: map ordered ascending (lowest price = best ask)
using BidBook = std::map<double, PriceLevel, std::greater<double>>;
using AskBook = std::map<double, PriceLevel>;
struct LimitOrderBook {
BidBook bid_book;
AskBook ask_book;
double best_bid() const { return bid_book.empty() ? 0.0 : bid_book.begin()->first; }
double best_ask() const { return ask_book.empty() ? 0.0 : ask_book.begin()->first; }
double mid() const { return (best_bid() + best_ask()) / 2.0; }
double spread() const { return best_ask() - best_bid(); }
};
Order Types
Limit Order
A limit order to buy units at price is a commitment to buy at most units at a price of or better (i.e., at or any lower price on the ask side). It rests in the book until filled, cancelled, or expired.
Execution risk: the limit order may not be filled if the market never reaches price . In a fast-moving market, by the time the exchange acknowledges a limit order, the price may have moved away.
Adverse selection risk: a resting limit order is a free option granted to the market. If the true value of the asset moves to (below the bid limit), the market maker who posted a bid at is filled at a price now worse than fair value. This is the fundamental adverse selection problem of liquidity provision.
Market Order
A market order to buy units executes immediately at the best available ask prices, walking up the book if necessary. It pays the spread and any market impact above the best ask.
Guaranteed fill, uncertain price. The execution price is the volume-weighted average of the levels consumed. For a buy market order of size :
where are the ask levels traversed in order, and "remaining" is the unfilled quantity.
Immediate-or-Cancel (IOC)
An IOC order executes as much as possible at the limit price (or better) immediately. Any unfilled portion is cancelled. Used to "lift" a specific quantity without risking a resting order.
Fill-or-Kill (FOK)
A FOK order must be filled in its entirety immediately or cancelled entirely. Used when partial fills are unacceptable (e.g., hedging a position that requires exact notional).
Iceberg (Reserve) Order
An iceberg order displays only a portion (the "peak") of its total size. When the displayed peak is filled, the next tranche is automatically shown. Icebergs are used to reduce information leakage from large orders. Many exchanges give iceberg orders lower priority than fully displayed orders at the same price (the hidden quantity is placed behind visible orders at the same level).
Queue Position Dynamics
Why Queue Position Matters
On a liquid equity, hundreds of limit orders may rest at the best bid. Price-time priority means that an order submitted later will be filled after all earlier orders at the same price are exhausted. The queue position — measured as the quantity of orders ahead in the queue — directly determines:
- The probability that the order is filled before the quote moves.
- The expected execution time.
- The expected adverse selection cost (fill probability is higher when the stock is moving toward the limit price — exactly when you don't want to be filled).
Queue Model
Let denote the quantity ahead in the queue and the quantity behind. At the moment the queue empties from the front (a large market order arrives), the resting limit order is at risk of being filled. The fill probability at the best bid over a horizon is approximately:
where is the arrival rate of market orders of average size exceeding . This is a crude Poisson approximation; more accurate models (e.g., Cont-Stoikov-Talreja 2010) use Markov chains on the LOB state.
Queue position deteriorates over time as new orders are posted behind (these don't affect priority) and as the best quote cancels/refills. Cancellations of orders ahead improve your queue position; new orders behind worsen it.
Adverse Selection Cost of Market Orders
A market order to buy reveals information: the buyer believes the asset is worth more than the current ask. The market maker who filled the market order has sold at the ask, but if the buyer is informed, the true value is higher — the market maker sold at a discount. This is the adverse selection cost borne by liquidity providers.
Glosten-Milgrom decomposition (preview). The bid-ask spread compensates the market maker for adverse selection plus inventory risk plus order processing costs:
At time , suppose a fraction of arriving traders are informed (they know the true value ) and fraction are uninformed (they trade for liquidity reasons). The market maker sets:
where is the prior on value and is the value conditional on an informed buy. The spread is positive precisely because informed orders are indistinguishable from uninformed ones.
Mid-Price and Microprice
Microprice
The mid-price ignores the imbalance between bid and ask queue sizes. If the bid queue is very large relative to the ask queue, the price is more likely to move up than down — the market is "leaning bid". The microprice incorporates this imbalance:
where and are the best-level quantities. Interpretation: the microprice is the weighted average of the two best quotes, with weights inversely proportional to the queue sizes. A large bid queue pushes the microprice towards the ask.
Why microprice predicts price moves. If , an incoming market sell order is less likely to deplete the bid entirely and more likely to bounce — the next quote move is more likely upward. Empirically, the microprice is a better short-term price predictor than the mid-price (Stoikov 2018).
Order Flow Imbalance (OFI)
Over a time window , the order flow imbalance is:
where bid events are best-bid size increases (new orders posted) and ask events are best-ask size decreases (orders cancelled or filled). OFI has a strong linear relationship with mid-price changes over short horizons (Cont, Kukanov, Stoikov 2014):
Limitations
Model of discrete prices. Real LOBs operate at discrete tick sizes. Continuous-price models of the LOB (e.g., the PDE models of Cont and de Larrard) are tractable approximations that break down at tick-level granularity, particularly for instruments with few resting orders at each level.
Latency. In HFT contexts, the LOB state received by a participant is already stale by the time it arrives. Round-trip latency (co-location to exchange) of 50–500 µs means the book has potentially changed significantly since the last snapshot. Queue position models must account for the probability of cancellations during the latency window.
Hidden orders. Iceberg orders, dark pools, and internalised flow mean that the visible LOB is not the complete picture of available liquidity. A displayed size of 1000 shares may be backed by a 50,000-share iceberg. Models that assume the visible book is complete systematically underestimate available liquidity at the touch.
Non-stationarity. LOB dynamics are strongly non-stationary across the trading day: the spread is wide at the open, narrows through the session, widens near earnings announcements, and widens dramatically in stress events. A single static model is insufficient; adaptive models are required.
Interview Angle
L1. Describe the structure of a limit order book. What is price-time priority and why does it matter for a market maker? Explain the difference between a market order and a limit order, and what risk each carries.
LOB structure: Two sorted queues (bid and ask), each a sorted list of price levels, each level a FIFO queue. Best bid is the highest buy price; best ask is the lowest sell price. Price-time priority: within a level, earliest order fills first; a better-priced order always fills before a worse-priced one regardless of arrival time.
Market order: guaranteed fill, uncertain price (pays the spread, may walk the book). Risk: execution price can be far from the pre-trade mid if the book is thin. Limit order: certain price, uncertain fill. Risk: may not execute; adverse selection when it does.
L2. Derive the microprice formula and explain why it is a better short-term price predictor than the mid-price. What is order flow imbalance (OFI) and what does it measure?
Microprice: . A large bid queue () makes it harder for incoming sell market orders to move the price down (the bid absorbs them), so the next price move is more likely upward — the microprice reflects this by being closer to the ask. The mid-price equally weights both sides regardless of liquidity imbalance, making it a weaker predictor.
OFI measures the net demand for liquidity at the touch: bid-side additions minus ask-side depletions. Large positive OFI signals aggressive buying pressure and predicts positive price moves. The OFI-price change regression (Cont et al. 2014) provides one of the most robust linear price impact models from Level-2 data.
L3. A market maker rests a limit sell at the ask. Explain the adverse selection risk this creates, derive the break-even spread in the Glosten-Milgrom model with informed fraction , value states , and equal prior. How does the presence of iceberg orders affect the market maker's assessment of adverse selection?
Adverse selection: the resting limit sell at is a free option to informed buyers. If the true value is , informed buyers take the offer and the market maker sells at — a loss. Uninformed buyers trade at random, contributing no information loss.
Break-even in GM: With prior , let . A buy arrives with probability from an informed buyer (value ) and from an uninformed buyer (value ). The market maker's expected value when a buy arrives: . Break-even ask: . Similarly, . Spread: . The spread is zero only when (no informed traders).
Iceberg effect: the hidden quantity in an iceberg order is not visible in Level-2 data. A market maker observing a small displayed ask size may infer the true ask liquidity is larger (icebergs are common for institutional sellers). This reduces the estimated adverse selection — if an informed buyer would consume the book, they are less likely to reveal themselves against a large iceberg. In practice, iceberg orders reduce the rate of adverse fills but increase queue uncertainty.