Ternary operator
dir = close > open ? 1 : -1
color = close > open ? color.lime : color.red
Nested ternaries read best when each branch is on its own line:
regime =
close > ta.sma(close, 200) ? "bull"
: close < ta.sma(close, 200) ? "bear"
: "neutral"
Both branches must share a type (see Operators).
if statement
if cond
body
else if cond2
body2
else
body3
- The
if/else if/elsechain can be as long as you like. - Blocks are indented; the dedent closes the block.
- Any number of
else ifbranches is allowed.
if close > ta.sma(close, 20)
bgColor = color.new(color.lime, 90)
else if close < ta.sma(close, 20)
bgColor = color.new(color.red, 90)
else
bgColor = color.new(color.gray, 90)
if as an expression
Assign the result of an if block to a variable — the last statement of the taken branch becomes the value:
score =
if close > open
1
else if close < open
-1
else
0
Branches must share a type.
Nested if
Nest as deeply as needed:
if cond1
if cond2
innerBody
else
otherInner
else
outer
switch statement
Two forms are supported.
Expression switch
tf = input.string("D", "Timeframe", options=["30", "60", "D", "W"])
bars =
switch tf
"30" => 48
"60" => 24
"D" => 1
"W" => 5
=> 1 // default (no match)
- The subject expression is evaluated once; its value is compared with each arm's match value with
==. - The right side of
=>is either a single expression or an indented block whose last statement is the value. - An arm with no match (
=> …) is the default. Omitting it is allowed; a non-match returnsna.
Boolean-chain switch
Omit the subject to use each arm's left side as a condition — the first truthy arm wins:
color =
switch
close > open and volume > ta.sma(volume, 20) * 2 => color.lime
close < open and volume > ta.sma(volume, 20) * 2 => color.red
close > open => color.new(color.lime, 60)
close < open => color.new(color.red, 60)
=> color.gray
This is often clearer than a long if … else if … chain.
once
A compact form for "run this block the first time the condition is true, then never again":
once close > ta.sma(close, 200)
label.new(bar_index, high, "First close above 200-SMA")
Equivalent to:
var fired = false
if not fired and close > ta.sma(close, 200)
fired := true
label.new(bar_index, high, "First close above 200-SMA")
Bare once (no condition) runs its block on the first bar of the chart's history.
See also
- Loops
- Operators — ternary and short-circuit semantics
- Execution model — why series-mode functions should run every bar