Why is the ATR (indicator and self-calculated) not the same?

 

Hello guys,

I made a little script which shows the ATR(100). I did it by using the built in ATR indicator and by calculating it in a loop.

Can someone explain why the results are not the same?

void OnStart() {
   double bufferATR100[];
   int handleATR100=iATR(_Symbol,PERIOD_CURRENT,100);
   if (CopyBuffer(handleATR100,0,0,1,bufferATR100)!=1) {
      Alert("Copy problem");
      return;
   }
   double atr1=bufferATR100[0];
   Alert("atr1: "+(string)atr1);
   double a=0;
   for (int i=1;i<=100;i++) {
      a=a+(iHigh(_Symbol,PERIOD_CURRENT,i)-iLow(_Symbol,PERIOD_CURRENT,i));
   }
   double atr2=(a/100);
   Alert("atr2: "+(string)atr2);
}
 
Marbo:

Hello guys,

I made a little script which shows the ATR(100). I did it by using the built in ATR indicator and by calculating it in a loop.

Can someone explain why the results are not the same?

void OnStart() {
   double bufferATR100[];
   int handleATR100=iATR(_Symbol,PERIOD_CURRENT,100);
   if (CopyBuffer(handleATR100,0,0,1,bufferATR100)!=1) {
      Alert("Copy problem");
      return;
   }
   double atr1=bufferATR100[0];
   Alert("atr1: "+(string)atr1);

// First calculate the true range which takes into account the gaps
// TrueRange = currHigh-currLow + (prevClose<currLow)*(currLow-prevClose) + (prevClose>currHigh)*(prevClose-currHigh)

   double a=TrueRange(0);
   for (int i=1;i<100;i++) {
      a=a + TrueRange(i);
   }
   double atr2=(a/100);
   Alert("atr2: "+(string)atr2);
}
 
// TrueRange = currHigh-currLow + (prevClose<currLow)*(currLow-prevClose) + (prevClose>currHigh)*(prevClose-currHigh)
TrueRange = MathMax(prevClose, currHigh) - MathMin(prevClose, currLow); // simplified
 
Ok, so I used a wrong formula in my loop. Thank you guys!