//+------------------------------------------------------------------+
//|                                                   DT-RSI-Sig.mq4 |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_minimum    0
#property indicator_maximum    100
#property indicator_buffers    3
#property indicator_color1     Aqua
#property indicator_width1     2
#property indicator_color2     Blue
#property indicator_color3     Red
#property indicator_levelcolor DarkSlateGray



//
//
//
//
//

extern string TimeFrame       = "current time frame";
extern int    RSIPeriod       = 7;
extern int    Price           = 0;
extern double levelOb         = 75.0;
extern double levelOs         = 25.0;
extern int    arrowSize       = 1;
extern bool   alertsOn        = true;
extern bool   alertsOnCurrent = true;
extern bool   alertsMessage   = true;
extern bool   alertsSound     = true;
extern bool   alertsEmail     = false;
extern bool   Interpolate     = true;
extern bool   DotsOnFirst     = false;

//
//
//
//
//

double RSILine[];
double SupLevel2[];
double ResLevel2[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

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

int init()
{

   IndicatorBuffers(4);
   SetIndexBuffer(0,RSILine); 
   SetIndexBuffer(1,SupLevel2); SetIndexStyle(1,DRAW_ARROW,0,arrowSize); SetIndexArrow(1,159); SetIndexLabel(1,"SupLevel");
   SetIndexBuffer(2,ResLevel2); SetIndexStyle(2,DRAW_ARROW,0,arrowSize); SetIndexArrow(2,159); SetIndexLabel(2,"ResLevel");
   SetIndexBuffer(3,trend);
   
   SetLevelValue(0,levelOb);
   SetLevelValue(1,50);
   SetLevelValue(2,levelOs);
   
      //
      //
      //
      //
      //
                  
      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="CalculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
         
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(timeFrame)+ " DT-RSI-SIG ("+RSIPeriod+")");
return(0);
}
   
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//

int deinit()  {   return(0);  }

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

int start()
{
   int counted_bars=IndicatorCounted();
   int i,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars)  { RSILine[0] = limit+1; return(0); }
         
   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame==Period())
   {
   
     for(i=limit; i >= 0; i--)
     {
        RSILine[i]   = iRsi(iMA(NULL,0,1,0,MODE_SMA,Price,i),RSIPeriod,i);
        ResLevel2[i] = EMPTY_VALUE;
        SupLevel2[i] = EMPTY_VALUE; 
        trend[i] = trend[i+1];
   
        if   ((RSILine[i+1] < RSILine[i+2] && RSILine[i+2] > RSILine[i+3]) || (RSILine[i+1] < RSILine[i+2] && RSILine[i+2] == RSILine[i+3] && RSILine[i+3] > RSILine[i+4]))                   
             { ResLevel2[i+2] = RSILine[i+2]; trend[i]= -1; } 
            
        if   ((RSILine[i+1] > RSILine[i+2] && RSILine[i+2] < RSILine[i+3]) || (RSILine[i+1] > RSILine[i+2] && RSILine[i+2] == RSILine[i+3] && RSILine[i+3] < RSILine[i+4])) 
             { SupLevel2[i+2] = RSILine[i+2]; trend[i]= 1; } 
     }
       
     manageAlerts();  
     return(0);           
     }
     
     //
     //
     //
     //
     //
     
     int displace = -1; if (DotsOnFirst) displace = 1;
     limit = MathMax(limit,MathMin(Bars,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
     for (i=limit;i>=0; i--)
     {
        int y = iBarShift(NULL,timeFrame,Time[i]);
        int x = iBarShift(NULL,timeFrame,Time[i+displace]);
           RSILine[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RSIPeriod,Price,levelOb,levelOs,arrowSize,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
           trend[i]     = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RSIPeriod,Price,levelOb,levelOs,arrowSize,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,3,y);
           if (x!=y)
           {           
              SupLevel2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RSIPeriod,Price,levelOb,levelOs,arrowSize,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,1,y);
              ResLevel2[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RSIPeriod,Price,levelOb,levelOs,arrowSize,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,2,y); 
           }
           else
           {
              SupLevel2[i] = EMPTY_VALUE;
              ResLevel2[i] = EMPTY_VALUE;
           }              
           
           //
           //
           //
           //
           //
      
           if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

           //
           //
           //
           //
           //

           datetime time = iTime(NULL,timeFrame,y);
              for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
              for(int k = 1; k < n; k++) RSILine[i+k] = RSILine[i] + (RSILine[i+n] - RSILine[i])*k/n;
                         
   }
   return(0);
}

//
//
//
//
//

double workRsi[][3];
#define _price  0
#define _change 1
#define _changa 2

//
//
//
//

double iRsi(double price, double period, int shift, int forz=0)
{
   if (ArrayRange(workRsi,0)!=Bars) ArrayResize(workRsi,Bars);
      int    z     = forz*3; 
      int    i     = Bars-shift-1;
      double alpha = 1.0/period; 

   //
   //
   //
   //
   //
   
   workRsi[i][_price+z] = price;
   if (i<period)
      {
         int k; double sum = 0; for (k=0; k<period && (i-k-1)>=0; k++) sum += MathAbs(workRsi[i-k][_price+z]-workRsi[i-k-1][_price+z]);
            workRsi[i][_change+z] = (workRsi[i][_price+z]-workRsi[0][_price+z])/MathMax(k,1);
            workRsi[i][_changa+z] =                                         sum/MathMax(k,1);
      }
   else
      {
         double change = workRsi[i][_price+z]-workRsi[i-1][_price+z];
                         workRsi[i][_change+z] = workRsi[i-1][_change+z] + alpha*(        change  - workRsi[i-1][_change+z]);
                         workRsi[i][_changa+z] = workRsi[i-1][_changa+z] + alpha*(MathAbs(change) - workRsi[i-1][_changa+z]);
      }
   if (workRsi[i][_changa+z] != 0)
         return(50.0*(workRsi[i][_change+z]/workRsi[i][_changa+z]+1));
   else  return(0);
}

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

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar=0;
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert("Support"  );
         if (trend[whichBar] == -1) doAlert("Resistance");
      }
   }
}

//
//
//
//
//

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

       //
       //
       //
       //
       //

       message =  timeFrameToString(Period())+" "+Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" RSI now showing "+doWhat;
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(Symbol()+" RSI",message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

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

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);
}