← Back to the docs
LootX

Язык Loot

LootScript — custom indicators and alerts in the terminal, backtest strategies on history.

Generated: 2026-11-21 docs.lootx.trade
Основы

1LootScript Language

What LootScript is: indicators, strategies and libraries that run directly in the terminal on chart data. What data is available, how to enable scripts, and what they don't do.

LootScript is the scripting language of the LootX terminal. You write your own indicators, strategies for backtesting ideas on history, and libraries of shared functions. A script is a text file that runs directly in the terminal on the data of the chart you’ve added it to: candles, volume, delta, footprint clusters, open interest, funding rate.

Here’s a complete indicator — the delta of each bar as columns under the chart:

Loot
indicator("Bar Delta", overlay = false)

d = delta.available ? delta.value : na
plot(d, "Delta", style = plot.style_columns, color = d >= 0 ? color.teal : color.red)

What you can write

The first line of a script declares its kind, and the kind determines what the script is allowed to do.

Kind First line What it does
Indicator indicator("Name") Calculates values per bar and draws them: lines, histograms, levels, markers, background, labels. Draws on the price or in a separate panel under the chart.
Strategy strategy("Name") Same as an indicator, plus entry and exit rules. Strategy orders are virtual — the Strategy Tester executes them on history and shows trades, equity curve and metrics.
Library library("Name", 1) Stores functions that your other scripts import. Not added to a chart and draws nothing.

Besides your own scripts, you can bring over existing Pine Script files: the terminal converts them to LootScript on import. How this works and what to check after conversion — on the Pine Script import page.

What data the script has access to

  • Chart candles: open, high, low, close, volume, bar time and derivatives like hl2.
  • Order flow: aggressive buyer and seller delta, footprint clusters by price level, open interest, funding rate, recorded order book history, screener metrics.
  • Live order book and time and sales — only on the current, not yet closed bar: their history is not recorded.
  • Other timeframes and instruments — via a series request from a higher timeframe or another coin.

If an exchange doesn’t provide a certain metric or there is no data for a bar, the script receives not zero but a special value na — “no value”. On the chart this is a line break, not a false zero. Details and coverage by exchange — on the Market data page.

Where the script runs

The script runs inside the terminal on your computer. It is not sent to or executed on the LootX server.

  • Isolation. The script has no access to the network, files, exchange connections or API keys. Such functions simply don’t exist in the language — neither accidentally nor intentionally can the script transmit your data anywhere.
  • Limits. An overly long loop or a huge array stops only that script. Other indicators, panels and the terminal itself keep working, and the reason for stopping is shown in the editor.
  • Files. Each script is a separate file with the .loot extension. On Windows they are stored in %APPDATA%\TradingTerminal\scripts\, outside the installation folder, so terminal updates don’t touch them. Moving a script to another computer means copying the file.

How to enable scripts

Scripts are a separate module that is enabled for your LootX account. For it to work, sign in to the terminal with your account.

When the module is enabled, the chart indicators window (the ƒ button on the chart panel) shows the sections Favorites, My scripts, Built-in and Strategies, and at the top — the Import… and Editor… buttons.

When the module is not enabled, scripts are not shown at all: the indicators window contains only built-in indicators, with no editor or import. There are also no locks or purchase offers — the terminal looks as if scripts don’t exist in it. As soon as access appears, the indicators window rebuilds itself; you don’t need to restart the terminal.

Access is granted per account — as part of a plan or separately. Current plans are on the Subscriptions page.

What scripts don’t do

  • Does not go online or read files. Everything the script knows is the data of the chart it is on.
  • Is not published or sold. There is no script catalog: a script is your local file; you can share it only by passing the file.
  • Does not execute Pine Script directly. Scripts in that format are first converted to LootScript on import; identical numbers with other platforms are not guaranteed.

Next

https://docs.lootx.trade/en/loot/overview

Справочник

2Function 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.

Loot
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.
  • = na on 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
Loot
htfEma = request.security(sym.ticker, "60", ta.ema(close, 20))
  • symbol — "VENUE:SYMBOL" or sym.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 = true peeks into the future on history; the compiler warns about this.
  • Inside expression you 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.

Next

https://docs.lootx.trade/en/loot/reference

Основы

3Your first script

Step by step: open the LootScript editor, write a two-line indicator, add it to a chart, read errors, and find the script file. Second example: a channel with settings.

On this page you’ll go from an empty editor to your own indicator on a chart: you’ll write a two-line script, see how the editor catches errors, learn where the file lives, and add a settings window. You’ll need an open chart and scripts enabled — if they’re not in the indicators window, read How to enable scripts.

Open the editor

Open the indicators window

On the chart panel, click the ƒ button — its tooltip says “Indicators”.

Launch the editor

Click Editor… next to the search field or New script at the bottom of the window. To open an existing script, find it under My scripts and click the pencil Edit script in its row (or select the row and press Ctrl+E).

Find the buttons you need

The editor opens in a separate window with its own taskbar button — you can move it to a second monitor. At the top — a dropdown list of scripts and the New, Save, and Add to chart buttons; at the bottom — the Problems, Log, and Output tabs.

The editor remembers the chart panel whose indicators window you opened it from — it will add the script there. If you open the editor another way, the script goes to the active chart panel.

Write an indicator

The New button (Ctrl+N) creates a script from a template — a moving average with one setting:

Loot
indicator("Без названия", overlay = true)

length = input.int(20, "Length", minval = 1)
plot(ta.ema(close, length), "EMA", color = color.orange)

Replace the text with the shortest working indicator — a simple 20-bar moving average:

Loot
indicator("Мой первый индикатор", overlay = true)

plot(ta.sma(close, 20), "Средняя 20", color = color.orange)

What’s here:

  • indicator(...) — the declaration, a required first line of any script. The name goes to the My scripts list and the chart legend. overlay = true draws over candles; with overlay = false the indicator gets its own chart panel below the chart.
  • ta.sma(close, 20) — the average of closing prices over the last 20 bars.
  • plot(...) — draws a line: one value per bar. The second argument is the line’s name in settings, color is the color.

The script runs for each bar in order, from the oldest to the current one. The first 19 bars don’t have enough history for the average, so the line doesn’t start at the left edge — that’s normal. The editor shows how many bars this “warm-up” takes in the status bar at the bottom.

As you type, the editor suggests function and constant names, shows function parameters after an opening parenthesis, and shows a description when you hover over a name. You can bring up the suggestion list manually with Ctrl+Space.

Save and add to chart

  • Save (Ctrl+S) writes the script to the scripts folder. While there are unsaved changes, a dot • appears before the file name in the window title.
  • Add to chart (Ctrl+Enter) checks the script, saves it, and places it on the chart panel. The editor panel will show: “Мой первый индикатор” added to chart.

Done: a line on the chart, the indicator’s name in the legend. The indicator is saved in the layout and returns after the terminal restarts.

How the editor shows errors

The script is checked automatically — a moment after you stop typing. The result is visible in the editor header: compiling…, then ok · 12 ms or, if something’s wrong, errors: 1 or warnings: 1.

Try making a mistake: type ta.smaa instead of ta.sma. The error is underlined with a wavy line, the counter in the header shows errors: 1, and the Problems tab gets a line with the error code, explanation, and position:

TEXT
LS2002  Неизвестное имя «ta.smaa» — проверьте написание или объявите его выше   Стр 3:6

Double-clicking the line moves the cursor to the error. Every error has a permanent code like LS####, and the text immediately suggests how to fix it. Common errors are covered in Compile and runtime errors.

A script with errors won’t go on the chart: Add to chart responds with “Script with errors can’t be placed on the chart — see Problems” and moves the cursor to the first error. In the indicators window, such a script is marked with a red badge showing the error count instead of the Script badge.

There are also runtime errors — for example, a loop that doesn’t finish in the allotted time. Then the script stops, and the reason appears on the Output tab: “Script stopped: …”. Other indicators and the terminal keep working.

Editing a script that’s already on a chart

While you edit, the chart keeps showing the version you added. As soon as a working version that differs from the chart appears in the editor, two things happen:

  • the editor panel shows an Update indicator button;
  • the indicator’s legend on the chart shows an update icon.

Either one saves the script and replaces it on every chart where it’s placed. Add to chart for a script that’s already added somewhere does the same — it updates all copies instead of adding a second one. The editor header shows how many panels will get the new version with an on charts: N badge.

Where the files live

On Windows, scripts are stored in %APPDATA%\TradingTerminal\scripts\, one .loot file per script. It’s plain text — you can open it in any editor, copy it, back it up. The folder is outside the installation folder, so terminal updates don’t touch it.

The file name comes from the title at first save: spaces become underscores, Cyrillic is preserved. “Мой первый индикатор” becomes Мой_первый_индикатор.loot.

When the folder is first created, six starter scripts are placed in it — Two moving averages, RSI with zones, Volume impulse, Cumulative delta, Interest vs price, and Funding rate annualized. They’re in the My scripts section; they’re handy to open and study.

Second example: a channel with settings

Let’s make the script more useful: a channel from an average and two boundaries at a distance of a few standard deviations. We’ll put the period, width, and price source into settings, and highlight the upper and lower boundaries in red when price breaks out of them.

Loot
indicator("Канал вокруг средней", overlay = true)

length = input.int(20, "Период", minval = 2)
mult   = input.float(2.0, "Ширина в сигмах", minval = 0.1, step = 0.1)
src    = input.source(close, "Источник")

basis = ta.sma(src, length)
dev   = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev

plot(basis, "Середина", color = color.gray)
plot(upper, "Верх", color = close > upper ? color.red : color.teal)
plot(lower, "Низ", color = close < lower ? color.red : color.teal)

What’s new:

  • Each input.* call becomes a row in the indicator’s settings window, in the order it’s written. minval prevents entering a period below two, and step = 0.1 means the width field shows one decimal place.
  • input.source becomes a dropdown list of series: close, open, hl2, volume, and others.
  • The boundary colors are expressions, so they’re calculated on every bar separately.

Add the script to the chart and double-click its row in the legend (or click the settings icon there). On the Inputs tab there are your three settings: change the period and the lines recalculate immediately. Values are remembered for this indicator on this chart; the Defaults button restores the values written in the code. On the Style tab — the average’s color and each line’s thickness; on the Visibility tab — checkboxes to hide any of the three lines. The boundary colors have no setting: the script chooses them on every bar.

Next

https://docs.lootx.trade/en/loot/first-script

Основы

4Syntax and Types

How LootScript works: bar-by-bar execution, script declaration, five assignment forms, types and qualifiers, na, history x[n], operators, conditionals, switch, loops, functions, and custom types.

This page is a brief language reference: how a script executes, how to declare variables, what types exist, what na means, how to read past bars, how to write conditionals, loops and functions. All examples are complete working scripts: you can paste them into the editor and add them to a chart.

How a Script Executes

Everything at the top level of a file runs once per bar — from the oldest loaded bar to the current one, line by line. So a variable in LootScript stores not a single number but a value per bar; past values are accessible.

Loot
indicator("Тело свечи")

body = close - open          // считается заново на каждом баре
plot(body, "Тело", style = plot.style_columns)

On the current, still-open bar the script recalculates on every new tick, starting from the state it had at the previous bar’s close. Closed bars are not recalculated.

Declaration

The first statement of a script is exactly one declaration: indicator(...), strategy(...) or library(...). Above it, only comments and an optional version string #version 1 may appear. Without a declaration the script won’t compile, showing the error “No script declaration — start with indicator("Name")”.

Loot
#version 1
// Комментарии и строка версии могут стоять выше объявления.
indicator("Размах бара", shortTitle = "Размах", overlay = false)

plot(high - low, "Размах", style = plot.style_histogram)

The main indicator parameters: title — the name in the script list, shortTitle — the short legend name, overlay — draw over price (true) or in a separate panel (false, default). Strategy parameters are described on the Strategies and Tester page.

Variables and Assignment

Form What it does
x = expression Declares a variable. On each bar it is recalculated.
x := expression Assigns a new value to an already declared variable. The type must match.
var x = expression Declares a variable once, on the first bar. Its value carries over to subsequent bars.
varip x = expression Like var, but the value also persists between ticks of the current bar.
[a, b, c] = function(...) Destructures multiple function results into variables.

To modify an already declared variable there are also shorthand forms: +=, -=, *=, /=, %=. The type can be specified explicitly: float level = 0. Names of built-in series and namespaces (close, volume, ta and others) are reserved — you cannot use them for your own variables.

The key difference from ordinary languages is that a normal variable does not accumulate value between bars. For counters and sums you need var:

Loot
indicator("Счётчик зелёных свечей")

var greens = 0          // объявляется один раз и переживает переход к следующему бару
if close > open {
    greens += 1
}

today = 0               // а эта переменная равна 0 на каждом новом баре
today := today + 1      // поэтому здесь всегда 1

plot(greens, "Зелёных с начала истории")

varip is rarely needed — for example, to count ticks inside a bar. There are no ticks in history, so its value on past bars will differ from what it was live. If a varip value is plotted, the editor warns about repainting.

Types

Type Stores Example
int integer 14, 1_000_000, 0xFF
float floating-point number 2.5, .5, 1e-9
bool true or false true, false
string text "BTC", 'BTC'
color color with transparency #FF9800, #FF980080, color.teal

There are also composite types: arrays array<float>, maps map<string, float>, matrices matrix<float>, plus your own types and enums (see below) and drawing objects line, box, label, table.

The rules that trip people up most often:

  • The type is fixed at declaration. After x = 1 you cannot assign x := 2.5: x is an integer. Write x = 1.0 or float x = 1.
  • An integer converts to float automatically, the reverse only explicitly: math.round, math.floor, math.ceil, math.trunc.
  • Integer division is integer: 7 / 2 equals 3. For a fraction, make one operand fractional: 7.0 / 2.
  • Exponentiation ^ always yields a float: 2 ^ 3 equals 8.0.
  • A string cannot be concatenated with a number. "Цена: " + close won’t compile — write "Цена: " + str.tostring(close).
  • A condition must be bool. if volume { … } is an error; write if volume > 0 { … }.

Qualifiers: How Constant a Value Is

Besides its type, each value has a qualifier — how constant it is during script execution. From weakest to strongest:

Qualifier When value is known Example
const already at compile time 14, "EMA"
input after reading settings, then unchanged input.int(14, "Период")
simple at startup, then unchanged step size of the instrument
series may change on every bar close, bar_index

In practice this matters in one place: lengths of ta.* functions must be constant — a literal or a setting. Otherwise the function would have to rebuild its state on every bar.

Loot
indicator("Период из настроек")

len = input.int(14, "Период", minval = 2)
plot(ta.rsi(close, len), "RSI")

// ta.rsi(close, bar_index) не скомпилируется:
// «length» в «ta.rsi» требует значение не слабее input, а передано series

na — No Value

na means “no value”: not enough history for the calculation, the exchange doesn’t provide the metric, or there is a gap in the data. na exists in any type.

  • Arithmetic with na yields na: na + 1 is na.
  • Any comparison with na is false, so if x > 0 won’t execute when x = na.
  • Check absence only via na(x). Writing x == na is rejected by the compiler with the error “Comparison with na is always false — use na(x)”.
  • nz(x) substitutes 0 for na, nz(x, v) substitutes v. The same, shorter: x ?? v.
  • na on a chart is a gap in the line, not zero.
Loot
indicator("Средняя без пустого начала", overlay = true)

avg = ta.sma(close, 50)             // на первых 49 барах — na

line1 = na(avg) ? close : avg       // проверка через na(x)
line2 = avg ?? close                // то же короче

plot(line2, "Средняя или цена", color = color.orange)

History: x[n]

x[n] is the value of x on the bar n bars ago; x[0] is the current one. Works with any series, including your own variables.

Loot
indicator("Наклон средней")

ma    = ta.ema(close, 20)
slope = ma - ma[1]                  // изменение за один бар

plot(slope, "Наклон", style = plot.style_histogram,
     color = slope >= 0 ? color.teal : color.red)
  • If n is greater than the number of bars before history starts, the result is na, not an error.
  • n can vary from bar to bar: close[len] with a variable len is allowed.
  • A negative index is an error: you cannot look into future bars.
  • You don’t need to configure history depth: the script has access to all history loaded on the chart.

Operators

From highest precedence to lowest:

Priority Operators
1 x[n], call f(…), dot access a.b
2 ^ — exponentiation, right-associative
3 unary -, +, not
4 *, /, %
5 +, -
6 <, >, <=, >=
7 ==, !=
8 and
9 or
10 ?? — na replacement
11 ? : — conditional expression
  • Comparisons do not chain: instead of a < b < c write a < b and b < c.
  • and and or don’t evaluate the right operand if the answer is already determined by the left one.
  • Exponentiation binds tighter than unary minus: -2 ^ 2 equals -4. For 4, write (-2) ^ 2.
  • Compare fractional numbers with a tolerance: math.approx(a, b), because 0.1 + 0.2 == 0.3 is false.

Conditionals

Blocks always use curly braces. if can be a statement and an expression; for a simple binary choice there is ? :.

Loot
indicator("Направление бара")

dir = 0
if close > open {
    dir := 1
} else if close < open {
    dir := -1
}

// if как выражение: обе ветки обязательны
bodySize = if close >= open { close - open } else { open - close }

// условный оператор для простых случаев
barColor = dir > 0 ? color.teal : color.red

plot(bodySize, "Тело", style = plot.style_columns, color = barColor)

switch

switch picks the first matching branch. The form with an object compares it against the branch values; the form without an object checks conditions in order. A => branch without a condition is the default branch. There is no fall-through to the next branch. When switch returns a value, the default branch is mandatory.

Loot
indicator("Средняя на выбор", overlay = true)

kind = input.string("EMA", "Тип средней", options = ["EMA", "SMA", "WMA"])

ma = switch kind {
    "EMA" => ta.ema(close, 20)
    "SMA" => ta.sma(close, 20)
    =>       ta.wma(close, 20)
}

zone = switch {
    close > ma * 1.02 => 1
    close < ma * 0.98 => -1
    =>                   0
}

plot(ma, "Средняя", color = zone == 1 ? color.teal : zone == -1 ? color.red : color.gray)

Loops

for i in a .. b iterates over numbers from a inclusive to b exclusive. The step is set with by, including negative. The loop variable exists only inside the loop and cannot be changed in the body.

Loot
indicator("Зелёные свечи за N баров")

n = input.int(10, "Сколько баров", minval = 1, maxval = 200)

greens = 0
for i in 0 .. n {               // i = 0, 1, …, n − 1
    if close[i] > open[i] {
        greens += 1
    }
}

plot(greens, "Зелёных", style = plot.style_columns)
Loot
indicator("Виды циклов")

total = 0
for i in 0 .. 10 by 2 {         // 0, 2, 4, 6, 8
    total += i
}
for i in 10 .. 0 by -1 {        // 10, 9, …, 1
    if i % 3 == 0 {
        continue                // сразу к следующему шагу
    }
    total += i
}

var closes = array.new<float>(0)
closes.push(close)
if closes.size() > 20 {
    closes.shift()
}
sum = 0.0
for v in closes {               // по элементам массива; for [i, v] in … — с индексом
    sum += v
}

k = 0
while k < 100 {
    k += 7
    if k > 50 {
        break                   // выход из цикла
    }
}

plot(sum / closes.size(), "Средняя из массива")

An infinite loop won’t hang the terminal: a script has an operations budget per bar and a time limit. When exceeded, the script stops with the message “Script exhausted per-bar operations budget — simplify the loop” or “Script exceeded per-pass time limit”.

Functions

A function is declared with func. The short form is an expression after =>, the long form is a body in braces with return. Parameter types can be omitted — they are inferred from calls, and parameters may have default values. Arguments are passed by position or by name.

Loot
indicator("Z-оценка объёма")

func barRange(h, l) => h - l

func zscore(series float src, input int len) => float {
    m = ta.sma(src, len)
    s = ta.stdev(src, len)
    return s == 0 ? na : (src - m) / s
}

func scaled(x, k = 2.0) => x * k

z = zscore(volume, 50)
plot(z, "Z объёма", style = plot.style_columns, color = z > 2 ? color.orange : color.gray)
plot(scaled(barRange(high, low), k = 0.5), "Полразмаха")
  • No recursion. A function cannot call itself, directly or through another function. Repetition is written with a loop.
  • State is per call. If a function contains ta.* or var, two calls to the same function maintain independent calculations:
Loot
indicator("Два вызова одной функции", overlay = true)

func smooth(src, len) => ta.ema(src, len)

fast = smooth(close, 10)        // своя средняя
slow = smooth(close, 30)        // другая, независимая средняя

plot(fast, "Быстрая", color = color.teal)
plot(slow, "Медленная", color = color.orange)

Functions needed in multiple scripts are moved into a library: a script with the declaration library("Имя", 1), export before functions, and in another script import Имя/1 as имя. The library is taken from your scripts folder.

Multiple Results

Some functions return multiple series at once: ta.bb, ta.macd, ta.kc, ta.dmi, ta.supertrend and others. Their result is destructured into variables in square brackets; the number of names must match the number of results.

Loot
indicator("Полосы Боллинджера", overlay = true)

[basis, upper, lower] = ta.bb(close, 20, 2.0)

plot(basis, "Середина", color = color.gray)
plot(upper, "Верх", color = color.teal)
plot(lower, "Низ", color = color.teal)

Custom Types and Enums

type collects several fields into one structure. An object is created via Имя.new(...), fields are read and modified via dot.

Loot
indicator("Последний локальный максимум", overlay = true)

type Swing {
    int   barIndex
    float price
}

var Swing last = Swing.new(barIndex = 0, price = high)

ph = ta.pivothigh(high, 5, 5)
if not na(ph) {
    last.barIndex := bar_index - 5
    last.price := ph
}

plot(last.price, "Максимум", style = plot.style_stepline, color = color.orange)

enum is a closed list of options with labels. It is safer than strings: a typo in a variant name is a compile error, not a silently failing condition. Combined with input.enum, an enum becomes a dropdown in settings — see Inputs and Drawing.

Loot
indicator("Режим рынка")

enum Regime {
    trend = "Тренд"
    flat  = "Флэт"
}

regime = math.abs(close - close[20]) > ta.atr(14) * 3 ? Regime.trend : Regime.flat

plot(regime == Regime.trend ? 1 : 0, "Тренд", style = plot.style_stepline)

ta.* Functions Inside Conditionals

Functions like ta.ema, ta.rsi or ta.atr remember their state from the previous bar. If such a call ran only on some bars — inside an if or one branch of ? : — its calculation would skip bars and silently produce wrong numbers.

LootScript does not allow this: the compiler hoists every ta.* call out of the conditional and runs it on every bar, and the condition only selects whether to use the result. So this code computes RSI correctly:

Loot
indicator("RSI только на зелёных барах")

r = close > open ? ta.rsi(close, 14) : na

plot(r, "RSI", style = plot.style_circles)

The call cannot be hoisted only if its argument itself is born inside a branch. Then the compiler does not guess, but reports: “Argument «len» cannot be computed outside the branch — hoist the ta.* call to the top level”. The solution is to compute the argument before the condition:

Loot
indicator("Аргумент до условия")

// Так нельзя — len объявлена внутри ветки:
// if close > open {
//     len = 10
//     e = ta.ema(close, len)
// }

len = 10
e = ta.ema(close, len)

plot(close > open ? e : na, "EMA на зелёных барах", style = plot.style_circles)

Comments and Line Breaks

  • // — comment to end of line, /* … */ — block comment, blocks can be nested.
  • A statement ends at end of line; a semicolon is not needed.
  • A long expression continues on the next line if the line is broken inside parentheses, ends with an operator, or the next line starts with an operator, ? or :.
Loot
indicator("Перенос строк")

typical = high
        + low
        + close

signal = close > open
    ? typical / 3
    : na

plot(signal, "Типичная цена на зелёных барах", style = plot.style_circles)

Next

https://docs.lootx.trade/en/loot/syntax

Основы

5Settings and Rendering

Input.* settings in the indicator window, plot lines and their styles, hline levels, fills, background and candle color, markers, labels, line segments, boxes, tables, colors and transparency. Limits: three plottable plots and 500 objects of each type.

This page covers what the user sees and can change. It describes the settings a script exposes in the indicator window, lines and their styles, levels and fills, background and candle color, markers, labels, line segments, boxes, and tables, plus colors and transparency. A section on limits worth knowing in advance is at the end.

Settings: input.*

Each input.* call becomes a row on the Inputs tab in the indicator settings window. Rows appear in the order the calls are written in the script. The first argument sets the default value, the second sets the row label.

Call What appears in the settings window
input.int Field for an integer
input.float Field for a decimal number
input.bool Checkbox
input.color Color picker
input.string Dropdown list if options is set; otherwise a text field
input.source Dropdown list of series: open, high, low, close, hl2, hlc3, ohlc4, hlcc4, volume
input.enum Dropdown list of enum labels
input.timeframe Text field; with options, a dropdown list
input.symbol Text field

The example below brings together five kinds of settings in one script:

Loot
indicator("Средняя на выбор", overlay = true)

enum Basis {
    sma = "Простая"
    ema = "Экспоненциальная"
    wma = "Взвешенная"
}

basis     = input.enum(Basis.ema, "Тип средней")
length    = input.int(50, "Период", minval = 1, maxval = 500)
src       = input.source(close, "Источник")
lineColor = input.color(color.orange, "Цвет линии")
showBg    = input.bool(false, "Подсвечивать фон")

avg = switch basis {
    Basis.sma => ta.sma(src, length)
    Basis.ema => ta.ema(src, length)
    =>           ta.wma(src, length)
}

plot(avg, "Средняя", color = lineColor, linewidth = 2)
bgcolor(showBg and close > avg ? color.new(color.teal, 40) : na, title = "Фон")

The settings window will show a dropdown list “Тип средней” with the items “Простая”, “Экспоненциальная”, and “Взвешенная”. Below it are a length field, a source list, a color picker, and a checkbox. How to declare enums is covered in Свои типы и перечисления.

Number and string parameters

  • minval and maxval set bounds: the field will not accept a period below minval or above maxval.
  • step on input.float sets how many decimal places the field shows: with step = 0.1, one decimal is visible. The field has no arrows; the value is typed.
  • options on input.string and input.timeframe turns the field into a dropdown list. The default value must be one of the items, otherwise the compiler raises an error.
  • tooltip, group, and inline are accepted by the compiler but currently have no effect on the settings window appearance.
Loot
indicator("Цена для расчёта")

mode  = input.string("Закрытие", "Считать по", options = ["Закрытие", "Середина свечи"])
price = mode == "Закрытие" ? close : hl2

plot(ta.rsi(price, 14), "RSI", color = color.purple)

For input.source, the default can also be a market data series, for example delta.cum. Such a series appears as the first item in the list, before price series. If the default is an expression like (high + low) / 2, no row appears in the settings window: there is nothing to choose from.

There are currently no dedicated settings for time, trading session, or a price chosen by clicking on the chart.

Where selected values are stored

Values are remembered separately for each indicator on each chart: two copies of the same script on different panels can have different periods. The Defaults button in the settings window restores the values written in the code.

The value is tied to the variable name that stores the input.* call. The row label can be changed freely; the selected value is kept. Rows can also be reordered. But if the variable is renamed (length to period), the setting resets to the value from the code.

The settings window opens by double-clicking the indicator row in the chart legend or by clicking the settings icon in that row. Besides the Inputs tab, it has Style and Visibility — covered below.

Lines: plot

plot draws a series, one value per bar. Only the first argument — the series itself — is required. The rest of the parameters are passed by name:

  • title — the line name in the legend and in the settings window;
  • color — the color, constant or calculated on each bar;
  • linewidth — the thickness;
  • style — the rendering style, see the table;
  • offset — shift by a number of bars: positive to the right, negative to the left;
  • show_last — draw only the last N bars;
  • join = true — connect the points of circles and cross styles with a line;
  • editable = false — remove the line from the settings window;
  • display = display.none — hide the line when added; it can be enabled on the Visibility tab.
Style Appearance
plot.style_line Polylined line, the default style
plot.style_linebr Same as line
plot.style_stepline Step line
plot.style_stepline_diamond Step line with diamonds
plot.style_histogram Thin bars from zero, line width
plot.style_columns Bars from zero, candle width
plot.style_area Area filled to zero
plot.style_areabr Same as area
plot.style_circles Dots
plot.style_cross Crosses

The line always breaks where the series has no value (na) and does not jump over a gap with a straight segment. That is why the pairs line/linebr and area/areabr render the same.

Loot
indicator("Стили линий")

d = close - open

plot(d, "Тело свечи", style = plot.style_histogram, color = d >= 0 ? color.teal : color.red)
plot(ta.sma(d, 10), "Средняя 10", style = plot.style_stepline, color = color.orange, linewidth = 2)
plot(ta.sma(d, 30), "Средняя 30", style = plot.style_circles, color = color.gray)

Color by bar

The color can be an expression: it is then recalculated on each bar. A color of na means there is no line on that bar:

Loot
indicator("Средняя только над ценой", overlay = true)

m = ta.sma(close, 50)
plot(m, "Средняя", color = close > m ? color.teal : na)

What a line gets in the settings window

  • On the Style tab, the thickness of each line can be adjusted. A color row appears only for a line with a constant color: if the script picks the color on each bar, there is nothing to change in the window.
  • On the Visibility tab, each line has a show checkbox. It appears when there is more than one line or when the line is hidden via display.
  • A line with editable = false gets no rows on either tab.

Levels and fills

hline draws a horizontal line at a constant price — for example, RSI zone boundaries. The price must be a number or an input.* setting: a series that changes bar by bar does not fit here. For such a line, use plot. The line style is set with hline.style_solid, hline.style_dashed, and hline.style_dotted.

fill shades the area between two boundaries. To get a boundary, save the result of hline or plot to a variable:

Loot
indicator("RSI с зонами")

length = input.int(14, "Период", minval = 1)
r = ta.rsi(close, length)

top    = hline(70, "Перекупленность", color = color.gray, linestyle = hline.style_dashed)
bottom = hline(30, "Перепроданность", color = color.gray, linestyle = hline.style_dashed)
fill(top, bottom, color = color.new(color.purple, 30), title = "Зона")

plot(r, "RSI", color = r > 70 ? color.red : r < 30 ? color.teal : color.purple)

Both boundaries must be of the same kind: two hline levels or two plot lines. A fill between a line and a level is not accepted by the compiler.

The fill color between two lines can change bar by bar. This is how a “cloud” of two moving averages is made:

Loot
indicator("Облако", overlay = true)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)

pf = plot(fast, "Быстрая", color = color.teal)
ps = plot(slow, "Медленная", color = color.orange)
fill(pf, ps, color = fast > slow ? color.new(color.teal, 50) : color.new(color.red, 50), title = "Облако")

There is also gradient fill. Set top_value and bottom_value to indicate the heights where the color equals top_color and bottom_color; between them the color transitions smoothly. These heights must be constant numbers. If you need a fill to a constant level, make it a line, plot(50). But remember that is one of the three plotted lines.

Loot
indicator("RSI с градиентом")

r  = ta.rsi(close, 14)
pr = plot(r, "RSI", color = color.purple)
pm = plot(50, "Середина", color = color.gray)
fill(pr, pm, top_value = 80, bottom_value = 50,
     top_color = color.new(color.teal, 160), bottom_color = color.new(color.teal, 0))

Background and candle color

bgcolor shades the background under a bar, barcolor recolors the candle itself. Both accept a color calculated on each bar; on bars with a color of na, nothing changes.

Loot
indicator("Подсветка объёма", overlay = true)

avgVol = ta.sma(volume, 20)
spike  = volume > avgVol * 2

bgcolor(spike ? color.new(color.orange, 40) : na, title = "Всплеск объёма")
barcolor(close > open ? color.teal : color.red, title = "Цвет свечей")

Markers: plotshape and plotchar

plotshape places an icon on bars where a condition is true. plotchar does the same with any character.

Loot
indicator("Пересечения", overlay = true)

fast = ta.ema(close, 9)
slow = ta.ema(close, 21)

plotshape(ta.crossover(fast, slow), "Вверх", style = shape.triangleup,
          location = location.belowbar, color = color.teal, size = size.small)
plotshape(ta.crossunder(fast, slow), "Вниз", style = shape.triangledown,
          location = location.abovebar, color = color.red, size = size.small)
plotchar(volume > ta.sma(volume, 20) * 3, "Объём", char = "●", location = location.top, color = color.orange)
  • Shape, shape.*: triangleup, triangledown, arrowup, arrowdown, circle, square, diamond, cross, xcross, flag, labelup, labeldown.
  • Location, location.*: abovebar — above the candle, belowbar — below the candle, top and bottom — at the top and bottom edge of the panel. In a separate panel below the chart, “above the candle” and “below the candle” also mean the top and bottom edge: such a panel has its own scale, and candle prices are not plotted on it.
  • Size, size.*: auto, tiny, small, normal, large, huge.
  • text adds a short label next to the icon. When the chart is zoomed out far and candles are narrow, labels are hidden, but icons remain.

Drawing objects

Besides series, a script can draw individual objects: labels label.new, line segments line.new, boxes box.new, and tables table.new. Each *.new call returns an object. It can be moved with set_* functions (label.set_xy, line.set_x2, box.set_top, and so on), read with get_*, copied with copy, or deleted with delete.

Horizontally, an object is bound by default to the bar number, bar_index. With the parameter xloc = xloc.bar_time, the coordinate is set by bar time. For a line segment and a box, the parameter extend (extend.right, extend.left, extend.both) extends the edge to the chart boundary.

An object stays on the chart until it is deleted. The script runs on every bar, so an unconditional label.new would create a label on every bar. To keep one object and move it, store it in a var variable and delete the old one:

Loot
indicator("Последний пивот", overlay = true, maxLabelsCount = 50)

ph = ta.pivothigh(high, 10, 10)

var line level = na
if not na(ph) {
    label.new(bar_index - 10, ph, str.tostring(ph), style = label.style_label_down,
              color = color.orange, textcolor = color.white, size = size.small)
    line.delete(level)
    level := line.new(bar_index - 10, ph, bar_index, ph, extend = extend.right,
                      color = color.orange, style = line.style_dashed)
}

The script labels each found high and extends a dashed line to the right from the latest one. It deletes the previous dashed line.

No more than 500 live objects of each kind can exist at once. When the five hundred and first appears, the oldest one disappears. The maxLinesCount, maxLabelsCount, and maxBoxesCount parameters in indicator() lower this limit. A value above 500 is capped at 500.

Tables

A table is anchored not to bars but to a corner or edge of the panel and does not move when the chart scrolls. The position is set by position.*: top_left, top_center, top_right, middle_left, middle_center, middle_right, bottom_left, bottom_center, bottom_right. Cells are filled by table.cell. It is convenient to do this only on the last bar, to avoid rewriting the table across the entire history:

Loot
indicator("Сводка", overlay = true)

var t = table.new(position.top_right, 2, 2, bgcolor = color.new(color.black, 160))
if barstate.islast {
    table.cell(t, 0, 0, "RSI", text_color = color.white)
    table.cell(t, 1, 0, str.tostring(math.round(ta.rsi(close, 14), 1)), text_color = color.white)
    table.cell(t, 0, 1, "ATR", text_color = color.white)
    table.cell(t, 1, 1, str.tostring(math.round(ta.atr(14), 2)), text_color = color.white)
}

A table has no more than 200 columns and 200 rows. A table with more than 2000 cells is not created.

Colors

Named 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 can also be written as a code: #FF8800 — opaque, #FF880040 — with transparency. The last pair of digits sets opacity: 00 — fully transparent, FF — solid.

  • color.rgb(r, g, b) builds a color from components from 0 to 255. The fourth argument is opacity, default 255.
  • color.from_gradient(value, bottomValue, topValue, bottomColor, topColor) returns a color between the two extremes based on the position of value in the range. Handy for coloring an oscillator from cool to hot.
  • na in place of a color means “do not draw”.
Loot
indicator("RSI в цвете")

r = ta.rsi(close, 14)
heat = color.from_gradient(r, 30, 70, color.rgb(0, 150, 136), color.rgb(244, 67, 54))

plot(r, "RSI", color = heat, linewidth = 2)
bgcolor(r > 70 ? color.new(color.red, 30) : r < 30 ? color.new(color.teal, 30) : na, title = "Зоны")

Next

https://docs.lootx.trade/en/loot/inputs-drawing

Основы

6Market data: footprint clusters, delta, open interest, order book

What a LootScript script can read besides candles: footprint clusters, delta, open interest, funding rate, recorded and live order book, time and sales, screener, other timeframes and instruments.

Besides candles, a LootScript script reads order flow data: footprint clusters, delta, open interest, funding rate, recorded order book history, live order book and time and sales, and screener metrics. You don’t need to enable anything: as soon as the script accesses, say, cluster.poc, the terminal subscribes to clusters for the chart’s instrument and timeframe — even if the chart shows regular candles. When the script is removed from the chart, the subscription is released.

This page covers what’s in each namespace, where the data comes from, which exchanges have it, and how to access values from another timeframe or instrument.

The main rule: no data means na, not 0

Any value on this page can be na. This happens when the exchange isn’t covered by the server, the timeframe isn’t supported, history is still loading, or the bar is older than the available history. Zero would mean “no trades happened”, which is a different fact: an accumulated sum with zeroes filled in looks plausible but is wrong.

Every namespace has an availability flag — cluster.available, delta.available, oi.available, and so on. Check it or use the na(x) function. Comparing to na with == won’t compile.

Loot
indicator("Accumulated delta without zero substitution", overlay = false)
var float cvd = 0.0
if delta.available {
    cvd := cvd + delta.value
}
plot(delta.available ? cvd : na, "CVD", color = color.teal)

The chart legend next to the script name hints why data is missing: “venue not covered”, “timeframe not supported”, “data loading…”, “no open order book”, “screener unavailable”.

Where each thing comes from

Namespace What it is History on chart
cluster.* Footprint clusters of a bar: volume by price Yes, from the cluster server
delta.* Delta of aggressive buys and sells Yes
oi.* Open interest Yes
funding.* Funding rate and its calculations Yes
depth.* Order book recorded by the server, per bar Yes, limited depth
book.* Live order book Last bar only
tape.* Live time and sales of trades Last bar only
screener.* Screener metrics for the instrument Last bar only

Clusters: cluster.*

Volume at each price level inside a bar, split into aggressive buys and sells — the same data drawn by the footprint chart. Levels are numbered from bottom to top, from 0 to cluster.levels - 1.

Name Returns
cluster.available Whether clusters are available on this bar
cluster.levels Number of price levels in the bar
cluster.price(i) Price of level i
cluster.bid(i) Aggressive buys at level i
cluster.ask(i) Aggressive sells at level i
cluster.total Total volume of the bar
cluster.delta Buys minus sells across all levels
cluster.poc, cluster.poc_index Price and index of the level with the highest volume
cluster.max_cell Volume of the largest cell in the bar
cluster.imbalance(i) Level skew: +1 buys, -1 sells, 0 none
cluster.stacked_buy, cluster.stacked_sell Price where the longest run of skewed levels starts
cluster.stacked_buy_steps, cluster.stacked_sell_steps Length of that run in levels
cluster.value_area(pct) Lower and upper bounds of the value area; pct is the share of volume, 0.7 = 70%
cluster.grid_step Price grid step of the bar

Note the names: cluster.bid(i) is the buys that “lifted” the ask, not resting buy orders in the order book.

Clusters are available on timeframes from 30 seconds to one day.

Loot
indicator("POC and value area", overlay = true)
[vaLow, vaHigh] = cluster.value_area(0.7)
plot(cluster.poc, "POC", color = color.orange, style = plot.style_circles)
plot(vaHigh, "Area high", color = color.gray, style = plot.style_linebr)
plot(vaLow, "Area low", color = color.gray, style = plot.style_linebr)

Delta: delta.*

Difference between aggressive buys and sells for a bar. Volume is in coins (base currency).

Name Returns
delta.value Bar delta: buys minus sells
delta.buy, delta.sell The two components separately
delta.cum Cumulative delta from the start of loaded history
delta.min, delta.max Minimum and maximum of running delta within the bar
delta.open, delta.high, delta.low, delta.close Bar delta as a candle
delta.trades Number of trades in the bar
delta.usd Delta in quote currency, based on actual trade amounts
delta.available Whether delta is available on this bar

delta.min and delta.max can’t be computed from clusters — that’s the intra-bar delta path, calculated by the server. They show that buyers led the bar, but sellers closed it. delta.usd is more precise than delta.value * close: on a sharp bar, trade prices differ significantly from the close.

delta.cum starts at zero on the first loaded bar, so its level depends on the depth of loaded history. Compare changes, not absolute values.

Delta is available on timeframes from 30 seconds.

Loot
indicator("Delta and intra-bar reversal", overlay = false)
d = delta.value
reversed = delta.available and d < 0 and delta.max > -d
plot(d, "Delta", style = plot.style_columns, color = d >= 0 ? color.teal : color.red)
plotshape(reversed, "Reversal", style = shape.xcross, location = location.top, color = color.orange, size = size.tiny)

Open interest: oi.*

Name Returns
oi.open, oi.high, oi.low, oi.close Open interest for the bar in the units the exchange publishes
oi.coins Open interest in coins
oi.usd Open interest in quote currency
oi.change Change in oi.close from the previous bar
oi.available Whether data is available on this bar

Units of oi.open…oi.close differ across exchanges, so for cross-exchange comparisons use oi.coins or oi.usd. Open interest comes on a minute grid: on second-based timeframes all values are na.

Loot
indicator("Price and open interest", overlay = false)
dp = ta.change(close)
build = oi.available and dp > 0 and oi.change > 0
plot(oi.change, "OI change", style = plot.style_columns, color = build ? color.teal : color.gray)

Funding rate: funding.*

Name Returns
funding.rate Predicted rate for the next settlement
funding.interval_hours Hours between settlements
funding.settled true on the bar where settlement occurred
funding.settled_rate Rate actually charged on this bar; if there are multiple settlements in a bar, their sum
funding.cum Sum of charged rates over loaded history
funding.available Whether the instrument has funding

The rate is a fraction, not percent: 0.0001 means 0.01%. The chart shows percent; scripts don’t convert. For backtesting, use funding.settled_rate: funding.rate is a prediction and changes until settlement. Spot has no funding, and on second-based timeframes values are na.

Loot
indicator("Funding per settlement, %", overlay = false)
plot(funding.rate * 100, "Rate prediction", style = plot.style_area, color = funding.rate >= 0 ? color.teal : color.red)
plotshape(funding.settled, "Settlement", style = shape.circle, location = location.bottom, color = color.orange, size = size.tiny)

Recorded order book: depth.*

The order book as the server recorded it — the same data drawn by the heatmap — laid out per bar. Unlike live book.*, these values exist on every recorded bar. Prices are grouped into buckets; each bucket’s volume is the maximum during the bar, in coins.

Name Returns
depth.available Whether the order book is recorded for this bar
depth.levels Number of non-empty buckets in the bar
depth.price(i) Lower bound of bucket i, ascending
depth.qty(i) Maximum volume resting in the bucket during the bar
depth.side(i) +1 bids, -1 asks, 0 bucket was on both sides
depth.at(price) Volume in the bucket at that price
depth.grid_step Bucket size in price units
depth.best_bid, depth.best_ask Best prices at bar close
depth.max_cell Volume of the heaviest bucket
depth.bid_sum(pct), depth.ask_sum(pct) Side volume within pct% from mid
depth.imbalance(pct) Skew in the same band: from -1 to +1
depth.max_bid(pct), depth.max_ask(pct) Price and volume of the heaviest bucket on each side within the band

Limitations:

  • Data is available where the server-side heatmap is, and on timeframes from one second.
  • The server stores a band of about ±4% from price. Outside it depth.at returns na; inside the band an empty bucket is 0.
  • History depth is limited: the oldest bars of a long history return na.
  • Values for the forming bar change as data arrives.
Loot
indicator("Recorded order book skew", overlay = false)
band = input.float(1.0, "Band, % of price", minval = 0.1, maxval = 4.0, step = 0.1)
imb = depth.imbalance(band)
plot(imb, "Skew", style = plot.style_columns, color = imb >= 0 ? color.teal : color.red)

To draw the recorded order book under candles, one line heatmap.depth() in a script with overlay = true is enough. Colors and field thresholds are on the Inputs and drawing page.

Loot
indicator("Recorded order book as heat", overlay = true)
heatmap.config(palette = heatmap.inferno, low = 25)
heatmap.depth()

Live order book and time and sales: book.* and tape.*

Live order book and time and sales are not recorded, so values exist only on the last bar and are always na on history. They require an open order book panel for the same instrument: otherwise book.available and tape.available are false and the legend shows “no open order book”. In replay mode these data are unavailable.

Name Returns
book.bid(i), book.ask(i) Price of level i; 0 is best price
book.bid_qty(i), book.ask_qty(i) Volume at the level, in coins
book.spread Best ask minus best bid
book.mid Midpoint between best prices
book.imbalance(n) Volume skew across the top n levels of each side: from -1 to +1
book.available Whether an order book snapshot is available
tape.last_price, tape.last_qty Price and volume of the last trade
tape.last_side +1 aggressive buyer, -1 aggressive seller, 0 no trades yet
tape.count(ms) Number of trades in the last ms milliseconds
tape.buy_volume(ms), tape.sell_volume(ms) Aggressive buy and sell volume over the window
tape.max_print(ms) Largest trade in the window
tape.available Whether the time and sales feed is connected

The time and sales window and book.imbalance depth are set as numbers in code or via an input.int setting. The window counts from the last trade time on the exchange, not from the computer clock. The script only sees the tail of the time and sales — about the last two thousand trades, so on an active market a long window won’t cover the whole interval.

When such a value is used in plot, the editor warns: “Data is available only in real time — the series is empty on history”. This is expected: to the left of the last bar the series is empty. Strategies cannot read these data — see Strategies and tester.

Loot
indicator("Order book skew", overlay = false)
levels = input.int(20, "Levels per side", minval = 1, maxval = 200)
imb = book.available ? book.imbalance(levels) : na
plot(imb, "Skew", style = plot.style_area, color = imb >= 0 ? color.teal : color.red)
hline(0, "Zero", color = color.gray)

Screener: screener.*

screener metrics for the chart’s instrument — the same numbers as in its columns. There is no history: a value exists only on the last bar. The window is a string, and not every metric has every window.

Function Shows Windows
screener.change(w) Price change "1m" "5m" "15m" "1h" "24h"
screener.vol(w) Turnover "1m" "5m" "15m" "1h" "24h"
screener.avg_vol(w) Average turnover "1m" "5m" "15m" "1h"
screener.rvol(w) Relative volume "1h" "24h"
screener.natr(w) NATR "1m" "5m"
screener.oi_delta(w) Open interest change "1m" "5m" "1h" "24h"
screener.btc_corr(w) Correlation with BTC "1m" "5m"
screener.available Whether the instrument is covered by the screener —

A window not listed in the table returns na. A metric not included in your screener subscription also returns na. The editor marks output of these values with the same warning as for the order book: the series is empty on history.

Loot
indicator("Screener: RVOL and NATR", overlay = false)
plot(screener.rvol("1h"), "RVOL 1h", color = color.orange)
plot(screener.natr("5m"), "NATR 5m", color = color.teal)

Exchange coverage

Exchange Clusters and delta Open interest and funding
Binance, Bybit, OKX, Bitget, Gate.io, MEXC, KuCoin, BingX, AsterDEX Spot and futures Futures
Hyperliquid Futures; no spot Futures
Binance Alpha No: exchange doesn’t publish aggressor side No
Upbit No No
Data Timeframes
Clusters 30 seconds to 1 day
Delta 30 seconds and up
Open interest, funding 1 minute and up
Recorded order book 1 second and up, where server-side heatmap is available
Live order book, time and sales Any, with an open order book panel
Screener Any, for instruments the screener sees

Coverage is determined by the data server and may change. The most reliable approach is to rely on the .available flag and the legend caption.

Another timeframe and another instrument

request.security evaluates an expression on another series — a higher timeframe or another coin — and maps the result to the chart’s bars.

TEXT
request.security(symbol, timeframe, expression, gaps = false, lookahead = false, ignore_invalid_symbol = false)
  • symbol — in “EXCHANGE:TICKER” format, as in TradingView: "BINANCE:BTCUSDT.P", where .P is a perpetual futures contract. The chart’s instrument is sym.ticker.
  • timeframe — a string like "5", "60", "4h", "1D", "1W". The chart’s timeframe is tf.period.
  • expression — one number or multiple numbers in square brackets: [high, low].

No lookahead. By default, a chart bar sees the value of the last closed bar of the higher timeframe. That’s why an hourly EMA on 5-minute bars is a step that only moves when the hour closes. This makes the backtest match what you would have seen live.

  • gaps = true — value appears only on the first chart bar where a new higher-timeframe bar appeared, then na.
  • ignore_invalid_symbol = true — an unknown symbol returns na. Without this, the script stops with the error “Symbol … unknown”.

Inside the expression you can use the other series’ candles and calculations on them. You cannot pass a chart variable there — only values from input.* settings. The order book, time and sales, and screener don’t compile inside the request, and clusters, delta, open interest, and funding for another series return na. A script can have up to 8 different “instrument + timeframe” pairs and up to 32 request.security calls.

Loot
indicator("Higher-timeframe EMA", overlay = true)
len = input.int(20, "EMA length", minval = 2, maxval = 500)
tfHigh = input.timeframe("60", "Higher timeframe")
emaHigh = request.security(sym.ticker, tfHigh, ta.ema(close, len))
plot(emaHigh, "EMA", color = color.orange, style = plot.style_stepline)
Loot
indicator("Spread to another exchange", overlay = false)
other = input.symbol("BYBIT:BTCUSDT.P", "Compare to")
px = request.security(other, tf.period, close, ignore_invalid_symbol = true)
plot(close - px, "Difference", color = color.orange)

Next

https://docs.lootx.trade/en/loot/market-data

Основы

7Strategies and the Tester

How to write a strategy in LootScript and verify it on historical data with the tester: declaring strategy(), orders, the fill model, costs, report tabs and backtest limits.

A strategy is a script that, besides drawing lines on the chart, submits orders. Orders are not executed by an exchange but by a simulator inside the terminal: it runs the strategy over chart history with commissions, slippage and funding rate, and shows the result in the Strategy Tester window.

Declaring strategy()

A strategy is distinguished from an indicator by the first line: strategy(...) instead of indicator(...). Everything else — settings, drawing, market data — works the same. strategy.* functions in an indicator do not compile: “strategy.* is available only in strategy(…)”.

Parameter Default What it sets
initialCapital 10000 Starting capital
defaultQtyType, defaultQtyValue strategy.qty.fixed, 1 Order size when qty is not specified
commissionType, commissionValue percent, none Commission: strategy.commission.percent — percent of turnover (0.05 = 0.05 %), strategy.commission.cash_per_contract — cash per unit, strategy.commission.cash_per_order — cash per execution
slippageTicks 0 Slippage in ticks
pyramiding 0 How many entries in the same direction can be open; 0 — one
positionModel strategy.model.netting Single net position or separate long and short (strategy.model.hedging)
processOrdersOnClose false Execute market orders on the current bar close
calcOnEveryTick false Allow orders on the forming bar
marginLong, marginShort, leverage 0, 0, 1 Margin in percent or leverage; at 0 liquidation is not modelled
applyFunding true Apply funding rate
fillModel strategy.fill.conservative Assumption about price path inside a bar

Parameter values must be numbers or constants written directly. An expression or input.* inside the declaration is a compilation error. The parameter calcOnOrderFills is accepted but inactive in this release: on the tester’s “Properties” tab it is marked “inactive in this build”.

Order size when qty = na is determined by defaultQtyType:

Type What defaultQtyValue means
strategy.qty.fixed Quantity in coins (base currency)
strategy.qty.cash Amount in quote currency
strategy.qty.percent_of_equity Percent of current equity
strategy.qty.risk_percent Percent of equity you risk up to a protective stop

strategy.qty.risk_percent requires a strategy.exit with a stop (loss or stop), otherwise the compiler stops with: “requires a stop to calculate size”. Quantity is rounded down to the instrument’s quantity increment. If rounding yields zero, the order is rejected and counts toward the tester counter “Rejected orders (size)”.

Orders

Function What it does
strategy.entry(id, direction, qty, limit, stop, …) Opens a position or reverses it. Respects the position model and pyramiding
strategy.order(id, direction, qty, limit, stop, …) Same without position model and pyramiding
strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_price, trail_points, trail_offset, …) Places an exit — take, stop or trailing — for an open entry
strategy.close(id, comment, qty, qty_percent) Closes an entry with a market order
strategy.close_all(comment) Closes everything
strategy.cancel(id), strategy.cancel_all() Cancels unfilled orders

Direction is strategy.long or strategy.short. All functions accept an optional when: when = false skips the call. Entries, exits and closes also accept comment — a text label attached to the order.

  • Type of entry. Without limit and stop — a market order; with limit — a limit order; with stop — a stop order; with both — a stop-limit. Re-submitting strategy.entry with the same id replaces an unfilled order.
  • Reversal. In netting model an entry in the opposite direction closes the current position and opens a new one in a single action.
  • Exit units. profit and loss are in ticks from the entry price; limit and stop are absolute prices. Trailing is specified as a pair: trail_offset plus trail_price or trail_points.
  • An exit with no levels does nothing. The compiler warns: “strategy.exit without any level (profit/loss/stop/limit/trail) — no-op”.
  • Moving a stop. Re-submitting strategy.exit with the same id replaces the exit — that’s how stops are moved.

Strategy state is read via fields: strategy.position_size (signed; short is negative), strategy.position_avg_price, strategy.equity, strategy.netprofit, strategy.openprofit, strategy.opentrades, strategy.closedtrades, strategy.funding_paid and others — full list in the reference.

How the tester fills orders

An order submitted on a bar cannot execute earlier than the next bar. Decisions are made at bar close, and filling at the same price would imply peeking forward.

Order Execution
Market At the open of the next bar plus slippage. With processOrdersOnClose = true — at the current bar close
Limit When price reaches the limit, at the limit price. If the bar opened beyond the limit — at the open
Stop When price reaches the stop, at the stop price plus slippage. On a gap — at the open plus slippage

Price path inside the bar. The tester does not know the real intra-bar path and assumes one. The strategy.fill.conservative model (default) assumes price first reached the worst extreme: on a bullish bar — open → low → high → close; on a bearish bar — the reverse. If a stop and a take occur within the same bar, the stop fires. The strategy.fill.optimistic model assumes the opposite — useful only for comparison. There is no lower-timeframe replay in this release: the “Path” column marks each trade as assumed by the model.

Costs.

  • Commission. If commissionValue is not set, the tester uses a default tariff: 0.02% for limit fills and 0.05% for market and stop fills. Your account tariff and any rebates to the terminal are unknown. A configured number applies to all fills.
  • Slippage — slippageTicks against you on market and stop fills. Limit fills do not slip.
  • Funding rate is charged at every real exchange settlement — using the actual funding rate and the bar close price for the settlement. This requires funding data: futures funding on exchanges from the coverage table.
  • Margin. With marginLong/marginShort or leverage > 1 the tester models a simplified isolated margin. A long position liquidates at entry × (1 − m/2), a short at entry × (1 + m/2), where m is the fraction of initial margin. A liquidated trade loses the entire initial margin.

Trades not closed by the end of history are closed at the final bar close with reason “end of data”.

Strategy Tester

Add the strategy to the chart

In the script Editor press Add to chart (Ctrl+Enter). A script with errors will not be added to the chart.

Open the tester

In the Editor toolbar press Strategy Tester… — the button is active only for a script with strategy(...). The alternative path is strategy settings from the indicator legend (gear), button Strategy Tester….

Wait for the run

The tester computes on the candles loaded on the chart. While there are no candles the window shows “Strategy has not been run yet: wait for candles to load”. When new candles arrive the result recalculates automatically; the Recalculate button runs a full pass manually.

If multiple strategies are on the chart, pick the one you want directly in the tester window.

Tab What’s on it
Summary Tiles “Net profit”, “Profit factor”, “Max. drawdown (by closes)”, “Percent profitable”, “SQN”; a strip “What this backtest doesn’t know”; equity curves, buy-and-hold, equity without funding and two drawdowns
Metrics Results, risk (drawdown by closes and intra-bar separately, Sharpe, Sortino, Calmar), trades (percent profitable, averages and largest, run lengths), costs (commission and funding)
Trades Trades table: entry, exit, reason, size, P&L, run-up, drawdown, commission, funding. Click a row to scroll the chart to the entry bar, Ctrl+C copies selected rows
Properties Declaration parameters, bar range, price step, quantity step, minimum lot, commission, run counters: rejected orders, skipped due to pyramiding, liquidations, funding settlements

The window title shows mode tags: conservative or optimistic for the fill model and close-fill when processOrdersOnClose = true. Tags optimistic and close-fill mean the live result will most likely be worse.

What a strategy cannot read

Live order book and time and sales. A strategy that reads book.* or tape.* does not compile: “Strategy reads … order book and time and sales have no history, the backtest would be fiction”. For book history use depth.*, for trades use delta.* and cluster.*.

Screener. screener.* is also only available on the latest bar, but the compiler allows such a strategy. On history screener values are na, so conditions on them never fire and there will be no trades in the report.

Peeking forward. request.security(..., lookahead = true) in a strategy shows a warning in the Editor: “Strategy peeks forward … report marked as unreachable in real time”. Treat such a report as inflated: on history the strategy sees values that would not exist live. More in Market data.

Example

A channel breakout confirmed by delta. Entry on close outside the channel over the last len bars if the bar delta is in the same direction. Stop in ATR, take twice as far.

Loot
strategy("Пробой канала с дельтой", overlay = true,
         initialCapital = 10000,
         defaultQtyType = strategy.qty.percent_of_equity, defaultQtyValue = 20,
         commissionValue = 0.05, slippageTicks = 2)

len      = input.int(20, "Канал, баров", minval = 5, maxval = 200)
stopAtr  = input.float(1.5, "Стоп, ATR", minval = 0.5, maxval = 10, step = 0.1)
needFlow = input.bool(true, "Подтверждать дельтой")

upper = ta.highest(high, len)[1]
lower = ta.lowest(low, len)[1]
atr   = ta.atr(14)

flowLong  = not needFlow or (delta.available and delta.value > 0)
flowShort = not needFlow or (delta.available and delta.value < 0)

if close > upper and flowLong and strategy.position_size <= 0 {
    strategy.entry("L", strategy.long, comment = "пробой вверх")
}
if close < lower and flowShort and strategy.position_size >= 0 {
    strategy.entry("S", strategy.short, comment = "пробой вниз")
}

stopTicks = math.round(atr * stopAtr / sym.tick_size)
strategy.exit("L-x", from_entry = "L", loss = stopTicks, profit = stopTicks * 2)
strategy.exit("S-x", from_entry = "S", loss = stopTicks, profit = stopTicks * 2)

plot(upper, "Верх канала", color = color.teal)
plot(lower, "Низ канала", color = color.red)

On an exchange without delta (for example, Binance Alpha) with “Подтверждать дельтой” enabled the strategy will make no trades: delta.available is false there. This is na at work, not an error.

Limitations

  • Simulation only: no real orders.
  • Limit orders execute as if you were first in queue. For maker strategies this is the main source of inflated results.
  • Your trades do not move price; no partial fills: an order either fills entirely or not at all.
  • The intra-bar price path is assumed by a model, not reconstructed from a lower timeframe.
  • Liquidation is simplified: the exchange’s liquidation engine, ADL and insurance fund are not modelled.
  • Commission is the default tariff, not your account tariff.
  • Missing data is not missing movement: a bar without clusters still moved.
  • Results depend on how much history is loaded on the chart.

Next

https://docs.lootx.trade/en/loot/strategies

Основы

8Script alerts

How a LootScript script reports a trigger: alert() and alertcondition(), frequency, arming, where alerts are delivered, and what script alerts don't support.

A script can tell you that a condition occurred on the live market: a breakout, a delta spike, a line crossover. LootScript provides two functions for that — alert(), which the script calls itself, and alertcondition(), a condition you enable manually.

A trigger enters the same pipeline as the terminal’s other notifications: an entry in the Alerts tape, a sound, and a popup card. All of this is handled locally in the terminal on your computer: alerts work only while the terminal runs and the script is on the chart.

Two ways

alert() alertcondition()
Who decides whether to ring Script code You: the condition must be armed
When it triggers By the chosen frequency, including on an unclosed bar Only on bar close, not more than once per bar
Text Any string, can be built from numbers Fixed text in code
Where it’s enabled Always while the script is on the chart Checkbox in the Editor console

If an alert is needed always — use alert(). If a script declares several signals but only some should ring — declare them with alertcondition() and arm the ones you want.

alert(): alert from code

TEXT
alert(message, freq = alert.freq_once_per_bar_close)

message — a string. Insert numbers via str.tostring: "Цена " + str.tostring(close). The text arrives in the notification verbatim; the terminal does not translate or alter it.

Frequency is set by a constant:

Frequency When it rings
alert.freq_once_per_bar_close Default. Once, when the bar closed: on the first update of the next bar, using the closed bar’s values
alert.freq_once_per_bar At the first moment the call ran on that bar — even if the bar is still forming. Then silent until the next bar
alert.freq_all On every recalculation of the live bar where the call ran

Frequency is tracked for each alert() call separately: two calls in one script do not mute each other. Per single recalculation a script sends up to 16 alerts; the rest are dropped.

Example: an alert on a delta spike as soon as it appears on a forming bar.

Loot
indicator("Всплеск дельты", overlay = false)
mult = input.float(3.0, "Во сколько раз больше обычного", minval = 1.5, step = 0.5)
base = ta.sma(math.abs(delta.value), 50)
spike = delta.available and math.abs(delta.value) > base * mult
plot(delta.value, "Дельта", style = plot.style_columns, color = delta.value >= 0 ? color.teal : color.red)
if spike {
    alert("Всплеск дельты: " + str.tostring(delta.value, "#.##"), freq = alert.freq_once_per_bar)
}

Where delta is unavailable, delta.available is false and the alert is silent — see Market data for the rule about na.

alertcondition(): a condition you arm

TEXT
alertcondition(condition, title, message)

condition — a boolean expression, title — the condition’s name, message — the alert text. title and message are literals in code; you cannot build them from numbers. Without message the notification will contain title.

The condition rings only on bar close, not more than once per bar and only if it is armed. Conditions are off by default.

Add the script to the chart

In the Script Editor click Add to chart.

Open the Output tab

In the console under the code select the Output tab. It shows series values on the last bar and the list “Alert conditions (alertcondition) — arm the ones you need”.

Arm the conditions

Check the boxes for the conditions you want notifications for. If the script is on multiple charts each chart has its own list.

History is silent

Alerts only ring on live updates. The first calculation after loading the chart, after switching instruments, or after loading older history is considered history: neither alert() nor alertcondition() fire on past bars. So adding a script to a chart will not produce a batch of notifications for the past.

You can check a condition on history visually: draw its marker with plotshape — it will show every bar where the alert would have fired.

Where an alert goes

Each trigger:

  • Is recorded in the Alerts tape with source “Script alert”. The entry contains the message text, the script name and, for alertcondition(), the condition title. The tape opens in a separate window or a workspace panel; the Sources filter leaves only script alerts.
  • Plays a sound. It is selected in Settings → Alerts, the Sounds block, the “Script alert” line: a list of sounds and a toggle that mutes the sound.
  • Shows a card “Script name: message”.
  • Highlights the workspace tab that contains the chart with the script.

Other terminal notifications are described on the Alerts and levels page.

Log: log.*

There is a log for debugging conditions. log.info, log.warning and log.error write a line to the Log tab of the Script Editor console — the same area that shows Problems and Output.

  • The log, like alerts, writes only on live updates — it is silent on history.
  • Up to 16 lines per bar; the rest are dropped.
  • The console keeps the last 256 lines. Older lines are pushed out; their count is shown as “lines pushed out”. The Clear button clears the log.
Loot
indicator("Проверка условия", overlay = true)
len = input.int(20, "Канал, баров", minval = 2, maxval = 500)
upper = ta.highest(high, len)[1]
plot(upper, "Верх канала", color = color.teal)
if barstate.islast {
    log.info("Закрытие " + str.tostring(close) + ", верх канала " + str.tostring(upper))
}

Example: channel breakout

The script draws the channel upper boundary, marks breakouts with a triangle and reports them in two ways: alert() rings always, while the condition “Breakout up” rings only if you armed it.

Loot
indicator("Пробой канала с алертом", overlay = true)
len = input.int(20, "Канал, баров", minval = 2, maxval = 500)
upper = ta.highest(high, len)[1]
breakUp = ta.crossover(close, upper)
plot(upper, "Верх канала", color = color.teal)
plotshape(breakUp, "Пробой", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small)
if breakUp {
    alert("Пробой вверх, цена " + str.tostring(close), alert.freq_once_per_bar_close)
}
alertcondition(breakUp, "Пробой вверх", "Цена закрылась выше канала")

The boundary uses a [1] offset — from previous bars; otherwise the current high would always be inside the channel. freq_once_per_bar_close means the alert arrives after the bar closed above the channel, and the triangle on the chart stays exactly where the alert rang. In real scripts you usually keep one of the two methods — both are shown here for comparison.

Next

https://docs.lootx.trade/en/loot/alerts

Основы

9AI Assistant in the Editor

Chat with an AI model inside the LootScript editor: it writes and edits scripts, runs them on candles, answers market questions. Which providers are supported, where to enter your key, and what is sent from your computer.

The LootScript editor includes a chat with an AI model. Describe in words the indicator you need — the assistant will write the code directly in the editor, compile it, run it on real candles and report the results. It also edits existing scripts, explains other people’s code and answers market questions using terminal data.

You choose the model yourself: cloud — with your API key, or local — running on your machine. Requests go from the terminal directly to the chosen provider, without passing through LootX servers.

How to open the assistant

  1. Click ƒ on the chart panel — the Indicators window opens.
  2. Click Editor… next to the search box, or open your script.
  3. In the editor’s top bar, next to Add to chart, click Assistant.

The chat docks to the right of the code. Resize its width by dragging the divider. The X in the chat header (Hide chat) closes it without deleting the conversation; clicking Assistant again reopens it.

Connecting a model

Open the connection card

On first use the card opens automatically. Later open it via the gear Key and connection in the chat header.

Choose a provider

The list is in the table below. Claude is selected by default.

Paste your API key

There’s a link under the field Get key on … — it goes to the provider dashboard. A saved key is not shown in the field: leave it empty to keep the existing key, or click Delete key.

Check the model and save

The Model field is prefilled with a default; hints list a few more. Enter any model name the provider recognises. Click Save.

Provider What you need
Claude Anthropic API key. A Claude subscription does not work — Anthropic forbids third-party apps from using it.
Gemini Google API key. A Gemini subscription does not work for the same reason.
OpenAI, DeepSeek, Grok, Mistral, Qwen, Kimi, GLM, Groq Provider API key.
OpenRouter OpenRouter key: gives access to models from different companies.
Ollama, LM Studio No key required: the model runs on your computer. Start the server, load the model and enter its name.
OpenAI-compatible Any server with an OpenAI Chat Completions-style API: a gateway, vLLM, corporate proxy. Provide the address (usually ending in /v1), model and key if required.

Cloud requests are billed according to your account with the provider, separate from LootX. After each chat reply you’ll see how many tokens were used for input and output.

A local model must support tool calling. Without tool calling the assistant cannot write into the editor or run checks.

Proxy and your own address

If a provider’s service is unreachable from your network, enter a proxy in the Proxy field — http://host:port or socks5://login:password@host:port. The proxy is shared across providers. The API Address (for your gateway) field is needed only if you access the provider via your own gateway.

What the assistant can do

  • Write a new script from a description and place the code in the editor immediately.
  • Edit an existing script — targeted edits without rewriting the whole file.
  • Self-check. Compiles code and runs it on real candles — by default on the instrument and timeframe of the chart, up to the last 5000 bars; on request it can run on any other. It inspects outputs per row and looks for runtime errors.
  • Add the script to the chart when you ask.
  • Answer market questions. It takes candles for any instrument from the terminal, screener metrics (volatility, volume, open interest, funding rate, spread) and ranks the market: “Which futures are the most volatile right now?”
  • Cross-check the language reference, looks at Built-in indicators and scripts from your library.

Each step is shown in the time and sales as a line: “Compiling”, “Running on candles”, “Editing code”. If the model displays its reasoning, it is folded in a Chain of thought block. You can interrupt a reply with the Stop button.

Everything the assistant writes in the editor is undoable with the usual Ctrl+Z. If code arrives as a block it has buttons in its header. For a whole script this is To editor — replace the editor code; for a fragment it’s Insert at the cursor. Both have Copy.

Quick commands

Type / in the input field — a hint appears. The same commands are available as buttons in an empty chat. Text after the command is your clarification: /fix look at volume.

Command What it does
/fix Finds and fixes errors: compiles, runs on candles, repairs errors and rows that are all na. Preserves your intent and style, and lists the fixes at the end.
/explain Explains in plain words what the script does, what each setting affects, what it draws and how to read the signals. Does not change code.
/optimize Speeds up the script without changing results: replaces custom loops with built-ins, removes redundant work and verifies by running that values are unchanged.

Any other word after the slash is sent to the model as a normal question.

Images and chart snapshots

Attach an image to your question via the paperclip under the input field, paste from the clipboard (Ctrl+V) or drag a file into the chat. The chart button next to the paperclip attaches a snapshot of the panel where the script will be added. Up to six images per question. Large images are downscaled before sending.

Not all models see images. If the selected model can’t see images the chat warns you before sending. If the terminal cannot determine whether the model sees images and the provider rejects the request, the images are returned to the input field.

Conversation history

A conversation is tied to a script. Open another script — the chat for that script appears. Close the editor or restart the terminal — the conversation remains.

  • A new, unsaved script’s conversation is not written to disk. It is saved with the script on first Save.
  • The New chat icon in the header starts a new conversation and deletes the previous one from disk.
  • Deleting a script deletes its conversation.
  • While the assistant is replying you cannot open a different script: stop the reply first.

The entire conversation is sent to the model with each question, so a long chat increases cost. The conversation size in tokens is shown as a number in the chat header, e.g. “42k”. Click it to compress the conversation into a summary: the assistant will remember the chat by that summary from then on. Old test results and images are collapsed automatically. In saved history older images are eventually replaced with the note “Image for this question is no longer stored”.

What is sent from your computer

Sent directly to the chosen provider:

  • your messages and attached images;
  • the script name, line count and errors, the chart instrument and timeframe — with each question;
  • code from the editor and compiler reports — when the assistant reads or edits the script;
  • data the assistant requested: candles, screener metrics, run results, fragments of the language documentation.

Not sent:

  • Secrets. The assistant does not see exchange keys. The provider key is stored on this computer encrypted, is not synced with settings and is sent only to the provider — for authentication. The terminal strips from outgoing text anything that looks like a key, token or password, and file paths. A message in which you pasted something that looks like a key is not sent at all — the chat asks you to remove the secret.
  • Account. The assistant has no access to balances, positions or orders — it only sees what you show in a snapshot. It cannot place orders.
  • Chat history. It is stored encrypted on this computer and is not part of settings sync, export or support reports.

With Ollama or LM Studio the conversation and code never leave your computer.

Limitations

  • No streaming data in test runs. Footprint clusters, delta, open interest, funding rate, order book, time and sales, screener and order book history are na when running on candles. The assistant cannot validate logic that relies on them — add the script to the chart and check yourself.
  • Step limit. The assistant performs up to 24 steps per reply, then summarises. A reply cut short by length can be continued — just ask.
  • The model errs. Runs catch compile and runtime errors, but not conceptual mistakes. Before relying on signals, inspect the script on the chart.
  • Provider rejections are shown as text with the provider name: key not accepted, request quota exhausted, out of funds or quota, no connection, local server not responding. Check your internet or set a proxy.

Next

https://docs.lootx.trade/en/loot/ai-assistant

Основы

10Import from Pine Script

How to move an indicator from Pine Script to LootScript: where the import button is, what the converter changes automatically, what it flags for review and how to finish the result.

If an indicator is already written in Pine Script, you don’t have to rewrite it by hand. The terminal converts a .pine file to LootScript: it changes syntax and names, adds missing pieces and writes notes at the top of the file — what was changed and where the converter had to guess.

The converter is a translator, not a compatibility layer. It does not guarantee identical numeric results to the original environment, and it does not add terminal features that don’t exist. After import, open the script, read the notes and verify it on a chart. LootScript was developed independently and is not affiliated with TradingView: the syntax is intentionally similar, but the languages are not compatible.

How to import

Open the Indicators window

Click ƒ on the chart panel — the Indicators window will open.

Click “Import…”

The button sits next to the search field. Choose a .pine, .loot or .txt file. A .loot file is added to the library as-is. A .pine file — a text file resembling Pine Script — is fed through the converter.

Read the result

One of the following lines will appear under the search field:

  • “Imported ‘…’ — no notes; the script is ready.”;
  • “Imported ‘…’: converter notes — N, see the script header”;
  • “Imported ‘…’, but the script does not compile (errors: N)…” — the first error is shown next to the message.

The window will switch to the My scripts section and the search field will be filled with the new script’s name.

Open the script in the Editor

Read the header with notes and fix the items it points out. How — below.

Import does not overwrite a script with the same name: the new file gets a suffix, for example -2. The original file is not changed.

Via the scripts folder

You can also drop name.pine into the scripts folder — on Windows that’s %APPDATA%\TradingTerminal\scripts. On next launch the terminal will create name.loot next to it. If name.loot already exists it is left alone — your edits won’t be lost. To re-convert (for example after a terminal update) delete the .loot.

What the converter does

  • Indentation → braces. if, else if, else, loop and function blocks get braces. Line continuations are merged into one line.
  • Functions. f(x) => becomes func f(x), and the function’s final expression is turned into an explicit return.
  • Loops. Inclusive for i = 0 to 9 becomes half-open for i in 0 .. 10. Direction is taken from the step or from literal bounds; if it’s not visible the converter assumes an ascending loop and notes that.
  • Conditional expressions. if with single-expression branches becomes a ternary operator; switch gets braces.
  • Transparency → alpha. In Pine Script transparency runs 0…100 where 0 is opaque. In LootScript alpha runs 0…255 where 255 is opaque. color.new(c, 50) becomes color.new(c, 128), and a transp= argument is turned into color.new(…) wrapping the color.
  • Names. Old names without a namespace get one: sma → ta.sma. study → indicator, security → request.security, tostring → str.tostring, syminfo.* → sym.*, timeframe.* → tf.*. Short form input(…) receives a typed form: input.int, input.source, etc.
  • Reserved names. A variable whose name is a LootScript keyword or namespace (delta, oi, tf, sym, func …) gets an underscore appended everywhere it appears: delta → delta_.
  • Extra arguments. Arguments that don’t exist for the function in LootScript are removed.
  • Declaration. If the file lacked indicator(…) or strategy(…), the converter will add indicator using the file name.
  • Comments and blank lines remain in place.

The converter never rejects a file. A line it doesn’t understand is not dropped but left as a comment // [не разобрано] … in the same place.

Header with notes

The first header line states the origin — “Imported from a Pine Script (version 5). Converter notes:”. Then one line per change, in source-line order: “Line N: type: what — details”. Notes are written in the interface language.

Note type What it means Check?
renamed Name replaced by LootScript equivalent no
recomputed Transparency converted to alpha no
rewritten Form changed: loop, return, short input type glance
name “…” is reserved in LootScript An underscore was added to the variable no
indicator(…) declaration was missing Declaration added from the file name no
argument removed The function has no such parameter in LootScript yes
assumption The converter guessed: loop direction, input type that couldn’t be inferred yes
not available in this build That function doesn’t exist in the terminal — the script will not compile with an “unknown name” error yes
not parsed The line couldn’t be parsed and was preserved as a comment yes

When you’ve checked them you can remove the header — it’s just comments.

Example

A small Pine Script indicator: bar range columns highlighted when the range is twice the average.

PINE
//@version=5
indicator("Range spike", overlay=false)
len = input.int(20, "Length")
avgRange(n) =>
    r = high - low
    ta.sma(r, n)
base = avgRange(len)
spike = high - low > base * 2
plot(high - low, style=plot.style_columns, color=spike ? color.orange : color.new(color.gray, 60))
plot(base, color=color.blue, trackprice=true)

This is how the converter writes it:

Loot
// Импортировано из скрипта на Pine Script (версия 5). Заметки конвертера:
//
// Строка 6: переписано: avgRange — неявный возврат последнего оператора записан как return
// Строка 9: пересчитано: transp → alpha — прозрачность 0…100 пересчитана в альфу 0…255
// Строка 10: аргумент снят: plot: trackprice — такого параметра в LootScript нет

indicator("Range spike", overlay = false)
len = input.int(20, "Length")
func avgRange(n) {
    r = high - low
    return ta.sma(r, n)
}
base = avgRange(len)
spike = high - low > base * 2
plot(high - low, color = spike ? color.orange : color.new(color.gray, 102), style = plot.style_columns)
plot(base, color = color.blue)

The function gained braces and return, transparency 60 became alpha 102, and trackprice was removed — that parameter doesn’t exist. The “argument removed” note asks you to check whether the parameter was semantically required. Here it only drew a last-value line, and the script works without it.

How to check and refine

  1. Read the header. Start with lines marked “argument removed”, “assumption”, “not available in this build” and “not parsed”.
  2. Check the “Problems” tab in the Editor console. A script with errors will not be added to a chart.
  3. Add to chart and compare with what the original showed across several historical segments.
  4. Ask the assistant. Open the AI assistant and type /fix — it will compile the script, run it over candles and fix errors. You can add a clarification: /fix parse the converter notes in the header. /explain will describe what the script does.

What is not ported

  • Functions that don’t exist in the terminal. The name stays in the code, the note “not available in this build” and a compiler error point to the same place. Replace the call manually or ask the assistant to suggest an alternative.
  • Multiline strings, importing external libraries, exporting functions. The converter transfers what it can write and flags the rest.
  • More than three plot lines. A chart panel draws only the first three plot calls of a script. Put extra series into separate scripts.
  • Live trading. A strategy(…) declaration is converted, but LootScript strategies trade only in the Strategy Tester — on a simulated account.

Next

https://docs.lootx.trade/en/loot/pine-import

Справочник

11Compilation and runtime errors

All LS codes that the Editor and chart can show: message text, cause and fix, common errors with examples, runtime limits and cases where you get na instead of an error.

Each LootScript compiler and runtime message starts with a code like LS2008. The code is stable across versions and independent of the UI language, so it’s convenient to search by it. This page lists every code the terminal can show, with the message text, the cause and how to fix it.

Messages appear in Russian when the terminal interface is Russian; for any other language they appear in English. First — the most common errors, then runtime errors and a complete table.

Where errors are visible

At compile time. The Editor compiles the script on each typing pause. Findings appear in the “Problems” tab at the bottom of the Editor: code, text and position in the form “Line 6:6”. Double‑clicking a line moves the cursor to the error location. The Editor header shows the result: “ok · 12 ms”, “warnings: 2” or “errors: 1”.

At runtime. A script that compiles cleanly can still stop on a bar: operation budget exhausted, an index went out of bounds, unknown symbol, etc. Then the “Output” tab will show a line like “Script stopped: LS6004: …”, and the same reason appears in the Strategy Tester. Other scripts, panels and the terminal continue to run.

Diagnostics have three levels:

Level What it means What happens on the chart
Error The script failed to build The script is not added to the chart: “Script with errors is not added to the chart — see ‘Problems’.” If the script was already on charts, the previous working version remains
Warning The script built, but the result may be misleading — for example, it will repaint on the live bar The script runs
Notice The script built, but some setting does nothing The script runs

How codes are organised

Codes Stage About
LS0001–LS0009 Text reading Characters, strings, numbers, colors, the #version directive
LS1000–LS1012 Parsing Brackets, blocks, operator order, script declaration
LS2000–LS2030 Types and names Unknown names, types, arguments, na
LS3000–LS3033 Program semantics ta.* in branches, recursion, strategies, libraries, request.security
LS4000–LS4009 Compilation limits Too many series, outputs, calls
LS5000–LS5013 Repainting and test honesty Values that look different on history than live
LS6000–LS6036 Execution Budgets, indices, collections, strings, drawing objects
LS0999 Internal fault A compiler bug — report it

Common compile errors

LS1009 — missing script declaration

“No script declaration — start with indicator("Name")”. The first statement in the file must be indicator(...), strategy(...) or library(...). The same error appears if the declaration exists but something is written above it. Comments and the #version 1 directive do not interfere.

Loot
// Так нельзя: объявление не первое
len = input.int(14, "Длина")
indicator("RSI")
Loot
indicator("RSI")
len = input.int(14, "Длина")

A second declaration in the same file gives LS1008: a script may have only one.

LS2002 — unknown name

“Unknown name ‘…’ — check spelling or declare it earlier.” Most often a typo or a function without its namespace: indicator functions live in ta, math in math, colors in color.

Loot
avg = sma(close, 20)
Loot
avg = ta.sma(close, 20)

The same error occurs if you read a variable before the line where it’s declared. The full list of names is in the Function reference.

LS2008 — comparison with na

“Comparison with na is always false — use na(x)”. Any comparison with na, including == and !=, yields false, so the compiler rejects such expressions.

Loot
x = ta.sma(close, 50)
plot(x == na ? close : x)
Loot
x = ta.sma(close, 50)
plot(na(x) ? close : x)

The shorter equivalent is plot(x ?? close).

LS2014 — value changes bar-to-bar where a constant is required

“‘…’ in ‘…’ requires a value at least as strong as input, but a series was given — use input.*(…) or a literal.” A window length for ta.* must be known before the first bar. A length chosen by a per-bar condition is not acceptable.

Loot
len = close > open ? 10 : 20
avg = ta.sma(close, len)

Compute both options and choose the result, not the length:

Loot
fast = ta.sma(close, 10)
slow = ta.sma(close, 20)
avg  = close > open ? fast : slow

If the length must be user‑selectable, take it from input.int(...).

LS3004 — ta.* call depends on a variable from a branch

“Argument ‘…’ cannot be computed outside the branch — move the ta.* call to the top level.” ta.* functions remember past bars, so the compiler treats them as computed on every bar even if written inside an if. If the argument is declared only inside the branch, on other bars it simply doesn’t exist.

Loot
var float avgBody = na
if close > open {
    body = close - open
    avgBody := ta.sma(body, 10)
}
Loot
body    = close - open
avgBody = ta.sma(body, 10)

LS2017, LS2007, LS1006 — strings, conditions and chained comparisons

These three errors share a cause: LootScript does not coerce types implicitly.

Code Message How to fix
LS2017 “Cannot add string and number (… + …) — use str.tostring(…)” "RSI " + str.tostring(r) instead of "RSI " + r
LS2007 “Condition must be bool, but here is …” if volume > 0 instead of if volume — numbers are not truthy
LS1006 “Comparisons do not chain — write a < b and b < c” low < close and close < high instead of low < close < high

LS2018 and LS2019 — name already taken

“‘…’ already declared in this scope” (LS2018) — you declared the variable a second time with =. To change a value use :=.

Loot
level = high
level := low

“‘…’ shadows a built‑in name — choose another” (LS2019) — a variable, function or type was named the same as a built‑in series or function: close, time, hour, volume. Rename it: startHour instead of hour. Using namespace names like color or position for variables is allowed.

LS2004 and LS2005 — call arguments

“‘…’ expects … argument(s), but … were given” (LS2004) and “‘…’ has no parameter ‘…’” (LS2005). Check the call against the signature in the Function reference: parameter names must be written exactly as shown.

Loot
plot(close, colour = color.red)
Loot
plot(close, color = color.red)

LS3011 and LS5011 — strategies

“strategy.* is available only in strategy(…)” (LS3011): orders and position state exist only for a script declared with strategy(...). Replace indicator("…") with strategy("…").

“Strategy reads ‘…’: book and tape have no history, a backtest would be fictional” (LS5011): a strategy is tested on history, but book.* and tape.* have no history — they are na on past bars.

Loot
strategy("Book imbalance")
if book.imbalance(10) > 0.5 {
    strategy.entry("L", strategy.long)
}

For historical order book data there’s the depth namespace: where the order book is recorded it gives values on each bar.

Loot
strategy("Book imbalance")
if depth.imbalance(1.0) > 0.5 {
    strategy.entry("L", strategy.long)
}

LS5000–LS5006 — repainting warnings

These warnings do not stop the script. They say the line on history will look different from what was seen live:

  • LS5001 — a value that exists only on the live bar reaches output (barstate.isrealtime, barstate.isnew).
  • LS5000 — a varip value reaches output: it accumulates live‑bar ticks that don’t exist on history.
  • LS5006 — book.* or tape.* reach output: the series is empty on history.
  • LS5003 — higher timeframe value from request.security without [1]: the unclosed bar will repaint.
  • LS5002 — lookahead = true in request.security: the script sees the future on history.
  • LS5005 — math.random or timenow reaches output: two runs give different lines.

If that’s intended — e.g. the indicator is meant only for live trading — the warning can be left.

LS3016 — a setting accepted and does nothing

This is a notice, not an error. It appears in scripts ported from other platforms: the parameter exists for compatibility but has no effect in the terminal. The message’s second part explains why.

What is written Explanation in the message
maxBarsBack in the declaration history is loaded column‑wise in full
format, precision, scale in the declaration the terminal controls scale and its format
timeframe in the declaration the script is calculated on the chart’s timeframe; another timeframe gives request.security
Line width, style or other output setting set by an expression rather than a constant (plot color and mark may change per bar) this build reads the setting only as a constant
color on the fourth and following plot the panel draws only the first three series
location.absolute on plotshape or plotchar the mark has no series to stick to
display that the series doesn’t have that series has no such surface

Runtime errors

A runtime error stops the script on the bar where it occurred. The text appears in the “Output” tab as “Script stopped: LS6004: …”.

LS6004 and LS6005 — script runs too long

“Script exhausted its operation budget on the bar — simplify the loop” (LS6004) and “Script exceeded the time limit for a pass” (LS6005). Each bar has a budget of 2,000,000 operations. Time is limited too: the whole historical pass — 2 seconds, one live‑bar tick — 20 ms. Almost always the cause is a loop that doesn’t terminate or iterates over too much data per bar.

Loot
var int n = 0
i = 0
while i < 10 {
    n := n + 1
}
Loot
var int n = 0
i = 0
while i < 10 {
    n := n + 1
    i := i + 1
}

LS6002 and LS5004 — reading the future

A history index x[n] cannot be negative: close[-1] would mean the next bar. If a negative number is written literally, the compiler rejects it immediately (LS5004). If it comes from a calculation, the script stops with “Negative history offset — cannot read the future” (LS6002). An index larger than the amount of loaded bars is not an error — it yields na.

LS6001, LS6007, LS6019 — collections and objects

  • LS6001 “Index … out of bounds” — array.get, array.set or matrix.get past the size. Check array.size(a) before access.
  • LS6007 “Access to an empty object (na)” — a collection was declared but not created: var array<float> a = na, then a.push(x). Create it with array.new<float>().
  • LS6019 “Drawing object already deleted or evicted by the ceiling — create it anew”. At most 500 objects of one kind live simultaneously; the oldest is evicted. Raise the ceiling via maxLinesCount, maxLabelsCount or maxBoxesCount in the declaration or reuse the object via set_*.

LS6017 and LS6018 — symbol and timeframe in request.security

“Symbol ‘…’ unknown — check the format ‘VENUE:SYMBOL’ or set ignore_invalid_symbol = true” (LS6017) and “Timeframe ‘…’ not parsed — expected ‘5’, ‘60’, ‘4h’, ‘1D’, ‘1W’” (LS6018). With ignore_invalid_symbol = true an unknown symbol yields na instead of stopping.

Execution limits

What is limited Limit Code on exceed
Operations per bar 2,000,000 LS6004
Time for history pass / live tick 2 s / 20 ms LS6005
Array elements 100,000 LS6003
Pairs in dictionary 50,000 LS6003
Matrix elements 1,000,000 LS6003
ta.* window length 100,000 bars LS6034
Line length 100,000 chars LS6014
Table cells 2000 LS6029
Heatmap layers 4 (0…3) LS6036
Drawing objects of one kind 500 by default oldest are evicted
Distinct instrument+timeframe pairs in request.security 8 —
request.security calls 32 LS4009 at compile time

When there’s no error, but there’s no value

Many situations that would crash in other languages give na in LootScript — a gap on the chart, not a stop:

  • arithmetic with na yields na: close - x with empty x is empty;
  • x[n] deeper than the start of history — na;
  • integer division by zero — na; floating division by zero does not stop the script;
  • book.*, tape.* and screener.* on historical bars — na;
  • footprint clusters, delta, open interest and order book history — na on bars where data is absent. Check cluster.available, delta.available and the neighbouring flags;
  • ta.* on the first bars while the window fills — na.

na is never drawn as zero on the chart: the line is interrupted. To substitute a value use nz(x), x ?? fallback or fixnan(x).

All codes

LS0001–LS0009 and LS0999 — text reading

Code Message What to do
LS0001 Unexpected character “…” Remove the character that doesn’t belong to the language
LS0002 String not closed — add a closing quote on the same line Close the quote on the same line
LS0003 Block comment not closed — add */ Close /* … */
LS0004 Unknown escape sequence “…” in string Allowed: \n, \r, \t, \0, \\, \", \' and \u{…}; double a single \
LS0005 Invalid numeric literal “…” Check the number’s notation
LS0006 Number “…” does not fit the type Reduce the number
LS0007 Invalid color literal “…” — expected #RRGGBB or #RRGGBBAA Six or eight hex digits
LS0008 Digit separator “_” at start, end or doubled Write 1_000_000
LS0009 Invalid version directive — expected #version <number> as the first line #version 1 on the first line
LS0999 The compiler failed on this file — this is a build defect, report it Report to support, attach the script

LS1000–LS1012 — parsing

Code Message What to do
LS1000 Unexpected: … Check the line for extra characters
LS1001 Expected “…”, found … Most often a missing closing bracket
LS1002 Expected an expression, found … A value is missing after an operator or comma
LS1004 Expected a name, found … After var, func, . you need a name
LS1005 Expected a block in braces, found … Add { … }
LS1006 Comparisons do not chain — write a < b and b < c Split into two comparisons with and
LS1008 Second script declaration — a script may have only one Leave a single declaration
LS1009 No script declaration — start with indicator(“Name”) First line must be indicator, strategy or library
LS1010 Too deep nesting (> 64) — move part into a function Split the expression or block
LS1012 The body of if / for / while is written in braces: if cond { … } Add braces

LS2000–LS2030 — types and names

Code Message What to do
LS2000 Type mismatch: expected …, got … Pass the value of the required type
LS2001 Cannot convert … to … Convert explicitly: str.tostring, math.round
LS2002 Unknown name “…” — check spelling or declare it earlier Fix the typo, add a namespace (ta.), declare earlier
LS2003 “…” is not a function, cannot call Remove parentheses: it’s a series or a constant
LS2004 “…” expects … argument(s), but … were given Check number of arguments in the reference
LS2005 “…” has no parameter “…” Fix the parameter name
LS2006 Argument “…” passed twice Remove the duplicate
LS2007 Condition must be bool, but here is … Compare explicitly: x > 0, not na(x)
LS2008 Comparison with na is always false — use na(x) na(x) instead of x == na
LS2014 “…” in “…” requires a value at least as strong as …, but got … — use input.*(…) or a literal Literal, input.* or constant instead of a series
LS2015 “…” declared constant — cannot assign; declare with var input.*, loop variables and function parameters cannot be reassigned — copy into your variable
LS2017 Cannot add string and number (… + …) — use str.tostring(…) str.tostring or str.format
LS2018 “…” already declared in this scope Use := to change value or rename
LS2019 “…” shadows a built‑in name — choose another Rename
LS2020 Branches give different types: … and … Make the branches yield the same type
LS2021 switch without default branch “=> …” — add one Add => value
LS2022 “…” element type cannot be inferred — specify it: … array.new<float>()
LS2028 Field “…” of type “…” has no type — write it before the name: float … float price in a type declaration
LS2029 export “…”: an exported function must have all parameter types and a return type Specify types
LS2030 “…” in “…” is read before the first bar — needs a literal or named constant Only constants in the declaration

LS3000–LS3033 — program semantics

Code Message What to do
LS3002 “…” calls itself — recursion is forbidden in LootScript Replace recursion with a loop
LS3003 Mutual recursion forbidden: … Break the cycle
LS3004 Argument “…” cannot be computed outside the branch — move the ta.* call to the top level Compute the argument and call outside if
LS3006 “…” shadows a name from an outer scope (warning) Rename the inner variable
LS3007 “…” outside a loop break and continue only inside loops
LS3008 return outside a function return only in a function body
LS3009 export “…” is allowed only in library(…) Remove export or make the file a library
LS3010 “…” without a single level (profit/loss/stop/limit/trail) — a no‑op (warning) Provide stop, take or trailing
LS3011 strategy.* available only in strategy(…) Declare the script with strategy(...)
LS3012 In a library you cannot draw or declare inputs: … Move outputs and settings into an indicator
LS3013 “…” inside request.security will not become a settings string — declare the input above and pass its value Declare input.* above and pass the variable
LS3016 Setting “…” accepted and does nothing: … (notice) You may leave it or remove it
LS3018 Library “…” not found in the libraries folder — its name is taken from library(“…”, N), not from the filename Check the name in the library declaration
LS3019 Libraries “…” version … not found; installed: … Specify an installed version
LS3020 “…” inside request.security: book and tape have no history on another series Remove book.*, tape.* from the expression
LS3025 Function “…” declared but not called — its body is only tentatively checked (warning) Call the function or delete it
LS3026 “…” requires a stop to size the position: loss/stop on entry or in strategy.exit Add a stop to the entry or strategy.exit
LS3028 This build does not support: … Rewrite without that construct
LS3029 switch branch for “…” repeats — the second is unreachable Remove the duplicate
LS3030 “…” is a chart series, and the request.security expression is evaluated on another series; pass the value via input.* or compute it inside the expression Compute inside the expression
LS3031 Libraries import each other in a cycle: … Break the import cycle
LS3032 In a library “…” only function declarations and imports are allowed — here is … Remove the rest from the library
LS3033 Library “…” does not compile (…) — open it in the Editor and fix it Fix the error in the library itself

LS4000–LS4009 — compilation limits

Code Message What to do
LS4000 Too many series: … at the limit 512 — remove extra ta.* or reuse variables Reduce ta.* calls and history variables
LS4001 Program too large (more than 4096 inlinings) — simplify functions Reduce calls to user functions
LS4002 Too many plots — the panel draws no more than three series Outputs — plot, plotshape, plotchar, bgcolor — no more than 64; the first three plot are drawn
LS4009 Too many request.security calls: …, limit 32 Combine the calls

LS5000–LS5013 — repainting and tester

Code Message What to do
LS5000 varip value reaches output — on history it will differ (warning) Use var if you need identical history
LS5001 Live‑bar‑only value reaches output — it is absent on history (warning) Use barstate.isconfirmed
LS5002 lookahead = true reads the future — unreachable on real time (warning) Remove lookahead = true
LS5003 Higher timeframe without offset — unclosed bar will repaint; add [1] (warning) request.security(…, close[1])
LS5004 Negative offset shifts output into the past — the line knows the future on history Remove negative index x[-n]
LS5005 Non‑deterministic value reaches output — two runs will give different series (warning) Do not output math.random and timenow
LS5006 Data exists only live — the history series is empty (warning) For order book history use depth.*
LS5011 Strategy reads ‘…’: book and tape have no history, a backtest would be fictional Remove book.*, tape.* from the strategy
LS5012 Strategy looks ahead (“…”) — the report is marked as unreachable in real time (warning) Remove lookahead = true
LS5013 “…” enabled: orders execute on bar close, the report is marked (notice) Remove processOrdersOnClose if you need a realistic report

LS6000–LS6036 — execution

Code Message What to do
LS6001 Index … out of bounds Check collection size before access
LS6002 Negative history offset — cannot read the future History index must be ≥ 0
LS6003 Collection size limit exceeded (…) — the collection was created on line … Limit growth: remove old elements
LS6004 Script exhausted its operation budget on the bar — simplify the loop Check loop exit condition
LS6005 Script exceeded the time limit for the pass Reduce work per bar
LS6007 Access to an empty object (na) Create the collection or object before access
LS6014 String longer than the 100000 char ceiling — shorten or build it in parts Shorten the string
LS6015 Unknown timezone “…” — an IANA identifier is required, e.g. “Europe/Berlin” Timezone in IANA format
LS6017 Symbol “…” unknown — check format “VENUE:SYMBOL” or set ignore_invalid_symbol = true Fix the symbol
LS6018 Timeframe “…” not parsed — expected “5”, “60”, “4h”, “1D”, “1W” Fix the timeframe
LS6019 Drawing object already deleted or evicted by the ceiling — create it anew Check the object or raise the ceiling
LS6020 str.format: placeholder {…} has no argument Provide an argument for each {n}
LS6021 str.match: pattern exhausted the step budget — simplify it Simplify the regex
LS6026 Script-wide collection budget exhausted (… cells) — a collection from line … didn’t fit Reduce the number or size of collections
LS6027 Invalid argument “…” in … e.g. negative size in array.new
LS6028 String budget exhausted (…) — reuse strings instead of allocating new ones each bar Do not build new strings each bar
LS6029 Table has more than 2000 cells — this is the panel ceiling Reduce the table
LS6030 Table cell outside the grid: … Column and row numbers must be inside table size
LS6031 Built‑in function “…” declared but not implemented — this is a build defect, report it Report to support
LS6032 Handle does not point to an object of the required kind — the object was freed or the handle is from another run Do not keep references to deleted objects
LS6033 Field … outside type declaration “…” — this is a build defect, report it Report to support
LS6034 Window length … exceeds the 100000 ceiling — such a window won’t fit in memory Reduce the window length
LS6035 Loop step is zero — counter does not move and the end is unreachable by in for cannot be zero
LS6036 Heat layer … outside 0…3 layer from 0 to 3
Codes this version does not issue

These numbers are reserved in the language but not emitted by the current terminal version: LS1003, LS1007, LS1011, LS2016, LS3000, LS3001, LS3005, LS4003, LS4004, LS5007, LS6000, LS6006, LS6008, LS6022, LS6023. For example, “declaration not on the first line” is reported as LS1009 now, and division by zero no longer stops the script with LS6000.

Next

https://docs.lootx.trade/en/loot/errors

Справочник

12Example scripts

Eight ready LootScript scripts: moving averages, RSI, VWAP with bands, cumulative delta with divergences, open interest, funding rate, cluster imbalances, and a strategy for the Strategy Tester.

Eight ready LootScript scripts — from moving averages and RSI to cumulative delta, open interest, funding rate and clusters. Each is a working indicator you can add to a chart and tweak. All examples compile with the current compiler without errors or warnings.

How to run an example

  1. Click ƒ on the chart panel; in the Indicators window, click Editor….
  2. In the Editor, click New (Ctrl+N), replace the template with the example code, and click Save.
  3. Click Add to chart (Ctrl+Enter). Settings from input.* will appear in the indicator settings window.

1. Three MAs with type selector

Fast, medium and slow moving averages of the selected type. Background highlights when all three align by trend.

Loot
indicator("Три скользящие", shortTitle = "MA×3", overlay = true)
maType = input.string("EMA", "Тип средней", options = ["EMA", "SMA", "WMA", "HMA"])
src    = input.source(close, "Источник")
len1   = input.int(20, "Быстрая", minval = 1)
len2   = input.int(50, "Средняя", minval = 1)
len3   = input.int(200, "Медленная", minval = 1)

func ma(s, len) => switch maType {
    "SMA" => ta.sma(s, len)
    "WMA" => ta.wma(s, len)
    "HMA" => ta.hma(s, len)
    => ta.ema(s, len)
}

m1 = ma(src, len1)
m2 = ma(src, len2)
m3 = ma(src, len3)

plot(m1, "Быстрая", color = m1 >= m1[1] ? color.teal : color.red, linewidth = 2)
plot(m2, "Средняя", color = color.orange)
plot(m3, "Медленная", color = color.gray, linewidth = 2)
bgcolor(m1 > m2 and m2 > m3 ? color.new(color.teal, 20) : m1 < m2 and m2 < m3 ? color.new(color.red, 20) : na)

How it works

  • input.string with options becomes a dropdown in the settings.
  • The ma function selects the MA via switch. The ta.* state is local to each call site, so three calls to ma produce three independent averages.
  • The fast line’s color is an expression: if it’s rising vs the prior bar (m1[1]) it’s teal, otherwise red.
  • The panel can draw up to three plot lines per script — hence three MAs.

2. RSI with zones and alerts

RSI with a filled band between levels. Line and background color when RSI sits in overbought or oversold zones.

Loot
indicator("RSI с зонами", shortTitle = "RSI", overlay = false)
len = input.int(14, "Период", minval = 2)
src = input.source(close, "Источник")
ob  = input.float(70, "Перекупленность", minval = 50, maxval = 100)
os  = input.float(30, "Перепроданность", minval = 0, maxval = 50)

r = ta.rsi(src, len)

hOb = hline(ob, "Перекупленность", color = color.red)
hOs = hline(os, "Перепроданность", color = color.teal)
fill(hOb, hOs, color = color.new(color.purple, 20))
plot(r, "RSI", color = r > ob ? color.red : r < os ? color.teal : color.purple, linewidth = 2)
bgcolor(r > ob ? color.new(color.red, 35) : r < os ? color.new(color.teal, 35) : na)

alertcondition(ta.crossunder(r, ob), "RSI вышел из перекупленности", "RSI опустился ниже верхнего уровня")
alertcondition(ta.crossover(r, os), "RSI вышел из перепроданности", "RSI поднялся выше нижнего уровня")

How it works

  • hline returns a level handle, and fill paints the zone between two handles.
  • Levels are input.float settings, so lines and fill move with them.
  • alertcondition declares two alerts. They don’t ring by themselves — how to enable them is explained on the Script alerts page.
  • Alpha in color.new is 0 (transparent) to 255 (opaque).

3. Day VWAP with deviation bands

Volume-weighted average price from UTC midnight and a ±σ band around it.

Loot
indicator("VWAP дня с полосами", shortTitle = "VWAP", overlay = true)
src  = input.source(hlc3, "Цена")
mult = input.float(1.0, "Ширина полосы, σ", minval = 0.1, step = 0.1)

anchor = session.isfirstbar
vw = ta.vwap(src, anchor)

// Сумма объёма и сумма объёма на квадрат цены с начала дня — для разброса вокруг VWAP.
var float sumV  = 0.0
var float sumV2 = 0.0
if anchor {
    sumV  := 0.0
    sumV2 := 0.0
}
if not na(volume) and not na(src) {
    sumV  := sumV + volume
    sumV2 := sumV2 + volume * src * src
}
sigma = sumV > 0 and not na(vw) ? math.sqrt(math.max(sumV2 / sumV - vw * vw, 0)) : na

pUp = plot(vw + mult * sigma, "Верх", color = color.new(color.blue, 150))
plot(vw, "VWAP", color = color.blue, linewidth = 2)
pDn = plot(vw - mult * sigma, "Низ", color = color.new(color.blue, 150))
fill(pUp, pDn, color = color.new(color.blue, 25))

How it works

  • ta.vwap restarts on the bar where the anchor is true. For crypto session.isfirstbar is the first bar after 00:00 UTC.
  • var variables persist across bars. They are zeroed by the same anchor, so the band is calculated for the same period as VWAP.
  • Deviation is sqrt(weighted mean of price^2 minus VWAP^2). math.max(…, 0) protects against tiny negatives from rounding.
  • This is meaningful on intraday timeframes. If you want VWAP since the last funding payment, set anchor = funding.settled.

4. Daily cumulative delta with divergences

Cumulative delta that resets daily, with marks on bars where price updates an extreme but delta does not.

Loot
indicator("Дневная кумдельта с расхождениями", shortTitle = "CVD", overlay = false)
len = input.int(20, "Окно поиска максимумов", minval = 3)

var float cvd = 0.0
if session.isfirstbar {
    cvd := 0.0
}
if delta.available {
    cvd := cvd + delta.value
}
cvdLine = delta.available ? cvd : na

// Цена обновила максимум окна, а кумдельта — нет: покупатели не подтверждают рост.
bearish = high >= ta.highest(high, len) and cvdLine < ta.highest(cvdLine, len)
bullish = low <= ta.lowest(low, len) and cvdLine > ta.lowest(cvdLine, len)

plot(cvdLine, "Кумдельта", color = cvdLine >= 0 ? color.teal : color.red, linewidth = 2)
hline(0, "Ноль", color = color.gray)
plotshape(bearish, "Медвежье расхождение", style = shape.triangledown, location = location.top, color = color.red, size = size.tiny)
plotshape(bullish, "Бычье расхождение", style = shape.triangleup, location = location.bottom, color = color.teal, size = size.tiny)

How it works

  • delta.value is aggressive buying minus aggressive selling for the bar. Where the feed is missing delta.available is false and the line gaps rather than plotting zero.
  • The accumulator var is reset at the start of the day. If you need a cumulative delta over the whole loaded history without resets, use the ready series delta.cum.
  • Divergence: price at the window high, but cumulative delta below its high for the same window. Minimums are mirrored.
  • location.top and location.bottom place marks at the pane edges, not at price.

5. Open interest spikes

Open interest change from bar to bar in percent, with marks where it deviates from normal volatility.

Loot
indicator("Изменение открытого интереса", shortTitle = "ΔOI %", overlay = false)
len = input.int(50, "Окно для всплесков", minval = 5)
k   = input.float(3.0, "Порог всплеска, σ", minval = 0.5, step = 0.5)

pct = oi.available and oi.close[1] > 0 ? 100 * (oi.close - oi.close[1]) / oi.close[1] : na
sd  = ta.stdev(pct, len)
spike = not na(sd) and math.abs(pct) > k * sd

plot(pct, "ΔOI, %", style = plot.style_columns, color = pct >= 0 ? color.teal : color.red)
hline(0, "Ноль", color = color.gray)
plotshape(spike, "Всплеск", style = shape.circle, location = location.top, color = color.orange, size = size.tiny)

How it works

  • oi.close is open interest at the bar close, oi.close[1] at the previous bar. oi.available prevents computing changes from nothing.
  • A spike is a bar whose absolute change exceeds k standard deviations over len bars.
  • Open interest arrives per minute. On timeframes under a minute adjacent bars repeat the same value and the change is zero — that’s the data, not a bug.

6. Funding rate

Perpetual funding rate in percent per period or annualized, with marks on settlements and highlighting for high rates.

Loot
indicator("Ставка финансирования", shortTitle = "Funding", overlay = false)
mode = input.string("За период", "Показывать", options = ["За период", "Годовых"])
thr  = input.float(0.05, "Порог, %", minval = 0.0, step = 0.01)

perPeriod = funding.rate * 100
periodsPerYear = funding.interval_hours > 0 ? 24.0 / funding.interval_hours * 365 : na
value = mode == "Годовых" ? perPeriod * periodsPerYear : perPeriod
level = mode == "Годовых" ? thr * periodsPerYear : thr

plot(value, "Ставка, %", style = plot.style_columns, color = value >= 0 ? color.teal : color.red)
hline(0, "Ноль", color = color.gray)
plotshape(funding.settled, "Выплата", style = shape.circle, location = location.bottom, color = color.gray, size = size.tiny)
bgcolor(math.abs(value) > level ? color.new(color.orange, 30) : na)

How it works

  • funding.rate is a fraction, not percent: 0.0001 means 0.01%. So the rate is multiplied by 100.
  • For annualized values the rate is multiplied by the number of settlements per year. 24.0 is written as a float deliberately: integer division in LootScript truncates.
  • funding.settled is true on the bar where a payment occurred — a dot is placed there.
  • The threshold is specified per period and is converted the same way for annualized mode.

7. Cluster imbalances

Marks on the price chart where a bar’s clusters contain a vertical ladder of imbalances or simply many imbalances, plus the POC (maximum volume level) of each bar.

Loot
indicator("Дисбалансы кластеров", shortTitle = "Imbalance", overlay = true)
minSteps = input.int(3, "Уровней подряд", minval = 2)
minCount = input.int(5, "Дисбалансов в баре", minval = 1)

levels = cluster.available ? cluster.levels : 0
buys  = 0
sells = 0
for i in 0 .. levels {
    side = cluster.imbalance(i)
    if side == 1 {
        buys := buys + 1
    } else if side == -1 {
        sells := sells + 1
    }
}

plot(cluster.poc, "POC", style = plot.style_circles, color = color.orange)
plotshape(cluster.stacked_buy_steps >= minSteps, "Лесенка покупок", style = shape.triangleup, location = location.belowbar, color = color.teal, size = size.small)
plotshape(cluster.stacked_sell_steps >= minSteps, "Лесенка продаж", style = shape.triangledown, location = location.abovebar, color = color.red, size = size.small)
plotshape(buys >= minCount, "Много дисбалансов покупок", style = shape.circle, location = location.belowbar, color = color.new(color.teal, 120), size = size.tiny)
plotshape(sells >= minCount, "Много дисбалансов продаж", style = shape.circle, location = location.abovebar, color = color.new(color.red, 120), size = size.tiny)

How it works

  • cluster.imbalance(i) returns +1, −1 or 0 for price level i. The imbalance threshold comes from the chart cluster settings, so the script sees the same definition as the chart.
  • cluster.stacked_buy_steps is how many consecutive levels contain buy imbalances. The for i in 0 .. levels loop counts all imbalances in the bar, not only consecutive ones.
  • The script subscribes to cluster data and runs on a normal candlestick chart. On exchanges without coverage, and on timeframes under 30 seconds or over a day, there are no clusters — then levels is 0 and no marks appear.

8. Strategy: EMA cross with ATR stop

Long entry on MA cross, stop and take-profit in ATR multiples, exit on the opposite cross.

Loot
strategy("EMA-кросс со стопом по ATR", overlay = true, initialCapital = 10000,
         defaultQtyType = strategy.qty.percent_of_equity, defaultQtyValue = 10,
         slippageTicks = 2)
fastLen = input.int(12, "Быстрая EMA", minval = 1)
slowLen = input.int(26, "Медленная EMA", minval = 2)
atrLen  = input.int(14, "Период ATR", minval = 1)
stopK   = input.float(1.5, "Стоп, в ATR", minval = 0.1, step = 0.1)
takeK   = input.float(3.0, "Цель, в ATR", minval = 0.1, step = 0.1)

fast = ta.ema(close, fastLen)
slow = ta.ema(close, slowLen)
atr  = ta.atr(atrLen)

// ATR запоминается в момент сигнала, чтобы стоп и цель не ползли вслед за волатильностью.
var float riskAtr = na
if ta.crossover(fast, slow) and strategy.position_size == 0 {
    riskAtr := atr
    strategy.entry("Long", strategy.long)
}
if ta.crossunder(fast, slow) {
    strategy.close("Long", comment = "Обратный кросс")
}
if strategy.position_size > 0 {
    entry = strategy.position_avg_price
    strategy.exit("Стоп/цель", from_entry = "Long", stop = entry - stopK * riskAtr, limit = entry + takeK * riskAtr)
}

plot(fast, "Быстрая", color = color.teal)
plot(slow, "Медленная", color = color.orange)

How it works

  • strategy(…) parameters are literals: capital 10,000, position size 10% of equity, slippage 2 ticks. Commission is not set, so the tester uses the default fee: 0.02% for limit fills and 0.05% for market and stop. Set your own percentage via commissionValue.
  • Market entries execute on the open of the next bar, not on the signal bar’s close: the tester does not look into the future.
  • strategy.exit sets stop and target from the average entry price. If both are touched in one bar, the tester by default assumes the stop fired.
  • Results — trades, equity curve, drawdowns — appear in the Strategy Tester… window of the Editor. See Strategies and tester for details.

Next

https://docs.lootx.trade/en/loot/examples