Skip to main content

For Loops and else if in Pine Script

· 10 min read

Ever find yourself copying and pasting the same Pine Script code over and over? Yeah, I've been there too. That's exactly why for loops exist - they're your ticket to writing cleaner, smarter code that doesn't make you want to pull your hair out.

If you're just getting started with Pine Script, you might want to check out our Pine Script Tutorial: A Quick Start Guide for Beginners first. But if you're ready to dive into loops, let's make this as painless as possible.

For Loops in Pine Script

What Are For Loops Anyway?

Think of a for loop like giving someone instructions to count from 1 to 10 and do something specific at each number. In Pine Script, the basic syntax looks like this:

for counter = start_value to end_value
// Your code goes here

The counter is just a variable that keeps track of where you are in the counting process. It starts at start_value, does whatever you tell it to do, then moves up by 1 until it reaches end_value.

Why Bother with For Loops?

The Best Pine Script Generator

Here's the thing - for loops aren't just some fancy programming concept. They solve real problems that every Pine Script developer runs into:

  • Looking back through historical data: Need to check the last 20 bars for a pattern? Loop it.
  • Working with arrays: Got a list of values to process? Perfect loop territory.
  • Repetitive calculations: Instead of writing close[0] + close[1] + close[2]... forever, let a loop handle it.
  • Building complex indicators: Many sophisticated trading tools rely on loops to crunch historical data.

The beauty is simple: write the logic once, let the loop repeat it. No more copy-paste madness.

Skip the Coding Headaches with Pineify

Look, I totally get it - Pine Script can feel overwhelming when you're starting out. Between syntax errors, debugging nightmares, and trying to remember which function does what, it's enough to make anyone want to quit.

That's exactly why I built Pineify. It's designed for traders who want powerful custom indicators without the coding hassle. You literally just describe what you want in plain English, and it generates clean Pine Script code for you.

Pineify | Best Pine Script Editor

Check it out: Pineify


Here's what makes it a game-changer:

  • Zero coding required - Describe your strategy in normal words, get working code
  • Works with free TradingView - No more 2-indicator limit frustrations
  • Import and modify existing scripts - Got Pine Script code that needs tweaking? Just paste it in
  • Visual strategy builder - Drag and drop indicators, set conditions visually
  • Built-in backtesting - Test your strategies with proper risk management
  • Saves serious time - No need to spend months learning syntax or hire expensive developers
Explore all features here.

Real Examples That Actually Work

Alright, let's get our hands dirty with some practical examples. Before we dive in, here's a crucial tip: Pine Script won't let you plot things inside loops. If you need to visualize what's happening during each iteration, you'll need to use labels or store values to plot later.

Building a Custom Moving Average from Scratch

Want to understand how moving averages really work under the hood? It's surprisingly simple - just add up the last N closing prices and divide by N. Here's how you can build one using a for loop (even though Pine Script has built-in functions for this):

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//======================================================================//
// ____ _ _ __ //
// | _ \(_)_ __ ___(_)/ _|_ _ //
// | |_) | | '_ \ / _ \ | |_| | | | //
// | __/| | | | | __/ | _| |_| | //
// |_| |_|_| |_|\___|_|_| \__, | //
// |___/ //
//======================================================================//

//@version=6
indicator("[Pineify] Custom SMA with For Loop", overlay=true)

length = input.int(30, title="How many bars to average?")
src = close

sum = 0.0
for i = 0 to length - 1
sum := sum + src[i]

sma = sum / length

plot(sma, color=color.blue, title="My Custom SMA")

What's happening here? We start with sum = 0, then loop through the last 30 bars (or whatever length you choose), adding each closing price to our running total. Finally, we divide by the length to get our average. That's literally all a moving average is - just the average of recent prices!

If you want to learn more about different types of moving averages, check out our guide on How to Use Pine Script SMA for More Accurate Trading Signals.

Counting Higher and Lower Bars

Here's a more practical example - let's count how many bars in the recent past had higher or lower highs than the current bar. This can help you understand whether you're at a relative high or low:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//======================================================================//
// ____ _ _ __ //
// | _ \(_)_ __ ___(_)/ _|_ _ //
// | |_) | | '_ \ / _ \ | |_| | | | //
// | __/| | | | | __/ | _| |_| | //
// |_| |_|_| |_|\___|_|_| \__, | //
// |___/ //
//======================================================================//

