Quant Sandbox
DerivativesPortfolio & RiskFixed IncomeCorporate FinanceProbability & MeasureStochastic ModelsMarket MicrostructureGuide
Guide
Derivatives pricing0 / 17
01Forwards, calls and puts02Combining positions03Arbitrage and the forward price04Put–call parity05The one-step binomial model06Risk-neutral probabilities07Multi-step trees and backward induction08American options and early exercise09Delta and hedging10Geometric Brownian motion11The Black–Scholes formula12The Greeks: gamma, vega, theta and rho13Options on dividend-paying stocks, indices, currencies and futures14Implied volatility and the volatility smile15Stochastic volatility and the Heston model16Static replication: Breeden–Litzenberger and Carr–Madan17Exotic options: barriers, Asians and digitals
Portfolio & risk0 / 12
01Returns and volatility02Diversification and correlation03The efficient frontier and the capital market line04Risk aversion and the optimal complete portfolio05CAPM, beta and the security market line06Performance measures: Sharpe, Treynor, Jensen and information ratio07Factor models and systematic risk08The Fama–French factor models09Value at Risk and expected shortfall10Systemic risk and contagion11Portfolio constraints and the no-short-sales frontier12Estimating expected returns and covariances
Fixed income0 / 10
01Bond prices and yields02Duration and convexity03Immunization and duration matching04Spot rates, forward rates and the yield curve05Non-parallel curve moves and key-rate durations06Bond futures and the cheapest-to-deliver07Interest rate swaps08Callable bonds and negative convexity09Credit risk: default probabilities and credit spreads10Real rates, inflation and inflation-linked bonds
Corporate finance0 / 10
01Interest, compounding and discounting02Annuities, perpetuities and loan amortization03Net present value and internal rate of return04Project risk: sensitivity, scenarios and Monte Carlo NPV05The weighted average cost of capital06Capital structure and the Modigliani–Miller theorems07Dividends, payout policy and the dividend discount model08Discounted cash flow valuation09Relative valuation with multiples10Real options: the value of flexibility
Probability and measure0 / 13
01Measuring the size of sets02σ-algebras and Borel sets03Lebesgue measure and null sets04Measurable functions05The Lebesgue integral06Convergence theorems07Probability spaces and Kolmogorov's axioms08Random variables and their distributions09Expectation, variance and inequalities10Independence and product measures11Modes of convergence and the law of large numbers12Conditional probability and conditional expectation13Measure theory in option pricing
Stochastic models0 / 17
01Random walks and Brownian motion02The law of large numbers and the central limit theorem03Probability spaces, σ-algebras and random variables04Filtrations, adapted processes and stopping times05Conditional expectation and martingales06Properties of Brownian motion07The reflection principle and first passage times08The Brownian bridge09The Itô integral10Itô's lemma11Kolmogorov equations and the Feynman–Kac formula12Change of measure and Girsanov's theorem13Monte Carlo option pricing14Simulating SDEs: the Euler–Maruyama scheme15Correlated Brownian motions and multi-asset models16Mean reversion: Ornstein–Uhlenbeck and Vasicek17Jumps and the Merton jump-diffusion model
Market microstructure0 / 11
01Market makers and liquidity02The limit order book03Queue position and fill probability04Adverse selection and informed trading05The Glosten–Milgrom model06Measuring and decomposing the bid–ask spread07Informed trading and Kyle's lambda08Price impact and optimal execution09Inventory risk and quote skewing10Optimal quoting: the Avellaneda–Stoikov model11Market making profit and loss attribution
Knowledge graph

© 2026 Quant Sandbox · A study aid for quantitative finance

Privacy & dataNo cookies

This site does not use cookies and asks for no personal data. It keeps a few small settings in your browser's local storage — your chosen theme and language, the sidebar layout, and your progress and answers in the Guides — so it remembers them on your next visit. This data never leaves your device; clearing your browser storage removes it. Inputs you change can also be captured in the page URL, so you can share or bookmark a specific setup. The site uses Vercel Web Analytics, a privacy-friendly, cookieless service that records only anonymous, aggregated usage (such as page views) without identifying you or tracking you across other sites.

Guides/Market microstructure/02

The limit order book

Lesson 2 of 11 · 1 min read

"Market makers and liquidity" described what a market maker does: it quotes a bid and an ask and earns the spread for standing ready to trade. This lesson builds the machine those quotes live in, the limit order book. It defines the two kinds of order, shows how the book is organised and who gets filled first, and then follows a large market order down the book to measure what it costs to trade size.

Prices are quoted in USD per share, and a tick is the smallest allowed price step, 0.01 here. Sizes are in shares.

Orders

