A high-performance, simplified stock exchange core implementation written in C++20.
Modern financial exchanges need to process hundreds of thousands of orders per second with microsecond latency while maintaining data consistency and fault tolerance. This project tackles the fundamental challenges:
- Order Matching: Efficiently match buy and sell orders using different algorithms
- Market Data: Real-time distribution of quotes and trade notifications
- Fault Tolerance: Handle message loss and system recovery
- Concurrency: Thread-safe processing of concurrent order flows
- Protocol Design: Efficient binary message formats for high-frequency trading
├── src/
│ ├── core/ # Order matching and book management
│ ├── services/ # Exchange services (gateway, quotes, etc.)
│ ├── client/ # Client implementation
│ └── queue/ # Event processing
├── include/ # Header files
├── tests/ # Unit and performance tests
└── Makefile # Build configuration
-
Three-Tier Protocol Architecture:
ClientProtocol(24 bytes) carries minimal order data over the network,SystemProtocol(44 bytes) adds sequencing and integrity metadata for internal processing, andBatchSystemProtocol(1000 bytes) aggregates multiple orders for efficient bulk operations and reduced system calls. -
Dual-Strategy Price Levels: The
PriceLevelclass supports both time-priority (FIFO) and size-priority (Pro-Rata) matching, allowing flexibility in match execution -
Batch Protocol: The
BatchSystemProtocoluses a fixed 1000-byte array with inline serialization, enabling efficient batching. -
Singleton Services with Thread Safety: Services like
RetransmissionServiceuse the singleton pattern with proper mutex protection, ensuring system-wide consistency while avoiding global state issues. -
Transaction Id and Sequence Number Gap Detection: The
OrderBook::processmethod implements intelligent gap detection, automatically requesting retransmissions or snapshots based on sequence number discontinuities. -
Event-Driven Architecture: The
EventQueuedecouples order processing from client notifications, allowing for asynchronous trade reporting without blocking the matching engine.
The system supports pluggable matching algorithms:
- FIFO Strategy (
FIFOStrategy): Time-priority matching (first-in-first-out) - Pro-Rata Strategy (
ProRataStrategy): Size-weighted allocation for large orders
- Message Retransmission: Automatic detection and recovery of lost messages
- Snapshot Recovery: Point-in-time order book snapshots for fast recovery
- Checksum Validation: Built-in message integrity verification
- Real-time Quotes: Live bid/ask prices and market depth via
QuoteService - Trade Notifications: Asynchronous client notifications for order status changes
- Market Depth: Top-of-book and deep market data aggregation
- C++20 compatible compiler (GCC 10+ or Clang 12+)
- Linux environment
# Build the main exchange
make build
# Run the exchange
make run
# Run performance tests
make perf
# Run performance tests
make test
# Clean build artifacts
make cleandocker build -t stock-exchange-core
docker run --rm stock-exchange-core
docker run --rm stock-exchange-core ./bin/unit_tests # to run unit tests
docker run --rm stock-exchange-core ./bin/perf_tests # to run performance testsInitializing exchange...
Client 1 sending BUY order: 9 at price 98
Client 2 sending SELL order: 10 at price 98
Client 3 sending SELL order: 44 at price 98
Processing final batch of 3 orders before shutdown
TradeNotificationService: Processing event 1
Client 1 received notification: Order 1 (timestamp: 1759532881458000) status: Partially filled and added
Client 2 received notification: Order 1 (timestamp: 1759532881458000) status: Partially filled and added
Client 3 received notification: Order 1 (timestamp: 1759532881458000) status: Partially filled and added
TradeNotificationService: Processing event 2
Client 1 received notification: Order 2 (timestamp: 1759532881458002) status: Partially filled and added
Client 2 received notification: Order 2 (timestamp: 1759532881458002) status: Partially filled and added
Client 3 received notification: Order 2 (timestamp: 1759532881458002) status: Partially filled and added
Exchange shutting down.
=== Single Thread Throughput ===
Throughput: 403452.21 orders/sec
Total Orders: 10000 orders
Duration: 0.02 seconds
Avg Latency: 2.9 μs
P95 Latency: 0.55 μs
P99 Latency: 57.00 μ
