Pine Script Reference

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

Introduction

Pine Script Reference

Welcome to the Muuned Pine Script documentation. This reference covers all supported functions, operators, and built-in variables available in the script editor.

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)

Symbol Variables

VariableDescription
syminfo.tickeridCurrent symbol identifier
syminfo.tickerCurrent symbol
syminfo.basecurrencyBase asset
syminfo.currencyQuote asset
syminfo.mintickSymbol tick size used by tick-based exits and math.round_to_mintick()

Backtesting Behavior

Muuned evaluates strategies on the selected candle data. It does not replay intrabar ticks.

Simple entry/close strategies use a fast signal path. Strategies with entry-specific exits, partial exits, stop/limit/profit/loss exits, trailing exits, multiple entry or exit IDs, or trade introspection use advanced mode so strategy.* state is available while the script runs.

Market entries and market closes fill on the next candle. If a candle touches both stop and limit for an open trade, Muuned uses the conservative fill.

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)

ParameterTypeDescription
defvalintDefault value
titlestringDisplay name in the parameter form
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)

ParameterTypeDescription
defvalfloatDefault value
titlestringDisplay name
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")

input.source

Declares a price source input parameter.

Syntax: input.source(defval, title)

ParameterTypeDescription
defvalseriesDefault source (e.g. close, hl2)
titlestringDisplay name
src = input.source(close, "Source")

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(source, length, offset, sigma)

ParameterTypeDefaultDescription
sourceseriesInput 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, fast, slow, signal)

ParameterTypeDefaultDescription
sourceseriesInput series
fastint12Fast EMA period
slowint26Slow EMA period
signalint9Signal 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(source, length, mult)

ParameterTypeDefaultDescription
sourceseriesInput 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(source, length, mult)

ParameterTypeDefaultDescription
sourceseriesInput 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(source, length, mult, atrLength)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthintEMA period
multfloat1.5ATR multiplier
atrLengthintlengthATR period
[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(source, length, mult)

ParameterTypeDefaultDescription
sourceseriesInput series
lengthintEMA period
multfloat1.5ATR multiplier
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, atrLength)

ParameterTypeDefaultDescription
factorfloat3ATR multiplier
atrLengthint10ATR 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(diLength, adxSmoothing)

ParameterTypeDefaultDescription
diLengthint14DI period
adxSmoothingint14ADX 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(source, length)

ParameterTypeDescription
sourceseriesTypical 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 bar offset (negative) 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 bar offset (negative) 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, transp)

ParameterTypeDefaultDescription
plot1plotFirst plot reference
plot2plotSecond plot reference
colorcolorcolor.blueFill color
titlestringDisplay name
transpint90Transparency (0–100)
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.blue, title="Band", transp=90)

bgcolor

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

Syntax: bgcolor(color, title, transp)

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

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(base_color, transp)

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

Color Constants

ConstantHex
color.red#EF4444
color.green#10B981
color.blue#3B82F6
color.orange#F97316
color.purple#8B5CF6
color.yellow#EAB308
color.white#FFFFFF
color.black#000000
color.gray#6B7280
color.lime#84CC16
color.aqua#06B6D4
color.fuchsia#D946EF
color.teal#14B8A6
color.navy#1E3A8A
color.maroon#881337
color.olive#84CC16
color.silver#E5E7EB

Strategy Functions

Strategy Functions

Strategy functions control position entry, exit, and risk management.

How Orders Execute

Muuned uses two strategy execution paths.

Fast mode is used for simple strategy.entry() plus strategy.close() strategies. The script emits a signal series and the trusted backtester runs the portfolio simulation.

Advanced mode is used when Pine code needs trade state while it runs. This includes strategy.exit() with from_entry, qty, qty_percent, profit, loss, stop, limit, or trailing parameters; multiple entry or exit IDs; and strategy.closedtrades.* or strategy.opentrades.* calls. Advanced mode tracks open entries while the script executes, then the trusted backtester replays the resulting fills for the final summary.

Market entries and market closes are placed when the script calls them and fill on the next candle. strategy.position_size, strategy.position_avg_price, and trade counters update after that fill, so exits that depend on position state begin from the candle where the entry is actually open.

Muuned simulates over the available OHLC candles, such as 5m or 15m bars. It does not use tick-level replay. If a candle touches both a stop and a limit for an open trade, Muuned uses the conservative fill for that trade. For a long, the stop wins; for a short, the stop wins.

Backtests use a default combined fee/slippage assumption of 0.1% unless parameters override it.

strategy

Declares the script as a strategy. Must appear at the top of the script.

Syntax: strategy(title, overlay)

ParameterTypeDefaultDescription
titlestringStrategy name
overlaybooltruePlot on the price chart
initial_capitalfloatStarting capital
strategy("My Strategy", overlay=true)

strategy.entry

Opens a new position or adds to an existing one.

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

ParameterTypeDefaultDescription
idstringOrder identifier
directionconststrategy.long or strategy.short
qtyfloatAsset quantity

In advanced mode, explicit qty values are asset units. For high-priced symbols, qty=1 means one full coin/share/contract. If qty is omitted, Muuned sizes the entry from available starting capital. In fast mode, portfolio sizing follows the backtest position size setting.

strategy.entry("Long", strategy.long)
strategy.entry("Short", strategy.short)

strategy.close

