Matching Engine
Order matching behavior and execution
Matching Engine
The matching engine is responsible for executing trades when compatible orders meet.
Order Book Structure
The order book maintains two sides:
| Side | Contains | Best Price |
|---|---|---|
| Bids (Buy) | Buy orders | Highest price |
| Asks (Sell) | Sell orders | Lowest 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 Order | Matches Against | Execution Price |
|---|---|---|
| Buy at 101 | Resting ask at 100 | 100 (maker's price) |
| Sell at 99 | Resting bid at 100 | 100 (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 Point | Use Cases |
|---|---|
| Pre-order | Custom validation, trading restrictions |
| Post-match | Logging, external integrations |
Hooks can reject orders that don't meet custom criteria.