Skip to main content

Operators & Control Flow

Arithmetic, comparison, logical, and conditional operators. Lazy evaluation, operator precedence, for loops, while loops, switch statements, and scope.

Arithmetic Operators

PineScript supports five arithmetic operators. These work on both simple and series values. When you perform arithmetic on a series, the result is a series: the operation is applied independently on every bar.

pine-Arithmetic operators
1//@version=6
2indicator("Arithmetic Demo")
3
4// Basic operations
5priceRange = high - low // subtraction: bar range in USD
6midpoint = (high + low) / 2 // division: bar midpoint price
7doubleVol = volume * 2 // multiplication
8pctChange = (close - open) / open * 100 // combined: percent change
9
10// Modulo (remainder): useful for every-Nth-bar logic
11barMod = bar_index % 10 // 0 on every 10th bar
12isEvery10th = barMod == 0
13
14// BTC-specific: dollar change per bar
15dollarChange = close - close[1]
16plot(dollarChange, "$ Change", dollarChange > 0 ? color.green : color.red,
17 1, plot.style_histogram)
+ (addition)Adds two values. Works on int, float, and string (concatenation).
- (subtraction)Subtracts. Also used as unary negation: -close inverts the price.
* (multiplication)Multiplies. Common for scaling: atr * 2.0 doubles the ATR value.
/ (division)Divides. Watch for division by zero. Always guard with a check or nz().
% (modulo)Returns the remainder after division. 10 % 3 = 1. Useful for cyclic patterns.

Comparison Operators

Comparison operators produce boolean (true/false) results. They are the foundation of every condition, filter, and signal in your scripts. When applied to series, they produce a series bool: a different true/false value on every bar.

pine-Comparison operators
1//@version=6
2indicator("Comparisons", overlay=true)
3
4sma50 = ta.sma(close, 50)
5rsi = ta.rsi(close, 14)
6
7// All six comparison operators
8aboveSMA = close > sma50 // greater than
9belowSMA = close < sma50 // less than
10atOrAbove = close >= sma50 // greater than or equal
11atOrBelow = close <= sma50 // less than or equal
12exactMatch = close == open // equal (doji candle)
13notEqual = close != open // not equal (has a body)
14
15// Compound conditions with comparisons
16inBullZone = close > sma50 and rsi > 50
17inBearZone = close < sma50 and rsi < 50
18
19bgcolor(inBullZone ? color.new(color.green, 90) :
20 inBearZone ? color.new(color.red, 90) : na)

Logical Operators

Logical operators combine boolean expressions. PineScript uses the keywords and, or, and not (not symbols like && or ||). These are used constantly to build multi-factor trading conditions.

pine-Logical operators for multi-factor signals
1//@version=6
2indicator("Multi-Factor Signals", overlay=true)
3
4ema21 = ta.ema(close, 21)
5rsi = ta.rsi(close, 14)
6vol = ta.sma(volume, 20)
7
8// AND: all conditions must be true
9highConviction = close > ema21 and rsi > 50 and volume > vol * 1.5
10// This is true ONLY when price is above EMA AND RSI is above 50 AND volume is elevated
11
12// OR: at least one condition must be true
13exitSignal = rsi > 80 or close < ema21
14// This triggers if RSI is overbought OR price breaks below EMA
15
16// NOT: inverts a condition
17isNotOversold = not (rsi < 30)
18// True when RSI is NOT below 30
19
20// Combining all three
21cleanEntry = (close > ema21 and rsi > 40) and not (rsi > 75) and (volume > vol or close > high[1])
22
23plotshape(cleanEntry and barstate.isconfirmed, "Clean Entry",
24 shape.triangleup, location.belowbar, color.green, size=size.small)

Lazy evaluation

PineScript uses lazy (short-circuit) evaluation for and and or. With and, if the first condition is false, the second is not evaluated. With or, if the first is true, the second is skipped. This matters when the second condition could cause an error (like division by zero): put the safety check first.

Conditional (Ternary) Operator

The ternary operator condition ? valueIfTrue : valueIfFalse is the most common conditional pattern in PineScript. It appears in plot colors, variable assignments, calculations, and virtually everywhere a value depends on a condition.

