Sub topic 5
How a buyer and a seller are matched
This chapter assumes you know what a bid and an ask price are, and that your broker sends your order to a trading venue. Here you look inside the venue, at the order book and the rules that pair one order with another. By the end you should be able to trace an order through a book by hand and explain why you can pay less than your limit price.
The order book
A trading venue keeps one limit order book for each stock. The book holds every limit order that has been accepted but not yet fully traded. These are called resting orders, because they wait in the book until someone trades against them. The book has two sides:
- The bid side holds buy orders. The best bid is the highest price.
- The ask side (also called the offer side) holds sell orders. The best ask is the lowest price.
The gap between the best bid and the best ask is the spread. A later chapter covers its cost. For matching, what matters is that the book is uncrossed while it rests: the best bid is always below the best ask. If a buyer is willing to pay at least what a seller will accept, a trade happens immediately, so such an order never rests as it arrived.
An order that trades on arrival is called marketable. A resting order is called a maker of liquidity, and the order that trades against it is the taker.
| Side | Price | Quantity | Arrived |
|---|---|---|---|
| Ask | 10.03 | 200 | 3rd |
| Ask | 10.02 | 100 | 1st |
| Ask | 10.01 | 50 | 2nd |
| Bid | 10.00 | 300 | 4th |
| Bid | 9.99 | 150 | 5th |
Here the best ask is 10.01 and the best bid is 10.00, so the spread is 0.01.
Price-time priority
Most equity venues use price-time priority, also called FIFO (first in, first out). It ranks resting orders by two rules, applied in order:
- Price first. A higher bid or a lower ask is ahead of any worse-priced order, regardless of when it arrived.
- Time second. Among orders at the same price, the earliest arrival is ahead.
An incoming order is matched against the opposite side, best-ranked order first. Matching continues until the incoming order is filled, or until the next resting order's price is no longer acceptable.
Price priority rewards aggressive pricing. Time priority rewards early commitment. Together they give traders a reason to quote tight spreads and to quote early.
Trading at the resting order's price
Trades execute at the resting order's price, not at the incoming order's limit. The resting order announced its price first, and it is entitled to that price. The incoming order only says the worst price it will accept.
This is why a limit order can fill at a better price than the limit. The improvement is a direct result of the rule, and nobody grants it as a favor. In the table above, a buy limit at 10.02 for 120 shares would trade first with the ask at 10.01, then with the ask at 10.02. It would never touch 10.03, because that is above its limit.
A working example
The code below is a minimal book. Bids are stored as (-price, arrival_seq, qty) in a min-heap, so the smallest tuple is the highest price, and ties on price go to the lowest arrival number. Asks use (price, arrival_seq, qty).
import heapq
from itertools import count
seq = count()
bids = [] # entries: (-price, arrival_seq, qty); highest price first
asks = [] # entries: (price, arrival_seq, qty); lowest price first
def submit(side, price, qty):
"""Match a limit order against the book using price-time priority.
Returns a list of (trade_price, trade_qty). Unfilled quantity rests in the book."""
fills = []
order_seq = next(seq)
if side == "buy":
while qty and asks and asks[0][0] <= price:
ask_price, ask_seq, ask_qty = heapq.heappop(asks)
traded = min(qty, ask_qty)
fills.append((ask_price, traded))
qty -= traded
if ask_qty > traded:
heapq.heappush(asks, (ask_price, ask_seq, ask_qty - traded))
if qty:
heapq.heappush(bids, (-price, order_seq, qty))
else:
while qty and bids and -bids[0][0] >= price:
neg_price, bid_seq, bid_qty = heapq.heappop(bids)
traded = min(qty, bid_qty)
fills.append((-neg_price, traded))
qty -= traded
if bid_qty > traded:
heapq.heappush(bids, (neg_price, bid_seq, bid_qty - traded))
if qty:
heapq.heappush(asks, (price, order_seq, qty))
return fills
submit("sell", 10.02, 100)
submit("sell", 10.01, 50)
print(submit("buy", 10.02, 120)) # [(10.01, 50), (10.02, 70)]Follow the last call step by step:
- The best ask is 10.01 for 50. It is at or below the limit of 10.02, so 50 shares trade at 10.01. Seventy shares remain.
- The next ask is 10.02 for 100, and 10.02 is still within the limit. Seventy shares trade at 10.02.
- The resting order at 10.02 had 100 shares and now has 30. The code pushes it back with its original arrival number, so it keeps its place in the queue.
- The buyer's quantity is now zero, so nothing rests on the bid side.
The buyer's average price is (50 × 10.01 + 70 × 10.02) / 120, about 10.0158, below the 10.02 limit.
Market orders and walking the book
A market order has no price limit. It trades against whatever is best, then the next best, until it is filled. When one order consumes several price levels, it is said to walk the book.
Using the book from the table, a market buy for 400 shares would trade as follows:
| Step | Price | Shares taken | Cumulative |
|---|---|---|---|
| 1 | 10.01 | 50 | 50 |
| 2 | 10.02 | 100 | 150 |
| 3 | 10.03 | 200 | 350 |
| 4 | next ask above 10.03 | 50 | 400 |
The last 50 shares go at whatever price comes next, which is unknown when you send the order. The difference between the price you saw and the average price you got is called slippage. It grows with order size and shrinks in deep, liquid books.
A market order never rests in the book. If the book empties before the order is filled, most venues cancel the unfilled part. Many venues also add protections, such as price collars, that reject or cancel an order that would trade too far from the current price.
Partial fills and the resting remainder
A limit order can be partially filled. If the buyer in the example had asked for 200 shares at 10.02, the code would fill 150 and then rest the final 50 on the bid side at 10.02. That remainder is now the best bid and waits for a seller.
Partial fills explain why your broker's app can show "filled 150 of 200". They also affect cost: each fill may be reported separately, and some brokers charge per execution.
Priority is fragile
Queue position is valuable, and several actions affect it:
- Cancelling removes the order and its place.
- Reducing size usually keeps priority on most venues.
- Increasing size or changing the price usually counts as a new order with a new arrival time, so the order goes to the back of the queue.
- A better price puts you ahead of everyone at worse prices, whatever their age. Improving the best bid by one tick moves you to the front of the book.
The tick size is the smallest allowed price increment. In the US, stocks priced at or above $1 generally quote in whole cents. Tick size limits how finely you can jump ahead. With a one-cent tick, a trader who wants priority must pay at least a cent more, which keeps queues at popular prices long.
Details that matter in real systems
The example is deliberately small. Production venues differ in several ways.
- Integer prices. The example uses floats for readability. Real engines store prices as integers (for example, hundredths of a cent) because floating-point comparison can misorder or mismatch prices like 10.01 and 10.02 after arithmetic.
- Price levels with queues. Engines usually keep one first-in-first-out queue per price and an ordered structure of price levels. A heap cannot cancel an order in the middle efficiently, and cancellations are the most common message on a venue.
- Order types beyond limit and market. Examples are immediate-or-cancel (fill what you can now, cancel the rest), fill-or-kill (all or nothing), and post-only (reject rather than take liquidity). They change only what happens to the remainder, not the matching rule.
- Auctions. Many exchanges open and close the day with an auction. Orders collect, and one price is chosen that maximizes the shares traded. Everyone who trades gets that single price.
- Other priority rules. Some markets, such as some futures contracts, use pro-rata allocation, where orders at the best price share a fill in proportion to size, instead of strict time order.
- Self-trade prevention. A firm's own buy and sell orders can be stopped from matching each other.
- Fairness across venues. In the US, rules require venues to protect the best displayed quotes nationwide. A venue's book is therefore not the only thing that determines your price, which is the topic of the routing and venue chapters.
Common mistakes
- Assuming you always pay your limit. You pay the resting price, which can be better.
- Assuming a limit buy at the current ask waits. If your limit is at or above the best ask, it trades immediately.
- Assuming earlier always wins. Earlier wins only at the same price. A later order at a better price goes first.
- Treating a market order as risk-free. It trades at the available prices, however far they sit from the quote you saw.
- Expecting a resized order to keep its place. Increasing size or moving the price usually sends it to the back of the queue.
Exercise
The book has asks of 40 shares at 20.05 (arrived first), 60 shares at 20.05 (arrived second), and 100 shares at 20.06. You submit a buy limit order for 120 shares at 20.05. What are the fills, and what happens to the rest of your order?
Show answer
Both 20.05 orders are within your limit, and the 20.06 ask is above it. Time priority fills the first 20.05 order for 40 shares, then the second for 60 shares, giving fills of (20.05, 40) and (20.05, 60). That is 100 shares in total. The remaining 20 shares cannot trade at 20.05 or lower, so they rest on the bid side at 20.05 as the best bid. The 20.06 ask stays untouched.
Exercise
A resting sell order for 100 shares at 15.00 sits in the book. An incoming buy limit order for 100 shares at 15.10 arrives. At what price does the trade happen, and why?
Show answer
At 15.00. Trades execute at the resting order's price, and the incoming limit of 15.10 only sets the highest price the buyer will accept. The buyer gets 0.10 per share of price improvement.