σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Data pipelines skill›Module 1 · Sources and normalisation›Topic 1.4·~50 minIntermediate

Tiers of market data: L1 to L3

Skill positionModule 1 of 4 · Topic 4 of 4
1.4 Tiers of market data: L1 to L3
—Lab score— / 100Total XP—Streak—
Lecture0% read

12 min readCode examples: 5

  1. 01Three tiers of the same market
  2. 02Level 3: every order
  3. 03Level 2: the depth
  4. 04Level 1: the best prices
  5. 05From trades to a bar
  6. 06Putting the tiers together
  7. 07What you will build

One SPY day is a single bar, 40 trades, or 33 order events, depending on how closely you look. Vendors sell the same market at three levels of detail, and each level is a summary of the one above it. How much do you lose at each step, and what can you still compute?

01

Three tiers of the same market

Where we are: the first three topics cleaned bars, which are one summary row per day. A bar hides almost everything that happened during the day. Market data vendors sell finer views, called tiers or levels, and a pipeline has to know which tier it holds because each one supports different questions. By the end of this topic you will be able to replay an order feed into a book, summarise the book into depth and into the best prices, compute the numbers that the best prices give, and build a bar from trades.

Think of an exchange as a waiting room for orders. Each order says "I will buy 300 shares at 20.00" or "I will sell 100 at 20.02" and waits until someone agrees. The waiting orders are the order book. The three tiers are three ways of describing it.

  • Level 3, every order: each order is listed with its own id, and every change to it (add, modify, cancel, execute) is an event. You can rebuild the whole book at any moment.
  • Level 2, the depth: orders are added up by price, so you see how much quantity waits at each price on each side, and how many orders make it up. You no longer see single orders.
  • Level 1, the top of the book: only the best bid (the highest buy price) and the best ask (the lowest sell price), each with its size, plus the last trades.
DefinitionMarket data tier

One of the three levels of detail at which a vendor describes a market: level 3 lists orders, level 2 the depth by price, level 1 the best prices. A tier can be computed from the one above it, and never the other way round.

The arrow only points one way because every step throws information away. From the orders you can add up the depth, but from the depth you cannot say which orders it was made of. From the depth you can read the best prices, but not the depth. And a bar is yet another summary: from trades, not from orders. The lab gives you a level 3 feed made around real SPY closes. Here are its size and its first events, to see what an event looks like.

main.pyPython
bars = load_bars()events = synth_events(bars.iloc[0], 1)1print(len(events), "events; the first three:")for event in events[:3]:    print(event)
33 events; the first three:
('add', 1, 'B', 93.68, 200)
('add', 2, 'S', 93.7, 800)
('add', 3, 'B', 93.67, 700)
  1. 1synth_events makes a valid feed of orders around the close of a day; you will replay it.

The cost of detail is volume. For a busy stock, level 3 can mean tens of millions of events in one day, level 2 a few million changes of the depth, and level 1 some hundreds of thousands of changes of the best prices. A bar is 5 numbers. That is why most research starts from bars, why execution and market-making research needs level 2 or level 3, and why a pipeline records which tier each table came from. Real level 3 feeds are binary protocols, but their content is the same four kinds of event that the lab uses.

02

Level 3: every order

A level 3 feed is a list of events in the order they happened. To know what is resting at the end you replay them: keep a dictionary from order id to what is left of the order, and let each kind of event change it in its own way. The method has four rules, one for each kind of event, and one rule about mistakes.

  1. 1
    addPut the order in the dictionary with its side, price and quantity. An id that is already resting is an error, because ids are unique.
  2. 2
    modifyKeep the side and the price, and replace the quantity with the new one. The new quantity replaces the old one; it is not added to it.
  3. 3
    cancel and executeCancel removes the order. Execute lowers the quantity by the traded amount and removes the order when nothing is left.
  4. 4
    Reject nonsenseAn event on an order that is not resting, or an execute of more than is left, means the feed or the replay is wrong. Raise ValueError rather than guessing.

Worked example 1. *Problem:* six events: two buy orders and a sell order are added, order 2 is modified to 150, 40 of the sell order trades, and order 1 is cancelled. What rests at the end? *Plan:* a dictionary updated event by event, using the rule of each kind. *Steps:* loop, branch on the kind, update.

main.pyPython
events = [("add", 1, "B", 20.00, 300), ("add", 2, "B", 20.00, 200), ("add", 3, "S", 20.02, 100),          ("modify", 2, 150), ("execute", 3, 40), ("cancel", 1)]book = {}for event in events:    kind, order = event[0], event[1]    if kind == "add":        book[order] = (event[2], event[3], event[4])    elif kind == "cancel":        del book[order]    elif kind == "modify":1        side, price, qty = book[order]        book[order] = (side, price, event[2])    elif kind == "execute":2        side, price, qty = book[order]        book[order] = (side, price, qty - event[2])print(book)
{2: ('B', 20.0, 150), 3: ('S', 20.02, 60)}
  1. 1modify keeps side and price, and sets the quantity.
  2. 2execute subtracts; a full execution must also remove the order, which this sketch does not do.

