rea
Reverse engineer anything with agents, from app behavior down to native binaries.
- 473k
- TypeScript
- MIT
- 7 min ago
High-performance C++ limit order book matching engine — 2.3M msg/s, sub-μs P50 latency, O(1) cancel, zero hot-path allocations, intrusive lists
Repo sfeirc/LOB-Matching-Engine, read from GitHub 1 min ago. sfeirc has not joined Take My Repo.
sfeirc/LOB-Matching-Engine is a public repo on GitHub by sfeirc. High-performance C++ limit order book matching engine — 2.3M msg/s, sub-μs P50 latency, O(1) cancel, zero hot-path allocations, intrusive lists. It declares the MIT license on GitHub. It is written mainly in C++, has 2 stars and last changed on 2026-08-14. Nobody has reviewed it on Take My Repo yet, which says nothing about its quality. Read from GitHub on 2026-11-22.
In the maintainer's words. Shown from GitHub; Take My Repo does not keep a copy.
High-Performance Single-Threaded Limit Order Book with Price-Time Priority Matching
Throughput: 2.3M+ msg/s (engine-only) · P99 Latency: 2-4 μs · P95 Latency: 1-2 μs · P50 Latency: 0.6-1.0 μs
Features: Zero hot-path allocations · O(1) cancel · Intrusive lists · Object pooling · Cache-aligned structures
Reproducible • Engine-only timing • Latency percentiles • JSON metrics • Unit tested
What: Production-grade C++ limit order book matching engine with price-time priority, handling NewLimit, NewMarket, and Cancel messages. Optimized for HFT workloads with sub-microsecond P99 latency targets.
Why it matters: Single-threaded performance of 2.3M+ messages/second with zero hot-path allocations and O(1) cancel operations. Demonstrates rigorous benchmarking (engine-only timing, latency percentiles, reproducible metrics) required for HFT systems.
How: Walk-forward benchmark suite, regime-aware evaluation (low/mid/high message rates), allocator profiling (object pools vs heap), and optimization ablations (before/after each enhancement). No data leakage via deterministic replay and isolated timing measurements.
A limit order book matching engine is the literal transaction core of every electronic exchange and most trading firms' internal simulators, which makes the domain itself directly relevant to quant/finance/banking roles. But the engineering techniques this project actually exercises generalize well past that one domain: a compact, cache-aligned order representation (32 bytes, two per 64-byte cache line), an intrusive doubly-linked list per price level so cancelling an order is a pointer unlink instead of a container search, a pre-allocated object pool that keeps the matching loop free of malloc/new, and branch-prediction/prefetch hints tuned against the real hot loop. That toolbox -- deterministic memory, cache-aware layout, zero-allocation hot paths -- applies to any domain where microseconds matter and allocation stalls are not acceptable: real-time ad-bidding auctions, game engine tick loops, and embedded/automotive control code all face the same constraints this engine was built around. It also carries over to oil & gas SCADA and real-time process-control systems, which enforce comparably hard latency budgets on a completely different problem (valve/sensor polling and interlock response instead of order matching) but reward the identical discipline: predictable memory behavior and rigorously measured, not assumed, worst-case latency.
flowchart LR
CSV["CSV file<br/>ts, MsgType, Side, id, price, qty"] --> CR["CSVReader::read_messages<br/>parses into Msg structs"]
CR --> OB{"OrderBook::process_message"}
OB -->|"NewLimit"| POOL["allocate_order()<br/>O(1) from pre-allocated 2M-Order pool"]
POOL --> MATCH["match_limit_buy_fast / match_limit_sell_fast<br/>walk best price level via bids_/asks_ std::map"]
OB -->|"NewMarket"| MATCH
MATCH --> FIFO["PriceLevel intrusive doubly-linked list<br/>FIFO match against resting orders"]
FIFO -->|"match found"| TRADE["Trade recorded<br/>trades_ vector"]
FIFO -->|"residual qty, no more matches"| BOOK["insert_limit_order_fast<br/>inserted into bids_ or asks_"]
OB -->|"Cancel"| LOOKUP["order_pointers_ hash map<br/>O(1) OrderId to Order-pointer lookup"]
LOOKUP --> REMOVE["PriceLevel::remove_order<br/>O(1) intrusive-list unlink"]
TRADE --> METRICS["replay: engine-only timing<br/>+ latency percentiles + JSON metrics export"]
| Metric | 10K Dataset | 1M Dataset | 10M Dataset |
|---|---|---|---|
| Engine Throughput (msg/s) | 2.1M |
2.3M |
2.4M |
| P50 Latency (μs) | 0.8 |
0.7 |
0.6 |
| P95 Latency (μs) | 1.2 |
1.1 |
1.0 |
| P99 Latency (μs) | 2.5 |
2.3 |
2.1 |
| P99.9 Latency (μs) | 4.8 |
4.2 |
3.9 |
| Max Latency (μs) | 12.5 |
15.3 |
18.7 |
| CSV Read Time (ms) | 26.4 |
2270 |
17448 |
| Engine Time (ms) | 4.8 |
435 |
4167 |
| Memory Allocations (hot path) | 0 |
0 |
0 |
Evaluation: Deterministic replay with 10M message dataset
| Optimization | Before | After | Improvement |
|---|---|---|---|
| Throughput (msg/s) | 1.2M |
2.3M |
+91.7% |
| P99 Latency (μs) | 8.5 |
2.3 |
-73% |
| Hot-Path Allocations | ~2/msg |
0 |
-100% |
| Cancel Operation (O complexity) | O(n) |
O(1) |
∞ |
| Cache Misses (per 1K msgs) | ~45 |
~12 |
-73% |
Optimizations Applied:
LIKELY/UNLIKELY)PREFETCH hints)| System | Throughput | P99 Latency | Architecture |
|---|---|---|---|
| This LOB Engine | 2.3M msg/s |
2.3 μs |
Single-thread |
| Industry HFT Target | >1M msg/s |
<1 μs |
Multi-thread |
| Academic LOB (Baseline) | ~500K msg/s |
~10 μs |
Single-thread |
| Reference Implementation (std::map) | ~800K msg/s |
~5 μs |
Single-thread |
Note: HFT industry target is <1 μs P99, but that typically requires:
This implementation achieves software-only performance competitive with industry standards.
process_message() loop is timedstd::chrono::steady_clock with ns resolutionCMakeLists.txtbuild/data/results/valgrind / AddressSanitizermalloc/new in matching loops# Clone and setup git clone https://github.com/sfeirc/LOB-Matching-Engine.git cd LOB-Matching-Engine mkdir build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release cmake --build . -j # Generate test datasets ./generate_dataset 10000 # 10K messages ./generate_dataset 1000000 # 1M messages ./generate_dataset 10000000 # 10M messages # Run benchmarks with metrics ./replay data/large_dataset_10k.csv --metrics results/metrics_10k.json ./replay data/large_dataset_1000k.csv --metrics results/metrics_1M.json ./replay data/large_dataset_10000k.csv --metrics results/metrics_10M.json # Run unit tests ./test_orderbook # Full benchmark suite (all datasets) ../scripts/run_benchmark.ps1 # Windows ../scripts/run_benchmark.sh # Linux/Mac
Optimization flags in CMakeLists.txt:
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -march=native -flto -ffast-math -funroll-loops") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -finline-functions -fno-strict-aliasing") set(CMAKE_INTERPROCEDURAL_OPTIMIZATION_RELEASE ON)
Price Levels:
std::map<Price, PriceLevel, std::greater<Price>> (highest price first)std::map<Price, PriceLevel, std::less<Price>> (lowest price first)Order Storage:
Order* next_in_level, Order* prev_in_level)std::unordered_map<OrderId, Order*> for O(1) cancelstd::vector<Order>)Price Level Structure:
class PriceLevel { Order* head_; // Front of queue (oldest order) Order* tail_; // Back of queue (newest order) Quantity cached_qty_; // O(1) total quantity (incremental updates) };
Price-Time Priority:
Matching Flow:
NewLimit Order → Match against opposite side
├─ While (incoming.qty > 0 && opposite_book.not_empty)
│ ├─ Get best price level
│ ├─ Check price compatibility
│ ├─ Match against orders in FIFO order
│ │ ├─ Calculate match quantity: min(incoming.qty, resting.qty)
│ │ ├─ Update quantities: incoming.qty -= match_qty, resting.qty -= match_qty
│ │ ├─ Record trade
│ │ └─ If resting fully filled: remove from level
│ └─ If level empty: remove from book
└─ If residual quantity: insert into book
| Operation | Complexity | Notes |
|---|---|---|
| Insert Limit Order | O(log n) | Map lookup + list append |
| Cancel Order | O(1) | Hash lookup + list remove |
| Match Limit Order | O(k) | k = price levels to sweep |
| Match Market Order | O(k·m) | k = levels, m = orders per level |
| Get Best Bid/Ask | O(1) | map.begin() access |
| Get Total Quantity | O(1) | Cached value |
Where n = number of price levels, k = levels to sweep, m = orders per level
10K Dataset: 2.1M msg/s (4.8 ms engine time)
1M Dataset: 2.3M msg/s (435 ms engine time)
10M Dataset: 2.4M msg/s (4167 ms engine time)
Scaling: Throughput increases slightly with dataset size (cache warming, branch prediction)
P50: 0.6-0.8 μs (typical limit order insert/match)
P95: 1.0-1.2 μs (occasional multi-level sweep)
P99: 2.1-2.5 μs (worst-case multi-level matching)
P99.9: 3.9-4.8 μs (complex market order sweeps)
Max: 12.5-18.7 μs (edge cases: many levels, large queue)
Total: ~545 MB for 10M message dataset (mostly pre-allocation)
Single-Threaded: Designed for single-threaded execution. Multi-threading would require lock-free data structures and careful synchronization.
Price Range: Uses std::map which is efficient for sparse price levels (~500 levels typical). For dense price ranges (>10K levels), consider flat arrays or hash maps.
Memory: Pre-allocates large object pools (545 MB for 10M dataset). Trade-off: memory usage vs. zero allocations.
P99 Latency: Achieves 2.3 μs P99, but HFT industry target is <1 μs. To reach sub-microsecond, consider:
Network I/O: No networking layer. For production, add:
Persistence: No order book snapshots or state recovery. Add for production.
.
├── README.md # This file
├── LICENSE # MIT license
├── CMakeLists.txt # Build configuration
├── BENCHMARK_RESULTS.md # Detailed performance analysis
│
├── include/ # Headers
│ ├── OrderBook.h # Core LOB implementation
│ ├── Message.h # Message types
│ ├── Trade.h # Trade structure
│ └── CSVReader.h # CSV parsing
│
├── src/ # Implementation
│ ├── main.cpp # Benchmark entry point
│ ├── OrderBook.cpp # Matching engine
│ ├── CSVReader.cpp # CSV parser
│ └── generate_dataset.cpp # Dataset generator
│
├── tests/ # Unit tests
│ └── test_orderbook.cpp # Correctness tests
│
├── scripts/ # Automation
│ ├── run_benchmark.sh # Linux/Mac benchmark script
│ └── run_benchmark.ps1 # Windows benchmark script
│
├── results/ # Benchmark outputs
│ ├── metrics_10k.json # 10K dataset metrics
│ ├── metrics_1M.json # 1M dataset metrics
│ └── metrics_10M.json # 10M dataset metrics
│
├── docs/ # Documentation
│ ├── diagrams/ # Performance charts
│ │ ├── throughput_chart.png
│ │ ├── latency_distribution.png
│ │ ├── memory_profile.png
│ │ └── performance_comparison.png
│ └── architecture.md # System design
│
└── data/ # Test datasets
├── sample.csv # Small test dataset
└── large_dataset_*.csv # Generated benchmarks
This implementation demonstrates techniques from:
Industry Standards:
MIT License - see LICENSE file for details.
Contributions welcome in:
High-frequency trading system demonstrating:
Keywords: High-Frequency Trading, Limit Order Book, Matching Engine, C++ Optimization, HFT Performance, Sub-Microsecond Latency, Object Pooling, Cache Optimization
Engine-Only Timing:
Total Time = CSV Read Time + Engine Processing Time
Engine Throughput = Messages / Engine Processing Time
Latency Measurement:
std::chrono::steady_clockReproducibility:
seed=42Baseline (Initial Implementation):
1.2M msg/s8.5 μs~2 per message (heap allocations)O(n) (vector erase)After Object Pooling:
1.8M msg/s (+50%)5.2 μs (-39%)0 (zero hot-path allocations)After Intrusive Lists:
2.1M msg/s (+75%)3.1 μs (-64%)O(1) (direct pointer manipulation)After Branch Prediction + Prefetch:
2.3M msg/s (+92%)2.3 μs (-73%)Order Structure (32-byte aligned):
struct Order { OrderId id; // 8 bytes Price price; // 8 bytes Quantity qty; // 8 bytes Side side; // 1 byte (+ 7 padding) Order* next_in_level; // 8 bytes Order* prev_in_level; // 8 bytes }; // Total: 32 bytes (perfect cache line alignment)
Cache Performance:
I've built a production-grade C++ limit order book achieving 2.3M msg/s throughput and 2.3 μs P99 latency through zero hot-path allocations, O(1) cancel operations, and aggressive compiler optimizations—all with rigorous benchmarking (engine-only timing, latency percentiles, reproducible metrics) and unit test coverage—reproducible in one command with
./replay data/large_dataset_10000k.csv --metrics results/metrics.json.
sfeirc/LOB-Matching-Engine is a public repo on GitHub by sfeirc. High-performance C++ limit order book matching engine — 2.3M msg/s, sub-μs P50 latency, O(1) cancel, zero hot-path allocations, intrusive lists.
It declares the MIT license on GitHub.
Its maker has not tagged a system, so it is unknown here. Its README says what it needs.
Open "Take it" on its page: Take My Repo writes an install plan for your machine and hands it to your AI agent (Claude Code, Codex or Cursor), which asks you before each step. Take My Repo has not tested it on any machine.
Its last change on GitHub was on 2026-08-14. GitHub counts 0 open issues and pull requests. Take My Repo does not judge from that whether it is maintained.
Nobody has reviewed it on Take My Repo yet, which says nothing about its quality.
Open-source Rust framework for building event-driven live-trading & backtesting systems
SRS is a simple, high-performance, AI-driven real-time media server supporting RTMP, WebRTC, HLS, HTTP-FLV, HTTP-TS, SRT, MPEG-DASH, and GB28181, with codec support for H.264, H.265, AV1, VP9, AAC, Opus, and G.711.

Ultra-fast matching engine written in Java based on LMAX Disruptor, Eclipse Collections, Real Logic Agrona, OpenHFT, LZ4 Java, and Adaptive Radix Trees.
VisualHFT Terminal: open-source observability and decision terminal for electronic trading desks. Live Level 2 order books, microstructure analytics, and quantitative execution monitoring.
5-min directional forecast from LOB microstructure — AUROC 0.916, 84% accuracy, walk-forward CV, XGBoost/Transformer ensemble, fees & slippage modeled

Ultra-low-latency NASDAQ ITCH 5.0 feed handler — 97 ns book update, AF_XDP/recvmmsg, SIMD order-map probing, lock-free BBO cache
Dent ta Maison: mobile + backend app for rapid dental self-check via guided photo capture and cavity pre-screening

Statistical arbitrage engine — C++ signal pipeline, Python walk-forward backtesting, Streamlit P&L dashboard
MRV toolkit for a CO2 injection well: Peng-Robinson EOS density, mass-balance with Monte Carlo uncertainty, CUSUM leak/anomaly detection
Incident Lens: OpenTelemetry incident lab turning correlated metrics/logs/traces/deployments into ranked, evidence-citing failure hypotheses
This page is also available as structured data, with the same sources and dates.
/api/v1/resources/gh/sfeirc/LOB-Matching-EngineTake My Repo has not tested this on your machine. Requirements come from the project's own documentation.
