---
title: "The Limit Order Book"
book: "Microstructure and Execution"
subject: quant
language: en
chapter: 1
exercises: 8
source: https://one-course.com/books/quant/10/en/chapter/1-the-limit-order-book
---

# Chapter 1 — The Limit Order Book

A trader sends an order to buy 100 shares at the best bid. The screen shows a price and a size; what it does not show is a line. In the simulated hour this book uses throughout, 2 834 orders joined the back of the best bid or ask: they found a median of 1 400 shares ahead of them, and only 13% of them ever traded. The best price is not a place where an order sits; it is a queue that an order waits in, and the order in which the queue formed decides who trades. This chapter describes the book as a state, as a stream of events that change the state, as a data structure a venue and every participant must maintain, and as a queueing system whose simplest model already says how long the wait is.

## 1.1 State: price levels and queues

**Definition 1.1 (Limit order, market order).**

A *limit order* is an order to buy at a stated price or lower, or to sell at a stated price or higher; the part that cannot execute at once rests in the book until it executes, is cancelled or expires. A *market order* is an order to buy or sell a quantity at the best prices available; it never rests.

**Definition 1.2 (Tick size, price level).**

The *tick size* $\delta_{\mathrm{tick}}$ is the smallest price increment a venue accepts for an instrument: every limit price is an integer multiple of it. A *price level* is the set of resting orders on one side of the book at one price.

**Definition 1.3 (Limit order book).**

