Optimizing a Limit Order Book for HFT
The Order Book is the heart of an exchange or trading system. It must support Insert, Cancel, and Execute operations with predictable, constant-time latency.
The Goal: O(1) Everything
| Operation | Frequency | Target Latency |
|---|---|---|
| Add Order | High | < 100ns |
| Cancel Order | Very High (90% of traffic) | < 50ns |
| Execute (Match) | Low | < 200ns |
Why std::map Fails
A std::map<Price, Level> is usually implemented as a Red-Black Tree.
Cons: $O(\log N)$ inserts/deletes. Worst of all: Pointer Chasing. Each node is allocated separately on the heap, destroying CPU cache locality.
The Standard HFT Pattern: Array + Linked List
1. Price Levels as Array: If ticks are dense (e.g. Eurodollar Futures), use a flat array indexed by price. $O(1)$ access.
2. Orders as Doubly Linked List: Each Price Level contains a linked list of orders.
3. Order Map: A hash map (std::unordered_map or custom open-addressing map) mapping OrderID → (Price, OrderNode*).
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
Memory Pools (Arena Allocation)
new and delete are system calls (expensive!). They also fragment memory.
Pre-allocate a giant array of Order objects at startup. When you need a new order, just increment an index. When you free it, add it to a "free list". This keeps all orders contiguous in memory, maximizing cache hits.