How komal-ai417/hft-matching-engine works
Purpose and Entry Points
A C++20, single-threaded limit-order-book matching engine optimized for low and predictable latency. Its public integration point is hft::OrderBook, accepting synchronous add/cancel calls and delivering executions through caller-provided trade callbacks. src/main.cpp is the standalone workload/benchmark executable; the library core is src/OrderBook.h and src/OrderBook.cpp.
Order Book Orchestration
OrderBook owns book state, validates inbound order fields, rejects duplicate IDs, routes by side/type, and coordinates matching, resting insertion, and cancellation. The hot path returns status rather than throwing, preserving predictable control flow. Core paths: src/OrderBook.h, src/OrderBook.cpp, src/Macros.h.
Matching Pipeline
On add_order, the engine first validates ID, quantity, and price bounds; then it matches an aggressive order against the opposite-side best prices. Matching follows price priority across bid/ask price-indexed storage and FIFO time priority within each price level. Filled makers are unlinked and released; residual limit quantity becomes a resting maker. Trade records are passed directly to the supplied callback rather than accumulated in an engine-owned result buffer. Paths: src/OrderBook.cpp, src/PriceLevel.h, src/Order.h.
Compact Order and FIFO Representation
Order is a compact pool-resident object that carries order attributes plus index-based intrusive next/previous links. Each PriceLevel anchors a FIFO doubly linked list, allowing insertion, head matching, and arbitrary unlinking without separately allocated list nodes. This is the primary cache-locality boundary: stable 32-bit indices replace heap pointers. Paths: src/Order.h, src/PriceLevel.h.
Memory and Identity Management
MemoryPool<Order> preallocates contiguous order storage at construction and hands out/reclaims indices through an intrusive LIFO free list. It avoids dynamic allocation during active order processing and includes allocation-state checking for memory safety. Separately, an order-ID-to-pool-index flat lookup enables constant-time duplicate detection and cancellation lookup. Paths: src/MemoryPool.h, src/OrderBook.h, src/OrderBook.cpp.
Price-Side State and Cancellation
The book maintains distinct flat price-level arrays for bids and asks over configured price bounds. Best-price tracking selects the crossing level; empty levels are removed from active consideration after their final order is filled or cancelled. cancel_order uses the ID index to locate an order, unlinks it from its level, updates level/best-price state where needed, clears identity state, and returns the slot to the pool. Paths: src/OrderBook.cpp, src/PriceLevel.h, src/MemoryPool.h.
Runtime and Deployment Boundaries
The engine has no embedded network, FIX/ITCH parser, queue, persistence layer, mutexes, atomics, or external execution service. It runs synchronously under a caller-enforced single-thread contract. Production deployment may place it on an isolated, pinned Linux CPU core and feed it through a future SPSC queue, but these are not current runtime components. Build orchestration is CMake/C++20 in CMakeLists.txt; GoogleTest and Google Benchmark are fetched for validation and performance measurement.
Main entry points: OrderBook.cpp Matching loop · OrderBook.h OrderBook · PriceLevel.h PriceLevel · MemoryPool.h MemoryPool<Order>
Components 15
Public API
- Integrating caller · Provides synchronous orders, cancels, and trade callback.
- OrderBook · Validates, routes, matches, rests, and cancels orders.
src/OrderBook.h - Trade callback · Receives executions directly without engine result buffering.
Matching Engine
- OrderBook implementation · Hot-path status-based add and cancel processing.
src/OrderBook.cpp - Order validation · Checks IDs, quantity, and price bounds before matching.
src/OrderBook.cpp - Matching loop · Consumes opposite-side best levels and emits executions.
src/OrderBook.cpp - Cancellation flow · Finds, unlinks, clears identity, and releases the order slot.
src/OrderBook.cpp - Hot-path macros
src/Macros.h
Book Storage
- Bid and ask level arrays · Separate price-bounded storage and best-price state per side.
src/OrderBook.cpp - PriceLevel · Anchors each price level's intrusive doubly linked FIFO.
src/PriceLevel.h - Order · Compact attributes with 32-bit intrusive next and previous indices.
src/Order.h - MemoryPool<Order> · Preallocates order slots and recycles indices through a LIFO free list.
src/MemoryPool.h - Order ID index · Maps order IDs to pool indices for duplicate detection and cancellation.
src/OrderBook.h
Runtime & Build
- Standalone workload · Exercises the library core as a standalone program.
src/main.cpp - CMake build · Builds the engine and fetches GoogleTest and Google Benchmark.
CMakeLists.txt
Connections 22
- Integrating caller → OrderBook: add / cancel
- Integrating caller → Trade callback: supplies
- OrderBook → OrderBook implementation: delegates
- OrderBook implementation → Order validation: validates add
- Order validation → Order ID index: checks duplicate ID
- Order validation → Matching loop: accepted aggressive order
- Matching loop → Bid and ask level arrays: selects best opposite price
- Bid and ask level arrays → PriceLevel: indexes active level
- PriceLevel → Order: FIFO head and links
- Matching loop → Trade callback: emits trades
- Matching loop → MemoryPool<Order>: releases filled makers
- Matching loop → Order ID index: clears filled IDs
- Matching loop → PriceLevel: rests residual limit order
- MemoryPool<Order> → Order: allocates indexed slots
- OrderBook implementation → Cancellation flow: routes cancel
- Cancellation flow → Order ID index: locates order
- Cancellation flow → PriceLevel: unlinks FIFO entry
- Cancellation flow → MemoryPool<Order>: returns slot
- OrderBook implementation → Hot-path macros: uses
- Standalone workload → OrderBook: drives workload
- CMake build → Standalone workload: builds
- CMake build → OrderBook: builds library