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#

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

Text
strategy "Name" { costs: { commission: 2.5 usd, slippage: 1 tick }, fill_model: through, latency: 60ms }
KeySyntaxDefaultRules
costs{ commission: …, slippage: … }none: requiredMissing, or not an object: E939 "a strategy needs its costs". Either key missing or not a literal: E939.
commissiona 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.
slippagen 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_modelthrough, touch or queue, written without quotesthrough"queue" (a string) or another word gives E939.
latencya duration ≥ 0 (60ms, 0ms, 1s)60msA 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 writeIt means (ES)
8 ticks8 × 0.25 = 2.00
2 points2.00
22.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.

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

Text
enter(side, size: 1, type: "market", price:, stop:, target:, timeout:, expire:, tag:)  → bool
ParameterValuesDefaultBehavior
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.
sizenumber1Rounded, minimum 1 (2.6 → 3; 0 or −3 → 1).
type"market", "limit", "stop""market"Another text gives E939.
pricea price—Required for limit and stop. Missing **or na** gives E939 "needs price:". Ignored for market.
stopdistance > 0noneProtective 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.
targetdistance > 0noneProfit target at fill price ± target. ≤ 0 gives E939.
timeoutduration > 0noneMarket exit at the first trade at or after entry + timeout. A number gives E939.
expireduration > 0neverA pending entry is withdrawn at the first trade after decision + expire. A number gives E939.
tagtext""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.

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

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

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

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:

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

OrderFills
marketat the trade's price + adverse slippage
stop entrywhen a trade reaches or passes the level, at that trade's price + slippage
limit, touchat 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, queueat 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:

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

FieldContent
position.flatTrue when no position is open.
position.side"buy" or "sell"; na when flat.
position.sizeSigned: + long, − short, 0 flat.
position.entry_price, position.entry_timeEntry of the open position.
position.open_ticksGross open profit in ticks, at the last price processed.
position.open_rOpen profit in R; na without a stop.
position.mfe, position.maeMaximum favorable and adverse excursion so far, in gross ticks.
position.pendingNumber of pending orders, exits included.
position.tradesNumber of closed trades.
position.net_usdNet USD of the closed trades.

An unknown field gives E932 with the list of fields.

Reacting to fills and exits#

Text
on fill(f) { … }
on exit(x) { … }

A strategy acting on every trade, the rawest decision point:

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

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

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:

Text
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,tag

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

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.

Pitfalls#

STRATE / PRODUCT SCREENSHOT

Actual platform screenshot.