Skip to content

Implemented a lock-free matching engine in C++ (C++20) supporting FIFO and pro-rata strategies; demonstrated 100000+ orders/sec

License

Notifications You must be signed in to change notification settings

ol1g3/stock-exchange-core-cpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Stock Exchange Core (C++)

A high-performance, simplified stock exchange core implementation written in C++20.

Problem Statement

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

Architecture Overview

plot

Project Structure

├── 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

Key Features & Design Decisions

  1. 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, and BatchSystemProtocol (1000 bytes) aggregates multiple orders for efficient bulk operations and reduced system calls.

  2. Dual-Strategy Price Levels: The PriceLevel class supports both time-priority (FIFO) and size-priority (Pro-Rata) matching, allowing flexibility in match execution

  3. Batch Protocol: The BatchSystemProtocol uses a fixed 1000-byte array with inline serialization, enabling efficient batching.

  4. Singleton Services with Thread Safety: Services like RetransmissionService use the singleton pattern with proper mutex protection, ensuring system-wide consistency while avoiding global state issues.

  5. Transaction Id and Sequence Number Gap Detection: The OrderBook::process method implements intelligent gap detection, automatically requesting retransmissions or snapshots based on sequence number discontinuities.

  6. Event-Driven Architecture: The EventQueue decouples order processing from client notifications, allowing for asynchronous trade reporting without blocking the matching engine.

🚀 Matching Strategies

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

🔄 Fault Tolerance

  • 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

📊 Market Data

  • 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

Building and Running

Prerequisites

  • C++20 compatible compiler (GCC 10+ or Clang 12+)
  • Linux environment

Build Commands

# 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 clean

Alternative setup using Docker

docker 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 tests

Sample Output (of the current main.cpp)

Initializing 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.

Results of performance tests for a single thread:

=== 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 μ

About

Implemented a lock-free matching engine in C++ (C++20) supporting FIFO and pro-rata strategies; demonstrated 100000+ orders/sec

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published