I wrote this function, it works, but the value doesn't match what MT4 shows me. What am I doing wrong?
MQL4:
void CalcRSI(int period, bool output = true) { int startDate = 2 * period; double gains[]; double losses[]; ArrayResize(gains, startDate + 1); ArrayResize(losses, startDate + 1); for (int i = startDate; i >= 0; i--) { double diff = Close[i] - Close[i + 1]; gains[i] = diff > 0 ? diff : 0.0; losses[i] = diff > 0 ? 0.0 : -diff; } double avrGain = 0.0; double avrLoss = 0.0; // initial average for (int i = startDate; i > startDate - period; i--) { avrGain += gains[i]; avrLoss += losses[i]; } avrGain /= period; avrLoss /= period; // Wilder's smoothing for (int i = startDate - period; i >= 0; i--) { avrGain = (avrGain * (period - 1) + gains[i]) / period; avrLoss = (avrLoss * (period - 1) + losses[i]) / period; } double rs = avrGain / avrLoss; double rsi = 100 - (100 / (1 + rs)); if(output) { Alert(StringFormat("RSI(%d): %.2f", period, rsi)); } }
Last edited by a moderator: