Conditional Statement


Posted by: Invos Research
Published on: January 16, 2023
Conditional Statement

In Pine Script, conditional statements are used to control the flow of execution based on certain conditions. The most common type of conditional statement is the if statement, which allows you to execute a block of code only if a specific condition is true.

Here is an example of how to use an if statement in Pine Script:

var myVariable = 5
if myVariable > 3 {
    // This block of code will execute if myVariable is greater than 3
    plot(sma(close, 10))
}
 

In this example, the if statement checks if the value of myVariable is greater than 3. If the condition is true, the code block inside the curly braces {} will be executed, which in this case is plotting a Simple Moving Average (SMA) of the close price with a period of 10.

You can also use other comparison operators like <, <=, >=, ==, != etc. to compare values.

You can also use else if and else statement to check multiple conditions and execute different code block based on the true condition.

if myVariable > 10 {
    plot(sma(close, 10))
} else if myVariable > 5 {
    plot(sma(close, 5))
} else {
    plot(sma(close, 2))
}
 

 In this example, the code block inside the first if statement will be executed if myVariable is greater than 10, the code block inside the second else if statement will be executed if myVariable is greater than 5 but less than or equal to 10, and the code block inside the else statement will be executed if myVariable is less than or equal to 5.

It's important to use proper indentation and whitespace when using conditional statements to make the code more readable and maintainable.