A limit order has three parts: a side (buy or sell), a price and a size. It says: trade up to this size, at this price or better. A buy limit order at 99.99 accepts any price of 99.99 or lower. If nothing on the other side is willing to trade at that price, the order rests in the book and waits. Resting orders are what provide liquidity.

A market order has a side and a size but no price. It trades immediately against the best resting orders on the opposite side, whatever their prices are. A market buy hits resting sell orders; a market sell hits resting buy orders. It takes liquidity instead of providing it.

A limit order whose price already reaches the other side, such as a buy at 100.05 when the best sell is at 100.01, is marketable. The part that can trade does so at once, at the resting orders' prices, and any remainder rests at the limit price. A resting order can also be cancelled at any time, which removes it from the book without a trade.

The book

The book collects all resting limit orders. Buy orders are the bids and sell orders the asks. Bids are sorted from the highest price down, asks from the lowest price up, so the best prices of both sides face each other in the middle.

The best bid bbb is the highest bid and the best ask aaa the lowest ask. Together they are the touch. The spread is a−ba - ba−b, and the mid price is their average:

m=a+b2.m = \frac{a + b}{2}.m=2a+b​.

At each price the book keeps a level, the queue of orders resting there. The depth of a level is the total size of its orders, and the cumulative depth at a level is the depth of that level plus all better ones on its side. In the examples below the best bid is 99.99 and the best ask 100.01, so the mid is 100.00 and the spread is two ticks.

Price–time priority

When a market order arrives, the book needs a rule for which resting order trades first. Almost every exchange uses price–time priority: orders at a better price trade first (higher for bids, lower for asks), and among orders at the same price the one that arrived earlier trades first. A level is therefore a first-in, first-out queue.

Both parts of the rule reward the people who provide liquidity. A better price moves an order to the front of the book, and an earlier arrival moves it to the front of its queue. The price rule pushes quotes towards each other and narrows the spread; the time rule rewards speed, and it is why a later lesson on queues treats a place in the line as something worth having. Cancelling an order and re-entering it, even at the same price, sends it to the back of the queue.

Walking the book

A market buy of size QQQ takes the whole of the best ask level first. If that is not enough, it moves to the next ask level, and so on until all QQQ shares are bought. The order walks the book. Suppose it takes qiq_iqi​ shares at price pip_ipi​ at the iii-th level it reaches, so that ∑iqi=Q\sum_i q_i = Q∑i​qi​=Q. Its average price is the size-weighted average of those prices:

pˉ=∑ipi qi∑iqi.\bar p = \frac{\sum_i p_i\, q_i}{\sum_i q_i}.pˉ​=∑i​qi​∑i​pi​qi​​.

The measure of cost is slippage, the gap between the average price and the mid price at the moment the order was sent. For a buy it is positive when pˉ\bar ppˉ​ is above mmm, and it is quoted in basis points (bp, one hundredth of a percent) of the mid. In dollars, the total cost of the order against the mid is the shares times the price gap:

slippage=pˉ−mm⋅104 bp,cost=Q (pˉ−m).\text{slippage} = \frac{\bar p - m}{m}\cdot 10^{4}\ \text{bp}, \qquad \text{cost} = Q\,(\bar p - m).slippage=mpˉ​−m​⋅104 bp,cost=Q(pˉ​−m).

For a market sell the signs flip: the order receives pˉ\bar ppˉ​ below the mid, so slippage is (m−pˉ)/m(m - \bar p)/m(m−pˉ​)/m. Even a one-share order pays something. With the best ask at 100.01 and the mid at 100.00, it costs 0.01 per share, or 1 bp. That is half the spread, the price of immediacy from the previous lesson.

Worked example

A market buy of 1,600 shares

  1. The asks are 100.01 for 318 shares, 100.02 for 311, 100.03 for 518 and 100.04 for 453. The first three levels are taken in full, so the fourth level supplies the rest of the order.

    1600−318−311−518=453\displaystyle 1600 - 318 - 311 - 518 = 4531600−318−311−518=453=453
  2. The order consumes all four levels exactly. Its notional value is the sum of price times shares over the levels, in USD.

    318⋅100.01+311⋅100.02+518⋅100.03+453⋅100.04\displaystyle 318\cdot 100.01 + 311\cdot 100.02 + 518\cdot 100.03 + 453\cdot 100.04318⋅100.01+311⋅100.02+518⋅100.03+453⋅100.04=160,043.06
  3. Divide by the 1,600 shares to get the average price.

    pˉ=160043.06/1600\displaystyle \bar p = 160043.06 / 1600pˉ​=160043.06/1600=100.0269
  4. Slippage against the mid of 100.00, in basis points.

    100.0269−100.00100.00⋅104\displaystyle \frac{100.0269 - 100.00}{100.00}\cdot 10^{4}100.00100.0269−100.00​⋅104=2.69
  5. Cost against the mid in USD.

    1600 (100.0269125−100.00)\displaystyle 1600\,(100.0269125 - 100.00)1600(100.0269125−100.00)=43.06

