Objective
"Implement an order book" is the most common quant developer design question. The Order Books, Bids, Asks and Spreads lesson covers what a book means to a trader, and Heaps, Hash Maps & Order Books lists the textbook complexities. This lesson goes one level down: which concrete structures you would write, what each operation touches, where the hidden costs are, and a working C++ implementation with tests that you can extend in the next lesson into a matching engine.
What the book must do, and how often
A book for one instrument serves four operations:
| Operation | Frequency | What it needs |
|---|---|---|
| Add a resting order | very high | find or create the price level; append to its queue |
| Cancel (or reduce) an order | highest: most orders are cancelled, not filled | find the order by id; unlink it |
| Execute against the front of the best level | high | the best level, and its oldest order |
| Query best bid / ask, size at a price | every event | the best price on each side; a cached total per level |
Cancels dominate traffic in modern electronic markets, so a design that makes cancels slow is wrong however elegant the rest is.
Prices are integers
Store prices as an integer number of ticks (100.03 with a 0.01 tick is 10003) and quantities as integers. Floating-point prices make equality, hashing and map keys unreliable: 0.1 + 0.2 is not 0.3 in binary floating point, and two orders at "the same" price could land on different levels. Convert to and from decimals only at the edges (feed decoding, display).
Three ways to hold the price levels
| Design | Add at new level | Remove empty level | Best price | Notes |
|---|---|---|---|---|
Sorted map (std::map, a red-black tree) | via begin() | Simple, no price bounds; a pointer chase per tree node | ||
| Array indexed by tick, plus best pointers | , then rescan for the next best | Fastest in practice; needs a bounded price range | ||
| Binary heap of prices | to find an arbitrary price | Poor fit: removing a non-top level is a search; lazy deletion leaves garbage |
Here is the number of non-empty levels. In practice most activity is within a few ticks of the touch, so near the action is small and both the map and the array work; the array wins on constant factors because a price converts straight to a memory address with no comparisons.
The array's one weakness: when the best level empties, you must find the next non-empty level. A linear scan costs the gap in ticks, usually one or two. To bound the worst case, keep a bitset of non-empty levels and jump with a count-leading-zeros instruction (std::countl_zero), 64 levels per word.
Inside a level: FIFO plus a cached total
Each level holds a FIFO queue of orders (time priority) and the sum of their quantities, so "size at price" never walks the queue. The queue must support three things in : append at the back, pop at the front, and unlink from the middle when an order is cancelled. A doubly linked list does all three. std::list is correct and is what the code below uses. Production books use an intrusive list (the prev/next pointers live inside the order object) with orders allocated from a pre-sized pool, which removes a heap allocation per order and keeps memory compact.
The order index
A hash map from order id to the order's list node makes cancel and modify : look up the node, subtract its quantity from the level total, unlink it. Without it a cancel would scan every queue. std::list iterators stay valid when other elements are inserted or erased, which is exactly the property the index relies on.
Modify semantics
Exchanges commonly apply this rule:
- Reduce quantity at the same price: keep queue position (update in place).
- Increase quantity or change price: lose priority; it is a cancel followed by a new add at the back of the queue.
Otherwise a trader could join a queue with 1 share and later inflate it to 10,000 while keeping a front position. Check the venue's rules in an interview answer, but state this default.
Implementation
This version rests passive orders only (matching comes in the next lesson). Prices are ticks in a fixed band; each side is a std::vector<Level>; the best bid and ask are cached and repaired only when the best level empties.
#include <cassert>
#include <cstdint>
#include <cstdio>
#include <list>
#include <unordered_map>
#include <vector>
enum class Side { Buy, Sell };
struct Order {
uint64_t id;
Side side;
int32_t tick; // price in ticks
int64_t qty; // remaining quantity
};
struct Level {
std::list<Order> queue; // FIFO: front = oldest
int64_t total = 0; // sum of qty at this level
};
class OrderBook {
public:
OrderBook(int32_t min_tick, int32_t max_tick)
: min_(min_tick), bids_(max_tick - min_tick + 1),
asks_(max_tick - min_tick + 1) {}
// Rests a passive order (no matching here). Returns false on a duplicate id.
bool add(uint64_t id, Side side, int32_t tick, int64_t qty) {
if (index_.count(id) || qty <= 0) return false;
Level& lvl = level(side, tick);
lvl.queue.push_back({id, side, tick, qty});
lvl.total += qty;
index_.emplace(id, std::prev(lvl.queue.end()));
if (side == Side::Buy && (best_bid_ < 0 || tick > best_bid_)) best_bid_ = tick;
if (side == Side::Sell && (best_ask_ < 0 || tick < best_ask_)) best_ask_ = tick;
return true;
}
// O(1): hash lookup, then unlink the list node. Returns false if unknown.
bool cancel(uint64_t id) {
auto it = index_.find(id);
if (it == index_.end()) return false;
auto node = it->second;
Level& lvl = level(node->side, node->tick);
lvl.total -= node->qty;
Side side = node->side;
int32_t tick = node->tick;
lvl.queue.erase(node);
index_.erase(it);
if (lvl.queue.empty()) fix_best(side, tick);
return true;
}
int32_t best_bid() const { return best_bid_; } // -1 if empty
int32_t best_ask() const { return best_ask_; }
int64_t size_at(Side s, int32_t tick) { return level(s, tick).total; }
private:
Level& level(Side s, int32_t tick) {
return (s == Side::Buy ? bids_ : asks_)[tick - min_];
}
// Only called when the level at this tick became empty.
void fix_best(Side s, int32_t tick) {
if (s == Side::Buy && tick == best_bid_) {
int32_t t = tick - 1;
while (t >= min_ && bids_[t - min_].queue.empty()) --t;
best_bid_ = t >= min_ ? t : -1;
} else if (s == Side::Sell && tick == best_ask_) {
int32_t t = tick + 1, max = min_ + (int32_t)asks_.size() - 1;
while (t <= max && asks_[t - min_].queue.empty()) ++t;
best_ask_ = t <= max ? t : -1;
}
}
int32_t min_;
std::vector<Level> bids_, asks_;
std::unordered_map<uint64_t, std::list<Order>::iterator> index_;
int32_t best_bid_ = -1, best_ask_ = -1;
};
int main() {
OrderBook book(9900, 10100); // ticks of 0.01 around 100.00
book.add(1, Side::Buy, 10000, 400);
book.add(2, Side::Buy, 9999, 600);
book.add(3, Side::Buy, 10000, 100);
book.add(4, Side::Sell, 10002, 300);
book.add(5, Side::Sell, 10003, 500);
std::printf("best %d / %d, bid size %lld\n", book.best_bid(), book.best_ask(),
(long long)book.size_at(Side::Buy, 10000));
assert(!book.add(1, Side::Buy, 9998, 10)); // duplicate id rejected
assert(book.cancel(1)); // front of the 100.00 queue
std::printf("after cancel 1: bid size %lld\n",
(long long)book.size_at(Side::Buy, 10000));
assert(book.cancel(3)); // level 100.00 now empty
std::printf("after cancel 3: best bid %d\n", book.best_bid());
assert(!book.cancel(3)); // second cancel is a no-op
assert(book.cancel(4));
std::printf("after cancel 4: best ask %d\n", book.best_ask());
assert(book.cancel(2) && book.best_bid() == -1);
std::printf("all tests passed\n");
}
Compiled with c++ -std=c++20 -O2 and run:
best 10000 / 10002, bid size 500
after cancel 1: bid size 100
after cancel 3: best bid 9999
after cancel 4: best ask 10003
all tests passed
The tests cover the cases interviewers probe: two orders at one level aggregate (400 + 100 = 500), a cancel from the front of a queue leaves the rest intact, emptying the best level moves the best price, a duplicate id is rejected, and a second cancel of the same id is a harmless no-op (cancels for unknown ids are routine, because an order can fill while its cancel is in flight).
Worked example
tracing the data structures
Using the class above, start from an empty book and apply: add #1 buy 400 @ 10000, add #2 buy 600 @ 9999, add #3 buy 100 @ 10000, cancel #1, cancel #3. After each step, state the queue at tick 10000, the cached total there, the best bid, and the cost of the step.
Show solutionHide solution
- Add #1: the level for 10000 is
bids_[10000 - 9900]=bids_[100], found by subtraction, . Queue: [#1(400)], total 400. Best bid was empty, so it becomes 10000. - Add #2 at 9999: a different array slot. 9999 < 10000, so the best bid is unchanged. .
- Add #3: appended behind #1. Queue: [#1(400), #3(100)], total 500. This is the "bid size 500" line in the output.
- Cancel #1: hash lookup gives the list iterator; subtract 400 (total 100); erase the node. The level is not empty, so the best bid stays 10000. , and #3 is now at the front.
- Cancel #3: total 0, the queue is empty and 10000 was the best bid, so
fix_bestscans down: 9999 is non-empty after one step. Best bid 9999. Cost: one step per empty tick skipped.
Every operation was constant time except the rescan, whose cost is the distance to the next populated tick. That is the right trade: rescans happen only when the touch is cleared, and the distance is usually one tick.
Worked example
sizing the tick array
A stock trades near 100.00 with a 0.01 tick, and the venue rejects orders more than 10% from a reference price. How many levels does each side's array need, how many 64-bit words does a non-empty-level bitset take, and what is the worst-case cost of finding the next best bid?
Show solutionHide solution
The band is 90.00 to 110.00 inclusive: ticks per side.
The bitset needs words ( is too few). Finding the next non-empty bid below a tick means masking the current word and, if it is zero, moving to lower words: at most 32 word reads, each followed by one countl_zero. Without the bitset the worst case is 2,000 level checks, which is why the bitset matters when the book is sparse (illiquid names, or right after a large trade sweeps several levels).
If prices can move outside a fixed band (an all-day session in a volatile name), either re-centre the array when the price drifts or fall back to a sorted map for levels far from the touch. Saying this out loud shows you know the array's assumption.
Knowledge check
Why does a production order book keep a hash map from order id to the order's position in its level queue?
Knowledge check
An order resting second in the queue at 100.00 is modified from 500 to 300 shares at the same price. Under the usual exchange rule, where is it afterwards?
Knowledge check
Why is a binary heap of price levels a poor choice for an order book?
How to answer the interview question
- Clarify: one instrument or many, price-time or pro-rata, bounded tick range, message rates, single-threaded?
- State the operations and their frequencies, and say cancels dominate.
- Propose the three structures: levels (tick array or sorted map), a FIFO per level with a cached total, and an id → node hash map. Give each operation's complexity.
- Mention the details that separate candidates: integer prices, intrusive lists and a memory pool (no allocation on the hot path), bitset for the next best level, modify semantics, cancels for unknown ids.
- Write add and cancel, then test the edge cases (empty level, empty side, duplicate id, double cancel).
Key takeaways
- Prices are integer ticks; never key a book by floating-point prices.
- Levels: a tick-indexed array is fastest when prices are bounded; a sorted map is simpler and unbounded; a heap is a poor fit.
- Each level is a FIFO (doubly linked list) plus a cached total; an id → node hash map makes cancels .
- Repair the best price only when the best level empties; a bitset bounds the rescan.
- Reducing quantity keeps priority; increasing it or changing price does not.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).