6.1 If, Else, and Ternary Operators
In Pinescript, you can use conditional statements like if, else, and ternary operators to control the flow of your script based on specific conditions. We have already seen if and else statements in Lesson 3. The ternary operator is a shorthand way to write simple if-else statements: Here the "?" acts as the IF and the ":" acts as the else.
condition ? value_if_true : value_if_false
For example, to assign a color based on whether the close price is above or below the open price, you can use the ternary operator:
barColor = close > open ? color.green : color.red
6.2 For Loops
For loops allow you to repeat a block of code for a specified number of iterations. In Pinescript, you can use the for keyword along with a counter variable and a specified range. We have already seen an example of for loops in Lesson 3. Here's another example to calculate a simple moving average:
sum = 0.0
length = 14
for i = 0 to length - 1
sum := sum + close[i]
sma = sum / length
6.3 While Loops
While loops are another type of loop in Pinescript that repeats a block of code as long as a specified condition is true. To use a while loop, you need to define a counter variable and use the while keyword followed by the condition:
sma = 0.0
sum = 0.0
i = 0
length = 14
while i < length
sum := sum + close[i]
i := i + 1
sma := sum / length
Comments
0 comments
Please sign in to leave a comment.