Skip to main content

Pine Script While Loop: A Concise Guide for Traders and Developers

· 4 min read

So you're getting into Pine Script and wondering about while loops? I get it - loops can seem a bit intimidating at first, but they're actually pretty useful once you get the hang of them. Let me walk you through while loops specifically, because they're different from the regular for loops you might already know.

What's a while loop anyway?

Think of a while loop like this: it keeps doing something over and over until a certain condition stops being true. It's like saying "keep checking the price until it goes above $100" or "keep counting bars until we find 5 green ones in a row."

The difference between a while loop and a for loop is that with a for loop, you know exactly how many times you want to repeat something. With a while loop, you're saying "I don't know how many times this will take, just keep going until this thing happens."

How to write one

Here's the basic structure:

[variable_declaration =] while condition
// your code goes here (make sure it's indented)

The condition part is what gets checked before each loop. If it's true, the code inside runs. If it's false, the loop stops and moves on.

One important thing - you need to make sure something inside your loop eventually makes that condition false, otherwise you'll get stuck in an infinite loop (which is not fun).

Let's look at a real example

The Best Pine Script Generator

Say you want to count how many of the last 30 bars were green (closed higher than they opened) versus red. Here's how you could do it:

//@version=5
indicator("Counting Green and Red Bars", overlay=true)
period = input.int(30, "How many bars to check", minval=1, maxval=200)
greenBars = 0
redBars = 0

if barstate.islast
var label myLabel = label.new(na, na, "", style=label.style_label_left, textcolor=color.white)
counter = 1
while counter <= period
if close[counter] > open[counter]
greenBars += 1
else if close[counter] < open[counter]
redBars += 1
counter += 1
label.set_xy(myLabel, bar_index, high)
label.set_text(myLabel, str.tostring(greenBars, "Green bars: #\n") + str.tostring(redBars, "Red bars: #"))

What's happening here? We start with counter = 1 and keep going while counter <= period. Each time through the loop, we check if that bar was green or red, add to our count, and then increase the counter by 1. Eventually the counter gets bigger than our period, the condition becomes false, and we're done.

Using while loops in functions

You can also put while loops inside your own functions, which is pretty handy for calculations:

//@version=5
indicator("Custom Price Difference Calculator")
lookbackPeriod = input.int(20, "Bars to look back", minval=1)

calculatePriceDifference() =>
index = 1
totalDifference = 0
while index <= lookbackPeriod
totalDifference += close[index] - open[index]
index += 1
totalDifference

myCalculation = calculatePriceDifference()
plot(myCalculation)

This function adds up all the differences between close and open prices for the last 20 bars (or whatever you set). It's a simple example, but you can see how you could build more complex calculations this way.

Things to keep in mind

Here are some tips I wish someone had told me when I was starting out:

  • Don't forget to update your counter! This is the most common mistake. If you don't change the variable that controls your loop, it'll run forever.
  • You can use break to exit early if you find what you're looking for before the loop would naturally end.
  • You can use continue to skip to the next iteration without running the rest of the code in the loop.
  • Keep an eye on performance - if you're looping through hundreds of bars on every tick, your script might get slow.

When should you use while loops?

While loops are great when you don't know exactly how many times you need to loop. Like if you want to:

  • Keep looking back through bars until you find a specific pattern
  • Count something until you reach a certain threshold
  • Do calculations that depend on changing market conditions

For loops are better when you know exactly how many times you want to repeat something.

Wrapping up

While loops might seem tricky at first, but they're really just a way to say "keep doing this until something changes." Once you start using them, you'll probably find lots of places where they come in handy for your trading scripts.

The key is to start simple - maybe try counting something basic first, then work your way up to more complex logic. And remember, if your script seems to freeze up, you probably have an infinite loop somewhere!