Download MetaTrader 5

Need help understanding the loop inside OnCalculate()

To add comments, please log in or register
hugebaozi
17
hugebaozi  

Hi guys:

standard question about how the loop works.

first time i know prev_calculated= 0 and limit = 0, Let's say in the first loop rates_total = 3 ;So in the first loop [i=0,1,2]  so after first loop prev_calculated=3 now limit = 3-1=2 and rate_total should equal to 4. so in the second loop [i=2,3] which is wrong because i've already computed the position i=2.. So I thought it should be "else limit=prev_calculated;"

 

where do i go wrong? 

int OnCalculate(....)
{
  int limit;
   if(prev_calculated==0)
      limit=0;
   else limit=prev_calculated-1;
//--- calculate MACD
   for(int i=limit;i<rates_total && !IsStopped();i++)
      ExtMacdBuffer[i]=ExtFastMaBuffer[i]-ExtSlowMaBuffer[i];
  return(rates_total);
}
enbo lu
Moderator
1959
enbo lu  

The fact is, there are some situations, when the last tick of the previous bar remains unprocessed, because when the last tick came, the last but one tick was processed. And the custom indicator was not called and was not calculated. That is why we diminish the variable counted_bars by 1, in order to eliminate this situation. 

Read this article : MQL4 Language for Newbies. Custom Indicators (Part 1) 

MQL4 Language for Newbies. Custom Indicators (Part 1) - MQL4 Articles
  • www.mql5.com
MQL4 Language for Newbies. Custom Indicators (Part 1) - MQL4 Articles: features of automated forex trading and strategy tester
Alain Verleyen
Moderator
33491
Alain Verleyen  
hugebaozi:

Hi guys:

standard question about how the loop works.

first time i know prev_calculated= 0 and limit = 0, Let's say in the first loop rates_total = 3 ;So in the first loop [i=0,1,2]  so after first loop prev_calculated=3 now limit = 3-1=2 and rate_total should equal to 4. so in the second loop [i=2,3] which is wrong because i've already computed the position i=2.. So I thought it should be "else limit=prev_calculated;"

 

where do i go wrong? 

In the first loop, position 2 is the current candle, still open.

So on next tick, either you have a new bar (rates_total=4) and you need to update position 2 for the last time. And to calculate position 3, which is the new open candle.

Either you don't have a new candle, and you are only recalcullating position 2.

To add comments, please log in or register