Variables, Data Types & Inputs
All data types, var and varip keywords, series vs simple values, na handling, type casting, the execution model, and building configurable inputs.
Variable Declaration
Variables in PineScript are declared by assigning a value to a name. There is no let, const, or var keyword required for a standard declaration. However, PineScript provides two special keywords: var and varip: that fundamentally change how a variable persists across bars. Understanding the difference is essential for writing correct PineScript.
1//@version=62indicator("Variable Declaration Modes")34// Regular: recalculated from scratch on EVERY bar5barRange = high - low // this is different on every bar67// var: initialized ONCE on bar 0, then keeps its value across bars8var float allTimeHigh = 0.09allTimeHigh := math.max(allTimeHigh, high) // only updates when new high is made1011// varip: initialized once, updates on every TICK (intrabar) in real-time12varip int tickCount = 013tickCount += 1 // counts actual price ticks on the live bar1415plot(barRange, "Bar Range")16plot(allTimeHigh, "ATH", color.orange, 2)The := Reassignment Operator
When you first create a variable, use =. When you update an existing var or varip variable, use :=. This distinction is one of the most common sources of bugs for beginners. Using = on a previously declared variable creates a new variable with the same name, shadowing the original. Using := modifies the existing one.
1//@version=62indicator(":= Demo")34var float runningSum = 0.056// CORRECT: updates the existing var variable7runningSum := runningSum + close89// WRONG: this would create a NEW variable called runningSum, losing the var persistence10// runningSum = runningSum + close // compiler error: cannot redeclare1112plot(runningSum / bar_index, "Cumulative Average", color.yellow)Critical distinction
= declares. := updates. Mixing them up is the #1 PineScript beginner mistake. If your var variable seems to reset on every bar, you are probably using = instead of :=.All Data Types
PineScript is statically typed. Every variable has a type determined at compile time. You can declare types explicitly or let the compiler infer them from the assigned value. There are five fundamental types you will use in virtually every script:
| int | Whole numbers. Used for bar indices, lookback lengths, counters, and loop variables. Examples: 14, 200, -1, 0 |
| float | Decimal numbers. Used for prices, indicator values, percentages, and ratios. Examples: 67234.50, 0.075, -2.3, 3.14159 |
| bool | True or false. Used for conditions, filters, and signal flags. Examples: true, false, close > open, ta.crossover(a, b) |
| string | Text. Used for labels, alert messages, table cells, and input options. Examples: "Buy Signal", "BTC/USDT", "Bullish Divergence" |
| color | Visual colors. Used for all chart rendering. Examples: color.red, color.new(#5ce1e6, 50), color.rgb(255, 72, 149, 0) |
1//@version=62indicator("Types Demo")34// Explicit declarations: you specify the type5int lookback = 146float threshold = 70.07bool showSignal = true8string label = "Overbought"9color bullColor = color.new(color.green, 20)1011// Inferred declarations: the compiler figures it out12rsiValue = ta.rsi(close, lookback) // inferred: series float13crossed = ta.crossover(rsiValue, 30) // inferred: series bool14priceStr = str.tostring(close) // inferred: series string1516plot(rsiValue, "RSI", rsiValue > threshold ? color.red : bullColor, 2)Series vs Simple: The Core Concept
This is the single most important concept in PineScript. Every value is classified as either a series (changes on every bar) or a simple/const value (same across all bars). If you do not understand this distinction, you will write code that compiles but produces wrong results, or you will hit confusing error messages about type mismatches.
The built-in variable close is a series float. On bar 1 of a Bitcoin daily chart it might be 42,000. On bar 2 it might be 43,500. On bar 500 it might be 67,000. It is a different number on every bar. Any calculation that depends on close (or any other bar-changing value) produces a series. A literal number like 14 or an input.int(14) is a simple int: it is 14 on every bar.
1//@version=62indicator("Series vs Simple", overlay=true)34length = 14 // simple int: same value on every bar5src = close // series float: different on every bar6rsi = ta.rsi(src, length) // series float: computed from a series78// The history operator [] accesses previous bars of any series9prevClose = close[1] // yesterday's close (on daily)10closeWeekAgo = close[7] // close from 7 bars ago11prevRSI = rsi[1] // RSI value from the previous bar1213// You CANNOT use [] on simple values: length[1] would be meaningless14// This is the key insight: series have history, simple values do not1516plot(rsi, "RSI")17plot(prevRSI, "Prev RSI", color.gray)Why this matters for crypto trading
close > ta.sma(close, 50), you are creating a series bool: a true/false value that is different on every bar. On some bars Bitcoin is above the 50-SMA, on others it is below. PineScript evaluates this condition 1,000+ times as it moves through the chart. This is fundamentally different from Python or JavaScript where a comparison runs once.The History Operator []
The square bracket operator [] is one of PineScript's most powerful features. It accesses historical values of any series without requiring you to maintain arrays or loops. Think of it as looking backwards in time: close[1] is the close one bar ago, close[10] is the close ten bars ago, volume[0] is the same as volume (current bar).
1//@version=62indicator("History Operator", overlay=true)34// Price change from previous bar5priceChange = close - close[1]6pctChange = (close - close[1]) / close[1] * 10078// Compare current RSI to RSI 5 bars ago9rsi = ta.rsi(close, 14)10rsiMomentum = rsi - rsi[5]1112// 3-bar highest high (manual implementation of ta.highest(high, 3))13manualHighest = math.max(high, math.max(high[1], high[2]))1415// Detect inside bar (current range contained within previous range)16insideBar = high < high[1] and low > low[1]1718plotshape(insideBar, "Inside Bar", shape.diamond,19 location.abovebar, color.yellow, size=size.tiny)na Values and Handling
na means “not available.” It is PineScript's equivalent of null. You encounter na constantly because many calculations do not have enough data on early bars: ta.sma(close, 200) returns na for the first 199 bars. close[50] returns na if there are not 50 preceding bars. Any arithmetic involving na produces na. You must handle na explicitly.
1//@version=62indicator("NA Handling Demo")34sma200 = ta.sma(close, 200)56// na() checks if a value is na7isValid = not na(sma200)89// nz() replaces na with a fallback value10safeVal = nz(sma200) // returns 0.0 if na11safeVal2 = nz(sma200, close) // returns close if na1213// fixnan() carries forward the last non-na value14filled = fixnan(sma200) // on early bars, uses the first valid value once available1516// Practical pattern: conditional plotting (na = gap in the line)17aboveSMA = close > sma20018plot(isValid and aboveSMA ? sma200 : na, "SMA (above only)", color.green, 2)19plot(isValid and not aboveSMA ? sma200 : na, "SMA (below only)", color.red, 2)| na(value) | Returns true if the value is na. Use for validation checks before calculations. |
| nz(value) | Returns 0 (or 0.0) if value is na, otherwise returns the value. Simplest na guard. |
| nz(value, replacement) | Returns the replacement value if value is na. Use when 0 is not a sensible default. |
| fixnan(value) | Carries forward the last non-na value. Creates continuous lines even when the underlying series has gaps. |
| na as plot value | Plotting na creates a gap in the line. This is the standard way to conditionally show/hide parts of a plot. |
Type Casting
PineScript does not implicitly convert between types. If you need to use a float as a lookback length (which requires an int), or display a number in a label (which requires a string), you must cast explicitly.
1//@version=62indicator("Type Casting Demo")34// float to int (truncates toward zero, does not round)5floatVal = 14.76intVal = int(floatVal) // 147rounded = math.round(floatVal) // 15 (proper rounding)89// int to float10length = 2011floatLen = float(length) // 20.01213// number to string (essential for labels and tables)14priceStr = str.tostring(close, "#.##") // "67234.50"15pctStr = str.tostring(2.5, "#.#") + "%" // "2.5%"16volStr = str.tostring(volume, "#,###") // "1,234,567"1718// Dynamic lookback from a calculation19atrRatio = ta.atr(14) / ta.atr(50)20dynLen = math.round(atrRatio * 20)21dynSMA = ta.sma(close, dynLen > 1 ? dynLen : 2)2223plot(dynSMA, "Dynamic SMA", color.yellow, 2)The Execution Model
PineScript does not run your code once. It runs your entire script once for every bar on the chart, from left (oldest) to right (newest). On a daily BTC chart with 2,000 bars of history, your script executes 2,000 times during the initial load. On the current live bar, it re-executes on every incoming price tick.
Historical bars (left → right)
open, high, low, close, and volume reflect that bar's final data. Calculations are deterministic because the bar is already complete.Real-time bar (current)
close updates with the latest trade price. high and low may expand. Indicator values fluctuate intrabar. Use barstate.isconfirmed to act only on the final value when the bar closes.barstate namespace
barstate.isconfirmed: true when the bar has closed. barstate.islast: true on the most recent bar. barstate.isrealtime: true on live data. barstate.isfirst: true on the oldest bar. barstate.isnew: true on the first tick of a new bar.Repainting explained
barstate.isconfirmed for signals you intend to trade on.Getting User Input
The input family of functions creates a settings panel where users configure your indicator. Each input type renders a different UI control: number fields, checkboxes, dropdowns, color pickers, and more. Inputs are evaluated once when the script loads and remain constant across all bars (they are simple values, not series).
1//@version=62indicator("Input Types Showcase", overlay=true)34// Integer input with min/max constraints5rsiLen = input.int(14, "RSI Length", minval=2, maxval=100,6 tooltip="Period for RSI calculation")78// Float input with step size9atrMult = input.float(2.0, "ATR Multiplier", minval=0.5, maxval=5.0,10 step=0.1, tooltip="Multiplier for stop loss distance")1112// Boolean input (checkbox)13showBG = input.bool(true, "Show Background",14 tooltip="Toggle background coloring on/off")1516// String input (dropdown)17maType = input.string("EMA", "MA Type", options=["SMA", "EMA", "WMA", "VWMA"],18 tooltip="Select the moving average algorithm")1920// Color input (color picker)21maColor = input.color(#5ce1e6, "MA Color")2223// Timeframe input (timeframe selector)24htf = input.timeframe("D", "Higher Timeframe")2526// Source input (select OHLCV or another indicator's output)27src = input.source(close, "Price Source")2829// Use the inputs30ma = switch maType31 "SMA" => ta.sma(src, rsiLen)32 "EMA" => ta.ema(src, rsiLen)33 "WMA" => ta.wma(src, rsiLen)34 "VWMA" => ta.vwma(src, rsiLen)3536plot(ma, "MA", maColor, 2)Input Groups
As your indicator grows in complexity, the settings panel can become overwhelming. Input groups organize related parameters under collapsible headers, making the settings clean and navigable even for indicators with 20+ inputs.
1//@version=62indicator("Grouped Inputs Demo", overlay=true)34// Group 1: Moving Average Settings5grpMA = "Moving Average"6maLen = input.int(21, "Length", group=grpMA)7maType = input.string("EMA", "Type", options=["SMA", "EMA"], group=grpMA)8maCol = input.color(#5ce1e6, "Color", group=grpMA)910// Group 2: Signal Settings11grpSig = "Signals"12showBuy = input.bool(true, "Show Buy Signals", group=grpSig)13showSell = input.bool(true, "Show Sell Signals", group=grpSig)1415// Group 3: Risk Management16grpRisk = "Risk"17slMult = input.float(2.0, "Stop Loss (ATR×)", step=0.1, group=grpRisk)18tpMult = input.float(3.0, "Take Profit (ATR×)", step=0.1, group=grpRisk)1920ma = maType == "EMA" ? ta.ema(close, maLen) : ta.sma(close, maLen)21plot(ma, "MA", maCol, 2)Professional input patterns
Put this lesson to work
Free on Thrive, no account needed.