Pine Script Reference

Complete reference for supported Pine Script functions, operators, and built-in variables in TrainBard.

View the complete compatibility reference as Markdown

Introduction

Pine Script Reference

This reference covers supported functions, operators, and built-in variables available in the TrainBard script editor. TrainBard implements a verified subset of Pine Script v6; an unlisted function, overload, member, or named argument is rejected rather than silently ignored. The complete compatibility reference records exact supported subsets and known unsupported APIs.

Scripts follow Pine Script v6-style syntax. Every strategy begins with a version directive and strategy declaration:

//@version=6
strategy("My Strategy", overlay=true)

Quick Start

Define parameters with input.* functions, compute indicators with ta.* functions, and generate trade signals with strategy.* functions:

fast = input.int(10, "Fast MA")
slow = input.int(20, "Slow MA")

fastMA = ta.sma(close, fast)
slowMA = ta.sma(close, slow)

if ta.crossover(fastMA, slowMA)
    strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
    strategy.close("Long")

Built-in Variables

The following price and time series are available on every bar:

VariableDescription
openOpening price
highHighest price
lowLowest price
closeClosing price
volumeBar volume
hl2(high + low) / 2
hlc3(high + low + close) / 3
ohlc4(open + high + low + close) / 4
hlcc4(high + low + close + close) / 4
timeBar timestamp (Unix ms)
bar_indexCurrent bar number (0-based)
last_bar_indexIndex of the final loaded historical bar
last_bar_timeTimestamp of the final loaded historical bar
timenowCurrent execution timestamp

Symbol Variables

VariableDescription
syminfo.tickeridCurrent symbol identifier
syminfo.tickerCurrent symbol
syminfo.mintickSymbol tick size used by tick-based exits and math.round_to_mintick()
syminfo.pointvalueMarket point value when available; otherwise 1

syminfo.basecurrency, syminfo.currency, exchange metadata, and other unlisted syminfo.* members are not supported.

Backtesting Behavior

TrainBard evaluates strategies on the selected candle data without intrabar tick updates.

Market entries and market closes normally fill on the next candle. If a candle touches both stop and limit for an open trade, TrainBard uses the conservative fill. See the strategy section for the supported process_orders_on_close and immediate-close exceptions.

Time Variables

VariableDescription
yearUTC year
monthUTC month (1-12)
dayofmonthUTC day of month
dayofweekUTC day of week (1=Sun)
hourUTC hour
minuteUTC minute
secondUTC second

Strategy Constants

ConstantDescription
strategy.longLong direction
strategy.shortShort direction

Language Features

  • Variables: myVar = expression
  • Persistent variables: var myVar = initialValue (retains value across bars)
  • Conditionals: if / else if / else blocks
  • Ternary: condition ? valueA : valueB
  • For loops: for i = 0 to n
  • User-defined functions: myFunc(param1, param2) => expression
  • User-defined types: type MyType with fields
  • History operator: close[1] accesses previous bar values

Input Functions

Input Functions

Input functions define user-configurable parameters for your strategy. When running a backtest, parameter values can be set individually or as ranges for optimization.

input.int

Declares an integer input parameter.

Syntax: input.int(defval, title, minval, maxval, tooltip, inline, group)

ParameterTypeDescription
defvalintDefault value
titlestringDisplay name in the parameter form

The default must be a literal integer. Use either literal minval/maxval bounds or a non-empty literal options list. step is not currently supported.

length = input.int(14, "RSI Length")

Use range notation in the Test tab to sweep values: 10_50:5 tests 10, 15, 20, … 50.

input.float

Declares a floating-point input parameter.

Syntax: input.float(defval, title, minval, maxval, step, tooltip, inline, group)

ParameterTypeDescription
defvalfloatDefault value
titlestringDisplay name

The default must be finite and literal. Bounds are inclusive. You may use literal bounds and a positive step, or a non-empty literal options list.

factor = input.float(1.5, "Multiplier")

input.bool

Declares a boolean input parameter.

Syntax: input.bool(defval, title)

ParameterTypeDescription
defvalboolDefault value (true or false)
titlestringDisplay name
useLong = input.bool(true, "Enable Long")

input.string

Declares a string input parameter.

Syntax: input.string(defval, title)

ParameterTypeDescription
defvalstringDefault value
titlestringDisplay name
maType = input.string("SMA", "MA Type")

Additional supported inputs

FunctionSupported subset
input.color(defval, title, ...)Static color default plus tooltip, inline, and group metadata
input.timeframe(defval, title, ...)Literal string value, optional literal options, and tooltip/inline/group metadata
input.session(defval, title, ...)Literal string value, optional literal options, and tooltip/inline/group metadata
input.text_area(defval, title, ...)Literal string value plus tooltip and group metadata

Inputs must be assigned directly. Runtime values are validated against their declared types, bounds, and options.

Unsupported input forms

The unqualified input(), input.source, input.symbol, input.time, input.price, and input.enum forms are not supported. Unlisted arguments such as confirm, display, and active are rejected.

Moving Averages

Moving Averages

Moving average functions smooth price data over a specified period. All functions return a series (one value per bar).

ta.sma

Simple Moving Average. The unweighted arithmetic mean of the last length bars.

Syntax: ta.sma(source, length)

ParameterTypeDescription
sourceseriesInput series (e.g. close)
lengthintNumber of bars
sma20 = ta.sma(close, 20)

ta.ema

Exponential Moving Average. Gives more weight to recent values. Seeded with SMA of the first length values.

