Guides

The language

This page describes the whole StrateScript language: how a script is laid out, what it can declare, and how values, variables and history work. Data sources (bars, trades, the order book) have their own pages: Market data and Order flow.

How a script runs#

Lexical rules#

ElementRule
EncodingUTF-8 text. Names (identifiers) are ASCII only: [A-Za-z_][A-Za-z0-9_]*. A name with an accented letter gives E005.
Comments// … to the end of the line, and /* … */ over several lines (not nested; an unclosed /* gives E001).
Numbers20, 0.5, 1_000_000 (underscores as separators), 1e3, 2.5e-1. Write 0.5, not .5.
DurationsA number with a unit attached, no space: ns us ms s m h d w. m is minutes (there is no month unit). 1.5h is allowed.
Strings"…" on a single line. Escapes: \n, \t, \", \\. A line break inside a string gives E002.
Colors#RRGGBB or #RRGGBBAA in hexadecimal (#26a69a, #26a69a80 for 50% opacity). Anything else gives E003.
QuantitiesA number, a space, then a unit word: 4 ticks, 2 points, 2.5 usd. See Units. 4ticks (no space) gives E004.

Reserved words cannot be used as variable names: indicator research strategy pattern import as from fn type enum method var state const persist on when if else for in while return break continue and or not true false na self.

Built-in names such as close, plot or buy are not reserved. Assigning to one hides it for the rest of the script: after close = 5, close is 5. Avoid it.

Built-in text constants. A few names stand for the text of the same spelling, so they can be written without quotes: buy, sell, bid, ask, long, short, solid, dashed, dotted, left, right, both, center, full. side: right is the same as side: "right", and mbo.levels(bid, 3) the same as mbo.levels("bid", 3). This guide uses both forms.

End of statement. A statement ends at the end of the line or at ;. A line continues on the next one when:

  1. it is inside ( … ) or [ … ];
  2. it ends with an operator, a comma, ?, : or .;
  3. the next line starts with and, or, ?, :, ., .., *, /, %, +, a comparison or else.

A line that starts with - is a new statement, not a continuation.

StrateScript
x = 1 +
  2
y = (1
  + 2)
ok = true
  and false
print(x, y, ok)   // → 3 3 false
StrateScript
n = 1_000_000 + 2.5e-1
d = 250ms + 1.5s
c = #26a69a80
s = "tab:\t quote:\" newline:\n"
print(n, d, c)   // → 1000000.25 1750ms #26a69a80

Script kinds#

KindPurposeSpecific rules
indicator "Name"Draws on a chart. This is the default when there is no header.The only kind that may use persist, and only with a non-empty name.
strategy "Name"Simulated orders, with a report. Never sends a real order.costs: is required in the header. enter, exit, cancel, position.*, on fill and on exit are only allowed here. See Strategies.
research "Name"Measures what happens after a signal.study(), report() and compare() are only allowed here. See Research.

The name can be empty (indicator ""). It identifies the script for My indicators, for imports (my/<name>) and for persist memory.

The header#

Text
indicator "Name" { key: value, key: value }

There is at most one header, and it must come before any other statement (E104). Settings are separated by commas or line breaks. A value is an expression or an object { … }.

Display keys (all kinds)#

KeyValuesDefaultError
overlaytrue draws on the price chart. Only the literal false creates a separate pane.true—
candlesfalse hides the chart's candles while the script is shown.candles visible—
heightPane height in pixels, 40 to 800. A height the user sets by dragging takes priority.140—
backgroundPane background color #rrggbb[aa].chart background—
min, maxFixed bounds for the pane scale (negative allowed). One alone fixes one bound.automaticE942 if not a number or if min >= max
formatPane axis numbers: "compact" (12.4k, 3.2M), "volume", "percent" (adds %, does not multiply), "price"plain numberE942
precisionDecimals on the pane axis, whole number 0 to 10.automaticE942
labelstrue/false: last-value tags on the right axis.on in a pane, off on pricesE942
visible_onA text, or a non-empty list of texts, restricting the chart types or units the script is shown on: bar types "time" "range" "renko" "volume" "delta" "tick" "reversal", or units such as "5s" "1m" "1h" "1d" "1w" "8r" "4k" "500v" "300delta" "100t" "3x".everywhereE942

A wrong type for overlay, candles, height or background is ignored without an error.

Engine keys (all kinds)#

