Skip to main content

Built-in Functions & Variables

Technical analysis functions, custom user-defined functions, string functions, highest/lowest/barssince, time sessions, bar states, symbol info, tuples, and company financials.

Built-in Functions Overview

PineScript ships with hundreds of built-in functions organized into namespaces. These are optimized, battle-tested implementations that you should always prefer over rolling your own. The most important namespace for traders is ta (technical analysis), but math, str, request, and syminfo are equally essential.

The ta Namespace: All Major Functions

The ta namespace contains every standard technical indicator. Here is a comprehensive reference of the functions you will use most:

Moving Averages

pine-All moving average types
1//@version=6
2indicator("Moving Averages Reference", overlay=true)
3
4src = close
5len = input.int(20, "Length")
6
7sma_val = ta.sma(src, len) // Simple: equal weight to all bars
8ema_val = ta.ema(src, len) // Exponential: more weight to recent bars
9wma_val = ta.wma(src, len) // Weighted: linearly decreasing weights
10vwma_val = ta.vwma(src, len) // Volume-Weighted: volume determines weight
11rma_val = ta.rma(src, len) // Running (Wilder's): very smooth, used in RSI/ATR
12hma_val = ta.hma(src, len) // Hull: fast and smooth, reduced lag
13
14plot(sma_val, "SMA", color.blue, 2)
15plot(ema_val, "EMA", color.orange, 2)
16plot(hma_val, "HMA", color.purple, 2)

Oscillators and Multi-Return Indicators

pine-RSI, MACD, Stochastic, Bollinger Bands, ATR
1//@version=6
2indicator("Oscillators Reference")
3
4// RSI: Relative Strength Index (0 to 100)
5rsi = ta.rsi(close, 14)
6
7// MACD: returns three values via tuple destructuring
8[macdLine, signalLine, histogram] = ta.macd(close, 12, 26, 9)
9
10// Stochastic: returns %K and %D
11[stochK, stochD] = ta.stoch(close, high, low, 14)
12
13// Bollinger Bands: returns middle, upper, lower
14[bbMid, bbUpper, bbLower] = ta.bb(close, 20, 2.0)
15
16// ATR: Average True Range (pure volatility measure, no direction)
17atr = ta.atr(14)
18
19// True Range: single bar volatility
20tr = ta.tr
21
22// ADX: trend strength (not direction), 0 to 100
23adx = ta.dmi(14, 14)
24
25plot(rsi, "RSI", color.white, 2)

Tuple destructuring

Functions that return multiple values use PineScript's tuple syntax: [val1, val2, val3] = function(). You must capture all returned values. If you only need the MACD line, you still need to write [macdLine, _, _] = ta.macd(close, 12, 26, 9).

Crossover and Signal Detection

pine-Crossover, highest, lowest, pivot
1//@version=6
2indicator("Detection Functions", overlay=true)
3
4ema9 = ta.ema(close, 9)
5ema21 = ta.ema(close, 21)
6
7// Crossover / Crossunder: true on the EXACT bar where one series crosses another
8bullCross = ta.crossover(ema9, ema21) // fast crosses ABOVE slow
9bearCross = ta.crossunder(ema9, ema21) // fast crosses BELOW slow
10
11// Highest / Lowest in a lookback window
12highest20 = ta.highest(high, 20) // highest high in last 20 bars
13lowest20 = ta.lowest(low, 20) // lowest low in last 20 bars
14highBar = ta.highestbars(high, 20) // bars since the highest high (negative)
15lowBar = ta.lowestbars(low, 20) // bars since the lowest low (negative)
16
17// Pivot detection (retroactive: uses left AND right lookback)
18pivHigh = ta.pivothigh(high, 5, 5) // pivot high: 5 bars each side
19pivLow = ta.pivotlow(low, 5, 5)
20
21// Rate of change: percent change over N bars
22roc = ta.roc(close, 10) // % change from 10 bars ago
23
24// Change detection
25priceChanged = ta.change(close) // close - close[1]
26dirChanged = ta.change(math.sign(ta.roc(close, 5))) // momentum direction flip
27
28plotshape(bullCross, "Bull", shape.triangleup, location.belowbar, color.green, size=size.small)
29plotshape(bearCross, "Bear", shape.triangledown, location.abovebar, color.red, size=size.small)

Custom User-Defined Functions

When built-in functions do not cover your needs, you can define your own. User-defined functions encapsulate reusable logic, reduce code duplication, and make complex scripts manageable. There are two syntax forms: single-line (arrow) and multi-line (indented block).

