Guides
Strategies
A strategy script places simulated orders and produces a report. It never sends a real order, never touches an account, and is never copied to one.
- A first strategy
- The header: costs, fill model, latency
- Distances and units
- Entering:
enter() - Leaving:
exit()andcancel() - When a decision is made, and when it can fill
- How orders fill
- The open position:
position - Reacting to fills and exits
- The Report
- Exporting trades (CSV)
- Sweeping a setting
- Long backtests on MBO replay files
- Replay, multi-day runs and the fixed MBO start
- Pitfalls
A first strategy#
strategy "Bar breakout" { overlay: true, costs: { commission: 2.5 usd, slippage: 1 tick } }
len = input.int("Length", 20, min: 2)
hi = highest(high, len)
lo = lowest(low, len)
if position.flat and close > hi[1] {
enter("buy", stop: 8 ticks, target: 16 ticks, timeout: 30m)
}
if position.flat and close < lo[1] {
enter("sell", stop: 8 ticks, target: 16 ticks, timeout: 30m)
}
on exit(x) {
label.new(x.time, x.price, str(x.r, "+0.00") + " R", color: x.usd > 0 ? #22c55e : #ef4444)
}Entries are drawn as triangles and exits as dots (green for a winning trade, red for a losing one). The Report tab (panel mode Parameters) of the panel shows the results.
The simulation advances on trades: every fill, stop and target is decided against real trades of the market. A strategy script always loads trades, so this works on any chart that has them.
The header: costs, fill model, latency#
strategy "Name" { costs: { commission: 2.5 usd, slippage: 1 tick }, fill_model: through, latency: 60ms }| Key | Syntax | Default | Rules |
|---|---|---|---|
costs | { commission: …, slippage: … } | none: required | Missing, or not an object: E939 "a strategy needs its costs". Either key missing or not a literal: E939. |
commission | a number, with or without usd (2.5 usd = 2.5) | — | USD per contract and per side: a round trip costs 2 × commission × size. 0 usd is allowed; negative gives E939. It must be a literal, so it is neither a setting nor sweepable. |
slippage | n tick(s) = n ticks; a plain number or n point(s) = a price distance | — | slippage: 1 is 1 point = 4 ticks on ES. 0 tick is allowed. |
fill_model | through, touch or queue, written without quotes | through | "queue" (a string) or another word gives E939. |
latency | a duration ≥ 0 (60ms, 0ms, 1s) | 60ms | A number or a negative value gives E939. |
The point value and tick size come from the chart's instrument (50 and 0.25 on ES).
One position at a time. A pending entry counts as occupying the slot. There is no pyramiding and no direct reversal: exit first, then enter the other way.
The Report states the conditions of the simulation in one sentence, for example: simulated, in-sample over the loaded history; decision → exchange latency 60 ms; market and stop fills at the next eligible trade + 1 tick(s) slippage; limit fills: through (prudent); commission 2.5 usd per contract and side; one position at a time.
Distances and units#
Stops, targets and price offsets are price distances:
| You write | It means (ES) |
|---|---|
8 ticks | 8 × 0.25 = 2.00 |
2 points | 2.00 |
2 | 2.00 — a plain number is points, i.e. 8 ticks |
So stop: 2, target: 4, stop: 8 ticks, target: 16 ticks and stop: 2 points, target: 4 points give identical results. Be careful: stop: 4 is 16 ticks on ES, not 4.
A unit word only follows a number literal. With a setting, convert: price(n) turns ticks into a price distance, and ticks(d) turns a price distance into ticks.
strategy "Fade the stretch" { overlay: true, costs: { commission: 2.5 usd, slippage: 1 tick } }
len = input.int("Length", 20, min: 2)
k = input.float("Stretch", 1.5, step: 0.25)
stopTicks = input.int("Stop (ticks)", 8, min: 1)
basis = sma(close, len)
dev = stats.stdev(close, len)
if position.flat and close > basis + k * dev {
enter("sell", stop: price(stopTicks), target: price(stopTicks), timeout: 15m)
}
if position.flat and close < basis - k * dev {
enter("buy", stop: price(stopTicks), target: price(stopTicks), timeout: 15m)
}
plot(basis, title: "Basis")Entering: enter()#
enter(side, size: 1, type: "market", price:, stop:, target:, timeout:, expire:, tag:) → bool| Parameter | Values | Default | Behavior |
|---|---|---|---|
side | "buy" / "long" / a number > 0; "sell" / "short" / a number < 0 | — | na places nothing and returns false (no error), so enter(mySide, …) is safe when mySide may be na. Another text or 0 gives E939. |
size | number | 1 | Rounded, minimum 1 (2.6 → 3; 0 or −3 → 1). |
type | "market", "limit", "stop" | "market" | Another text gives E939. |
price | a price | — | Required for limit and stop. Missing **or na** gives E939 "needs price:". Ignored for market. |
stop | distance > 0 | none | Protective stop at fill price ∓ stop, computed from the actual fill price. ≤ 0 gives E939. Without a stop, results are in ticks and x.r / position.open_r are na. |
target | distance > 0 | none | Profit target at fill price ± target. ≤ 0 gives E939. |
timeout | duration > 0 | none | Market exit at the first trade at or after entry + timeout. A number gives E939. |
expire | duration > 0 | never | A pending entry is withdrawn at the first trade after decision + expire. A number gives E939. |
tag | text | "" | Carried by fills, exits, the trade list and the CSV. |
Returns true if the order was placed, false if a position is open or an entry is already pending (a second enter on the same bar returns false).
Outside a strategy, enter, exit and cancel give E939.
strategy "Buy the pullback" { overlay: true, costs: { commission: 2.5 usd, slippage: 1 tick }, fill_model: through }
offset = input.int("Offset (ticks)", 4, min: 1)
trend = ema(close, 50)
if position.flat and position.pending == 0 and close > trend {
enter("buy", type: "limit", price: close - price(offset), stop: 8 ticks, target: 8 ticks, expire: 5m, tag: "pullback")
}
plot(trend, title: "Trend")A stop entry above a range. highest(...) is na on the first bars, and a na price is an error, so it is guarded:
strategy "Range break" { overlay: true, costs: { commission: 2.5 usd, slippage: 1 tick } }
len = input.int("Range bars", 15, min: 2)
top = highest(high, len)
bottom = lowest(low, len)
if position.flat and position.pending == 0 and not na(top) {
enter("buy", type: "stop", price: top + 1 tick, stop: 8 ticks, target: 16 ticks, expire: 15m, tag: "up")
}
plot(top, title: "Top")
plot(bottom, title: "Bottom")Leaving: exit() and cancel()#
- **
exit(tag: "x")** closes the open position at market (the exit order can fill after the latency). Without a tag it closes whatever the tag. With a tag that differs from the position's, it does nothing. A secondexitwhile one is pending is ignored. The exit reason isexit. - **
cancel(tag: "x")withdraws pending entries** with that tag (all of them without a tag) and returns how many were withdrawn. It never touches a pending exit.
strategy "Manual management" { overlay: false, costs: { commission: 2.5 usd, slippage: 1 tick } }
var barsIn = 0
if position.flat {
barsIn = 0
if close > open and close > close[1] {
enter("buy", stop: 8 ticks, tag: "momo")
}
} else {
barsIn += 1
// leave after 5 closed bars, or at the first bar close where the trade shows 6 ticks of open profit
if barsIn >= 5 or position.open_ticks >= 6 {
exit(tag: "momo")
}
}
plot(position.size, title: "Size")When a decision is made, and when it can fill#
- In a handler (
on trade,on order,on match,on book,on session,on signal,on fill,on exit), in a clock, or in an event pattern, the decision is made at the event's time. - In the body (and in
on: barpatterns), the decision is made at the bar's known close: open + unit for time bars, the open of the next bar for other bar types. - An order can only fill on trades strictly after
decision + latency.
Example on one-minute bars: a decision on the 19:49 bar is made at 19:50:00; with latency: 60ms the order can fill from 19:50:00.060, at the first trade after that.
How orders fill#
For each trade (price p, size v), in this order:
1. An open position is checked. Its MFE and MAE are updated (in ticks from the entry), then:
- stop: triggered when a trade touches or crosses the stop level. Exit at that trade's price minus slippage (reason
stop). - target: with
touchorqueue, as soon as a trade touches it; withthrough, a trade must go at least 1 tick beyond. Exit at the target price exactly, without slippage (reasontarget). - timeout: the first trade at or after entry + timeout. Exit at the trade price minus slippage (reason
timeout).
The trade that opened the position is not tested against its stop and target; they start with the next trade.
2. Pending orders that are eligible (after the latency; an expired entry is removed first):
| Order | Fills |
|---|---|
| market | at the trade's price + adverse slippage |
| stop entry | when a trade reaches or passes the level, at that trade's price + slippage |
limit, touch | at the limit price, as soon as a trade is at the limit or better |
limit, through (default) | at the limit price, when a trade is at least 1 tick beyond it |
limit, queue | at the limit price, once the volume ahead of the order in the queue has traded (see below), or when a trade goes 1 tick beyond |
**The queue model.** The volume ahead of your simulated order is the size of the resting orders at that price that arrived before your order became eligible, read from the order-by-order book. It can only decrease: cancels and fills of those orders reduce it, and each trade at your price removes its size. Your order fills when that volume is used up on a trade at your price, or when price trades 1 tick through. Without order-by-order data, the volume ahead is 0 and queue behaves like touch. On a chart, fill_model: queue is enough to load order-by-order data. In a long backtest it is not: the book is only rebuilt for a script that also reads order-by-order data (on order, on match, mbo. or of.ofi(); otherwise queue behaves like touch there.
3. The result of a closed trade:
ticksare net of commission, per contract: gross ticks −2 × commission / (tick × point value);usd= gross USD × size −2 × commission × size;r= net ticks ÷ stop distance in ticks.
For example, on ES, a trade that reaches an 8-tick target with an 8-tick stop, on 3 contracts with a 2.5 USD commission, gives 7.6 ticks, 285 USD and 0.95 R.
The open position: position#
Only in a strategy (E939 elsewhere).
| Field | Content |
|---|---|
position.flat | True when no position is open. |
position.side | "buy" or "sell"; na when flat. |
position.size | Signed: + long, − short, 0 flat. |
position.entry_price, position.entry_time | Entry of the open position. |
position.open_ticks | Gross open profit in ticks, at the last price processed. |
position.open_r | Open profit in R; na without a stop. |
position.mfe, position.mae | Maximum favorable and adverse excursion so far, in gross ticks. |
position.pending | Number of pending orders, exits included. |
position.trades | Number of closed trades. |
position.net_usd | Net USD of the closed trades. |
An unknown field gives E932 with the list of fields.
Reacting to fills and exits#
on fill(f) { … }
on exit(x) { … }f:time,price,side("buy"/"sell"),size,tag.x:time,price,side(the side of the position that closed),reason(stop,target,timeout,exit, andend_of_datain long backtests),ticksandusd(net),r(nawithout a stop),entry_price,tag.- Any other field gives E932 with the list. Outside a strategy, these handlers give E939.
A strategy acting on every trade, the rawest decision point:
strategy "Follow large prints" { overlay: true, costs: { commission: 2.5 usd, slippage: 1 tick }, latency: 60ms }
minSize = input.int("Min size", 5, min: 1)
on trade(t) {
if position.flat and t.size >= minSize {
enter(t.delta > 0 ? "buy" : "sell", stop: 6 ticks, target: 12 ticks, timeout: 10m, tag: "print")
}
}
on fill(f) {
print("fill", f.side, f.size, f.price, f.tag)
}
on exit(x) {
print("exit", x.reason, x.ticks, x.usd, x.r)
}A strategy driven by the order-by-order book, with queue-position fills:
strategy "Join the defended bid" { overlay: true, mbo_from: rth, level_history: 2m, fill_model: queue, latency: 60ms, costs: { commission: 2.5 usd, slippage: 1 tick } }
minRefills = input.int("Min refills", 3, min: 1)
on match(m) {
// a seller hit the bid: was that bid refilled several times in the last 20 seconds?
if position.flat and position.pending == 0 and m.side == "sell" and mbo.available {
lv = mbo.level(m.price, window: 20s)
if lv.replenishments >= minRefills {
enter("buy", type: "limit", price: m.price, stop: 6 ticks, target: 6 ticks, expire: 30s, tag: "defended")
}
}
}
on exit(x) {
print(x.reason, x.ticks, x.r)
}The Report#
The Report tab shows, for all trades and separately for buys and sells:
- the number of trades, the number of sessions with entries, and whether a position is still open (not counted);
- win rate (a trade at exactly 0 counts as a loss), mean result per trade, and its 95% confidence interval;
- average win, average loss, and a check line:
win% × avg win + loss% × avg loss = mean; - total, net USD, maximum drawdown (in the report's unit and in USD), worst losing streak;
- how trades exited: target, stop, timeout, exit (in %;
end_of_dataexits are counted apart, so the sum can be below 100); - average MFE and MAE in ticks;
- the equity curve (up to 300 points, the deepest drawdown point always kept);
- the latest 200 trades, most recent first.
Unit. Results are in R when every trade of the group had a stop; otherwise in ticks.
Confidence interval. A bootstrap over days (1,000 draws), so a single exceptional day cannot fake a narrow interval. It needs at least 2 days.
DEV / VAL. On a chart, the sessions of the loaded bars are split in two halves: DEV (the first half) and VAL (the second half), with the cut at session index ⌊n/2⌋. The Report gives the number of trades and the mean for each half, so you can see whether a result holds on data that was not used to choose it. With fewer than 2 sessions there is no split. A CME session is dated by its New York trading date; it starts at 18:00 the evening before.
The Report also shows how many settings the script declares: the more settings were tuned, the more a good DEV result can be luck.
Exporting trades (CSV)#
Export trades (CSV) in the Report writes every closed trade (up to 200,000; beyond that, the most recent, with a final comment line) to your Downloads folder, named Strate-trades-<name>-YYYYMMDD-HHMMSS.csv.
Columns:
side,size,entry_time_utc,entry_time_ns,entry_price,exit_time_utc,exit_time_ns,exit_price,reason,net_ticks,net_r,net_usd,mfe_ticks,mae_ticks,cum_usd,tagTimes are UTC (ISO 8601 with milliseconds, and nanoseconds); results are net; comma separator, decimal point.
Sweeping a setting#
A sweep runs the strategy for a range of values of one setting and shows where results hold up, from the Report:
- choose an
input.intorinput.floatsetting by its title (other settings cannot be swept), a start, an end and a step; at most 40 values; - each value is measured on the DEV half only, with the same split as the Report. VAL is never looked at by a sweep;
- for each value: mean per trade with its 95% interval (day bootstrap), number of trades and days, win rate, net USD, maximum drawdown in USD.
Plateau, not best point. The sweep smooths each value's mean with its neighbors (3 values) and looks for the longest run of at least 3 consecutive values whose smoothed mean is positive. It shows the center of that plateau, and flags the best isolated point outside it as probable noise. It never proposes "the best" value. The intended use is: keep the center of a plateau, then judge that single value once on VAL.
Time limit. You choose 30 s, 2 min (default), 10 min or no limit (60 min). A strategy that reads order-by-order or book data from a fixed start runs in the background with progress and a Stop button. Other strategies are computed at once, within 60 seconds whatever the choice. When the limit would be exceeded, the sweep stops before the next value and says how many values it tried.
Costs and latency are header literals, so they cannot be swept.
Long backtests on MBO replay files#
From the Report you can run a strategy (or a research script) over many days of local MBO replay files, off the chart.
Files. A folder of MBO replay files, one per day, with the extension .dbn or .dbn.zst and an 8-digit date YYYYMMDD in the name. Choose a date range (empty = all), at most 600 days.
Bars. The chart's unit, time-based only, from 1 second to 1 day. Bars are built from the trades of the file's most active contract. At most 20,000 bars per day (only intervals with trades count).
Hours window. An optional New York window HH:MM-HH:MM within one day. For a script that reads order-by-order data (on order, on match, mbo., of.ofi(), the book is rebuilt from the start of the file up to the window's start. More than 15,000,000 order-by-order events in one day's window gives E960: narrow the window (for example 09:30-16:00).
Each file runs on its own. Variables restart each day. A position still open at the end is closed at the last trade processed (the end of the window if there is one), with slippage, reason end_of_data, counted apart. Studies too close to the end are incomplete. Only session.* and prev.* see the previous days (up to 8) of the same contract.
Not available in a long backtest: book snapshots (book.*), footprints, request(…, symbol:) (all na), and nothing is drawn. Trades one by one are complete, sweep fields included.
DEV / VAL, declared before running. Set "VAL from" (empty = the middle day of the range). By default VAL is not read: the report shows DEV only. Choose to read VAL once you have fixed your settings. Trades and studies of a VAL session that fall inside a DEV file are left out.
Sweep. A long backtest can include a sweep (same grid, 40 values at most), run on the DEV days only and shown as a plateau.
Running. One long backtest at a time; it can be stopped between blocks of data. The default time limit is 120 minutes. Errors: E960 (a day could not be read), E961 (the script failed on a given day, with the date and line).
Replay, multi-day runs and the fixed MBO start#
On a chart, a strategy starts reading order-by-order data and book snapshots at a fixed point (mbo_from: auto by default: 9:30 New York if launched during RTH, otherwise 18:00). Its results therefore do not drift as the chart scrolls. The available starts, the meaning of "launch" and how memory stays constant are explained in Order flow: how much history.
- Editing the code or a setting recalculates the strategy from the same start, in the background.
- Moving the Replay back before the launch relaunches it from the cursor.
- The bar window starts at the launch (the last 4,000 to 8,000 bars of the chart, or all of them if there are fewer) and grows up to 48,000 bars, then its start moves forward by 8,000 bars; the Report says what is no longer simulated. A strategy that reads the footprint receives the chart's last 2,000 bars instead (see Market data).
Pitfalls#
- **Unknown header keys and unknown
enter()arguments are ignored.**latancy: 60mskeeps the default latency;stopp: 4 ticksplaces a trade with no stop at all. Check names against this page. - A plain number is points:
stop: 4is 16 ticks on ES. - A
limitorstopentry with anaprice is an error: guard withnot na(x). - The check runs your script on a short synthetic market. An error in a branch that never runs there (for example a limit entry without
price:behind a condition that is never true) appears on the chart when that line first runs. persistis not allowed in a strategy (E943): usevar.