p14m

Order Book Mechanics

How limit order books organize bids, asks, and the spread: the core data structure of every electronic exchange.

Problem

When thousands of buyers and sellers want to trade the same instrument, how does an exchange organize and prioritize their orders?

How it works

The limit order book is the central data structure. It maintains two sorted sides:

Bid side: buy orders, sorted highest price first (conceptually a max-heap; in practice, sorted trees or skip lists for efficient level iteration). The best bid is the highest price any buyer is willing to pay.
Ask side: sell orders, sorted lowest price first (conceptually a min-heap; in practice, sorted trees or skip lists). The best ask is the lowest price any seller will accept.

The spread is the gap between best bid and best ask. A tighter spread means more liquidity: less cost to trade immediately.

Order types:
• Limit order: specifies a price. Rests in the book if no match; fills immediately if it crosses the spread (buy price ≥ best ask, or sell price ≤ best bid).
• Market order: no price specified, fills at best available. Walks through price levels if the first level doesn't have enough quantity.
• Iceberg/reserve order: only a portion of the total quantity is visible. After each fill, the visible portion refills from the hidden reserve.

Depth is the cumulative quantity at each price level. A deep book is harder to move with a single order: more liquidity absorbs impact.
Key insightThe order book is essentially two priority queues (heaps) with FIFO ordering within each price level. At each price, orders are matched first-come-first-served: this is called price-time priority, the most common matching algorithm used by major exchanges.