A C++20 limit order book matching engine with sub-50ns operations on Linux.
- Supports GTC, market, IOC, and FOK orders
- Lock-free MPMC order ingest
- Zero hot-path allocations
- Direct-indexed price ladder
- O(1) order lookup and cancellation
- Sub-50ns core operations on Linux
Adds a lock free queue for concurrent order ingest. Also cuts add and cancel latency further. The public API has not changed. Details and numbers are in docs/BENCHMARKS.md.
cmake -S . -B build
cmake --build build --config Releaseadd_subdirectory(liborderbook)
target_link_libraries(your_app PRIVATE orderbook::orderbook)#include <iostream>
#include "OrderBook.h"
#include "BookPrinter.h"
using namespace orderbook;
OrderBook book;
book.addOrder(OrderBuilder{}.id(OrderId{1}).buy().goodTillCancel()
.price(Price{100}).quantity(Quantity{10}).build());
book.addOrder(OrderBuilder{}.id(OrderId{2}).sell().goodTillCancel()
.price(Price{101}).quantity(Quantity{20}).build());
// Market order crosses the spread and returns the trades it produced.
auto trades = book.addOrder(OrderBuilder{}.id(OrderId{3}).buy().market()
.quantity(Quantity{5}).build());
book.cancelOrder(OrderId{1});
printBook(std::cout, book);=== ASKS ===
101 | 15 (1)
-------------
=== BIDS ===
OrderBuilder{}
.id(OrderId{42})
.buy() // or .sell()
.goodTillCancel() // or .market() / .fillOrKill() / .immediateOrCancel()
.price(Price{100}) // omit for market orders
.quantity(Quantity{10})
.build();
std::span<const Trade> addOrder(Order order); // Match against the book, rest the remainder
bool cancelOrder(OrderId id); // Remove a resting order by id
std::size_t size() const; // Live resting order count
OrderBookLevelInfos getLevelInfos() const; // Aggregated depth, both sidesOrder, OrderId, Price, and Quantity are strong types. A price cannot be passed where a quantity is expected.
Single core, Linux, GCC Release -O3:
| Operation | Latency |
|---|---|
| Add, no match | 37 ns |
| Add, single match | 37.5 ns |
| Add into 10k price levels | 34 ns |
| Cancel | 20 ns |
./build/orderbook_bench_allFull history in docs/BENCHMARKS.md.
CI runs the suite on GCC and Clang, in Release and Debug, and under AddressSanitizer, UndefinedBehaviorSanitizer, and ThreadSanitizer.
- How to Build a Fast Limit Order Book - the array indexed price level technique this book uses
- Bounded MPMC queue - Dmitry Vyukov, the design
ConcurrentQueueis built on - Limit Order Book in C++ - Abosi
- Bit Twiddling Hacks - Sean Eron Anderson, Stanford. The bit scan technique behind the occupancy bitset
- TomaszRewak/cpp-allocator - slab allocator
- Strong types with CRTP - Fluent C++
MIT
