if/else blocks
Pine's if statement works on series — the branch is taken bar by bar. A common pattern:
signal = close > ta.ema(close, 50) ? 1 : -1
This assigns 1 when close is above the 50-EMA, else -1. The ternary is the cleanest form for two-way decisions.
Multi-branch if/else
For three or more branches, if/else if/else reads better:
regime = close > ta.ema(close, 200) ? "uptrend"
: close < ta.ema(close, 200) ? "downtrend"
: "range"
Switch expressions
Pine v5 has a switch expression that is cleaner when one variable drives the branch. The MA example from Part 1 used it:
ma = switch maType
"SMA" => ta.sma(src, length)
"EMA" => ta.ema(src, length)
"WMA" => ta.wma(src, length)
State matters
Plain if only changes a variable on the bar the condition is true. If you need state that persists across bars (like "I am currently in a long"), use var:
var bool inLong = false
if not inLong and close > ta.ema(close, 50)
inLong := true
else if inLong and close < ta.ema(close, 50)
inLong := false
Common mistake: missing an else
Inside an if without an else, a variable assignment only takes effect on the bar the condition is true. On other bars the variable keeps its previous value — which is sometimes what you want and sometimes a bug. Be explicit.
What to remember
Series-aware if + var for persistent state is the spine of every strategy. Master it before moving to functions.