//------------------------------------------------------------------
#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   PaleVioletRed
#property indicator_color4   LimeGreen
#property indicator_color5   LimeGreen
#property indicator_color6   Silver
#property indicator_width3   2
#property indicator_width4   2
#property indicator_width5   2
#property indicator_style1   STYLE_DOT
#property indicator_style2   STYLE_DOT
#property indicator_minimum  0
#property indicator_maximum  100

//
//
//
//
//

extern ENUM_TIMEFRAMES    TimeFrame       = PERIOD_CURRENT;
extern int                RsiPeriod       =  9;
extern ENUM_APPLIED_PRICE RsiPrice        = PRICE_CLOSE;
extern int    Smooth1         = 50;
extern int    Smooth2         =  5;
extern int    SignalPeriod    =  5;
extern double Deviations      =  2;
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = false;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsNotify    = false;
extern bool   alertsEmail     = false;
extern string soundFile       = "alert2.wav";
extern bool   Interpolate     = true;

//
//
//
//
//

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

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

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();
         returnBars        = TimeFrame==-99;
         TimeFrame         = MathMax(TimeFrame,_Period);
      
      //
      //
      //
      //
      //
   
   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 (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);
      }
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,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,PERIOD_CURRENT,RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,0,x);
         bandDn[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,1,x);
         rsi[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,2,x);
         rss[i]    = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,5,x);
         trend[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,RsiPeriod,RsiPrice,Smooth1,Smooth2,SignalPeriod,Deviations,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,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};

string timeFrameToString(int tf)
{
   for (int i=ArraySize(iTfTable)-1; i>=0; i--) 
         if (tf==iTfTable[i]) return(sTfTable[i]);
                              return("");
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] == 1) doAlert(whichBar,"buy");
         if (trend[whichBar] ==-1) doAlert(whichBar,"sell");
      }         
   }
}   

//
//
//
//
//

void doAlert(int forBar, string doWhat)
{
   static string   previousAlert="nothing";
   static datetime previousTime;
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," - ",timeFrameToString(_Period)+" dynamic rsi 3 ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsNotify)  SendNotification(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," dynamic rsi 3 "),message);
          if (alertsSound)   PlaySound(soundFile);
   }
}
