Reference

Reference: functions

Every built-in function, field and method of StrateScript, grouped by area. Arguments in name: form are named arguments; arguments shown with = value have that default. "→" gives the return value.

Bar data and time#

Name→Notes
open, high, low, close, volume, deltanumberSame as bar.open … bar.delta. In handlers: the bar so far. delta may be na.
bar.buy_volume, bar.sell_volumenumber(volume ± delta) / 2.
bar.delta_high, bar.delta_lownumberRunning-delta extremes inside the bar; na if unknown and inside handlers.
bar.time, bar.close_timetimeOpen; known close (next bar's open for non-time bars).
bar.indexnumber0 = first bar received.
bar.last, bar.confirmed, bar.gapboolLast bar; bar closed; gap before the bar.
bar.hour, bar.minute, bar.dayofweeknumberNew York time of the open; 1 = Monday.
bar.footprintfootprintSee Footprint. E911 inside handlers.
event.timetimeTime of the event being processed (bar open in the body).
now()timeEvent time in a handler; close of a closed bar; latest data time on the bar forming.

Chart and instrument#

Name→Notes
chart.timeframetext"1m", "8r", … or na.
chart.timeframe_secondsnumber0 for non-time bars.
chart.bar_typetext"time", "range", "renko", "volume", "delta", "tick", "reversal".
chart.tick_px, chart.bar_pxnumberPixels per tick and per bar.
chart.row_ticks(min_px = 14)numberRound number of ticks per row, rows at least min_px high. 1 if unknown.
chart.columns(min_px = 30)numberColumns of at least min_px that fit in a bar (≥ 1).
instrument.tick, instrument.symbol, instrument.point_valuenumber / text / numbere.g. 0.25 / "ES" / 50.

Sessions#

Name→Notes
session.is_new, session.is_new_day, session.is_last_bar, session.rthbool
session.daynumberTrading date of the CME session (days since 1970-01-01).
session.high, session.low, session.overnight_high, session.overnight_low, session.rth_high, session.rth_low, session.ib_high, session.ib_lownumberna when the period's start is missing. Not allowed inside request (E936).
prev.high, prev.low, prev.closenumberLast complete RTH session. Not allowed inside request.
session.in(range, time = bar open)bool"HHMM-HHMM[,…][:days]", New York time. Invalid range: E925.
on session(s)—s.kind, s.time, s.rth, s.day.

Example: bg_color(session.in("0930-1030") ? #ffffff08 : na).

Moving averages and windows#

All take a length len (a number ≥ 1, rounded to a whole number; E923 below 1 or na), return na until enough values have been seen, and keep a separate state for each call place.

Function→Notes
sma(src, len), ema(src, len), rma(src, len), wma(src, len)numberema and rma start from the simple average. They restart after a data gap. A na source value is skipped.
highest(src, n), lowest(src, n)numberOver the last n values.
change(src, n = 1)numbersrc − src[n] over the values seen.
cum(src)numberRunning sum since the first bar (na counts as 0).
crossover(a, b), crossunder(a, b)boolTrue on the bar where a crosses above (below) b; false if a value is na.

Example: plot(ema(close, 21)).

Statistics: stats.*#

Over the last n values (a number ≥ 1, rounded to a whole number; E923 below 1 or na).

Function→Notes
stats.mean(src, n)number
stats.stdev(src, n)numberPopulation standard deviation.
stats.zscore(src, n)number0 when the deviation is 0.
stats.percentile(src, n, pct)numberpct from 0 to 100 (positional or pct:), linear interpolation. E933 if pct is invalid.
stats.median(src, n)number
stats.rank(src, n)numberPercentile rank of the current value, 0 to 100, current value included.
stats.linreg_slope(y, x, n)numberLeast-squares slope; na if the variance is 0.
stats.corr(y, x, n)numberCorrelation; na if a variance is 0.

Example: marker(volume > stats.percentile(volume, 100, 95)).

Normalization: norm.*#

Compares a value with its own recent values. Window: a duration or a number of values (E933 otherwise). Options: min_count: (default 20), by:, push:. See Normalization.

Function→
norm.rank(x, window)Percentile rank 0–100.
norm.zscore(x, window)Z-score (0 if the deviation is 0).
norm.ratio(x, window, "median" \| "mean")x ÷ median (default) or mean.
norm.percentile(x, window, pct)The pct percentile of the values.
norm.mean(x, window), norm.median(x, window)Mean, median.
norm.count(x, window)Number of values held.
norm.unit(x, unit, window)unit: "raw", "rank" ("percentile"), "zscore", "x_median", "x_mean".

Example: rk = norm.rank(volume, 2h, min_count: 30).

Math#

Function→Notes
abs(x), sqrt(x), log(x) (natural), exp(x), floor(x), ceil(x)numberA non-finite result is na.
pow(x, y)number
round(x, decimals = 0)numberHalves round away from zero: round(2.5) is 3.
sign(x)number−1 for negatives, 1 otherwise — sign(0) returns 1. na gives na.
max(a, …), min(a, …)numberAny na gives na; non-numbers are ignored; no argument gives E924.
nz(x, default = 0)valuex, or default if x is na.
na(x)boolTrue if x is na (na() with no argument is true).
math.pi, math.enumberConstants.

Text and numbers#

Function→Notes
str(x)textNumbers without useless zeros; a duration as "5s", "5250ms", "1h"; a color as "#rrggbbaa"; a time as nanoseconds; a list as "na"; na as "na".
str(number, format)textFormat codes: the number of digits after the point sets the decimals ("0.00"); a leading + always shows the sign; a trailing k abbreviates with k or M from 1,000 or 1,000,000 (without abbreviation the decimals are dropped: 950 → "950"); a trailing % multiplies by 100 and adds %.
str(time, format)textTokens yyyy MM dd HH mm ss SSS, in the chart's display time zone (New York by default).
len(x)numberLength of a list, text, map, ring or window; na otherwise.
StrateScript
print(str(1234.5, "0.0k"), str(0.1234, "0.0%"), str(5, "+0"), str(1500000, "0.00k"), str(950, "0.0k"), str(5s), round(1.256, 2), round(2.5))
// → 1.2k 12.3% +5 1.50M 950 5s 1.26 3

Colors#

Function→Notes
rgb(r, g, b, transparency = 0)color0–255; transparency 0 (opaque) to 100; values are clamped.
alpha(color, opacity)colorOpacity 0–100 (clamped); na gives na; not a color: E928.
mix(c1, c2, t)colort from 0 to 1 (clamped); not a color: E928.

Units#

Function / form→Notes
N tick(s)numberN × instrument.tick.
N point(s), N usd, N contract(s), N trade(s), N event(s), N level(s)numberN unchanged.
ticks(distance)numberPrice distance → ticks.
price(n)numberTicks → price distance.

Collections#

Constructor→Notes
[a, b, …], array(), array<T>()listUp to 1,000,000 elements (E941).
map(), map<K, V>()mapKeys: number, time, duration, text or bool (E939 otherwise).
ring(n), ring<T>(n)ringKeeps the last n values; n from 1 to 1,000,000 (E940).
window(d)windowKeeps the values of the last duration d > 0 (E940).

Methods and fields are listed in The language: collections.

Settings: input.*#

All take a title first (E925 otherwise) and accept group:, inline:, tooltip:. See Settings.

Function→
input.int(title, default, min:, max:, step:)whole number
input.float(title, default, min:, max:, step:)number
input.bool(title, default)bool
input.color(title, default)color
input.duration(title, default)duration
input.string(title, default)text
input.choice(title, [options], default?)text
input.session(title, default)time-range text
input.price(title, 0)price picked on the chart, or na
input.time(title, 0)time picked on the chart, or na

Other series: request#

Form→Notes
request(tf, expr)valueexpr on bars of timeframe tf (text or duration, a multiple of the chart's unit), from the last closed bar.
request(expr, symbol: "XX")valueexpr on another instrument's one-minute bars.
request(tf, expr, symbol: "XX")valueBoth.

Errors E936: wrong arguments, unknown or incompatible timeframe, drawing inside expr, session levels inside expr, no bars for the symbol. See Market data.

Footprint#

Name→Notes
bar.footprintfootprintAlso bar.footprint[n].
fp.availablebool
fp.levelslist of levelsLowest price first.
fp.poc, fp.high, fp.lownumber
fp.volume, fp.delta, fp.buy, fp.sell, fp.trades, fp.stepnumber
fp.buy_trades, fp.sell_trades, fp.max_trade, fp.max_buy, fp.max_sell, fp.avg_trade, fp.avg_buy, fp.avg_sellnumberna without per-trade detail.
fp.first_time, fp.last_timetimena without per-trade detail.
fp.level(price)level or na
fp.value_area(pct = 70)object .high .low .poc or na
fp.rows(ticks)footprintRows of ticks ticks (≥ 1, E935 otherwise).
fp.imbalances(side, ratio: 3, min_volume: 0)list of pricesside "buy"/"sell" (E933 otherwise).
fp.stacked(side, ratio: 3, count: 3)list of [low, high]count at least 2.
level fieldsprice, buy, sell, volume, delta, trades, and the per-trade detail fields.
footprint.accumulator()accumulator.add(fp) (E934 if not a footprint), .reset(), .bars, and every footprint field and method.

Unknown field: E932; unknown method: E933.

Trades#

on trade(t):

Field→
t.timetime
t.price, t.size, t.deltanumber
t.side"buy", "sell" or na
t.is_buy, t.is_sellbool
t.sweep, t.levels, t.passive_countnumber (order-by-order only, na otherwise)
t.sweep_start, t.sweep_endbool (order-by-order only)
t.aggressor_id, t.passive_idnumber (order-by-order only; na if the feed has no id)

Order by order: on order, on match, mbo#

on order(o): o.time, o.id, o.action ("add", "cancel", "modify", "fill"), o.is_add, o.is_cancel, o.is_modify, o.is_fill, o.side ("bid"/"ask"), o.price, o.size, o.queue_position, o.priority_lost, o.previous_size, o.previous_price, o.age, o.modifications.

on match(m): m.time, m.side, m.size, m.first_price, m.price, m.levels, m.fills, m.largest_fill, m.orders (list of ids), m.aggressor_id.

mbo→Notes
mbo.availablebool
mbo.ordersnumberResting orders.
mbo.timetimeLatest order-by-order event.
mbo.best_bid, mbo.best_asknumber
mbo.size(price), mbo.count(price)number
mbo.queue(price)list of sizesFront first.
mbo.orders(price)list of resting ordersFront first.
mbo.mean_age(price)durationSize-weighted.
mbo.order(id)resting order or na
mbo.levels(side, n = 10)list of pricesbid/ask/buy/sell (E933 otherwise); n 1–500.
mbo.large(min_size)list of resting ordersBiggest first, at most 500; E933 if min_size < 0 or na.
mbo.level(price, window: 30s, depleted_below: 0, refill_within: 2s, same_id_only: false)level statisticsE933 on a bad window or a window longer than level_history:.

Resting order fields: .id, .side, .price, .size, .age, .position, .modifications.

Level statistics fields: price, window, displayed, queue_length, mean_order_age, added, canceled, filled, net, cancel_ratio, aggressor_hits, aggressor_volume, hidden_filled, depletions, replenishments, refill_same_id, refill_new_id, refill_delay, time_at_best. See Order flow.

Book snapshots: book#

book (latest snapshot) and b in on book(b):

Name→Notes
availablebool
timetime
best_bid, best_ask, mid, spread, bid_size, ask_size, micropricenumber
size(price)numberna beyond 300 ticks from the center.
depth(side, levels = 10)numberlevels 1–300; bad side: E933.
imbalance(levels = 10)number−1 to +1.

Order flow: of.*#

Function→
of.cvd(reset: "session")Cumulative delta; reset "session", "day", "rth", "none" (also "never"). The reset can also be passed positionally: of.cvd("rth").
of.flow(side = "both", window = 30s)Aggressor volume per second.
of.trade_count(side = "both", window = 30s)Number of trades.
of.aggression(window = 30s)(buy − sell) / total.
of.decay(side = "both", window = 30s)Last third ÷ first third of the window's volume.
of.burst(side = "both", window: 1s, min_trades: 10)bool.
of.vpin(bucket, buckets: 50)0 to 1.
of.ofi(window = 30s)Order flow imbalance at the best prices (order-by-order only).

Windows longer than flow_history: give E933. See Order flow.

Patterns, signals and clocks#

FormNotes
pattern "Name" { on: …, side:, price:, cooldown:, confirm:, show:, … when … }See Patterns.
on signal(s [from "Name" \| from alias])s.name, s.time, s.price, s.side, s.start, s.explain.
clock name = clock.time(d) / clock.volume(n) / clock.trades(n) / clock.events(n) / clock.range(d) / when(cond)on clock name { … }.

Plotting#

Function→Main options
plot(value, color?)handlecolor:, title:, width:, style:, overlay: / pane:
histogram(value, color?)handlecolor:, title:
candle(o, h, l, c, color?)handlecolor:. With x: or w: (and wick:) it draws a candle in the bar's column instead, and returns na
fill(p1, p2, color?) / fill(p, value, color)—
hline(value)handlecolor:, style:, width:, text:
level(price)handlecolor:, text:
bg_color(color), bar_color(color)handle
marker(cond)—shape:, location:, price:, color:, size:, text:, tip:
stat(title, value)—format:, color:, bg:
label(t, p, text), box(t1, p1, t2, p2), line(t1, p1, t2, p2), bubble(price, size, color)—Simple per-bar drawings.

See Plotting.

Objects and tables#

Function→
line.new(t1, p1, t2, p2, color:, width:, style:, glow:, pulse:)line object
box.new(t1, top, t2, bottom, color:, border:, text:, text_color:, fade:, glow:)box object
label.new(t, price, text, color:, bg:, text_color:, glow:, pulse:)label object
table.new(position, columns, rows, bg:, border:, frame:, text_color:, size:)table

Object fields: time1, price1, time2, price2, text, deleted (aliases time, price, top, bottom). Object methods: set_start, set_end, set_left, set_right, set_top, set_bottom, set_time, set_price, set_text, set_color, set_border, set_glow, set_fade, set_bg, pulse, delete.

Table methods: cell(col, row, text, text_color:, bg:, size:, align:), clear(), clear(col, row), set_position, set_bg, set_border, set_frame, set_text_color, set_size, delete. Fields: position, columns, rows, deleted.

Drawing in a bar's column#

FunctionOptions
cell(price, text)side:, bg:, color:, size:, ticks:, bar:, col:, cols:, x:, w:, tip:
hbar(price, value, max)side:, width:, color:, ticks:, bar:, col:, cols:, x:, w:, tip:
draw.rect(low, high) / draw.rect(price, ticks: n)x:, w:, fill:, border:, radius:, tip:
draw.text(price, text)x:, align:, color:, size:, bold:, ticks:, tip:
draw.line(p1, p2)x1:, x2:, color:, width:, style:
draw.candle(o, h, l, c)x:, w:, color:, wick:

Alerts and console#

FunctionNotes
alert(cond, message, every: duration)See Alerts.
signal(…)Draws a mark whenever it is called, whatever its arguments: one per call place and per bar.
print(a, b, …)Writes a line in the Console (last 500 bars, 500 characters).

Strategies#

Function / nameNotes
enter(side, size: 1, type: "market", price:, stop:, target:, timeout:, expire:, tag:) → bool
exit(tag:)
cancel(tag:) → number
position.flat, .side, .size, .entry_price, .entry_time, .open_ticks, .open_r, .mfe, .mae, .pending, .trades, .net_usd
on fill(f)f.time, f.price, f.side, f.size, f.tag
on exit(x)x.time, x.price, x.side, x.reason, x.ticks, x.usd, x.r, x.entry_price, x.tag

See Strategies.

Research#

FunctionNotes
study(s, horizons: [1m, 5m, 15m], target:, stop:, cost: 0)
report(by: ["name", "side"], ci: 1000)by: "name", "side", "rth".
compare(by:, ci:)Like report, with "name" first.

See Research.

Constants#

NameValue
buy, sell, bid, ask, long, shortThe texts "buy", "sell", … (usable without quotes, e.g. mbo.levels(bid, 3)).
solid, dashed, dottedLine styles.
left, right, both, center, fullSides and alignments (e.g. cell(p, "x", side: right)).
true, false, na
math.pi, math.e
STRATE / PRODUCT SCREENSHOT

Actual platform screenshot.