Pine Script Control Flow

Pine Script If Else: Conditional Logic, Ternary Operators & Multi-Conditions

In Pine Script v6, conditional branching is handled using the if statement structure and ternary expressions. Code blocks inside an if or else block must be indented by exactly 4 spaces or one tab. Variables declared outside an if block can be modified inside it using the reassignment operator (:=). Additionally, an if statement can function as an expression that returns a value directly to a variable.

Build Conditional Logic with AI

Syntax patterns: If statements vs ternary expressions in v6

Pine Script supports two primary styles for conditional logic: full if else blocks for multi-step logic and the ternary operator for quick scalar evaluations.

PatternSyntax structureWhen to useKey restriction
Standard if blockif condition\n statementExecuting multi-line actions or order submissionsRequires strict 4-space indentation
if else ladderif c1\n s1\nelse if c2\n s2\nelse\n s3Categorizing market regimes into multiple exclusive statesBlocks execute sequentially until first true match
Value-returning ifval = if c1\n res1\nelse\n res2Assigning complex multi-line calculation outputs to one variableEvery branch must return the same data type
Ternary operatorval = condition ? trueVal : falseValPlot color selection and simple threshold togglesLimited to single expressions per branch

Complete Pine Script v6 script with nested if-else structures

The following indicator classifies market trends into five distinct regimes (Strong Bullish, Weak Bullish, Neutral, Weak Bearish, Strong Bearish) using multi-condition if else logic and formatted on-chart tables.

Pine Script v6: Multi-condition trend regime classifierpinescript
//@version=6
indicator("Multi-Condition Regime Classifier [v6]", overlay = false)

// Inputs
int fastLen = input.int(20, "Fast EMA")
int slowLen = input.int(50, "Slow EMA")
int rsiLen = input.int(14, "RSI Length")

// Technical indicators
float fastEma = ta.ema(close, fastLen)
float slowEma = ta.ema(close, slowLen)
float rsiVal = ta.rsi(close, rsiLen)

// Multi-condition evaluation using if-else expressions
string regimeText = if close > fastEma and fastEma > slowEma
    if rsiVal > 60
        "Strong Bullish"
    else
        "Weak Bullish"
else if close < fastEma and fastEma < slowEma
    if rsiVal < 40
        "Strong Bearish"
    else
        "Weak Bearish"
else
    "Consolidation / Neutral"

// Color determination using ternary operator
color regimeColor = regimeText == "Strong Bullish" ? color.green :
                    regimeText == "Weak Bullish"   ? color.teal :
                    regimeText == "Strong Bearish" ? color.red :
                    regimeText == "Weak Bearish"   ? color.maroon : color.gray

// Plot oscillator score
int score = if regimeText == "Strong Bullish"
    2
else if regimeText == "Weak Bullish"
    1
else if regimeText == "Weak Bearish"
    -1
else if regimeText == "Strong Bearish"
    -2
else
    0

plot(score, "Market Regime Score", color = regimeColor, style = plot.style_columns)
hline(0, "Neutral Line", color = color.gray)

Important rules for variable scope and reassignment

A frequent source of Pine Script compile errors is misunderstanding local vs global variable scope inside conditional blocks:

  • Reassignment with := operator: If a variable is declared globally (e.g. float myVal = 0.0), modifying it inside an if block requires myVal := 1.0. Using myVal = 1.0 creates a local variable that vanishes outside the block.
  • Persistent state with var: If a variable must remember its updated value across chart candles, declare it with var outside the if statement: var float stopPrice = na.
  • Type consistency: When assigning a variable from an if expression, all branches (if, else if, else) must resolve to the identical data type (all float, all string, or all int).
  • No parentheses required: Unlike C++ or JavaScript, Pine Script does not require wrapping if conditions in parentheses: if close > open is standard syntax.

Evaluating multiple conditions with logical operators

When testing compound criteria, structure your boolean expressions with clear precedence:

  • and operator: Both expressions must be true. Example: if close > open and volume > ta.sma(volume, 20).
  • or operator: At least one expression must be true. Example: if ta.crossover(close, ema20) or close > highestHigh.
  • not operator: Inverts the boolean result. Example: if not na(priorStop).
  • Grouping with parentheses: When combining and with or in compound rules, wrap related conditions in parentheses to guarantee intended priority.
Where Pineify fits

Pine Script AI Coding Agent

Generate complex nested if-else statements, multi-timeframe regime filters, and state machine strategies in Pine Script v6 with Pineify AI.

Also useful: Visual Pine Editor. Combine rules and filters visually without typing indentations or variable reassignment symbols.

Build Conditional Logic with AI

Frequently asked questions

Conditional logic and decision trees depend on accurate chart inputs and consistent price series. Always backtest strategies across multiple market regimes prior to live execution.

Sources and verification