Syntax: ta.ema(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
ema50 = ta.ema(close, 50)

ta.wma

Weighted Moving Average. Linearly weights values so the most recent bar has the highest weight.

Syntax: ta.wma(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
wma10 = ta.wma(close, 10)

ta.hma

Hull Moving Average. A fast, smooth MA that reduces lag using WMA of WMA differences.

Syntax: ta.hma(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
hma20 = ta.hma(close, 20)

ta.rma

Relative Moving Average (Wilder’s smoothing). Used internally by RSI and ATR. Equivalent to an EMA with alpha = 1/length.

Syntax: ta.rma(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
rma14 = ta.rma(close, 14)

ta.vwma

Volume-Weighted Moving Average. Weights each bar’s value by its volume.

Syntax: ta.vwma(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
vwma20 = ta.vwma(close, 20)

ta.alma

Arnaud Legoux Moving Average. Uses a Gaussian distribution for weighting, controlled by offset and sigma.

Syntax: ta.alma(series, length, offset, sigma)

ParameterTypeDefaultDescription
seriesseriesInput series
lengthintWindow size
offsetfloat0.85Gaussian offset (0–1)
sigmafloat6Gaussian sigma
alma = ta.alma(close, 20, 0.85, 6)

ta.swma

Symmetrically Weighted Moving Average. A fixed 4-bar weighted average with weights [1, 2, 2, 1] / 6.

Syntax: ta.swma(source)

ParameterTypeDescription
sourceseriesInput series
sw = ta.swma(close)

ta.dema

Double Exponential Moving Average. 2 * EMA - EMA(EMA). Reduces lag compared to a standard EMA.

Syntax: ta.dema(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
dema20 = ta.dema(close, 20)

ta.tema

Triple Exponential Moving Average. 3 * EMA - 3 * EMA(EMA) + EMA(EMA(EMA)). Further reduces lag versus DEMA.

Syntax: ta.tema(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
tema20 = ta.tema(close, 20)

ta.kama

Kaufman Adaptive Moving Average. Adjusts smoothing speed based on market noise.

Syntax: ta.kama(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintEfficiency ratio period
kama10 = ta.kama(close, 10)

ta.t3

Tillson T3 Moving Average. A smooth, low-lag MA built from six cascaded EMAs with a volume factor.

Syntax: ta.t3(source, length, factor)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthintEMA period
factorfloat0.7Volume factor (0–1)
t3val = ta.t3(close, 5, 0.7)

Oscillators

Oscillators

Oscillator functions measure momentum and overbought/oversold conditions. They typically return bounded or centered values.

ta.rsi

Relative Strength Index. Measures the speed and magnitude of price changes on a 0–100 scale.

Syntax: ta.rsi(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
rsi14 = ta.rsi(close, 14)

ta.stoch

Stochastic oscillator. Returns the position of the source relative to the high-low range over length bars.

Syntax: ta.stoch(source, high, low, length)

ParameterTypeDescription
sourceseriesSource (typically close)
highseriesHigh series
lowseriesLow series
lengthintLookback period
k = ta.stoch(close, high, low, 14)

ta.cci

Commodity Channel Index. Measures the deviation of price from its statistical mean.

Syntax: ta.cci(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
cci20 = ta.cci(close, 20)

ta.cmo

Chande Momentum Oscillator. Measures momentum on a -100 to +100 scale using the difference between gains and losses.

Syntax: ta.cmo(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
cmo14 = ta.cmo(close, 14)

ta.tsi

True Strength Index. Double-smoothed momentum oscillator.

Syntax: ta.tsi(source, short_length, long_length)

ParameterTypeDefaultDescription
sourceseriesInput series
short_lengthint13Short EMA period
long_lengthint25Long EMA period
tsi_val = ta.tsi(close, 13, 25)

ta.wpr

Williams %R. An overbought/oversold indicator ranging from -100 to 0.

Syntax: ta.wpr(length)

ParameterTypeDescription
lengthintLookback period
wpr14 = ta.wpr(14)

ta.mom

Momentum. The difference between the current value and the value length bars ago.

Syntax: ta.mom(source, length)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthint1Bars ago
mom10 = ta.mom(close, 10)

ta.roc

Rate of Change. Percentage change between the current value and length bars ago.

Syntax: ta.roc(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
roc12 = ta.roc(close, 12)

ta.cog

Center of Gravity. A leading oscillator based on linear regression of price over a window.

Syntax: ta.cog(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
cog10 = ta.cog(close, 10)

ta.ao

Awesome Oscillator. The difference between a 5-period and 34-period SMA of the midpoint (hl2).

Syntax: ta.ao()

No parameters — uses hl2 automatically.

ao_val = ta.ao()

ta.macd

Moving Average Convergence/Divergence. Returns three series: MACD line, signal line, and histogram.

Syntax: [macdLine, signal, histogram] = ta.macd(source, fastlen, slowlen, siglen)

ParameterTypeDefaultDescription
sourceseriesInput series
fastlenint12Fast EMA period
slowlenint26Slow EMA period
siglenint9Signal line EMA period
[macdLine, signalLine, hist] = ta.macd(close, 12, 26, 9)

Volatility & Bands

Volatility & Bands

Functions for measuring volatility and computing price bands/channels.

ta.atr

Average True Range. The RMA of the true range over length bars.

Syntax: ta.atr(length)

ParameterTypeDescription
lengthintLookback period
atr14 = ta.atr(14)

ta.natr

Normalized Average True Range. ATR expressed as a percentage of the closing price.

Syntax: ta.natr(length)

ParameterTypeDescription
lengthintLookback period
natr14 = ta.natr(14)

ta.tr

True Range. The greatest of: current high minus low, absolute(high minus previous close), absolute(low minus previous close). Also available as the built-in variable ta.tr.

Syntax: ta.tr

No parameters — available as a series variable.

trueRange = ta.tr

ta.bb

Bollinger Bands. Returns three series: middle band (SMA), upper band, and lower band.

Syntax: [middle, upper, lower] = ta.bb(series, length, mult)

ParameterTypeDefaultDescription
seriesseriesInput series
lengthintSMA period
multfloat2Standard deviation multiplier
[basis, upper, lower] = ta.bb(close, 20, 2)

ta.bbw

Bollinger Bandwidth. The percentage width between the upper and lower Bollinger Bands: (upper - lower) / middle.

Syntax: ta.bbw(series, length, mult)

ParameterTypeDefaultDescription
seriesseriesInput series
lengthintSMA period
multfloat2Standard deviation multiplier
bbw = ta.bbw(close, 20, 2)

ta.kc

Keltner Channels. Returns three series: middle (EMA), upper, and lower bands based on ATR.

Syntax: [middle, upper, lower] = ta.kc(series, length, mult, useTrueRange)

ParameterTypeDefaultDescription
seriesseriesInput series
lengthintEMA period
multfloat1.5ATR multiplier
useTrueRangebooltrueUse true range instead of high-low range
[kcMid, kcUpper, kcLower] = ta.kc(close, 20, 1.5)

ta.kcw

Keltner Channel Width. The percentage width between upper and lower Keltner Channels: (upper - lower) / middle.

Syntax: ta.kcw(series, length, mult, useTrueRange)

ParameterTypeDefaultDescription
seriesseriesInput series
lengthintEMA period
multfloat1.5ATR multiplier
useTrueRangebooltrueUse true range instead of high-low range
kcw = ta.kcw(close, 20, 1.5)

ta.donchian

Donchian Channels. Returns three series based on the highest high and lowest low over length bars.

Syntax: [middle, upper, lower] = ta.donchian(length)

ParameterTypeDefaultDescription
lengthint20Lookback period
[dcMid, dcUpper, dcLower] = ta.donchian(20)

ta.stdev

Standard Deviation over a rolling window.

Syntax: ta.stdev(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
sd20 = ta.stdev(close, 20)

ta.variance

Variance over a rolling window.

Syntax: ta.variance(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
v20 = ta.variance(close, 20)

ta.dev

Mean absolute deviation over a rolling window.

Syntax: ta.dev(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
dev20 = ta.dev(close, 20)

Trend Indicators

Trend Indicators

Functions for identifying trend direction, strength, and reversal points.

ta.supertrend

Supertrend indicator. Returns two series: the supertrend line and a direction value (+1 or -1).

Syntax: [supertrend, direction] = ta.supertrend(factor, atrPeriod)

ParameterTypeDefaultDescription
factorfloat3ATR multiplier
atrPeriodint10ATR period
[st, dir] = ta.supertrend(3, 10)

ta.adx

Average Directional Index. Measures trend strength on a 0–100 scale regardless of direction.

Syntax: ta.adx(di_length, adx_smoothing)

ParameterTypeDefaultDescription
di_lengthint14DI period
adx_smoothingint14ADX smoothing period
adx14 = ta.adx(14, 14)

ta.dmi

Directional Movement Index. Returns three series: +DI, -DI, and ADX.

Syntax: [plusDI, minusDI, adx] = ta.dmi(diLength, adxSmoothing)

ParameterTypeDefaultDescription
diLengthint14DI period
adxSmoothingint14ADX smoothing period
[pDI, mDI, adxVal] = ta.dmi(14, 14)

ta.sar

Parabolic SAR (Stop and Reverse). A trend-following indicator that plots trailing stop levels.

Syntax: ta.sar(start, inc, max)

ParameterTypeDefaultDescription
startfloat0.02Initial acceleration factor
incfloat0.02Acceleration increment
maxfloat0.2Maximum acceleration factor
sarVal = ta.sar(0.02, 0.02, 0.2)

ta.aroon

Aroon indicator. Returns two series measuring time since highest high and lowest low.

Syntax: [aroonUp, aroonDown] = ta.aroon(length)

ParameterTypeDefaultDescription
lengthint14Lookback period
[arUp, arDown] = ta.aroon(14)

ta.vwap

Volume-Weighted Average Price. The cumulative average price weighted by volume.

Syntax: ta.vwap(source)

ParameterTypeDescription
sourceseriesInput series (typically hlc3)
vwapVal = ta.vwap(hlc3)

ta.linreg

Linear Regression value. The value of the linear regression line at the current bar, optionally offset.

Syntax: ta.linreg(source, length, offset)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthintRegression period
offsetint0Bar offset
lr = ta.linreg(close, 20, 0)

Volume Indicators

Volume Indicators

Functions that analyze price-volume relationships to gauge buying and selling pressure.

ta.obv

On Balance Volume. Running total of volume, added on up bars and subtracted on down bars. Also available as the built-in variable ta.obv.

Syntax: ta.obv

obvVal = ta.obv

ta.mfi

Money Flow Index. A volume-weighted RSI oscillator (0–100).

Syntax: ta.mfi(series, length)

ParameterTypeDescription
seriesseriesTypical price (usually hlc3)
lengthintLookback period
mfi14 = ta.mfi(hlc3, 14)

ta.pvt

Price Volume Trend. Cumulative volume weighted by the percentage change in close price.

Syntax: ta.pvt()

No parameters.

pvtVal = ta.pvt()

ta.cmf

Chaikin Money Flow. Measures money flow volume over a period, ranging from -1 to +1.

Syntax: ta.cmf(length)

ParameterTypeDefaultDescription
lengthint20Lookback period
cmf20 = ta.cmf(20)

ta.ad

Chaikin A/D Line (Accumulation/Distribution). Running total of money flow volume.

Syntax: ta.ad()

No parameters.

adLine = ta.ad()

ta.accdist

Accumulation/Distribution index. Cumulative CLV (Close Location Value) multiplied by volume. Available as a built-in variable.

Syntax: ta.accdist

ad = ta.accdist

ta.wad

Williams Accumulation/Distribution. Measures buying and selling pressure using true range direction.

Syntax: ta.wad

wadVal = ta.wad

ta.wvad

Williams Variable Accumulation/Distribution. Measures the proportional location of the close within the bar’s range, scaled by volume.

Syntax: ta.wvad

wvadVal = ta.wvad

ta.nvi

Negative Volume Index. Tracks price changes on days when volume decreases. Starts at 1000.

Syntax: ta.nvi

nviVal = ta.nvi

ta.pvi

Positive Volume Index. Tracks price changes on days when volume increases. Starts at 1000.

Syntax: ta.pvi

pviVal = ta.pvi

ta.iii

Intraday Intensity Index. (2 * close - high - low) / ((high - low) * volume). Measures the intraday pressure.

Syntax: ta.iii

iiiVal = ta.iii

Signals & Patterns

Signal & Pattern Detection

Functions for detecting crossovers, price extremes, and bar-level patterns.

ta.crossover

Returns true when source1 crosses above source2.

Syntax: ta.crossover(source1, source2)

ParameterTypeDescription
source1seriesSeries that crosses above
source2seriesSeries that is crossed
if ta.crossover(fast, slow)
    strategy.entry("Long", strategy.long)

ta.crossunder

Returns true when source1 crosses below source2.

Syntax: ta.crossunder(source1, source2)

ParameterTypeDescription
source1seriesSeries that crosses below
source2seriesSeries that is crossed
if ta.crossunder(fast, slow)
    strategy.close("Long")

ta.cross

Returns true when source1 crosses source2 in either direction (crossover or crossunder).

Syntax: ta.cross(source1, source2)

ParameterTypeDescription
source1seriesFirst series
source2seriesSecond series
if ta.cross(fast, slow)
    strategy.close("All")

ta.highest

Returns the highest value of source over the last length bars.

Syntax: ta.highest(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
hh20 = ta.highest(high, 20)

ta.lowest

Returns the lowest value of source over the last length bars.

Syntax: ta.lowest(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
ll20 = ta.lowest(low, 20)

ta.max

Returns the all-time highest value of source up to the current bar.

Syntax: ta.max(source)

ParameterTypeDescription
sourceseriesInput series
recordClose = ta.max(close)

ta.min

Returns the all-time lowest value of source up to the current bar.

Syntax: ta.min(source)

ParameterTypeDescription
sourceseriesInput series
lowestClose = ta.min(close)

ta.highestbars

Returns the non-negative bar offset of the highest value of source over the last length bars.

Syntax: ta.highestbars(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
hbars = ta.highestbars(high, 20)

ta.lowestbars

Returns the non-negative bar offset of the lowest value of source over the last length bars.

Syntax: ta.lowestbars(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
lbars = ta.lowestbars(low, 20)

ta.change

Returns the difference between the current value and the value length bars ago.

Syntax: ta.change(source, length)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthint1Bars ago
priceChange = ta.change(close)
priceChange5 = ta.change(close, 5)

ta.rising

Returns true when source has been rising (increasing) for length consecutive bars.

Syntax: ta.rising(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
isRising = ta.rising(close, 3)

ta.falling

Returns true when source has been falling (decreasing) for length consecutive bars.

Syntax: ta.falling(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintNumber of bars
isFalling = ta.falling(close, 3)

ta.pivothigh

Detects pivot highs. Returns the pivot value when a high was confirmed rightBars bars ago, otherwise NaN.

Syntax: ta.pivothigh(source, leftbars, rightbars)

ParameterTypeDefaultDescription
sourceseriesInput series (typically high)
leftbarsint5Left confirmation bars
rightbarsint5Right confirmation bars
ph = ta.pivothigh(high, 5, 5)

ta.pivotlow

Detects pivot lows. Returns the pivot value when a low was confirmed rightBars bars ago, otherwise NaN.

Syntax: ta.pivotlow(source, leftbars, rightbars)

ParameterTypeDefaultDescription
sourceseriesInput series (typically low)
leftbarsint5Left confirmation bars
rightbarsint5Right confirmation bars
pl = ta.pivotlow(low, 5, 5)

ta.barssince

Returns the number of bars since condition was last true.

Syntax: ta.barssince(condition)

ParameterTypeDescription
conditionbool seriesCondition to check
barsSinceCross = ta.barssince(ta.crossover(fast, slow))

ta.valuewhen

Returns the value of source at the nth most recent occurrence of condition.

Syntax: ta.valuewhen(condition, source, occurrence)

ParameterTypeDefaultDescription
conditionbool seriesCondition to match
sourceseriesValue to capture
occurrenceint00 = most recent
priceAtCross = ta.valuewhen(ta.crossover(fast, slow), close, 0)

ta.cum

Cumulative sum of source from the first bar.

Syntax: ta.cum(source)

ParameterTypeDescription
sourceseriesInput series
totalVolume = ta.cum(volume)

Statistics

Statistics

Statistical functions for rolling-window analysis of series data.

ta.correlation

Pearson correlation coefficient between two series over a rolling window.

Syntax: ta.correlation(source1, source2, length)

ParameterTypeDescription
source1seriesFirst series
source2seriesSecond series
lengthintLookback period
corr = ta.correlation(close, volume, 20)

ta.rci

Rank Correlation Index. Measures whether source ranks are moving with or against time over a rolling window. Values range from -100 to 100.

Syntax: ta.rci(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
rci9 = ta.rci(close, 9)

ta.beta

Beta coefficient of source relative to a benchmark over a rolling window.

Syntax: ta.beta(source, benchmark, length)

ParameterTypeDescription
sourceseriesAsset returns
benchmarkseriesBenchmark returns
lengthintLookback period
b = ta.beta(close, open, 20)

ta.median

Rolling median of source over length bars.

Syntax: ta.median(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
med20 = ta.median(close, 20)

ta.mode

Rolling mode (most frequent value) of source over length bars.

Syntax: ta.mode(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
modeVal = ta.mode(close, 20)

ta.range

Rolling range (highest minus lowest) of source over length bars.

Syntax: ta.range(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
rng = ta.range(close, 20)

ta.percentrank

Percent rank of the current value within the previous length values.

Syntax: ta.percentrank(source, length)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
pr = ta.percentrank(close, 20)

ta.percentile_linear_interpolation

Rolling percentile using linear interpolation.

Syntax: ta.percentile_linear_interpolation(source, length, percentage)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
percentagefloatPercentile (0–100)
p75 = ta.percentile_linear_interpolation(close, 100, 75)

ta.percentile_nearest_rank

Rolling percentile using nearest rank method.

Syntax: ta.percentile_nearest_rank(source, length, percentage)

ParameterTypeDescription
sourceseriesInput series
lengthintLookback period
percentagefloatPercentile (0–100)
p90 = ta.percentile_nearest_rank(close, 100, 90)

Plot Functions

Plot Functions

Plot functions render visual indicators, overlays, and markers on the chart. They execute during backtesting and their output is displayed alongside candlestick data.

plot

Draws a line, area, histogram, or other series on the chart.

Syntax: plot(series, title, color, linewidth, style, trackprice, histbase, offset, join, editable, show_last, display, format, precision, force_overlay, linestyle)

ParameterTypeDefaultDescription
seriesfloatData series to plot
titlestringDisplay name in the legend
colorcolorcolor.blueLine/fill color
linewidthint1Line thickness (1–4)
styleconstplot.style_lineVisual style
trackpriceboolfalseExtend a tracked price marker across the pane
histbaseint/float0Base level for area, columns, and histograms
offsetint0Shift the plot left or right in bars
joinboolfalseJoin circle/cross markers with a line
editablebooltrueAllow style edits in chart settings
show_lastintOnly show the last N bars
displayconstdisplay.allOutput locations for plot values
formatconstNumeric format override
precisionintDecimal precision override
force_overlayboolfalseDraw in the main chart pane
linestyleconstplot.linestyle_solidLine dash style

Plot Styles

ConstantDescription
plot.style_lineContinuous line (default)
plot.style_steplineStepped line
plot.style_stepline_diamondStepped line with diamond transitions
plot.style_histogramVertical bars from zero
plot.style_columnsColumn bars
plot.style_circlesDot markers
plot.style_areaFilled area under line
plot.style_areabrArea with breaks on NaN
plot.style_crossCross markers
plot.style_linebrLine with breaks on NaN

Line Styles

ConstantDescription
plot.linestyle_solidSolid line
plot.linestyle_dashedDashed line
plot.linestyle_dottedDotted line

Display and Format

ConstantDescription
display.allShow everywhere
display.noneCalculate without displaying
display.paneScript pane
display.status_lineStatus line
display.data_windowData Window
display.price_scalePrice scale
format.pricePrice formatting
format.percentPercent formatting
format.volumeVolume formatting
format.mintickMinimum tick formatting
sma20 = ta.sma(close, 20)
sma50 = ta.sma(close, 50)
plot(sma20, title="SMA 20", color=color.blue, linewidth=2, linestyle=plot.linestyle_dashed)
plot(sma50, title="SMA 50", color=color.red)

Histogram Example

macdLine = ta.ema(close, 12) - ta.ema(close, 26)
plot(macdLine, title="MACD", style=plot.style_histogram, color=color.green)

Conditional Plotting

Use na values or na colors to hide bars without moving the plot call into an if block.

plot(bar_index % 2 == 0 ? high : na, "Every other high", color=color.gray, style=plot.style_linebr)
plot(close, "Colored close", close >= open ? color.lime : color.red)

plotshape

Draws shape markers on the chart when a condition is true. Useful for marking entry/exit signals and pattern detections.

Syntax: plotshape(condition, title, style, location, color)

ParameterTypeDefaultDescription
conditionboolWhen true, draw the shape
titlestring“Shape”Display name
styleconstshape.circleShape type
locationconstlocation.abovebarPlacement
colorcolorcolor.blueShape color

Shape Styles

ConstantDescription
shape.circleFilled circle
shape.squareFilled square
shape.diamondDiamond
shape.triangleupUpward triangle
shape.triangledownDownward triangle
shape.arrowupUp arrow
shape.arrowdownDown arrow
shape.labelupUp label
shape.labeldownDown label
shape.xcrossX cross
shape.crossPlus cross
shape.flagFlag

Shape Locations

ConstantDescription
location.abovebarAbove the candle
location.belowbarBelow the candle
location.topTop of pane
location.bottomBottom of pane
location.absoluteAt the series value
bullish = ta.crossover(ta.sma(close, 20), ta.sma(close, 50))
bearish = ta.crossunder(ta.sma(close, 20), ta.sma(close, 50))
plotshape(bullish, title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green)
plotshape(bearish, title="Sell", style=shape.triangledown, location=location.abovebar, color=color.red)

hline

Draws a horizontal line at a fixed price level. Commonly used for overbought/oversold thresholds on oscillators.

Syntax: hline(price, title, color, linestyle)

ParameterTypeDefaultDescription
pricefloatConstant price level
titlestringDisplay name
colorcolorcolor.grayLine color
linestyleconsthline.style_solidLine style

Horizontal Line Styles

ConstantDescription
hline.style_solidSolid line
hline.style_dottedDotted line
hline.style_dashedDashed line
rsiVal = ta.rsi(close, 14)
plot(rsiVal, title="RSI", color=color.purple)
hline(70, "Overbought", color=color.red, linestyle=hline.style_dashed)
hline(30, "Oversold", color=color.green, linestyle=hline.style_dashed)

fill

Fills the area between two plots with a semi-transparent color.

Syntax: fill(plot1, plot2, color, title)

ParameterTypeDefaultDescription
plot1plotFirst plot reference
plot2plotSecond plot reference
colorcolorcolor.blueFill color
titlestringDisplay name
upper = ta.sma(close, 20) + 2 * ta.stdev(close, 20)
lower = ta.sma(close, 20) - 2 * ta.stdev(close, 20)
p1 = plot(upper, title="Upper", color=color.blue)
p2 = plot(lower, title="Lower", color=color.blue)
fill(p1, p2, color=color.new(color.blue, 90), title="Band")

bgcolor

Colors the chart background based on a condition or value. Useful for visually highlighting market regimes.

Syntax: bgcolor(color, title)

ParameterTypeDefaultDescription
colorcolorBackground color (use na for no color)
titlestring“Background”Display name
isBullish = close > ta.sma(close, 50)
bgcolor(color.new(isBullish ? color.green : color.red, 90), title="Trend")

barcolor

Colors the candlestick bars. Overrides the default green/red candle coloring.

Syntax: barcolor(color, title)

ParameterTypeDefaultDescription
colorcolorCandle color (use na for default)
titlestring“Bar Color”Display name
vol_high = volume > 2 * ta.sma(volume, 20)
barcolor(vol_high ? color.orange : na, title="High Volume")

Color Functions

color.rgb

Creates a color from red, green, and blue components.

Syntax: color.rgb(red, green, blue)

ParameterTypeRangeDescription
redint0–255Red channel
greenint0–255Green channel
blueint0–255Blue channel
plot(close, color=color.rgb(255, 165, 0))

color.new

Creates a color with transparency applied.

Syntax: color.new(color, transp)

ParameterTypeDescription
colorcolorBase color
transpintTransparency (0 = opaque, 100 = invisible)

Color Constants

ConstantHex
color.red#F23645
color.green#4CAF50
color.blue#2196F3
color.orange#FF9800
color.purple#9C27B0
color.yellow#FDD835
color.white#FFFFFF
color.black#363A45
color.gray#787B86
color.lime#00E676
color.aqua#00BCD4
color.fuchsia#E040FB
color.teal#089981
color.navy#311B92
color.maroon#880E4F
color.olive#808000
color.silver#B2B5BE

Strategy Functions

Strategy Functions

Strategy scripts may place market and limit entries, market orders, price- and tick-based exits, trailing exits, immediate or next-bar closes, and order cancellations. Unlisted strategy functions, arguments, and overloads are rejected.

Historical execution model

TrainBard evaluates the selected OHLC candles without intrabar tick updates. Orders normally fill at the next bar open. A supported process_orders_on_close=true declaration fills newly queued market orders at the current close, and strategy.close(..., immediately=true) or strategy.close_all(..., immediately=true) also fills at the current close.

When the same candle touches both a stop and a limit, TrainBard uses the conservative fill for that trade. Tick distances use syminfo.mintick, and generated order prices are rounded to valid tick increments. The backtest configuration applies the final fee/slippage assumption; its default is 0.1% unless overridden.

Short positions are supported for cash-denominated backtests. Coin-denominated shorts are not supported.

strategy declaration

Syntax: strategy(title, shorttitle, overlay, initial_capital, pyramiding, default_qty_type, default_qty_value, commission_type, commission_value, slippage, process_orders_on_close, calc_on_every_tick, ...)

The supported subset includes:

  • Literal title, short title, overlay, initial capital, and pyramiding metadata.
  • Positive strategy.fixed sizing.
  • strategy.percent_of_equity sizing greater than zero through 100.
  • commission_type=strategy.commission.percent with commission_value=0.
  • Non-negative integer slippage in syminfo.mintick units.
  • Literal process_orders_on_close.
  • calc_on_every_tick=false.
  • Literal drawing limits from 1 through 500.

strategy.cash, non-zero declaration commission, leveraged percentages above 100, and other declaration arguments are not supported.

strategy.entry

Places a market or limit entry. Opposite entries reverse the position. Pyramiding and proven runtime quantities are supported.

Syntax: strategy.entry(id, direction, qty, limit)

ParameterRequiredDescription
idyesLiteral or unreassigned top-level literal-string order identifier
directionyesstrategy.long or strategy.short
qtynoPositive asset quantity; overrides declaration sizing
limitnoVerified numeric limit price

Limit orders become eligible on the next bar, honor a better opening price, and update in place when the same ID is submitted again. Stop-entry and OCA metadata are not supported.

strategy.entry("Long", strategy.long)
strategy.entry("Pullback", strategy.long, qty=1, limit=close - ta.atr(14))

strategy.order

Places a market order that nets against the current position and ignores pyramiding.

Syntax: strategy.order(id, direction, qty)

An omitted quantity uses admitted declaration sizing when available. Limit, stop, and OCA arguments are not supported.

strategy.exit

Registers or updates an exit for an entry.

Syntax: strategy.exit(id, from_entry, qty, qty_percent, profit, limit, loss, stop, trail_points, trail_offset, oca_name, comments...)

ParameterDescription
idStatic exit identifier
from_entryRequired static entry identifier
qtyAsset quantity to close
qty_percentPercentage of the matching entry to close
profit / lossTake-profit or stop-loss distance in ticks
limit / stopAbsolute exit price
trail_pointsTrailing activation distance in ticks
trail_offsetTrailing stop distance in ticks; must accompany trail_points

trail_price, alert fields, disable-alert fields, and general OCA grouping are unsupported. A constant oca_name is accepted only where one exit/from-entry key makes grouping irrelevant.

if strategy.position_size == 0
    strategy.entry("Long", strategy.long, qty=2)

if strategy.position_size > 0
    strategy.exit("Half", "Long", qty_percent=50, profit=100, loss=50)
    strategy.exit("Trail", "Long", trail_points=100, trail_offset=50)

strategy.close and strategy.close_all

strategy.close(id, comment, immediately) closes the matching entry ID. strategy.close_all(comment, immediately) closes every open entry. Comments are descriptive. Quantity, alert, and disable-alert parameters are not supported on these calls.

strategy.close("Long")
strategy.close_all(immediately=true)

strategy.cancel and strategy.cancel_all

strategy.cancel(id) removes pending orders with the matching ID. strategy.cancel_all() removes all pending market, entry, and exit orders.

Strategy state

The following variables are available while a strategy runs:

VariableDescription
strategy.position_sizeCurrent signed position quantity
strategy.position_avg_priceCurrent average entry price
strategy.position_entry_nameCurrent entry ID
strategy.equityPine-visible gross equity
strategy.openprofitGross open profit
strategy.netprofitGross closed profit
strategy.grossprofit / strategy.grosslossGross winning/loss totals
strategy.closedtrades / strategy.opentradesTrade counts
strategy.wintrades / strategy.losstrades / strategy.eventradesOutcome counts
strategy.avg_tradeNet profit divided by closed trades
strategy.avg_winning_tradeGross profit divided by winning trades
strategy.avg_losing_tradeGross loss divided by losing trades
strategy.initial_capitalDeclared initial capital

State updates after the corresponding fill, not when the order is submitted.

Closed-trade inspection

Each supported function takes a zero-based trade_num:

  • strategy.closedtrades.entry_price(trade_num)
  • strategy.closedtrades.exit_price(trade_num)
  • strategy.closedtrades.entry_time(trade_num)
  • strategy.closedtrades.exit_time(trade_num)
  • strategy.closedtrades.entry_bar_index(trade_num)
  • strategy.closedtrades.exit_bar_index(trade_num)
  • strategy.closedtrades.entry_id(trade_num)
  • strategy.closedtrades.exit_id(trade_num)
  • strategy.closedtrades.profit(trade_num)
  • strategy.closedtrades.profit_percent(trade_num)
  • strategy.closedtrades.size(trade_num)

Open-trade inspection

Each supported function takes a zero-based trade_num:

  • strategy.opentrades.entry_price(trade_num)
  • strategy.opentrades.entry_time(trade_num)
  • strategy.opentrades.entry_bar_index(trade_num)
  • strategy.opentrades.entry_id(trade_num)
  • strategy.opentrades.profit(trade_num)
  • strategy.opentrades.profit_percent(trade_num)
  • strategy.opentrades.size(trade_num)

Trade comments, commission accessors, drawdown/run-up accessors, strategy.risk.*, margin fields, and unlisted strategy state are not supported.

Math Functions

Math Functions

Mathematical functions for arithmetic, trigonometry, and rounding. These operate on scalar values (not series).

Arithmetic

FunctionDescription
math.abs(x)Absolute value
math.sign(x)Sign (-1, 0, or 1)
math.min(x, y)Minimum of two values
math.max(x, y)Maximum of two values
math.avg(x, y, ...)Average of N values
math.pow(base, exp)Power
math.sqrt(x)Square root
math.cbrt(x)Cube root
math.exp(x)e raised to the power x
math.log(x)Natural logarithm
math.log10(x)Base-10 logarithm
math.hypot(x, y)Hypotenuse: sqrt(x^2 + y^2)
math.sum(source, length)Rolling sum of a series over length bars
vol = math.sqrt(ta.variance(close, 20))
logReturn = math.log(close / close[1])

Rounding

FunctionDescription
math.round(x)Round to nearest integer
math.floor(x)Round down
math.ceil(x)Round up
math.trunc(x)Truncate toward zero
math.round_to_mintick(x)Round to the symbol’s syminfo.mintick

math.round_to_mintick() uses the selected market’s tick size. The same tick size is used when strategy.exit() converts profit, loss, trail_points, and trail_offset into prices.

Trigonometry

FunctionDescription
math.sin(x)Sine (radians)
math.cos(x)Cosine (radians)
math.tan(x)Tangent (radians)
math.asin(x)Arcsine
math.acos(x)Arccosine
math.atan(x)Arctangent
math.atan2(y, x)Two-argument arctangent
math.sinh(x)Hyperbolic sine
math.cosh(x)Hyperbolic cosine
math.tanh(x)Hyperbolic tangent
math.todegrees(x)Convert radians to degrees
math.toradians(x)Convert degrees to radians

Constants

ConstantValueDescription
math.pi3.14159…Pi
math.e2.71828…Euler’s number
math.phi1.61803…Golden ratio
math.rphi0.61803…Reciprocal golden ratio

Other

FunctionDescription
math.random()Random number between 0 and 1

String Functions

String Functions

Functions for working with string values.

Conversion

FunctionDescription
str.tostring(value, format)Convert value to string. Optional format for decimals.
str.tonumber(string)Parse a string to a number. Returns NaN if invalid.
label_text = str.tostring(close, "#.##")
val = str.tonumber("3.14")

Query

FunctionDescription
str.length(string)Number of characters
str.contains(string, substr)true if string contains substr
str.startswith(string, prefix)true if string starts with prefix
str.endswith(string, suffix)true if string ends with suffix
str.indexof(string, substr)Index of first occurrence, or -1
str.pos(string, substr)Alias for str.indexof
str.match(string, regex)true if regex matches

Transform

FunctionDescription
str.lower(string)Convert to lowercase
str.upper(string)Convert to uppercase
str.trim(string)Remove leading/trailing whitespace
str.substring(string, start, end)Extract a substring
str.replace(string, old, new, n)Replace first (or nth) occurrence
str.replace_all(string, old, new)Replace all occurrences
str.repeat(string, n)Repeat string n times
str.split(string, separator)Split into array of strings

Formatting

FunctionDescription
str.format(template, arg0, ...)Format string with {0}, {1} placeholders
msg = str.format("Price: {0}, Volume: {1}", close, volume)

Array Functions

Array Functions

Functions for creating and manipulating dynamic arrays. Arrays persist across bars when declared with var.

Creating Arrays

FunctionDescription
array.new_float(size, value)Create float array, optionally filled
array.new_int(size, value)Create integer array
array.new_bool(size, value)Create boolean array
array.new_string(size, value)Create string array
array.from(value1, value2, ...)Create an array from up to 4,000 values
array.copy(arr)Copy an existing array
var prices = array.new_float(0)

Access & Mutation

FunctionDescription
array.get(arr, index)Get element at index
array.set(arr, index, value)Set element at index
array.push(arr, value)Add to end
array.pop(arr)Remove and return last element
array.unshift(arr, value)Add to beginning
array.shift(arr)Remove and return first element
array.insert(arr, index, value)Insert at index
array.remove(arr, index)Remove at index
array.clear(arr)Remove all elements
array.fill(arr, value, from, to)Fill range with value

Query

FunctionDescription
array.size(arr)Number of elements
array.first(arr)First element
array.last(arr)Last element
array.includes(arr, value)true if value is present
array.indexof(arr, value)Index of first occurrence
array.lastindexof(arr, value)Index of last occurrence

Math & Statistics

FunctionDescription
array.sum(arr)Sum of all elements
array.avg(arr)Arithmetic mean
array.min(arr)Minimum value
array.max(arr)Maximum value
array.median(arr)Median value
array.mode(arr)Most frequent value
array.stdev(arr)Sample standard deviation
array.variance(arr)Sample variance
array.range(arr)max - min
array.covariance(arr1, arr2)Sample covariance
array.abs(arr)Absolute value of each element
array.percentile_linear_interpolation(arr, pct)Percentile (interpolated)
array.percentile_nearest_rank(arr, pct)Percentile (nearest rank)
array.percentrank(arr, index)Percent rank of the element at index

Ordering

FunctionDescription
array.sort(arr, order)Sort in place (0=asc, 1=desc)
array.reverse(arr)Reverse in place
array.sort_indices(arr, order)Return sorted index array

Slicing & Combining

FunctionDescription
array.splice(arr, index, count)TrainBard extension that removes elements and returns them
array.concat(arr1, arr2)Concatenate two arrays
array.join(arr, separator)Join elements into a string
FunctionDescription
array.binary_search(arr, value)Binary search (sorted array). Returns index or -1.
array.binary_search_leftmost(arr, value)Leftmost insertion point
array.binary_search_rightmost(arr, value)Rightmost insertion point

Predicates

FunctionDescription
array.every(arr)true when every bool/int/float element is truthy
array.some(arr)true when any bool/int/float element is truthy

array.slice and array.standardize are known but unsupported. Collection receiver syntax such as prices.push(close) is supported only when TrainBard can prove the receiver type. Mutating procedures such as push, set, sort, and clear return void and must be used as statements.

Map Functions

Map Functions

Functions for creating and manipulating key-value maps. Maps persist across bars when declared with var.

Creating Maps

FunctionDescription
map.new<K, V>()Create a typed empty map
map.copy(m)Create a copy of a map
var myMap = map.new<string, float>()

Access & Mutation

FunctionDescription
map.put(m, key, value)Set key to value
map.get(m, key)Get a value by key, or na when missing
map.remove(m, key)Remove key and return its value
map.clear(m)Remove all entries
map.put_all(m, other)Copy all entries from another map

Query

FunctionDescription
map.contains(m, key)true if key exists
map.size(m)Number of entries
map.keys(m)Array of all keys
map.values(m)Array of all values
var levels = map.new<string, float>()
map.put(levels, "support", low)
map.put(levels, "resistance", high)

if map.contains(levels, "support")
    sl = map.get(levels, "support")

Keys and values must use supported primitive types: float, int, bool, string, or color. The untyped map.new() spelling and a default-value overload for map.get() are not supported.

Matrix Functions

Matrix Functions

Functions for creating and manipulating 2D matrices, including linear algebra operations used in quantitative strategies.

Creating Matrices

FunctionDescription
matrix.new<type>(rows, cols, value)Create a typed float or integer matrix
matrix.copy(m)Deep copy
var m = matrix.new<float>(3, 3, 0)

Access & Mutation

FunctionDescription
matrix.get(m, row, col)Get element
matrix.set(m, row, col, value)Set element
matrix.row(m, index)Get row as array
matrix.col(m, index)Get column as array
matrix.fill(m, value, r0, c0, r1, c1)Fill a range

Dimensions

FunctionDescription
matrix.rows(m)Number of rows
matrix.columns(m)Number of columns
matrix.elements_count(m)Number of elements

Row & Column Operations

FunctionDescription
matrix.add_row(m, index, arr)Insert row
matrix.add_col(m, index, arr)Insert column
matrix.remove_row(m, index)Remove and return row
matrix.remove_col(m, index)Remove and return column
matrix.swap_rows(m, r1, r2)Swap two rows
matrix.swap_columns(m, c1, c2)Swap two columns
matrix.submatrix(m, r0, c0, r1, c1)Extract sub-matrix
matrix.reverse(m)Reverse all elements across rows and columns
matrix.concat(m1, m2)Append rows from m2 to m1
matrix.sort(m, column, order)Sort rows by a column

Aggregation

FunctionDescription
matrix.sum(m)Sum of all elements
matrix.avg(m)Average of all elements
matrix.min(m)Minimum element
matrix.max(m)Maximum element
matrix.median(m)Median element
matrix.mode(m)Most frequent element
matrix.trace(m)Sum of diagonal elements

Linear Algebra

FunctionDescription
matrix.transpose(m)Transpose
matrix.reshape(m, rows, cols)Reshape to new dimensions
matrix.mult(a, b)Matrix multiply (or scalar multiply)
matrix.diff(a, b)Element-wise subtraction
matrix.det(m)Determinant
matrix.kron(a, b)Kronecker product

Properties

FunctionDescription
matrix.is_square(m)true if rows == columns
matrix.is_symmetric(m)true if m == transpose(m)
matrix.is_antisymmetric(m)true if m == -transpose(m)
matrix.is_diagonal(m)true if all off-diagonal = 0
matrix.is_antidiagonal(m)true if all non-antidiagonal values are 0
matrix.is_identity(m)true if identity matrix
matrix.is_binary(m)true if all values are 0 or 1
matrix.is_zero(m)true if all values are 0
matrix.is_triangular(m)true if upper or lower triangular
matrix.is_stochastic(m)true if each row contains non-negative values that sum to 1

matrix.inv, matrix.pinv, matrix.rank, matrix.eigenvalues, matrix.eigenvectors, and matrix.pow are known but unsupported. Mutating procedures such as set, fill, reshape, sort, and row/column swaps return void and must be used as statements.

Utilities, Time, Requests & Drawings

Utilities, Time, Requests & Drawings

Missing values and casts

FunctionSupported behavior
naMissing-value literal
na(x)Numeric missing-value check
nz(source, replacement)Numeric replacement; defaults to zero
fixnan(source)Stateful numeric forward-fill from the last non-na value
int(x)Truncates a numeric value toward zero
float(x)Converts a proven numeric value to float
bool(x)Converts a proven bool or numeric value
max_bars_back(var, num)Validated, zero-runtime-cost history hint

String/color casts and other overloads are not supported.

request.security

Fetches or locally aggregates supported data from another symbol or timeframe.

Syntax: request.security(symbol, timeframe, expression, gaps, lookahead)

The call must be assigned directly to a scalar variable or a matching tuple declaration. TrainBard accepts a literal symbol, syminfo.ticker, or syminfo.tickerid; a non-empty literal timeframe, or input.timeframe for the current symbol; and supported direct OHLCV-derived expressions, ta.sma/ta.ema, bounded tuples of direct sources, or an admitted no-argument scalar UDF. A script may lower at most 40 requested outputs.

dailyClose = request.security(syminfo.tickerid, "D", close)
[dailyHigh, dailyLow] = request.security(syminfo.tickerid, "D", [high, low])

Omitted lookahead uses barmerge.lookahead_off. barmerge.lookahead_on is supported but exposes an active requested bar from its opening timestamp and can repaint. barmerge.gaps_off forward-fills aligned values. Other request.* functions and optional request.security arguments are unsupported.

Time and timeframe

Function or memberSupported behavior
dayofweek(timestamp)UTC day of week for a proven integer timestamp
time(timeframe)Opening timestamp of the containing UTC timeframe bucket
time(timeframe.period, session, timezone)Chart timestamp while inside the supplied session, otherwise na
timeframe.change(timeframe)True at the first bar in a new UTC bucket
timeframe.in_seconds(timeframe)Converts a supported fixed timeframe; argument may be omitted
timeframe.periodNormalized chart timeframe
timeframe.multiplierFixed chart timeframe multiplier
timeframe.isintraday / timeframe.isdailyFixed chart-timeframe flags

Weeks begin Monday UTC. Calendar functions with timezone overloads and timestamp() are not supported.

Color functions

TrainBard supports #RRGGBB and #RRGGBBAA literals, 17 color.* constants, and:

  • color.new(color, transp)
  • color.rgb(red, green, blue, transp)
  • color.from_gradient(value, bottom_value, top_value, bottom_color, top_color)
  • color.r(color), color.g(color), color.b(color), and color.t(color)

Transparency ranges from 0 (opaque) through 100 (transparent).

Historical drawings

TrainBard exposes the final representable drawing state from these supported subsets:

FunctionSupported subset
line.new(x1, y1, x2, y2, ...)Bar-index coordinates, colors, three line styles, width 1–100, and extend.right
line.delete(id)Deletes a proven line reference
box.new(left, top, right, bottom, ...)Colors, three border styles, text, and tiny/small text sizes
box.delete(id)Deletes a proven box reference
box.get_top(id) / box.get_bottom(id)Reads an active box boundary
label.new(x, y, text, ...)Colors, relative above/below-bar placement, three admitted label styles, and tiny/small sizes
label.delete(id)Deletes a proven label reference
table.new(position.top_right, columns, rows, ...)Literal positive dimensions and admitted colors/border width
table.cell(table_id, column, row, text, ...)Text, foreground/background color, limited alignment, and tiny/small sizes

Drawings are historical final state, not an intrabar command log. Setters, copies, *.all, chart.point, polylines, linefills, and unlisted drawing APIs are unsupported.

Runtime errors and alert observations

runtime.error(message) is a statement-only function that halts execution with a proven string message.

alertcondition(condition, title, message) is supported at global scope as historical observation metadata. It records the bar indices where a proven boolean condition was true; it does not create, schedule, or deliver live alerts. alert() and log.* are unsupported.