mt4: Wrong Calculation in the main for() loop in Simple Indicator.

 

I am learning to compose indicators. 

I changed the official RSI a little. Most I do is changed the final step of RSI formula. 

For practice, the idea is to calculate the (net profit in pips) / [total rise pips + abs(total fall pips)], windows = 20, time frame is M1 or M5

The main loop is shown below:

   for(i=pos; i<rates_total && !IsStopped(); i++)
     {
      diff=close[i]-close[i-1];
      //Print("diff=",diff);
      ExtPosBuffer[i]=(ExtPosBuffer[i-1]+(diff>0.0?diff:0.0));
      Print("ExtPosBuffer[i]", ExtPosBuffer[i]);
      ExtNegBuffer[i]=(ExtNegBuffer[i-1]+(diff<0.0?-diff:0.0));
      Print("ExtNegBuffer[i]", ExtNegBuffer[i]);
      ExtmyBuffer[i]= (ExtPosBuffer[i]-MathAbs(ExtNegBuffer[i]))/(ExtPosBuffer[i]+MathAbs(ExtNegBuffer[i]));
     }

In expectation, since diff is quite small, usually less than 0.0010 for EURUSD,  ExtPosBuffer[i] in 20 windows shall be much less than 1.00.  But above script returns  ExtPosBuffer[i] > 2.0.

This is obviously wrong. 

I don't understand which line code is wrong. Thank you. Whole file is uploaded in attachment. 

Files:
 

Solved.

In mt4, mt5, close[0] is the latest bar. So,  ExtPosBuffer[i] actually gets the sum from 0 to rates_total bars. 

To get the net profit pips in 20 windows,  I just need to minus bars[-20].

In the main loop, change the on-going formula as follows solves my question.

      ExtmyBuffer[i]= (ExtPosBuffer[i]- ExtPosBuffer[i-InpmyPeriod]-MathAbs(ExtNegBuffer[i]-ExtNegBuffer[i-InpmyPeriod]))/
                        (ExtPosBuffer[i]-ExtPosBuffer[i-InpmyPeriod]+MathAbs(ExtNegBuffer[i]-ExtNegBuffer[i-InpmyPeriod]));