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.
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.
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))
from pine documentation,
my_sma(src, len) =>
sum = 0.0
sum := nz(sum[1]) - nz(src[len]) + src
sum/len
And that is efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With