Guides
Order flow
This page covers the deepest data a script can read: every event of the order-by-order (MBO) feed, the order book built from it, statistics per price level, aggregated book snapshots, and the of module. It ends with worked examples written directly with these primitives.
- Order events:
on order - Executions:
on match - The order-by-order book:
mbo - Level statistics:
mbo.level - Book snapshots:
on bookandbook - The
ofmodule - Event order and causality
- How much history
- Worked examples
Order-by-order data is available in Replay of recorded sessions, live (Strate records the feed for the instruments your scripts read), and in long backtests. See Market data. Without it, everything on this page that starts with mbo returns na, and on order / on match never run — no error is raised. Always test mbo.available or na(x) where it matters.
Order events: on order#
on order(o) { … }Runs for every event of the order-by-order feed that changes a resting order: add, cancel, modify and fill. It runs in exchange order, interleaved with trades and book snapshots (see Event order).
| Field | Value |
|---|---|
o.time | Event time. |
o.id | Order id. |
o.action | "add", "cancel", "modify" or "fill". Compare with a string: o.action == "add". |
o.is_add, o.is_cancel, o.is_modify, o.is_fill | Bools. |
o.side | Resting side, "bid" or "ask". A fill against a buying aggressor is on the "ask" side. |
o.price | Price of the event. For a modify: the new price. |
o.size | Add: the size. Cancel: the size removed. Modify: the new size. Fill: the size filled. |
o.queue_position | Rank in its price queue before the event, 0 = front of the queue. na on an add. |
o.priority_lost | True for a modify that increased the size or moved the price (the order goes to the back of the queue). |
o.previous_size, o.previous_price | The order's size and price before the event. na on an add. |
o.age | Duration since the order's original add (a modify does not reset it). na on an add. |
o.modifications | Number of modifies before this event (the current modify is not counted; 0 on an add). |
When on order runs, the book (mbo) already includes the event: mbo.size(o.price) is the size after it. The fields queue_position, previous_size and previous_price describe the order before it.
Queue rules. A size decrease keeps the order's place in the queue. A size increase or a price change sends it to the back of the queue at its new price. A partial cancel keeps the place. A modify of an unknown order is treated as an add; cancels and fills of unknown orders leave the book unchanged. on order still runs for them, with queue_position, previous_size, previous_price and age set to na.
indicator "Pulled at the front" { overlay: false }
state pulled = 0
on order(o) {
// a resting order canceled while it was first in its queue
if o.is_cancel and o.queue_position == 0 { pulled += o.size }
}
histogram(pulled, #ef5350, title: "Size pulled at the front")
pulled = 0Executions: on match#
on match(m) { … }One call per aggressive order execution: the aggressor's trade record(s) together with every resting order it hit at the same timestamp. A sweep across several prices is one match. It runs once the execution is complete (after its last fill) and before the on trade calls of that execution.
| Field | Value |
|---|---|
m.time | Timestamp. |
m.side | Aggressor side, "buy" or "sell". |
m.size | Total aggressor size, all prices together. |
m.first_price, m.price | First and last price traded. |
m.levels | Price span in ticks + 1: abs(last − first) / tick + 1. A sweep that skips a price still counts it. (For the number of distinct prices traded, use t.levels in on trade.) |
m.fills | Number of resting-order fills. |
m.largest_fill | Largest single fill (na if none). |
m.orders | List of the ids of the resting orders hit, in order. |
m.aggressor_id | Id of the aggressive order, na when the feed gives none. |
indicator "Orders hit per execution" { overlay: false }
state most = 0
on match(m) {
if m.orders.len() > most { most = m.orders.len() }
}
histogram(most, #2962ff, title: "Most resting orders hit by one execution")
most = 0The order-by-order book: mbo#
mbo is the book rebuilt from every order. It can be read anywhere: in the body, in handlers and in patterns. It shows the state after the latest order-by-order event processed.
Fields
| Field | Value |
|---|---|
mbo.available | False until the first order-by-order event. |
mbo.orders | Number of resting orders. |
mbo.time | Time of the latest order-by-order event. |
mbo.best_bid, mbo.best_ask | Best prices; na if a side is empty. |
Methods (prices are rounded to the tick; everything returns na when mbo.available is false)
| Method | Returns |
|---|---|
mbo.size(price) | Resting size at the price. |
mbo.count(price) | Number of resting orders at the price. |
mbo.queue(price) | List of the sizes in the queue, front first. |
mbo.orders(price) | List of the resting orders at the price, front first. |
mbo.mean_age(price) | Size-weighted mean age (a duration) of the orders at the price; na if none. |
mbo.order(id) | One resting order, or na if it is gone. |
mbo.levels(side, n = 10) | Prices of the n best levels of a side, best first. side is bid/ask (buy/sell accepted), E933 otherwise; n is clamped to 1…500. |
mbo.large(min_size) | Resting orders of at least min_size, biggest first (ties: lower id first), at most 500. A negative or na size gives E933. |
mbo.level(price, …) | Statistics of a price level over a window. See Level statistics. |
A resting order (from mbo.orders(price), mbo.order(id), mbo.large(n)) has the fields .id, .side, .price, .size, .age, .position (0 = front of its queue) and .modifications.
Ages are measured at mbo.time, the time of the latest order-by-order event, not at the bar's close.
indicator "Large resting orders" { overlay: true }
minSize = input.int("Min size", 50, min: 1)
if bar.last {
for o in mbo.large(minSize) {
label.new(bar.time, o.price, o.side + " " + str(o.size) + " #" + str(o.position) + " " + str(o.age), color: o.side == "bid" ? #26a69a : #ef5350)
}
}
plot(close, title: "Close")indicator "Queue at the best bid" { overlay: false }
bb = mbo.best_bid
q = mbo.queue(bb)
plot(na(bb) ? na : q.len(), #2962ff, title: "Orders at best bid")
plot(na(bb) or q.len() == 0 ? na : q.first(), #e8c15a, title: "Size at the front")
plot(na(bb) ? na : mbo.mean_age(bb) / 1s, #ffffff80, title: "Mean age (s)")Level statistics: mbo.level#
lv = mbo.level(price, window: 30s, depleted_below: 0, refill_within: 2s, same_id_only: false)Everything that happened at one price over a sliding window that ends at mbo.time.
window: a duration > 0 (default30s). Another value gives E933.- The engine keeps the per-price history for the duration set by the header key
level_history:(default2m, at most30m). A window longer than that gives E933 with the header line to add, e.g.level_history: 3m. depleted_below: a level counts as depleted when its displayed size falls to this value or below (default 0).refill_within: how soon after a depletion a refill must happen to count (default2s).same_id_only: count only refills by orders already seen at that price.- Returns
nabefore any order-by-order event, or without order-by-order data.
| Field | Meaning |
|---|---|
lv.price, lv.window | The price and the window. |
lv.displayed | Resting size at the price now. |
lv.queue_length | Number of resting orders now. |
lv.mean_order_age | Size-weighted mean age of those orders now. |
lv.added | Size added in the window: adds, size increases, orders moved to this price. |
lv.canceled | Size removed without trading: cancels, size decreases, orders moved away. |
lv.filled | Size of displayed resting orders filled. |
lv.net | added − canceled − filled. |
lv.cancel_ratio | canceled / added; na if nothing was added. |
lv.aggressor_hits, lv.aggressor_volume | Number and volume of aggressor trades at the price. |
lv.depletions | Times the displayed size fell to depleted_below or less. |
lv.replenishments | Refills: displayed size back above the threshold within refill_within of a depletion (only same-id refills if same_id_only). |
lv.refill_same_id, lv.refill_new_id | Refills by an order already seen at that price, and by other orders. |
lv.refill_delay | Median refill delay (a duration), na if none. |
lv.time_at_best | How long (a duration) the price was the best bid or best ask during the window. |
Memory: the per-price history keeps every event for the level_history: duration. On a very active market, long histories use a lot of memory; keep it as short as your windows allow.
indicator "Hidden volume at the best ask" { overlay: false, level_history: 5m }
win = input.duration("Window", 2m)
lv = mbo.level(mbo.best_ask, window: win)
plot(na(lv) ? na : lv.hidden_filled, #e040fb, title: "Hidden filled")
plot(na(lv) ? na : lv.aggressor_volume, #2962ff, title: "Aggressor volume")Book snapshots: on book and book#
Aggregated snapshots of the book (size per price), every 250 ms, within 300 ticks of the center. Each snapshot shows the book at the end of its 250 ms step and is dated there, so it never shows anything early.
book is the latest snapshot and can be read anywhere. At the start of a bar it is the last snapshot before that bar. on book(b) runs for every snapshot; b has the same fields and methods as book.
| Field | Value |
|---|---|
available | False without book data. |
time | Time of the snapshot. |
best_bid, best_ask, mid, spread | Prices. |
bid_size, ask_size | Size at the best bid and best ask. |
microprice | (bid × ask_size + ask × bid_size) / (bid_size + ask_size); the mid if both sizes are 0. |
| Method | Returns |
|---|---|
size(price) | Size at the price; na outside the 300-tick range. |
depth(side, levels = 10) | Total size of levels price levels from the best price of a side (bid/ask/buy/sell, else E933); levels is clamped to 1…300. |
imbalance(levels = 10) | (bids − asks) / (bids + asks) over levels levels, from −1 to +1; na if empty. |
book.imbalance without parentheses is a field error (E932): write book.imbalance().
History. Indicators replay the last book_history: of snapshots (default 2h, start rounded down to the hour, never before the first bar). Strategies and research scripts start at a fixed point (see How much history).
indicator "Book imbalance" { overlay: false, min: -1, max: 1 }
levels = input.int("Levels", 5, min: 1, max: 300)
plot(book.imbalance(levels), #2962ff, title: "Imbalance")
plot(na(book.microprice) ? na : (book.microprice - book.mid) / instrument.tick, #e8c15a, title: "Microprice - mid (ticks)")
hline(0)The of module#
Aggressor flow over a time window, ending at the latest event processed.
| Function | Returns |
|---|---|
of.cvd(reset: "session") | Cumulative bar delta, reset at each "session", "day", "rth" (first RTH bar) or "none". Another value gives E933. |
of.flow(side = "both", window = 30s) | Aggressor volume per second over the window. side is "buy", "sell" or "both" (else E933); window a duration (else E933). |
of.trade_count(side = "both", window = 30s) | Number of trades. |
of.aggression(window = 30s) | (buy − sell) / total, from −1 to +1; na without trades. |
of.decay(side = "both", window = 30s) | Volume of the last third of the window divided by the volume of the first third; na if the first third is empty. |
of.burst(side = "both", window: 1s, min_trades: 10) | True when the window holds at least min_trades trades. |
of.vpin(bucket, buckets: 50) | 0 to 1: the mean of abs(buy − sell) / bucket over the last buckets full buckets of bucket contracts. bucket must be > 0 (E933); buckets is clamped to 1…1000; na until enough buckets are full. |
of.ofi(window = 30s) | Order flow imbalance at the best bid and ask, summed over the window. Needs order-by-order data; na otherwise. |
- Arguments may be positional or named (
side:,window:). - The window ends at the latest event processed: in a handler, the event's time; in the body, the bar's last event (a book snapshot, a trade or an order-by-order event), not the bar's close.
of.ofiends at the later of that andmbo.time. of.flowandof.trade_countreturn 0 when the window has no trade.- History is kept for
flow_history:(default5m, at most60m). A window longer than the history gives E933 with the header line to add.
indicator "Flow" { overlay: false }
win = input.duration("Window", 30s)
plot(of.flow("buy", win), #26a69a, title: "Buy volume / s")
plot(-of.flow("sell", win), #ef5350, title: "Sell volume / s")
plot(nz(of.ofi(win)), #e8c15a, title: "OFI")
hline(0)indicator "CVD" { overlay: false }
plot(of.cvd(reset: "rth"), #2962ff, title: "CVD since the RTH open")
plot(cum(delta), #ffffff60, title: "CVD since the first bar")Event order and causality#
- Events are processed by time. At the same timestamp: order-by-order events first, then trades, then the book snapshot.
- One execution produces
on orderfor each fill andon matchonce, and itson matchalways runs before its firston trade. When several executions share the same timestamp, all their order-by-order events come first (soon orderandon matchof several executions can alternate), then all their trades. - All events of a bar run before the bar's body. Clocks fire after the handlers and patterns of the event that closed them.
- Inside handlers,
open,high,low,close,volumeanddeltadescribe the bar so far;bar.delta_highandbar.delta_lowarena;bar.footprintgives E911. statevariables, settings and constants are visible in handlers. A value computed in the body and stored in astatevariable is, inside a handler, the value from the last closed bar.- No order-by-order function looks back in the event stream. The past a script can see is bounded by
level_history:,flow_history:, and whatever it stores in its own variables.
indicator "Sequence" { overlay: false }
state k = 0
on order(o) {
if o.is_fill {
k += 1
label.new(o.time, o.price, str(k) + " fill of order " + str(o.id))
}
}
on match(m) {
k += 1
label.new(m.time, m.price, str(k) + " match " + str(m.size))
}
on trade(t) {
k += 1
label.new(t.time, t.price, str(k) + " trade " + str(t.size))
}
plot(k, title: "Events so far")How much history#
Indicators use rolling windows:
- order-by-order data: the last
mbo_history:(default30m); the window starts at the latest :00 or :30 beforenow − mbo_history, and never before the first bar; - book snapshots: the last
book_history:(default2h).
Strategies and research scripts start at a fixed point, so that their results do not change as time passes. The start is set by mbo_from: (and book_from: for snapshots, which falls back to mbo_from:):
| Value | Start |
|---|---|
auto (default) | 9:30 New York if launched during RTH, otherwise 18:00 (start of the CME session) |
launch | The minute the script was launched |
rth | The latest 9:30 at or before launch |
session | The latest 18:00 at or before launch |
"HH:MM" | The latest time HH:MM (New York) at or before launch |
start | The first bar of the chart |
rolling | A rolling window, like an indicator |
An indicator may also set mbo_from: to get a fixed start. In a strategy or research header, mbo_history: 2h without mbo_from: means "two hours before launch", rounded down to the half hour.
Launch. The launch is the first run of the script on that chart (same instrument, tick, timeframe and Replay session). Editing the code or the settings, scrolling or zooming does not relaunch it: the script is recalculated from the same start, reading the data again in the background. Moving the Replay back before the launch, or removing the script and adding it again, relaunches it.
Memory. With a fixed start, data is read as a stream: memory stays roughly constant however long the run. What is held in memory is the bar not closed yet, plus what the script keeps (level and flow histories, norm windows, its own variables). mbo_max: bounds the order-by-order events held for one bar that has not closed (default 25,000,000; about 32 bytes per event). Exceeding it gives E944: use a shorter timeframe or raise mbo_max:. An open bar also holds at most 8 hours of book snapshots.
strategy "Fixed start" { overlay: true, mbo_from: "08:00", costs: { commission: 2.5 usd, slippage: 1 tick } }
plot(mbo.orders, title: "Resting orders")Worked examples#
These examples are written with the raw primitives so you can see, and change, every step. Each one is only one possible definition: absorption, icebergs or spoofing have no single correct formula. The shipped pattern library offers several competing definitions as well (see Patterns).
Absorption: heavy hitting at a price that holds#
Aggressors keep trading into one price, yet that price is still displayed and has stayed at the best for most of the window. The heavy volume is measured against its own recent values with norm.rank (see Normalization), computed at every execution so the comparison population is not biased by the other conditions.
indicator "Absorption (raw)" { overlay: true, level_history: 2m }
win = input.duration("Window", 30s)
minRank = input.float("Min volume rank", 95, min: 0, max: 100)
heldPct = input.float("Held at best (% of window)", 60, min: 0, max: 100)
on match(m) {
lv = mbo.level(m.price, window: win)
if not na(lv) {
// rank of this price's aggressor volume among the values seen over the last 30 minutes
rk = norm.rank(lv.aggressor_volume, 30m, min_count: 50)
held = lv.time_at_best >= win * heldPct / 100
if rk >= minRank and held and lv.displayed > 0 {
// buyers hitting the ask that holds: sellers absorbed them
label.new(m.time, m.price, (m.side == "buy" ? "ask absorbs " : "bid absorbs ") + str(lv.aggressor_volume), color: m.side == "buy" ? #ef5350 : #26a69a)
}
}
}
plot(close, title: "Close")Iceberg-like refills: more traded than displayed#
At an iceberg, the visible size is refilled after each fill, so more volume trades than was ever displayed. hidden_filled measures the excess; refill_same_id counts refills by an order already seen at that price.
indicator "Refills (raw)" { overlay: true, level_history: 2m }
win = input.duration("Window", 60s)
minHidden = input.int("Min hidden volume", 20, min: 1)
minRefills = input.int("Min refills", 2, min: 1)
on trade(t) {
if not na(t.levels) and t.sweep_end {
lv = mbo.level(t.price, window: win, refill_within: 2s)
if not na(lv) and lv.hidden_filled >= minHidden and lv.replenishments >= minRefills {
label.new(t.time, t.price, "refill " + str(lv.hidden_filled) + " / " + str(lv.refill_same_id) + " same id", color: #e040fb)
}
}
}
plot(close, title: "Close")Pulled liquidity: large orders canceled before they trade#
A large order near the best price that is canceled in full after a short life. Each cancel is inspected individually: its size before the cancel, its age, how far it rested from the best price of its side. Only cancels that remove the whole order count (mbo.order(o.id) is na once it is gone); a partial cancel only removes o.size. The order may have traded partly before it was canceled: Pulled before touch shows how to keep a memory of fills and leave those orders out.
indicator "Pulled size (raw)" { overlay: true }
minSize = input.int("Min size", 50, min: 1)
maxAge = input.duration("Max age", 5s)
maxTicks = input.int("Max distance from best (ticks)", 4, min: 0)
state pulledBid = 0
state pulledAsk = 0
on order(o) {
if o.is_cancel and na(mbo.order(o.id)) and o.previous_size >= minSize and o.age <= maxAge {
best = o.side == "bid" ? mbo.best_bid : mbo.best_ask
if not na(best) and abs(o.price - best) <= maxTicks * instrument.tick {
if o.side == "bid" { pulledBid += o.previous_size } else { pulledAsk += o.previous_size }
label.new(o.time, o.price, "pulled " + str(o.previous_size) + " after " + str(o.age), color: #ffb300)
}
}
}
stat("Bid pulled", pulledBid, format: "0")
stat("Ask pulled", pulledAsk, format: "0")
pulledBid = 0
pulledAsk = 0Queue position of a resting order#
The front of the queue at the best bid, order by order, with each order's age and position.
indicator "Best bid queue" { overlay: true }
if bar.last and mbo.available {
i = 0
for o in mbo.orders(mbo.best_bid) {
if i < 5 { label.new(bar.time, o.price, "#" + str(o.position) + " id " + str(o.id) + " size " + str(o.size) + " age " + str(o.age)) }
i += 1
}
}
plot(close, title: "Close")