pine-Ternary patterns
1//@version=6
2indicator("Ternary Mastery", overlay=true)
3
4ema50 = ta.ema(close, 50)
5rsi = ta.rsi(close, 14)
6
7// Simple ternary
8trendColor = close > ema50 ? color.green : color.red
9
10// Nested ternary: three states (use sparingly for readability)
11rsiZone = rsi > 70 ? "Overbought" : rsi < 30 ? "Oversold" : "Neutral"
12
13// Ternary for conditional plotting (na = no plot)
14plot(close > ema50 ? ema50 : na, "EMA (bullish)", color.green, 2)
15plot(close <= ema50 ? ema50 : na, "EMA (bearish)", color.red, 2)
16
17// Dynamic transparency based on distance from EMA
18dist = math.abs(close - ema50) / ema50 * 100
19intensity = math.min(dist * 15, 80)
20bgcolor(close > ema50 ? color.new(color.green, 100 - intensity) :
21 color.new(color.red, 100 - intensity))

Operator Precedence

When an expression has multiple operators, PineScript evaluates them in a specific order. Understanding precedence prevents bugs from unexpected evaluation order. When in doubt, use parentheses to make the order explicit.

1. (): ParenthesesHighest precedence. Always evaluated first. Use liberally for clarity.
2. not: Logical NOTUnary negation of a boolean. not true == false.
3. * / %: MultiplicativeMultiplication, division, and modulo. Evaluated left to right.
4. + -: AdditiveAddition and subtraction. Evaluated left to right.
5. > < >= <=: ComparisonRelational comparisons. Produce boolean results.
6. == !=: EqualityEquality and inequality checks.
7. and: Logical ANDBoth sides must be true.
8. or: Logical ORLowest precedence among logical operators. At least one side must be true.
9. ?:, TernaryLowest precedence. The entire condition and both branches are evaluated within context.

for Loops

PineScript supports for loops for iterating over a range of values. Loops run within a single bar's execution. They do not iterate over bars (the engine does that). Use loops for aggregating data within a lookback window, counting occurrences, or custom calculations that built-in functions do not cover.

pine-for loop: count bullish bars in a window
1//@version=6
2indicator("Bullish Bar Counter")
3
4lookback = input.int(20, "Lookback Period", minval=1)
5
6// Count how many of the last N bars were bullish (close > open)
7bullCount = 0
8for i = 0 to lookback - 1
9 if close[i] > open[i]
10 bullCount += 1
11
12bullPct = bullCount / lookback * 100
13
14plot(bullPct, "Bullish %", color.from_gradient(bullPct, 30, 70, color.red, color.green), 2)
15hline(50, "50%", color.new(color.gray, 70))

while Loops

while loops repeat as long as a condition is true. They are useful when you do not know in advance how many iterations are needed: for example, finding the first bar that meets a condition or accumulating values until a threshold is reached.

pine-while loop: bars since condition
1//@version=6
2indicator("Bars Since Demo")
3
4// Count bars since RSI was oversold (manual implementation)
5rsi = ta.rsi(close, 14)
6barsSinceOS = 0
7idx = 0
8while idx < 500
9 if rsi[idx] < 30
10 barsSinceOS := idx
11 break
12 idx += 1
13
14plot(barsSinceOS, "Bars Since Oversold", color.orange)

Loop limits

PineScript enforces a maximum number of loop iterations (currently 500 for historical bars and 100,000 for real-time). Infinite loops cause a runtime error. Always include a break condition or ensure your while loop has a bounded exit. Prefer for loops when the iteration count is known.

switch Statements

PineScript supports two forms of switch: one that matches against a specific value (like switch on a string), and one that evaluates a series of conditions (like an if/else chain, but cleaner). Use switch when you have more than two or three branches.

pine-switch with value and without
1//@version=6
2indicator("Switch Demo")
3
4// Form 1: switch on a value
5dayName = switch dayofweek
6 dayofweek.monday => "Mon"
7 dayofweek.tuesday => "Tue"
8 dayofweek.wednesday => "Wed"
9 dayofweek.thursday => "Thu"
10 dayofweek.friday => "Fri"
11 dayofweek.saturday => "Sat"
12 => "Sun"
13
14// Form 2: switch with conditions (no input value)
15rsi = ta.rsi(close, 14)
16signal = switch
17 rsi > 80 => "Strong Sell"
18 rsi > 70 => "Sell"
19 rsi < 20 => "Strong Buy"
20 rsi < 30 => "Buy"
21 => "Neutral"
22
23// switch for MA type selection (common pattern)
24maType = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "RMA"])
25maLen = input.int(21, "Length")
26ma = switch maType
27 "SMA" => ta.sma(close, maLen)
28 "EMA" => ta.ema(close, maLen)
29 "WMA" => ta.wma(close, maLen)
30 "RMA" => ta.rma(close, maLen)
31 => ta.ema(close, maLen)
32
33plot(rsi, "RSI")