KeyValuesDefaultError
budgetOperations allowed per bar and per event, whole number 1 to 20,000,000. See Budget.200,000E902
initial_balanceLength of the initial balance for session.ib_high / session.ib_low, whole minutes from 1m to 390m.60mE942
level_historyHow long per-price MBO history is kept for mbo.level(…), a duration up to 30m.2mE942
flow_historyHow long trade and OFI history is kept for the of.* functions, a duration up to 60m.5mE942
mbo_historyIndicators: length of the rolling order-by-order window. Strategy and research: fixed start = launch time minus this duration, rounded down to the half hour.30m for indicatorsa non-duration is ignored
book_historySame, for book snapshots.2h for indicatorsa non-duration is ignored
mbo_fromFixed start of the order-by-order data: auto, launch, rth, session, start, rolling, or "HH:MM" (New York).indicators: rolling; strategy and research: autoE942
book_fromSame values, for book snapshots. Falls back to mbo_from.as mbo_fromE942
mbo_maxMaximum number of order-by-order events held for one bar that has not closed yet, whole number 1,000 to 100,000,000.25,000,000E942; E944 at run time if exceeded

The history and start keys are explained in Order flow: how much history.

Strategy keys#

KeyValuesDefaultError
costsRequired. { commission: 2.5 usd, slippage: 1 tick }—E939
fill_modelthrough (prudent), touch or queue (uses MBO queue position)throughE939
latencyDelay between a decision and the moment an order can fill, a duration ≥ 060msE939

See Strategies.

