#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 DodgerBlue
#property indicator_level1 70
#property indicator_level2 30

double RSI_Buffer[];

input int RSI_Period = 4;
input int EMA_Period = 14;

//---------------------------------------------------
int OnInit()
{
   SetIndexBuffer(0, RSI_Buffer);
   SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 5);
   SetIndexLabel(0, "RSI(EMA14,4)");

   IndicatorShortName("RSI of EMA(14,4)");

   return(INIT_SUCCEEDED);
}

//---------------------------------------------------
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
   int limit = rates_total - EMA_Period - RSI_Period - 2;
   if(limit < 0) return(0);

   for(int i = limit; i >= 0; i--)
   {
      double gains = 0;
      double losses = 0;

      for(int j = 0; j < RSI_Period; j++)
      {
         double ema_now  = iMA(NULL, 0, EMA_Period, 0, MODE_EMA, PRICE_CLOSE, i + j);
         double ema_prev = iMA(NULL, 0, EMA_Period, 0, MODE_EMA, PRICE_CLOSE, i + j + 1);

         double diff = ema_now - ema_prev;

         if(diff > 0)
            gains += diff;
         else
            losses -= diff;
      }

      if(losses == 0)
         RSI_Buffer[i] = 100;
      else
      {
         double rs = gains / losses;
         RSI_Buffer[i] = 100 - (100 / (1 + rs));
      }
   }

   return(rates_total);
}