insideout Get Pro

03 · Matching a trade

Free

Markets, lesson 3

Matching a trade

An order that crosses the spread trades at the waiting orders' prices.

So far every order has waited in the book. This lesson follows the order that doesn't: one that can trade the moment it arrives. You need the order book and price-time priority: best price first, then first come, first served.

By the end, you can:

  1. Tell whether a new order trades on arrival or waits in the book.
  2. Find the price a crossing order trades at, and name the maker and the taker.
  3. Fill an order across several prices, and place what's left in the book.
  4. List every fill when several orders arrive one after another.

Part 1. Crossing the spread

Tell whether a new order trades on arrival or waits in the book.

The moment an order arrives, the exchange asks one question: is anyone on the other side willing to trade with it right now? The answer depends only on the order's price and the best price opposite.

Example 1.1

Four orders, one book

GULL's bids are 300 at 99 and 300 at 98. Its asks are 300 at 101, 400 at 102 and 500 at 103. Take each order on its own, against this book: a buy at 100, a buy at 102, a sell at 99 and a sell at 100. Which ones trade on arrival?

  1. A buy at 100100 < 101

    No seller takes 100, so it waits. It becomes the new best bid, and the spread shrinks to 1.

  2. A buy at 102102 ≥ 101

    It pays at least what the best seller asks, so it trades at once.

  3. A sell at 9999 ≤ 99

    It takes what the best buyer pays, so it trades too.

  4. A sell at 100100 > 99

    No buyer pays 100. It waits as the new best ask.

AnswerThe buy at 102 and the sell at 99 trade. The other two wait in the book.

a new buya new sellbidsasks1035001024001013001009930098300tradesat oncewaits inthe bookwaits inthe booktradesat once
Figure 1Where a new order lands. A buy at 101 or more reaches the asks and trades. A sell at 99 or less reaches the bids. Anything in between waits.

A buy has to reach up to the best ask, and a sell has to reach down to the best bid. An order priced inside the gap reaches nobody, so it joins the book and the gap shrinks. An order that reaches across finds someone at once.

Crossing the spread

A buy priced at or above the best ask, or a sell at or below the best bid, crosses the spread and trades on arrival. An order that doesn't cross rests in the book.

a buy crosses if price ≥ best ask; a sell if price ≤ best bid

Mind the equals sign. A buy at exactly the best ask crosses: it doesn't need to beat it. And a buy never trades with the bids below it. Buyers only ever trade with sellers, however close their prices.

Your turn

A stock's best bid is 50.00 and its best ask is 50.04. Which of these orders trades on arrival?

A sell crosses at or below the best bid, and 50.00 is exactly the best bid. The two buys don't reach 50.04, and the sell at 50.01 asks more than any buyer pays. Those three rest inside the spread.

Part 2. The waiting order sets the price

Find the price a crossing order trades at, and name the maker and the taker.

A crossing order names a price, and the order it meets names another. A sell at 97 might meet a bid at 99. The trade can only happen at one of them.

Example 2.1

A sell with room to spare

GULL's best bid is 99, for 300 shares. You send a sell for 200 shares at 97. At what price do you trade, and how much money do you get?

  1. Check that it crosses97 ≤ 99

    You'll take less than the best buyer pays.

  2. Use the waiting order's price99

    The bid at 99 was there first, and its price stands. Your 97 was only the least you'd accept.

  3. Work out the money200 × 99 = 19,800

    At your own price it would have been 200 × 97 = 19,400.

Answer200 shares at 99, for 19,800: 400 more than your price promised.

Your price is the worst you'll accept, not an offer to trade there. The waiting order showed its price first, and whoever crosses it gets that price. So when your price was more generous than it needed to be, the difference stays with you.

Maker and taker

The waiting order made the price, so its owner is the maker. The order that arrived and traded took it, so its owner is the taker.

trade price = the maker's price

One order can be both: a taker for the shares it trades on arrival, and a maker for any it leaves resting, which trade later at its own price. Many exchanges charge makers and takers different fees, which "Queue position and fees" takes up.

Your turn

The best ask is 101, with 300 shares. You send a buy for 200 at 104. What do you pay per share?

The seller asked 101, so 101 is the price. A limit is your worst case, and the book gives you better when it can.

Part 3. Filling up to a limit

Fill an order across several prices, and place what's left in the book.

