Sidechair

if

Browse the reference

Runs a block only when a condition is true, with optional else if and else branches, and returns the value of the branch it ran.

Try it in the editor

An if statement tests a bool condition and runs the indented block beneath it when the condition is true. Add else if branches to test further conditions in order and a final else for everything left. Only the first branch whose condition holds runs, and the blocks are indented four spaces or one tab.

if is also an expression: it returns the last value evaluated in the branch that ran, so you can assign the whole block to a variable: write c = if close > open, put color.green on the next indented line, then else and color.red on the lines after it. Every branch must give the same type. When no branch runs and there is no else, the result is na (or false, 0 or an empty string for the types that have no na).

Syntax

var_declarationX = if condition var_decl_then0 var_decl_then1 … var_decl_thenN else if [optional block] var_decl_else0 var_decl_else1 … var_decl_elseN else var_decl_else0 var_decl_else1 … var_decl_elseN return_expression_else

Remarks

  • In v6 the condition must be a bool. A number is not accepted: write x != 0, and use na(x) to test for na.
  • The condition is checked on every bar, so a plain assignment inside it lasts only for that bar. Declare the variable with var to carry a value forward.
  • On Sidechair: if, else if and else run as described. A number used as a condition counts as true when it is non-zero, and na counts as false.

Example

Pine ScriptBranches and a returned valueOpen in editor
//@version=6
indicator("If expression", overlay = true)
trend = if close > ta.sma(close, 50)
    1
else if close < ta.sma(close, 50)
    -1
else
    0
plot(close, "Close", trend > 0 ? color.green : trend < 0 ? color.red : color.gray)
bgcolor(trend == 0 ? color.new(color.gray, 85) : na)

See also

Runs on Sidechair