Depth and the cost of size

The worked example shows the pattern: every extra level costs one more tick. To see how the cost grows with size, take a simple book in which every level holds the same depth ddd and the best ask is hhh ticks above the mid (here h=1h = 1h=1). Level j=1,2,…j = 1, 2, \dotsj=1,2,… then sits h+j−1h + j - 1h+j−1 ticks above the mid.

A buy of Q=k dQ = k\,dQ=kd shares takes kkk complete levels. Its average distance above the mid is the average of those kkk distances, and the arithmetic series ∑j=1k(j−1)=k(k−1)/2\sum_{j=1}^{k}(j-1) = k(k-1)/2∑j=1k​(j−1)=k(k−1)/2 gives

pˉ−m=(h+k−12)ticks,k=Qd.\bar p - m = \left(h + \frac{k-1}{2}\right)\text{ticks}, \qquad k = \frac{Q}{d}.pˉ​−m=(h+2k−1​)ticks,k=dQ​.

Slippage is therefore about linear in size: a fixed part hhh for the spread and a part that grows by 1/(2d)1/(2d)1/(2d) ticks for every extra share. Multiplying by QQQ gives the total cost in ticks:

Q (pˉ−m)=Q h+Q22d−Q2  ≈  Q22dfor large Q.Q\,(\bar p - m) = Q\,h + \frac{Q^2}{2d} - \frac{Q}{2}\;\approx\;\frac{Q^2}{2d}\quad\text{for large } Q.Q(pˉ​−m)=Qh+2dQ2​−2Q​≈2dQ2​for large Q.

Total cost grows with the square of the size. Doubling an order roughly quadruples the part of its cost that comes from walking the book, because it takes twice as many levels and each of its shares is also dearer on average. Deep books, with a large ddd, flatten this. Real books are usually thinner at the touch and thicker further out, so the first levels are the expensive ones and the curve eventually bends over; the quadratic rule is a guide for moderate sizes, not a law.

The figure runs this experiment on a book with ten levels a side, about 450 shares each beyond the first four. Choose a market buy or sell and drag the size: the rows the order consumes are highlighted, and the curve beside them shows slippage against size, with a marker at the chosen size. At the default of 1,600 shares it reproduces the worked example, four levels and 2.69 bp, costing 43.06 USD. A single level of 100 shares costs 1.00 bp. Double the size to 3,200 and eight levels are hit: slippage rises to 4.50 bp and the cost to 144.06 USD, more than three times as much for twice the shares.

A market order walking the bookOpen in Order Book
1 600
1004000

Bid 99.99 · mid 100.00 · ask 100.01

PriceRestingCumulativeTaken
100.01318318318
100.02311629311
100.035181 147518
100.044531 600453
100.054502 050
100.064502 500
100.074502 950
100.084503 400
100.094503 850
100.104494 299
Average price
100.0269
Slippage vs mid
2.69 bp
Levels hit
4
Cost vs mid
43.06 USD

A market order at the touch pays half the spread, and every further level adds a tick to the average price. Cost against the mid is Q(pˉ−m)Q(\bar p - m)Q(pˉ​−m), which grows roughly like Q2Q^2Q2 in a book of even depth.

Summary

  • A limit order has a side, a price and a size, and rests in the book until it trades or is cancelled; a market order has no price and trades at once against the opposite side.
  • The book keeps bids from high to low and asks from low to high, with the best bid, the best ask, the spread and the mid m=(a+b)/2m = (a+b)/2m=(a+b)/2 at the touch.
  • Price–time priority fills better prices first and earlier orders first within a price, so each level is a first-in, first-out queue.
  • A market order walks the book at average price pˉ=∑piqi/∑qi\bar p = \sum p_i q_i / \sum q_ipˉ​=∑pi​qi​/∑qi​, with slippage (pˉ−m)/m(\bar p - m)/m(pˉ​−m)/m and cost Q(pˉ−m)Q(\bar p - m)Q(pˉ​−m).
  • Even depth makes slippage about linear in size and total cost about proportional to Q2Q^2Q2, so size is expensive.
Try itWalk the book with market orders in the Order Book lab
3 questions on this lesson at the end of the series
Previous · 01Market makers and liquidityNext · 03Queue position and fill probability
Connections

The limit order book

Open the full graph
Builds on
07.01Market makers and liquidity
Leads to
07.03Queue position and fill probability07.04Adverse selection and informed trading07.06Measuring and decomposing the bid–ask spread07.08Price impact and optimal execution
See it in the knowledge graph
Labs for this lesson
Order Book