*Check:* order 1 is gone, order 2 rests with 150 (the new quantity, not 350), and the sell order rests with 60 after 40 traded. *What to notice:* the sketch above has two gaps that the lab asks you to close: an order whose quantity reaches zero must disappear, and an event on an unknown order must raise ValueError instead of a KeyError. A book with zero-quantity orders in it silently counts them as orders at a price.

An execute is a trade

Every execute event is one trade seen from the side of the order that was resting. A feed that also sends a separate list of trades repeats them. If you add both to the volume of a day, you count every share twice, so decide which one is your source of truth and use only that one.

03

Level 2: the depth

Level 2 answers "how much is waiting at each price". Orders at the same price on the same side are added together, and the number of orders is kept, because 500 shares from one order and 500 shares from ten orders behave differently when someone sells into them. The bids are listed from the highest price down, because the best buyer is the one who pays most, and the asks from the lowest price up, because the best seller asks least.

Worked example 2. *Problem:* five resting orders: buys of 300 and 200 at 20.00 and 500 at 19.99, sells of 100 and 250 at 20.02. Give the depth of each side. *Plan:* group by side and price with a dictionary from price to (total, count), then sort the bids high to low and the asks low to high. *Steps:* split by side, group, sort.

main.pyPython
book = {1: ("B", 20.0, 300), 2: ("B", 20.0, 200), 3: ("B", 19.99, 500), 4: ("S", 20.02, 100), 5: ("S", 20.02, 250)}bids, asks = {}, {}for side, price, qty in book.values():    target = bids if side == "B" else asks    total, count = target.get(price, (0, 0))1    target[price] = (total + qty, count + 1)print(sorted(bids.items(), reverse=True))2print(sorted(asks.items()))
[(20.0, (500, 2)), (19.99, (500, 1))]
[(20.02, (350, 2))]
  1. 1get with a default starts a price at (0, 0) the first time it is seen.
  2. 2reverse=True puts the highest bid first.

*Check:* the 20.00 level holds 500 shares in 2 orders, and the sell level holds 350 in 2 orders. *What to notice:* the simple method, sorting the bids like the asks, puts the worst bid first. The first entry of each list must be the best price, which is what the next level relies on.

A summary cannot be undone

If a vendor sells only level 2, you cannot rebuild the orders: five levels of depth do not say which orders were added or cancelled. Decide which tier your research needs before you buy or store data, because the cheaper tiers can never be turned back into the richer ones.

04

Level 1: the best prices

Level 1 is the first level of each side with its total size. From it you get the numbers that most strategies use. The mid price is the average of the two. The spread is their difference, which is what it costs to buy and sell at once, and it is often stated in basis points, hundredths of a percent of the mid. The microprice is a mid that leans towards the thinner side: where the size on the bid is large, a trade is more likely to push the price up, so the microprice lies closer to the ask.

Worked example 3. *Problem:* the depth below has two bid levels and one ask level. Give the mid, the spread, the spread in basis points and the microprice. *Plan:* take the first level of each side, then apply the four formulas. *Steps:* top of book, mid, spread, microprice.

main.pyPython
depth = {"bids": [(20.0, 500, 2), (19.99, 500, 1)], "asks": [(20.02, 350, 2)]}bid, ask = depth["bids"][0], depth["asks"][0]mid = (bid[0] + ask[0]) / 2spread = ask[0] - bid[0]micro = (bid[0] * ask[1] + ask[0] * bid[1]) / (bid[1] + ask[1])1print(round(mid, 4), round(spread, 4), round(10000 * spread / mid, 2), round(micro, 4))
20.01 0.02 10.0 20.0118
  1. 1The bid price is weighted by the ask size, and the ask price by the bid size.

*Check:* the mid is 20.01, the spread 0.02 and about 10 basis points of the mid. The microprice is 20.0118, a little above the mid, because the bid side (500) is larger than the ask side (350). *What to notice:* if you weight each price by its own size you get the opposite lean, which is a mistake that looks reasonable and is wrong.

Prices on an exchange move in steps called ticks. For most US stocks the tick is one cent, so the smallest spread is 0.01 and a stock whose spread is always one cent is called tight. That is why the two best prices in the lab differ by two cents on a price of 93.69, which is about 2 basis points. A wide spread means that trading is expensive, and the spread in basis points is the number that compares instruments with very different prices.

05

