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:
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)
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.
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)
Parameter
Type
Description
defval
bool
Default value (true or false)
title
string
Display name
useLong = input.bool(true, "Enable Long")
input.string
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")
Additional supported inputs
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.
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)
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
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)
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.
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
atr14 = ta.atr(14)
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
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.
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.
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.
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.
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.
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")
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.
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.
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.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.