Sub topic 1
Reading the Order Book
Prerequisites
This chapter assumes you have bought and sold crypto on an exchange, that you know what a trading pair such as BTC/USDT means, and that you can read simple Python. You should know that a price is what one unit costs and a size is how many units are on offer.
What the order book shows
An order book is the live list of open orders for one trading pair. Buy orders are called bids. Sell orders are called asks. Each row holds a price and a size, which is the quantity available at that price. The best bid is the highest bid. The best ask is the lowest ask. Depth is the total quantity resting on each side.
bids = [(99.5, 3.0), (99.0, 4.0)] # (price, size), best bid first
asks = [(100.0, 2.0), (100.5, 3.0)] # (price, size), best ask first
best_bid = bids[0][0]
best_ask = asks[0][0]
bid_depth = sum(size for _, size in bids)
ask_depth = sum(size for _, size in asks)
print(best_bid, best_ask) # 99.5 100.0
print(bid_depth, ask_depth) # 7.0 5.0The spread: the cost of immediacy
The spread is the gap between the best ask and the best bid. In this book it is 100.0 - 99.5 = 0.5. If you buy at market, you pay the best ask. If you sell at market, you receive the best bid. Trading immediately therefore costs you the spread. Thinly traded pairs usually have wide spreads.
Limit orders: naming your price
A limit order sets the worst price you accept. A buy limit at 99.8 is below the best ask of 100.0, so nothing matches it. It rests on the bid side and waits for a seller. A buy limit at or above 100.0 would match the asks at once.
Limit orders control price. They do not guarantee a fill, because the market may move away before anyone trades with your order.
Market orders: trading now at the available price
A market order fills immediately against the best available prices. A large order can use up the best ask and move to the next level. Its average fill price can then sit above the best ask. That gap is slippage.
def market_buy(asks, qty):
remaining, cost = qty, 0.0
for price, size in asks:
take = min(remaining, size)
cost += take * price
remaining -= take
if remaining == 0:
break
filled = qty - remaining
return filled, cost / filled
print(market_buy(asks, 4.0)) # (4.0, 100.25)Exercise
Using the book above, what is the average fill price of a market buy for 3 units, and what is the slippage against the best ask?
Show answer
The order fills 2 units at 100.0 and 1 unit at 100.5. The total cost is 300.5, so the average fill is 300.5 / 3 = 100.17 (about 100.1667). That is about 0.17 above the best ask, or roughly 0.17%.