Skip to content

Order Book Implementation

An order book is a fundamental component of electronic trading systems that maintains a real-time list of buy and sell orders for a financial instrument. It enables price discovery, order matching, and market depth analysis.

Core Concepts

Order Book Structure

  • Buy Side (Bids): Orders to buy, sorted by price (highest first) and time (FIFO)
  • Sell Side (Asks): Orders to sell, sorted by price (lowest first) and time (FIFO)
  • Order Matching: Automatic crossing of compatible buy and sell orders
  • Market Depth: Aggregated quantity at each price level

Order Types

cpp
enum class Side { BUY, SELL };

struct Order {
    uint64_t order_id;     // Unique identifier
    double price;          // Limit price
    uint64_t quantity;     // Order size
    Side side;             // Buy or sell
    uint64_t timestamp;    // Order entry time
};

Key Operations

1. Add Order

  • Validate order parameters
  • Check for immediate matching opportunities
  • Place remaining quantity in appropriate side
  • Update market depth

2. Cancel Order

  • Remove order from the book
  • Update aggregated quantities
  • Maintain FIFO ordering

3. Modify Order

  • Cancel existing order
  • Add new order with updated parameters
  • Preserve time priority if price unchanged

4. Order Matching (Crossing)

  • Match incoming orders against opposite side
  • Execute trades at the resting order's price
  • Handle partial fills and complete fills
  • Maintain FIFO execution order

Implement a complete order book system that supports add, cancel, modify operations and automatically crosses orders on a FIFO basis. The system should maintain separate buy and sell sides, handle order matching, and provide market depth information.

cpp
#include <iostream>
#include <cstdint>
#include <stdexcept>
#include <utility>
#include <map>
#include <unordered_map>
#include <list>
#include <vector>

enum class Side { BUY, SELL };

struct Order {
    uint64_t order_id;
    uint64_t price;  // Price in smallest unit (e.g., cents for dollars)
    uint64_t quantity;
    Side side;
    uint64_t timestamp;

    Order(uint64_t id, uint64_t p, uint64_t qty, Side s, uint64_t ts = 0)
        : order_id(id), price(p), quantity(qty), side(s), timestamp(ts) {}
};

struct Trade {
    uint64_t buy_order_id;
    uint64_t sell_order_id;
    double price;
    uint64_t quantity;

    Trade(uint64_t buy_id, uint64_t sell_id, double p, uint64_t qty)
        : buy_order_id(buy_id), sell_order_id(sell_id), price(p), quantity(qty) {}
};

class OrderBook {
private:
    uint64_t next_timestamp_ = 0;

public:
    OrderBook() = default;

    // TODO: Implement add order functionality
    // - Check for duplicate order IDs
    // - Try to match against opposite side first
    // - Place remaining quantity in appropriate side
    // - Update aggregated quantities
    // - Return vector of executed trades
    std::vector<Trade> addOrder(Order order) {
        // TODO: Implement order matching and book placement
        return {};
    }

    // TODO: Implement cancel order functionality
    // - Find order by ID
    // - Remove from price level
    // - Update aggregated quantities
    // - Handle case where order doesn't exist
    void cancelOrder(uint64_t order_id) {
        // TODO: Implement order cancellation
    }

    // TODO: Implement modify order functionality
    // - Cancel existing order
    // - Add new order with updated parameters
    // - Preserve time priority if price unchanged
    std::vector<Trade> modifyOrder(Order order) {
        // TODO: Implement order modification
        return {};
    }

    // TODO: Implement get best bid price
    // - Return highest buy price or 0 if no bids
    uint64_t getBestBid() const {
        // TODO: Implement best bid retrieval
        return 0;
    }

    // TODO: Implement get best ask price
    // - Return lowest sell price or 0 if no asks
    uint64_t getBestAsk() const {
        // TODO: Implement best ask retrieval
        return 0;
    }

    // TODO: Implement get market depth
    // - Return number of price levels on specified side
    uint64_t getDepth(Side side) const {
        // TODO: Implement depth calculation
        return 0;
    }

    // TODO: Implement get level info
    // - Return price and quantity for specified level
    // - Level 0 is best price, level 1 is second best, etc.
    std::pair<uint64_t, uint64_t> getLevelInfo(Side side, uint64_t level) const {
        // TODO: Implement level info retrieval
        return {0, 0};
    }

    // TODO: Implement get total quantity at price
    // - Return total quantity at specified price level
    uint64_t getQuantityAtPrice(uint64_t price, Side side) const {
        // TODO: Implement quantity lookup
        return 0;
    }

    // Helper function to generate timestamps
    uint64_t getNextTimestamp() {
        return ++next_timestamp_;
    }

    // Helper function to check if prices cross
    bool pricesCross(uint64_t buy_price, uint64_t sell_price) const {
        return buy_price >= sell_price;
    }
};