Moving averages are one of the basic building blocks of many traders’ toolboxes as well as many popular indicators. In this Pine Script tutorial, we’re going to walk you through how to code your own moving average. Maybe you’re trying to create a custom script that plots something which requires more complex math than a simple moving average, or maybe you just want to know the math behind it, either way, read on.

What is a Moving Average (Mathematically)?

Well, first of all, an average is the sum of a set of numbers divided by the number of numbers. For example, if we want the average of these numbers: [1, 2, 3, 4, 5] we would add them up (15) then divide by how many of them there are to get our average (15 / 5 = 3).

With this in mind, a moving average is one where the set of numbers moves. This is because in trading, charts are candle after candle after candle, and taking the average of all candles ever would make no sense and not be a very useful indicator. So we have to choose what we want the length of our average to be. Let’s continue with the example above and use 5.

As a new value is added to the set, we have to recalculate our average with the 5 last values, which will be different from the 5 we used in the previous calculation.

First calculation
Data: [1, 2, 3, 4, 5]
Avg :              3
Second calculation (new value added)
Data: 1, [2, 3, 4, 5, 6]
Avg :              3, 4

And this continues indefinitely until there is no more data…in trading: no more candles.

Data: 1, 2, 3, 4, 5, [6, 7, 8, 9, 10]
Avg :             3,  4, 5, 6, 7, 8

Yes, this example is very simple and the data is very clean. But that doesn’t matter, the math remains the same.

Coding a Moving Average in Pine Script

Of course you could simply use the built-in sma function, give it a series and a length, and it will do the math for you. There may be times however when you’d want to code your own moving average function for a more complex indicator. Let’s make one that can be used just like the built-in one.

The main tool we’re going to need to use is the for loop. The loop is what is going to get the values and add them up.

length = 5                 // define the number of numbers you want to average
sum = 0                    // create storage space for adding up the values
for i=0 to length          // define the for loop to iterate length times
    sum := sum + source[i] // reassign the sum variable as the sum plus the source value at the ith candle
average = sum / length.    // after the loop is done adding the numbers, divide by the number of numbers

Pretty cool huh! Pretty easy. The average variable now stores the value of the moving average for this candle. That is all the build in sma function is doing.

But we’re not done yet. We still want to wrap this up into a function so that we can use this formula multiple times without having to copy-paste and repeat what we’re already done. This is a PRO TIP for developing good software and writing clean, professional code. Use functions so that you don’t repeat yourself.

Here’s how we write a function in Pine Script:

mySma(source, length) =>        // define the function name and parameters
    sum = 0
    for i=0 to length
        sum := sum + source[i]
    sum / length                // the last value of a function will be returned to the caller

Ok what’s happening here? Well, the first line just means “I’m creating a function with name mySma and it needs two parameters source and length when its called.” Then we have the math from before…the for loop and the calculating of the average. The last line is different though, and this is because in a function, the last value is what gets returned to the caller, meaning the function gives that value wherever it was called.

Now your simple moving average function can be used just like any other function in Pine Script:

source = close
length = 5
average = mySma(source, length)   // call our moving average function and store its value in a variable

Not much else is needed to make this an actual study indicator…and I’ll leave that as an exercise for the reader 😉 Go ahead, code this up, and plot your very own SMA!

We’re done!

This was a Pine Script tutorial on how to write your own simple moving average function in TradingView. Things get more complex if you wanted to write a different type of moving average, for example an Exponential (ema) or Rolling (rma) moving averages.

Need help with Pine Script? Just reach out in our Discord server 🙂