Matching Engine
The matching engine is the core of the OrderBook contract, responsible for organizing orders by price and executing trades when compatible orders meet.Price Tree Structure
Orders are organized using Red-Black Trees for efficient price-level management:Why Red-Black Trees?
| Operation | Complexity | Benefit |
|---|---|---|
| Insert price level | O(log n) | Fast order placement |
| Remove price level | O(log n) | Efficient level removal |
| Find best price | O(1)* | Instant best bid/ask lookup |
| Find next price | O(log n) | Quick iteration through prices |
Order Queues
At each price level, orders are stored in a FIFO queue:Queue Structure
Queue Operations
| Operation | Description |
|---|---|
| Enqueue | Add new order at tail |
| Dequeue | Remove filled order from head |
| Peek | View head order without removal |
Matching Algorithm
Price-Time Priority
The matching engine follows strict price-time priority:-
Price Priority: Best prices match first
- Buy orders: Highest bid first
- Sell orders: Lowest ask first
- Time Priority: At same price, FIFO order
Matching Process
Match Execution
For each potential match:Iteration Limits
To prevent gas exhaustion, matching has configurable limits:| Limit | Purpose |
|---|---|
maxIterations | Maximum price levels to traverse |
maxOrdersPerLevel | Maximum orders to match at single price |
Gas-Bounded Matching
If limits are reached:- IOC/FOK: Cancel remaining
- GTC: Remaining quantity rests in book
Price Level Management
Adding a Price Level
When the first order arrives at a new price:Removing a Price Level
When the last order at a price is filled/cancelled:Spread and Best Prices
Spread Definition
Best Price Tracking
The engine maintains pointers to best prices for O(1) access:- Order placement (if improves best)
- Order cancellation (if was best)
- Order fill (if empties best level)
Cross-Spread Execution
When a new order’s price crosses the spread:Buy Order Crossing Ask
Execution Price
Trades execute at the maker’s price (resting order):- Buy crossing ask: Executes at ask price
- Sell crossing bid: Executes at bid price
Performance Characteristics
Time Complexity
| Operation | Average | Worst |
|---|---|---|
| Place order (no match) | O(log n) | O(log n) |
| Place order (with match) | O(log n + m) | O(n) |
| Cancel order | O(log n) | O(log n) |
| Get best price | O(1) | O(1) |
- n = number of price levels
- m = number of orders matched
Space Complexity
| Structure | Size |
|---|---|
| Price tree | O(n) price levels |
| Order queues | O(m) total orders |
| Order storage | O(m) orders |
Hooks Integration
The matching engine can trigger hooks at key points: Hooks can:- Validate orders against custom rules
- Log trading activity
- Trigger external integrations
- Implement trading restrictions