An order bigger than the best price's size walks the book, as in "What an exchange is". Now give it a price it won't go past, and follow it to where it stops.

Example 3.1

A sell for 800 at 98

GULL's bids are 300 at 99, 300 at 98 and 600 at 97, and its best ask is 101. You send a sell for 800 shares at 98. What fills, what's left, and what does the book look like after?

  1. Take the best bid300 × 99 = 29,700

    99 is better than your 98, so it trades.

  2. Move down a price300 × 98 = 29,400

    Exactly your price, so it still trades. 600 filled, 200 to go.

  3. Stop at your price97 < 98

    The next bid is below the least you'll accept. Matching stops.

  4. Rest the leftover200 at 98

    The rest waits in the book as an ask at 98. It's a maker now.

Answer600 fill, for 59,100. The other 200 become the best ask, at 98.

Beforebidpriceask101300100993009830097600Afterbidpriceask101300100999820097600sell 800at 98600 fill200 rest
Figure 2Before and after. The sell takes the bids at 99 and 98, and its last 200 shares wait at 98. The best ask moves from 101 down to 98.

Your price is a wall the order won't go past, so matching stops there. The leftover doesn't vanish: it rests at that price, and here it moved the whole market. The best ask was 101. Now it's 98, one above the best bid of 97.

Limit price and partial fill

The price on an order is its limit price: the worst price it will trade at. An order that trades only some of its shares gets a partial fill, and the rest waits in the book at its limit.

The limit is also your protection. Without one, the sell for 800 would have taken its last 200 at 97. To trade what's there now and never wait, an order needs a different instruction, which "Order types, cancels and amends" covers.

Your turn

The asks are 300 at 101, 400 at 102 and 500 at 103. You buy 1,000 with a limit of 102. What happens?

300 at 101 and 400 at 102 are within your limit. 103 isn't, so matching stops at 700. The other 300 wait in the book at 102.

Part 4. One order at a time

List every fill when several orders arrive one after another.

An exchange handles orders one at a time, in the order they arrive, and each one can change the book for the next. To follow it, number every order and list every fill.

Example 4.1

Three orders in a row

The bids are #1 for 200 at 99, then #2 for 100 at 99, and #3 for 300 at 98. The asks are #4 for 200 and #5 for 100 at 101, #6 for 400 at 102, and #7 for 300 and #8 for 200 at 103. Three orders arrive in turn: a sell for 250 at 99, a buy for 800 at 102, and a sell for 400 at 97. List every fill.

  1. Sell 250 at 99#1 200 @ 99, #2 50 @ 99

    #1 came first and fills in full. #2 gets the last 50 and keeps 50.

  2. Buy 800 at 102#4 200 @ 101, #5 100 @ 101, #6 400 @ 102

    It walks 101, then 102. 103 is past its limit, so 700 fill and the last 100 rest as a bid at 102.

  3. Sell 400 at 97100 @ 102, #2 50 @ 99, #3 250 @ 98

    The buy's leftover at 102 is now the best bid. Then 50 at 99 and 250 at 98. It never reaches 97.

  4. Read the bookbid 50 @ 98, asks 500 @ 103

    #3 keeps 50 at 98, and #7 and #8 wait at 103. The spread opened from 2 to 5.

AnswerEight fills. The book ends with a bid of 50 at 98 and asks of 500 at 103.

Each order meets the book the last one left. The buy's leftover sat at the front at 102, so the last sell met it first. Swap the last two orders and the fills change: the sell would leave 50 resting at 97, and the buy would take them first.

Matching engine and fill

The matching engine is the exchange's program that takes orders one at a time, matches each against the book by its priority rule, and rests what's left. Each match between the arriving order and one waiting order is a fill, with its own size and price.

Your turn

Asks wait at 51 from #2 for 300, then #3 for 200, and at 52 from #4 for 500. A buy for 600 at 52 arrives. What are its fills?

Best price first: both asks at 51, oldest first, so #2 then #3, each at the maker's price of 51. The last 100 come from #4 at 52, within the limit, so nothing rests. #4 keeps 400 waiting.

Where you'll meet it

On a real exchange

Nasdaq's rulebook gives part 2 as its own example: a bid rests at 10, a sell priced at 9 arrives, and the trade happens at 10, so the seller gets $1 of price improvement. The London Stock Exchange's trading guide says the same: an order that can trade at once executes at the resting order's price.

