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
1//@version=62indicator("Moving Averages Reference", overlay=true)34src = close5len = input.int(20, "Length")67sma_val = ta.sma(src, len) // Simple: equal weight to all bars8ema_val = ta.ema(src, len) // Exponential: more weight to recent bars9wma_val = ta.wma(src, len) // Weighted: linearly decreasing weights10vwma_val = ta.vwma(src, len) // Volume-Weighted: volume determines weight11rma_val = ta.rma(src, len) // Running (Wilder's): very smooth, used in RSI/ATR12hma_val = ta.hma(src, len) // Hull: fast and smooth, reduced lag1314plot(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
1//@version=62indicator("Oscillators Reference")34// RSI: Relative Strength Index (0 to 100)5rsi = ta.rsi(close, 14)67// MACD: returns three values via tuple destructuring8[macdLine, signalLine, histogram] = ta.macd(close, 12, 26, 9)910// Stochastic: returns %K and %D11[stochK, stochD] = ta.stoch(close, high, low, 14)1213// Bollinger Bands: returns middle, upper, lower14[bbMid, bbUpper, bbLower] = ta.bb(close, 20, 2.0)1516// ATR: Average True Range (pure volatility measure, no direction)17atr = ta.atr(14)1819// True Range: single bar volatility20tr = ta.tr2122// ADX: trend strength (not direction), 0 to 10023adx = ta.dmi(14, 14)2425plot(rsi, "RSI", color.white, 2)Tuple destructuring
[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
1//@version=62indicator("Detection Functions", overlay=true)34ema9 = ta.ema(close, 9)5ema21 = ta.ema(close, 21)67// Crossover / Crossunder: true on the EXACT bar where one series crosses another8bullCross = ta.crossover(ema9, ema21) // fast crosses ABOVE slow9bearCross = ta.crossunder(ema9, ema21) // fast crosses BELOW slow1011// Highest / Lowest in a lookback window12highest20 = ta.highest(high, 20) // highest high in last 20 bars13lowest20 = ta.lowest(low, 20) // lowest low in last 20 bars14highBar = ta.highestbars(high, 20) // bars since the highest high (negative)15lowBar = ta.lowestbars(low, 20) // bars since the lowest low (negative)1617// Pivot detection (retroactive: uses left AND right lookback)18pivHigh = ta.pivothigh(high, 5, 5) // pivot high: 5 bars each side19pivLow = ta.pivotlow(low, 5, 5)2021// Rate of change: percent change over N bars22roc = ta.roc(close, 10) // % change from 10 bars ago2324// Change detection25priceChanged = ta.change(close) // close - close[1]26dirChanged = ta.change(math.sign(ta.roc(close, 5))) // momentum direction flip2728plotshape(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).
1//@version=62indicator("Custom Functions", overlay=true)34// Single-line function (arrow syntax)5pctDiff(a, b) => (a - b) / b * 10067// Multi-line function (indented block)8calcZone(rsiVal, obLevel, osLevel) =>9 result = "Neutral"10 if rsiVal > obLevel11 result := "Overbought"12 else if rsiVal < osLevel13 result := "Oversold"14 result // last expression is the return value1516// Function with series inputs (works on every bar)17volumeProfile(vol, avgVol) =>18 ratio = vol / avgVol19 isSpike = ratio > 2.020 [ratio, isSpike] // return a tuple2122// Usage23rsi = 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))2728plotshape(isVolSpike, "Vol Spike", shape.diamond,29 location.abovebar, color.yellow, size=size.tiny)Function limitations
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.
1//@version=62indicator("String Functions", overlay=true)34rsi = ta.rsi(close, 14)56// Number to string with formatting7priceStr = 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%"1112// str.format(): positional placeholders13msg = str.format("{0} | RSI: {1} | Vol: {2}", syminfo.ticker, rsiStr, volStr)1415// String operations16hasUSD = str.contains(syminfo.ticker, "USD") // true for BTCUSD, ETHUSD17upperTick = str.upper(syminfo.ticker) // "BTCUSDT"18replaced = str.replace(syminfo.ticker, "USDT", "/USDT")1920// Display on the last bar21if barstate.islast22 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.
1//@version=62indicator("Range Functions", overlay=true)34period = input.int(50, "Lookback")56// Highest and lowest values7periodHigh = ta.highest(high, period)8periodLow = ta.lowest(low, period)9periodRange = periodHigh - periodLow1011// Where is price within the range? (0% = at low, 100% = at high)12pricePosition = (close - periodLow) / periodRange * 1001314// How many bars since a condition was true?15rsi = ta.rsi(close, 14)16barsSinceOversold = ta.barssince(rsi < 30)17barsSinceOverbought = ta.barssince(rsi > 70)1819// 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.
1//@version=62indicator("Session Filter", overlay=true)34// Check if current bar falls within a session window5inAsian = 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"))89// Highlight sessions with subtle backgrounds10bgcolor(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")1314// Day of week filtering15isMonday = dayofweek == dayofweek.monday16isFriday = dayofweek == dayofweek.friday1718// Timestamp comparisons19barTimestamp = time // bar open time in milliseconds (Unix)20barDuration = time - time[1] // milliseconds between bar opensSymbol 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.tickerid | Full symbol ID including exchange prefix (e.g., "BINANCE:BTCUSDT"). Used for request.security() calls. |
| syminfo.ticker | Symbol name without exchange (e.g., "BTCUSDT"). Use for display purposes. |
| syminfo.currency | Quote currency (e.g., "USD", "USDT"). Useful for adapting position sizing. |
| syminfo.type | Asset type: "crypto", "stock", "forex", "futures", "index". Use for asset-specific logic. |
| syminfo.mintick | Minimum price movement (tick size). For BTC usually 0.01. Essential for precise stop placement. |
| syminfo.timezone | Exchange timezone. Needed for accurate session calculations. |
| syminfo.session | Trading 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.
1//@version=62indicator("External Data Demo", overlay=false)34// Company financials (for stocks, not available for crypto tokens)5// pe = request.financial(syminfo.tickerid, "PRICE_EARNINGS_TTMFY", "FQ")67// Multi-symbol data (crypto traders use this heavily)8btcClose = request.security("BINANCE:BTCUSDT", timeframe.period, close)9ethClose = request.security("BINANCE:ETHUSDT", timeframe.period, close)1011// ETH/BTC ratio: fundamental crypto metric12ethBtcRatio = ethClose / btcClose13plot(ethBtcRatio, "ETH/BTC", color.new(#5ce1e6, 0), 2)1415// BTC dominance proxy16// 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.
1//@version=62indicator("Tuples Demo")34// Custom function returning a tuple5analyzeVolume(vol, avgPeriod) =>6 avg = ta.sma(vol, avgPeriod)7 ratio = vol / avg8 isSpike = ratio > 2.09 isLow = ratio < 0.510 [avg, ratio, isSpike, isLow]1112// Destructure the tuple13[avgVol, volRatio, isVolSpike, isVolLow] = analyzeVolume(volume, 20)1415// Use the values16plot(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.
1//@version=62indicator("Tick Analysis", overlay=true)34// Count real-time ticks on the current bar5varip int ticksOnBar = 06if barstate.isnew7 ticksOnBar := 08ticksOnBar += 1910// Track price direction of each tick11varip int upTicks = 012varip int downTicks = 013if barstate.isnew14 upTicks := 015 downTicks := 016if close > close[0] // current tick vs previous tick17 upTicks += 118else if close < close[0]19 downTicks += 12021// Display tick stats on last bar22if barstate.islast23 totalTicks = upTicks + downTicks24 buyPressure = totalTicks > 0 ? upTicks / totalTicks * 100 : 5025 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
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.