Loops in PineScript
Authored by
Invos Research
Date Released
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.
forloops:forloops are used to execute a block of code a specified number of times. The general structure of aforloop is:
for i = 1 to n {
// Code block to execute
}
// Code block to execute
}
whileloops:whileloops are used to execute a block of code as long as a specific condition is true. The general structure of awhileloop is:
while (condition) {
// Code block to execute
}
// 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
}
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.

