How do you calculate moving average in MQL5?

196

Hi,

I'm porting code across from MQL4 to MQL5 and am battling on what I thought would be quite simple.

I want to work out the moving average.

In MQL4 it was:
double movingAverage = iMA(m_symbol, m_timeFrame, period, index, m_maMethod , PRICE_CLOSE, 0);

In MQL 5 we now get:

double firstMA = iMA(Symbol(), PERIOD_H1, maSize, index, MODE_SMA, PRICE_CLOSE);

The help file: https://www.mql5.com/en/docs/indicators/ima

Seems to show how to set the moving average... I'm after the value of the moving average (i.e. the average close is 1.2030) , not it's handle or how to set it.

Please can I example of how to get the moving average.

Thanks

Documentation on MQL5: Technical Indicators / iMA
• www.mql5.com
Technical Indicators / iMA - Reference on algorithmic/automated trading language for MetaTrader 5
Moderator
32842

https://www.mql5.com/en/articles/43
How to call indicators in MQL5
• 2010.03.12
• KlimMalgin
• www.mql5.com
With new version of MQL programming language available not only the approach of dealing with indicators have changed, but there are also new ways of how to create indicators. Furthermore, you have additional flexibility working with indicator's buffers - now you can specify the desired direction of indexing and get exactly as many indicator's values as you want. This article explains the basic methods of calling indicators and retrieving data from the indicator's buffers.
196

Thanks!

I put a simple example at the bottom of the article in the comments.

Please tell me if it's wrong and I'll amend it.

Much appreciated.

196

Nope... it didn't work in a function on the USDCAD. All the values in the array were zero. When I ran it on #MSFT it worked.

Have a look at my comments on that article.

I'm doing something wrong but don't know what it is. I'm just after the moving average... nothing fancy.

196

Figured it out...

The OnInit() code initializes the indicator.

Then the OnTick() calls it. The two bits of code need to be separate.
I put an example in the comments section on that post (https://www.mql5.com/en/articles/43)

How to call indicators in MQL5
• 2010.03.12
• KlimMalgin
• www.mql5.com
With new version of MQL programming language available not only the approach of dealing with indicators have changed, but there are also new ways of how to create indicators. Furthermore, you have additional flexibility working with indicator's buffers - now you can specify the desired direction of indexing and get exactly as many indicator's values as you want. This article explains the basic methods of calling indicators and retrieving data from the indicator's buffers.