Loops in PineScript


Posted by: Invostock.com
Published on: January 16, 2023
Loops in PineScript

In Pine Script, loops are used to repeatedly execute a block of code. There are two types of loops that can be used in Pine Script: for loops and while loops.

  • for loops: for loops are used to execute a block of code a specified number of times. The general structure of a for loop is:
for i = 1 to n {
    // Code block to execute
}
  • while loops: while loops are used to execute a block of code as long as a specific condition is true. The general structure of a while loop is:
 while (condition) {
    // Code block to execute
}

Here is an example of a while loop that plots a Moving average of the close price while the value of close is greater than 10:

var myVariable = close
while (myVariable > 10) {
    plot(sma(close, 5))
    myVariable := close
}

In this example, the while loop starts with the variable myVariable equal to the current close price, and runs the code block inside the loop as long as the value of myVariable is greater than 10.