//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers  6
#property indicator_color1   Silver
#property indicator_color2   Silver
#property indicator_color3   Red
#property indicator_color4   Blue
#property indicator_color5   Green
#property indicator_color6   Silver
#property indicator_width3   3
#property indicator_width4   3
#property indicator_width5   3
#property indicator_style1   STYLE_DOT
#property indicator_style2   STYLE_DOT
#property indicator_minimum  0
#property indicator_maximum  100

//
//
//
//
//

extern string TimeFrame    = "Current time frame";
extern int    RsiPeriod    =  9;
extern int    RsiPrice     = PRICE_CLOSE;
extern int    Smooth1      = 50;
extern int    Smooth2      =  5;
extern int    SignalPeriod =  5;
extern double Deviations   =  2;
extern bool   Interpolate  = true;

//
//
//
//
//

double rsi[];
double rsiUa[];
double rsiUb[];
double rss[];
double bandUp[];
double bandDn[];
double trend[];
string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(7);
   SetIndexBuffer(0,bandUp);
   SetIndexBuffer(1,bandDn);
   SetIndexBuffer(2,rsi);
   SetIndexBuffer(3,rsiUa);
   SetIndexBuffer(4,rsiUb);
   SetIndexBuffer(5,rss);
   SetIndexBuffer(6,trend);
   
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue";   if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";       if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
      
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" Dynamic RSI ("+RsiPeriod+")");
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int countedBars = IndicatorCounted();
      if (countedBars<0) return(-1);
      if (countedBars>0) countedBars--;
         int limit = MathMin(Bars-countedBars,Bars-1);
         if (returnBars) { bandUp[0] = MathMin(limit+1,Bars-1); return(0); }
   
   //
   //
   //
   //
   //

   if (calculateValue || timeFrame == Period())
   {
      if (trend[limit]==-1) CleanPoint(limit,rsiUa,rsiUb);
      for(int i=limit; i >= 0; i--)
      {
         double trsi = iRSI(NULL,0,RsiPeriod,RsiPrice,i);
         double y    = iSma(50-(iSma(trsi,Smooth1,i,0)-trsi),Smooth2,i,1);
         double z    = iSma(y,SignalPeriod,i,2);
         double d    = iDeviation(y,Smooth1,50,i);
            rsi[i]    = y;
            rss[i]    = z;
            bandUp[i] = 50+d*Deviations;
            bandDn[i] = 50-d*Deviations;
            trend[i]  = trend[i+1];
            rsiUa[i]  = EMPTY_VALUE;
            rsiUb[i]  = EMPTY_VALUE;
               if (rsi[i]>rss[i]) trend[i] =  1;
               if (rsi[i]<rss[i]) trend[i] = -1;
               if (trend[i]==1) PlotPoint(i,rsiUa,rsiUb,rsi);
      }
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (trend[limit]==-1) CleanPoint(limit,rsiUa,rsiUb);
   for (i=limit; i>=0; i--)
   {
      int x = iBarShift(NULL,timeFrame,Time[i]);
         bandUp[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,0,x);
         bandDn[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,1,x);
         rsi[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,2,x);
         rss[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,5,x);
         trend[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,6,x);
         rsiUa[i]  = EMPTY_VALUE;
         rsiUb[i]  = EMPTY_VALUE;
   
         if (!Interpolate || x==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

            datetime time = iTime(NULL,timeFrame,x);
               for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
               for(int k = 1; k < n; k++)
               {
                  rsi[i+k]    = rsi[i]    + (rsi[i+n]    - rsi[i]   )*k/n;
                  rss[i+k]    = rss[i]    + (rss[i+n]    - rss[i]   )*k/n;
                  bandUp[i+k] = bandUp[i] + (bandUp[i+n] - bandUp[i])*k/n;
                  bandDn[i+k] = bandDn[i] + (bandDn[i+n] - bandDn[i])*k/n;
               }
   }         
   for (i=limit;i>=0;i--) if (trend[i]==1) PlotPoint(i,rsiUa,rsiUb,rsi);
   return(0);
}


//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double array[];
double iDeviation(double value, double period, double avg, int i)
{
   if (ArraySize(array)!=Bars) ArrayResize(array,Bars); i= Bars-i-1; array[i] = value;
      double sum = 0; for(int k=0; k<period; k++) sum += (array[i-k]-avg)*(array[i-k]-avg);
   return(MathSqrt(sum/period));
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double workSma[][6];
double iSma(double price, int period, int r, int instanceNo=0)
{
   if (ArrayRange(workSma,0)!= Bars) ArrayResize(workSma,Bars); instanceNo *= 2; r=Bars-r-1;

   //
   //
   //
   //
   //
      
   workSma[r][instanceNo] = price;
   if (r>=period)
          workSma[r][instanceNo+1] = workSma[r-1][instanceNo+1]+(workSma[r][instanceNo]-workSma[r-period][instanceNo])/period;
   else { workSma[r][instanceNo+1] = 0; for(int k=0; k<period && (r-k)>=0; k++) workSma[r][instanceNo+1] += workSma[r-k][instanceNo];  
          workSma[r][instanceNo+1] /= k; }
   return(workSma[r][instanceNo+1]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   if ((second[i]  != EMPTY_VALUE) && (second[i+1] != EMPTY_VALUE))
        second[i+1] = EMPTY_VALUE;
   else
      if ((first[i] != EMPTY_VALUE) && (first[i+1] != EMPTY_VALUE) && (first[i+2] == EMPTY_VALUE))
          first[i+1] = EMPTY_VALUE;
}

//
//
//
//
//

void PlotPoint(int i,double& first[],double& second[],double& from[])
{
   if (first[i+1] == EMPTY_VALUE)
      {
         if (first[i+2] == EMPTY_VALUE) {
                first[i]   = from[i];
                first[i+1] = from[i+1];
                second[i]  = EMPTY_VALUE;
            }
         else {
                second[i]   =  from[i];
                second[i+1] =  from[i+1];
                first[i]    = EMPTY_VALUE;
            }
      }
   else
      {
         first[i]  = from[i];
         second[i] = EMPTY_VALUE;
      }
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

string sTfTable[] = {"M1","M5","M15","M30","H1","H4","D1","W1","MN"};
int    iTfTable[] = {1,5,15,30,60,240,1440,10080,43200};

//
//
//
//
//

int stringToTimeFrame(string tfs)
{
   tfs = stringUpperCase(tfs);
   for (int i=ArraySize(iTfTable)-1; i>=0; i--)
         if (tfs==sTfTable[i] || tfs==""+iTfTable[i]) return(MathMax(iTfTable[i],Period()));
                                                      return(Period());
}
string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//
//
//
//
//

string stringUpperCase(string str)
{
   string   s = str;

   for (int length=StringLen(str)-1; length>=0; length--)
   {
      int tchar = StringGetChar(s, length);
         if((tchar > 96 && tchar < 123) || (tchar > 223 && tchar < 256))
                     s = StringSetChar(s, length, tchar - 32);
         else if(tchar > -33 && tchar < 0)
                     s = StringSetChar(s, length, tchar + 224);
   }
   return(s);
}