Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Moving Average in TradingView?

Tags:

pine-script

I want to implement the Moving Average (MA) TradingView.

There are already some built-in functions for moving averages (like sma(), ema(), and wma()). Now I want to built my own MA function.

Can you help me? Thanks.

like image 793
ledien Avatar asked Oct 29 '17 10:10

ledien


People also ask

How do you create a moving average?

A simple moving average is formed by computing the average price of a security over a specific number of periods. Most moving averages are based on closing prices; for example, a 5-day simple moving average is the five-day sum of closing prices divided by five.


Video Answer


2 Answers

According to the manual, sma is the standard MA.

The sma function returns the moving average, that is the sum of last y values of x, divided by y. sma(source, length) → series

But if you still insist, they also show you how to do it in pine-script, like this:

// same in pine, but much less efficient
pine_sma(x, y) =>
    sum = 0.0
    for i = 0 to y - 1
        sum := sum + x[i] / y
    sum
plot(pine_sma(close, 15))
like image 193
not2qubit Avatar answered Oct 17 '22 10:10

not2qubit


from pine documentation,

my_sma(src, len) =>
    sum = 0.0
    sum := nz(sum[1]) - nz(src[len]) + src
    sum/len   

And that is efficient.

like image 1
Aftershock Avatar answered Oct 17 '22 09:10

Aftershock