Hello!
Im trying to add SMA line over RSI indicator, but smth wrong with my code, SMA line doesnt work correctly.
SMA calculation code goes at the bottom of funciton. Please help!
Kindly appreciate any advice
public IndicatorResult calculate(int startIndex, int endIndex) {
if (startIndex - getLookback() < 0) {
startIndex -= startIndex - getLookback();
}
if (startIndex > endIndex) {
return new IndicatorResult(0, 0);
}
int i,j, today = startIndex - getLookback(), outIdx = 0;
double prevValue = inputs[0][today], prevGain = 0, prevLoss = 0, tempValue1, tempValue2;
int pv=0;
today++;
for (i = timePeriod; i > 0; i--) {
tempValue1 = inputs[0][today++];
tempValue2 = tempValue1 - prevValue;
prevValue = tempValue1;
if( tempValue2 < 0 ) prevLoss -= tempValue2;
else prevGain += tempValue2;
}
prevGain /= timePeriod;
prevLoss /= timePeriod;
if( today > startIndex){
tempValue1 = prevGain + prevLoss;
outputs[0][outIdx++] = tempValue1 == 0 ? 0 : 100 * (prevGain / tempValue1);
}
while(today <= endIndex){
tempValue1 = inputs[0][today++];
tempValue2 = tempValue1 - prevValue;
prevValue = tempValue1;
prevLoss *= (timePeriod - 1);
prevGain *= (timePeriod - 1);
if( tempValue2 < 0 ) prevLoss -= tempValue2;
else prevGain += tempValue2;
prevLoss /= timePeriod;
prevGain /= timePeriod;
tempValue1 = prevLoss + prevGain;
pv=outIdx++;
outputs[0][pv] = tempValue1 == 0 ? 0 : 100 * (prevGain / tempValue1);
}
//SMA calculation goes here
for (i = startIndex, j = 0; i <= endIndex; i++, j++) {
if ((i - smaPeriod)>0 && ((i - smaPeriod)<=95)) {
double sum = 0;
boolean calculated = true;
for (int k = (i - smaPeriod); k < i; k++) {
double curIndex = outputs[0][k];
if (Double.isNaN(curIndex)) {
calculated = false;
break;
}
sum += outputs[0][k];
}
if (calculated) {
outputs[1][i] = (sum / smaPeriodDouble);
}
}
}