Function reference
All built-in LootScript functions, series and constants: ta, math, str, color, input, drawing, collections, strategies and order flow data — with parameters and default values.
This lists everything built into LootScript: script declarations, bar series, namespace functions, constants and order flow data. The list is assembled from the compiler’s table of built-in names — if a name is not on this page, it is not in the language and calling it will error with LS2002.
The reference does not teach the language: types, na, history x[1] and bar replay are covered in Syntax and types, and drawing and settings in Inputs and drawing.
How to read the reference
Each function is written on one line: name, parameters in the order positional calls parse them, and the result type.
ta.stdev(source, length, biased = true) → float- A parameter without
= …is required. A parameter with a default is optional: if omitted the listed default is used. = naon an optional parameter means “not set”: the function behaves as described in the line.- Parameter names may be written explicitly in the call:
ta.stdev(close, 20, biased = false). Names are part of the language and cannot be shortened. - A result of
[float, float, float]— multiple return values. Unpack them into variables:[mid, up, dn] = ta.bb(close, 20, 2). - A name without parentheses (
close,ta.obv,strategy.equity) is a series or constant and is read without calling it. - A result of
—means the function returns nothing and is written on its own line.
Script declaration
The script’s first line must contain exactly one declaration: indicator, strategy or library. Its arguments are read before the first bar, so only literals and constants are allowed.
| Declaration | What it creates |
|---|---|
indicator(title, …) |
An indicator on the chart |
strategy(title, …) |
A strategy for the tester: the same capabilities as an indicator, plus strategy.* orders |
library(title, version) |
A library of functions. Import it with import Name/version as alias. Libraries cannot draw or declare inputs |
indicator parameters
| Parameter | Default | What it sets |
|---|---|---|
title |
— | Name in the indicator list and in the legend |
shortTitle |
na |
Short title for the legend |
overlay |
false |
true — draw over candles, false — in a separate pane under the chart |
format, precision, scale |
na |
Accepted for compatibility: the terminal controls numeric format and scale |
maxBarsBack |
na |
Accepted and ignored: history is always fully loaded |
timeframe |
na |
Accepted and ignored: the script runs on the chart timeframe; a different timeframe uses request.security |
maxLinesCount, maxLabelsCount, maxBoxesCount |
500 |
How many lines, labels and rectangles of a single type may exist simultaneously. When the limit is exceeded the oldest is removed |
maxPolylinesCount |
500 |
Reserved: polyline objects are not implemented yet |
Constants for format: format.inherit, format.price, format.volume, format.percent, format.mintick. For scale: scale.right, scale.left, scale.none. str.tostring also accepts format.* strings.
strategy parameters
strategy accepts the same title, shortTitle, overlay and drawing-object limits as indicator, plus tester parameters:
| Parameter | Default | What it sets |
|---|---|---|
initialCapital |
10000 |
Starting capital |
currency |
"USD" |
Accepted; does not affect calculations |
defaultQtyType |
strategy.qty.fixed |
How to interpret default order size: strategy.qty.fixed — units, strategy.qty.cash — cash amount, strategy.qty.percent_of_equity — percent of equity, strategy.qty.risk_percent — percent risk to stop-loss |
defaultQtyValue |
1 |
Default order size |
commissionType |
strategy.commission.percent |
Commission in percent, strategy.commission.cash_per_contract — per unit, strategy.commission.cash_per_order — per order |
commissionValue |
na |
Commission value. na — use instrument’s maker and taker rates |
slippageTicks |
0 |
Slippage in price ticks |
pyramiding |
0 |
How many additional same-side entries are allowed |
positionModel |
strategy.model.netting |
Net single position or separate (strategy.model.hedging) |
calcOnEveryTick |
false |
Calculate orders on every tick of a live bar instead of only on close |
calcOnOrderFills |
false |
Accepted; this version doesn’t use it |
processOrdersOnClose |
false |
Execute orders at the same bar’s close price. The report is flagged as unattainable in live trading |
marginLong, marginShort |
0 |
Initial long and short margin as percent of position. 0 — no margin/liquidation simulation |
leverage |
1 |
Leverage |
applyFunding |
true |
Account for funding rate on perpetual futures in results |
fillModel |
strategy.fill.conservative |
Price path inside the bar. Conservative assumes price first moved the worse way: if stop and take are both inside the bar the stop executes. strategy.fill.optimistic is the opposite |
Bar and instrument
Bar series
| Name | Type | What it contains |
|---|---|---|
open, high, low, close, volume |
float |
Bar prices and volume |
hl2, hlc3, ohlc4, hlcc4 |
float |
Bar averages: (H+L)/2, (H+L+C)/3, (O+H+L+C)/4, (H+L+2C)/4 |
time, time_close |
int |
Bar open and close times, milliseconds UTC |
bar_index |
int |
Bar index from the start of loaded history, zero-based |
last_bar_index |
int |
Index of the last loaded bar |
timenow |
int |
Terminal current time, milliseconds UTC |
Bar state: barstate
| Name | True when |
|---|---|
barstate.isfirst |
First bar of the loaded history |
barstate.islast |
Last loaded bar |
barstate.ishistory |
Bar comes from history, not forming live |
barstate.isrealtime |
Bar is forming in real time |
barstate.isnew |
First pass over a new bar |
barstate.isconfirmed |
Bar closed — value will no longer change |
isrealtime, isnew and values depending on them differ between history and live — the compiler will warn if they reach the chart.
Instrument: sym
| Name | Type | What it contains |
|---|---|---|
sym.ticker |
string |
Venue and symbol in the form accepted by request.security |
sym.exchange |
string |
Venue code |
sym.base, sym.quote |
string |
Base and quote assets: BTC and USDT for BTCUSDT. na if quote couldn’t be parsed |
sym.tick_size |
float |
Price tick size |
sym.qty_step, sym.min_qty |
float |
Quantity step and minimum |
sym.maker_fee, sym.taker_fee |
float |
Maker and taker fees as fractions: 0.0002 is 0.02% |
Timeframe: tf
| Name | Type | What it contains |
|---|---|---|
tf.period |
string |
Chart timeframe as text: "5", "60", "1D" |
tf.ms, tf.seconds |
int |
Bar length in milliseconds and seconds |
tf.isintraday, tf.isdaily |
bool |
Bar shorter than a day; bar equals a day |
tf.in_ms(period) |
int |
Length of an arbitrary timeframe in ms; na if the string cannot be parsed |
tf.in_seconds(period = na) |
int |
Same in seconds; without argument — the chart timeframe |
Time and calendar
All calendar functions default to UTC, not the computer timezone: indicators look the same for everyone.
| Function | Returns | What it does |
|---|---|---|
year, month, dayofmonth, weekofyear (timestamp = time, timezone = "UTC") |
int |
Year, month, day, ISO week number |
dayofweek(timestamp = time, timezone = "UTC") |
int |
Day of week: Sunday — 1, Saturday — 7 |
hour, minute, second (timestamp = time, timezone = "UTC") |
int |
Hour, minute, second |
time_of_day(timestamp = time, timezone = "UTC") |
int |
Milliseconds since midnight in the given timezone |
timestamp(year, month, day, hour = 0, minute = 0, second = 0, timezone = "UTC") |
int |
Timestamp from a date |
time_in_range(session, timezone = "UTC") |
bool |
Whether a bar falls into a range like "0930-1600" |
session.ismarket, session.isfirstbar, session.islastbar |
bool |
Bar inside a session, first and last bar of the session. For 24/7 venues the session is a UTC day |
Day constants match dayofweek returns: dayofweek.sunday (1), dayofweek.monday, dayofweek.tuesday, dayofweek.wednesday, dayofweek.thursday, dayofweek.friday, dayofweek.saturday (7). Timezone is an IANA identifier like "Europe/Moscow".
ta — technical analysis
ta.* functions retain state between bars, so the compiler evaluates them on every bar even if the call is inside an if. Early bars return na until their window fills.
Moving averages
| Function | Returns | What it does |
|---|---|---|
ta.sma(source, length) |
float |
Simple moving average over length bars |
ta.ema(source, length) |
float |
Exponential MA: weight of new value 2/(length+1) |
ta.rma(source, length) |
float |
Wilder smoothing, weight 1/length. RSI and ATR use this; it is not the same as ta.ema of the same length |
ta.wma(source, length) |
float |
Linearly weighted: recent bars weigh more |
ta.vwma(source, length) |
float |
Volume-weighted moving average |
ta.hma(source, length) |
float |
Hull MA: less lag on reversals |
ta.swma(source) |
float |
Symmetrically weighted average over four bars |
ta.alma(source, length, offset = 0.85, sigma = 6) |
float |
Gaussian-windowed average; offset shifts the peak to recent bars, sigma sets width |
ta.linreg(source, length, offset = 0) |
float |
Point on the regression line over the last length values |
Oscillators
| Function | Returns | What it does |
|---|---|---|
ta.rsi(source, length) |
float |
Relative strength index, 0…100 |
ta.stoch(source, high, low, length) |
float |
Where source sits inside high–low over length bars, 0…100 |
ta.cci(source, length) |
float |
Deviation from mean normalized by mean absolute deviation |
ta.mfi(source, length) |
float |
Money Flow Index: RSI with volume |
ta.cmo(source, length) |
float |
Chande Momentum Oscillator, −100…100 |
ta.roc(source, length) |
float |
Percent change vs value length bars ago |
ta.mom(source, length) |
float |
Difference vs value length bars ago |
ta.tsi(source, shortLength, longLength) |
float |
True Strength Index: double-smoothed momentum over double-smoothed absolute momentum |
ta.wpr(length) |
float |
Williams %R, −100…0 |
ta.bop(length = 1) |
float |
Balance of power: how much of the bar range is the body, with smoothing |
ta.cog(source, length) |
float |
Center of gravity of the window |
Volatility and channels
| Function | Returns | What it does |
|---|---|---|
ta.tr(handle_na = true) |
float |
True range of the bar |
ta.atr(length) |
float |
Average true range |
ta.natr(length) |
float |
ATR as percent of close price |
ta.stdev(source, length, biased = true) |
float |
Standard deviation. biased = false — sample sd with divisor length−1 |
ta.variance(source, length, biased = true) |
float |
Variance, same divisor choice |
ta.dev(source, length) |
float |
Mean absolute deviation from the mean |
ta.bb(source, length, mult) |
[float, float, float] |
Bollinger Bands: middle, upper, lower |
ta.bbw(source, length, mult) |
float |
Bollinger Band width relative to middle |
ta.kc(source, length, mult, useTrueRange = true) |
[float, float, float] |
Keltner Channel: middle, upper, lower |
ta.kcw(source, length, mult, useTrueRange = true) |
float |
Keltner Channel width relative to middle |
ta.range(length) |
float |
Height of the last length bars: max high minus min low |
Trend
| Function | Returns | What it does |
|---|---|---|
ta.macd(source, fastLength, slowLength, signalLength) |
[float, float, float] |
MACD: line, signal line, histogram |
ta.dmi(diLength, adxLength) |
[float, float, float] |
Directional Movement Index: +DI, −DI, ADX |
ta.adx(diLength, adxLength) |
float |
ADX only |
ta.supertrend(factor, atrLength) |
[float, int] |
Supertrend line and direction: 1 — up, −1 — down |
ta.sar(start = 0.02, increment = 0.02, maximum = 0.2) |
float |
Parabolic SAR |
ta.vortex(length) |
[float, float] |
Vortex indicator: VI+ and VI− |
ta.aroon(length) |
[float, float] |
Aroon up and down: how long since window high/low, 0…100 |
Volume
| Function | Returns | What it does |
|---|---|---|
ta.obv, ta.pvt, ta.nvi, ta.pvi, ta.ad |
float |
Cumulative series without parentheses: on-balance volume, price-volume trend, negative/positive volume indexes, accumulation/distribution |
ta.cmf(length) |
float |
Chaikin Money Flow |
ta.eom(length = 14, divisor = 10000) |
float |
Ease of movement: price move per unit of volume |
ta.vwap(source = hlc3, anchor = session.isfirstbar) |
float |
VWAP since the last bar where anchor was true |
Structure and events
| Function | Returns | What it does |
|---|---|---|
ta.highest(source, length), ta.lowest(source, length) |
float |
High and low over length bars |
ta.highestbars(source, length), ta.lowestbars(source, length) |
int |
Offset to the bar with the high or low: 0 — current bar, more negative numbers are older |
ta.crossover(a, b) |
bool |
a crossed b upwards on this bar |
ta.crossunder(a, b) |
bool |
a crossed b downwards |
ta.cross(a, b) |
bool |
Either cross |
ta.change(source, length = 1) |
float |
Difference vs value length bars ago |
ta.rising(source, length), ta.falling(source, length) |
bool |
Value increased (decreased) every one of the last length bars |
ta.barssince(condition) |
int |
Bars since the last time the condition was true |
ta.valuewhen(condition, source, occurrence = 0) |
float |
source value on the bar where the condition was true; occurrence = 1 — the previous such bar |
ta.pivothigh(source, leftBars, rightBars), ta.pivotlow(…) |
float |
Confirmed pivot high or low. Appears rightBars bars after the point |
ta.percentrank(source, length) |
float |
Percent of past window values not greater than the current |
ta.median(source, length), ta.mode(source, length) |
float |
Median and most frequent value of the window |
ta.correlation(source1, source2, length) |
float |
Correlation of two series, −1…1 |
ta.sum(source, length) |
float |
Sum over length bars |
ta.cum(source) |
float |
Cumulative sum from the first loaded bar |
Absence of value: na
| Function | Returns | What it does |
|---|---|---|
na(x) |
bool |
True if the value is missing. Works with any type, including objects and collections |
nz(x, replacement = 0) |
float |
Replaces na with replacement |
fixnan(x) |
float |
Carries the last existing value through gaps |
Comparing x == na is rejected by the compiler: it is always false. Test with na(x) and substitute a default using a ?? b.
math
| Function | Returns | What it does |
|---|---|---|
math.abs(x), math.sign(x) |
float |
Absolute and sign (−1, 0, 1). math.abs of an integer remains integer |
math.round(x, precision = na) |
int or float |
Without precision — to integer, result int. With precision — to decimal places, result float |
math.floor(x), math.ceil(x), math.trunc(x) |
int |
Floor, ceiling, truncate fractional part |
math.min(a, b, c = na, d = na), math.max(…) |
float |
Min and max of 2–4 values; na is skipped. From integers — integer result |
math.sum(a, b, c = na, d = na), math.avg(…) |
float |
Sum and average of 2–4 values |
math.clamp(x, lower, upper) |
float |
Clamp value into bounds |
math.pow(base, exponent) |
float |
Power |
math.sqrt(x), math.cbrt(x) |
float |
Square and cube root |
math.exp(x), math.log(x), math.log10(x), math.log2(x) |
float |
Exponential and logarithms |
math.hypot(x, y) |
float |
Hypotenuse length |
math.gcd(a, b), math.lcm(a, b) |
int |
Greatest common divisor, least common multiple |
math.approx(a, b, tolerance = 1e-9) |
bool |
Numbers equal with relative tolerance tolerance |
math.random(min = 0, max = 1, seed = na) |
float |
Random in [min, max). Each call has its own sequence |
math.pi, math.e, math.phi, math.rphi, math.inf, math.epsilon |
float |
Constants: π, e, golden ratio and its inverse, infinity, machine epsilon |
Trigonometry
| Function | Returns | What it does |
|---|---|---|
math.sin(x), math.cos(x), math.tan(x) |
float |
Sin, cos, tan; angle in radians |
math.asin(x), math.acos(x), math.atan(x) |
float |
Inverse functions |
math.atan2(y, x) |
float |
Angle of point (x, y) with quadrant taken into account |
math.sinh(x), math.cosh(x), math.tanh(x) |
float |
Hyperbolic functions |
math.todegrees(radians), math.toradians(degrees) |
float |
Convert between radians and degrees |
str — strings
| Function | Returns | What it does |
|---|---|---|
str.tostring(value, format = na) |
string |
Number to text; format is format.* or a template |
str.tonumber(text) |
float |
Text to number; na if not parsed |
str.format(pattern, arg0, arg1 = na, arg2 = na, arg3 = na) |
string |
Substitute values into a template like "RSI {0}, ATR {1}" |
str.format_time(timestamp, format = "yyyy-MM-dd HH:mm:ss", timezone = "UTC") |
string |
Timestamp to text |
str.length(text) |
int |
String length |
str.substring(text, begin, end = na) |
string |
Substring; without end — to the end |
str.pos(text, needle) |
int |
Position of first occurrence |
str.contains(text, needle), str.startswith(text, prefix), str.endswith(text, suffix) |
bool |
Containment, startswith and endswith checks |
str.replace(text, target, replacement, occurrence = 0) |
string |
Replace one occurrence, first by default |
str.replace_all(text, target, replacement) |
string |
Replace all occurrences |
str.split(text, separator) |
array<string> |
Split a string into parts |
str.join(parts, separator = "") |
string |
Join array of strings |
str.upper(text), str.lower(text), str.trim(text) |
string |
Case and trim |
str.repeat(text, count, separator = "") |
string |
Repeat text count times |
str.match(text, pattern) |
string |
First regex match or na |
str.escape_regex(text) |
string |
Escape regex metacharacters so the text is searched literally |
You cannot add a string and a number with + — convert the number to text with str.tostring.
color — colors
| Function | Returns | What it does |
|---|---|---|
color.rgb(red, green, blue, alpha = 255) |
color |
Color from 0…255 channels |
color.new(base, alpha) |
color |
Same color with different opacity |
color.from_gradient(value, bottomValue, topValue, bottomColor, topColor) |
color |
Color between two colors by value position in the range |
color.r(c), color.g(c), color.b(c), color.t(c) |
int |
Red, green, blue channels and alpha, 0…255 |
Alpha in LootScript is opacity: 255 is solid, 0 is fully transparent. Built-in colors: color.red, color.green, color.blue, color.teal, color.orange, color.purple, color.yellow, color.white, color.black, color.gray, color.silver, color.maroon, color.navy, color.olive, color.lime, color.aqua, color.fuchsia. A color literal also works: #FF9800 or #FF980080.
input — script inputs
Each input.* call adds a row to the indicator settings window. Values persist for an entire run, so they are valid for ta.* window lengths.
| Function | Returns | Settings row |
|---|---|---|
input.int(defval, title = na, minval = na, maxval = na, step = 1, tooltip = na, group = na, inline = na) |
int |
Integer |
input.float(defval, title = na, minval = na, maxval = na, step = 0.1, tooltip = na, group = na, inline = na) |
float |
Float |
input.bool(defval, title = na, tooltip = na, group = na, inline = na) |
bool |
Checkbox |
input.string(defval, title = na, options = na, tooltip = na, group = na, inline = na) |
string |
Text or list from options |
input.color(defval, title = na, tooltip = na, group = na, inline = na) |
color |
Color picker |
input.source(defval, title = na, tooltip = na, group = na, inline = na) |
float |
Series chooser: close, hl2, volume, etc. |
input.enum(defval, title = na, tooltip = na, group = na, inline = na) |
enum type | Dropdown from members of your enum |
input.symbol(defval, title = na, tooltip = na, group = na, inline = na) |
string |
Instrument in the form "VENUE:SYMBOL" |
input.timeframe(defval, title = na, options = na, tooltip = na, group = na, inline = na) |
string |
Timeframe: "5", "60", "1D" |
group groups rows under a common heading, inline places multiple rows on one line, tooltip shows a hint. A saved value is bound to the variable name: renaming the variable resets the setting to defval.
Plotting to the chart
These functions are written on their own line. A script may have up to 64 outputs, but the chart panel draws only the first three plot series.
| Function | What it draws |
|---|---|
plot(series, title = na, color = #2196F3, linewidth = na, style = plot.style_line, offset = 0, join = false, editable = true, show_last = na, display = display.all) |
A series of values. na produces a gap. Without linewidth the pane thickness is used |
plotshape(condition, title = na, style = shape.triangleup, location = location.belowbar, color = color.blue, text = na, size = size.small, offset = 0) |
An icon on bars where the condition is true |
plotchar(condition, title = na, char = "▲", location = location.abovebar, color = color.blue, text = na, size = size.auto, offset = 0) |
A character on bars where the condition is true |
hline(price, title = na, color = color.gray, linestyle = hline.style_dashed, linewidth = na) |
A horizontal level. Price is constant |
fill(plot1, plot2, color = na, title = na, top_value = na, bottom_value = na, top_color = na, bottom_color = na) |
Fill between two plot or hline: single color or a gradient by the last four parameters |
bgcolor(color, offset = 0, title = na) |
Bar background; na — no background |
barcolor(color, offset = 0, title = na) |
Candle color |
plot and hline return a reference which is passed to fill: p1 = plot(a), then fill(p1, p2, color = …).
Plot styles: plot.style_line, plot.style_linebr, plot.style_stepline, plot.style_stepline_diamond, plot.style_histogram, plot.style_columns, plot.style_area, plot.style_areabr, plot.style_circles, plot.style_cross.
hline styles: hline.style_solid, hline.style_dashed, hline.style_dotted.
Shapes: shape.triangleup, shape.triangledown, shape.circle, shape.square, shape.diamond, shape.arrowup, shape.arrowdown, shape.cross, shape.xcross, shape.flag, shape.labelup, shape.labeldown.
Shape locations: location.abovebar, location.belowbar, location.top, location.bottom, location.absolute.
Size: size.auto, size.tiny, size.small, size.normal, size.large, size.huge.
Where to show the series: display.all, display.pane, display.price_scale, display.status_line, display.data_window, display.none.
Drawing objects
Lines, rectangles, labels and tables are created with .new and live until deleted or evicted by the limit (default 500 per type). .new returns a reference used to change the object. Setting a setter to na does nothing, so the “delete-and-create” pattern needs no checks. All objects of a type are available as arrays line.all, box.all, label.all, table.all.
X coordinate defaults to the bar index (xloc.bar_index); with xloc.bar_time it is the bar time in ms. Y coordinate is a price or pane value.
line
| Function | Returns | What it does |
|---|---|---|
line.new(x1, y1, x2, y2, xloc = xloc.bar_index, extend = extend.none, color = color.blue, style = line.style_solid, width = 1) |
line |
Segment between two points |
line.set_x1(id, x), line.set_y1(id, y), line.set_x2(id, x), line.set_y2(id, y) |
— | Change one end |
line.set_xy1(id, x, y), line.set_xy2(id, x, y) |
— | Set a point entirely |
line.set_xloc(id, x1, x2, xloc) |
— | Change both X and how they are read |
line.set_extend(id, extend), line.set_color(id, color), line.set_style(id, style), line.set_width(id, width) |
— | Extension, color, style, thickness |
line.get_x1(id), line.get_x2(id) |
int |
X coordinates of the ends |
line.get_y1(id), line.get_y2(id) |
float |
Y coordinates of the ends |
line.get_price(id, x) |
float |
Price on the line at x |
line.copy(id) |
line |
Copy of the line |
line.delete(id) |
— | Delete the line |
Extensions: extend.none, extend.left, extend.right, extend.both. Styles: line.style_solid, line.style_dotted, line.style_dashed, line.style_arrow_left, line.style_arrow_right, line.style_arrow_both.
label
| Function | Returns | What it does |
|---|---|---|
label.new(x, y, text = na, xloc = xloc.bar_index, yloc = yloc.price, color = color.blue, style = label.style_label_down, textcolor = color.white, size = size.normal, textalign = text.align_center, tooltip = na, text_font_family = font.family_default) |
label |
Text label |
label.set_x(id, x), label.set_y(id, y), label.set_xy(id, x, y) |
— | Position |
label.set_text(id, text), label.set_tooltip(id, text) |
— | Text and tooltip |
label.set_color(id, color), label.set_textcolor(id, color) |
— | Background and text color |
label.set_style(id, style), label.set_size(id, size), label.set_textalign(id, align), label.set_text_font_family(id, family) |
— | Shape, size, align, font |
label.set_xloc(id, x, xloc), label.set_yloc(id, yloc) |
— | How coordinates are read |
label.get_x(id) |
int |
X coordinate |
label.get_y(id) |
float |
Y coordinate |
label.get_text(id) |
string |
Text |
label.copy(id) |
label |
Copy |
label.delete(id) |
— | Delete the label |
Y anchoring: yloc.price, yloc.abovebar, yloc.belowbar. Styles: label.style_none, label.style_label_up, label.style_label_down, label.style_label_left, label.style_label_right, label.style_label_center, label.style_circle, label.style_square, label.style_diamond, label.style_arrowup, label.style_arrowdown, label.style_triangleup, label.style_triangledown, label.style_flag, label.style_cross, label.style_xcross, label.style_text_outline. Fonts: font.family_default, font.family_monospace.
box — rectangles
| Function | Returns | What it does |
|---|---|---|
box.new(left, top, right, bottom, border_color = color.blue, border_width = 1, border_style = line.style_solid, extend = extend.none, xloc = xloc.bar_index, bgcolor = na, text = na, text_size = size.auto, text_color = color.white, text_halign = text.align_center, text_valign = text.align_center, text_wrap = text.wrap_none) |
box |
Rectangle with optional text |
box.set_left(id, x), box.set_right(id, x), box.set_top(id, y), box.set_bottom(id, y) |
— | One side |
box.set_lefttop(id, x, y), box.set_rightbottom(id, x, y) |
— | Corner as a whole |
box.set_xloc(id, left, right, xloc) |
— | Both X and how they are read |
box.set_border_color(id, color), box.set_border_width(id, width), box.set_border_style(id, style) |
— | Border |
box.set_bgcolor(id, color), box.set_extend(id, extend) |
— | Fill and extension |
box.set_text(id, text), box.set_text_color(id, color), box.set_text_size(id, size), box.set_text_halign(id, align), box.set_text_valign(id, align) |
— | Text inside |
box.get_left(id), box.get_right(id) |
int |
X coordinates |
box.get_top(id), box.get_bottom(id) |
float |
Y coordinates |
box.copy(id) |
box |
Copy |
box.delete(id) |
— | Delete the rectangle |
Text alignment: text.align_left, text.align_center, text.align_right, text.align_top, text.align_bottom. Wrapping: text.wrap_none, text.wrap_auto.
table — tables
Tables are anchored to a pane corner and do not move with candles. Max 2000 cells.
| Function | Returns | What it does |
|---|---|---|
table.new(position, columns, rows, bgcolor = na, frame_color = na, frame_width = 0, border_color = na, border_width = 0) |
table |
Table of the given size |
table.cell(id, column, row, text = "", width = 0, height = 0, text_color = color.black, text_halign = text.align_center, text_valign = text.align_center, text_size = size.normal, bgcolor = na, tooltip = na, text_font_family = font.family_default) |
— | Fill a cell |
table.cell_set_text(id, column, row, text), table.cell_set_tooltip(…, text) |
— | Cell text and tooltip |
table.cell_set_text_color(…, color), table.cell_set_bgcolor(…, color) |
— | Cell colors |
table.cell_set_text_size(…, size), table.cell_set_text_halign(…, align), table.cell_set_text_valign(…, align), table.cell_set_text_font_family(…, family) |
— | Text formatting |
table.cell_set_width(…, width), table.cell_set_height(…, height) |
— | Cell size |
table.set_position(id, position) |
— | Pane corner |
table.set_bgcolor(id, color), table.set_frame_color(id, color), table.set_frame_width(id, width), table.set_border_color(id, color), table.set_border_width(id, width) |
— | Background, frame, cell lines |
table.merge_cells(id, start_column, start_row, end_column, end_row) |
— | Merge a rectangle of cells |
table.clear(id, start_column, start_row, end_column = na, end_row = na) |
— | Clear a cell or range |
table.delete(id) |
— | Delete the table |
Positions: position.top_left, position.top_center, position.top_right, position.middle_left, position.middle_center, position.middle_right, position.bottom_left, position.bottom_center, position.bottom_right.
heatmap — heatmap layer
Draws price × bar cells under the candles the same way the built-in heatmap does. Works only in a script with overlay = true. Up to four layers (layer 0…3).
| Function | What it does |
|---|---|
heatmap.cell(price, value, layer = 0) |
Put a value into the cell at price of the current bar |
heatmap.depth(side = 0, min_qty = na, layer = 0) |
Paint the layer with the recorded order book for this bar. side: 1 — bids only, −1 — asks only, 0 — both sides |
heatmap.config(layer = 0, grid = na, palette = na, opacity = na, gamma = na, low = na, high = na, scale = na, cut = na, merge = na) |
Layer styling: price step, palette, opacity in percent, contrast, palette thresholds in percent, top of scale, cutoff for weak cells, how repeats are combined |
Palettes: heatmap.viridis (default), heatmap.magma, heatmap.inferno, heatmap.plasma, heatmap.turbo, heatmap.cividis, heatmap.ocean, heatmap.fire, heatmap.mono, heatmap.spectrum, heatmap.forest, heatmap.violet. Repeats on the same bar: heatmap.merge_max (default) or heatmap.merge_sum.
Collections: array, map, matrix
Element type is specified at creation: array.new<float>(0), map.new<string, float>(). To persist a collection between bars create it with var. Functions may be called as methods: a.push(x) is the same as array.push(a, x).
array
| Function | Returns | What it does |
|---|---|---|
array.new<T>(size = 0, initial = na) |
array<T> |
Array of size elements with value initial |
array.from(v0, v1, …) |
array<T> |
Array from listed values, up to ten |
array.size(id) |
int |
Number of elements |
array.get(id, index), array.set(id, index, value) |
T, — |
Read and write by index |
array.push(id, value), array.pop(id) |
—, T |
Push to end, pop from end |
array.unshift(id, value), array.shift(id) |
—, T |
Push to front, pop from front |
array.insert(id, index, value), array.remove(id, index) |
—, T |
Insert and remove by index |
array.clear(id) |
— | Clear |
array.includes(id, value) |
bool |
Whether the value exists |
array.indexof(id, value), array.lastindexof(id, value) |
int |
First and last position of the value |
array.sort(id, order = order.ascending) |
— | In-place sort; order.descending for descending |
array.sum(id), array.avg(id) |
float |
Sum and average; na are skipped |
array.min(id, nth = 0), array.max(id, nth = 0) |
float |
Min and max; nth = 1 — second by order |
array.join(id, separator = ",") |
string |
Elements joined by separator |
More array functions
| Function | Returns | What it does |
|---|---|---|
array.fill(id, value, index_from = 0, index_to = na) |
— | Fill a range with a single value |
array.slice(id, index_from, index_to) |
array<T> |
Slice of the array |
array.concat(id1, id2) |
array<T> |
Append second array to the first |
array.copy(id) |
array<T> |
Copy |
array.reverse(id) |
— | Reverse in place |
array.sort_indices(id, order = order.ascending) |
array<int> |
Element indices in sort order |
array.binary_search(id, value), array.binary_search_leftmost(…), array.binary_search_rightmost(…) |
int |
Binary search in a sorted array |
array.equals(id1, id2) |
bool |
Element-wise equality |
array.median(id), array.mode(id), array.range(id) |
float |
Median, mode, range |
array.stdev(id, biased = true), array.variance(id, biased = true) |
float |
Std dev and variance |
array.covariance(id1, id2, biased = true) |
float |
Covariance of two arrays |
array.abs(id) |
array<float> |
Array of absolute values |
array.percentile_linear_interpolation(id, percentage) |
float |
Percentile with interpolation |
array.percentrank(id, index) |
float |
Percentile rank of an element |
map
| Function | Returns | What it does |
|---|---|---|
map.new<K, V>() |
map<K, V> |
Empty dictionary |
map.put(id, key, value) |
V |
Write a value, returns previous |
map.get(id, key) |
V |
Value by key or na |
map.contains(id, key) |
bool |
Whether the key exists |
map.remove(id, key) |
V |
Remove the key, return the value |
map.clear(id), map.size(id) |
—, int |
Clear; number of pairs |
map.keys(id), map.values(id) |
array<K>, array<V> |
Keys and values as arrays |
map.copy(id) |
map<K, V> |
Copy |
matrix — matrices
| Function | Returns | What it does |
|---|---|---|
matrix.new<T>(rows = 0, columns = 0, initial = na) |
matrix<T> |
Matrix of the given size |
matrix.get(id, row, column), matrix.set(id, row, column, value) |
T, — |
Read and write element |
matrix.rows(id), matrix.columns(id) |
int |
Dimensions |
matrix.add_row(id, row = na, values = na), matrix.add_col(id, column = na, values = na) |
— | Add row or column; without index — append |
matrix.remove_row(id, row = na), matrix.remove_col(id, column = na) |
array<T> |
Remove a row or column and return it |
matrix.row(id, row), matrix.col(id, column) |
array<T> |
Row or column as an array |
matrix.fill(id, value, from_row = 0, to_row = na, from_column = 0, to_column = na) |
— | Fill a region |
matrix.copy(id), matrix.transpose(id) |
matrix<T> |
Copy and transpose |
matrix.mult(id1, id2), matrix.sum(id1, id2), matrix.diff(id1, id2) |
matrix<float> |
Product, sum, difference of two matrices |
matrix.det(id), matrix.trace(id) |
float |
Determinant and trace |
matrix.inv(id) |
matrix<float> |
Inverse matrix |
matrix.is_square(id) |
bool |
Whether the matrix is square |
Limits: array — 100,000 elements, map — 50,000 pairs, matrix — 1,000,000 elements.
request.security — another timeframe or instrument
| Function | Returns | What it does |
|---|---|---|
request.security(symbol, timeframe, expression, gaps = false, lookahead = false, ignore_invalid_symbol = false) |
float |
Evaluate expression on another timeframe or instrument and return the result on chart bars |
htfEma = request.security(sym.ticker, "60", ta.ema(close, 20))symbol—"VENUE:SYMBOL"orsym.ticker,timeframe— a string like"5","60","4h","1D","1W".- An unclosed higher timeframe bar can change until it closes — use
expression[1]for immutable history. lookahead = truepeeks into the future on history; the compiler warns about this.- Inside
expressionyou cannot read the order book or time and sales and chart variables — only inputs and series. - Limit — 8 different “instrument + timeframe” pairs and 32 calls per script.
Examples are in Other timeframe and instrument.
Alerts and the log
| Function | What it does |
|---|---|
alert(message, freq = alert.freq_once_per_bar_close) |
Send an alert with text. Works only live; silent on history |
alertcondition(condition, title, message = na) |
Declare a condition the user can attach an alert to in the terminal. Fires on bar close |
log.info(message), log.warning(message), log.error(message) |
Write a line to the Editor “Log” tab. Silent on history |
Alert frequency: alert.freq_all — on every pass, alert.freq_once_per_bar — once per bar on first trigger, alert.freq_once_per_bar_close — once per bar on close. See Script alerts.
strategy — strategies
Only works in a script declared with strategy(...). Orders are executed by the tester emulator on history — they are not placed on exchanges. How the tester works is explained in Strategies and the tester.
Orders
| Function | What it does |
|---|---|
strategy.entry(id, direction, qty = na, limit = na, stop = na, oca_name = na, oca_type = strategy.oca.none, comment = na, when = true) |
Enter strategy.long or strategy.short. Observes position model and pyramiding; an entry against a position reverses it |
strategy.order(id, direction, qty = na, limit = na, stop = na, oca_name = na, oca_type = strategy.oca.none, comment = na, when = true) |
Place an order bypassing entry rules: ignores position model and pyramiding |
strategy.exit(id, from_entry = na, qty = na, qty_percent = na, profit = na, limit = na, loss = na, stop = na, trail_price = na, trail_points = na, trail_offset = na, oca_name = na, comment = na, when = true) |
Exit by take, stop or trailing. profit, loss, trail_points — in ticks; limit, stop, trail_price — by price |
strategy.close(id, comment = na, qty = na, qty_percent = na, when = true) |
Close the entry id by market |
strategy.close_all(comment = na, when = true) |
Close everything |
strategy.cancel(id, when = true), strategy.cancel_all(when = true) |
Cancel unfilled orders |
If qty is not set the size is taken from defaultQtyType and defaultQtyValue in the declaration. OCA groups: strategy.oca.none, strategy.oca.cancel, strategy.oca.reduce.
Status
| Name | Type | What it contains |
|---|---|---|
strategy.position_size |
float |
Position size: positive — long, negative — short |
strategy.position_avg_price |
float |
Average entry price |
strategy.position_entry_name |
string |
Entry name that opened the position |
strategy.openprofit, strategy.netprofit |
float |
Unrealized and realized PnL |
strategy.grossprofit, strategy.grossloss |
float |
Sum of wins and sum of losses |
strategy.equity, strategy.initial_capital |
float |
Current and starting capital |
strategy.max_drawdown, strategy.max_runup |
float |
Largest drawdown and largest runup |
strategy.wintrades, strategy.losstrades, strategy.eventrades |
int |
Winning, losing and break-even trades |
strategy.opentrades, strategy.closedtrades |
int |
Open and closed trades |
strategy.margin_liquidation_price |
float |
Liquidation price for the given margin |
strategy.funding_paid |
float |
Funding paid and received |
Trade fields and constants
Fields of an open trade by index i — strategy.opentrades.<field>(i), closed — strategy.closedtrades.<field>(i):
| Field | Type | What it contains |
|---|---|---|
entry_price, entry_bar_index, entry_time, entry_id |
float, int, int, string |
Price, bar, time and entry name |
size |
float |
Trade size |
profit, max_runup, max_drawdown |
float |
Result, best and worst moments of the trade |
commission, funding |
float |
Commission and funding for the trade |
exit_price, exit_bar_index, exit_time, exit_id, exit_reason |
float, int, int, string, int |
Only on closed trades: price, bar, time, name and exit reason |
Exit reasons: strategy.exit_reason.stop_loss, take_profit, trailing_stop, market_order, reverse, oca, liquidation, end_of_data. This version does not return the oca reason.
Declaration constants: strategy.long, strategy.short, strategy.model.netting, strategy.model.hedging, strategy.qty.fixed, strategy.qty.cash, strategy.qty.percent_of_equity, strategy.qty.risk_percent, strategy.commission.percent, strategy.commission.cash_per_contract, strategy.commission.cash_per_order, strategy.fill.conservative, strategy.fill.optimistic.
Order flow data
These namespaces do not exist in ordinary indicator languages: clusters, delta, open interest, funding rate, recorded order book history and live data. If data for a bar is missing the value is na, not zero. Where the data comes from and how to check availability is explained in Market data: clusters, delta, open interest, funding rate, order book history, live order book and time and sales, screener.
History: available on every bar
| Namespace | Names |
|---|---|
cluster — footprint clusters of the bar |
available (data loaded), levels (number of levels), total (bar volume), delta, poc and poc_index (price and level index with the highest volume), max_cell (largest cell volume), grid_step (price step), stacked_buy / stacked_sell (price where a series of imbalances starts), stacked_buy_steps / stacked_sell_steps (series length in levels) |
cluster — functions |
cluster.price(index), cluster.bid(index), cluster.ask(index) — price and level volumes, counted from the bottom; cluster.imbalance(index) → int: 1 — buy-dominant, −1 — sell-dominant, 0 — none; cluster.value_area(coverage) → [low, high] — value area covering coverage share of volume |
delta — bar delta |
available, value (buys minus sells), buy, sell, cum (cumulative), min / max (intrabar extremes), open / high / low / close (delta as a candle), trades (number of trades), usd (in quote currency) |
oi — open interest |
available, open, high, low, close, usd, coins, change (change vs previous bar) |
funding — funding rate |
available, rate (forecasted rate), interval_hours (int, hours between settlements), settled (a settlement occurred on the bar), settled_rate (applied rate), cum (cumulative) |
depth — recorded order book history |
available, levels, grid_step, best_bid, best_ask, max_cell; depth.price(index), depth.qty(index), depth.side(index) (1 — bid, −1 — ask); depth.at(price); depth.bid_sum(percent), depth.ask_sum(percent), depth.imbalance(percent) — in a band of percent % from the middle; depth.max_bid(percent), depth.max_ask(percent) → [price, qty] |
Live only: always na on history
| Namespace | Names |
|---|---|
book — order book |
available, spread, mid; book.bid(index), book.ask(index) — level prices from best; book.bid_qty(index), book.ask_qty(index) — quantities; book.imbalance(depth) — imbalance over depth levels, −1…1 |
tape — time and sales |
available, last_price, last_qty, last_side (1 — buyer, −1 — seller); tape.count(window_ms) → int, tape.buy_volume(window_ms), tape.sell_volume(window_ms), tape.max_print(window_ms) — over the last window_ms milliseconds |
screener — screener metrics |
available; screener.natr(window), screener.rvol(window), screener.avg_vol(window), screener.btc_corr(window), screener.change(window), screener.oi_delta(window), screener.vol(window) |
Screener windows are strings: natr — "1m", "5m"; rvol — "1h", "24h"; avg_vol — "1m", "5m", "15m", "1h"; btc_corr — "1m", "5m"; change and oi_delta — "1m", "5m", "1h", "24h", change also supports "15m"; vol — "1m", "5m", "15m", "1h", "24h". A window not listed returns na.