//@version=6
indicator("[Pineify] Bar Counter", overlay=true)
lookbackInput = input.int(50, "How far back to look?", minval = 1, maxval = 4999)
higherBars = 0
lowerBars = 0
if barstate.islast
var label lbl = label.new(na, na, "", style = label.style_label_left)
for i = 1 to lookbackInput
if high[i] > high
higherBars += 1
else if high[i] < high
lowerBars += 1
label.set_xy(lbl, bar_index, high)
label.set_text(lbl, str.tostring(higherBars, "# higher bars\\n") + str.tostring(lowerBars, "# lower bars"))

This example looks back at the last 50 bars and counts how many had higher highs versus lower highs compared to the current bar. It's a simple way to gauge whether you're at a relative high or low in the recent price action. The label displays both counts right on your chart.

Working with Arrays (Lists of Data)

Arrays are basically lists of numbers, and for loops are perfect for processing them. Here's how you can loop through an array and perform calculations on each element:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//======================================================================//
// ____ _ _ __ //
// | _ \(_)_ __ ___(_)/ _|_ _ //
// | |_) | | '_ \ / _ \ | |_| | | | //
// | __/| | | | | __/ | _| |_| | //
// |_| |_|_| |_|\___|_|_| \__, | //
// |___/ //
//======================================================================//

//@version=6
indicator("[Pineify] Array Fun", overlay=true)

arr = array.from(1, 5, 2, 4, 3)
if barstate.islast
label.new(bar_index, close, str.tostring(arr))

sum = 0
for el in arr
sum += el

if barstate.islast
label.new(bar_index + 5, close, str.tostring(sum))

sum_even = 0
for [ind, el] in arr
if ind % 2 == 1
sum_even += el

if barstate.islast
label.new(bar_index + 10, close, str.tostring(sum_even))

plot(close)

In this example, we create an array with the numbers [1, 5, 2, 4, 3]. The first loop adds up all elements (total: 15). The second loop only adds elements at odd index positions - so it adds 5 (index 1) and 4 (index 3) for a total of 9. The for/in syntax makes working with arrays much cleaner.

If you want to dive deeper into arrays, check out our comprehensive guide: Pine Script Arrays: A Simple Guide That Actually Makes Sense.

Loop Control: Break and Continue

Sometimes you need more control over your loops. Maybe you want to skip certain iterations or exit early based on conditions. That's where break and continue become your best friends:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//======================================================================//
// ____ _ _ __ //
// | _ \(_)_ __ ___(_)/ _|_ _ //
// | |_) | | '_ \ / _ \ | |_| | | | //
// | __/| | | | | __/ | _| |_| | //
// |_| |_|_| |_|\___|_|_| \__, | //
// |___/ //
//======================================================================//

//@version=6
indicator("[Pineify] Loop Control", overlay=false)

length = 10
sum = 0

for i = 1 to length
if i == 3
continue // Skip when i is 3
if i == 7
break // Stop completely when i is 7
sum := sum + i

plot(sum, title="Sum")

This loop normally would add 1+2+3+4+5+6+7+8+9+10 = 55, but with our control statements, it adds 1+2+4+5+6 = 18. We skip 3 with continue and stop completely at 7 with break.

Pro Tips to Save Your Sanity

Here are some hard-learned lessons that'll save you from debugging nightmares:

Avoid infinite loops at all costs - Always make sure your loop has a clear exit condition. Pine Script will timeout, but not before wasting your time.

Remember the plotting rule - You can only use plot() outside of loops. If you need to visualize loop data, store it in variables or use labels.

Start small, then scale up - Test your loops with small ranges first (like 5-10 iterations) before running them on hundreds of bars.

Watch your variable scope - Variables declared inside loops stay inside loops. Plan your data flow carefully.

Use meaningful counter names - Instead of just i, try barIndex or dataPoint. Your future self will thank you.

For more debugging tips, check out How to Debug Pine Script Code (The Easy Way).

Combining Loops with Conditional Logic

One powerful pattern is combining for loops with if-else statements. This lets you process data selectively based on conditions. If you're not familiar with conditional statements yet, our guide on If Else in Pine Script: Making Your Code Actually Think covers this in detail.

Wrapping Up

For loops are genuinely one of the most powerful tools in Pine Script. Once you get the hang of them, you'll wonder how you ever built complex indicators without them. They're the secret sauce behind many professional trading tools.

The key is starting simple. Pick one of the examples above, modify it slightly, and see what happens. Then gradually add complexity as you get more comfortable.

And hey, if you find yourself getting frustrated with syntax errors and debugging headaches, remember that Pineify can generate clean, working Pine Script code from plain English descriptions. Sometimes the best way to learn is to see working examples, then reverse-engineer how they work.

Ready to level up your Pine Script game? Start with loops, master the basics, and before you know it, you'll be building indicators that would make the pros jealous.