Indentation and Scope Rules

PineScript uses indentation (4 spaces) to define code blocks, similar to Python. Everything indented under an if, for, while, or function definition belongs to that block. The first line that returns to the original indentation level exits the block.

pine-Indentation and scope
1//@version=6
2indicator("Scope Demo", overlay=true)
3
4ema21 = ta.ema(close, 21)
5
6// Correct indentation: both lines belong to the if block
7if ta.crossover(close, ema21)
8 label.new(bar_index, high, "Cross ▲",
9 color=color.green, textcolor=color.white,
10 style=label.style_label_down, size=size.tiny)
11 // This line is also inside the if block
12
13// This line is OUTSIDE the if block (back to base indentation)
14plot(ema21, "EMA", close > ema21 ? color.green : color.red, 2)
15
16// Variables declared inside a block are LOCAL to that block
17var float lastCrossPrice = na
18if ta.crossover(close, ema21)
19 lastCrossPrice := close // updates the var variable
20 float tempVal = close * 1.01 // local variable, only exists inside this if
21 // tempVal cannot be accessed outside this block

Complete Build: Multi-Factor Scoring System

Let's combine every operator and control flow concept into a practical trading tool: a multi-factor scoring system that rates market conditions from -5 (extremely bearish) to +5 (extremely bullish) by evaluating trend, momentum, volume, volatility, and structure.

pine-Multi-Factor Score (all operators combined)
1//@version=6
2indicator("Market Score", overlay=false)
3
4// Calculations
5ema21 = ta.ema(close, 21)
6ema50 = ta.ema(close, 50)
7rsi = ta.rsi(close, 14)
8atr = ta.atr(14)
9vol = ta.sma(volume, 20)
10[_, _, hist] = ta.macd(close, 12, 26, 9)
11
12// Score each factor using comparison + ternary operators
13trendScore = (close > ema21 ? 1 : -1) + (close > ema50 ? 1 : -1)
14momScore = rsi > 60 ? 1 : rsi < 40 ? -1 : 0
15macdScore = hist > 0 ? (hist > hist[1] ? 1 : 0) : (hist < hist[1] ? -1 : 0)
16volScore = volume > vol * 1.5 ? 1 : volume < vol * 0.5 ? -1 : 0
17
18// Count bullish bars using a for loop
19bullBars = 0
20for i = 0 to 9
21 if close[i] > open[i]
22 bullBars += 1
23structScore = bullBars > 6 ? 1 : bullBars < 4 ? -1 : 0
24
25// Total score: -5 to +5
26totalScore = trendScore + momScore + macdScore + volScore + structScore
27
28// Classify with switch
29label_text = switch
30 totalScore >= 4 => "Strong Buy"
31 totalScore >= 2 => "Buy"
32 totalScore <= -4 => "Strong Sell"
33 totalScore <= -2 => "Sell"
34 => "Neutral"
35
36// Visualize
37scoreColor = color.from_gradient(totalScore, -5, 5, color.red, color.green)
38plot(totalScore, "Score", scoreColor, 3, plot.style_histogram)
39hline(0, "Zero", color.new(color.gray, 70))
40hline(3, "Bull Threshold", color.new(color.green, 80), hline.style_dashed)
41hline(-3, "Bear Threshold", color.new(color.red, 80), hline.style_dashed)
42bgcolor(math.abs(totalScore) >= 4 ? color.new(scoreColor, 85) : na)

Building conviction with confluence

Multi-factor scoring systems quantify what experienced traders do intuitively: they check multiple independent signals before taking a position. A score of +5 means trend, momentum, volume, MACD, and structure are all aligned bullish. That level of confluence is rare, which is exactly what makes it high-probability.

Put this lesson to work

Free on Thrive, no account needed.