In interviews

Writing a matching engine is a classic quant developer coding question: limit orders, partial fills, price-time priority and the leftover resting. The loop below is the core of most answers, run on the example from part 4. Expect follow-ups on cancels, order types and speed.

A matching engine, in Python
from collections import deque

class Book:
    def __init__(self):
        # side -> {price: queue of [order id, shares]}, oldest first
        self.levels = {"buy": {}, "sell": {}}

    def best(self, side):
        prices = self.levels[side]
        if not prices:
            return None
        return max(prices) if side == "buy" else min(prices)

    def submit(self, oid, side, size, limit):
        other = "sell" if side == "buy" else "buy"
        fills = []
        while size > 0:
            price = self.best(other)
            if price is None:
                break
            if side == "buy" and price > limit:
                break
            if side == "sell" and price < limit:
                break
            queue = self.levels[other][price]
            maker = queue[0]                 # oldest order at the best price
            take = min(size, maker[1])
            fills.append((maker[0], take, price))
            size -= take
            maker[1] -= take
            if maker[1] == 0:
                queue.popleft()
                if not queue:
                    del self.levels[other][price]
        if size > 0:                         # the rest waits at its limit
            self.levels[side].setdefault(limit, deque()).append([oid, size])
        return fills

book = Book()
for oid, side, size, price in [
        (1, "buy", 200, 99), (2, "buy", 100, 99), (3, "buy", 300, 98),
        (4, "sell", 200, 101), (5, "sell", 100, 101),
        (6, "sell", 400, 102), (7, "sell", 300, 103), (8, "sell", 200, 103)]:
    book.submit(oid, side, size, price)

print(book.submit(9, "sell", 250, 99))    # [(1, 200, 99), (2, 50, 99)]
print(book.submit(10, "buy", 800, 102))   # [(4, 200, 101), (5, 100, 101), (6, 400, 102)]
print(book.submit(11, "sell", 400, 97))   # [(10, 100, 102), (2, 50, 99), (3, 250, 98)]
print("best bid", book.best("buy"), "best ask", book.best("sell"))
# best bid 98 best ask 103

Finding the best price with max and min checks every price each time, which is fine for a sketch. "Fast data structures" shows how real engines avoid that.

Check yourself

Four questions from across the lesson. Try each one before you look back.

1

The bids are 300 at 99 and 300 at 98. You send a sell for 200 at 98. What happens?

A sell at or below the best bid crosses. The best bid, 99, has 300 shares, enough for all 200, so they trade at 99. Your 98 was only the least you'd accept.

2

The asks are 200 at 50.01 and 300 at 50.02, and the best bid is 49.99. A buy for 600 at 50.01 arrives. What's the best bid afterwards?

Only the 200 at 50.01 are within the limit. The other 400 rest at 50.01, above the old best bid of 49.99, so they're the new best bid. The spread is now 50.02 − 50.01 = 0.01.

3

The best bid is 20.00 and the best ask is 20.05. A buy for 100 shares at 20.05 arrives. What happens?

A buy at exactly the best ask crosses, so it trades on arrival, at the maker's price of 20.05. It doesn't have to beat the ask. The mid isn't a price anyone in this book offered.

4

Two asks wait at 101: #4 for 200, which arrived first, then #5 for 100. A buy for 250 at 101 arrives. What are its fills?

Price-time priority: #4 was first at 101, so it fills in full, and #5 gets the last 50 and keeps 50 waiting. Shares in proportion to size, 167 and 83, would be pro-rata.

What to remember

  1. 1Crossing the spread

    A buy crosses when its price is at or above the best ask, and a sell when it's at or below the best bid. Anything else rests, like a buy at 100 under an ask of 101.

  2. 2The waiting order sets the price

    A trade happens at the maker's price: a sell at 97 into a bid at 99 trades at 99, and the extra 2 a share stay with the taker.

  3. 3Filling up to a limit

    An order fills up to its limit and the rest waits there: a sell for 800 at 98 fills 600 and leaves 200 as the new best ask.

  4. 4One order at a time

    Each order meets the book the last one left, so the same orders in a different order give different fills.

Markets overviewSpotted a mistake? Tell us.

Adapted from the Quant Finance Lectures (CC BY 4.0).