StrateScript
indicator "Delta pane" { overlay: false, height: 200, background: #0b1d33, min: -500, max: 500, format: "compact", precision: 0, labels: true }
histogram(delta, delta >= 0 ? #26a69a : #ef5350, title: "Delta")
hline(0, color: #888888)
StrateScript
indicator "Tuned" { overlay: true, visible_on: ["time", "8r"], budget: 5000000, initial_balance: 30m }
plot(session.ib_high, #e8c15a, title: "IB high")
plot(session.ib_low, #e8c15a, title: "IB low")

Values and types#

Types are dynamic: a variable holds whatever value is assigned to it.

TypeWritten as / comes fromNotes
number20, 0.5, 1e364-bit floating point. Any non-finite result (division by zero, sqrt(-1)) becomes na.
booltrue, false
string"text"Joined with +, compared alphabetically.
color#rrggbb[aa], rgb(), alpha(), mix(), input.color()Only == and !=. str(color) gives #rrggbbaa.
duration5s, 250ms, input.duration(), the difference of two timesNanosecond precision.
timebar.time, event.time, now(), .time fieldsAn instant (nanoseconds since 1970, UTC).
nanaA missing value.
list[1, 2, 3], array()A reference (see Collections).
map, ring, windowmap(), ring(n), window(d)References.
objectan instance of a custom typeA reference.
functionfn(x) { … }, or the name of a function of the script
plot handlereturned by plot, histogram, candle, level, hline, bar_color, bg_colorUsed by fill.
library objectsfootprint, footprint level, trade, book, order event, match, resting order, level statistics, line, box, label, tableRead their fields with ..

Type annotations are allowed after a declaration (var x: float = 0), on parameters (x: float) and on return values (-> float). They are documentation only: the engine does not check them. A bare x: int = 3 (without var, state, const or persist) is a syntax error (E103).

Generic constructors array<T>(), map<K, V>() and ring<T>(n) are accepted, with the same meaning as without the type. Write window(10s), not window<T>(10s).

Truth. In if, while, and, or, not, ?:, and in the conditions of marker, alert and patterns, true and any finite non-zero number are true. Everything else is false: false, 0, na, strings (even non-empty), colors, lists and objects.

Operators#

From lowest to highest precedence:

  1. cond ? a : b (right-associative; only the chosen branch is evaluated)
  2. or, ||
  3. and, &&
  4. not, !
  5. comparisons == != < <= > >= (not chainable: a < b < c gives E114, write a < b and b < c)
  6. .. (ranges, only in for)
  7. + -
  8. * / %
  9. unary -
  10. quantity N unit
  11. call (), field ., index []
OperandsOperatorsResult
number, number+ - * / %number. % keeps the sign of the left operand (-7 % 3 is -1).
string, string+, comparisonsjoined text; alphabetical order
string + another type+E921: convert with str(x) first
bool, bool / color, color== !=
duration, duration+ - → duration; / → number (d / 1s = seconds); comparisons
duration and numberd * 2, 2 * d, d / 2 → duration
time − time→ duration
time ± duration→ time
duration with a number (other than 0) in + - < …E922: write the number as a duration, or divide the duration by 1s

**Rules for na:**

StrateScript
d = 5s + 250ms
t = bar.time + 5m
print(d * 2, d / 1s, (t - bar.time) / 1m, 7 % 3, -7 % 3, 7 / 0)   // → 10500ms 5.25 5 1 -1 na
print(na != 1, na == na, not (na == 1), "a" < "b")                 // → false false true true

Variables and scope#

FormWhereLifetimeHistory x[n]
x = expr (first assignment at the top level)bodyA series: reset to na when each bar opens, then computed again.yes
var x = exprtop level only (E903 elsewhere)Initialized once, then keeps its value from bar to bar.yes
state x = exprtop level onlySame as var. Use it as a reminder that the value is shared with event handlers.yes
const x = exprtop level onlyEvaluated once, on the first bar (const k = close freezes the first close). Assigning to it gives E909.yes
persist x = exprtop level, named indicator onlyLike var, and also saved durably between restarts of the app. See below.yes

Scope rules:

What handlers see. Event handlers and patterns run before the body of their bar. Inside them:

StrateScript
indicator "Counters"
var bars = 0
state seen = 0
const k = 3
bars += 1
seen += 1
up = close > open ? 1 : 0
print(bars, bars[1], seen, k * 2, up[1] + up)
StrateScript
last_up = na
if close > open { last_up = close }
print(na(last_up) ? "down bar" : "up bar")

persist: memory that survives a restart#

persist keeps a variable's value when the app is restarted, so a long calculation does not start from zero each time.

StrateScript
indicator "Session high memory" { overlay: true }
persist best = 0.0
if high > best { best = high }
plot(best, #e8c15a, title: "Best high")

History: x[n]#

x[n] is the value of x, n bars ago. x[0] is the current value.

Functions with memory (ema, sma, highest, change, cum, crossover, stats.*, of.cvd, norm.*…) keep their own state for each place they are called. A call inside one of your functions has a separate state for each place that function is called from.

StrateScript
mid = (high + low) / 2
k = 2
print(close[1], bar.close[2], mid[k], close[100000])

The bar still forming: bar.confirmed#

bar.confirmed is false only on the last bar, and only while it is still forming:

Everywhere else (history, the check, long backtests) it is true. Requiring bar.confirmed for a signal stops it from appearing and disappearing while the candle forms.

StrateScript
signal_up = crossover(close, sma(close, 20)) and bar.confirmed
marker(signal_up, shape: "triangle_up", location: "below")
alert(signal_up, "Close crossed above SMA 20")

Related fields: bar.last (last bar received), bar.index (0 = first bar received), bar.gap (true after a real gap in the data; moving averages restart after a gap).

Control flow#

| Form | Visits | |---|---| | for x in list (or ring, window) | values | | for k in map | keys, in increasing order | | for i, x in list (or ring) | index, value | | for k, v in map | key, value | | for t, x in window | time, value |

The loop works on a copy, so changing the collection inside the loop is safe.

StrateScript
s = 0
for i in 0..5 {
  if i % 2 == 0 { continue }
  s += i
}
n = 0
while true {
  n += 1
  if n >= 3 { break }
}
a = [10, 20, 30]
txt = ""
for i, x in a { txt += str(i) + ":" + str(x) + " " }
m = map()
m["b"] = 2
m["a"] = 1
for k, v in m { txt += k + "=" + str(v) + " " }
print(s, n, txt)   // → 9 3 0:10 1:20 2:30 a=1 b=2

Functions#

Text
fn name(a, b = 2, c: float = 1) -> float {
  return a + b + c
}

Function values. f = fn(x) { return x * k } creates a function value, called as f(3). It keeps a copy of the local variables visible where it was created; top-level variables are read live. The name of a script function is also a value, so it can be passed to list methods such as map, filter or count.

StrateScript
fn add(a, b = 10) { return a + b }
fn big(x) { return x >= 2 }
k = 3
mul = fn(x) { return x * k }
fn smooth(x) { return ema(x, 3) }
print(add(1), add(1, 2), add(b: 5, a: 1), mul(2), [1, 2, 3].map(mul).sum(), [1, 2, 3].count(big), smooth(close) != smooth(volume))
// → 11 3 6 6 18 2 true

Custom types, enums and methods#

StrateScript
enum Mode { Waiting, Active }
type Zone { top: float, bottom: float, hits: int = 0, mode: Mode = Mode.Waiting }
method Zone.contains(self, p) { return p >= self.bottom and p <= self.top }
z = Zone { top: high, bottom: low }
z.hits += 1
print(z.contains(close), z.hits, z.mode == Mode.Waiting)   // → true 1 true

Collections#

All collections are references. Limits: 1,000,000 elements per list or map (E941); ring(n) takes n from 1 to 1,000,000 (E940); window(d) takes a duration > 0 (E940).

List — […] or array()

Map — map()

Ring — ring(n): keeps the last n values pushed.

Window — window(10s): keeps the values pushed during the last duration, measured on the time of the event or bar being processed.

len(x) also works on a list, text, map, ring or window.

Whole-collection operations (sum, sort, keys…) cost about 1 + n/8 operations of the budget.

print and str show a list as na, not its content: print its elements, or its len().

StrateScript
a = [3, 1, 2]
a.sort()
a.push(7)
m = map()
m.add("n")
m.add("n", 4)
r = ring(3)
r.push(1, 2, 3, 4)
print(a[0], a[-1], a.sum(), a.median(), m["n"], m.get("x", "none"), r.first(), r.sum(), r.full)
// → 1 7 13 2.5 5 none 2 9 true

Imports#

Text
import "path" [as alias] [{ name: value, … }]

Imports are written at the top level.

Alias. Without as, the alias is the last segment of the path, in lower case, with non-alphanumeric characters replaced by _ (and an i in front if it starts with a digit). Two imports with the same alias give E937.

What an import gives you. Everything the imported script declares at its top level (variables, settings, functions, clocks) is reached through the alias: tools.basis, tools.dev(x). Its settings appear in your Settings tab, titled alias · Title. Its patterns keep running, and on signal(s from alias) listens to all of them (see Listening to signals; label.new is described in Plotting).

Overriding values. { name: value } replaces the expression of a top-level declaration of the imported script — typically an input.* — which then disappears from the Settings tab. Naming something the import does not declare gives E937, with the list of its declarations.

Limits. One level only: an imported script cannot import another (E937). Of an imported script's header, only level_history, flow_history, mbo_history and book_history are used (the longest wins), and an imported mbo_history never moves a strategy's fixed start.

StrateScript
indicator "Two absorption definitions" { overlay: true }
import "strate/patterns/absorption_held_volume" as strict { minVol: 99 }
import "strate/patterns/absorption_held_volume" as loose { minVol: 80 }
on signal(s from strict) { label.new(s.time, s.price, "strict") }

A helper script and a script that imports it. On a chart, both must be scripts of that chart:

StrateScript
indicator "Tools"
len = input.int("Length", 20)
fn dev(x) { return x - sma(x, len) }
basis = sma(close, len)
StrateScript
indicator "Uses tools" { overlay: true }
import "my/Tools" as tools { len: 50 }
plot(tools.basis, title: "Basis")
plot(close + tools.dev(close), title: "Close + deviation")

Units#

A quantity is a number literal, a space, and a unit word.

UnitValue
tick, ticksThe number times instrument.tick (a price distance). On ES, 4 ticks is 1.0.
point, points, contract, contracts, event, events, trade, trades, usd, level, levelsThe number unchanged. The word is only for readability.
StrateScript
print(4 ticks, 1 tick, 2 points, 2.5 usd, ticks(1.0), price(4), instrument.tick)   // → 1 0.25 2 2.5 4 1 0.25

Budget and protections#

A script cannot freeze the chart. The engine counts the work a script does and stops it with an error when a bound is exceeded.

BoundValueError
Operations per bar (body) and per event (each handler and each pattern has its own budget)200,000 by default; header budget: from 1 to 20,000,000. One operation is roughly one expression node evaluated; collection operations cost 1 + n/8.E902 "script too slow"
Loop iterations (for range, while)10,000E906
Nested function calls64E914
Syntax nesting (parentheses, blocks, else if, operator chains)200 levelsE117
Script length200,000 charactersE950
StrateScript
indicator "Heavy loop" { budget: 5000000 }
s = 0
for i in 0..9000 { s += i }
print(s)   // → 40504500

More limits are listed in Reference: limits.

Pitfalls#

STRATE / PRODUCT SCREENSHOT

Actual platform screenshot.