Sub topic 4
Market orders: trading now at the available price
This chapter assumes you can read an order book (best bid, best ask, depth), know what a trading pair like BTC/USDT is, and can follow short Python functions. It covers how a market order executes, what it costs, and how it fails.
What a market order is
A market order is an instruction to buy or sell a given quantity immediately, at whatever prices are available. You set no price. You set the side (buy or sell) and the size. The exchange fills the order against the resting orders on the opposite side of the book.
- A market buy consumes the ask side, starting at the lowest ask and moving up.
- A market sell consumes the bid side, starting at the highest bid and moving down.
A market order is a taker order. It removes liquidity from the book instead of adding it, so it normally pays the taker fee. Fees are covered in a later chapter. This chapter uses them only to compute total cost.
A market order gives you certainty of execution and no certainty of price. A limit order, from the previous chapter, gives you the reverse.
Walking the book
Take this ask side, written as (price, size) pairs from best to worst:
| Level | Ask price | Size available |
|---|---|---|
| 1 | 100.0 | 2.0 |
| 2 | 100.5 | 3.0 |
| 3 | 101.0 | 5.0 |
A market buy of 4 units cannot be satisfied at the best ask, because only 2 units sit there. The order takes all 2 units at 100.0, then 2 of the 3 units at 100.5. The book is "walked" level by level until the order is full.
The cost is 2 × 100.0 + 2 × 100.5 = 401.0. The average fill price is 401.0 / 4 = 100.25, which is 0.25% above the best ask.
Estimating the fill before you trade
You can estimate a market order's outcome from the order book snapshot. The function below works for both sides, because it only needs the list of levels to consume.
asks = [(100.0, 2.0), (100.5, 3.0), (101.0, 5.0)] # best (lowest) first
bids = [(99.5, 1.5), (99.0, 4.0), (98.0, 10.0)] # best (highest) first
def market_order(levels, qty):
"""Walk the levels. Return (filled_qty, average_price, unfilled_qty)."""
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 else None
return filled, avg, remaining
# Market buy of 4 units against the asks
filled, avg, left = market_order(asks, 4.0)
print(filled, avg, left) # 4.0 100.25 0.0
print(round((avg - asks[0][0]) / asks[0][0] * 100, 4)) # 0.25 (percent above best ask)
# Market sell of 3 units against the bids
filled, avg, left = market_order(bids, 3.0)
print(filled, avg, left) # 3.0 99.25 0.0
print(round((bids[0][0] - avg) / bids[0][0] * 100, 4)) # 0.2513 (percent below best bid)For a sell, the slippage is measured in the other direction. Selling into a falling price ladder gives you less than the best bid, so the average price is below it.
A snapshot is only an estimate. Other traders can add or cancel orders between your look at the book and the moment your order arrives. The estimate is most reliable when your order is small relative to the depth shown.
Sizing by quantity or by spend
Most exchanges let you size a market buy in one of two ways.
- Base quantity: "buy 0.5 BTC". The quantity is fixed and the cost varies with the book.
- Quote amount: "spend 500 USDT". The spend is fixed and the quantity you receive varies.
Market sells are usually sized in the base asset, because you are selling coins you hold.
A spend-based buy must stop when the money runs out, and it can end in the middle of a level, so fractional quantities are normal.
asks = [(100.0, 2.0), (100.5, 3.0), (101.0, 5.0)]
def market_buy_by_spend(asks, budget):
"""Spend up to `budget` in quote currency. Return (qty_bought, average_price, unspent)."""
remaining = budget
qty = 0.0
for price, size in asks:
affordable = remaining / price
take = min(size, affordable)
qty += take
remaining -= take * price
if take < size: # budget ran out inside this level
break
spent = budget - remaining
avg = spent / qty if qty else None
return qty, avg, remaining
qty, avg, unspent = market_buy_by_spend(asks, 300.0)
print(round(qty, 6), round(avg, 4)) # 2.995025 100.1661 (all 2.0 at 100.0, then about 0.995 at 100.5)Real exchanges also round quantities down to the market's lot size and enforce a minimum order value. The tiny leftover this produces is usually called dust. It stays in your balance unspent.
What a market order really costs
The price you see on a ticker is not the price you pay. For a market buy, the total cost has three parts:
- Spread: you buy at the ask, not the midpoint between bid and ask.
- Slippage: the extra amount your average price sits above the best ask, caused by consuming several levels.
- Fee: the taker rate applied to the traded value.
Using the 4-unit buy above with an illustrative 0.20% taker rate:
TAKER_RATE = 0.0020 # illustrative; real rates depend on the exchange and your fee tier
notional = 401.0 # 2 x 100.0 + 2 x 100.5
fee = notional * TAKER_RATE
print(fee) # 0.802
print(notional + fee) # 401.802 total paidThe fee is charged on the traded value, so it grows with the size of the trade. Slippage grows faster than linearly in thin books, because each additional unit is bought at a worse price than the one before.
When market orders go wrong
Thin books
If few orders rest near the top of the book, a modest market order can sweep many price levels. The same order that costs 0.05% slippage on a busy pair can cost several percent on an illiquid altcoin pair. Depth, not the quoted price, determines the cost.
Fast markets
During sharp moves, the book changes by the millisecond. Liquidity is withdrawn, and spreads widen. A market order sent during a news spike executes against the book as it is when the order arrives, which may be far from what your screen showed.
Insufficient liquidity
If the order is larger than all resting liquidity on that side, behavior depends on the exchange. Common outcomes:
- The order fills what it can, and the remainder is cancelled.
- The order is rejected outright.
- The order is capped by a price-protection band (see below).
Check the exchange's documentation for the rule that applies to you. Never assume the remainder will wait on the book. A market order has no price, so it cannot rest there.
Fat fingers
An extra zero in the quantity turns a small trade into a book sweep. Because a market order has no price limit, nothing in the order itself stops it. Check the quantity and the estimated total before you confirm.
Safeguards
| Safeguard | What it does | Where it comes from |
|---|---|---|
| Price-protection band | Rejects or stops a market order that would fill beyond a set distance from a reference price | Some exchanges apply it automatically |
| Estimated-cost preview | Shows the expected average price before you confirm | Many exchange order forms |
| Smaller child orders | Splits a large order into pieces executed over time | You or an execution tool |
| Marketable limit order | A limit order priced so it fills immediately but never beyond a ceiling | You choose the limit price |
The marketable limit order is the most useful of these. A limit buy priced above the best ask fills like a market order, but it never pays more than your limit price. Anything it cannot fill at or below that price is left on the book as a bid (or cancelled, depending on its time-in-force setting, which later chapters cover). The earlier limit_buy example showed this behavior: at a limit of 100.2, only the 100.0 level filled.
When a market order is the right tool
Market orders suit situations where being filled matters more than the last fraction of a percent:
- Liquid pairs with deep books and tight spreads, where slippage is tiny.
- Small orders relative to visible depth.
- Exits where staying in the position is the larger risk.
They suit poorly when the pair is illiquid, the order is large, or the market is moving violently. The final chapter of this tutorial gives a full decision framework.
Exercise
Using the bids [(99.5, 1.5), (99.0, 4.0), (98.0, 10.0)], you place a market sell of 6 units. What is the average fill price, and how far below the best bid is it, in percent (rounded to 2 decimals)?
Show answer
The sell takes 1.5 at 99.5 (149.25), then 4.0 at 99.0 (396.0), then the last 0.5 at 98.0 (49.0). Total proceeds are 594.25 for 6 units, so the average price is about 99.0417. Against the best bid of 99.5, that is (99.5 - 99.0417) / 99.5 ≈ 0.46% below it.
Exercise
A market buy of 12 units is sent against the asks [(100.0, 2.0), (100.5, 3.0), (101.0, 5.0)]. How much can fill, and what happens to the rest? Why can't the remainder simply wait on the book at some price?
Show answer
Only 10 units are available (2 + 3 + 5), so at most 10 fill, at an average of (200 + 301.5 + 505) / 10 = 100.65. The remaining 2 units are cancelled or the whole order is rejected, depending on the exchange. A market order carries no price, and a resting order on the book must have one, so there is no level at which the remainder could rest.