Skip to content

arshmessi/order_book_simulator

Repository files navigation

Order Book Simulator

A high-performance C++ order book implementation that simulates a limit order book matching engine, commonly used in financial exchanges and trading systems.

Overview

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.

Features

Order Types

  • 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)

Core Functionality

  • 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

Project Structure

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

Technical Details

Data Structures

  • Bids: Stored in a std::map with descending price order (std::greater<Price>)
  • Asks: Stored in a std::map with 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

Matching Algorithm

The order book implements price-time priority:

  1. Best bid (highest buy price) is matched with best ask (lowest sell price)
  2. When prices cross or match, orders execute
  3. Orders at the same price level execute in FIFO order
  4. Partial fills are supported for all order types except FOK

Thread Safety

  • Mutex-protected order operations
  • Background thread for GFD order pruning
  • Condition variables for clean shutdown

Building the Project

Prerequisites

  • C++20 compatible compiler (MSVC, GCC, or Clang)
  • Visual Studio 2019/2022 (for Windows) or CMake

Windows (Visual Studio)

# Open the solution file
Orderbook.sln

# Build using Visual Studio or MSBuild
msbuild Orderbook.sln /p:Configuration=Release

Running Tests

# Build and run the test project
cd OrderbookTest
# Tests use Google Test framework
# Run from Visual Studio Test Explorer or command line

Usage Example

#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;
}

Testing

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.txt
  • Match_Market.txt
  • Match_FillAndKill.txt
  • Match_FillOrKill_Hit.txt
  • Match_FillOrKill_Miss.txt
  • Cancel_Success.txt
  • Modify_Side.txt

Performance Characteristics

  • 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

License

This project is available under the MIT License. See the LICENSE file for details.

Contributing

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

Architecture Notes

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.

About

No description, website, or topics provided.

Resources

License

MIT, MIT licenses found

Licenses found

MIT
LICENSE
MIT
LICENSE.txt

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors