Lesson 1.1: How markets work: exchanges, order books and liquidity
Learn how an exchange matches buyers and sellers: order types, the limit order book, call auctions, spreads, depth and the price you really pay.
By the end of this lesson you will be able to explain how an exchange turns orders into trades, read a limit order book, work out the average price a large order really pays when it eats through several price levels, find the price at which an opening auction matches the most shares, and judge how liquid a security is. You will walk a market order through a small book and find that buying 900 shares costs 5.3 basis points more than the mid-price, work an auction table to a price of 100.00 with 1,100 shares matched, and see why the quoted price is not the price you get. You need no earlier lessons. The mathematics is weighted averages and percentages. This course is education about how markets and trading research work. It is not investment advice, and nothing in it is a recommendation to buy or sell anything.
Quantitative trading starts well before any model. Before you can test an idea you must understand the machine that executes it: how a trade actually happens, who is on the other side, and what it costs to get in and out. A strategy that looks profitable on a chart of closing prices can be unprofitable in practice because the prices on the chart were not prices you could have traded at, in the size you needed. The first lesson is therefore about market mechanics, in the plain language of the exchange itself.
What a market is for
A market is a place, physical or electronic, where buyers and sellers meet and agree prices. Markets do three jobs. They do price discovery: many people's views about the value of an asset are combined into one number that everybody can see. They provide liquidity: the ability to buy or sell quickly without moving the price much. And they allow risk transfer: a farmer sells a future harvest, a company hedges a currency, an investor takes on risk for a reward.
Trading happens in two broad ways. On an exchange, such as the National Stock Exchange of India (NSE) or the Bombay Stock Exchange (BSE), orders from all participants are sent to a central system that matches them under published rules, and trades and quotes are visible to everyone. In an over-the-counter, or OTC, market, two parties deal directly or through a dealer, with prices that are negotiated and often seen only by the people involved. Shares and listed futures and options trade mainly on exchanges. Many bonds, currency forwards and swaps trade OTC. This course concentrates on exchange trading, because its data and rules are the clearest.
In India, the securities regulator is the Securities and Exchange Board of India, SEBI. It sets the rules that exchanges, brokers and funds must follow. Cash equity trades on the exchanges settle the next trading day, a convention written T+1, meaning the shares and the money change hands one business day after the trade. Settlement is handled by a clearing corporation that stands between buyer and seller, so neither has to worry about the other failing to pay or deliver.
Who is in the market
Participant · What they want · How they behaveRetail investors · Savings growth, sometimes short-term gains · Small orders, often at the market
Institutions: mutual funds, insurers, pension funds · To invest large sums over long periods · Big orders, split up over hours or days to limit the price impact
Hedge funds and proprietary traders · Profit from views or from price differences · Anything from seconds to months
Market makers · The spread between buying and selling prices · Quote both sides all day, hold little inventory
Arbitrageurs · Tiny differences between related prices · Fast, high volume, keep prices consistent
Hedgers · To reduce a risk they already have · Trade for protection, not profit
No one is the "market". Prices come from the interaction of these groups, and every price you see is a trade-off between people who are impatient and people who are paid to be patient.
Orders: how you ask for a trade
An order is an instruction to the exchange. The two basic kinds define almost everything else.
A market order says "buy or sell now, at whatever price is available". It is certain to be filled, as long as there is someone on the other side, and uncertain in price.
A limit order says "buy or sell, but only at this price or better". A buy limit at 100.00 will not pay more than 100.00. It controls the price and gives up certainty of being filled: if nobody sells at 100.00 or less, the order waits.
Other order types are variations. A stop order becomes a market order once a trigger price is reached, often used to cap a loss. An immediate-or-cancel order fills what it can at once and cancels the rest. A fill-or-kill order must fill completely or not at all. Many exchanges also restrict which orders may be sent at which time, and some products allow only limit orders within a price range, a protection against typing errors.
Predict first: you want to buy a stock whose best offer is 100.05, and you send a market order for 900 shares. Only 400 shares are offered at 100.05. Will you pay 100.05 for all 900, pay more for some of them, or will the order be refused? Decide before reading on.
The limit order book
Almost all modern exchanges run a central limit order book, a list, kept by the exchange's computer, of every limit order waiting to trade. Buy orders are called bids, sell orders asks or offers. The book is sorted by price, with the highest bid and the lowest ask at the top.
The best bid is the highest price anyone will pay now. The best ask is the lowest price anyone will accept.
The gap between them is the bid-ask spread. The mid-price is halfway between them.
The number of shares waiting at each price is the depth at that level.
Orders at the same price are matched in the order they arrived, a rule called price-time priority: better prices go first, and among equal prices, earlier orders go first. This rule is why speed matters to some traders: being at the front of the queue means being filled first.
Here is a small book for a stock.
Side · Price · Shares waitingAsk · 100.20 · 1,000
Ask · 100.10 · 600
Ask · 100.05 · 400
Bid · 100.00 · 500
Bid · 99.95 · 300
Bid · 99.90 · 800
The best bid is 100.00 and the best ask is 100.05, so the spread is 0.05 and the mid-price is 100.025. A trade happens when an order crosses the spread: a buy order at or above the best ask, or a sell order at or below the best bid, is matched against the orders waiting on the other side. A limit buy at 99.95 does not cross, so it joins the queue at 99.95 and waits.
Walking the book
Now return to the market buy of 900 shares. The order takes the best offers first. It buys 400 shares at 100.05, which exhausts that level. The remaining 500 shares are bought at the next level, 100.10, which has 600 waiting. The total cost is 400 × 100.05 + 500 × 100.10 = 40,020 + 50,050 = 90,070, an average price of 90,070 ÷ 900 = 100.0778. So the answer to the question is the middle one: you pay more for some of the shares. The first 400 cost 100.05, the other 500 cost 100.10, and the order is filled in full because the book had enough.
Compare the average price with the mid-price of 100.025 before you traded. You paid 100.0778 − 100.025 = 0.0528 more, which is 0.0528 ÷ 100.025 = 5.3 basis points. A basis point, abbreviated bp, is one hundredth of a percentage point, so 5.3 bp is 0.053 per cent. This gap between the price you pay and the mid-price is called the cost of immediacy, or in part slippage, and Lesson 1.4 treats it in detail. It has two parts. Half the spread, here 0.025, or 2.5 bp, is the cost of any market order, however small. The rest, 2.8 bp, is the price impact of taking more than the best level could offer.
A bigger order eats deeper into the book.
Order size · Average price paid · Cost above the mid-price100 shares · 100.0500 · 2.5 bp
400 shares · 100.0500 · 2.5 bp
900 shares · 100.0778 · 5.3 bp
1,500 shares · 100.1200 · 9.5 bp
2,000 shares · 100.1400 · 11.5 bp
Two lessons stand out. First, the cost does not rise in a straight line, it steps up as each level is used. Second, the book changes as soon as you trade: after your 900-share buy, the best ask is now 100.10 and the spread has widened, so the next buyer pays more. Real markets refill their books as other participants respond, but the response takes time, which is why large orders are usually broken up and spread over time.
Opening and closing: call auctions
A continuous order book is not the only way to match orders. In a call auction, orders are collected for a period and then matched all at once at a single price. Auctions are used where the book is thin or where a fair single price matters most: at the opening and often at the close, and after a trading halt. The NSE's equity market, for example, runs a short pre-open call auction before continuous trading begins, and exchanges have in recent years extended such sessions to other products. The exact times and rules change from time to time, so always check the exchange's current circulars, and treat the times in any course, this one included, as a guide.
The auction price is chosen by a simple rule: the price at which the most shares can be matched. At any price, buyers are willing to buy if the price is at or below their limit, so the cumulative buy quantity rises as the price falls. Sellers sell at or above their limit, so the cumulative sell quantity rises as the price rises. The quantity that can actually trade at a price is the smaller of the two.
Price · Cumulative buy · Cumulative sell · Shares matched100.20 · 300 · 1,800 · 300
100.10 · 700 · 1,500 · 700
100.00 · 1,300 · 1,100 · 1,100
99.90 · 1,900 · 800 · 800
99.80 · 2,400 · 400 · 400
At 100.20, only 300 shares of buying interest remains, though 1,800 shares are on sale, so only 300 trade. At 99.80, plenty of buyers but only 400 shares are offered. At 100.00 the two meet: 1,300 shares of buying interest against 1,100 of selling, so 1,100 shares trade. That is the maximum, so the opening price is 100.00 and every matched order trades at it, buyers who offered more paying less than they were willing to, sellers who asked less receiving more. Because all matched orders trade at one price, no one gains from being a few milliseconds faster, which is one reason auctions are popular for the opening and closing prices that many funds and indices are measured against.
What is liquidity?
Liquidity is how easily and cheaply you can trade. It is not one number but four properties together.
Tightness: how narrow the spread is. The quoted spread is the best ask minus the best bid. The relative spread divides it by the mid-price, usually expressed in basis points. In the example it is 0.05 ÷ 100.025 = 5.0 bp.
Depth: how many shares are waiting near the best prices. A deep book can absorb a large order with little movement.
Resilience: how quickly the book recovers after a large trade. A resilient market refills.
Immediacy: how fast you can trade at all.
Liquid and illiquid securities behave very differently. A large, widely held company may have a spread of one tick, the smallest allowed price step, and millions of shares of depth, so trading a few lakh rupees costs next to nothing. A small company's shares may have a spread of 50 bp or more and a few hundred shares waiting, so even a modest order moves the price. Strategies that look excellent on small, illiquid stocks often vanish once the costs of real trading are included, which is why serious research always tests the liquidity of what it trades.
A simple summary measure is average daily volume, or ADV: the typical number of shares, or rupees, traded in a day. A common safety rule is to keep an order below a small fraction of ADV, often a few per cent or less, because the price impact of an order grows with its size relative to normal volume. A related measure, the Amihud illiquidity ratio, divides the absolute daily return by the rupees traded that day and averages over time: a stock that moves a lot on little volume is illiquid. Lesson 1.4 returns to the link between order size, volume and cost.
Why the spread exists
Why is there a spread at all? A market maker who posts both a bid and an ask is offering immediate trading to anyone who wants it. In return, the market maker earns the spread, on average half of it per trade on each side. They also take risks. Their inventory can lose value if the price moves against it, and some of the people trading against them are better informed. If someone knows good news is coming, they will buy from the market maker at the ask just before the price jumps, leaving the market maker short at a loss. This is adverse selection, and the spread has to be wide enough to pay for it. That is why spreads widen around news, in volatile markets and for shares with few informed observers: the compensation the market maker needs grows with the risk of trading against someone who knows more.
This view of the spread shapes what a quantitative trader should believe about costs. The spread is not a fee that a clever trader can avoid. It is a payment for liquidity, and the trader who takes liquidity with market orders pays it, while one who provides it with limit orders earns it, together with the risk of being picked off. Lesson 5.4 develops market making as a strategy.
Safeguards and where they matter
Exchanges protect orderly trading with a few standard tools. Price bands limit how far a stock may move in a day, and an order outside the band is rejected. Circuit breakers pause trading, in a stock or the whole market, when prices move by a set percentage. Trading halts stop trading while news is released. Tick sizes fix the smallest price step. These rules differ by exchange and product, and they change, so a researcher should treat them as part of the data and always check the current circular. For a strategy they matter in three ways: orders can be rejected or delayed, prices can jump across a halt, and a backtest that ignores a band or a halt will overstate what could have been traded.
python
from collections import deque
class Book:
"""A minimal limit order book with price-time priority."""
def init(self):
self.bids = {} # price -> deque of [orderid, shares]
self.asks = {}
def add(self, side, price, shares, oid):
"""Match against the opposite side first; any remainder rests in the book."""
book, other = (self.bids, self.asks) if side == "buy" else (self.asks, self.bids)
fills = []
while shares > 0 and other:
best = min(other) if side == "buy" else max(other)
crosses = price >= best if side == "buy" else price <= best
if not crosses:
break
queue = other[best]
while shares > 0 and queue:
take = min(shares, queue[0][1])
fills.append((best, take))
shares -= take
queue[0][1] -= take
if queue[0][1] == 0:
queue.popleft()
if not queue:
del other[best]
if shares > 0:
book.setdefault(price, deque()).append([oid, shares])
return fills
book = Book()
for i, (p, s) in enumerate([(100.05, 400), (100.10, 600), (100.20, 1000)]):
book.add("sell", p, s, f"a{i}")
for i, (p, s) in enumerate([(100.00, 500), (99.95, 300), (99.90, 800)]):
book.add("buy", p, s, f"b{i}")
mid = (max(book.bids) + min(book.asks)) / 2
fills = book.add("buy", 1e9, 900, "mine") # a market buy is a limit order at a very high price
avg = sum(p q for p, q in fills) / sum(q for , q in fills)
print(fills, round(avg, 4), round((avg - mid) / mid 1e4, 2), "bp above the mid-price")
opening auction: the price with the most matched shares
prices = [100.20, 100.10, 100.00, 99.90, 99.80]
cumbuy = [300, 700, 1300, 1900, 2400]
cumsell = [1800, 1500, 1100, 800, 400]
matched = [min(b, s) for b, s in zip(cumbuy, cumsell)]
print(dict(zip(prices, matched)), "opening price", prices[matched.index(max(matched))])
Common mistakes
Treating the last traded price as the price you can trade at. You buy at the ask and sell at the bid, and size changes both.
Ignoring the spread because it looks small. A spread of 5 bp is a cost of 5 bp on every round trip, which adds up for a strategy that trades often.
Assuming you can trade any size at the quoted price. The price shown applies only to the shares shown.
Using a market order in a thin book. The order will walk the book and pay for it. Use a limit order or split the order.
Confusing volume with liquidity. A stock can trade a lot on a few busy days and be thin on others. Look at depth and spread as well.
Ignoring auctions, halts and bands in research. They change what could really have been traded.
Forgetting the other side. Every trade has someone who agreed to it. Ask why they did.
Key takeaways
A market does price discovery, liquidity provision and risk transfer. Exchanges match orders centrally, and OTC markets deal directly.
A market order buys certainty of a fill and gives up certainty of price. A limit order does the reverse.
The limit order book lists bids and asks by price, and orders at one price are served first-come, first-served. The spread is the best ask less the best bid, and the mid-price is halfway.
A large market order walks the book. Buying 900 shares in the example costs an average of 100.0778, which is 5.3 bp above the mid-price, and the cost rises with size.
A call auction matches all orders at one price, the price that maximises the shares matched. In the example it is 100.00 with 1,100 shares.
Liquidity means tightness, depth, resilience and immediacy. Spreads pay market makers for immediacy and for the risk of trading against better-informed people.
Rules about bands, halts and tick sizes are part of the data. A backtest that ignores them overstates what was possible.
Check yourself
1. In the example book, you sell 600 shares at the market. What is the average price you receive, and how far is it below the mid-price?
The best bid takes 500 shares at 100.00, then 100 shares at 99.95. The average is (500 × 100.00 + 100 × 99.95) ÷ 600 = 99.9917, which is 0.0333 below 100.025, or 3.3 bp.
2. What is the relative spread of a stock with a bid of 249.90 and an ask of 250.10?
The spread is 0.20 and the mid-price is 250.00, so the relative spread is 0.20 ÷ 250 = 8 bp.
3. A buy limit order is placed at 100.00 when the best ask is 100.05. Does it trade at once? What happens to it?
No. A buy limit below the best ask does not cross the spread. It joins the bids at 100.00, behind earlier orders at that price, and waits for a seller.
4. In an opening auction, 1,000 shares of buying interest exist at the highest price and sellers offer 700 at that price. How many shares can trade at that price?
The smaller of the two, 700 shares.
5. Why do spreads usually widen around important news?
Market makers face more adverse selection, since some traders know more than they do, and more inventory risk, so they ask for more compensation.
Try this
Use the free live or delayed order book of any exchange, or the example book, and set aside forty minutes.
1. Write down the best bid, best ask, spread, mid-price and relative spread in basis points for three securities of different size, a large well-known company, a mid-sized one and a small one.
2. For each, note the depth at the best bid and ask in shares and in rupees. Say which is most liquid and why.
3. Work out by hand the average price and the cost above the mid-price for a market buy of three different sizes in the example book, then check with the simulator.
4. Use the Python book to add two more ask levels of your own and test an order that clears all of them.
5. Construct your own call auction table with five prices and find the price that matches the most shares.
6. Pick a stock with a low average daily volume and write a sentence on how you would execute a large order in it.
7. Write a short note listing the exchange rules, such as price bands and halts, that a backtest on this stock should respect.
A good result is a short table of spreads and depths for three securities, a worked market-order walk and a note on the rules that limit what can be traded. The next lesson turns from how trading works to what is traded: shares, futures, options and currencies.
Read more
For market mechanics, Larry Harris, Trading and Exchanges, is the standard book. For a research-level view of order books and price impact, see Trades, Quotes and Prices by Bouchaud, Bonart, Donier and Gould. For the current rules on trading sessions and price bands, use the exchange's own circulars, since they change.
Tags: Quant Trader Market microstructure Order book Liquidity Bid-ask spread