Lipi Reference Lipi

Keywords

if

Chooses which block of statements runs. Any number of `else if` arms may follow, and one `else` arm may close it; both are optional. It is a statement, not an expression: it decides which block runs rather than producing a value. And it opens a scope of its own, which is why a chart-output call placed inside one is rejected — put the condition in an argument instead, and leave the call at the top level.

Syntax

                if <condition> {
	<true_block>
} else if <condition> {
	<true_block>
} else {
	<false_block>
}
              

Example


          indicator("If Function Example - Moving Average Strategy", overlay=true)
// Define Moving Averages
shortMA = talib.sma(close, 10)
longMA = talib.sma(close, 50)
// Function to determine signal color
func getSignalColor() {
    if shortMA > longMA {
        return color.green
    } else {
        return color.blue
    }
}
// Plot Moving Averages
plot(shortMA, title="Short MA (10)", color=color.blue)
plot(longMA, title="Long MA (50)", color=color.orange)
bgcolor(getSignalColor())