Matching Logic

Core price-time prioerity logic explained

The matching engine implements a continuous limit order book with price-time priority.

Order Book Structure

Orderbook {
    bids: BTreeMap<OrderbookKey, Order>,  // Sorted high-to-low
    asks: BTreeMap<OrderbookKey, Order>,  // Sorted low-to-high
}

OrderbookKey {
    price: i64,      // Negated for bids
    timestamp: u64,
    order_id: OrderId,
}
  • Bids: Price negated so BTreeMap iteration yields highest prices first

  • Asks: Price as-is so iteration yields lowest prices first

  • Tie-breaking: Secondary sort by (timestamp, order_id) for FIFO at same price level

Matching Algorithm

while best_bid.price >= best_ask.price:
    1. Prune any zero-quantity orders at top of book
    2. Check crossing conditions (price, market_id, self-trade)
    3. Determine maker (earlier timestamp wins)
    4. Execute at maker's price
    5. Update quantities; remove exhausted orders

Maker Determination

The order that arrived first is the maker; the match executes at the maker's price. This protects passive liquidity providers.

Partial Fills

When order quantities differ:

  • Smaller order is fully filled and removed

  • Larger order has quantity decremented; remains in book

  • Multiple trades may result from a single aggressive order

Trade Output

Safety Checks

  • Cross-market prevention: Matching stops if bid.market_id != ask.market_id

  • Self-trade prevention: Optional flag stops matching if bid.account_id == ask.account_id


Last updated