Matching Engine

The matching engine is responsible for executing trades when compatible orders meet.

Order Book Structure

The order book maintains two sides:
SideContainsBest Price
Bids (Buy)Buy ordersHighest price
Asks (Sell)Sell ordersLowest price
The spread is the difference between the best ask and best bid prices.

Price-Time Priority

All matching follows strict price-time priority:

Price Priority

  • Buy orders: Highest prices have priority
  • Sell orders: Lowest prices have priority
  • A trade occurs when bid price >= ask price

Time Priority

At the same price level, orders are filled in the sequence they were placed (first-in, first-out).

Execution Behavior

When Orders Match

A new order that crosses the spread executes immediately:
New OrderMatches AgainstExecution Price
Buy at 101Resting ask at 100100 (maker’s price)
Sell at 99Resting bid at 100100 (maker’s price)
Trades always execute at the maker’s price (the resting order), providing price improvement for takers.

Partial Fills

Orders may be partially filled:
  • The filled portion settles immediately
  • Remaining quantity behavior depends on TimeInForce:
    • GTC: Rests in book
    • IOC: Cancelled
    • FOK: Entire order cancelled (no partial execution)

Gas Considerations

To ensure predictable gas costs, matching operations have configurable limits. If an order cannot be fully processed within gas limits:
  • IOC/FOK orders: Remaining quantity is cancelled
  • GTC orders: Remaining quantity rests in the book
This ensures orders never fail due to unbounded gas consumption.

Best Price Queries

Query current market state:
// Get best bid or ask
PriceVolume memory best = router.getBestPrice(
    baseCurrency,
    quoteCurrency,
    Side.Buy  // or Side.Sell
);

// Get multiple price levels
PriceVolume[] memory depth = router.getNextBestPrices(
    pool,
    Side.Sell,
    0,     // start from best
    10     // number of levels
);

Hooks Integration

The matching engine supports hooks at key points:
Hook PointUse Cases
Pre-orderCustom validation, trading restrictions
Post-matchLogging, external integrations
Hooks can reject orders that don’t meet custom criteria.