Operators and Control Flow

Every trading decision boils down to a question: "Is this condition true?" Is price above the moving average? Is volume higher than yesterday? Did a crossover just happen? Operators and control flow are how you ask and answer those questions in code.

This tutorial walks through every operator category with trading examples, then shows you how to build decision-making logic with if, switch, and for.

Arithmetic Operators

Arithmetic operators let you calculate derived values from price data. You will use these constantly -- to compute spreads, percentage changes, average prices, and custom indicators.

Calculating a candle's body size and range

Suppose you want to measure how "decisive" a candle is. A large body relative to the total range suggests strong conviction. Here is how you compute both values:

Pine Script
//@version=5
indicator("Candle Metrics", overlay=false)

bodySize = math.abs(close - open)
totalRange = high - low
bodyRatio = totalRange != 0 ? (bodySize / totalRange) * 100 : 0

plot(bodyRatio, "Body %", color=color.teal)
hline(70, "Strong candle threshold")

What happened: We used subtraction to get the body size and range, math.abs to handle both bullish and bearish candles, and division to express the body as a percentage of the range. When bodyRatio is above 70%, the candle closed near its extreme -- a sign of conviction.

Continue reading

Sign in or create a free account to unlock Operators and Control Flow and access the full academy.

Free account · No credit card required