Skip to main content

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.

pine-Three declaration modes
1//@version=6
2indicator("Variable Declaration Modes")
3
4// Regular: recalculated from scratch on EVERY bar
5barRange = high - low // this is different on every bar
6
7// var: initialized ONCE on bar 0, then keeps its value across bars
8var float allTimeHigh = 0.0
9allTimeHigh := math.max(allTimeHigh, high) // only updates when new high is made
10
11// varip: initialized once, updates on every TICK (intrabar) in real-time
12varip int tickCount = 0
13tickCount += 1 // counts actual price ticks on the live bar
14
15plot(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.

pine-= vs := in practice
1//@version=6
2indicator(":= Demo")
3
4var float runningSum = 0.0
5
6// CORRECT: updates the existing var variable
7runningSum := runningSum + close
8
9// WRONG: this would create a NEW variable called runningSum, losing the var persistence
10// runningSum = runningSum + close // compiler error: cannot redeclare
11
12plot(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:

intWhole numbers. Used for bar indices, lookback lengths, counters, and loop variables. Examples: 14, 200, -1, 0
floatDecimal numbers. Used for prices, indicator values, percentages, and ratios. Examples: 67234.50, 0.075, -2.3, 3.14159
boolTrue or false. Used for conditions, filters, and signal flags. Examples: true, false, close > open, ta.crossover(a, b)
stringText. Used for labels, alert messages, table cells, and input options. Examples: "Buy Signal", "BTC/USDT", "Bullish Divergence"
colorVisual colors. Used for all chart rendering. Examples: color.red, color.new(#5ce1e6, 50), color.rgb(255, 72, 149, 0)
pine-Explicit vs inferred type declarations
1//@version=6
2indicator("Types Demo")
3
4// Explicit declarations: you specify the type
5int lookback = 14
6float threshold = 70.0
7bool showSignal = true
8string label = "Overbought"
9color bullColor = color.new(color.green, 20)
10
11// Inferred declarations: the compiler figures it out
12rsiValue = ta.rsi(close, lookback) // inferred: series float
13crossed = ta.crossover(rsiValue, 30) // inferred: series bool
14priceStr = str.tostring(close) // inferred: series string
15
16plot(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.

pine-Series vs simple demonstration
1//@version=6
2indicator("Series vs Simple", overlay=true)
3
4length = 14 // simple int: same value on every bar
5src = close // series float: different on every bar
6rsi = ta.rsi(src, length) // series float: computed from a series
7
8// The history operator [] accesses previous bars of any series
9prevClose = close[1] // yesterday's close (on daily)
10closeWeekAgo = close[7] // close from 7 bars ago
11prevRSI = rsi[1] // RSI value from the previous bar
12
13// You CANNOT use [] on simple values: length[1] would be meaningless
14// This is the key insight: series have history, simple values do not
15
16plot(rsi, "RSI")
17plot(prevRSI, "Prev RSI", color.gray)

Why this matters for crypto trading

When you write 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).

pine-History operator patterns
1//@version=6
2indicator("History Operator", overlay=true)
3
4// Price change from previous bar
5priceChange = close - close[1]
6pctChange = (close - close[1]) / close[1] * 100
7
8// Compare current RSI to RSI 5 bars ago
9rsi = ta.rsi(close, 14)
10rsiMomentum = rsi - rsi[5]
11
12// 3-bar highest high (manual implementation of ta.highest(high, 3))
13manualHighest = math.max(high, math.max(high[1], high[2]))
14
15// Detect inside bar (current range contained within previous range)
16insideBar = high < high[1] and low > low[1]
17
18plotshape(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.

pine-na handling functions
1//@version=6
2indicator("NA Handling Demo")
3
4sma200 = ta.sma(close, 200)
5
6// na() checks if a value is na
7isValid = not na(sma200)
8
9// nz() replaces na with a fallback value
10safeVal = nz(sma200) // returns 0.0 if na
11safeVal2 = nz(sma200, close) // returns close if na
12
13// fixnan() carries forward the last non-na value
14filled = fixnan(sma200) // on early bars, uses the first valid value once available
15
16// Practical pattern: conditional plotting (na = gap in the line)
17aboveSMA = close > sma200
18plot(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 valuePlotting 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.

pine-Type casting examples
1//@version=6
2indicator("Type Casting Demo")
3
4// float to int (truncates toward zero, does not round)
5floatVal = 14.7
6intVal = int(floatVal) // 14
7rounded = math.round(floatVal) // 15 (proper rounding)
8
9// int to float
10length = 20
11floatLen = float(length) // 20.0
12
13// 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"
17
18// Dynamic lookback from a calculation
19atrRatio = ta.atr(14) / ta.atr(50)
20dynLen = math.round(atrRatio * 20)
21dynSMA = ta.sma(close, dynLen > 1 ? dynLen : 2)
22
23plot(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.

1

Historical bars (left → right)

The script runs once per completed bar. On each bar, built-in variables like open, high, low, close, and volume reflect that bar's final data. Calculations are deterministic because the bar is already complete.
2

Real-time bar (current)

On the live bar, the script re-executes on every price tick. 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.
3

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

Because the script re-runs on every tick of the live bar, indicator values can change before the bar closes. A buy signal that appears at 2:15 PM may vanish by 2:30 PM if price reverses. This is called “repainting.” Always use 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).

pine-All input types
1//@version=6
2indicator("Input Types Showcase", overlay=true)
3
4// Integer input with min/max constraints
5rsiLen = input.int(14, "RSI Length", minval=2, maxval=100,
6 tooltip="Period for RSI calculation")
7
8// Float input with step size
9atrMult = input.float(2.0, "ATR Multiplier", minval=0.5, maxval=5.0,
10 step=0.1, tooltip="Multiplier for stop loss distance")
11
12// Boolean input (checkbox)
13showBG = input.bool(true, "Show Background",
14 tooltip="Toggle background coloring on/off")
15
16// String input (dropdown)
17maType = input.string("EMA", "MA Type", options=["SMA", "EMA", "WMA", "VWMA"],
18 tooltip="Select the moving average algorithm")
19
20// Color input (color picker)
21maColor = input.color(#5ce1e6, "MA Color")
22
23// Timeframe input (timeframe selector)
24htf = input.timeframe("D", "Higher Timeframe")
25
26// Source input (select OHLCV or another indicator's output)
27src = input.source(close, "Price Source")
28
29// Use the inputs
30ma = switch maType
31 "SMA" => ta.sma(src, rsiLen)
32 "EMA" => ta.ema(src, rsiLen)
33 "WMA" => ta.wma(src, rsiLen)
34 "VWMA" => ta.vwma(src, rsiLen)
35
36plot(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.

pine-Organized inputs with groups
1//@version=6
2indicator("Grouped Inputs Demo", overlay=true)
3
4// Group 1: Moving Average Settings
5grpMA = "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)
9
10// Group 2: Signal Settings
11grpSig = "Signals"
12showBuy = input.bool(true, "Show Buy Signals", group=grpSig)
13showSell = input.bool(true, "Show Sell Signals", group=grpSig)
14
15// Group 3: Risk Management
16grpRisk = "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)
19
20ma = maType == "EMA" ? ta.ema(close, maLen) : ta.sma(close, maLen)
21plot(ma, "MA", maCol, 2)

Professional input patterns

Always provide tooltips for non-obvious inputs. Use sensible defaults that work on BTC/USDT daily charts. Group inputs by function (visual, signal, risk, advanced). Put the most commonly changed inputs at the top. These small touches separate amateur scripts from professional tools.

Put this lesson to work

Free on Thrive, no account needed.