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.
1//@version=62indicator("Arithmetic Demo")34// Basic operations5priceRange = high - low // subtraction: bar range in USD6midpoint = (high + low) / 2 // division: bar midpoint price7doubleVol = volume * 2 // multiplication8pctChange = (close - open) / open * 100 // combined: percent change910// Modulo (remainder): useful for every-Nth-bar logic11barMod = bar_index % 10 // 0 on every 10th bar12isEvery10th = barMod == 01314// BTC-specific: dollar change per bar15dollarChange = 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.
1//@version=62indicator("Comparisons", overlay=true)34sma50 = ta.sma(close, 50)5rsi = ta.rsi(close, 14)67// All six comparison operators8aboveSMA = close > sma50 // greater than9belowSMA = close < sma50 // less than10atOrAbove = close >= sma50 // greater than or equal11atOrBelow = close <= sma50 // less than or equal12exactMatch = close == open // equal (doji candle)13notEqual = close != open // not equal (has a body)1415// Compound conditions with comparisons16inBullZone = close > sma50 and rsi > 5017inBearZone = close < sma50 and rsi < 501819bgcolor(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.
1//@version=62indicator("Multi-Factor Signals", overlay=true)34ema21 = ta.ema(close, 21)5rsi = ta.rsi(close, 14)6vol = ta.sma(volume, 20)78// AND: all conditions must be true9highConviction = close > ema21 and rsi > 50 and volume > vol * 1.510// This is true ONLY when price is above EMA AND RSI is above 50 AND volume is elevated1112// OR: at least one condition must be true13exitSignal = rsi > 80 or close < ema2114// This triggers if RSI is overbought OR price breaks below EMA1516// NOT: inverts a condition17isNotOversold = not (rsi < 30)18// True when RSI is NOT below 301920// Combining all three21cleanEntry = (close > ema21 and rsi > 40) and not (rsi > 75) and (volume > vol or close > high[1])2223plotshape(cleanEntry and barstate.isconfirmed, "Clean Entry",24 shape.triangleup, location.belowbar, color.green, size=size.small)Lazy evaluation
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.
1//@version=62indicator("Ternary Mastery", overlay=true)34ema50 = ta.ema(close, 50)5rsi = ta.rsi(close, 14)67// Simple ternary8trendColor = close > ema50 ? color.green : color.red910// Nested ternary: three states (use sparingly for readability)11rsiZone = rsi > 70 ? "Overbought" : rsi < 30 ? "Oversold" : "Neutral"1213// 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)1617// Dynamic transparency based on distance from EMA18dist = math.abs(close - ema50) / ema50 * 10019intensity = 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. (): Parentheses | Highest precedence. Always evaluated first. Use liberally for clarity. |
| 2. not: Logical NOT | Unary negation of a boolean. not true == false. |
| 3. * / %: Multiplicative | Multiplication, division, and modulo. Evaluated left to right. |
| 4. + -: Additive | Addition and subtraction. Evaluated left to right. |
| 5. > < >= <=: Comparison | Relational comparisons. Produce boolean results. |
| 6. == !=: Equality | Equality and inequality checks. |
| 7. and: Logical AND | Both sides must be true. |
| 8. or: Logical OR | Lowest precedence among logical operators. At least one side must be true. |
| 9. ?:, Ternary | Lowest 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.
1//@version=62indicator("Bullish Bar Counter")34lookback = input.int(20, "Lookback Period", minval=1)56// Count how many of the last N bars were bullish (close > open)7bullCount = 08for i = 0 to lookback - 19 if close[i] > open[i]10 bullCount += 11112bullPct = bullCount / lookback * 1001314plot(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.
1//@version=62indicator("Bars Since Demo")34// Count bars since RSI was oversold (manual implementation)5rsi = ta.rsi(close, 14)6barsSinceOS = 07idx = 08while idx < 5009 if rsi[idx] < 3010 barsSinceOS := idx11 break12 idx += 11314plot(barsSinceOS, "Bars Since Oversold", color.orange)Loop limits
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.
1//@version=62indicator("Switch Demo")34// Form 1: switch on a value5dayName = switch dayofweek6 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"1314// Form 2: switch with conditions (no input value)15rsi = ta.rsi(close, 14)16signal = switch17 rsi > 80 => "Strong Sell"18 rsi > 70 => "Sell"19 rsi < 20 => "Strong Buy"20 rsi < 30 => "Buy"21 => "Neutral"2223// switch for MA type selection (common pattern)24maType = input.string("EMA", "Type", options=["SMA", "EMA", "WMA", "RMA"])25maLen = input.int(21, "Length")26ma = switch maType27 "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)3233plot(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.
1//@version=62indicator("Scope Demo", overlay=true)34ema21 = ta.ema(close, 21)56// Correct indentation: both lines belong to the if block7if 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 block1213// This line is OUTSIDE the if block (back to base indentation)14plot(ema21, "EMA", close > ema21 ? color.green : color.red, 2)1516// Variables declared inside a block are LOCAL to that block17var float lastCrossPrice = na18if ta.crossover(close, ema21)19 lastCrossPrice := close // updates the var variable20 float tempVal = close * 1.01 // local variable, only exists inside this if21 // tempVal cannot be accessed outside this blockComplete 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.
1//@version=62indicator("Market Score", overlay=false)34// Calculations5ema21 = 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)1112// Score each factor using comparison + ternary operators13trendScore = (close > ema21 ? 1 : -1) + (close > ema50 ? 1 : -1)14momScore = rsi > 60 ? 1 : rsi < 40 ? -1 : 015macdScore = hist > 0 ? (hist > hist[1] ? 1 : 0) : (hist < hist[1] ? -1 : 0)16volScore = volume > vol * 1.5 ? 1 : volume < vol * 0.5 ? -1 : 01718// Count bullish bars using a for loop19bullBars = 020for i = 0 to 921 if close[i] > open[i]22 bullBars += 123structScore = bullBars > 6 ? 1 : bullBars < 4 ? -1 : 02425// Total score: -5 to +526totalScore = trendScore + momScore + macdScore + volScore + structScore2728// Classify with switch29label_text = switch30 totalScore >= 4 => "Strong Buy"31 totalScore >= 2 => "Buy"32 totalScore <= -4 => "Strong Sell"33 totalScore <= -2 => "Sell"34 => "Neutral"3536// Visualize37scoreColor = 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
Put this lesson to work
Free on Thrive, no account needed.