Sub topic 5
How the matching engine fills orders
This chapter assumes you can read the order book (best bid, best ask, depth) and know the difference between a market and a limit order. You should also be comfortable reading short Python programs. Earlier chapters covered those ideas. Here we look at the component that connects them.
What the matching engine does
The matching engine is the program inside the exchange that accepts incoming orders and decides which ones trade against each other. It owns the order book. Nothing else on the exchange changes the book, and every fill you see started in the engine.
Each incoming order is handled in one of three ways:
- It trades fully against resting orders and disappears.
- It trades partly, and the rest either rests on the book (limit) or is cancelled (market).
- It trades not at all and rests on the book (a limit order that does not cross).
Two terms from this chapter are used throughout:
- Resting order (maker): an order already on the book, waiting for a counterparty.
- Incoming order (taker): the order the engine is processing right now.
An incoming order is called marketable if it can trade immediately. A market order always is. A limit buy is marketable if its price is at or above the best ask. A limit sell is marketable if its price is at or below the best bid.
Price-time priority
Most spot crypto exchanges use price-time priority, also called FIFO (first in, first out). The engine ranks resting orders by two keys, in this order:
- Price. For bids, higher is better. For asks, lower is better.
- Time. Among orders at the same price, the one that arrived first is filled first.
The first rule is why the best prices always trade first. The second rule rewards early arrivals. Joining a queue at 100.0 puts you behind everyone already there. Someone who arrives later at 100.0 is behind you.
An incoming order consumes liquidity from the best price level, and within that level from the front of the queue. When the level is empty it moves to the next level, which is the "walking the book" behavior described in the slippage chapter.
The trade price is the resting order's price
When two orders match, the trade executes at the resting order's price, not the incoming order's price. This has a visible consequence. A buyer who submits a limit at 101.0 against an ask at 100.5 pays 100.5. The limit price is a worst-case bound, not the price you pay. The gap between your limit and the actual fill is called price improvement.
The rule is also fair to the maker. The maker named a price and waited, so the maker gets that price or better.
The matching loop
The core algorithm is short:
- Take the incoming order and look at the best opposite-side level.
- If there is no opposite-side order, stop.
- If the order is a limit order and the best opposite price is worse than its limit, stop.
- Trade
min(remaining, resting size)at the resting price. - Remove the resting order if it is fully filled, then go back to step 1.
- When the loop stops with quantity left over, a limit order rests on the book. A market order is cancelled for the remainder.
A minimal matching engine in Python
The following code implements the loop above. Each side of the book is a heap. Bids are stored with a negated price so that the highest bid sorts first. Each entry carries the order's sequence number, which gives the time priority. The sequence number is unique, so Python never has to compare the order dictionaries.
import heapq
from itertools import count
class Book:
def __init__(self):
self.bids = [] # heap of (-price, seq, order)
self.asks = [] # heap of (price, seq, order)
self._seq = count() # doubles as order id and time priority
def submit(self, side, qty, price=None):
"""Match an order. price=None means a market order.
Returns (order_id, trades, remaining_qty).
Each trade is (maker_id, taker_id, trade_price, qty)."""
order_id = next(self._seq)
remaining = qty
trades = []
opposite = self.asks if side == "buy" else self.bids
while remaining > 0 and opposite:
key, _, maker = opposite[0]
maker_price = key if side == "buy" else -key
if price is not None:
if side == "buy" and maker_price > price:
break
if side == "sell" and maker_price < price:
break
take = min(remaining, maker["qty"])
maker["qty"] -= take
remaining -= take
trades.append((maker["id"], order_id, maker_price, take))
if maker["qty"] == 0:
heapq.heappop(opposite)
if remaining > 0 and price is not None:
own = self.bids if side == "buy" else self.asks
key = -price if side == "buy" else price
heapq.heappush(own, (key, order_id, {"id": order_id, "qty": remaining}))
return order_id, trades, remaining
book = Book()
book.submit("sell", 2, 100.0) # id 0, first in the 100.0 queue
book.submit("sell", 1, 100.0) # id 1, behind id 0
book.submit("sell", 3, 100.5) # id 2
book.submit("buy", 2, 99.5) # id 3, a resting bid
_, trades, left = book.submit("buy", 4) # id 4, market buy
print(trades, left)
# [(0, 4, 100.0, 2), (1, 4, 100.0, 1), (2, 4, 100.5, 1)] 0
_, trades, left = book.submit("buy", 5, 101.0) # id 5, limit above the best ask
print(trades, left)
# [(2, 5, 100.5, 2)] 3
_, trades, left = book.submit("sell", 1, 100.0) # id 6, limit sell below the best bid
print(trades, left)
# [(5, 6, 101.0, 1)] 0Read the three results in turn:
- Market buy of 4. Order 0 fills before order 1 because both are at 100.0 and 0 arrived first. The last unit comes from 100.5. The average price is (2 × 100.0 + 1 × 100.0 + 1 × 100.5) / 4 = 100.125.
- Limit buy of 5 at 101.0. Only 2 units remain on the ask side, and they trade at 100.5, the resting price, not 101.0. The other 3 units rest as a bid at 101.0.
- Limit sell of 1 at 100.0. The best bid is now the resting 101.0 bid (id 5), so the sell trades at 101.0. The seller receives more than the limit asked for, which is price improvement for sellers.
Edge cases to know
| Situation | What usually happens | Why it matters |
|---|---|---|
| Market order on an empty or thin opposite side | The order fills what exists. The remainder is cancelled or the order is rejected, depending on the exchange. | You can end up with less than you asked for. Check the filled quantity. |
| Limit order priced through the spread | It trades immediately as a taker at the resting prices, and any remainder rests. | You pay taker fees on the part that trades. |
| Increasing the size or changing the price of a resting order | Most exchanges treat this as a cancel and re-add, so you go to the back of the queue. | Amending can cost you queue position. |
| Reducing the size of a resting order | Many exchanges keep your queue position. Some do not. | Behavior is exchange-specific, so read the documentation. |
| Your own orders on both sides | Without self-trade prevention, your buy can match your own sell. | Wash trades distort volume and still cost fees. Many exchanges offer a self-trade prevention setting. |
| Two orders arrive at nearly the same moment | The engine processes them one at a time in the order it received them. | There is no "simultaneous" fill. The exchange's receive order is the only order that counts. |
Not every venue uses price-time priority
Price-time priority is the common rule on spot crypto exchanges, but it is not universal. Some derivatives venues use pro-rata matching, where the incoming order is split across all resting orders at the best price in proportion to their sizes. Others give priority to larger orders or market makers. If a venue documents something different, your queue-position reasoning changes with it. The price rule (best price first, trade at the resting price) holds almost everywhere.
Why the engine is sequential
A matching engine must produce one consistent history. If two orders raced to consume the same resting order, the result would be ambiguous. Exchanges therefore feed all orders for one market into a single sequence and process them one by one, which is why the Python code above needs no locks inside one book. Speed comes from making each step very cheap, not from processing one market's orders in parallel. The practical effect for you is latency: what matters is when your order reaches the engine, and network delay between you and the exchange counts against you.
Summary of the rules
- Orders are ranked by price, then by arrival time.
- Trades execute at the resting order's price.
- An incoming order consumes levels from the best price outward until it is filled, its limit stops it, or the book runs out.
- A limit order's unfilled remainder rests on the book. A market order's unfilled remainder is cancelled.
- Changing a resting order can reset your queue position.
Exercise
The ask side of a book holds, in arrival order, A: 1 unit at 100.0, B: 2 units at 100.0, and C: 4 units at 100.5. You submit a limit buy for 5 units at 100.5. Which resting orders trade, at what prices and sizes, how much of your order rests, and what is your average fill price?
Show answer
A fills 1 at 100.0 and B fills 2 at 100.0, because price is equal and A arrived first. Then C fills 2 at 100.5, because only 2 units are needed to reach 5. All 5 units trade, so nothing rests. Average price = (1 × 100.0 + 2 × 100.0 + 2 × 100.5) / 5 = 501 / 5 = 100.2. C keeps 2 units at 100.5.
Exercise
A trader has a resting buy of 10 units at 99.0 and wants to raise the size to 15 units at the same price. Why might this cost them, and how could they avoid losing queue position?
Show answer
Many exchanges treat a size increase as a cancel and re-add, which sends the order to the back of the queue at 99.0. To keep their position, the trader can leave the 10-unit order in place and place a separate 5-unit order at 99.0. The new order joins the back of the queue, but the original 10 units keep their place.