Projects / Orderbook
C++20 · systems · 2026

Orderbook

A small, readable limit order book in C++20. Orders rest on a price-sorted ladder, match by price-time priority, and can be cancelled or modified in place.

price-time priority matching

Overview

The core of an exchange, kept small enough to read in one sitting.

An order book holds every resting buy and sell order for an instrument and decides who trades with whom. This one sticks to the essentials: a bid side and an ask side, strict price-time priority, and a clear rule for every order type, so each step of the matching logic is easy to follow and check.

How it works

  • Two sorted ladders

    Bids live in a std::map sorted high to low and asks in one sorted low to high, so the best price on each side is always begin(). Each price level holds a FIFO queue of orders, which gives time priority within a price.

  • Matching until the book uncrosses

    After every add, the engine trades the front of the best bid against the front of the best ask for the smaller remaining quantity, records both sides of the trade, and pops filled orders and empty levels, repeating until the best bid is below the best ask.

  • Constant-time cancels

    An unordered_map maps each order id to its order and its exact position (a list iterator) in its level's queue. Cancelling is one hash lookup and an unlink, with no search through the level.

  • Order types with clear rules

    Good-Till-Cancel orders rest until filled or cancelled. Fill-and-Kill orders are rejected if they can't cross the spread, and anything left over after matching is cancelled rather than left on the book.

  • Modify as cancel-replace

    Changing an order's price, side or size cancels it and re-adds it with the same id and type. That sends it to the back of the queue at its new level, which is how real exchanges treat a modify.

  • Depth snapshots

    GetOrderInfos() collapses each side into per-level price and total remaining quantity: the aggregated view a market-data feed would publish.

Architecture

OrderGTC · FAK
→
Orderbookbid/ask ladders · id map
→
Tradesbid + ask fills
→
Level infosdepth snapshot

What I'd do next

Market orders are declared but not wired into matching yet. After that: a unit-test suite, replaying real historical tick data through the book, measuring throughput and latency, and moving matching onto its own thread fed by an order queue.