A *limit order book* is the set of resting [limit orders](#def-mx-the-limit-order-book-orders) of one instrument on one venue, organised by side and by [price level](#def-mx-the-limit-order-book-tick); within a level, by priority. Its best bid $b_t$ and best ask $a_t$ are the highest resting buy price and the lowest resting sell price; $Q^b_t$ and $Q^a_t$ are the displayed quantities at them.

A book is *crossed* if $b_t\ge a_t$; a continuously trading book never is, because an order that would cross executes instead. The spread $s_t = a_t - b_t$ is at least one tick. Three views of the same state appear in every later chapter (One Quant Book 1, chapter 28): level 1 is $(b_t, Q^b_t, a_t, Q^a_t)$; level 2 adds the aggregated size at each deeper price; level 3 is the book itself, every order with its reference, in queue order ([Figure 1.1](#fig-mx-the-limit-order-book-book)).

![A limit order book at level 3. Each box is a resting order, its width its size; within a price level the oldest order is at the left. The best bid is 100.00 and the best ask 100.01, one tick apart. A new bid at 100.00 joins the back of its level; a market buy consumes the best ask from the front.](https://one-course.com/images/onecourse/chapters/quant-10/mx-the-limit-order-book/fig-68aaba5fa121.svg)

***Figure 1.1.** A [limit order book](#def-mx-the-limit-order-book-lob) at level 3. Each box is a resting order, its width its size; within a [price level](#def-mx-the-limit-order-book-tick) the oldest order is at the left. The best bid is 100.00 and the best ask 100.01, one tick apart. A new bid at 100.00 joins the back of its level; a market buy consumes the best ask from the front.*

## 1.2 Events: add, cancel, modify, execute

**Definition 1.4 (Order-book event).**

An *order-book event* is one change to the book: an order added at a [price level](#def-mx-the-limit-order-book-tick), reduced or removed by its owner (a cancellation), replaced by a new order, or reduced or removed by an execution against an incoming order. A venue’s market-by-order feed (One Quant Book 1, chapter 19) publishes one message per event, with the order’s reference.

The table maps the events to the messages of Nasdaq’s TotalView-ITCH 5.0 feed, whose layouts the exchange simulator of chapter 26 keeps. Nasdaq’s specification is explicit about the replace: all remaining shares of the original order are removed, and the replacement arrives with a new order reference used from then on, which is how a feed says that the order lost its place.

| event | ITCH message | level 3 | level 2 and level 1 |
| --- | --- | --- | --- |
| add | A (add order) | a new order at the back of its level | the level’s size grows; the best may move |
| partial cancel | X (order cancel) | the order shrinks, keeps its place | the level’s size falls |
| full cancel | D (order delete) | the order leaves | the level may vanish |
| replace | U (order replace) | old order leaves, new one at the back | two levels may change |
| execution | E / C (executed) | the front order shrinks or leaves | the best level shrinks; a trade prints |

Executions are few. In the simulated hour (`firm.tape`, Book 7’s synthetic market, 31 535 messages), 49.7% of messages are adds, 47.8% cancellations and 2.5% executions: 40 messages for each trade. Only 3.8% of the orders that left the book did so by trading; the median order lived 15.5 seconds (24.9 for those that traded, 15.3 for those cancelled), and the best bid price lasted a median of 4.5 seconds before it moved. Real books in liquid stocks run faster and cancel more (chapter 3 sets the simulated facts beside published ones); what matters here is the proportion: the book is mostly orders that will never trade.

## 1.3 Priority and what resets it

A [matching engine](#def-mx-the-limit-order-book-engine) ([Definition 1.5](#def-mx-the-limit-order-book-engine)) ranks resting orders by price, then by a rule within the level; price-time priority, first come first served, is the common rule for equities (One Quant Book 1, chapter 19, gives the pro-rata and top-order alternatives of futures venues). Priority is a property of an order’s *arrival*, and venues must say which changes count as a new arrival. The rules are close across venues:

- **A reduction keeps the place.** A partial cancellation (ITCH X) leaves the order where it was: it takes away only its own shares.
- **An increase or a price change loses it.** CME Globex lists the modifications that change an order’s priority: an increase of quantity, the price, the order type, the stop trigger price, the minimum fill quantity and the account. On Nasdaq a cancel-replace arrives on the feed as an Order Replace with a new reference.
- **A refreshed iceberg slice goes to the back** (chapter 2): showing more of a hidden reserve is an increase.

The reason is fairness to the orders behind: if a size increase kept its place, a trader could stand at the front with one lot and grow it whenever a large order arrived. The consequence for a trader is that a queue position is an asset (chapter 6 prices it) that a careless modification destroys.

**Definition 1.5 (Matching engine).**

A *matching engine* is the venue’s program that holds the [limit order books](#def-mx-the-limit-order-book-lob), applies each incoming message in the order it arrives, executes incoming orders against resting ones by the priority rule, and publishes the resulting events and execution reports.

## 1.4 The book as a data structure

A book has three operations on its hot path: find an order by reference (every cancel and execution names one), find the best price (every aggressive order starts there), and walk a level in priority order (every execution). `firm.lob`, the running project’s reference book, keeps a hash map from reference to order, a map from price to level on each side, and two first-in-first-out queues per level, displayed orders first ([Figure 1.2](#fig-mx-the-limit-order-book-ds)).

![The structures of firm.lob. A cancellation finds its order through the hash map (dashed); an aggressive order finds the best level through the sorted map and walks its queues from the front.](https://one-course.com/images/onecourse/chapters/quant-10/mx-the-limit-order-book/fig-9f17cac614f1.svg)

***Figure 1.2.** The structures of `firm.lob`. A cancellation finds its order through the hash map (dashed); an aggressive order finds the best level through the sorted map and walks its queues from the front.*

```python
    def add(self, o: Order) -> None:
        if o.ref in self.orders:
            raise KeyError(f"duplicate order reference {o.ref}")
        lv = self.levels[o.side].get(o.price)
        if lv is None:
            lv = self.levels[o.side][o.price] = _Level()
            bisect.insort(self._px[o.side], o.price)
        (lv.vis if o.visible else lv.hid).append(o)
        self.orders[o.ref] = o

    def get(self, ref: int) -> Order | None:
        return self.orders.get(ref)

    def remove(self, ref: int) -> Order:
        o = self.orders.pop(ref)
        lv = self.levels[o.side][o.price]
        (lv.vis if o.visible else lv.hid).remove(o)
        if not lv.vis and not lv.hid:
            del self.levels[o.side][o.price]
            px = self._px[o.side]
            del px[bisect.bisect_left(px, o.price)]
        return o

    def reduce(self, ref: int, q: int) -> Order:
        """Take q off the order's executable quantity; remove it when nothing is left."""
        o = self.orders[ref]
        if q > o.qty or q <= 0:
            raise ValueError(f"reduce {q} from {o.qty}")
        o.qty -= q
        if o.qty == 0:
            self.remove(ref)
        return o
```

***Listing 1.1.** The core of `firm.lob`: add, find, remove and reduce. code/firm/lob/firm_lob.py*

**Proposition 1.6 (Costs of the book operations).**

With $L$ non-empty levels on a side and $m$ orders at a level, the structure of [Figure 1.2](#fig-mx-the-limit-order-book-ds) finds an order in $O(1)$ expected time, adds an order in $O(\log L)$ when it creates a level and $O(1)$ otherwise, finds the best price in $O(1)$ (the end of the sorted map), and removes an order in $O(\log L+m)$ worst case. A price-indexed array covering $W$ ticks, with a pointer to the best index, adds and removes in $O(1)$ and moves the best pointer in $O(g)$, where $g$ is the number of empty ticks it crosses.

**Proof.** Hash lookup is expected constant. A sorted map (a balanced tree, or a sorted list with binary search as in the Python reference) inserts a new key in $O(\log L)$. Removal locates the order in its queue, linear in $m$ unless each order keeps a link to its neighbours (an intrusive doubly linked list, the production choice, makes it $O(1)$). In the array, a level is an index computed from the price; after a removal empties the best level, the pointer moves to the next non-empty index, $g$ steps. ∎

Production books for liquid instruments use the array: prices cluster within a few hundred ticks of the best, $g$ is small, and every operation touches memory at a computed address (One Quant Book 13 builds one). `firm.lob` carries both: its `ArrayBook` and its tree-keyed `MessageBook` rebuilt the simulated hour’s book message by message and agreed on all 3 154 level-2 snapshots compared. Its C++20 and Rust twins rebuild a shared five-minute fixture and reproduce every one of its 147 snapshots.

## 1.5 The book as a queueing system

Seen from one order, the best level is a queue in which it waits: orders ahead leave by execution (from the front) or by cancellation (from anywhere), and the order itself may be cancelled before its turn comes. The simplest model of the whole book treats every flow as random.

**Definition 1.7 (Zero-intelligence model).**

A *zero-intelligence model* of a [limit order book](#def-mx-the-limit-order-book-lob) lets [limit orders](#def-mx-the-limit-order-book-orders), [market orders](#def-mx-the-limit-order-book-orders) and cancellations arrive as independent Poisson processes whose rates may depend on the distance from the best prices, with no trader choosing anything; its spread, depth, volatility and fill probabilities follow from the rates alone.

Smith, Farmer, Gillemot and Krishnamurthy (2003) built the model with [limit orders](#def-mx-the-limit-order-book-orders) placed at random over a band of prices, [market orders](#def-mx-the-limit-order-book-orders) and cancellations, and derived by dimensional analysis how the spread, depth, volatility and impact scale with the rates; with all the rates measurable from data, it has no free parameters. Cont, Stoikov and Talreja (2010) wrote the book as a set of birth–death queues (One Quant Book 4, chapter 8) with cancellations at a rate proportional to the queue’s size, fitted it to Tokyo Stock Exchange data and computed, among other conditional probabilities, that of executing an order at the bid before the ask moves. The following result is the building block.

**Proposition 1.8 (Fill probability behind nnn orders).**

An order joins a [price level](#def-mx-the-limit-order-book-tick) behind $n$ orders of one unit each. [Market orders](#def-mx-the-limit-order-book-orders) arrive at rate $\mu$ and each takes one unit from the front; each order ahead is cancelled at rate $\theta$; the order itself is cancelled at rate $\nu$. All clocks are independent and exponential. The probability that it fills before it is cancelled is

$$
P_n=\frac{\mu}{\mu+\nu}\prod_{k=1}^{n}\frac{\mu+k\theta}{\mu+k\theta+\nu},
$$

and, when $\nu=0$, the expected time until it fills is $1/\mu+\sum_{k=1}^{n}1/(\mu+k\theta)$.

**Proof.** With $k\ge1$ orders ahead, the next event is a departure from ahead (rate $\mu+k\theta$) or our cancellation (rate $\nu$); by memorylessness the departure comes first with probability $(\mu+k\theta)/(\mu+k\theta+\nu)$, and the queue then restarts from $k-1$. At the front ($k=0$) the next [market order](#def-mx-the-limit-order-book-orders) fills us with probability $\mu/(\mu+\nu)$. The stages are independent, so the probabilities multiply. With $\nu=0$ the stage durations are exponential with means $1/(\mu+k\theta)$ and $1/\mu$; the expected total is their sum. ∎

```python
def fill_probability(n: int, mu: float, theta: float, nu: float) -> float:
    """Probability that an order behind n unit orders fills before it is cancelled. Market orders arrive at rate mu
    and take one unit from the front; each order ahead cancels at rate theta; ours cancels at rate nu."""
    p = mu / (mu + nu)
    for k in range(1, n + 1):
        p *= (mu + k * theta) / (mu + k * theta + nu)
    return p
```

***Listing 1.2.** The proposition in code. code/microstructure/01-the-limit-order-book/python/mx_lob.py*

The proposition holds in a queue where nobody jumps ahead. In a real book, and in the [zero-intelligence model](#def-mx-the-limit-order-book-zi), someone does: a buyer who places a bid one tick above ours becomes the best bid, and the market sells go to it. [Figure 1.3](#fig-mx-the-limit-order-book-fill) measures the gap. The chapter’s zero-intelligence market (unit orders, [limit orders](#def-mx-the-limit-order-book-orders) at rate 0.5 per price per side over 20 prices, [market orders](#def-mx-the-limit-order-book-orders) at rate 2 per side, cancellations at 0.05 per order) tracks every bid that joins the back of the best bid. With price improvement switched off, its fill rates match the proposition with $\mu=2$, $\theta=\nu=0.05$: behind five orders 0.871 measured against 0.870. With improvement on, as in the original model, they fall to 0.672 behind five and 0.535 behind eight: between a quarter and a third of the fills the proposition promises are taken by orders that arrive later at a better price. Switching improvement off has a price of its own: the spread, 2.55 ticks with it, grows without bound without it, because nothing ever narrows it. Price improvement is what keeps the spread finite and what makes queue position less than a guarantee.

![Left: the probability that an order at the back of the best bid fills before it is cancelled, against the orders ahead of it: the proposition, and the zero-intelligence market with and without price improvement (400 000 events each; beyond eight orders ahead the tracked orders are too few, under a hundred per point). Right: the mean displayed depth at each distance from the best price in the simulated hour of firm.tape, sampled every second; it peaks one tick behind the best. Data: mx_lob.zi_market, mx_lob.depth_profile.](https://one-course.com/images/onecourse/chapters/quant-10/mx-the-limit-order-book/fig-ea4f3b7a503b.svg)

***Figure 1.3.** Left: the probability that an order at the back of the best bid fills before it is cancelled, against the orders ahead of it: the proposition, and the zero-intelligence market with and without price improvement (400 000 events each; beyond eight orders ahead the tracked orders are too few, under a hundred per point). Right: the mean displayed depth at each distance from the best price in the simulated hour of `firm.tape`, sampled every second; it peaks one tick behind the best. Data: `mx_lob.zi_market`, `mx_lob.depth_profile`.*

The right panel of [Figure 1.3](#fig-mx-the-limit-order-book-fill) shows a shape chapter 3 will find in real books: displayed depth is not largest at the best price but one tick behind it, because the best level is where executions and the most cancellations happen.

## 1.6 Tutorial: rebuild a book and time its queue

**Goal.** Rebuild the simulated hour’s book in two structures, measure its event mix and its queues, and test the fill-probability proposition in a zero-intelligence market. **End state:** the numbers of section 2, the two structures agreeing, and [Figure 1.3](#fig-mx-the-limit-order-book-fill).

1. **Rebuild.** `mx_lob.tree_vs_array(session())` replays 31 535 messages into a `MessageBook` and an `ArrayBook` and compares their ten best levels every tenth message: 3 154 comparisons, no mismatch.
2. **Measure.** `event_mix` , `best_survival` and `joiners` give the shares of adds, cancels and executions, the lives of orders, how long a best price lasts and what becomes of orders that join the best queue.
3. **Queue.** Evaluate `fill_probability` and check it against `queue_mc` ; run `zi_market(improve=False)` and `zi_market(improve=True)` ; draw the figure with `fig_lob.py` .
4. **Twins.** Run `make_lob_fixture.py` ; build `cpp/firm_lob_test.cpp` and `cargo test` in `rust/` : both reproduce the Python book’s 147 snapshots.

**What to change next.** Give the zero-intelligence market’s orders sizes drawn from a geometric law and see how far the proposition, counted in orders, drifts from the fill rate; halve the cancellation rate and watch the spread and the depth at the best.

## 1.7 Build: the reference order book

**Purpose.** The book every later component of the firm stores orders in: the exchange simulator’s engine (chapter 26), the participants’ own views of the market, and the tests of Book 13’s production books.

**Interface.** `Order(ref, side, price, qty, visible, seq, owner)`; `LimitOrderBook`: `add`, `remove`, `reduce`, `get`, `best`, `best_visible`, `prices`, `level_orders`, `top`, `depth`, `check`; `MessageBook.apply(kind, ref, side, price, qty, new_ref)` for A, X, D, E, C and U; `ArrayBook(lo, hi, tick)`; C++20 `firm::lob::MessageBook` and Rust `firm_lob::MessageBook` with the same `l2_lines`.

**Rules.** Displayed before hidden, then time, at each price; a reduction keeps the place; a replace arrives under a new reference at the back; the book stores and never matches; `check()` verifies that every order sits in exactly its level.

**Acceptance tests.** `code/firm/lob/tests/`: priority by hand; the two Python structures agreeing on a simulated session; the replace; the fixture’s 147 level-2 snapshots in C++20 and Rust.

**Stretch.** An intrusive linked list per level for $O(1)$ removal; an array book that recentres when the price leaves its band.

Sources and further reading

- M. D. Gould, M. A. Porter, S. Williams, M. McDonald, D. J. Fenn and S. D. Howison, “Limit order books”, *Quantitative Finance* 13(11), 2013.
- E. Smith, J. D. Farmer, L. Gillemot and S. Krishnamurthy, “Statistical theory of the continuous double auction”, *Quantitative Finance* 3(6), 2003.
- R. Cont, S. Stoikov and R. Talreja, “A stochastic model for order book dynamics”, *Operations Research* 58(3), 2010.
- Nasdaq, *TotalView-ITCH 5.0* specification; CME Group, client systems documentation, “Order functionalities”.

## 1.8 Exercises

**Exercise 1.1 ★.**

The best bid is 100.00 with 700 shares in three orders of 300, 200 and 200; the best ask is 100.01. A market sell of 450 shares arrives. What trades, and what is the new level 1?

**Solution of Exercise 1.1.**

The sell executes against the level in time order: 300 shares against the first order and 150 against the second. The best bid stays 100.00 with $50+200=250$ shares in two orders; the best ask is unchanged at 100.01.

**Exercise 1.2 ★.**

An order joins behind three unit orders; [market orders](#def-mx-the-limit-order-book-orders) arrive at rate 1 per second, each order ahead cancels at 0.1 per second, and the order’s owner cancels it at 0.2 per second. What is its fill probability?

**Solution of Exercise 1.2.**

$P_3=\tfrac{1}{1.2}\cdot\tfrac{1.1}{1.3}\cdot\tfrac{1.2}{1.4}\cdot\tfrac{1.3}{1.5}=0.524$.

**Exercise 1.3 ★.**

A trader first reduces an order from 500 to 300 shares, then raises it back to 500. What happens to its queue position at each step on CME Globex, and how does each step appear in an ITCH feed?

**Solution of Exercise 1.3.**

The reduction keeps the order’s place (an X message of 200 shares on an ITCH-style feed); the increase changes its priority on CME Globex, which puts it behind every order at its price. On Nasdaq the increase is a cancel-replace: an Order Replace message removes the old reference and adds a new one at the back.

**Exercise 1.4 ★★.**

A price-indexed array covers the prices within 1% of 100.00 for a stock with a one-cent tick. How many slots does it need, and what happens on a day the stock moves 3%?

**Solution of Exercise 1.4.**

From 99.00 to 101.00 in cents: $2\times100+1=201$ slots. A 3% move takes the best price out of the band: the book must recentre (rebuild the array around the new price) or keep the orders outside the band in an overflow map, and the recentring is a latency spike exactly when the market moves.

**Exercise 1.5 ★★.**

With no cancellation of its own, an order waits behind ten unit orders; [market orders](#def-mx-the-limit-order-book-orders) arrive at 0.5 per second and each order ahead cancels at 0.02 per second. What is its expected wait?

**Solution of Exercise 1.5.**

$1/0.5+\sum_{k=1}^{10}1/(0.5+0.02k)=2+16.54=18.5$ seconds.

**Exercise 1.6 ★★.**

Why is displayed depth in [Figure 1.3](#fig-mx-the-limit-order-book-fill) larger one tick behind the best than at the best?

**Solution of Exercise 1.6.**

The best level is where every execution happens and where stale orders are pulled first when the price moves through it; one tick behind, orders accumulate out of reach of small [market orders](#def-mx-the-limit-order-book-orders) and are replenished by the orders that arrive there, so they pile up. The shape is the hump chapter 3 finds in real books.

**Exercise 1.7 ★★★.**

*Coding.* Rerun `zi_market` with [market orders](#def-mx-the-limit-order-book-orders) at rate 1 instead of 2. What happens to the spread, and to the gap between the proposition and the measured fill probability behind five orders? Explain both.

**Solution of Exercise 1.7.**

With [market orders](#def-mx-the-limit-order-book-orders) at rate 1 the spread falls from 2.55 to 1.64 ticks and the best level holds 3.29 orders instead of 2.72: [market orders](#def-mx-the-limit-order-book-orders) empty the best level half as often. Behind five orders the fill probability is 0.602 against the proposition’s 0.769, a loss of 22% (23% at rate 2): waits are twice as long, which gives later orders more time to improve the price, but a narrower spread leaves fewer prices to improve into, and the two effects nearly offset.

**Exercise 1.8 ★★★.**

*Find the flaw.* “Our order has been at the front of the best bid for ten seconds, so by the proposition it will fill with probability $\mu/(\mu+\nu)$ whatever happens next.”

**Solution of Exercise 1.8.**

The factor $\mu/(\mu+\nu)$ assumes nobody can take the order’s place at the front. Any bid placed above it becomes the best and takes the market sells first; the level may stop being the best, and the order then waits indefinitely. Ten seconds at the front also says something about the rates: in a quiet market $\mu$ is lower than its average.

## 1.9 Problem: The Line at the Best Bid

**Problem 1.1.**

Weekend problem — the line at the best bid

A desk asks how long its passive orders wait and how many of them trade. You have the simulated hour of `firm.tape` and the chapter’s zero-intelligence market.

**Part I — The stream.**

1. How many messages does the hour hold, and in what proportions of adds, cancels and executions?
2. How many messages are there per trade, and what share of orders leave the book by trading?
3. How long does the median order live, and does an order that trades live longer than one that is cancelled?
4. How long does a best bid price last, in the median?

**Part II — The queue at the best.**

5. How many orders join the back of the best bid or ask, and how many shares do they find ahead?
6. What share of them ever trade, and what share fill in full?
7. Where does mean displayed depth peak, and why there?
8. Which of these numbers would change if cancellations were slower?

**Part III — The model.**

9. State the fill-probability proposition and its assumptions.
10. Compute $P_1$ , $P_5$ and $P_{12}$ for $\mu=2$ , $\theta=\nu=0.05$ .
11. Check $P_5$ by simulation of the stylised queue.
12. What is the expected wait behind five orders with $\nu=0$ ?

**Part IV — The market.**

13. What fill rates does the zero-intelligence market give without price improvement, and why do they match the proposition?
14. What does it give with improvement, behind one, five and eight orders?
15. State the *named result* : the fill probability of an order at the back of the best bid against the orders ahead, and the share of it that price improvement takes away.
16. Why does the market without improvement have an unbounded spread?
17. What is the zero-intelligence market’s spread and mean best-level depth with improvement?
18. Which assumption of the proposition fails most in a real book, and in which direction does it bias the answer?
19. What would you measure in real data to estimate $\mu$ , $\theta$ and $\nu$ ?
20. In one sentence: what is a queue position worth, before chapter 6 prices it?

**Solution of Problem 1.1.**

**1.** 31 535 messages: 49.7% adds, 47.8% cancellations, 2.5% executions. **2.** 40 messages per trade; 3.8% of the orders that left the book did so by trading. **3.** 15.5 seconds in the median; 24.9 for orders that traded, 15.3 for those cancelled: trading takes longer than giving up. **4.** 4.5 seconds for the best bid (4.8 for the best ask). **5.** 2 834 orders, with a median of 1 400 shares ahead. **6.** 13% trade at least in part, 10% in full. **7.** One tick behind the best (1 508 shares on the bid side against 1 366 at the best): the best level is emptied by executions and stale cancellations, the next one is not. **8.** Order lives and the share of orders that trade would rise; queues ahead would be longer and depth larger; messages per trade would fall. **9.** Unit orders; [market orders](#def-mx-the-limit-order-book-orders) at rate $\mu$ from the front; cancellations at $\theta$ per order ahead and $\nu$ for ours; independent exponential clocks; nobody jumps ahead. Then $P_n=\tfrac{\mu}{\mu+\nu}\prod_{k=1}^{n}\tfrac{\mu+k\theta}{\mu+k\theta+\nu}$. **10.** 0.952, 0.870 and 0.755. **11.** `queue_mc(5, 2, 0.05, 0.05)` with 20 000 paths agrees to within 0.01 (0.869). **12.** 2.83 seconds. **13.** 0.953 behind one, 0.871 behind five: the best bid queue then behaves exactly as the model assumes, because nobody can place a bid above it. **14.** 0.912, 0.672 and 0.535. **15.** *Named result*: the fill probability behind $n$ orders falls from 0.95 ($n=1$) to 0.76 ($n=12$) in the proposition; in the zero-intelligence market with price improvement it falls from 0.91 to 0.54 behind eight, and improvement takes away 23% of the promised fills behind five and 35% behind eight. **16.** Only [market orders](#def-mx-the-limit-order-book-orders) and cancellations remove orders from the best levels, and nothing is ever placed inside the spread, so each side’s best price only moves away. **17.** 2.55 ticks and 2.72 orders. **18.** That nobody gets ahead (price improvement), together with constant rates: both bias the proposition upwards; in a real book, flow at the best also clusters in time (One Quant Book 4, chapter 7). **19.** $\mu$ from the executions at the best per unit time, $\theta$ from cancellations at the best divided by the time-integrated queue size, $\nu$ from one’s own order lifetimes; all conditional on the queue’s state. **20.** The probability, and the time, of filling before the price moves: the front of a long queue is worth a fill; the back of it, a lottery.

## 1.10 Interview questions

**Interview question 1.1 ★ developer.**

Design the data structures of a [limit order book](#def-mx-the-limit-order-book-lob). What are the costs of add, cancel, execute and best-price lookup?

**Solution of Interview question 1.1.**

A hash map from order reference to order (cancels and executions name it), a sorted map or price-indexed array from price to level, and a FIFO list per level. Cancel and execute: $O(1)$ with an intrusive list; add: $O(1)$, or $O(\log L)$ when a tree gets a new level; best price: $O(1)$ with a cached pointer.

*What the interviewer is looking for: the three access paths, the hash map for references, why arrays win when prices cluster.*

**Interview question 1.2 ★ trader, researcher.**

Why does increasing an order’s size lose its queue position, while decreasing it does not?

**Solution of Interview question 1.2.**

A decrease only removes the order’s own shares, which harms nobody behind it; an increase would let a trader hold the front with a small order and enlarge it when a big counterparty appears, jumping everyone who waited.

*What the interviewer is looking for: fairness to the orders behind, and the gaming a size increase would allow.*

**Interview question 1.3 ★★ researcher.**

You are fifth in a queue. [Market orders](#def-mx-the-limit-order-book-orders) arrive at rate $\mu$, orders ahead cancel at rate $\theta$ each. What is the probability you fill before you cancel at rate $\nu$?

**Solution of Interview question 1.3.**

With four ahead: $P=\tfrac{\mu}{\mu+\nu}\prod_{k=1}^{4}\tfrac{\mu+k\theta}{\mu+k\theta+\nu}$, from competing exponential clocks and memorylessness.

*What the interviewer is looking for: the stage decomposition and the independence of stages; a remark that price improvement lowers it.*

**Interview question 1.4 ★★ developer.**

A price-indexed array book is fast. When does it fail, and what do you do about it?

**Solution of Interview question 1.4.**

When the price leaves the band the array covers (a fast market, a halt reopening far away), or for instruments with huge price ranges and sparse books. Recentre the array, keep an overflow map for far orders, and size the band from the instrument’s volatility.

*What the interviewer is looking for: memory against range, and the latency spike of recentring at the worst moment.*

**Interview question 1.5 ★★ researcher, trader.**

Most orders in a modern book are cancelled. Is that a problem for the market?

**Solution of Interview question 1.5.**

Not in itself: cancellations are how liquidity providers update quotes when information arrives, and the displayed book stays current. It costs message capacity and makes displayed depth less firm (chapter 18’s quote fade); regulators watch it through order-to-trade ratios (chapter 24).

*What the interviewer is looking for: a two-sided answer: stale quotes are worse, but fleeting liquidity misleads.*

**Interview question 1.6 ★★★ researcher.**

What does a [zero-intelligence model](#def-mx-the-limit-order-book-zi) of the order book get right, and what does it get wrong?

**Solution of Interview question 1.6.**

Right: the order of magnitude of the spread and its scaling with the order-flow rates, the shape of depth near the best, why most orders do not trade. Wrong: order flow is not independent (signs of trades have long memory, chapter 12), rates react to the state and to information, and prices have no anchor to value.

*What the interviewer is looking for: it is a null model: a benchmark for what needs no intelligence to explain.*