From trades to a bar

A bar is a summary of trades, not of orders. A trade says that a quantity changed hands at a price at a time. To make a daily bar you need the order in time, because the open is the price of the first trade and the close the price of the last, and the vendor may deliver trades in any order. The high and the low are the largest and the smallest price, and the volume is the sum of the quantities. This is the link back to the first topic: the bar you used there is the output of this function.

Worked example 4. *Problem:* four trades arrive in the order (36000, 20.05, 100), (34200, 20.00, 300), (57600, 20.10, 200), (40000, 19.95, 150), where the first number is the second of the day. Build the bar. *Plan:* sort by time, then the first price is the open and the last the close. *Steps:* sort, collect prices, summarise.

main.pyPython
trades = [(36000, 20.05, 100), (34200, 20.00, 300), (57600, 20.10, 200), (40000, 19.95, 150)]ordered = sorted(trades)1prices = [price for _, price, _ in ordered]print(prices[0], max(prices), min(prices), prices[-1], sum(qty for _, _, qty in ordered))2print(trades[0][1], trades[-1][1])
20.0 20.1 19.95 20.1 750
20.05 19.95
  1. 1Sorting tuples sorts by their first item, the second of the day.
  2. 2open, high, low, close, volume.

*Check:* the earliest trade is at 34200 seconds, which is 09:30, so the open is 20.0 and the close is 20.1 from 16:00. *What to notice:* the second line is the simple method, taking the first and last trades of the list as they arrived: it gives 20.05 and 19.95, both wrong. Always sort before you summarise. When two trades share a second, the lab asks you to keep the order of the list, which a stable sort on the second does.

Stable sorting keeps arrival order

sorted(trades, key=lambda trade: trade[0]) sorts by the second only and leaves trades of the same second in the order they came. Sorting whole tuples would reorder them by price, which can change the open or the close.

Bars of other lengths come out of the same function. A bar of one minute is the summary of the trades of one minute, so with trades you can make a bar for any window by selecting the trades with the right seconds first. The daily bar of the first topic is just the window that runs from the open to the close. If a vendor's daily bar does not match the one you build from its own trades, the likely reasons are a different definition of the session, trades reported late, or a different rule for which trades count.

06

Putting the tiers together

A real pipeline keeps the richest tier it can afford and derives the others, so the tiers are always consistent. The lab checks that consistency in two ways. First it rebuilds the bars of five real SPY days from 40 synthetic trades each, which add up exactly to the real bar, and counts how many agree (all of them, if your functions are right). Then it replays the order feed and walks down the tiers from the orders to the depth to the best prices.

  • FunctionQuestion it answers
  • apply_orders(events)What is resting after these events?raises ValueError on nonsense
  • levels(book)How much waits at each price?best price first
  • top_of_book(depth)What are the best bid and ask?None for an empty side
  • quote_stats(top)What do the best prices tell us?None unless both sides exist
  • trades_to_bar(trades)What bar do these trades make?any order in
  • study(bars)Do the tiers agree on real SPY days?uses all of the above
What the real data saysthe first five daily bars of SPY and a book around the close of the first day
Trades per day40they add up to the real bar exactly
Orders in the book21after 33 events
Levels6 + 6bid levels and ask levels
Spread2.13bpsbest bid 93.68, best ask 93.70

Key takeaways

  • Each tier summarises the one above. Level 3 can make level 2 and level 1; level 1 can never give back the orders.
  • Replay, group, take the first. The book is built event by event, depth is a grouped and sorted view, and the best prices are the first level of each side.
  • Sort by time before you summarise. A bar's open and close depend on the order of the trades, not on the order they arrived in.
Quick check
Your turn. The bid side of a book holds two orders at 10.00 (100 and 300 shares) and one at 9.99 (50 shares). What does level 1 report for the best bid?
Pick an answer.
07

What you will build

The lab follows the lecture. Task 1 replays a level 3 feed into a book and task 2 sums the book into level 2. Task 3 takes the best prices for level 1 and task 4 computes the mid, the spread and the microprice from them. Task 5 builds a bar from trades, and task 6 runs the tiers on five real SPY days and on a book around the first close.

Next topic: you now know which data you hold. The next topic, Data quality rules and anomaly flags, asks whether it is right: bars where the high is below the close, prices that jump for no reason and days that repeat the same price all happen in real feeds, and a pipeline must flag them.

Lab · what's graded

6 tasks · 100 pts
  • Replay the orders20 pts
  • Sum into depth15 pts
  • The best prices10 pts
  • Mid, spread and microprice10 pts
  • Trades to a bar15 pts
  • The study on the SPY table30 pts
Explorer · lab-dp-04
▾ lab-dp-04
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-dp-04$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-dp-04 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes