QTrader
Menu

QTrader documentation

Task guides

Getting started

QTrader is a strategy backtesting workbench. You write a strategy in vanilla Python or in a subset of Pine Script, QTrader compiles it into a whitelisted, sandboxed program, and runs it bar by bar over historical candles.

A strategy defines up to four entry points — enter_long(), exit_long(), enter_short(), exit_short() in Python, or strategy.entry(...) / strategy.close(...) in Pine. Each bar, QTrader evaluates whichever ones apply to the current position and queues an order that fills at the next bar's open. See Python strategies, Position and Backtest rules below for the full model, including stop-loss/ take-profit and short positions.

In the workbench: the editor opens on a short working strategy — a moving-average cross — in Python or Pine; change it, paste your own code, or open one of the Examples. Set the symbol, timeframe and period with the button above the chart (it shows the current ones, e.g. BTCUSDT · 1h · 30 Mar – 28 Sep 2026), then run Backtest. Results appear as metrics, a trade list, an equity curve and notes, alongside markers on the price chart.

No account is needed to try it; saving strategies, running robots and the assistant need one. The Assistant tab next to Notes writes a strategy from a description in plain words — in the language of the open strategy — and checks it with QTrader's compiler before showing it; Use this code puts it in the editor (undo brings your code back) and backtests it. Ask for changes in the same conversation (“add a 2% stop”).

Examples

Complete strategies to start from or learn by. Open in workbench puts the code in the editor as a new, unsaved strategy — save it to keep it — on the example's timeframe, unless you have picked a timeframe yourself. Unsaved work in the workbench is never replaced without asking.

MACD cross, EMA 200 filter (Pine)

Pine4h

Long only. Buys when the MACD line (12, 26, 9) crosses above its signal line while the close is above the 200-bar EMA; closes the position when the MACD line crosses back below. No stop-loss or take-profit.

Show code
//@version=6
strategy("MACD cross, EMA 200 filter", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
[macdLine, signalLine, _] = ta.macd(close, 12, 26, 9)
trend = ta.ema(close, 200)
if ta.crossover(macdLine, signalLine) and close > trend
    strategy.entry("Long", strategy.long)
if ta.crossunder(macdLine, signalLine)
    strategy.close("Long")
Open in workbench

SMA 50/200 cross

Python4h

Long only. Buys when the 50-bar SMA crosses above the 200-bar SMA and sells when it crosses back below; both lengths are inputs. No stop-loss or take-profit.

Show code
fast_length = input.int(50, "Fast SMA", minval=2)
slow_length = input.int(200, "Slow SMA", minval=2)


def enter_long():
    return indicator.crossover(indicator.sma(close, fast_length), indicator.sma(close, slow_length))


def exit_long():
    return indicator.crossunder(indicator.sma(close, fast_length), indicator.sma(close, slow_length))
Open in workbench

SMA 50/200 cross (Pine)

Pine4h

The same SMA 50/200 cross in Pine Script: long only, buys when the fast SMA crosses above the slow one and closes when it crosses back below; both lengths are inputs.

Show code
//@version=6
strategy("SMA 50/200 cross", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
fastLength = input.int(50, "Fast SMA", minval=2)
slowLength = input.int(200, "Slow SMA", minval=2)
fast = ta.sma(close, fastLength)
slow = ta.sma(close, slowLength)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")
Open in workbench

EMA 20/50 cross long/short, 2% stop

Python4h

Long and short. Goes long when the 20-bar EMA crosses above the 50-bar EMA and short when it crosses below: each cross reverses the open position. A 2% stop-loss guards both sides.

Show code
fast_length = input.int(20, "Fast EMA", minval=2)
slow_length = input.int(50, "Slow EMA", minval=2)

strategy(stop_loss_percent=2)


def enter_long():
    return indicator.crossover(indicator.ema(close, fast_length), indicator.ema(close, slow_length))


def enter_short():
    return indicator.crossunder(indicator.ema(close, fast_length), indicator.ema(close, slow_length))
Open in workbench

SMA 50/200 cross, 2% stop / 4% target (Pine)

Pine1h

Long only. Buys when the 50-bar SMA crosses above the 200-bar SMA and leaves only through strategy.exit: a 2% stop-loss or a 4% take-profit from the entry price, both inputs.

Show code
//@version=6
strategy("SMA percent exit", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
longLossPerc = input.float(2.0, "Stop Loss (%)") * 0.01
longProfitPerc = input.float(4.0, "Take Profit (%)") * 0.01
fast = ta.sma(close, 50)
slow = ta.sma(close, 200)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if strategy.position_size > 0
    strategy.exit("XL", "Long", stop=strategy.position_avg_price * (1 - longLossPerc), limit=strategy.position_avg_price * (1 + longProfitPerc))
Open in workbench

Bollinger mean reversion, 3% trailing stop

Python4h

Long only, mean reversion. Buys when the close crosses back above the lower Bollinger Band (20 bars, 2.5 standard deviations) and sells when it falls back below the upper band. A 3% trailing stop protects the position.

Show code
strategy(trailing_stop_percent=3)

length = input.int(20, "Length", minval=2)
mult = input.float(2.5, "Multiplier")


def enter_long():
    middle, upper, lower = indicator.bb(close, length, mult)
    return indicator.crossover(close, lower)


def exit_long():
    middle, upper, lower = indicator.bb(close, length, mult)
    return indicator.crossunder(close, upper)
Open in workbench

Three green bars in a row (state)

Python4h

Long only. Counts green bars in a row in a state() variable: buys after three green bars in a row and sells on a red bar that closes below the previous bar's open. No stop-loss or take-profit.

Show code
streak = state(0)


def on_bar():
    # Counts green bars in a row: +1 on a green bar, back to 0 on a red one.
    if close > open:
        streak = streak + 1
    else:
        streak = 0


def enter_long():
    return streak >= 3


def exit_long():
    return streak == 0 and close < open[-1]
Open in workbench

Fear & Greed contrarian

Python1d

Long only. Buys when the Fear & Greed Index drops below 25 (extreme fear) and closes the position when it rises above 75 (extreme greed); both levels are inputs. Reads the index as market_data.fear_n_greed: a value counts from 02:00 UTC of its day, when a live robot has it too, so a daily bar trades on the value of the day it opened. No stop-loss or take-profit.

Show code
fear_level = input.int(25, "Buy below")
greed_level = input.int(75, "Sell above")

fear_n_greed = market_data.fear_n_greed


def enter_long():
    return fear_n_greed < fear_level


def exit_long():
    return fear_n_greed > greed_level
Open in workbench

Breakout, trailing high stop (Pine var)

Pine1h

Long only, breakout. Buys when the close rises above the highest high of the previous 20 bars, keeps the highest close since in a var, and closes once the close falls 3% below it: a trailing stop written in the script.

Show code
//@version=6
strategy("Trailing high stop (var)", initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
len = input.int(20, "Breakout length", minval=2)
stopPct = input.float(3.0, "Trail, %") * 0.01
var float peak = na
breakout = close > ta.highest(high, len)[1]
if breakout
    peak := close
if close > peak
    peak := close
if breakout
    strategy.entry("Long", strategy.long)
if close < peak * (1 - stopPct)
    strategy.close("Long")
Open in workbench

Python strategies

The Python dialect is a small, whitelisted subset — only what is needed to express a signal. At the top level you may define functions, input parameters, series such as fast_ema = indicator.ema(close, fast) (usable in every function, as in Pine), and one strategy(...) call (see Strategy settings):

strategy(stop_loss_percent=2, take_profit_percent=4)

fast = input.int(20, "Fast EMA")
slow = input.int(50, "Slow EMA")
fast_ema = indicator.ema(close, fast)
slow_ema = indicator.ema(close, slow)


def enter_long():
    return indicator.crossover(fast_ema, slow_ema)


def exit_long():
    return position.bars_since_entry > 30


def enter_short():
    return indicator.crossunder(fast_ema, slow_ema)


def exit_short():
    return position.pnl_percent > 10
FunctionDescription
enter_long()True to open a long position while flat, or to reverse from short into long. Old name, still supported: buy().
exit_long()True to close a long position. Has no effect while short or flat. Old name, still supported: sell().
enter_short()True to open a short position while flat, or to reverse from long into short.
exit_short()True to close a short position. Has no effect while long or flat.

A stop or target at a price the code computes: stop_long(), take_profit_long(), stop_short(), take_profit_short() return a price, or na for none — e.g. return position.entry_price - 2 * indicator.atr(14). They run on every bar after its fills, for the position the next bar holds, and combine with stop_loss_percent / take_profit_percent: the stricter stop and the nearer target win. On the bar the entry fills, one its open is already past (a price set before a gap) fills at that open, as in TradingView. A live robot doesn't place them on the exchange: it closes at market within about a minute after the price touches them.

An entry at a price: enter_long_stop(), enter_long_limit(), enter_short_stop(), enter_short_limit() return the trigger price of an order for the next bar, or na — a stop buys when the price rises to it, a limit when it falls to it (at the open when the bar opens past it). An order on the other side of a position reverses it; one on the side already held waits. The stop and target are armed at the fill and see the rest of that bar — the extremes after it and the move to the close. A live robot sends a market order within about a minute after the price touches it. History may go back by an input.int: close[-length] (or close[-(length - 1)]). An indicator.* length may be arithmetic of numbers and inputs — indicator.wma(close, length / 2), math.round(math.sqrt(length)) — computed for the run's parameters, its fraction dropped.

  • All four are optional and take no arguments, but at least one of enter_long()/enter_short() must be defined. Each returns a boolean; a missing or na result counts as False.
  • buy() and sell() are exactly enter_long() and exit_long() under old names — they keep working, but declaring both the old and the new name of the same function (e.g. both buy() and enter_long()) is a compile error. This also means a helper you happen to name buy() in a short-only strategy is a long entry, not a helper function.
  • position.* (see Position) is a read-only view of the current position, usable inside any of the four functions.
  • Parameters are declared with input.int(default, title, minval=..., maxval=...), input.float(...), input.bool(...), input.string(...), input.source(...) or input.timeframe(...) (see Inputs); they show up as editable fields in the Parameters tab.
  • Inside a function: if/else, return, assigning a variable once (a state variable in on_bar() as often as needed), arithmetic and comparison operators, calls to indicator.*, math.* or your other top-level functions, and history with close[-1] (the previous bar — future bars are never available).
  • State between bars: streak = state(0) at the top level keeps its value from one bar to the next, and def on_bar(): — run on every bar, in order, before the four functions — is the one place to change it (as often as you like, inside if/else too). Read it anywhere, with history streak[-1]; the starting value may be any expression (it's computed on the first bar, e.g. peak = state(high)). on_bar() may read position.* — the position after that bar's fills, e.g. to track the high since entry. A state variable can be a indicator.* source — e.g. avg_streak = indicator.sma(streak, 5) read in the entry functions — computed once its values are known: not inside on_bar(), and not when on_bar() reads position.*.
    streak = state(0)
    
    
    def on_bar():
        if close > open:
            streak = streak + 1
        else:
            streak = 0
    
    
    def enter_long():
        return streak >= 3
  • Log lines: log.info(f"close {close:.2f}"), log.warning(...) and log.error(...) on a line of their own in on_bar() — see Strategy log.
  • Loops inside functions: for i in range(n) (or range(a, b[, step])) and while, with break/continue; close[-i] reads i bars back. Every loop pass on a bar counts against 10,000 — past that the backtest stops with the loop's line.
  • Arrays: array.new_float(size, value), array.from_items(...), array.push, array.get, array.avg and the rest of Pine's array.* as functions. Keep one from bar to bar with window = state(array.new_float(0)) and change it in on_bar(); the entry functions read what they need from a state variable on_bar() sets (avg = state(na), then avg = array.avg(window)). An array made inside a function lives for that call.
  • Maps and objects — what Pine's map.* and user-defined types become: map.new(), map.put(m, key, value), map.get, map.contains, map.remove, map.size, map.keys, map.values, map.clear, map.copy, map.put_all (keys are numbers or true/false); an object is obj.new(field, ...), read with obj.get(t, i), changed with obj.set(t, i, value), copied with obj.copy(t). Arrays and maps may hold them; obj.ref(array.get(trades, 0)) marks one read out of another. Kept in state and changed in on_bar(), as arrays are. Matrices, Pine's matrix.*: matrix.new(rows, columns, value), matrix.get(m, i, j), matrix.set(m, i, j, value), matrix.row, matrix.mult, matrix.inv and the rest as functions, kept in state the same way.
  • Several entries in one direction: strategy(pyramiding=3) lets each further enter_long() while long add one (sized from position_size_percent of the equity), each a trade of its own with its own stop/target; position.entry_price is their average. A partial close: def exit_long_percent() returns the percent of the position to close at the next open (or na), the oldest entries first. An exit ladder: steps take_profit_long_1() / stop_long_1() … _4, each closing its strategy(exit_long_1_percent=50) of the position as entered (a step without a percent closes what is left). Backtests only for now — a live robot refuses all three.
  • Not allowed: imports, classes, comprehensions, lambdas, try/except, f-strings, augmented assignment, or any name starting with _.
  • An indicator.* function that returns several values (indicator.macd, indicator.bb, indicator.kc, indicator.dmi, indicator.supertrend) must be unpacked into that many names, e.g. macd_line, signal_line, histogram = indicator.macd(close, 12, 26, 9); use _ for a name you don't need.
  • An indicator.* function's source argument can also be arithmetic over price series, parameters and other indicator.* results, e.g. indicator.sma(close - open, 10) or indicator.sma(nz(close - close[-1], 0), 5) — see indicator.* functions.

Pine Script

QTrader also accepts a subset of Pine Script (//@version=4, //@version=5 or //@version=6), translated internally into the same vanilla Python dialect before compiling. See Pine support below for exactly which Pine features are supported, ignored or unsupported.

//@version=6
strategy("SMA 20/50 cross", initial_capital=10000, default_qty_type=strategy.percent_of_equity,
     default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1)
fastLength = input.int(20, "Fast SMA", minval=2)
slowLength = input.int(50, "Slow SMA", minval=2)
fast = ta.sma(close, fastLength)
slow = ta.sma(close, slowLength)
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fast, slow)
    strategy.close("Long")

History works the same way as in Python, but with TradingView's own offset convention: close[1] is the previous bar (Python's close[-1]); only bars at or before the current one can be read.

strategy.entry(id, strategy.short) opens a short position, and strategy.exit(...) with stop=/limit= as a percent of strategy.position_avg_price sets a stop-loss/take-profit — see Stop-loss and take-profit and Pine support below for the exact forms accepted.

The Convert to Python editor action turns a compiling Pine script into the equivalent, readable vanilla Python — a starting point for strategies that need something the Pine subset doesn't support yet.

Position

position is a read-only namespace: it reflects the current bar's position and cannot be assigned to, indexed with history ([-1]), or used as a indicator.* source. In Pine, the same state is read through strategy.position_size and strategy.position_avg_price — there strategy.position_size[1] reads the previous bar's (see Pine support).

FieldTypeDescription
position.sizefloatSigned position size: positive while long, negative while short, 0 while flat.
position.is_longboolTrue while holding a long position.
position.is_shortboolTrue while holding a short position.
position.is_flatboolTrue when there is no open position.
position.entry_pricefloatFill price of the current position's entry. na while flat.
position.pnl_percentfloatUnrealized profit or loss in percent of the entry price, as of this bar's close, before commissions (signed for shorts). na while flat.
position.bars_since_entryfloatBars since the entry fill, 0 on the entry bar itself. na while flat.
position.equityfloatAccount value at this bar's close: cash plus the open position marked at the close (Pine: strategy.equity).
position.net_profitfloatProfit of all closed trades so far, after fees (Pine: strategy.netprofit).
position.open_profitfloatProfit of the open position at this bar's close, 0 when flat (Pine: strategy.openprofit).
position.closed_tradesfloatNumber of closed trades so far (Pine: strategy.closedtrades).
position.win_tradesfloatClosed trades with a profit (Pine: strategy.wintrades).
position.loss_tradesfloatClosed trades with a loss (Pine: strategy.losstrades).
position.open_tradesfloatOpen trades: the lots of a position built with pyramiding, else 1 while a position is open (Pine: strategy.opentrades). Each trade's own values: open_trades.entry_price(n), entry_bar_index, entry_time, size (negative for a short), profit, profit_percent, commission, max_runup, max_drawdown (n = 0 the oldest); the closed ones: closed_trades.entry_price(n), exit_price, entry_bar_index, exit_bar_index, entry_time, exit_time, profit, profit_percent, size, commission, max_runup, max_drawdown (and their _percent), closed_trades.first_index() -- na for a price, time or bar of a trade that doesn't exist, 0 for the rest.
position.initial_capitalfloatThe run's starting capital: the Parameters tab's Initial capital, a robot's own capital (Pine: strategy.initial_capital).
position.max_drawdownfloatThe deepest drawdown so far, in money: from the peak of the closed trades' equity down to the open position's worst price within a bar, its entry commission counted (Pine: strategy.max_drawdown).
position.max_drawdown_percentfloatThe same drawdown in percent of the peak it fell from (Pine: strategy.max_drawdown_percent).

While flat, entry_price, pnl_percent and bars_since_entry are na — any comparison against na is False.

Strategy settings

strategy(...) configures the backtest from inside the strategy itself. In Python, call it at most once, at the top level, with named arguments only:

strategy(stop_loss_percent=2, take_profit_percent=4)
ArgumentDefaultRangeDescription
initial_capital10000greater than 0, at most 1,000,000,000,000Starting cash for the backtest, in quote currency.
position_size_percent100greater than 0, at most 100Position size as a percentage of current cash, used for both long and short entries.
commission_percentthe market's taker fee0–10Commission charged on each side of a trade (entry and exit), as a percentage of the traded notional. Left out, it is the taker fee of the market's exchange (0.1 for a market with none on file); the Parameters tab names it.
stop_loss_percent0 (off)0–1000Stop-loss distance from the entry fill price, in percent. 0 or omitted disables it.
take_profit_percent0 (off)0–1000Take-profit distance from the entry fill price, in percent. 0 or omitted disables it.
trailing_stop_percent0 (off)0–100Trailing-stop distance from the running best price since entry, in percent. Combines with stop_loss_percent -- whichever is nearer to the price wins. 0 or omitted disables it.
leverage1 (off)1–125Futures leverage multiplies the notional of percent-sized entries. In backtests on perpetual markets (.P), each entry uses isolated margin and has its own liquidation price. Pyramiding and partial exits are supported. Priced strategy.order calls require 1x leverage. In Pine, margin_long and margin_short are ignored: as in TradingView they don't change the position's size, so leverage comes from this setting only.
slippage_percent0 (off)0–5Price lost on each exit by stop and each entry or exit at the market, in percent: buys fill higher, sells lower. Limit entries and take-profits are not slipped. 0 or omitted disables it. Ignored when the Pine code sets strategy(slippage=N).
process_orders_on_closeFalseTrue or FalseTrue: a signal fills at its own bar's close instead of the next bar's open (a live robot sends it right after that close either way).

A value can be a number, an input parameter, or arithmetic (+ - * /) over them — so a stop-loss can be exposed as a Parameters-tab input. Whatever the code sets, the Parameters tab overrides it once a run's settings are edited there.

In Pine there is no single strategy(...) argument for stop-loss/take-profit: initial_capital, default_qty_type/default_qty_value and commission_type/commission_value map to initial_capital, position_size_percent and commission_percent above; stop_loss_percent/take_profit_percent are derived instead from strategy.exit(...) — see Stop-loss and take-profit.

Stop-loss and take-profit

The stop-loss and take-profit levels are fixed once, at the entry fill price, and never move: for a long, stop is entry × (1 − stop_loss_percent / 100) and target is entry × (1 + take_profit_percent / 100); for a short the two are mirrored. Either one is off when its percent is 0 or not set.

They are checked against every bar's high/low while the position is open, including the entry bar itself — like a protective order placed together with the entry on an exchange. This is different from the common TradingView pattern of an exit keyed off strategy.position_avg_price, which only becomes accurate one bar later (strategy.position_avg_price is na on the entry signal's own bar), and never arms at all if the exit is written inside that same entry if:

if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)
    // In TradingView this exit only starts checking the NEXT bar; in QTrader the
    // matching stop_loss_percent is active from the entry's own fill bar.
    strategy.exit("Exit", from_entry="Long", stop=strategy.position_avg_price * 0.98)

A gap — the bar after entry opening already past a level — exits at that bar's open instead of the level price. If a single bar's high/low reaches both levels, QTrader follows TradingView's own path rule: when the bar's high is closer to its open than its low is (high − open ≤ open − low), the assumed path is open → high → low, otherwise open → low → high, and whichever level is reached first on that path wins.

An exit filled by stop-loss or take-profit still leaves the rest of the bar's signal evaluation to run — a new entry can be queued for the very next bar's open.

In Pine, a Pine input whose default is 0 — the common input.float(0, "Stop %") — turns the stop off in QTrader, whereas TradingView itself would place a stop right at the entry price.

trailing_stop_percent adds a trailing stop on top: QTrader tracks the best price since entry (starting at the entry fill price itself) — the running high for a long, the running low for a short — and the stop trails it by that percent: running_high × (1 − trailing_stop_percent / 100) for a long, running_low × (1 + trailing_stop_percent / 100) for a short. The level only ever moves in the position's favour, never back. It uses the same intrabar path rule as above: on the leg towards the running extreme, the extreme (and the level) updates first; the level is then checked on the other leg. QTrader also walks a final leg back to the bar's close, so a single bar can extend the peak on one leg and still exit on the new, tighter level on the way back to the close, even when neither the high nor the low touched it directly — the same way TradingView does. A gap past the level exits at that bar's open, same as stop-loss/take-profit.

A trailing stop combines with a plain stop_loss_percent — whichever of the two is nearer to the current price applies, a tie favouring the fixed stop. The exit reason is trailing_stop (shown as Trail) only when the trailing level is the one that actually fired. Pine has no strategy(...) argument to set this from code — there is no Pine equivalent of trailing_stop_percent to translate from, so a converted or hand-written Pine strategy gets it the same way as any other setting override: the Trailing stop, % field on the Parameters tab. Pine's own strategy.exit trailing arguments are also supported: trail_price is an absolute activation price, while trail_points and trail_offset are tick distances. See the Pine support reference for activation rules. They are distinct from the percentage setting above.

Price series

NameDescription
openBar's opening price.
highBar's high price.
lowBar's low price.
closeBar's closing price.
volumeBar's traded volume.
hl2Average of high and low: (high + low) / 2.
hlc3Average of high, low and close: (high + low + close) / 3.
ohlc4Average of open, high, low and close: (open + high + low + close) / 4.
timeBar's open time, in UTC milliseconds — compare it with timestamp(2024, 3, 1).
bar_indexBar's number among the bars loaded for this backtest (warm-up included), from 0.
yearYear of the bar's open time, UTC.
monthMonth of the bar's open time, 1–12, UTC.
dayofmonthDay of the month of the bar's open time, 1–31, UTC.
dayofweekDay of the week of the bar's open time, UTC: 1 = Sunday … 7 = Saturday (Pine's numbering).
hourHour of the bar's open time, 0–23, UTC.
minuteMinute of the bar's open time, 0–59.
time_closeBar's close time, in UTC milliseconds: its open time plus one bar.
last_bar_indexbar_index of the last bar loaded for this backtest — the same on every bar.
timenow"Now": the last loaded bar's close time, UTC milliseconds — for a live robot, the moment of its tick.
mintickThe price step (Pine: syminfo.mintick): the decimal step the symbol's prices are written in, e.g. 0.01.
weekofyearISO 8601 week of the bar's open time, 1–53, UTC.

timestamp(year, month, day[, hour[, minute[, second]]]) is that moment in UTC, in the same milliseconds as time — e.g. trade only from a date on: time >= timestamp(2024, 3, 1). Its arguments may be input parameters.

A longer timeframe: daily = request.security("1d", indicator.sma(close, 20)) (Pine: request.security(syminfo.tickerid, "D", ta.sma(close, 20))) — the value computed on this chart's candles merged into "4h", "1d", "1w" or "1M" bars. A chart bar sees a longer bar's value once that bar has closed, so it never looks ahead; a third argument True (Pine: lookahead=barmerge.lookahead_on) gives the bar it's in instead — use it with [-1] (Pine: [1]). Only this chart's symbol, and only a timeframe longer than the chart's.

indicator.* functions

In Python every indicator is called as indicator.*; ta.* still works as an old name for it, and Pine keeps ta.*. Every function here is computed once per backtest over the whole candle array. A function's warm-up is how many extra bars QTrader reads before the requested period so the indicator is no longer na at the first visible bar; see Backtest rules. A source argument can also be arithmetic over price series, parameters and other indicator.* results — e.g. indicator.sma(close - open, 10) — computed once the same way as a plain series.

Every number-valued indicator.* result the strategy computes is drawn on the workbench chart after a backtest: moving averages and bands over the candles, oscillators (RSI, MACD, ATR…) in a pane of their own under them. The legend names each line after the variable it's assigned to (else after its call), shows its value under the cursor, and lets you recolour or hide it. Two variables that compute exactly the same thing are one line, named after both — fast = slow. The Indicators menu over the chart adds a declaration such as rsi_14 = indicator.rsi(close, 14) under your inputs and re-runs the backtest.

FunctionReturnsWarm-upDescription
indicator.sma(source, length)floatlength − 1 bars

Simple moving average of source over length bars.

Python: close > indicator.sma(close, 20)
Pine:   close > ta.sma(close, 20)
indicator.ema(source, length)float10 × length bars

Exponential moving average, seeded with the SMA of the first length values.

Python: close > indicator.ema(close, 20)
Pine:   close > ta.ema(close, 20)
indicator.rma(source, length)float20 × length bars

Wilder's moving average: seeded and na-handled like ema, but with a slower smoothing step.

Python: close > indicator.rma(close, 20)
Pine:   close > ta.rma(close, 20)
indicator.wma(source, length)floatlength − 1 bars

Weighted moving average: newer bars in the window carry linearly higher weight.

Python: close > indicator.wma(close, 20)
Pine:   close > ta.wma(close, 20)
indicator.rsi(source, length)float20 × length + 1 bars

Relative strength index (0–100), from the average of gains vs. losses over length bars.

Python: indicator.rsi(close, 14) < 30
Pine:   ta.rsi(close, 14) < 30
indicator.highest(source, length)floatlength − 1 bars

Highest value of source over the last length bars.

Python: close >= indicator.highest(high, 20)
Pine:   close >= ta.highest(high, 20)
indicator.lowest(source, length)floatlength − 1 bars

Lowest value of source over the last length bars.

Python: close <= indicator.lowest(low, 20)
Pine:   close <= ta.lowest(low, 20)
indicator.stdev(source, length)floatlength − 1 bars

Standard deviation of source over length bars (biased, population formula).

Python: indicator.stdev(close, 20) > 5
Pine:   ta.stdev(close, 20) > 5
indicator.change(source, length=1)floatlength bars

Difference between source now and length bars back.

Python: indicator.change(close, 1) > 0
Pine:   ta.change(close, 1) > 0
indicator.mom(source, length)floatlength bars

Momentum: identical to change — the difference between source now and length bars back.

Python: indicator.mom(close, 10) > 0
Pine:   ta.mom(close, 10) > 0
indicator.roc(source, length)floatlength bars

Rate of change: percentage difference between source now and length bars back.

Python: indicator.roc(close, 10) > 0
Pine:   ta.roc(close, 10) > 0
indicator.crossover(a, b)boolmax(a, b) + 1 bars

True on the bar where a crosses from at-or-below b to above b.

Python: indicator.crossover(indicator.sma(close, 20), indicator.sma(close, 50))
Pine:   ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
indicator.crossunder(a, b)boolmax(a, b) + 1 bars

True on the bar where a crosses from at-or-above b to below b.

Python: indicator.crossunder(indicator.sma(close, 20), indicator.sma(close, 50))
Pine:   ta.crossunder(ta.sma(close, 20), ta.sma(close, 50))
indicator.atr(length)float20 × length + 1 bars

Average True Range: Wilder's moving average of the true range (uses high, low and close).

Python: indicator.atr(14) > 100
Pine:   ta.atr(14) > 100
indicator.vwma(source, length)floatlength − 1 bars

Volume-weighted moving average of source over length bars (uses volume).

Python: close > indicator.vwma(close, 20)
Pine:   close > ta.vwma(close, 20)
indicator.cci(source, length)floatlength − 1 bars

Commodity Channel Index: distance of source from its length-bar average, scaled by mean deviation.

Python: indicator.cci(close, 20) > 100
Pine:   ta.cci(close, 20) > 100
indicator.cross(a, b)boolmax(a, b) + 1 bars

True on the bar where a and b cross in either direction; a tie never preceded by a strict relation does not arm it, unlike crossover/crossunder.

Python: indicator.cross(close, indicator.sma(close, 20))
Pine:   ta.cross(close, ta.sma(close, 20))
indicator.rising(source, length)boollength bars

True once source has risen for length consecutive bars.

Python: indicator.rising(close, 3)
Pine:   ta.rising(close, 3)
indicator.falling(source, length)boollength bars

True once source has fallen for length consecutive bars.

Python: indicator.falling(close, 3)
Pine:   ta.falling(close, 3)
indicator.macd(source, fast_length, slow_length, signal_length)float10 × max(fast_length, slow_length) + 10 × signal_length bars

Moving Average Convergence Divergence: the fast ema minus the slow ema, a signal line that's the ema of that difference, and their own difference as the histogram. Returns 3 values: unpack them, e.g. a, b, c = indicator.macd(...) in Python or [a, b, c] = ta.macd(...) in Pine.

Python: macd_line, signal_line, histogram = indicator.macd(close, 12, 26, 9)
        indicator.crossover(macd_line, signal_line)
Pine:   [macdLine, signalLine, histogram] = ta.macd(close, 12, 26, 9)
        ta.crossover(macdLine, signalLine)
indicator.bb(source, length, mult)floatlength − 1 bars

Bollinger Bands: the middle band is the SMA, the outer bands are the (biased) standard deviation scaled by mult around it. Returns 3 values: unpack them, e.g. a, b, c = indicator.bb(...) in Python or [a, b, c] = ta.bb(...) in Pine.

Python: middle, upper, lower = indicator.bb(close, 20, 2)
        close > upper
Pine:   [middle, upper, lower] = ta.bb(close, 20, 2)
        close > upper
indicator.kc(source, length, mult)float20 × length + 1 bars

Keltner Channels: the middle line is the EMA, the outer bands are the EMA of the true range scaled by mult around it (uses high, low and close). Returns 3 values: unpack them, e.g. a, b, c = indicator.kc(...) in Python or [a, b, c] = ta.kc(...) in Pine.

Python: middle, upper, lower = indicator.kc(close, 20, 2)
        close > upper
Pine:   [middle, upper, lower] = ta.kc(close, 20, 2)
        close > upper
indicator.dmi(di_length, adx_smoothing)float20 × (di_length + adx_smoothing) + 1 bars

Directional Movement Index: +DI, -DI and ADX, from the smoothed directional movement and true range (uses high, low and close). Returns 3 values: unpack them, e.g. a, b, c = indicator.dmi(...) in Python or [a, b, c] = ta.dmi(...) in Pine.

Python: plus_di, minus_di, adx = indicator.dmi(14, 14)
        adx > 25
Pine:   [plusDi, minusDi, adx] = ta.dmi(14, 14)
        adx > 25
indicator.supertrend(factor, length)float20 × length + 1 bars

Supertrend: a band that flips side and direction (1 down, -1 up) whenever price closes through it (uses high, low and close). Returns 2 values: unpack them, e.g. a, b = indicator.supertrend(...) in Python or [a, b] = ta.supertrend(...) in Pine.

Python: supertrend, direction = indicator.supertrend(3, 10)
        direction < 0
Pine:   [supertrend, direction] = ta.supertrend(3, 10)
        direction < 0
indicator.stoch(source, high, low, length)floatlength − 1 bars

Stochastic Oscillator: where source sits within the length-bar high/low range, scaled to 0-100 (not clamped).

Python: indicator.stoch(close, high, low, 14) < 20
Pine:   ta.stoch(close, high, low, 14) < 20
indicator.mfi(source, length)floatlength bars

Money Flow Index: a volume-weighted RSI-like oscillator (0–100) over length bars (uses volume).

Python: indicator.mfi(hlc3, 14) > 80
Pine:   ta.mfi(hlc3, 14) > 80
indicator.hma(source, length)floatlength + √length − 2 bars

Hull moving average: a fast, smooth average -- wma(2 × wma(source, length / 2) − wma(source, length), √length).

Python: close > indicator.hma(close, 21)
Pine:   close > ta.hma(close, 21)
indicator.sum(source, length)floatlength − 1 bars

Sum of the last length values (Pine: math.sum).

Python: indicator.sum(volume, 20) > 1000
Pine:   math.sum(volume, 20) > 1000
indicator.median(source, length)floatlength − 1 bars

Median of the last length values.

Python: close > indicator.median(close, 20)
Pine:   close > ta.median(close, 20)
indicator.dev(source, length)floatlength − 1 bars

Mean absolute deviation from the length-bar average.

Python: indicator.dev(close, 20) > 50
Pine:   ta.dev(close, 20) > 50
indicator.variance(source, length)floatlength − 1 bars

Variance of the last length values (biased, like stdev²).

Python: indicator.variance(close, 20) > 100
Pine:   ta.variance(close, 20) > 100
indicator.percentrank(source, length)floatlength bars

Percent of the previous length values at or below the current one, 0–100.

Python: indicator.percentrank(close, 50) > 80
Pine:   ta.percentrank(close, 50) > 80
indicator.linreg(source, length, offset=0)floatlength − 1 bars

Linear regression line over length bars, read offset bars back from its newest end.

Python: close > indicator.linreg(close, 50, 0)
Pine:   close > ta.linreg(close, 50, 0)
indicator.cmo(source, length)floatlength bars

Chande Momentum Oscillator: 100 × (gains − losses) / (gains + losses) over length bars, −100..100.

Python: indicator.cmo(close, 14) > 50
Pine:   ta.cmo(close, 14) > 50
indicator.wpr(length)floatlength − 1 bars

Williams %R: where the close sits under the length-bar high, −100..0 (uses high, low and close).

Python: indicator.wpr(14) < -80
Pine:   ta.wpr(14) < -80
indicator.range(source, length)floatlength − 1 bars

Highest minus lowest of the last length values.

Python: indicator.range(close, 20) > 500
Pine:   ta.range(close, 20) > 500
indicator.correlation(source1, source2, length)floatmax(source1, source2) + length − 1 bars

Correlation of two series over length bars, −1..1.

Python: indicator.correlation(close, volume, 20) > 0.5
Pine:   ta.correlation(close, volume, 20) > 0.5
indicator.tr(handle_na=0)float1 bar

True range: the bar's range including a gap from the previous close; on the first bar na, or high − low with handle_na=1 (Pine: ta.tr, or ta.tr(true)).

Python: indicator.tr() > indicator.atr(14) * 2
Pine:   ta.tr > ta.atr(14) * 2
indicator.cum(source)floatsource's own

Running total of source from the first loaded bar.

Python: indicator.cum(volume) > 0
Pine:   ta.cum(volume) > 0
indicator.obv()float1 bar

On-balance volume: the running total of volume, added on up closes and taken away on down closes (Pine: ta.obv).

Python: indicator.obv() > indicator.ema(indicator.obv(), 20)
Pine:   ta.obv > ta.ema(ta.obv, 20)
indicator.accdist()floatnone

Accumulation/distribution: the running total of volume weighted by where the close sits in the bar's range (Pine: ta.accdist).

Python: indicator.accdist() > indicator.ema(indicator.accdist(), 20)
Pine:   ta.accdist > ta.ema(ta.accdist, 20)
indicator.vwap(source)floatsource's own

Volume-weighted average price, restarting at each UTC day (Pine: ta.vwap is ta.vwap(hlc3)).

Python: close > indicator.vwap(hlc3)
Pine:   close > ta.vwap
indicator.barssince(condition)floatthe condition's own

Bars since the condition was last true (0 on a true bar); na before the first.

Python: indicator.barssince(indicator.crossover(close, indicator.sma(close, 20))) < 5
Pine:   ta.barssince(ta.crossover(close, ta.sma(close, 20))) < 5
indicator.valuewhen(condition, source, occurrence=0)floatmax(condition, source) bars

source on the bar the condition was true -- the latest one for occurrence 0, the one before for 1, and so on.

Python: close > indicator.valuewhen(indicator.crossover(close, indicator.sma(close, 20)), low, 0)
Pine:   close > ta.valuewhen(ta.crossover(close, ta.sma(close, 20)), low, 0)
indicator.highestbars(source, length)floatlength − 1 bars

Offset of the highest value in the last length bars: 0 for this bar, −1 for the previous, … (Pine: also ta.highestbars(length) on high).

Python: indicator.highestbars(high, 20) == 0
Pine:   ta.highestbars(high, 20) == 0
indicator.lowestbars(source, length)floatlength − 1 bars

Offset of the lowest value in the last length bars: 0 for this bar, −1 for the previous, … (Pine: also ta.lowestbars(length) on low).

Python: indicator.lowestbars(low, 20) == 0
Pine:   ta.lowestbars(low, 20) == 0
indicator.pivothigh(source, leftbars, rightbars)floatleftbars + rightbars bars

The pivot high's value, rightbars bars after it (na elsewhere): a bar above the leftbars before it and the rightbars after it (Pine: also ta.pivothigh(leftbars, rightbars) on high).

Python: not is_na(indicator.pivothigh(high, 5, 5))
Pine:   not na(ta.pivothigh(5, 5))
indicator.pivotlow(source, leftbars, rightbars)floatleftbars + rightbars bars

The pivot low's value, rightbars bars after it (na elsewhere): a bar below the leftbars before it and the rightbars after it (Pine: also ta.pivotlow(leftbars, rightbars) on low).

Python: not is_na(indicator.pivotlow(low, 5, 5))
Pine:   not na(ta.pivotlow(5, 5))
indicator.swma(source)float3 bars

Symmetrically weighted moving average over 4 bars (weights 1, 2, 2, 1).

Python: close > indicator.swma(close)
Pine:   close > ta.swma(close)
indicator.alma(source, length, offset=0.85, sigma=6)floatlength − 1 bars

Arnaud Legoux moving average: Gaussian weights centred at offset × (length − 1), width length / sigma.

Python: close > indicator.alma(close, 9, 0.85, 6)
Pine:   close > ta.alma(close, 9, 0.85, 6)
indicator.tsi(source, short_length, long_length)float1 + 10 × (short_length + long_length) bars

True strength index: double-smoothed momentum over double-smoothed absolute momentum, −1..1.

Python: indicator.tsi(close, 13, 25) > 0
Pine:   ta.tsi(close, 13, 25) > 0
indicator.cog(source, length)floatlength − 1 bars

Center of gravity: a front-weighted average position of source over length bars.

Python: indicator.cog(close, 10) > indicator.cog(close, 10)[-1]
Pine:   ta.cog(close, 10) > ta.cog(close, 10)[1]
indicator.sar(start=0.02, inc=0.02, max=0.2)float1 bar

Parabolic SAR: a trailing stop that accelerates by inc up to max each new extreme (uses high and low).

Python: close > indicator.sar(0.02, 0.02, 0.2)
Pine:   close > ta.sar(0.02, 0.02, 0.2)
indicator.bbw(source, length, mult)floatlength − 1 bars

Bollinger Bands width: (upper − lower) / middle, in percent.

Python: indicator.bbw(close, 20, 2) < 5
Pine:   ta.bbw(close, 20, 2) < 5
indicator.kcw(source, length, mult)floatas indicator.kc

Keltner Channels width: (upper − lower) / middle (uses high, low and close).

Python: indicator.kcw(close, 20, 1.5) < 0.05
Pine:   ta.kcw(close, 20, 1.5) < 0.05
indicator.mode(source, length)floatlength − 1 bars

Most frequent of the last length values (the smallest of equally frequent ones).

Python: close > indicator.mode(math.round(close), 20)
Pine:   close > ta.mode(math.round(close), 20)
indicator.percentile_linear_interpolation(source, length, percentage)floatlength − 1 bars

The percentage-th percentile of the last length values, interpolating between ranks.

Python: close > indicator.percentile_linear_interpolation(close, 50, 80)
Pine:   close > ta.percentile_linear_interpolation(close, 50, 80)
indicator.percentile_nearest_rank(source, length, percentage)floatlength − 1 bars

The percentage-th percentile of the last length values, by the nearest rank.

Python: close > indicator.percentile_nearest_rank(close, 50, 80)
Pine:   close > ta.percentile_nearest_rank(close, 50, 80)
indicator.rci(source, length)floatlength bars

Rank correlation index: how closely the last length values rank in time order, −100..100.

Python: indicator.rci(close, 9) > 80
Pine:   ta.rci(close, 9) > 80
indicator.pvt()float1 bar

Price-volume trend: the running total of volume times the close's relative change (Pine: ta.pvt).

Python: indicator.pvt() > indicator.ema(indicator.pvt(), 20)
Pine:   ta.pvt > ta.ema(ta.pvt, 20)
indicator.nvi()float1 bar

Negative volume index: follows the close only on bars of falling volume, from 1 (Pine: ta.nvi).

Python: indicator.nvi() > indicator.ema(indicator.nvi(), 255)
Pine:   ta.nvi > ta.ema(ta.nvi, 255)
indicator.pvi()float1 bar

Positive volume index: follows the close only on bars of rising volume, from 1 (Pine: ta.pvi).

Python: indicator.pvi() > indicator.ema(indicator.pvi(), 255)
Pine:   ta.pvi > ta.ema(ta.pvi, 255)
indicator.iii()floatnone

Intraday intensity index: (2 × close − high − low) / ((high − low) × volume) (Pine: ta.iii).

Python: indicator.iii() > 0
Pine:   ta.iii > 0
indicator.wad()float1 bar

Williams accumulation/distribution: the running total of each close against the true range's far end (Pine: ta.wad).

Python: indicator.wad() > indicator.ema(indicator.wad(), 20)
Pine:   ta.wad > ta.ema(ta.wad, 20)
indicator.wvad()floatnone

Williams variable accumulation/distribution: (close − open) / (high − low) × volume (Pine: ta.wvad).

Python: indicator.wvad() > 0
Pine:   ta.wvad > 0
indicator.max(source)floatsource's own

Highest value so far, from the first loaded bar.

Python: close >= indicator.max(high)
Pine:   close >= ta.max(high)
indicator.min(source)floatsource's own

Lowest value so far, from the first loaded bar.

Python: close <= indicator.min(low)
Pine:   close <= ta.min(low)

Market data

A strategy, in Python or Pine, can read the catalog's time series next to the candles: market_data.<key> is the series' value on each bar, usable like close — in any function, in indicator.* sources (Pine's own functions there), with history:

fear_n_greed = market_data.fear_n_greed
liq_long, liq_short = market_data.liquidations


def enter_long():
    return fear_n_greed < 25 and fear_n_greed[-1] >= 25

History is negative-indexed as everywhere in Python: fear_n_greed[-1] is the previous bar. A series with several parts, such as liquidations, is unpacked like indicator.macd. The Market data menu over the chart adds a declaration such as fear_n_greed = market_data.fear_n_greed under your inputs, and each series is drawn in a pane of its own after a backtest.

In Pine the same series is a series like any other, with Pine's history and unpacking:

fg = market_data.fear_n_greed
[liq_long, liq_short] = market_data.liquidations
if fg < 25 and fg[1] >= 25 and not na(liq_long)
    strategy.entry("L", strategy.long)
SeriesDescriptionWhere
market_data.fear_n_greedFear & Greed Index. The Crypto Fear & Greed Index from alternative.me: one value a day from 0 (extreme fear) to 100 (extreme greed), for the crypto market as a whole.Any market
market_data.fundingFunding rate. The funding rate of the perpetual contract you trade, at each funding time, as the exchange publishes it: positive when longs pay shorts, negative when shorts pay longs.Perpetual futures
market_data.open_interestOpen interest. The value of all open contracts on the market, in USD, every hour. Rising open interest means new positions are being opened; falling, that they are being closed.Perpetual futures, timeframe 1h or longer
market_data.long_shortLong/short ratio. How many accounts hold longs against how many hold shorts on the market, every hour, as the exchange publishes it.Perpetual futures, timeframe 1h or longer
market_data.top_long_shortTop traders long/short. The same long/short ratio among the exchange's largest traders, every hour, as the exchange publishes it.Perpetual futures, timeframe 1h or longer
market_data.takerTaker buy/sell volume. Market buy volume against market sell volume each hour, as a ratio: above 1, buyers are crossing the spread more than sellers.Perpetual futures, timeframe 1h or longer
market_data.liquidations (long, short)Liquidations. The USD value of long and of short positions the exchange liquidated each hour.Perpetual futures, timeframe 1h or longer

What a bar sees

A bar's value is the one known at the bar's close, never a later one, so a backtest does not look ahead. A series is na before its data starts; test it with is_na(x).

A live robot reads the series right after its bar closes. One reading open interest or long/short waits up to 13 seconds after the close for the exchange's snapshot of the latest hour; if it doesn't come in time, that hour is na. The latest hour of taker and liquidations is usually not there yet: on 1h a live robot usually sees na for them. A later backtest of the same period shows the full values. The robot is the honest one: it traded on what it knew then.

The Fear & Greed Index is stamped at 00:00 UTC but is published and loaded a little later, so a value counts from 02:00 UTC of its day. A 1d bar sees the value of the day it opened, the same in a backtest and in a robot that decides at 00:00.

The history of a derivatives series (open interest, long/short, taker volume, liquidations) is loaded for a market the first time something reads it. Until it arrives its values are na, and the backtest says so in a note.

Limit

On a free account a strategy reads up to 3 market data series. Paid accounts are coming soon. The limit counts every distinct market_data.<key> written in the code, including inside functions that are never called. A series the chart's market or timeframe can't have (funding on a spot market, open interest on a 15m chart) is an error before the run.

math.*

SignatureDescription
math.abs(value)Absolute value; na in, na out.
math.max(a, b, ...)Largest of two or more values; na if any is na.
math.min(a, b, ...)Smallest of two or more values; na if any is na.
math.avg(a, b, ...)Average of the values; na if any is na.
math.round(value, precision)Rounded half away from zero (2.5 → 3); with a precision, to that many decimals.
math.floor(value)Largest whole number not above the value.
math.ceil(value)Smallest whole number not below the value.
math.sign(value)1, 0 or -1 by the value's sign.
math.sqrt(value)Square root; na below 0.
math.pow(base, exponent)base to the power of exponent; na when it isn't a real number.
math.exp(value)e to the power of the value.
math.log(value)Natural logarithm; na at 0 and below.
math.log10(value)Base-10 logarithm; na at 0 and below.
math.sin(angle)Sine of an angle in radians.
math.cos(angle)Cosine of an angle in radians.
math.tan(angle)Tangent of an angle in radians.
math.asin(value)Arcsine, in radians; na outside -1..1.
math.acos(value)Arccosine, in radians; na outside -1..1.
math.atan(value)Arctangent, in radians.
math.todegrees(radians)Radians to degrees.
math.toradians(degrees)Degrees to radians.

Built-ins

na is the missing-data value: it propagates through arithmetic, and any comparison with it — including na == na — is false, matching TradingView. Use is_na(x) to test for it, and nz(x) / nz(x, y) to substitute a fallback (default 0) when x is na. nz can also appear inside an arithmetic indicator.* source or value argument (see indicator.* functions), e.g. indicator.sma(nz(close - close[-1], 0), 10).

SignatureDescription
na

The missing-data value. Propagates through arithmetic; any comparison with na, including na == na, is false — check for it with is_na(...) instead.

Python: nz(close if close > open else na, -1) > 0
Pine:   nz(close > open ? close : na, -1) > 0
is_na(x)

True when x is na.

Python: is_na(close[-1])
Pine:   na(close[1])
nz(x, y=0)

x, or y (default 0) when x is na. Also usable inside an arithmetic ta.* source or value argument, e.g. ta.sma(nz(close - close[1], 0), 10).

Python: nz(close - close[-1], 0) > 0
Pine:   nz(close - close[1], 0) > 0

Strategy log

Write lines from the code to see what it saw on a bar: log.info(...), log.warning(...) and log.error(...) — TradingView's Pine Logs. Each line keeps the time of the bar it was written on. A backtest lists the lines of the bars it played (the warm-up writes none) in the Logs tab beside Notes, oldest first, times in your time zone; a click on a line moves the chart to its bar. A robot's page has a Logs tab too, with the lines of every bar it has closed since it started — yours alone: a published robot's public page never shows them.

Python: a log call is a line of its own in on_bar() (the one function run once on every bar, in order — define it just for this if the strategy has no state). The message is text, an f-string, or a value: log.info(f"rsi {rsi:.1f} {'up' if close > open else 'down'}"). Format specs: Python's .2f, ,.0f, .1% or Pine's patterns #.##, 0.00, #,##0.00; na is written NaN, true/false as Pine writes them. math.log(x) is still the logarithm.

fast = indicator.ema(close, 12)
slow = indicator.ema(close, 26)


def on_bar():
    if indicator.crossover(fast, slow):
        log.info(f"cross up at {close:.2f}, rsi {indicator.rsi(close, 14):.1f}")
    if position.is_long and position.pnl_percent < -5:
        log.warning(f"down {position.pnl_percent:.1f}% since entry")

Pine: anywhere in the script — in if/else, loops and functions — with the message as text, + of texts, str.tostring(value[, "#.##"]), str.format("{0} > {1,number,#.##}", a, b) or log.info(format, values...). Converting to Python keeps them, in on_bar().

Limits: a backtest keeps the latest 1,000 lines and says how many earlier ones it let go; a robot keeps its latest 500. A line is cut at 500 characters, and control characters become spaces. Code with no log calls pays nothing for the log.

SignatureDescription
log.info(message)

Writes an info line to the strategy log, with the time of the bar it is written on.

Python: log.info(f"close {close:.2f}, rsi {indicator.rsi(close, 14):.1f}")
Pine:   log.info("close " + str.tostring(close, "#.##") + ", rsi " + str.tostring(ta.rsi(close, 14), "#.#"))
log.warning(message)

Writes a warning line to the strategy log: the Logs tab's count turns to its warning tone.

Python: log.warning(f"equity {position.equity:,.2f} is {'up' if position.net_profit > 0 else 'down'}")
Pine:   log.warning("{0} is below {1}", close, ta.sma(close, 50))
log.error(message)

Writes an error line to the strategy log. The backtest or the robot carries on: it is a line, not a stop.

Python: log.error("no cash left for an entry")
Pine:   log.error(str.format("low {0,number,#.##} under the 50-bar low {1,number,#.##}", low, ta.lowest(low, 50)[1]))

Inputs

SignatureDescription
input.int(defval, title)A whole-number parameter: a number field in the Parameters tab.
input.float(defval, title)A decimal parameter: a number field in the Parameters tab.
input.bool(defval, title)True or false: a checkbox in the Parameters tab. Read it as a condition -- if use_filter and close > trend.
input.string(defval, title, options=[...])Text: a select of its options in the Parameters tab, a text field without them. Compare it with text (ma_type == "EMA") to pick a ta.* or a branch -- decided when the code compiles, so the branch it doesn't pick is never computed.
input.source(defval, title)A price series -- open, high, low, close, hl2, hlc3, ohlc4 (and hlcc4 in Pine): a select in the Parameters tab, fed wherever the input is read, e.g. ta.sma(src, 20).
input.timeframe(defval, title, options=[...])A timeframe for request.security: a select of the timeframes ("4h", "1d" in Python; "240", "D" in Pine) or of its own options in the Parameters tab.

title is optional (it defaults to the variable name); minval and maxval are optional bounds. In Pine, group, tooltip, inline, step, confirm and display are accepted but ignored. Pine also has input.enum (a select of the enum's members, by their titles) and input.session (a text field checked as HHMM-HHMM, several with commas, optionally :days) -- see Pine support.

A value changed in the Parameters tab is written over the default in the code -- one edit, which Ctrl/Cmd+Z takes back -- so the code you save, copy back to TradingView or run as a robot carries the values, and typing a new default in the code changes the field. A default the code computes (a constant's name, arithmetic) is left as it is: the field says Value set here, not in the code, and the value goes with the run.

A number or true/false is read by the run. A choice -- input.string, input.source, input.timeframe, and in Pine input.enum and input.session -- is decided when the code compiles: another value compiles it again with that value, so indicator.ema(src, n) if ma_type == "EMA" else indicator.sma(src, n) only ever computes the one it picks.

Backtest rules

QTrader holds one position at a time — flat, long or short. Signals are read on the close of bar i; any order they queue fills at the open of bar i + 1. On every bar, in order:

  1. a pending order from the previous bar (entry, exit or reversal) fills at this bar's open;
  2. if a position is open, its stop-loss/take-profit is checked against this bar's high/low — including the bar the position was just opened on (see Stop-loss and take-profit);
  3. signals run against the (possibly just-updated) position, and queue the next pending order:
    • flat: enter_long() opens a long, enter_short() opens a short. If both are true on the same bar, they fill in the script's order, as TradingView fills a script's orders — in Pine the order its strategy.entry calls run in, in Python the order the two functions are defined in. With a position size over half the equity the first opens and the second is rejected; with half or less the first opens and reverses into the second at the same open (a trade that opens and closes at one price). A robot started on an older engine version opens the long;
    • long: enter_short() reverses to short (the long closes and the short opens in a single fill at the next open), else exit_long() closes it;
    • short: enter_long() reverses to long, else exit_short() closes it;
    • a function the strategy doesn't define is never called, and counts as false;
  4. equity is marked at this bar's close.

Shorts are accounted like longs, mirrored: opening one adds its notional to cash and closing it subtracts the buy-back. Leverage, liquidation and funding are opt-in and perpetual-only — see Leverage, liquidation, funding, fees; without them a short has none. Position size — a percentage of current cash — is computed the same way for both sides; on a reversal it's computed after the old side's cash is freed. A Pine script can set it with default_qty_type: strategy.fixed enters default_qty_value contracts, strategy.cash that much money (over the close of the signal bar), strategy.percent_of_equity a percentage of the equity; a size set by the code disables the Position size field, and without one TradingView enters 1 contract where QTrader uses the Position size. Commission is charged on both the entry and the exit, as a percentage of the traded notional. Trades record a side (long/short) and an exit_reason (signal, stop-loss, take-profit, trailing stop, liquidation, or open for a still-open trade at the period's end).

If cash is at or below zero, new entries (including the opening leg of a reversal) are skipped; Notes then reports "From <date> the account has no cash left: new entries are skipped".

A position still open when the period ends is included in the results, valued at the last bar's close; its tracked fees cover only the entry (there was no exit to charge a commission on).

Before the requested period, QTrader reads extra warm-up bars so indicator.* results aren't na at the first visible bar; if fewer warm-up bars exist than an indicator needs, Notes says that early signals may differ from TradingView.

Leverage, liquidation, funding, fees

A backtest on a perpetual market (a .P ticker) can model futures trading. It is off by default: Leverage 1 and Slippage 0 give the plain backtest without margin or price impact. Both are in the Parameters tab, and in strategy(...) as leverage and slippage_percent. Pine's margin_long and margin_short are ignored: in TradingView they don't change the position's size either, so a Pine strategy trades with leverage only when the Leverage setting says so.

Fees

The commission is charged on every fill, entry and exit, as a percentage of the traded notional. Where nothing sets it — no value in the Parameters tab, none in the code — QTrader uses the taker fee of the market's exchange at its base tier, and the field says whose: for example "Binance futures taker 0.05%". (TradingView's default is 0, so a translated Pine strategy with no commission_value now costs more here than there.) For a market with no fee on file the commission is 0.1%. Every fill is a taker fill: limit entries and take-profits pay the taker fee too, and VIP tiers and token discounts are not modeled.

Slippage

slippage_percent (0–5) makes a fill worse by that percentage of the price: a buy fills at price × (1 + s), a sell at price × (1 − s). It applies to market entries and exits on a signal, stop-losses, trailing stops, stop entries and liquidations. Limit entries and take-profits are not slipped: they fill at their own price. It is not available together with pyramiding or partial exits yet.

In Pine, strategy(slippage=N) moves market and stop fills N price steps worse instead of a percentage, and then slippage_percent is ignored. A robot started before engine version 6 sizes from the Parameters tab and ignores slippage.

Leverage and liquidation

With leverage L the position is L times the margin: the same percentage of equity as before is put up as margin, and the position is that many times larger. Margin is isolated — the position can lose its own margin, not the rest of the account. It is liquidated when the price reaches, with E the entry price and m the exchange's maintenance margin rate:

long:   E × (1 − 1/L + m)
short:  E × (1 + 1/L − m)

The position then closes at that price, like a stop, with the usual commission and slippage, and the trade's exit reason is Liquidation; Liquidations in the results counts them. With leverage 1 there is no liquidation. Leverage needs a perpetual market. With pyramiding, each entry reserves its own isolated margin and has its own liquidation price; a partial exit releases the corresponding share of that entry. Remaining entries keep their own margin.

Funding

A perpetual pays funding at the exchange's own intervals. QTrader reads the exchange's funding rate history and, on the bar whose interval holds a funding time, charges a position that is open then side × quantity × close × rate: a long pays when the rate is positive and receives when it is negative, a short the other way round. Each trade's Funding column is the sum for that trade, and it is part of its P&L. Where the exchange has no history for the period, or it can't be read right now, no funding is charged and Notes says so — as it does when the history starts after the period does.

What is not modeled

  • maker fees and fee tiers — every fill pays the base-tier taker fee;
  • cross margin — each position stands alone, with no other position's or the wallet's balance behind it;
  • the mark price — candles are last-trade prices, and an exchange liquidates on its mark price, so the real liquidation can come a little earlier or later (Notes says this on a run that had a liquidation);
  • maintenance-margin tiers by position size and by symbol — the rate of the exchange's first tier for BTC is used for every symbol on it, and a liquidation fee or insurance-fund charge is not added;
  • changes of leverage or margin during a trade, and auto-deleveraging.

A robot with leverage sizes its orders the same way (margin × leverage); the leverage has to be set on the exchange account separately, and a check on the robot says so.

Metrics

MetricMeaning
Net profitFinal equity minus initial capital, in quote currency and as a percentage. Includes an open trade at the last close, noted as "incl. N open trade(s)".
TradesNumber of trades (closed, plus one still-open trade if the period ends mid-position).
Win ratePercentage of trades with positive P&L; shown as "—" when there are no trades.
Profit factorGross profit divided by gross loss; shown as "—" when there are no losing trades to divide by.
Max drawdownThe largest percentage drop from a running peak of the equity curve.
Buy & holdPercentage change from the period's first bar open to the last bar's close, for comparison with the strategy's own return.
FeesThe commission of all trades, including the entry of one still open — shown under the metrics. See Leverage, liquidation, funding, fees.
FundingFunding paid (negative) or received over all trades; shown only when some was charged.
LiquidationsHow many positions would have been liquidated; shown only when there were any.

Pine support

FeatureStatusNote
//@version=4, 5 and 6supportedthe version line is optional; v4's un-namespaced sma(...), crossover(...), max(...), iff(...) and input(..., type=input.integer) are read as today's ta.*, math.* and typed inputs, and when= on strategy.entry/close works as an if around the call (security(...) is read as request.security(...), study(...) as indicator(...)); other version numbers are rejected
strategy(title, initial_capital, default_qty_type, default_qty_value, commission_type, commission_value, slippage)supporteddefault_qty_type=strategy.fixed enters default_qty_value contracts on every entry, strategy.cash default_qty_value of money over the close of the signal bar, strategy.percent_of_equity a percentage of the equity; a default_qty_value with no type is fixed, as in TradingView; with neither, the Position size from the Parameters tab (TradingView enters 1 contract); a size the code sets disables the Position size field. A commission_type other than strategy.commission.percent falls back to the Parameters tab with a warning instead of erroring; other named arguments are accepted, and one QTrader does not recognize prints its own warning; a missing commission_value is the market's taker fee (TradingView uses 0). slippage=N moves market and stop fills N price steps worse (not limit fills, not with pyramiding, partial exits or strategy.order yet), in place of the Slippage setting. A robot started before engine version 6 sizes from the Parameters tab and ignores slippage
strategy.entry(id, strategy.long | strategy.short)supportedseveral ids per direction open the same position (one entry at a time unless strategy(pyramiding=N)), and an exit or close from any of them closes it; the same id cannot be used for both long and short; qty=N enters N contracts (coins) instead of the position size from strategy(...)'s default_qty_type/default_qty_value or the Parameters tab -- N computed on the bar too, e.g. strategy.equity * risk / stopDistance, taken where the call is; an entry whose margin (N times the price, over the leverage) is more than the equity is not opened (Pine v6's margin of 100%; the Notes tab says from when), and a qty that is na or not above 0 drops the entry, as in TradingView; a live robot sends N as the order's quantity, rounded down to the exchange's lot size. qty= sizes an entry at a price (stop=/limit=) the same way -- a robot started before engine version 4 ignores it there with a warning -- and a robot started before engine version 3 ignores qty= (sizing from the settings, as it always did); if a long and a short entry both fire on the same bar while flat, they fill in the order the script's strategy.entry calls run, as in TradingView: with a position size over half the equity (Pine v6's default margin of 100%) the first opens and the second is rejected; with half or less the first opens and at once reverses into the second at the same open, a trade that opens and closes on one price; v4 and v5 scripts are treated as v6 here (in TradingView their default margin is 0, and they always reverse); a robot started before engine version 2 still opens the long
opposite-side strategy.entry while a position is opensupportedreverses the position — closes the current side and opens the other at the same next-bar open — exactly as in TradingView
strategy.close(id), strategy.close_all()supportedcloses the entry on the matching side (long or short); qty_percent=X closes X% of the position at the next open, the oldest entries first (each closed part is a trade of its own); qty= in contracts is not supported yet. Backtests only: a live robot refuses partial closes for now
strategy.position_size, strategy.position_avg_pricesupportedread-only, translated to position.size and position.entry_price
strategy.exit(id, from_entry, stop=, limit=)supportedstop and limit at any price -- close - 2 * ta.atr(14), low[1], a value from an input: the level is set where the strategy.exit call is reached (inside an if: on the bars the if runs, kept until it runs again), as TradingView places or replaces the exit order there; on a live robot it closes at market within about a minute after the price touches it. strategy.position_avg_price * F stays a percent of the entry fill (F is a number or (1 - x) / (1 + x) with x a number or an input), which a live robot's TradeAdapter connection mirrors as its own stop/target; with both, the stricter stop and the nearer target win. from_entry picks the side (omitted: every side the script enters). loss= and profit= are ticks of syminfo.mintick from the entry fill, active from the fill bar. On that bar, as in TradingView, a stop or target its open is already past (a price set on the signal bar, before a gap) fills at the open. trail_points (or trail_price) with trail_offset is a trailing stop in ticks: once the price has gone that far in the position's favour, the stop follows the best price since entry -- moved once a bar here, inside the bar on TradingView; with loss= too, the stricter stop wins. qty_percent makes an exit ladder: each strategy.exit of that entry is a step with its own stop and/or target (stop=/limit= prices, loss=/profit= ticks, strategy.position_avg_price * F, a trailing stop as above -- with loss= too, the stricter), closing its qty_percent of the position as entered -- one without qty_percent closes what is left -- up to 4 steps a side, as TradingView's take-profit ladders (TP1 50%, TP2 the rest trailing); backtests only, not together with pyramiding yet. qty= in contracts is not supported yet From engine version 5, as TradingView places an order: its stop and limit prices, loss=/profit= ticks and a trailing stop's prices are rounded to syminfo.mintick (a long's stop and a short's target down, a long's target and a short's stop up; a trailing offset cut to whole ticks); strategy.position_avg_price * F works from the bar after the entry -- TradingView places it at a bar's close, where the average price is first known (with process_orders_on_close, a close already past it fills it there) -- and with several lots at their average price, for every lot; a price set for one trade ends with it (before, it could stop the next trade of that side)
limit and stop orders (limit=, stop= on strategy.entry), strategy.cancel, strategy.cancel_allsupportedthe order is placed where the call is reached and waits until the price reaches it (at the bar's open when it gaps past), it's cancelled, or the position is on its side; an order on the other side of a position reverses it. Its strategy.exit stop and target are armed at the fill and see the rest of that bar -- the extremes after the fill and the move to the close, as TradingView's broker emulator walks it. A live robot sends a market order within about a minute after the price touches the order's price (not under strategy.risk.allow_entry_in yet). oca_name with oca_type=strategy.oca.cancel (or reduce) drops the other orders of the group once one fills. From engine version 5 the price is rounded to syminfo.mintick as TradingView places it (a buy limit and a sell stop down, a buy stop and a sell limit up), and an order that filled and closed on one bar doesn't fill again
input.int, input.float, and untyped input(...)supportedgroup, tooltip, inline, step, confirm and display are ignored; input(defval, ...) takes its type from the default -- a whole number, a fraction, true/false, text or a price series
name = input.int(...) * NUMBER or / NUMBERsupportedthe TradingView percent idiom (e.g. pct = input.float(2.0, "Stop Loss (%)") * 0.01): the parameter itself stays the raw value, and every later use of name in an expression is scaled automatically
input.bool, input.source, input.timesupportedinput.bool is a checkbox in the Parameters tab (the run reads it as 1 or 0); input.source is a select of the price series (open, high, low, close, hl2, hlc3, ohlc4, hlcc4), fed wherever the input is read; input.time is fixed to its default value, with a warning -- change it in the code
input.stringsupporteda select of its options= in the Parameters tab, a text field without them; comparing it with text (== / !=, switch) is decided when compiling, so maType == "EMA" ? ta.ema(close, 20) : ta.sma(close, 20) computes only the branch it picks -- another value compiles the script again with that value, as if written in the code. An input.string inside an expression (long = input.string("Long") == "Long") has no name to edit: it stays fixed to its default, with a warning
input.timeframesupporteda select of the timeframes ("" for the chart's own, 1, 5, 15 ... 240, D, W, M) or of its options= in the Parameters tab -- for request.security(syminfo.tickerid, tf, ...) and comparisons; like input.string it's decided when compiling. The backtest itself always runs on the chart's timeframe
input.symbol, input.text_areasupportedfixed to their default text, with a warning -- the backtest always runs on the chart's market
input.color, color.*, colour variablesignoreda variable holding a colour (color.*, color.new/rgb, #RRGGBB / #RRGGBBAA literals) is dropped with a warning: colours only reach the drawing calls, which QTrader ignores
text in variables: grp = "Risk", longId = "Long", msg = "Buy " + str.tostring(close)supporteda name given text once (never changed with :=) is that text wherever it is read -- a group= or title, a strategy.entry/close/exit id, a comparison with an input.string (mode == "Fast" is decided when compiling); text built from values (+ of texts, str.tostring) or a string changed with := only reaches what takes text -- comment=, alert_message=, alert(), labels; anywhere else is an error saying so. syminfo.ticker, tickerid, prefix, root, basecurrency, currency (the run's market: BTCUSDT, BINANCE:BTCUSDT, BINANCE, BTCUSDT, BTC, USDT; a perpetual's ticker ends in .P), syminfo.type ("crypto"), volumetype ("base"), timezone ("Etc/UTC") and session ("24x7") are text known when compiling: compare them (syminfo.type == "crypto") or test them with str.contains / str.startswith / str.endswith, also through str.upper / str.lower and variables holding them; syminfo.description isn't known. A true/false variable built from them isn't known when compiling, so it can't be a ta.* length (a direct syminfo.type == "crypto" ? 14 : 10 can)
if / else, nested if, around orderssupporteda ta.* call inside a nested if runs on every bar in QTrader, unlike TradingView — assign it to a variable at the top level for identical results
:= / += inside if blockssupportedchange a variable declared at the top level (var or plain) from any depth of if/else; a variable declared inside an if lives in that block only, as in TradingView -- also when := changes it there (float x = na, then x := ...)
var, varip, :=, +=, -=, *=, /=, %=supportedvar / varip keep a value from bar to bar; :=, +=, -=, *=, /=, %= change it. strategy.position_* can be read where such a variable is updated (it's the position after that bar's fills). A ta.* function over such a variable works outside its updates (smooth = ta.ema(acc, 10) at the top level), computed once the variable's values are known -- not where it's updated, and not when those updates read strategy.position_*
user-defined functions (name(x, y) => ...)supportedone-line and multi-line, typed parameters, defaults and named arguments; expanded where they're called, so ta.* inside get concrete arguments; an if/else the function ends with is its value (e.g. picking ta.ema or ta.sma by an input.string); [x, y] at its end returns several values, unpacked with [a, b] = f(...). A function may keep state -- var, :=, if blocks and loops in its body -- and each place it's called keeps its own, as in TradingView; such a function is called on its own line or in a condition, not inside ?: or after and/or. methods too: method f(x, y) => ... is called as x.f(y) (or f(x, y)). Not yet: recursion
switch (x = switch subject / x = switch, or as a statement)supportedas a value over an input.string it picks its arm when compiling; otherwise a chain of ?: (a ta.* inside warns: it runs on every bar). As a statement it's an if / else if chain: an arm runs the call after => or the block below it, `=> na` does nothing. Not yet: value arms with a block below =>
for i = a to b [by step]supporteda loop that only computes values (:=, +=, if, break/continue, its own variables) runs as a real loop: any bounds -- numbers, inputs, values computed on the bar (no loop while an end is na) -- counting down when a > b, as in TradingView; close[i] reads i bars back. Every loop pass on a bar counts against 10,000; past that the backtest stops with the loop's line. A loop that places orders (strategy.* inside) is unrolled when compiling, up to 200 passes: bounds are numbers, or an input.int with a maxval. for v in a and for [i, v] in a go over an array
whilesupporteda loop that only computes values (:=, +=, if, break/continue, its own variables); orders go after it. Counts against the same 10,000 passes a bar as for loops
array.* (float[], array<float>, array.new<float>, a.push(x), ...)supportedarrays of numbers or true/false: array.new_float/int/bool and array.new<T>, array.from, size, get, set, push, pop, shift, unshift, insert, remove, clear, includes, indexof, lastindexof, sum, avg, min, max, range, median, stdev, variance, sort (order.ascending / order.descending), copy, slice, first, last, fill, reverse, concat, abs -- as functions or methods (w.push(close)); a negative index counts from the end. An array is kept from bar to bar with var, else made anew on every bar -- also in a strategy that reads strategy.position_* where it changes the array. and / or and ?: skip the array reads they skip, as in TradingView: array.size(a) > 0 and array.get(a, 0) > close never reads past an empty array. Every element statistic skips na, as in TradingView. Arrays of objects of a type (array.new<Trade>()) are in the type row below. Not yet: arrays of strings, colours or drawings, array.slice as a view of the original (here a copy) -- matrices are in the matrix.* row below
type (user-defined types): type Trade, Trade.new(...), t.stop, t.stop := x, methodssupportedfields of type float, int, bool, string, an array, a map or another type, with defaults (a bool field without one is false, the rest na); Trade.new(...) with positional and named arguments; t.stop reads a field, t.stop := x / t.bars += 1 sets it -- also through a call, pivots.get(0).price := x. Objects are references, as in TradingView: every name holding one sees a change made through any of them, copy() (or Trade.copy(t)) makes a new one holding the same values. var Trade t = na keeps an object from bar to bar, na(t) tests it, a field of an na object reads na and setting one stops the backtest with an error. Objects go into functions and come out of them, method update(Trade this, float price) => ... is called as t.update(close) (a method ending with an if or a change is a statement), array.new<Trade>() holds objects (size, get, set, push, pop, shift, unshift, insert, remove, clear, copy, slice, first, last, reverse, concat, fill; for p in pivots). An entry reads a field where the script reads it -- after the lines above it on that bar, as in TradingView. Text in a field is compared with == / != (and goes into maps): text in quotes, a name holding it or an input.string -- text computed on the bar (str.tostring, syminfo.ticker) can't be stored, nor written into a log line. Fields holding a colour or a drawing (line, label, box, chart.point) are kept nowhere: drawings are ignored. A robot replays a script with objects from the start on every tick (an object changes in place, a snapshot can't hold it), as with arrays. History, as in TradingView: t[1] is the object the variable held a bar back -- the same one for a var changed in place, so t[1].stop reads its stop as it is now; t.stop[1] is the field's value as the script read it there a bar back (on the last bar it got there, inside an if block); the same for a value read out of a map or a matrix, m.get(key)[1]. A field may hold an enum's member. Not yet: history of an object or a field inside a function or a loop (read it at the top level into a variable), == between objects, array.sum/sort/includes & co. on an array of objects, request.security reading a field, a field read of a parameter written without its type (write f(Trade t))
map.* (map.new<string, float>(), m.put(k, v), m.get(k), for [k, v] in m)supportedkeys are numbers, true/false, an enum's members or text (in quotes, a name holding text chosen between texts in quotes, an input.string); values are numbers, true/false, text, arrays or objects of a type. put (gives the value the key had, na if none), get (na for a missing key), contains, remove, size, keys and values (new arrays, in the order the keys were first put), clear, copy, put_all -- as functions or methods. var keeps a map from bar to bar, else it's made anew on every bar; for [key, value] in m goes over it in the order the keys were first put; an entry reads a map where the script reads it. At most 50,000 keys, as in TradingView. A robot replays a script with a map from the start on every tick, as with arrays. Not yet: text keys computed on the bar (str.tostring(close), syminfo.ticker)
matrix.* (matrix.new<float>(rows, columns, initial), m.get(i, j), m.set(i, j, x))supportedmatrices of numbers or true/false (matrix<float>, matrix<int>, matrix<bool>): new, get, set, rows, columns, elements_count, row and col (new arrays), add_row and add_col (with an array of values or na), remove_row and remove_col (give the removed values), fill (with from_row/to_row/from_column/to_column), copy, submatrix, transpose, reverse, reshape, concat, swap_rows, swap_columns, sort (by a column, order.ascending / order.descending), sum and diff (a matrix or a number), mult (a matrix, an array or a number), pow, kron, avg, max, min, median, mode, trace, det, inv, is_square, is_zero, is_identity, is_symmetric, is_diagonal, is_binary -- as functions or methods, named arguments too. var keeps a matrix from bar to bar, else it's made anew on every bar; an index outside the matrix stops the backtest with an error, an na index of get() reads na; statistics skip na; inv of a singular matrix stops the backtest, as in PyneCore. At most 100,000 elements. A robot replays a script with a matrix from the start on every tick, as with arrays. Not yet: matrices of text, objects or drawings, for row in m (loop over m.rows()), eigenvalues, eigenvectors, pinv, rank and the other is_* checks
enum (enum Mode, Mode.fast, input.enum(Mode.fast, "Mode"))supportedmembers with or without a title (fast = "Fast MA"; without one the title is the member's name); == and != between members of the same enum, var / := of an enum type (var Mode m = Mode.fast), enum fields of a type, enum parameters (f(Mode m) => ...), map<Mode, float> keys, array<Mode>, switch over a member. str.tostring(member) -- and a member in str.format or log.info -- writes its title. input.enum is a select of the members, by their titles (or of its options=), in the Parameters tab: a comparison with it is decided when compiling (also inside a function it's passed to), so mode == Mode.fast ? ta.ema(...) : ta.sma(...) or switch mode picks its branch before anything runs -- another member compiles the script again with it. Comparing a member with a number or with another enum's, or < / >, is an error, as in TradingView. A robot resumes an enum from a snapshot like any number
?:, and / or / not, arithmetic, comparisonssupporteda ta.* call inside a ?: branch runs on every bar in QTrader (TradingView only on the bars that branch is taken) -- a warning says so; identical when the condition is decided when compiling (an input.string comparison)
history: close[1]supportedany price series, ta.* result, var variable, or arithmetic and comparisons of them can be indexed -- (close - open)[1], (close > open)[2], an inlined function's value; the offset may be an input.int (close[length]) or an input.int plus or minus a whole number (close[length - 1], as in Ichimoku's displaced spans) or a value computed on the bar -- a loop's counter or a var variable (close[i]); only past bars (offset ≥ 0) are available
ta.* functions (see the table below)supportedthe ta.* functions listed on this page. A length may be a number, an input.int or arithmetic of numbers and inputs -- length / 2, math.round(math.sqrt(length)), int(length * 1.5) -- computed for the run's parameters with its fraction dropped (a Hull MA written out by hand works); a length computed on the bar is an error. ta.kc / ta.kcw take useTrueRange=true (their default); false is not supported yet
[a, b, c] = ta.macd(...) tuple assignmentsupportedunpacks a multi-result ta.* call (ta.macd, ta.bb, ta.kc, ta.dmi, ta.supertrend); use _ to skip an output, only at the top level of the script
arithmetic ta.* sources and values, e.g. ta.sma(close - open, 10)supportedthe source (and value) argument of a ta.* call can be a price series, a ta.* result, or arithmetic of them -- numbers, input parameters, + - * / %, unary -, math.* functions, nz(x[, y]), and history [..] (including on a name bound to arithmetic, e.g. ta.sma(diff[1], 5) after diff = close - open) -- computed as a whole array before the bar loop, not just a bare series/ta.*/name
math.* (abs, max, min, avg, round, floor, ceil, sign, sqrt, pow, exp, log, log10, round_to_mintick, trigonometry; math.pi, math.e)supportedna in, na out; math.round_to_mintick(x) rounds to the price step, a half away from zero (1.005 -> 1.01)
plot, plotshape, plotchar, plotarrow, plotcandle, plotbar, bgcolor, barcolor, hline, fill, alertcondition, label.*, line.*, box.*, table.*, linefill.*, polyline.*ignoredin a strategy the calls are ignored, and so are variables holding a drawing (var label lbl = na, lbl := label.new(...), var table t = table.new(...)): QTrader draws the trades and every ta.* line the script computes by itself; an indicator(...) draws its plot() and hline() lines (see indicator(...) scripts) and ignores the rest, fill included -- the chart has no shading between two lines yet
alert(...)ignoredQTrader does not send alerts yet
na, is_na(x)/na(x), nz(x)/nz(x, y)supportedna is the missing-data value; any comparison with na, including na == na, is false, matching TradingView. is_na(x) (Pine: na(x)) tests for it. not na(x) and x == true also work as the condition of ta.barssince / ta.valuewhen; fixnan(x) is the last value of x that wasn't na. int(x) drops the fraction (na stays na), float(x) is x. nz(x) / nz(x, y) substitutes a fallback (default 0) when x is na, and is also usable inside an arithmetic ta.* source or value expression, e.g. ta.sma(nz(close - close[1], 0), 10)
time, bar_index, year, month, dayofmonth, dayofweek (and dayofweek.sunday … saturday), hour, minute, timestamp(...)supportedcalendar fields are UTC (a crypto exchange's time in TradingView); bar_index counts the bars loaded for the backtest, warm-up included, so it starts lower than TradingView's; timestamp takes numbers (inputs too), a leading UTC or fixed-offset zone like "GMT+3", or one date string like "2024-03-01" -- named zones like "America/New_York" aren't supported yet
hlcc4, secondsupportedhlcc4 is (high + low + close + close) / 4; second is always 0 — bars are a minute or longer
timeframe.isintraday, isdaily, isweekly, ismonthly, isdwm, isminutes, multiplier, timeframe.in_seconds(...), timeframe.change(tf), timeframe.period == "60"; syminfo.pointvalue, minmove, pricescalesupportedread off the chart's bar length (time_close - time), so the same code follows the timeframe it runs on; timeframe.in_seconds("240") is a timeframe string's seconds; timeframe.period itself is text -- compare it, or pass it to request.security. A crypto market's point is worth 1 (syminfo.pointvalue, minmove 1, pricescale 1 / syminfo.mintick). timeframe.change("D") is true on the first bar of each day (UTC; "W" from Monday 00:00, "M" from the 1st, or a timeframe that divides a day like "60" or "240") -- false on the first bar and when the chart's bar is longer than tf; "3D", "2W" and "7" are errors
last_bar_index, time_close, timenowsupportedlast_bar_index is the last loaded bar's bar_index (warm-up included); time_close is the bar's open time plus one bar; timenow is the last loaded bar's close time -- in a backtest that's the end of the period, for a live robot it's now
time(timeframe, session[, timezone]), time_close(...), hour(time[, tz]), minute(...), dayofweek(...), input.sessionsupportedsession filters: time(timeframe.period, "0930-1600") is na outside the session ("2200-0400" overnight, several with commas, ":23456" for weekdays 1 = Sunday … 7 = Saturday, "24x7"), in UTC or a fixed offset like "GMT-5"; time("D") is the start of the bar's day, so ta.change(time("D")) marks a new day; input.session is a text field in the Parameters tab, checked as HHMM-HHMM (several with commas, optionally :days) before it's used
strategy.opentrades, strategy.initial_capital, strategy.max_drawdown, strategy.max_drawdown_percent, input.pricesupportedstrategy.opentrades is the number of open trades: the lots of a position built with pyramiding or strategy.order, else 1 while a position is open (a robot started before engine version 4: 1 while in a position, whatever its lots); strategy.opentrades.entry_price(n) and the other strategy.opentrades.*(n) are trade n's (0 the oldest), na when there is none -- before engine version 4, entry_price(n) and entry_bar_index(n) were the position's whatever n, and an error with pyramiding. strategy.position_size[1], position_avg_price[1], opentrades[1], equity[1], netprofit[1], closedtrades[1] & co. read the value the script saw k bars back -- strategy.position_size[1] == 0 marks the bar after an entry filled; strategy.initial_capital is the run's capital (known on warm-up bars too); strategy.max_drawdown / max_drawdown_percent are TradingView's: from the peak of the closed trades' equity down to the open position's worst price within a bar, in money / percent of that peak; input.price is a number parameter
barstate.isconfirmed, ishistory, isnew, isrealtime, isfirst, islastsupportedon a backtest's bars: confirmed, history and new are true, realtime false; isfirst is the first loaded bar, islast the last -- a live robot also runs on closed bars
strategy.risk.allow_entry_in(strategy.direction.long | short | all)supportedentries open positions on that side only: with long, a strategy.entry short opens nothing while flat and closes the long instead of reversing it (an entry at a price closes it where the price is reached) -- TradingView's 'long exit trades instead of reverse trades' -- and a strategy.order short only takes from the long; short is the mirror. At the top level (inside an if it is ignored with a warning; called twice, the last call counts); the direction may be chosen by an input.string (dir == "Long" ? strategy.direction.long : strategy.direction.all). A robot started before engine version 3 ignores it with a warning: Start again to use it
strategy.risk.max_drawdown, max_intraday_loss and the other risk limitsignoredrisk limits in the code are ignored with a warning
a var / := value an order reads and the script changes after the order on the same barsupportedas in TradingView, a strategy.entry / close / close_all / order reads the script's variables as they are at its line -- if not tradedToday / strategy.entry(...) / tradedToday := true trades once a day; its qty= and qty_percent= too. A robot started before engine version 3 keeps deciding such an order with the values at the end of the bar (it never fires in that example), with a warning naming the order and the variable: Start again to switch
strategy.order(id, strategy.long | strategy.short, qty, limit=, stop=)supporteda market order that adds to or takes from the position, as in TradingView: a buy adds a trade to a long (beyond pyramiding) or opens one, and takes qty from a short, oldest trades first -- past zero the rest opens a long, no reversal of its own; without qty it is sized as an entry. It fills at the next open (with process_orders_on_close, at the close), before the bar's strategy.entry/close, which then act on what it left; strategy.close_all closes what it opened, and from engine version 4 strategy.close(id) of the order's id does, when that id is the only one its side opens with (with several, closing only one id's trades is not supported yet: an error). From engine version 5, limit= or stop= makes it an order at a price: placed where the call is reached (its price rounded to syminfo.mintick), replaced by the next call of its id, waiting until the price reaches it -- several of a bar fill in the order the bar's path reaches them, after the bar's stops and targets -- and dropped by strategy.cancel(id) / cancel_all; an na price makes it a market order, as in TradingView; the script sees the fill at the bar's close (strategy.position_size, position_avg_price, opentrades). Not yet: both limit= and stop= (a stop-limit order), one id at market and at a price, and together with strategy.entry at a price. Backtests only: a live robot refuses it, as pyramiding; a robot started before engine version 3 never had it (it was an error)
strategy.closedtrades.*(n), strategy.opentrades.*(n), strategy.closedtrades.first_indexsupportedthe script's list of trades, as TradingView's strategy sees it on each bar: a trade closed on a bar's path (an order at the open, a stop, a target) is in the list on that bar, one filled at the close (process_orders_on_close) on the next. Closed trades: entry_price, exit_price, entry_bar_index, exit_bar_index, entry_time, exit_time, profit (after both fees), profit_percent (of the entry's value plus its fee), size (negative for a short), commission, max_runup, max_drawdown and their _percent -- the best and worst profit on a bar's high or low while it was open; open trades: entry_price, entry_bar_index, entry_time, size, profit and profit_percent at the bar's close (the exit fee estimated), commission, max_runup, max_drawdown. n is cut to a whole number as int() does; a trade that doesn't exist gives na for a price, a time or a bar index and 0 for the rest; the latest 9,000 closed trades are kept (first_index). Each lot of a pyramided position is a trade; a partial close splits one, its fees and excursions shared by size. entry_id(n) compares with an id -- strategy.closedtrades.entry_id(n) == "Long" -- told by the trade's side, when that id is the only one its side enters with. From engine version 5 strategy.closedtrades.exit_id(n), exit_comment(n), entry_comment(n) and strategy.opentrades.entry_comment(n) compare with text (== and !=), and work in na(), str.contains, str.startswith and str.endswith -- told by the trade's side and what closed it, with TradingView's texts: a strategy.exit's id and its comment_loss / comment_profit / comment_trailing (else comment), "Close entry(s) order L" for strategy.close("L"), "Close position order" for close_all, the entry's id for a reversal, the order's id for a strategy.order; when two texts can close a trade the same way (two strategy.close ids on one side, a comment computed on the bar) the comparison is an error, and the text itself can't be a value (a variable, a log line). A robot whose code reads the list is replayed from its start on every tick (its snapshot would carry every trade)
a variable computed from an array, a map, an object or a var after the script changed it on the bar; an if block's old = history.shift()supportedas in TradingView, the script runs in order: total = m.get(1) or y = s * 2 after s := s + 1 is this bar's value where a := reads it, and an if block's variable set by a call that changes the array (shift, pop, remove...) calls it once, when the block runs. A robot started before engine version 4 keeps the old translation -- the previous bar's value there, and the call made at every read and on every bar -- until it is started again
import, renko and other chart types, request.security_lower_tfunsupportednot supported: each is a compile error saying why and what to use instead -- import: a TradingView library's code lives on TradingView, where QTrader can't read it: paste the functions you use into the script; request.security_lower_tf: QTrader doesn't keep the bars of shorter timeframes for every market and period, use request.security with the chart's timeframe or a longer one; Renko, Kagi, Line Break and Point & Figure: no such bars
request.security(...)supportedthis chart's symbol (syminfo.tickerid) on a longer timeframe -- minutes like "240", "D", "W", "M" or an input.timeframe; the value is computed on the chart's candles merged into the longer bars and, as TradingView does by default, a chart bar sees a longer bar's value once that bar has closed; lookahead=barmerge.lookahead_on with expr[1] works too. Another market works as well, on the chart's timeframe or a longer one -- any ticker of the catalog, e.g. "BINANCE:BTCUSDT", "BYBIT:ETHUSDT.P" (perpetual), "OKX:SOLUSDT.P"; a bare symbol is Binance spot -- a live robot may get its newest bar a bar late. [h, l] = request.security(syminfo.tickerid, "D", [high, low]) -- or of a function ending with [a, b] -- is one request per value. From engine version 5 the symbol can be ticker.heikinashi(syminfo.tickerid) -- or of another market, also through a variable -- the value is then computed on Heikin Ashi bars of the requested timeframe (built from its own bars, as TradingView does), e.g. [o, c] = request.security(ticker.heikinashi(syminfo.tickerid), "240", [open, close]). Not yet: gaps=barmerge.gaps_on, a shorter timeframe than the chart's
market_data.<key>supportedthe Market data series as in Python, read as a series: fg = market_data.fear_n_greed, with history fg[1], na(fg), ta.* over it and plot(fg); a series of several values is unpacked, [liq_long, liq_short] = market_data.liquidations. Up to 3 series on a free account; not inside request.security
process_orders_on_close=truesupporteda signal fills at its own bar's close; the signal on the last bar stays pending, as a live robot sends it
strategy(pyramiding=N)supportedup to N entries in one direction: each further entry signal while the position is open adds one, sized as strategy()'s default size (fixed contracts, cash, or percent of the equity, cut to what is left), each with its own stop/target from its own fill and each a trade of its own; strategy.position_avg_price is their average. Backtests only: a live robot refuses pyramiding for now. Not combined with entries at a price (stop=/limit=) yet
indicator(...) scripts (v4: study(...))supportedBacktest draws the lines the script plot()s and makes no trades -- the Notes tab says so. Each line is named by its plot title, else by the variable it plots, else by its call; with overlay=false (TradingView's default) every line goes to the indicator's own pane under the candles, named after its short title, with overlay=true each line sits where a strategy's would. Any number series is drawn: a ta.* result or request.security value, a price, arithmetic (plot(fast - slow), plot(close * 2)) or a var/:= value -- an untitled one is named by its expression; plot()'s colour, style and width are TradingView's look (the legend sets the chart's own) and offset= is ignored with a warning. hline(price, title) draws a dashed horizontal line at a number, an input or arithmetic of them (one at a series is a warning, as TradingView refuses it), in the indicator's pane -- with overlay=true over the candles when the level is on their scale, else by the indicator's first line under them; its colour and line style are ignored. fill(), plotshape, bgcolor and the other drawing calls are ignored with a warning. indicator()'s other arguments are accepted and ignored (timeframe= with a warning: use request.security). strategy.* calls and values are errors in an indicator, as in TradingView; an indicator can't run as a robot or be converted to Python
log.info / log.warning / log.error (Pine Logs)supportedeach call writes a line with its bar's time where the script reaches it -- in if/else, loops and functions alike -- to the backtest's Logs tab and the robot's; the message is text in quotes, + of texts, str.tostring(value[, "#.##"-style pattern]), str.format("{0} {1,number,#.##}", ...) or log.info(format, values...), and text ?: text; string variables, other str.* functions and the format.* constants (format.mintick) are not supported yet -- give a pattern

Robots

A robot runs a strategy live, bar by bar, exactly like a backtest, and — in Live mode — sends its entry/exit signals to a real exchange account as TradeAdapter webhook alerts. QTrader sends alerts to the TradeAdapter this site is connected to. Start one with Run as robot from the workbench. A dry robot needs no TradeAdapter at all and sends nothing; a TradeAdapter strategy can be chosen later on the robot page (Choose TradeAdapter strategy) and the robot stays a dry run. To go live, press Go live on the robot's own page: it switches at once when the robot holds no position, or when the paper position closes. Paper trades stay in the journal, and Community counts the live record from the moment of the switch. A stopped robot goes live with Start again with a strategy and Live. A live robot needs a TradeAdapter connection — the key from your TradeAdapter webhook URL, or the whole URL, works the same as connecting from the Account page — and a TradeAdapter strategy on that account to send alerts to.

Before a robot can go live, QTrader compares the chosen TradeAdapter strategy against the code's own strategy(...) settings and market:

  • Protection — stop-loss, take-profit, trailing stop — must match what the code sets. A mismatch is an error and blocks going live: it would mean the exchange applies a different stop than the one the strategy was tested with. The check names the exact values to set on the TradeAdapter strategy.
  • Where TradeAdapter can't place the code's protection on the exchange — some markets take no stop-loss or take-profit order, and fewer take a trailing stop — it's a warning: the robot's own close at the bar's close is then the only stop, and its fill can be far worse than the level. The warning names the markets that can place it.
  • A strategy that can go short needs a futures TradeAdapter strategy — spot has no way to hold a short position — also an error.
  • On a spot TradeAdapter strategy, a robot's exit sells what its entry bought, less the exchange fee when it was taken in the coin itself (rounded down to the lot size, so a little dust may stay on the account). Coins you held before the robot bought are never sold. A spot strategy with TradingView position sync turned on is an error: TradeAdapter refuses those exits.
  • A mismatch between the code's ticker and the TradeAdapter strategy's, and a TradeAdapter order type other than market, are warnings only — the robot can still go live, but they're worth double-checking.
  • A robot sizes its orders from its own capital (the strategy's initial capital), not from the exchange balance. A TradeAdapter strategy whose quantity is fixed or a share of the balance replaces that size — a warning: the code's size isn't what trades.
  • A TradeAdapter strategy that counts quantities in contracts of any size other than one unit of the base asset is an error — as are MEXC and KuCoin futures, which count in contracts whose size TradeAdapter doesn't report yet. A lot size TradeAdapter didn't report is a warning — quantities then go out unrounded.

Dry run computes and records every alert exactly as Live would, without ever sending it — a rehearsal against the checks above before risking a real account. The exchange's own protective order (the one configured on the TradeAdapter strategy) is what actually protects a live position; QTrader's own stop/take/trailing check on top of that is a backup, not the primary mechanism — if its simulation sees one of them hit on a bar, it sends its own backup close alert, in case the exchange-side order didn't fire.

A robot's one-word status is Running, Paused, Needs attention, or Stopped. Attention — a delivery problem, a missing connection, a red hourly re-check, the alert-rate pause, a close that wasn't confirmed — always takes over the summary while the robot is still active, whether it's otherwise running or paused, and stays until the robot is stopped or resumed; stopped always wins over everything else. Stop asks whether the position goes too: Stop and close position sends a closing alert for whatever the robot currently holds; Stop, keep position just stops ticking and leaves the position on the exchange exactly as it is. Either takes effect within a few seconds — the page shows Stopping… (or Resuming…) until it has — and from the moment you press it no new entry goes out. While a robot is running or paused — or, just after a stop, while its last alert is still going out — its TradeAdapter connection can be neither replaced nor removed on the Account page: stop the robot first.

The robots list splits into Active (running and paused) and Stopped. A robot's name can be changed in its page's header at any time. Start again on a stopped robot opens Run as robot on the workbench with its code, parameters, settings, market and TradeAdapter strategy: the result is a new robot with a history of its own, the stopped one stays as it is.

A robot replays its strategy on every bar, so a change in how QTrader fills orders could rewrite the trades it already made — and a live robot would then send orders for them. Each robot therefore keeps the engine version it was started with; backtests on the workbench always run the latest. A robot on an older engine says so under its Settings tab: Start again makes a new robot on the latest. What each version changed:

  • v2 — a long and a short entry on the same bar while flat fill in the script's order (v1 always opened the long);
  • v3 — Pine's orders as TradingView runs them: an order reads the script's variables where it is called, not at the end of the bar (if not tradedToday → strategy.entry → tradedToday := true now trades); strategy.entry(qty=...) sizes the entry; strategy.risk.allow_entry_in turns entries of the other side into closes; and strategy.order runs (backtests). A robot started on v1 or v2 compiles and trades its code exactly as before until it is started again.
  • v4 — Pine's sizes, lots and script order: qty= sizes an entry at a price (limit=/stop=); strategy.opentrades counts the lots of a position built with pyramiding or strategy.order, and strategy.opentrades.entry_price(n) is trade n's (na when there is none); strategy.close(id) closes what strategy.order opened under that id; a variable that reads an array, a map or a var changed above it on the bar is computed where it's declared (it read the previous bar's), and an if block's old = history.shift() runs once, when the block does. A robot started on v1–v3 keeps its translation until it is started again. The list of trades (strategy.closedtrades.*(n), strategy.opentrades.*(n)) works on every version: no code read it before.
  • v5 — Pine's prices and price orders: a limit=/stop= price,loss=/profit= ticks and a trailing stop's prices are rounded to the price step as TradingView places the order (a buy limit down, a buy stop up, an exit's stop away from the price); strategy.exit at strategy.position_avg_price * F works from the bar after the entry — TradingView places it at a bar's close, where the average price is first known — and with several lots at their average price; an entry at a price that filled and closed on one bar doesn't fill again, and an exit at a price ends with its trade. strategy.order at a limit= or stop=, strategy.closedtrades.exit_id(n), the orders' comments and ticker.heikinashi work from v5 (backtests). A robot started on v1–v4 keeps its translation until it is started again.

A robot computes on the market of its chart. When the TradeAdapter strategy trades on another market QTrader has candles of, Run as robot switches to it as you choose the strategy (Keep goes back), and the robot's page warns when the two differ: prices and fills can differ too.

A pause holds back new entries only. A paused robot keeps following the market bar by bar and sends its closes — exits and protective closes — as they come: closes are never held back, not by the pause, not by the limit of 60 alerts an hour, since a close held back would leave a position open on the exchange. Its new entries are recorded as Not delivered (not sent: the robot was paused) until you Resume; nothing held back goes out on Resume — the robot just acts on its next signal. If a close isn't confirmed — it ends Not delivered, Unknown or Rejected — the exchange may still hold the position, so the robot pauses: check the position in TradeAdapter's My trades, then Resume or stop the robot. While such a close is unconfirmed, Stop and close position sends a close even if the strategy itself is flat by now — a close when TradeAdapter's position is already flat is harmless.

Each alert's own status in the robot's event journal (the Events tab on its page):

  • Dry run — a dry-run robot's alert, recorded and never sent.
  • Dry run (live is off on the server) — a live robot's alert, recorded but not sent because live sending is switched off on this server.
  • Sending — going out now, waiting for a retry (up to 3 attempts within 30 seconds, always the same alert), or waiting behind the robot's previous alert.
  • Accepted — TradeAdapter's webhook took it. It always answers "ok" the moment it receives an alert, so this says nothing yet about the exchange.
  • Filled at … / Rejected: … — the exchange's own outcome. QTrader polls TradeAdapter's order history after sending, so these show up a minute or two later.
  • Not delivered — TradeAdapter never confirmed it: every attempt failed, there was no usable key, or it was never sent (the robot was stopped or paused, the hourly limit was reached, the entry was below the exchange minimum).
  • Unknown — the delivery is uncertain: it was sent, but no answer came back (the service restarted, or the robot was stopped or paused, mid-request), so TradeAdapter may or may not have received it. Check My trades in TradeAdapter.
  • Skipped (late) — an entry that would have gone out too late (see below).
  • Skipped — the second alert of a reversal (the new entry), not sent because the first one (the close) wasn't accepted.
  • Below minimum — a close not sent because the position is smaller than the exchange minimum and its entry never went out, so nothing was opened. A close after an entry that did go out is always sent, even below the minimum: if the exchange refuses it, the robot pauses like for any close that wasn't confirmed.

Where the service knows why, the journal shows the reason after the status.

An entry alert more than 60 seconds late — after a restart or a stalled tick — is never sent; it's recorded as Skipped (late) instead, since acting on a signal that stale could open a position at a very different price than intended. An exit alert is always sent, however late — leaving a position open longer than the strategy intended is worse than closing it late.

Quantities are rounded down to the exchange's lot size before they're sent; a position smaller than the exchange minimum isn't sent.

Signals are computed from the robot's configured candle market, but the trade itself executes on your own exchange account through TradeAdapter — the two prices can differ, sometimes by a meaningful amount, especially right after a gap or on a thin market.

Running-robot limits depend on your plan and server access; see the current plans. At most one robot can use a TradeAdapter strategy at a time — running, paused, or stopped with an alert still going out (stop it, and let its last alert finish, to free that strategy up for a new one).

Data for LLM robots

Besides the candles, an LLM robot's prompt can carry extra data series. The plan limits them in two counts: market data series (everything below except indicators) according to your plan, as do indicators. See the current plan limits. A recipe never holds more than 8 series in all, nor more than 3 other markets. The model sees them next to the candles on every bar.

What you can add

  • Indicators: RSI, EMA, SMA, MACD, ATR, Bollinger Bands, VWAP and Stochastic.
  • Other markets, on the robot's timeframe.
  • Funding, for perpetual futures only.
  • The Fear & Greed Index.
  • Derivatives series of a perpetual: open interest, long/short ratio, top traders' long/short, taker buy/sell volume and liquidations.
  • The US macro calendar.

How the model sees them

Indicators and other markets are extra columns after volume in the candle table, named like rsi14, ema50_hl2 or BINANCE:BTCUSDT.close; a value that doesn't exist yet is NA. Funding comes as a separate block: the last three accruals and the time of the next one. The Fear & Greed Index comes as the last seven days with their labels. Derivatives series are columns after volume, and a line above the table says what each one means. The US macro calendar comes as a short block with the next events and the last one, in UTC.

In Expert mode a series can also be put in the text on its own, in two forms: .current is its latest value and .full is all the candles of the table. For RSI 14, {indicator.rsi14.current} is a single number such as 57.3, and {indicator.rsi14.full} is a list of time value pairs, oldest first. Funding, Fear & Greed and the US macro calendar are blocks and have no such forms.

Derivatives series

These exist only for perpetual futures, and each exchange serves its own set; the Add data menu greys out what the robot's exchange doesn't publish and says why. The column names are oi, ls, ls_top, taker_ratio, liq.long and liq.short. On the chart each one gets its own pane. Values are hourly: a candle sees only the hours that had closed by the candle's close.

  • Open interest (oi): positions open on the perpetual, in USD at the candle's close. Binance, Bybit, OKX, Gate, Kraken, Bitget, KuCoin, MEXC and BingX.
  • Long/short ratio (ls): accounts long against accounts short. Binance, Bybit, OKX, Gate, Kraken and Bitget.
  • Top traders L/S (ls_top): the long against short positions of the exchange's top traders. Binance, OKX, Gate, Kraken and Bitget.
  • Taker buy/sell volume (taker_ratio): market buys against market sells during the candle. Binance, OKX, Gate and Bitget.
  • Liquidations (liq.long, liq.short): USD liquidated during the candle, longs and shorts apart. Binance, Bybit, OKX and Gate only; Kraken has no liquidations.

How far back the history goes depends on the exchange: Binance keeps about 30 days of its ratios, OKX about 60 and Gate 180; Bitget's ratios cover only the last 30 or so candles. When you add a series for a market for the first time, its history loads in the background and the chart says so; the lines appear when it is ready. Exchanges that publish only the current open interest (KuCoin, MEXC, BingX and, for open interest, Bitget) build their history hour by hour from the day this series appeared in QTrader. Taker volume and Gate's liquidations for the hour that just closed arrive a few minutes later, so in a robot's decision the newest candle shows them as NA.

Liquidations from Binance, Bybit and OKX are collected live, so a candle from before collection began has none, and a gap in the connection is not filled afterwards. Binance also sends at most one liquidation per symbol per second. Treat the figures as a floor, not an exact total: the prompt says they may be understated. Gate's come from its hourly statistics.

US macro calendar

The scheduled events that move markets: the FOMC rate decision and the FOMC minutes (14:00 New York time), CPI and the Employment Situation report, NFP (08:30 New York time). Times are converted to UTC with daylight saving taken into account, and the model sees the next events within 14 days and the last ones within 3 days before the candle. On the chart each event is a small square labelled with its name.

An event is shown only from the moment it was known. The calendar on a past candle is the calendar as it stood then: an event that was announced or moved afterwards is not there yet, and a date that was later moved still shows its old date until the move was published. That is the "known from" rule, and it keeps backtest-style questions free of hindsight. Dates come from the Federal Reserve's calendar and the Bureau of Labor Statistics' schedule, refreshed daily.

Freshness

Everything is cut at the close of the bar being decided: nothing later reaches the model. Funding older than two funding intervals, or a Fear & Greed value older than two days, shows as unavailable. If another market is missing a bar, the robot holds its position for that bar and Decisions shows no data.

Source: alternative.me (Fear & Greed Index).

Expert mode

In Expert you write the whole prompt yourself. There is no system part of ours: the template is all the model gets. Variables in braces are filled in on every closed bar:

  • {ticker}, {broker}, {interval} — the market and timeframe, as in TradingView's placeholders ({exchange} still works for {broker})
  • {candles} — the last closed candles as CSV, with your indicators and other markets as extra columns (required)
  • {market_position} — flat, or the side, entry and result so far
  • {equity} — the robot's equity as a percent of the starting capital
  • {indicator.rsi14.current} and {indicator.rsi14.full} — one series on its own: its value on the latest closed candle (57.3), or every candle of the table as time value pairs, oldest first (2026-10-26 08:00 51.2, 2026-10-26 12:00 57.3); a value that doesn't exist yet is NA. Each series you add in Data or Indicators gets these two; one with several lines (MACD, Bollinger Bands) also gets them per line, like {indicator.macd12_26_9.signal.current}. Derivatives series use the market_data. prefix: {market_data.oi.current}
  • {market_data.funding} — the latest funding rates (add Funding rate in Data)
  • {market_data.fear_greed} — the Fear & Greed Index of the last days (add Fear & Greed in Data)
  • {market_data.macro_calendar} — the next and last US macro events, in UTC (add US macro calendar in Data)

Anything else in braces stays as you wrote it, so a JSON example of the answer needs no escaping. A typo like {candels} is an error with a hint.

The answer format is yours, but the model must decide long, short or flat: either JSON with an "action" field, or the word alone on the last line of its reply. A Backtest checks this before the robot can run; a reply without a decision later keeps the last position, and a robot on your own LLM is paused after 5 failed or unreadable calls in a row.

Switching to Expert the first time starts the template from the guided prompt you have.

Approximate backtest

Backtest in LLM mode asks the model once: here is your prompt and the last candles, how would you have traded them? On a free account it tests the last 50 closed bars, with the 50 before them as history the model reads but doesn't trade. The model answers with the bars where it would have changed its position, and we play those changes like any backtest: an order fills on the next bar's open, with the default commission and starting capital. The Backtesting tab shows the report and the trades, each with the model's reason.

The result is approximate. A running robot asks the model on every closed bar and sees only the past; here the model sees all the bars in one go, so it can lean on what comes later, and the same prompt can answer differently each time. Take it as a sketch of how the prompt trades, not as its expected return.

A backtest is one call to the model and counts toward your monthly LLM limit. Up to 10 backtests an hour. A backtest the model answered in full is the check Run as robot needs, for a day: after a reload the same prompt stays ready to run.

Your own LLM

An LLM robot can run on any OpenAI-compatible endpoint: OpenRouter, Groq, Together, DeepSeek, or your own server reachable over https. Own models are a Pro feature. In the workbench's LLM mode, open the model list and click + Connect your LLM.

What you enter

  • Base URL: the address before /chat/completions, for example https://openrouter.ai/api/v1.
  • API key: optional. It is stored encrypted and never shown again, only its last four characters.
  • Model id: as your provider names it.

Test & save asks the model once; the connection is saved only if the reply holds a decision. A robot still needs a Backtest with its prompt before it runs.

Rules

  • https on the standard port only, to a public address: private networks and localhost are refused.
  • A call has 55 seconds. A server error or a network failure is tried once more if there is time.
  • Your provider bills the calls: our monthly LLM limit doesn't apply. Connection checks are up to 20 an hour.
  • After 5 failed or unreadable calls in a row the robot is paused with the reason. Resume it once the endpoint works.
  • Connection allowances depend on your plan; see current plan limits. On a shared prompt others see your model's id, never its address or key.

Limits

  • Markets: any ticker of the catalog, e.g. BINANCE:BTCUSDT, BYBIT:ETHUSDT.P (perpetual), OKX:SOLUSDT.P; a bare symbol is Binance spot. Search the catalog in the workbench; a market's history is loaded on first use.
  • Timeframes: 1m, 5m, 15m, 30m, 1h, 2h, 4h, 12h, 1d, 1W. 30m, 2h, 12h and 1W are built from 15m, 1h, 4h and 1d bars; a week starts on Monday 00:00 UTC, and a bar shows up once it has closed.
  • History a market loads on first use: 1m about six months (not before 2024-01-01), 5m and 15m two years, 1h and longer from 2020 or the market's listing; "Load earlier history" on a backtest goes deeper where the exchange has it.
  • A backtest evaluates the last permitted bars of its period, with the indicators' warm-up before them on top. Account/guest allowances depend on current settings and access; a longer requested period can be clipped or refused. Read the result Notes and actual evaluated dates rather than assuming the entire selected history was tested.
  • Guest backtest allowances and history depth depend on current settings; see plans and limits. The indicator lines on the chart are not counted. Saving strategies and running robots need an account.
  • A backtest that runs too long is stopped after a server-side timeout (10 seconds by default); too many backtests running at once return a "busy" error instead of queueing.
  • The price chart draws at most the last 50,000 bars of the selected period.
  • The equity curve is downsampled to at most 2,000 points for display.
  • The trade list shows only the latest 500 trades; the metrics cover all of them.
  • The strategy log keeps the latest 1,000 lines of a backtest and 500 of a robot, each at most 500 characters.

Charts by TradingView Lightweight Charts™

The interactive workbench needs JavaScript. Reload this page if interactive controls could not load.