Skip to content
C++ project #25Advanced

Order Matching Engine

A limit order book with price-time priority: limit and market orders, partial fills, cancellation, reductions, depth display and VWAP — an educational exchange simulation.

Estimated time
~8 hours to build
Files
7 files · 484 lines
Technologies
C++17, <map>, <list>, <unordered_map>, <functional>, Header/source split

Introduction

Every stock exchange is built around an order book that matches buyers with sellers. The rules are simple but strict: the best price trades first and, at the same price, the earliest order trades first. Implementing them efficiently is a great lesson in choosing containers: sorted maps for price levels, linked lists for queues and a hash index for cancellation. (This is a simulation for learning; it does not connect to any market.)

Problem statement

Implement an order book that accepts buy and sell limit orders (price in cents) and market orders. Incoming orders trade against the opposite side at the resting order's price while prices cross, by price then time priority, with partial fills; remaining limit quantity rests on the book and unfilled market quantity is cancelled. Support cancelling, reducing quantity without losing priority, displaying the top levels with the spread, and statistics (trade count, volume, last price, VWAP). Reject invalid prices and reused order ids.

Objectives

  • Choose containers for performance: map with a custom comparator, list and unordered_map
  • Implement price-time priority matching
  • Keep an index of iterators for O(1) removal
  • Use exact integer prices

Features

  • Limit and market orders, partial fills
  • Price-time priority, trades at the resting price
  • Cancel and reduce (keeping queue position)
  • Depth view with spread; VWAP statistics

Concepts demonstrated

  • Order books
  • Priority rules
  • Iterator stability
  • Custom comparators
  • Member templates
  • Fixed-point prices

System architecture

OrderBook keeps bids_ as std::map<price, std::list<Order>, std::greater<>> (best = highest) and asks_ as an ascending map (best = lowest), so begin() is always the best level. match is a member template used for both sides: it walks the best opposite level's FIFO list, filling against the front order until the incoming order is done or prices stop crossing, and erases empty levels. Remaining limit quantity is appended to its level and its list iterator stored in index_, which makes cancel a direct erase. modify only allows reductions, so the order keeps its place.

TextArchitecture diagram
ASK 102.25 [S4 200]
ASK 101.50 [S1 100]
ASK 101.00 [S2 50] -> [S3 70] <- best ask (asks_.begin())
---------- spread 1.00 ----------
BID 100.00 [B1 80] -> [B3 30] <- best bid (bids_.begin())
BID 99.75 [B2 40]
buy B4 60 @101.00 -> fills S2 50, then S3 10 (time priority)

Folder structure

TextProject tree
order-matching-engine/
├── README.md
├── Makefile
├── src/main.cpp
├── src/order_book.cpp
├── src/order_book.h
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CXX = g++
CXXFLAGS = -std=c++17 -Wall -Wextra -O2
SRC := $(wildcard src/*.cpp)
HDR := $(wildcard src/*.h src/*.hpp)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CXX) $(CXXFLAGS) -Isrc $(SRC) -o app
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/order_book.h
Order, Trade and the OrderBook interface with its containers.
src/order_book.cpp
Matching (a member template for both sides), resting orders, cancel, reduce, depth and best prices.
src/main.cpp
Command parsing, exact price parsing, trade reporting, the depth display and statistics.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
g++ -std=c++17 -Wall -Wextra -Isrc src/*.cpp -o app
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
=== Order Matching Engine (simulation) ===
> S1: 100 resting at 101.50
> S2: 50 resting at 101.00
> S3: 70 resting at 101.00
> S4: 200 resting at 102.25
> B1: 80 resting at 100.00
> B2: 40 resting at 99.75
> B3: 30 resting at 100.00
> price qty orders
ASK 102.25 200 1
ASK 101.50 100 1
ASK 101.00 120 2
---- spread 1.00 ----
BID 100.00 110 2
BID 99.75 40 1
> TRADE 50 @ 101.00 (buyer B4, seller S2)
TRADE 10 @ 101.00 (buyer B4, seller S3)
B4 fully filled
> price qty orders
ASK 102.25 200 1
ASK 101.50 100 1
ASK 101.00 60 1
---- spread 1.00 ----
BID 100.00 110 2
BID 99.75 40 1
> TRADE 60 @ 101.00 (buyer B5, seller S3)
TRADE 90 @ 101.50 (buyer B5, seller S1)
B5 fully filled
> price qty orders
ASK 102.25 200 1
ASK 101.50 10 1
---- spread 1.50 ----
BID 100.00 110 2
BID 99.75 40 1
> TRADE 80 @ 100.00 (buyer B1, seller S5)
TRADE 20 @ 100.00 (buyer B3, seller S5)
S5 fully filled
> reduced S4 to 120
> cannot reduce S4 (unknown, or not a reduction)
> cancelled B2
> not on the book: B2
> Invalid price 'abc'
> Order id B1 was already used
> TRADE 10 @ 101.50 (buyer B7, seller S1)
TRADE 120 @ 102.25 (buyer B7, seller S4)
B7: 170 unfilled, cancelled (market order, no more liquidity)
> price qty orders
----------------------
BID 100.00 10 1
> trades 8, volume 440, last 102.25, VWAP 101.23
>
Input
sell S1 100 101.50
sell S2 50 101.00
sell S3 70 101.00
sell S4 200 102.25
buy B1 80 100.00
buy B2 40 99.75
buy B3 30 100.00
book
buy B4 60 101.00
book
buy B5 150 101.50
book
sell S5 100 market
reduce S4 120
reduce S4 500
cancel B2
cancel B2
buy B6 10 abc
buy B1 10 99.00
buy B7 300 market
book
stats
quit

Testing

  • Compare ./app < tests/sample-input.txt with tests/expected-output.txt.
  • B4 buys 60 at 101.00: S2 (earlier) fills 50, then S3 fills 10.
  • The market sell S5 hits B1 (80) before B3 (20) because B1 arrived first at 100.00.
  • The market buy B7 takes all remaining asks (130) and cancels the unfilled 170.
  • VWAP = 44,540.00 / 440 = 101.23.

Common errors

Cancel crashes or removes the wrong order

Store std::list iterators (stable) in the index, not std::vector indices or deque iterators, which shift when other orders are removed.

Trades print prices like 100.99999

Represent prices as integer cents; never use floating point for money.

Possible improvements

  • Add stop orders that trigger at a price
  • Support several instruments (one book per symbol)
  • Record trades to a CSV file and replay them

Additional challenges

  1. 1Add immediate-or-cancel and fill-or-kill order types.
  2. 2Measure throughput with a million random orders.
  3. 3Show a time-and-sales tape of the last 10 trades.

Built and tested it yourself? Mark it to update your dashboard.