pine-User-defined function syntax
1//@version=6
2indicator("Custom Functions", overlay=true)
3
4// Single-line function (arrow syntax)
5pctDiff(a, b) => (a - b) / b * 100
6
7// Multi-line function (indented block)
8calcZone(rsiVal, obLevel, osLevel) =>
9 result = "Neutral"
10 if rsiVal > obLevel
11 result := "Overbought"
12 else if rsiVal < osLevel
13 result := "Oversold"
14 result // last expression is the return value
15
16// Function with series inputs (works on every bar)
17volumeProfile(vol, avgVol) =>
18 ratio = vol / avgVol
19 isSpike = ratio > 2.0
20 [ratio, isSpike] // return a tuple
21
22// Usage
23rsi = ta.rsi(close, 14)
24zone = calcZone(rsi, 70, 30)
25diffFromMA = pctDiff(close, ta.ema(close, 50))
26[volRatio, isVolSpike] = volumeProfile(volume, ta.sma(volume, 20))
27
28plotshape(isVolSpike, "Vol Spike", shape.diamond,
29 location.abovebar, color.yellow, size=size.tiny)

Function limitations

User-defined functions cannot call request.security(), alertcondition(), or input(). They cannot contain plot() or plotshape() calls. Functions are pure computation blocks. They take inputs, process them, and return outputs. All I/O (plotting, inputs, alerts) must happen in the global scope.

String Functions

String functions are essential for building labels, table content, alert messages, and tooltips. The str namespace provides everything you need for text manipulation.

pine-String function reference
1//@version=6
2indicator("String Functions", overlay=true)
3
4rsi = ta.rsi(close, 14)
5
6// Number to string with formatting
7priceStr = str.tostring(close, "#.##") // "67234.50"
8rsiStr = str.tostring(rsi, "#.#") // "54.3"
9volStr = str.tostring(volume, "#,###") // "1,234,567"
10pctStr = str.tostring(0.075 * 100, "#.###") + "%" // "7.500%"
11
12// str.format(): positional placeholders
13msg = str.format("{0} | RSI: {1} | Vol: {2}", syminfo.ticker, rsiStr, volStr)
14
15// String operations
16hasUSD = str.contains(syminfo.ticker, "USD") // true for BTCUSD, ETHUSD
17upperTick = str.upper(syminfo.ticker) // "BTCUSDT"
18replaced = str.replace(syminfo.ticker, "USDT", "/USDT")
19
20// Display on the last bar
21if barstate.islast
22 label.new(bar_index, high, msg,
23 color=color.new(color.gray, 20),
24 textcolor=color.white,
25 style=label.style_label_down, size=size.small)

Highest, Lowest, and barssince

These functions answer questions about recent price history: “What was the highest price in the last 50 bars?” “How many bars ago did RSI last cross 30?” They are essential for building range-based indicators and time-since-event counters.

pine-Range and time functions
1//@version=6
2indicator("Range Functions", overlay=true)
3
4period = input.int(50, "Lookback")
5
6// Highest and lowest values
7periodHigh = ta.highest(high, period)
8periodLow = ta.lowest(low, period)
9periodRange = periodHigh - periodLow
10
11// Where is price within the range? (0% = at low, 100% = at high)
12pricePosition = (close - periodLow) / periodRange * 100
13
14// How many bars since a condition was true?
15rsi = ta.rsi(close, 14)
16barsSinceOversold = ta.barssince(rsi < 30)
17barsSinceOverbought = ta.barssince(rsi > 70)
18
19// Donchian Channel (based on highest/lowest)
20plot(periodHigh, "Channel High", color.new(color.green, 50), 1)
21plot(periodLow, "Channel Low", color.new(color.red, 50), 1)
22plot((periodHigh + periodLow) / 2, "Channel Mid",
23 color.new(color.gray, 50), 1, plot.style_stepline)

Time and Session Filtering

The time() function filters bars by trading session and timezone. This is critical for crypto traders who want to analyze price action during specific market hours: the US session, the Asian session, or custom windows around economic data releases.

pine-Session-based filtering
1//@version=6
2indicator("Session Filter", overlay=true)
3
4// Check if current bar falls within a session window
5inAsian = not na(time("", "2000-0400", "America/New_York"))
6inLondon = not na(time("", "0300-1100", "America/New_York"))
7inNewYork = not na(time("", "0930-1600", "America/New_York"))
8
9// Highlight sessions with subtle backgrounds
10bgcolor(inAsian ? color.new(color.purple, 94) : na, title="Asia")
11bgcolor(inLondon ? color.new(color.blue, 94) : na, title="London")
12bgcolor(inNewYork ? color.new(color.orange, 94) : na, title="New York")
13
14// Day of week filtering
15isMonday = dayofweek == dayofweek.monday
16isFriday = dayofweek == dayofweek.friday
17
18// Timestamp comparisons
19barTimestamp = time // bar open time in milliseconds (Unix)
20barDuration = time - time[1] // milliseconds between bar opens

