7

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.

PineCoders-LucF
  • 8,288
  • 2
  • 12
  • 21
ledien
  • 529
  • 2
  • 8
  • 19
  • Is your question still relevant? If yes, then you need to understand what problems you have with building MA. – AnyDozer Jan 19 '21 at 13:38

2 Answers2

7

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))
not2qubit
  • 14,531
  • 8
  • 95
  • 135
  • How do you console.log in pine? – zero_cool Feb 07 '18 at 04:44
  • 1
    @zero_cool You don't. It is not JS based, but "invented" by T.V. – not2qubit Feb 07 '18 at 14:09
  • It's just an analogy to express what I'm looking to do. It's strange to invent a programming language that does not allow one to log to the console. – zero_cool Feb 07 '18 at 17:56
  • 2
    There is no console. If you search the TV Wiki pages, you can find ways to put some very simple text [like this](https://blog.tradingview.com/en/new-features-of-pine-script-language-893/) but you can't use variables for the text. – not2qubit Feb 07 '18 at 20:46
  • 1
    You can see the console underneath the script when you save. It indicates errors, and success. That's cool that you can put text in. If you could put variables in, that could be used as a substitute! – zero_cool Feb 07 '18 at 21:43
  • This doesn't compile on the latest release. Error is Script could not be translated from: for i = 0 to y. Any idea why? Was there a syntax update? – lukemtesta Jun 24 '18 at 23:20
  • If a previously working script suddenly doesn't work in TV, then make sure to refresh the entire webpage (CTRL-R). TV's webpage is notoriously unstable when not regularly refreshed! – not2qubit Jun 27 '18 at 16:50
1
from pine documentation,

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

And that is efficient.

Aftershock
  • 5,205
  • 4
  • 51
  • 64