A high-performance C++ order book implementation that simulates a limit order book matching engine, commonly used in financial exchanges and trading systems.
This project implements a fully functional order book with support for multiple order types, automated order matching, and thread-safe operations. It's designed to handle buy and sell orders, match them according to price-time priority, and maintain order book state efficiently.
- Market Orders: Execute immediately at the best available price
- Good Till Cancel (GTC): Remain active until explicitly cancelled
- Fill And Kill (FAK): Execute immediately for the available quantity, cancel the rest
- Fill Or Kill (FOK): Execute fully or cancel entirely
- Good For Day (GFD): Automatically expire at end of trading day (4:00 PM)
- Add Orders: Place new buy/sell orders into the order book
- Cancel Orders: Remove existing orders by order ID
- Modify Orders: Modify existing order parameters
- Order Matching: Automatic price-time priority matching engine
- Level Data: Real-time aggregated price level information
- Thread Safety: Mutex-protected operations for concurrent access
- Automatic Pruning: Background thread to remove expired GFD orders
├── Orderbook.h/cpp # Main order book implementation
├── Order.h # Order class definition
├── OrderType.h # Order type enumeration
├── OrderModify.h # Order modification structure
├── Side.h # Buy/Sell side enumeration
├── Trade.h # Trade execution information
├── TradeInfo.h # Trade details
├── LevelInfo.h # Price level information
├── OrderbookLevelInfos.h # Aggregated level data
├── Constants.h # System constants
├── Usings.h # Type aliases
├── main.cpp # Entry point
└── OrderbookTest/ # Unit tests with Google Test
├── test.cpp # Test cases
└── TestFiles/ # Test input files
- Bids: Stored in a
std::mapwith descending price order (std::greater<Price>) - Asks: Stored in a
std::mapwith ascending price order (std::less<Price>) - Orders: Hash map for O(1) order lookup by ID
- Level Data: Aggregated quantity and count per price level
The order book implements price-time priority:
- Best bid (highest buy price) is matched with best ask (lowest sell price)
- When prices cross or match, orders execute
- Orders at the same price level execute in FIFO order
- Partial fills are supported for all order types except FOK
- Mutex-protected order operations
- Background thread for GFD order pruning
- Condition variables for clean shutdown
- C++20 compatible compiler (MSVC, GCC, or Clang)
- Visual Studio 2019/2022 (for Windows) or CMake
# Open the solution file
Orderbook.sln
# Build using Visual Studio or MSBuild
msbuild Orderbook.sln /p:Configuration=Release# Build and run the test project
cd OrderbookTest
# Tests use Google Test framework
# Run from Visual Studio Test Explorer or command line#include "Orderbook.h"
int main()
{
Orderbook orderbook;
// Create a buy order (GTC)
auto buyOrder = std::make_shared<Order>(
OrderType::GoodTillCancel,
1, // Order ID
Side::Buy,
100, // Price
50 // Quantity
);
// Add order and get resulting trades
Trades trades = orderbook.AddOrder(buyOrder);
// Create a sell order that matches
auto sellOrder = std::make_shared<Order>(
OrderType::GoodTillCancel,
2,
Side::Sell,
100,
30
);
trades = orderbook.AddOrder(sellOrder);
// This will match 30 units at price 100
// Cancel an order
orderbook.CancelOrder(1);
// Get current order book state
OrderbookLevelInfos levels = orderbook.GetOrderInfos();
return 0;
}The project includes comprehensive unit tests covering:
- Order placement and cancellation
- Order matching for all order types
- Market order execution
- Fill And Kill / Fill Or Kill scenarios
- Good Till Cancel order lifecycle
- Order modification (including side changes)
Test files are located in OrderbookTest/TestFiles/ and include:
Match_GoodTillCancel.txtMatch_Market.txtMatch_FillAndKill.txtMatch_FillOrKill_Hit.txtMatch_FillOrKill_Miss.txtCancel_Success.txtModify_Side.txt
- Order Addition: O(log n) for price level insertion
- Order Cancellation: O(1) for order lookup + O(log n) for level update
- Order Matching: O(n) where n is the number of orders matched
- Order Lookup: O(1) using hash map
- Level Data Retrieval: O(n) where n is the number of price levels
This project is available under the MIT License. See the LICENSE file for details.
Contributions are welcome! Areas for potential improvement:
- Add support for additional order types (e.g., Iceberg orders)
- Implement order book snapshots
- Add performance benchmarks
- Extend test coverage
- Add Python/C API bindings
The order book maintains separate bid and ask sides with automatic matching when prices cross. Each order maintains its state (filled quantity, remaining quantity) and supports partial fills. The implementation uses modern C++ features including smart pointers, move semantics, and thread synchronization primitives.
The background pruning thread checks for Good For Day orders and automatically cancels them at 4:00 PM daily, simulating real market behavior.