# komal-ai417/hft-matching-engine architecture

> Architecture diagram of the GitHub repository komal-ai417/hft-matching-engine, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-07-21). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/komal-ai417/hft-matching-engine
- Repository: https://github.com/komal-ai417/hft-matching-engine

## Overview

#### 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: [`src/OrderBook.cpp`](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp) (Matching loop), [`src/OrderBook.h`](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.h) (OrderBook), [`src/PriceLevel.h`](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/PriceLevel.h) (PriceLevel), [`src/MemoryPool.h`](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/MemoryPool.h) (MemoryPool<Order>)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["Public API"]
  node_caller(("Integrating caller<br/>external caller"))
  node_order_book["OrderBook<br/>public engine API<br/>[OrderBook.h]"]
  node_trade_callback["Trade callback<br/>caller callback"]
end

subgraph group_engine["Matching Engine"]
  node_order_book_impl["OrderBook implementation<br/>orchestration<br/>[OrderBook.cpp]"]
  node_validation["Order validation<br/>hot-path checks<br/>[OrderBook.cpp]"]
  node_matching["Matching loop<br/>price-time matching<br/>[OrderBook.cpp]"]
  node_cancel["Cancellation flow<br/>order removal<br/>[OrderBook.cpp]"]
  node_macros["Hot-path macros<br/>compile-time utilities<br/>[Macros.h]"]
end

subgraph group_storage["Book Storage"]
  node_bid_ask_levels[("Bid and ask level arrays<br/>flat price index<br/>[OrderBook.cpp]")]
  node_price_level["PriceLevel<br/>FIFO level<br/>[PriceLevel.h]"]
  node_order["Order<br/>[Order.h]"]
  node_memory_pool[("MemoryPool&lt;Order&gt;<br/>contiguous slot pool<br/>[MemoryPool.h]")]
  node_id_index["Order ID index<br/>flat lookup<br/>[OrderBook.h]"]
end

subgraph group_runtime["Runtime &amp; Build"]
  node_benchmark["Standalone workload<br/>benchmark executable<br/>[main.cpp]"]
  node_cmake["CMake build<br/>C++20 build orchestration<br/>[CMakeLists.txt]"]
end

node_caller -->|"add / cancel"| node_order_book
node_caller -->|"supplies"| node_trade_callback
node_order_book -->|"delegates"| node_order_book_impl
node_order_book_impl -->|"validates add"| node_validation
node_validation -->|"checks duplicate ID"| node_id_index
node_validation -->|"accepted aggressive order"| node_matching
node_matching -->|"selects best opposite price"| node_bid_ask_levels
node_bid_ask_levels -->|"indexes active level"| node_price_level
node_price_level -->|"FIFO head and links"| node_order
node_matching -->|"emits trades"| node_trade_callback
node_matching -->|"releases filled makers"| node_memory_pool
node_matching -->|"clears filled IDs"| node_id_index
node_matching -->|"rests residual limit order"| node_price_level
node_memory_pool -->|"allocates indexed slots"| node_order
node_order_book_impl -->|"routes cancel"| node_cancel
node_cancel -->|"locates order"| node_id_index
node_cancel -->|"unlinks FIFO entry"| node_price_level
node_cancel -->|"returns slot"| node_memory_pool
node_order_book_impl -->|"uses"| node_macros
node_benchmark -->|"drives workload"| node_order_book
node_cmake -->|"builds"| node_benchmark
node_cmake -->|"builds library"| node_order_book

click node_order_book "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.h"
click node_order_book_impl "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp"
click node_validation "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp"
click node_matching "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp"
click node_cancel "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp"
click node_bid_ask_levels "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp"
click node_price_level "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/PriceLevel.h"
click node_order "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/Order.h"
click node_memory_pool "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/MemoryPool.h"
click node_id_index "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.h"
click node_macros "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/Macros.h"
click node_benchmark "https://github.com/komal-ai417/hft-matching-engine/blob/main/src/main.cpp"
click node_cmake "https://github.com/komal-ai417/hft-matching-engine/blob/main/CMakeLists.txt"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_caller,node_order_book,node_trade_callback toneBlue
class node_order_book_impl,node_validation,node_matching,node_cancel,node_macros toneAmber
class node_bid_ask_levels,node_price_level,node_order,node_memory_pool,node_id_index toneMint
class node_benchmark,node_cmake toneRose
```

## Components

### Public API

- **Integrating caller**: external caller · Provides synchronous orders, cancels, and trade callback.
- [OrderBook](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.h): public engine API · Validates, routes, matches, rests, and cancels orders. · `src/OrderBook.h`
- **Trade callback**: caller callback · Receives executions directly without engine result buffering.

### Matching Engine

- [OrderBook implementation](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp): orchestration · Hot-path status-based add and cancel processing. · `src/OrderBook.cpp`
- [Order validation](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp): hot-path checks · Checks IDs, quantity, and price bounds before matching. · `src/OrderBook.cpp`
- [Matching loop](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp): price-time matching · Consumes opposite-side best levels and emits executions. · `src/OrderBook.cpp`
- [Cancellation flow](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp): order removal · Finds, unlinks, clears identity, and releases the order slot. · `src/OrderBook.cpp`
- [Hot-path macros](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/Macros.h): compile-time utilities · `src/Macros.h`

### Book Storage

- [Bid and ask level arrays](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.cpp): flat price index · Separate price-bounded storage and best-price state per side. · `src/OrderBook.cpp`
- [PriceLevel](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/PriceLevel.h): FIFO level · Anchors each price level's intrusive doubly linked FIFO. · `src/PriceLevel.h`
- [Order](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/Order.h): pool-resident order · Compact attributes with 32-bit intrusive next and previous indices. · `src/Order.h`
- [MemoryPool<Order>](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/MemoryPool.h): contiguous slot pool · Preallocates order slots and recycles indices through a LIFO free list. · `src/MemoryPool.h`
- [Order ID index](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/OrderBook.h): flat lookup · Maps order IDs to pool indices for duplicate detection and cancellation. · `src/OrderBook.h`

### Runtime & Build

- [Standalone workload](https://github.com/komal-ai417/hft-matching-engine/blob/main/src/main.cpp): benchmark executable · Exercises the library core as a standalone program. · `src/main.cpp`
- [CMake build](https://github.com/komal-ai417/hft-matching-engine/blob/main/CMakeLists.txt): C++20 build orchestration · Builds the engine and fetches GoogleTest and Google Benchmark. · `CMakeLists.txt`

## Connections

- 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