Closes the position matching the given entry id.

Syntax: strategy.close(id)

ParameterTypeDescription
idstringEntry order identifier to close
strategy.close("Long")

strategy.close_all

Closes all open positions.

Syntax: strategy.close_all()

strategy.close_all()

strategy.exit

Registers a pending exit order with stop-loss and/or take-profit levels. The exit triggers automatically when price reaches the specified level.

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

ParameterTypeDescription
idstringExit order identifier
from_entrystringEntry order to exit from
qtyfloatQuantity to close
qty_percentfloatPercent of the matching entry quantity to close
stopfloatAbsolute stop-loss price
limitfloatAbsolute take-profit price
profitfloatProfit target in ticks
lossfloatStop-loss in ticks
trail_pointsfloatTrailing activation in ticks
trail_offsetfloatTrailing distance in ticks

Tick-based exits use syminfo.mintick. Absolute stop and limit prices are rounded to valid tick increments before orders are evaluated.

Repeated calls with the same id and from_entry update the same pending exit order. Once that exit ID has filled for an entry, it will not keep closing the remaining quantity of that same entry on later bars. Use a different exit ID or strategy.close() to close the remainder.

strategy.entry("Long", strategy.long)
strategy.exit("Exit", "Long", stop=low - ta.atr(14), limit=close + 3 * ta.atr(14))

Partial Exit Example

trend = close > ta.sma(close, 30)

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

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

if not trend and strategy.position_size > 0
    strategy.close("Long")

Trailing Stop Example

strategy.exit("Trail", "Long", trail_points=100, trail_offset=50)

strategy.order

Places an unconditional order in the specified direction. Unlike strategy.entry, it does not manage positions by entry ID.

Syntax: strategy.order(id, direction)

ParameterTypeDescription
idstringOrder identifier
directionconststrategy.long or strategy.short
strategy.order("Buy", strategy.long)

strategy.cancel

Cancels a pending order. No-op in backtesting.

Syntax: strategy.cancel(id)

ParameterTypeDescription
idstringOrder identifier to cancel
strategy.cancel("Exit")

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(arr)Copy an existing array
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.standardize(arr)Z-score normalization
array.percentile_linear_interpolation(arr, pct)Percentile (interpolated)
array.percentile_nearest_rank(arr, pct)Percentile (nearest rank)
array.percentrank(arr, value)Percent of values <= value

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.slice(arr, from, to)Extract sub-array
array.splice(arr, index, count)Remove elements and return 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, fn)true if fn returns true for all elements
array.some(arr, fn)true if fn returns true for any element

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()Create an empty map
map.copy(m)Create a copy of a map
var myMap = map.new()

Access & Mutation

FunctionDescription
map.put(m, key, value)Set key to value
map.get(m, key, default)Get value by key, or default
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()
map.put(levels, "support", low)
map.put(levels, "resistance", high)

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

Matrix Functions

Matrix Functions

Functions for creating and manipulating 2D matrices. Useful for linear algebra operations in quantitative strategies.

Creating Matrices

FunctionDescription
matrix.new(rows, cols, value)Create matrix filled with value
matrix.copy(m)Deep copy
var m = matrix.new(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.inv(m)Inverse
matrix.pinv(m)Moore-Penrose pseudo-inverse
matrix.rank(m)Matrix rank
matrix.eigenvalues(m)Eigenvalues (up to 2x2)
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

Utility Functions

Utility Functions

Helper functions for handling missing values, colors, and other operations.

Value Handling

nz

Replace NaN with a default value (0 if omitted).

Syntax: nz(x, replacement)

ParameterTypeDefaultDescription
xanyValue to check
replacementany0Value to use if x is NaN
safeVal = nz(ta.pivothigh(high, 5, 5), close)

na

Returns true if the value is NaN / not available.

Syntax: na(x)

if na(myIndicator)
    // handle missing data

fixnan

Replaces NaN values with the last non-NaN value. Stateful — remembers the last valid value across bars.

Syntax: fixnan(x)

smoothPivot = fixnan(ta.pivothigh(high, 5, 5))

Color Functions

color.new

Apply transparency to a color.

Syntax: color.new(color, transp)

ParameterTypeDescription
colorcolorBase color (hex string)
transpintTransparency (0–100)

color.rgb

Create a color from RGB components.

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

color.r / color.g / color.b

Extract the red, green, or blue component (0–255) from a color.

color.t

Extract the transparency (0–100) from a color.

color.from_gradient

Interpolate between two colors based on a value’s position in a range.

Syntax: color.from_gradient(value, bottom, top, bottomColor, topColor)

Higher Timeframe

request.security

Access data from a higher timeframe.

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

ParameterTypeDescription
symbolstringTrading pair
timeframestringTimeframe (e.g. "D", "240")
expressionanyValue to fetch from the higher timeframe
dailyClose = request.security(syminfo.tickerid, "D", close)

No-op Functions

The following functions are recognized but have no effect in backtesting:

FunctionDescription
plot()Chart drawing (visual only)
hline()Horizontal line
fill()Fill between plots
label.new()Chart label
line.new()Chart line
box.new()Chart box
table.new()Chart table
log.info()Debug logging
log.warning()Warning logging
log.error()Error logging
runtime.error()Runtime error
alertcondition()Alert setup
strategy.cancel()Cancel pending order