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-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#

Text
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).

FieldValue
o.timeEvent time.
o.idOrder 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_fillBools.
o.sideResting side, "bid" or "ask". A fill against a buying aggressor is on the "ask" side.
o.pricePrice of the event. For a modify: the new price.
o.sizeAdd: the size. Cancel: the size removed. Modify: the new size. Fill: the size filled.
o.queue_positionRank in its price queue before the event, 0 = front of the queue. na on an add.
o.priority_lostTrue 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_priceThe order's size and price before the event. na on an add.
o.ageDuration since the order's original add (a modify does not reset it). na on an add.
o.modificationsNumber 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.

StrateScript
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 = 0

Executions: on match#

Text
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.

FieldValue
m.timeTimestamp.
m.sideAggressor side, "buy" or "sell".
m.sizeTotal aggressor size, all prices together.
m.first_price, m.priceFirst and last price traded.
m.levelsPrice 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.fillsNumber of resting-order fills.
m.largest_fillLargest single fill (na if none).
m.ordersList of the ids of the resting orders hit, in order.
m.aggressor_idId of the aggressive order, na when the feed gives none.
StrateScript
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 = 0

The 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

FieldValue
mbo.availableFalse until the first order-by-order event.
mbo.ordersNumber of resting orders.
mbo.timeTime of the latest order-by-order event.
mbo.best_bid, mbo.best_askBest prices; na if a side is empty.

Methods (prices are rounded to the tick; everything returns na when mbo.available is false)

MethodReturns
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.

StrateScript
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")
StrateScript
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#

Text
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.

FieldMeaning
lv.price, lv.windowThe price and the window.
lv.displayedResting size at the price now.
lv.queue_lengthNumber of resting orders now.
lv.mean_order_ageSize-weighted mean age of those orders now.
lv.addedSize added in the window: adds, size increases, orders moved to this price.
lv.canceledSize removed without trading: cancels, size decreases, orders moved away.
lv.filledSize of displayed resting orders filled.
lv.netadded − canceled − filled.
lv.cancel_ratiocanceled / added; na if nothing was added.
lv.aggressor_hits, lv.aggressor_volumeNumber and volume of aggressor trades at the price.
lv.hidden_filledAggressor volume minus displayed volume filled (never below 0): volume that executed beyond what was displayed.
lv.depletionsTimes the displayed size fell to depleted_below or less.
lv.replenishmentsRefills: 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_idRefills by an order already seen at that price, and by other orders.
lv.refill_delayMedian refill delay (a duration), na if none.
lv.time_at_bestHow 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.

StrateScript
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.

FieldValue
availableFalse without book data.
timeTime of the snapshot.
best_bid, best_ask, mid, spreadPrices.
bid_size, ask_sizeSize 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.
MethodReturns
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).

StrateScript
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.

FunctionReturns
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.
StrateScript
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)
StrateScript
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#

StrateScript
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:

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:):

ValueStart
auto (default)9:30 New York if launched during RTH, otherwise 18:00 (start of the CME session)
launchThe minute the script was launched
rthThe latest 9:30 at or before launch
sessionThe latest 18:00 at or before launch
"HH:MM"The latest time HH:MM (New York) at or before launch
startThe first bar of the chart
rollingA 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.

StrateScript
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.

StrateScript
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.

StrateScript
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.

StrateScript
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 = 0

Queue position of a resting order#

The front of the queue at the best bid, order by order, with each order's age and position.

StrateScript
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")
STRATE / PRODUCT SCREENSHOT

Actual platform screenshot.