Symbol Information: syminfo Namespace

The syminfo namespace gives you metadata about the current chart's symbol. This is essential for building adaptive indicators that behave differently based on the asset type, exchange, or currency.

syminfo.tickeridFull symbol ID including exchange prefix (e.g., "BINANCE:BTCUSDT"). Used for request.security() calls.
syminfo.tickerSymbol name without exchange (e.g., "BTCUSDT"). Use for display purposes.
syminfo.currencyQuote currency (e.g., "USD", "USDT"). Useful for adapting position sizing.
syminfo.typeAsset type: "crypto", "stock", "forex", "futures", "index". Use for asset-specific logic.
syminfo.mintickMinimum price movement (tick size). For BTC usually 0.01. Essential for precise stop placement.
syminfo.timezoneExchange timezone. Needed for accurate session calculations.
syminfo.sessionTrading session string. Crypto is typically "24x7". Stocks have specific market hours.

Fundamentals and External Data

PineScript can access fundamental data via request.financial() for stock company data and request.quandl() for economic datasets. While these are more relevant for equities, crypto traders can use QUANDL data for macro indicators like interest rates, DXY, and commodity prices that influence crypto markets.

pine-External data access
1//@version=6
2indicator("External Data Demo", overlay=false)
3
4// Company financials (for stocks, not available for crypto tokens)
5// pe = request.financial(syminfo.tickerid, "PRICE_EARNINGS_TTMFY", "FQ")
6
7// Multi-symbol data (crypto traders use this heavily)
8btcClose = request.security("BINANCE:BTCUSDT", timeframe.period, close)
9ethClose = request.security("BINANCE:ETHUSDT", timeframe.period, close)
10
11// ETH/BTC ratio: fundamental crypto metric
12ethBtcRatio = ethClose / btcClose
13plot(ethBtcRatio, "ETH/BTC", color.new(#5ce1e6, 0), 2)
14
15// BTC dominance proxy
16// btcDom = request.security("BTC.D", "D", close)
17// plot(btcDom, "BTC Dominance", color.orange)

Tuples: Returning Multiple Values

Tuples let functions return multiple values at once. This is used by built-in functions like ta.macd() and you can use the same pattern in your own functions. Wrap the return values in square brackets on both the function definition side and the call site.

pine-Tuple patterns
1//@version=6
2indicator("Tuples Demo")
3
4// Custom function returning a tuple
5analyzeVolume(vol, avgPeriod) =>
6 avg = ta.sma(vol, avgPeriod)
7 ratio = vol / avg
8 isSpike = ratio > 2.0
9 isLow = ratio < 0.5
10 [avg, ratio, isSpike, isLow]
11
12// Destructure the tuple
13[avgVol, volRatio, isVolSpike, isVolLow] = analyzeVolume(volume, 20)
14
15// Use the values
16plot(volRatio, "Vol Ratio", isVolSpike ? color.yellow :
17 isVolLow ? color.gray : color.white, 2)
18hline(1.0, "Average", color.new(color.gray, 70))
19hline(2.0, "Spike Threshold", color.new(color.yellow, 70), hline.style_dashed)

varip Deep Dive: Tick-Level State

varip is PineScript's mechanism for tracking state at the tick level rather than the bar level. While var persists across bars (updating once per bar on historical data), varip persists across ticks on the real-time bar. This enables intrabar analysis that is impossible with regular variables.

pine-varip tick-level tracking
1//@version=6
2indicator("Tick Analysis", overlay=true)
3
4// Count real-time ticks on the current bar
5varip int ticksOnBar = 0
6if barstate.isnew
7 ticksOnBar := 0
8ticksOnBar += 1
9
10// Track price direction of each tick
11varip int upTicks = 0
12varip int downTicks = 0
13if barstate.isnew
14 upTicks := 0
15 downTicks := 0
16if close > close[0] // current tick vs previous tick
17 upTicks += 1
18else if close < close[0]
19 downTicks += 1
20
21// Display tick stats on last bar
22if barstate.islast
23 totalTicks = upTicks + downTicks
24 buyPressure = totalTicks > 0 ? upTicks / totalTicks * 100 : 50
25 label.new(bar_index, high,
26 str.format("Ticks: {0}\nBuy%: {1}",
27 str.tostring(ticksOnBar),
28 str.tostring(buyPressure, "#.#")),
29 color=color.new(color.gray, 20),
30 textcolor=color.white, size=size.small)

varip vs var, when to use which

Use var for bar-level state: running totals, counters, tracking the last signal bar, all-time highs. Use varip only when you need intrabar tick data: tick counters, real-time price movement tracking, or building custom intrabar volume analysis. On historical bars, varip behaves identically to var.

Put this lesson to work

Free on Thrive, no account needed.