Objective
Implement the matching step that turns an incoming order into trades and book updates, get every order type's edge cases right, and explain why exchanges build matching engines as deterministic state machines fed by a single sequenced stream.
Where the engine sits
At an exchange, gateways receive orders over many connections. A sequencer puts all of them for an instrument (or a partition of instruments) into one total order and stamps each with a sequence number. The matching engine then processes that stream one message at a time and emits, for each input: an acknowledgement or rejection, zero or more trades, and the resulting book changes, which become the public market-data feed.
The matching loop
For an incoming buy (sells are symmetric):
- While quantity remains and the best ask crosses (ask price the buy's limit, or any price for a market order):
- Fill against the oldest order at that level: . Emit a trade at the resting order's price.
- Remove resting orders that reach zero; remove the level when its queue empties; move to the next level.
- When the loop stops, handle the remainder according to the order type.
The trade price rule matters: the resting order set the price, so an aggressive buy limited at 103 that meets an ask at 101 trades at 101. The aggressor receives the price improvement.
Order types: what happens to the remainder
| Type | Matches | Remainder | Edge case |
|---|---|---|---|
| Limit (day or good-till-cancelled) | up to its limit | rests in the book at its limit | a marketable limit trades first, then rests |
| Market | at any price | cancelled, never rests | can sweep a thin book; venues add protection collars |
| Immediate-or-cancel (IOC) | up to its limit | cancelled | partial fills allowed |
| Fill-or-kill (FOK) | up to its limit, all or nothing | the whole order is killed if it cannot fill completely | needs a check before any fill |
| Post-only (common add-on) | never | rests, or is rejected if it would cross | guarantees a maker fee/rebate |
FOK is the one that trips people up: you cannot start filling and then discover there is not enough. Either sum the crossing quantity first (as below) or match on a scratch copy and commit only on success. Exchanges also apply self-trade prevention (an order may not trade with another from the same firm or account) and price bands, which are extra checks inside the same loop.
Determinism
Given the same initial state and the same sequenced input, the engine must produce byte-for-byte the same output. That property enables:
- Hot standby: a backup engine consumes the same sequenced stream and holds an identical book, so failover loses nothing.
- Replay: reproduce any incident exactly from the input log.
- Fairness and audit: outcomes depend only on sequence, which the exchange can prove.
What breaks determinism: reading the wall clock inside matching (time must come from the sequencer's stamp), iterating an unordered hash map to produce output, multiple threads touching one book, floating-point arithmetic whose result depends on evaluation order, and uninitialised memory. The standard design is therefore single-threaded per book, with parallelism across instruments (partitions) rather than within one.
A small engine you can run
This version uses the other level design from the previous lesson, a std::map per side (bids sorted descending), with a std::deque FIFO at each price. Each submission gets a sequence number and the engine prints every fill.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <deque>
#include <functional>
#include <map>
#include <string>
enum class Side { Buy, Sell };
enum class Type { Limit, Market, IOC, FOK };
struct Resting { std::string id; int64_t qty; };
class Engine {
public:
void submit(const std::string& id, Side side, Type type, int64_t px, int64_t qty) {
std::printf("[%llu] %s %s %s %lld @ %s\n", (unsigned long long)++seq_, id.c_str(),
side == Side::Buy ? "BUY" : "SELL", name(type), (long long)qty,
type == Type::Market ? "MKT" : std::to_string(px).c_str());
if (type == Type::FOK && available(side, px) < qty) {
std::printf(" killed: only %lld available\n", (long long)available(side, px));
return;
}
int64_t left = side == Side::Buy ? match(asks_, id, type, px, qty, true)
: match(bids_, id, type, px, qty, false);
if (left == 0) return;
if (type == Type::Limit) {
if (side == Side::Buy) bids_[px].push_back({id, left});
else asks_[px].push_back({id, left});
std::printf(" rests %lld @ %lld\n", (long long)left, (long long)px);
} else {
std::printf(" cancels unfilled %lld\n", (long long)left);
}
}
void print_book() const {
for (auto it = asks_.rbegin(); it != asks_.rend(); ++it) print_level("ask", it->first, it->second);
for (const auto& [px, q] : bids_) print_level("bid", px, q);
}
std::map<int64_t, std::deque<Resting>, std::greater<>> bids_; // best (highest) first
std::map<int64_t, std::deque<Resting>> asks_; // best (lowest) first
private:
template <class Book>
int64_t match(Book& book, const std::string& id, Type type, int64_t px, int64_t qty, bool buy) {
while (qty > 0 && !book.empty()) {
auto lvl = book.begin();
bool crosses = type == Type::Market || (buy ? lvl->first <= px : lvl->first >= px);
if (!crosses) break;
auto& queue = lvl->second;
while (qty > 0 && !queue.empty()) {
Resting& r = queue.front();
int64_t fill = std::min(qty, r.qty);
std::printf(" fill %lld @ %lld (%s vs %s)\n", (long long)fill,
(long long)lvl->first, id.c_str(), r.id.c_str());
qty -= fill;
r.qty -= fill;
if (r.qty == 0) queue.pop_front();
}
if (queue.empty()) book.erase(lvl);
}
return qty;
}
int64_t available(Side side, int64_t px) const {
int64_t total = 0;
auto add = [&](const auto& book, auto crosses) {
for (const auto& [p, q] : book) {
if (!crosses(p)) break;
for (const auto& r : q) total += r.qty;
}
};
if (side == Side::Buy) add(asks_, [&](int64_t p) { return p <= px; });
else add(bids_, [&](int64_t p) { return p >= px; });
return total;
}
static void print_level(const char* s, int64_t px, const std::deque<Resting>& q) {
std::printf(" %s %lld:", s, (long long)px);
for (const auto& r : q) std::printf(" %s(%lld)", r.id.c_str(), (long long)r.qty);
std::printf("\n");
}
static const char* name(Type t) {
return t == Type::Limit ? "LIMIT" : t == Type::Market ? "MARKET" : t == Type::IOC ? "IOC" : "FOK";
}
uint64_t seq_ = 0;
};
int main() {
Engine e;
e.asks_[101] = {{"S1", 200}, {"S2", 300}};
e.asks_[102] = {{"S3", 400}};
e.asks_[104] = {{"S4", 500}};
e.bids_[99] = {{"B1", 300}};
e.bids_[98] = {{"B2", 200}};
e.submit("F", Side::Buy, Type::FOK, 102, 1000);
e.submit("L", Side::Buy, Type::Limit, 101, 600);
e.submit("I", Side::Sell, Type::IOC, 99, 450);
e.submit("M", Side::Buy, Type::Market, 0, 700);
std::printf("final book:\n");
e.print_book();
}
Output (c++ -std=c++20 -O2):
[1] F BUY FOK 1000 @ 102
killed: only 900 available
[2] L BUY LIMIT 600 @ 101
fill 200 @ 101 (L vs S1)
fill 300 @ 101 (L vs S2)
rests 100 @ 101
[3] I SELL IOC 450 @ 99
fill 100 @ 101 (I vs L)
fill 300 @ 99 (I vs B1)
cancels unfilled 50
[4] M BUY MARKET 700 @ MKT
fill 400 @ 102 (M vs S3)
fill 300 @ 104 (M vs S4)
final book:
ask 104: S4(200)
bid 98: B2(200)
Worked example
reading the run
Initial book: asks S1 200 and S2 300 at 101, S3 400 at 102, S4 500 at 104; bids B1 300 at 99, B2 200 at 98. Explain each of the four results above.
Show solutionHide solution
- FOK buy 1000 @ 102. Crossing quantity at or below 102 is . FOK must fill entirely, so it is killed and the book is untouched. (An IOC with the same parameters would have bought 900.)
- Limit buy 600 @ 101. Fills S1 for 200 then S2 for 300 at 101 (time priority within the level). Level 101 empties; the next ask, 102, does not cross 101, so 100 remains and rests as a bid at 101. The spread is now 101 / 102.
- IOC sell 450 @ 99. The best bid is now L's own 100 at 101, which crosses and fills first: the new bid has price priority over B1. Then B1's 300 at 99. That is 400; the next bid, 98, is below the limit, so the remaining 50 is cancelled. Note the seller got 101 for the first 100, better than its limit.
- Market buy 700. No limit: S3 400 at 102, then 300 of S4's 500 at 104. Average price .
Final book: S4 200 at 104 against B2 200 at 98. Every trade printed at the resting order's price.
Worked example
what would break determinism?
A colleague proposes two speed-ups: (a) match each instrument on its own thread; (b) inside one book, use two threads, one for the bid side and one for the ask side. Which preserves deterministic output, and why?
Show solutionHide solution
(a) preserves it, provided each instrument's input is still a single sequenced stream and the outputs are tagged with that stream's sequence numbers. Books for different instruments share no state, so the order in which the threads run cannot change any book's result.
(b) does not. An incoming buy reads the asks and may then rest on the bids; an incoming sell does the reverse. With two threads, whether a sell sees a just-rested bid depends on thread timing, so the same input can produce different trades. Within one book, every message must see the state left by the previous one: that is a strictly serial computation.
Knowledge check
Asks: 200 @ 100, 250 @ 101, 400 @ 102. A FOK buy for 500 limited at 101 arrives. What happens?
Knowledge check
The best ask is a resting sell at 100.50. An incoming buy limit at 100.60 for less than the ask size arrives. At what price does it trade?
Knowledge check
Which of these inside a matching engine is most likely to make replaying the same input log produce different trades?
Key takeaways
- Match from the best opposite level, oldest order first; each fill is of the two remaining quantities and prints at the resting price.
- The order type decides the remainder: limit rests, market and IOC cancel it, FOK checks the total first and kills the whole order if it cannot fill.
- A marketable limit can trade and then rest; its rested remainder has price priority over worse bids.
- Engines are single-threaded per book and driven by one sequenced input stream, so output is deterministic: this makes hot standby and exact replay possible.
- Time, ordering and arithmetic inside the engine must come only from the input (no wall clock, no hash-map iteration order, no floats).
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).