How To Write A Pine Script Loop - Market Scripters (2024)

How do you do a loop in Pine Script? I’m glad you asked. Loops are powerful. Very powerful. Loops can be used to count, to add things, to average things, to find things, and for a lot of other useful math calculations.

Many of Pine Script’s built in functions use for loops. Writing them isn’t hard syntactically, but Pine has some weird quirks with loops that, unless you know what’s going on in their compiler, it can be hard to debug issues.

What is a loop?

A loop is a chunk of code that want the computer to run again and again and again. It’s something you want it to run multiple times for the purpose of some kind of calculation or display of information.
Loops in Pine Script are “for loops”. The word “for” is a special programming word that is used like this context: “for each apple in the basket: cut the apple in half”. No, Pine Script is not that Englishy, but you get the idea.

Examples of For Loops in Pine Script

The most common example is the simple moving average or sma. The math behind the SMA is you loop over the last N bars, add up the series value you want to average from each one, then divide by N.
In pseudo code, it looks something like this:

total = 0n = 7for each of the last n bars total = total + close sma = total / n

Does that make sense? See how that works?
This is a very simple example, but many complex programs are and can be built from for loops.

How to write a for loop in Pine Script

Ready to get your hands dirty? Good, let’s do this.
We’re going to write our own SMA function.

First you need to prepare a couple things. You need to know what you’re calculating. For an SMA, we’re adding up the sum of a certain number of bars.
So we need to know the number of bars (let’s call this N), and we need a place to store the sun as we go.

float total = 0int n = 30

Great, so far so good.
Next we’ll do the loop. Each for loop defines the specific code you want to run multiple times. And that code is “scoped” or lives in its own container, if you will. Because of this we write the n and total variables first, outside of the loops scope container, so that we can access them after the loop is done. The loop however can access these variables and even modify them. (And they’ll stay modified after the loop is over.)

float total = 0int n = 30SMA = for i = 0 to n-1 total := total + close[i] sma = total / n

That’s it! The SMA variable will hold the value of the Smoothed Moving Average over the last 30 bars (including the current candle). If you’ve programmed in other languages before, you probably noticed this is weird…yes, in PIne Script, for loops return a value. The for loop returns the last value that was calculated. If you break early from the loop, it behaves the same way.

If you’re new to programming, you might be asking why we go from 0 to n-1 instead of 1 to n. Well…computers count from 0. So, to do 30 iterations, we have to go from 0 to 29 instead of 1 to 30. If did do 1 to n, in this case, our SMA would NOT include the value of the current candle, since our first call would use close[1] (one candle before the previous) instead of close[0] (the current candle).

Loops in Pine Script are great, you can do so much and make some very useful functions. Built in functions like valuewhen, barssince, and pivothigh use loops, just to name a few. But there are some things to look out for when writing your own Pine Script loops.

Ending A Loop Early

If you’re using a for loop to look for something, (say, if the current price is higher than any of the 30 previous highs) it would make sense to stop looking if you found your answer early. Pine Script in TradingView is very computationally expensive and the more work your code does, the longer your script takes to run. And if it takes too long, TradingView will give you an error. So you have to be mindful of your script’s performance.

One great way to help performance when writing loops is to end early. You do this using the keyword break in your loop at the point you want it to end.

For example…

int n = 30SMA = for i = 0 to n-1 if i == 15 break

Ok, yes, this loop doesn’t actually do or calculate anything, but it does end halfway through. It works by checking if i is equal to 15 (half of n), and if so, we say break. This means “break the loop”. AKA, stop the loop and continue with the rest of the code. This can be very useful depending on what you’re trying to do and varies based on the logic in your loop.

Need help? Reach out to us in Discord. Want to hire us? Reach out in Discord as well 🙂

How To Write A Pine Script Loop - Market Scripters (2024)
Top Articles
API keys vs JWT authorization: Which is best?
How Credit Card Information Is Stolen And What To Do About It
Frases para un bendecido domingo: llena tu día con palabras de gratitud y esperanza - Blogfrases
Celebrity Extra
Hertz Car Rental Partnership | Uber
Paula Deen Italian Cream Cake
Vocabulario A Level 2 Pp 36 40 Answers Key
Umn Biology
Www.paystubportal.com/7-11 Login
Pollen Count Central Islip
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
George The Animal Steele Gif
Labor Gigs On Craigslist
Illinois Gun Shows 2022
Cashtapp Atm Near Me
Craigslist Southern Oregon Coast
Dragger Games For The Brain
Craigslist Battle Ground Washington
Imouto Wa Gal Kawaii - Episode 2
Kimoriiii Fansly
Craigslist Pasco Kennewick Richland Washington
When His Eyes Opened Chapter 3123
Sams Gas Price Sanford Fl
Rural King Credit Card Minimum Credit Score
Bfsfcu Truecar
Renfield Showtimes Near Marquee Cinemas - Wakefield 12
Edward Walk In Clinic Plainfield Il
W B Crumel Funeral Home Obituaries
Best Weapons For Psyker Darktide
Pillowtalk Podcast Interview Turns Into 3Some
Solemn Behavior Antonym
New Gold Lee
Frcp 47
1v1.LOL Game [Unblocked] | Play Online
Craigslist Tulsa Ok Farm And Garden
Discover Wisconsin Season 16
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Www.craigslist.com Waco
Myrtle Beach Craigs List
Az Unblocked Games: Complete with ease | airSlate SignNow
CrossFit 101
RubberDucks Front Office
Server Jobs Near
Sc Pick 3 Past 30 Days Midday
Mejores páginas para ver deportes gratis y online - VidaBytes
Stephen Dilbeck, The First Hicks Baby: 5 Fast Facts You Need to Know
Wrentham Outlets Hours Sunday
Osrs Vorkath Combat Achievements
Metra Union Pacific West Schedule
Bellin Employee Portal
login.microsoftonline.com Reviews | scam or legit check
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated:

Views: 6121

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.