Sub topic 1
How order books work
Prerequisites
This chapter assumes you know what a cryptocurrency exchange is and how to hold funds on one. You should be comfortable with percentages and simple arithmetic. You only need to read basic Python, because the examples are short. You do not need to know anything about futures or perpetual swaps yet. Later chapters build on the order book model introduced here.
What an order book is
An order book is a live list of all unfilled buy and sell orders for one market on one venue. A market is a trading pair such as BTC/USDT, or a contract such as a BTC perpetual swap. Each order states a side, a price, and a size.
- A bid is an order to buy at a given price or lower.
- An ask (also called an offer) is an order to sell at a given price or higher.
- A resting order is an order that sits in the book waiting for a counterparty.
The book has two sides. Bids are sorted from the highest price down. Asks are sorted from the lowest price up. The two sides meet in the middle at the top of the book.
| Term | Meaning |
|---|---|
| Best bid | The highest price any buyer currently offers |
| Best ask | The lowest price any seller currently accepts |
| Spread | Best ask minus best bid |
| Mid price | Average of best bid and best ask |
| Depth | Total size resting at or near a set of price levels |
If no one is willing to trade at the same price, the spread is positive. Bids and asks never overlap in a healthy book. If they did, the exchange would match them at once.
A worked example
Suppose the book for BTC/USDT looks like this. Sizes are in BTC.
| Side | Price (USDT) | Size (BTC) |
|---|---|---|
| Ask | 60,020 | 1.5 |
| Ask | 60,010 | 0.8 |
| Ask | 60,005 | 0.4 |
| Bid | 60,000 | 0.6 |
| Bid | 59,995 | 1.2 |
| Bid | 59,990 | 2.0 |
The best ask is 60,005 and the best bid is 60,000. The spread is 5 USDT. The mid price is 60,002.50.
Each price with orders on it is called a price level. The size shown at a level is the sum of every resting order at that price. Order books are usually shown as an aggregated list of levels, but internally the exchange stores each order separately.
How a trade happens
A trade happens when an incoming order can be matched against a resting order. The component that does this is the matching engine. It is the exchange software that receives orders, compares them to the book, and records the resulting trades.
Most venues use price-time priority:
- Better prices go first. For bids, a higher price is better. For asks, a lower price is better.
- At the same price, the order that arrived earlier goes first.
Some venues use other rules, such as pro-rata allocation, which splits a fill across all orders at a level in proportion to size. Spot and derivatives venues in crypto mostly use price-time priority, but check the venue documentation.
Matching always happens at the resting order's price, not the incoming order's price. This matters for the next section.
Walking the book
An order that is larger than the size at the best price keeps going to the next level until it is filled. This is called walking the book. Each level fills at its own price, so the average price gets worse as the order gets bigger.
Here is code that simulates a market buy against the example book. It consumes asks from best to worst and returns the average fill price.
def walk_book(levels, qty):
"""levels: list of (price, size) sorted best first.
Returns (filled_qty, average_price)."""
remaining = qty
cost = 0.0
for price, size in levels:
take = min(remaining, size)
cost += take * price
remaining -= take
if remaining <= 0:
break
filled = qty - remaining
avg = cost / filled if filled > 0 else None
return filled, avg
asks = [(60005, 0.4), (60010, 0.8), (60020, 1.5)]
filled, avg = walk_book(asks, 1.0)
print(filled, avg)
filled, avg = walk_book(asks, 5.0)
print(filled, avg)The first call buys 1.0 BTC. It takes 0.4 BTC at 60,005 and 0.6 BTC at 60,010. The average price is 60,008. That is 3 USDT above the best ask, and 5.50 USDT above the mid price.
The second call asks for 5.0 BTC, but the book holds only 2.7 BTC on the ask side. The function returns a partial fill of 2.7 BTC. A real exchange would handle the rest according to the order type, which the next chapter covers.
The gap between the price you expected and the average price you got is called slippage. A later chapter on liquidity and slippage treats it in more detail.
Maker and taker roles
The role an order plays depends on whether it adds liquidity to the book or removes it.
- A maker order rests in the book. It adds liquidity, meaning it gives others something to trade against.
- A taker order matches immediately against resting orders. It removes liquidity.
The same order can be a maker or a taker depending on the book at the moment it arrives. If you send a buy at 60,000 while the best ask is 60,005, your order rests and you are a maker. If you send a buy at 60,005 or higher, it matches immediately and you are a taker. Fees usually differ between the two roles, and this is covered in the next chapter.
Reading the book
A quick read of the book can tell you several things, but each has limits.
- A tight spread usually means many participants compete to trade, so the market is liquid.
- Thick levels near the top mean large orders can fill with little price movement.
- A large imbalance between total bid size and total ask size may hint at short-term pressure. It is a weak signal, because resting orders can be cancelled at any time.
The following code computes spread, mid price, and a simple imbalance measure over the top levels.
def book_stats(bids, asks, depth=3):
best_bid = bids[0][0]
best_ask = asks[0][0]
spread = best_ask - best_bid
mid = (best_ask + best_bid) / 2
bid_size = sum(size for _, size in bids[:depth])
ask_size = sum(size for _, size in asks[:depth])
imbalance = (bid_size - ask_size) / (bid_size + ask_size)
return spread, mid, imbalance
bids = [(60000, 0.6), (59995, 1.2), (59990, 2.0)]
asks = [(60005, 0.4), (60010, 0.8), (60020, 1.5)]
print(book_stats(bids, asks))The imbalance is a value between -1 and 1. Here it is (3.8 - 2.7) / (3.8 + 2.7), about 0.17, so slightly more size sits on the bid side.
Common errors and edge cases
- Confusing the last price with the executable price. The last traded price is where the most recent trade happened. It is not a price you can necessarily trade at now. Use the best bid and ask for that.
- Ignoring size at the top level. A quoted price only applies up to the size shown. A larger order walks the book.
- Trusting displayed depth. Orders can be cancelled or pulled in the moment before you trade. Some participants place large orders they do not intend to fill, a practice called spoofing, which is illegal in many jurisdictions but still occurs.
- Mixing units. Size can be in coins, in quote currency, or in contracts. On derivatives venues, one contract may be worth a fixed dollar amount. Check the contract specification before reading a size column. A later chapter on linear and inverse contracts covers this.
- Assuming one global book. Each venue keeps its own book. The same asset trades at slightly different prices on different venues, and the differences are small only when arbitrageurs keep them small.
- Tick and lot sizes. Prices must be multiples of a tick size, and quantities must be multiples of a lot size. Orders that violate these are rejected.
Summary of the working model
An order book stores resting bids and asks sorted by price and arrival time. The best bid and best ask define the spread. Incoming orders match against the best resting orders first and walk to worse prices if they are large. Resting orders are makers and matching orders are takers. Depth and spread together describe how costly it is to trade.
Exercise
Using the example book in this chapter (asks: 0.4 BTC at 60,005, 0.8 BTC at 60,010, 1.5 BTC at 60,020), what is the average price of a market buy for 1.5 BTC, and how far is it above the best ask?
Show answer
The order takes 0.4 BTC at 60,005, 0.8 BTC at 60,010, and 0.3 BTC at 60,020. Cost = 0.4 x 60,005 + 0.8 x 60,010 + 0.3 x 60,020 = 24,002 + 48,008 + 18,006 = 90,016 USDT. Average price = 90,016 / 1.5 = 60,010.67 USDT, which is about 5.67 USDT above the best ask of 60,005.
Exercise
A trader sends a buy order at 60,003 when the best bid is 60,000 and the best ask is 60,005. Is the order a maker or a taker, and where does it sit in the book?
Show answer
It is a maker order. The price is below the best ask, so it cannot match immediately. It rests in the book as the new best bid at 60,003, which narrows the spread from 5 to 2 USDT.
Exercise
Two buy orders rest at 59,995, one placed at 10:00:01 and one at 10:00:05. A sell order for the size of one of them arrives at 59,995. Under price-time priority, which buy order fills, and at what price?
Show answer
The order placed at 10:00:01 fills first because it arrived earlier at the same price. The trade happens at 59,995, the resting order's price.