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:
| Variable | Description |
|---|
open | Opening price |
high | Highest price |
low | Lowest price |
close | Closing price |
volume | Bar volume |
hl2 | (high + low) / 2 |
hlc3 | (high + low + close) / 3 |
ohlc4 | (open + high + low + close) / 4 |
hlcc4 | (high + low + close + close) / 4 |
time | Bar timestamp (Unix ms) |
bar_index | Current bar number (0-based) |
last_bar_index | Index of the final loaded historical bar |
last_bar_time | Timestamp of the final loaded historical bar |
timenow | Current execution timestamp |
Symbol Variables
| Variable | Description |
|---|
syminfo.tickerid | Current symbol identifier |
syminfo.ticker | Current symbol |
syminfo.mintick | Symbol tick size used by tick-based exits and math.round_to_mintick() |
syminfo.pointvalue | Market 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
| Variable | Description |
|---|
year | UTC year |
month | UTC month (1-12) |
dayofmonth | UTC day of month |
dayofweek | UTC day of week (1=Sun) |
hour | UTC hour |
minute | UTC minute |
second | UTC second |
Strategy Constants
| Constant | Description |
|---|
strategy.long | Long direction |
strategy.short | Short 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 define user-configurable parameters for your strategy. When running a backtest, parameter values can be set individually or as ranges for optimization.
Declares an integer input parameter.
Syntax: input.int(defval, title, minval, maxval, tooltip, inline, group)
| Parameter | Type | Description |
|---|
defval | int | Default value |
title | string | Display 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.
Declares a floating-point input parameter.
Syntax: input.float(defval, title, minval, maxval, step, tooltip, inline, group)
| Parameter | Type | Description |
|---|
defval | float | Default value |
title | string | Display 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")
Declares a boolean input parameter.
Syntax: input.bool(defval, title)
| Parameter | Type | Description |
|---|
defval | bool | Default value (true or false) |
title | string | Display name |
useLong = input.bool(true, "Enable Long")
Declares a string input parameter.
Syntax: input.string(defval, title)
| Parameter | Type | Description |
|---|
defval | string | Default value |
title | string | Display name |
maType = input.string("SMA", "MA Type")
| Function | Supported 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.
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)
| Parameter | Type | Description |
|---|
source | series | Input series (e.g. close) |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Default | Description |
|---|
series | series | | Input series |
length | int | | Window size |
offset | float | 0.85 | Gaussian offset (0–1) |
sigma | float | 6 | Gaussian 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
ta.dema
Double Exponential Moving Average. 2 * EMA - EMA(EMA). Reduces lag compared to a standard EMA.
Syntax: ta.dema(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Efficiency 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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
length | int | | EMA period |
factor | float | 0.7 | Volume 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Source (typically close) |
high | series | High series |
low | series | Low series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
cmo14 = ta.cmo(close, 14)
ta.tsi
True Strength Index. Double-smoothed momentum oscillator.
Syntax: ta.tsi(source, short_length, long_length)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
short_length | int | 13 | Short EMA period |
long_length | int | 25 | Long 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)
| Parameter | Type | Description |
|---|
length | int | Lookback period |
ta.mom
Momentum. The difference between the current value and the value length bars ago.
Syntax: ta.mom(source, length)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
length | int | 1 | Bars 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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.
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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
fastlen | int | 12 | Fast EMA period |
slowlen | int | 26 | Slow EMA period |
siglen | int | 9 | Signal 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)
| Parameter | Type | Description |
|---|
length | int | Lookback period |
ta.natr
Normalized Average True Range. ATR expressed as a percentage of the closing price.
Syntax: ta.natr(length)
| Parameter | Type | Description |
|---|
length | int | Lookback period |
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.
ta.bb
Bollinger Bands. Returns three series: middle band (SMA), upper band, and lower band.
Syntax: [middle, upper, lower] = ta.bb(series, length, mult)
| Parameter | Type | Default | Description |
|---|
series | series | | Input series |
length | int | | SMA period |
mult | float | 2 | Standard 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)
| Parameter | Type | Default | Description |
|---|
series | series | | Input series |
length | int | | SMA period |
mult | float | 2 | Standard 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)
| Parameter | Type | Default | Description |
|---|
series | series | | Input series |
length | int | | EMA period |
mult | float | 1.5 | ATR multiplier |
useTrueRange | bool | true | Use 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)
| Parameter | Type | Default | Description |
|---|
series | series | | Input series |
length | int | | EMA period |
mult | float | 1.5 | ATR multiplier |
useTrueRange | bool | true | Use 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)
| Parameter | Type | Default | Description |
|---|
length | int | 20 | Lookback period |
[dcMid, dcUpper, dcLower] = ta.donchian(20)
ta.stdev
Standard Deviation over a rolling window.
Syntax: ta.stdev(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
sd20 = ta.stdev(close, 20)
ta.variance
Variance over a rolling window.
Syntax: ta.variance(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
v20 = ta.variance(close, 20)
ta.dev
Mean absolute deviation over a rolling window.
Syntax: ta.dev(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Default | Description |
|---|
factor | float | 3 | ATR multiplier |
atrPeriod | int | 10 | ATR 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)
| Parameter | Type | Default | Description |
|---|
di_length | int | 14 | DI period |
adx_smoothing | int | 14 | ADX smoothing period |
ta.dmi
Directional Movement Index. Returns three series: +DI, -DI, and ADX.
Syntax: [plusDI, minusDI, adx] = ta.dmi(diLength, adxSmoothing)
| Parameter | Type | Default | Description |
|---|
diLength | int | 14 | DI period |
adxSmoothing | int | 14 | ADX 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)
| Parameter | Type | Default | Description |
|---|
start | float | 0.02 | Initial acceleration factor |
inc | float | 0.02 | Acceleration increment |
max | float | 0.2 | Maximum 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)
| Parameter | Type | Default | Description |
|---|
length | int | 14 | Lookback period |
[arUp, arDown] = ta.aroon(14)
ta.vwap
Volume-Weighted Average Price. The cumulative average price weighted by volume.
Syntax: ta.vwap(source)
| Parameter | Type | Description |
|---|
source | series | Input series (typically 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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
length | int | | Regression period |
offset | int | 0 | Bar 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
ta.mfi
Money Flow Index. A volume-weighted RSI oscillator (0–100).
Syntax: ta.mfi(series, length)
| Parameter | Type | Description |
|---|
series | series | Typical price (usually hlc3) |
length | int | Lookback period |
ta.pvt
Price Volume Trend. Cumulative volume weighted by the percentage change in close price.
Syntax: ta.pvt()
No parameters.
ta.cmf
Chaikin Money Flow. Measures money flow volume over a period, ranging from -1 to +1.
Syntax: ta.cmf(length)
| Parameter | Type | Default | Description |
|---|
length | int | 20 | Lookback period |
ta.ad
Chaikin A/D Line (Accumulation/Distribution). Running total of money flow volume.
Syntax: ta.ad()
No parameters.
ta.accdist
Accumulation/Distribution index. Cumulative CLV (Close Location Value) multiplied by volume. Available as a built-in variable.
Syntax: ta.accdist
ta.wad
Williams Accumulation/Distribution. Measures buying and selling pressure using true range direction.
Syntax: 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
ta.nvi
Negative Volume Index. Tracks price changes on days when volume decreases. Starts at 1000.
Syntax: ta.nvi
ta.pvi
Positive Volume Index. Tracks price changes on days when volume increases. Starts at 1000.
Syntax: ta.pvi
ta.iii
Intraday Intensity Index. (2 * close - high - low) / ((high - low) * volume). Measures the intraday pressure.
Syntax: 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)
| Parameter | Type | Description |
|---|
source1 | series | Series that crosses above |
source2 | series | Series 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)
| Parameter | Type | Description |
|---|
source1 | series | Series that crosses below |
source2 | series | Series 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)
| Parameter | Type | Description |
|---|
source1 | series | First series |
source2 | series | Second 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
hh20 = ta.highest(high, 20)
ta.lowest
Returns the lowest value of source over the last length bars.
Syntax: ta.lowest(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
recordClose = ta.max(close)
ta.min
Returns the all-time lowest value of source up to the current bar.
Syntax: ta.min(source)
| Parameter | Type | Description |
|---|
source | series | Input 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback 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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series |
length | int | 1 | Bars 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Number 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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series (typically high) |
leftbars | int | 5 | Left confirmation bars |
rightbars | int | 5 | Right 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)
| Parameter | Type | Default | Description |
|---|
source | series | | Input series (typically low) |
leftbars | int | 5 | Left confirmation bars |
rightbars | int | 5 | Right confirmation bars |
pl = ta.pivotlow(low, 5, 5)
Returns the number of bars since condition was last true.
Syntax: ta.barssince(condition)
| Parameter | Type | Description |
|---|
condition | bool series | Condition 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)
| Parameter | Type | Default | Description |
|---|
condition | bool series | | Condition to match |
source | series | | Value to capture |
occurrence | int | 0 | 0 = 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)
| Parameter | Type | Description |
|---|
source | series | Input 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)
| Parameter | Type | Description |
|---|
source1 | series | First series |
source2 | series | Second series |
length | int | Lookback 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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
ta.beta
Beta coefficient of source relative to a benchmark over a rolling window.
Syntax: ta.beta(source, benchmark, length)
| Parameter | Type | Description |
|---|
source | series | Asset returns |
benchmark | series | Benchmark returns |
length | int | Lookback period |
b = ta.beta(close, open, 20)
Rolling median of source over length bars.
Syntax: ta.median(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
med20 = ta.median(close, 20)
ta.mode
Rolling mode (most frequent value) of source over length bars.
Syntax: ta.mode(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
modeVal = ta.mode(close, 20)
ta.range
Rolling range (highest minus lowest) of source over length bars.
Syntax: ta.range(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
rng = ta.range(close, 20)
ta.percentrank
Percent rank of the current value within the previous length values.
Syntax: ta.percentrank(source, length)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
pr = ta.percentrank(close, 20)
ta.percentile_linear_interpolation
Rolling percentile using linear interpolation.
Syntax: ta.percentile_linear_interpolation(source, length, percentage)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
percentage | float | Percentile (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)
| Parameter | Type | Description |
|---|
source | series | Input series |
length | int | Lookback period |
percentage | float | Percentile (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)
| Parameter | Type | Default | Description |
|---|
series | float | | Data series to plot |
title | string | | Display name in the legend |
color | color | color.blue | Line/fill color |
linewidth | int | 1 | Line thickness (1–4) |
style | const | plot.style_line | Visual style |
trackprice | bool | false | Extend a tracked price marker across the pane |
histbase | int/float | 0 | Base level for area, columns, and histograms |
offset | int | 0 | Shift the plot left or right in bars |
join | bool | false | Join circle/cross markers with a line |
editable | bool | true | Allow style edits in chart settings |
show_last | int | | Only show the last N bars |
display | const | display.all | Output locations for plot values |
format | const | | Numeric format override |
precision | int | | Decimal precision override |
force_overlay | bool | false | Draw in the main chart pane |
linestyle | const | plot.linestyle_solid | Line dash style |
Plot Styles
| Constant | Description |
|---|
plot.style_line | Continuous line (default) |
plot.style_stepline | Stepped line |
plot.style_stepline_diamond | Stepped line with diamond transitions |
plot.style_histogram | Vertical bars from zero |
plot.style_columns | Column bars |
plot.style_circles | Dot markers |
plot.style_area | Filled area under line |
plot.style_areabr | Area with breaks on NaN |
plot.style_cross | Cross markers |
plot.style_linebr | Line with breaks on NaN |
Line Styles
| Constant | Description |
|---|
plot.linestyle_solid | Solid line |
plot.linestyle_dashed | Dashed line |
plot.linestyle_dotted | Dotted line |
| Constant | Description |
|---|
display.all | Show everywhere |
display.none | Calculate without displaying |
display.pane | Script pane |
display.status_line | Status line |
display.data_window | Data Window |
display.price_scale | Price scale |
format.price | Price formatting |
format.percent | Percent formatting |
format.volume | Volume formatting |
format.mintick | Minimum 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)
| Parameter | Type | Default | Description |
|---|
condition | bool | | When true, draw the shape |
title | string | “Shape” | Display name |
style | const | shape.circle | Shape type |
location | const | location.abovebar | Placement |
color | color | color.blue | Shape color |
Shape Styles
| Constant | Description |
|---|
shape.circle | Filled circle |
shape.square | Filled square |
shape.diamond | Diamond |
shape.triangleup | Upward triangle |
shape.triangledown | Downward triangle |
shape.arrowup | Up arrow |
shape.arrowdown | Down arrow |
shape.labelup | Up label |
shape.labeldown | Down label |
shape.xcross | X cross |
shape.cross | Plus cross |
shape.flag | Flag |
Shape Locations
| Constant | Description |
|---|
location.abovebar | Above the candle |
location.belowbar | Below the candle |
location.top | Top of pane |
location.bottom | Bottom of pane |
location.absolute | At 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)
| Parameter | Type | Default | Description |
|---|
price | float | | Constant price level |
title | string | | Display name |
color | color | color.gray | Line color |
linestyle | const | hline.style_solid | Line style |
Horizontal Line Styles
| Constant | Description |
|---|
hline.style_solid | Solid line |
hline.style_dotted | Dotted line |
hline.style_dashed | Dashed 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)
| Parameter | Type | Default | Description |
|---|
plot1 | plot | | First plot reference |
plot2 | plot | | Second plot reference |
color | color | color.blue | Fill color |
title | string | | Display 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)
| Parameter | Type | Default | Description |
|---|
color | color | | Background color (use na for no color) |
title | string | “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)
| Parameter | Type | Default | Description |
|---|
color | color | | Candle color (use na for default) |
title | string | “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)
| Parameter | Type | Range | Description |
|---|
red | int | 0–255 | Red channel |
green | int | 0–255 | Green channel |
blue | int | 0–255 | Blue channel |
plot(close, color=color.rgb(255, 165, 0))
color.new
Creates a color with transparency applied.
Syntax: color.new(color, transp)
| Parameter | Type | Description |
|---|
color | color | Base color |
transp | int | Transparency (0 = opaque, 100 = invisible) |
Color Constants
| Constant | Hex |
|---|
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)
| Parameter | Required | Description |
|---|
id | yes | Literal or unreassigned top-level literal-string order identifier |
direction | yes | strategy.long or strategy.short |
qty | no | Positive asset quantity; overrides declaration sizing |
limit | no | Verified 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...)
| Parameter | Description |
|---|
id | Static exit identifier |
from_entry | Required static entry identifier |
qty | Asset quantity to close |
qty_percent | Percentage of the matching entry to close |
profit / loss | Take-profit or stop-loss distance in ticks |
limit / stop | Absolute exit price |
trail_points | Trailing activation distance in ticks |
trail_offset | Trailing 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:
| Variable | Description |
|---|
strategy.position_size | Current signed position quantity |
strategy.position_avg_price | Current average entry price |
strategy.position_entry_name | Current entry ID |
strategy.equity | Pine-visible gross equity |
strategy.openprofit | Gross open profit |
strategy.netprofit | Gross closed profit |
strategy.grossprofit / strategy.grossloss | Gross winning/loss totals |
strategy.closedtrades / strategy.opentrades | Trade counts |
strategy.wintrades / strategy.losstrades / strategy.eventrades | Outcome counts |
strategy.avg_trade | Net profit divided by closed trades |
strategy.avg_winning_trade | Gross profit divided by winning trades |
strategy.avg_losing_trade | Gross loss divided by losing trades |
strategy.initial_capital | Declared 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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Constant | Value | Description |
|---|
math.pi | 3.14159… | Pi |
math.e | 2.71828… | Euler’s number |
math.phi | 1.61803… | Golden ratio |
math.rphi | 0.61803… | Reciprocal golden ratio |
Other
| Function | Description |
|---|
math.random() | Random number between 0 and 1 |
String Functions
String Functions
Functions for working with string values.
Conversion
| Function | Description |
|---|
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
| Function | Description |
|---|
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 |
| Function | Description |
|---|
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 |
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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 |
Search
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
matrix.rows(m) | Number of rows |
matrix.columns(m) | Number of columns |
matrix.elements_count(m) | Number of elements |
Row & Column Operations
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Description |
|---|
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
| Function | Supported behavior |
|---|
na | Missing-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 member | Supported 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.period | Normalized chart timeframe |
timeframe.multiplier | Fixed chart timeframe multiplier |
timeframe.isintraday / timeframe.isdaily | Fixed 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:
| Function | Supported 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.