//+------------------------------------------------------------------+
//|                        Smoothed Rsi Inverse Fisher Transform.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  LimeGreen
#property indicator_color2  Orange
#property indicator_color3  Orange
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_levelcolor DimGray

//
//
//
//
//

extern string TimeFrame         = "Current time frame";
extern int    RsiPeriod         = 15;
extern int    EmaPeriod         =  4;
extern double Filter            = 10;
extern double FilterSpeed       = 3;
extern bool   FilterAdaptive    = true;
extern int    FilterPrice       = PRICE_CLOSE;
extern double LevelUp           = 88;
extern double LevelDown         = 12;
extern int    Normalization     = 1;
extern bool   alertsOn          = false;
extern bool   alertsOnZoneEnter = true;
extern bool   alertsOnZoneExit  = true;
extern bool   alertsOnCurrent   = true;
extern bool   alertsMessage     = true;
extern bool   alertsSound       = false;
extern bool   alertsEmail       = false;
extern bool   Interpolate       = true;

//
//
//
//
//

double  inv[];
double  invda[];
double  invdb[];
double  rwm[];
double  ema1[];
double  ema2[];
double  trend[];
double  slope[];

//
//
//
//
//

int    timeFrame;
string indicatorFileName;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define noCheckValue 9999991
int init()
{
   IndicatorBuffers(8);
      SetIndexBuffer(0,inv);
      SetIndexBuffer(1,invda);
      SetIndexBuffer(2,invdb);
      SetIndexBuffer(3,rwm);
      SetIndexBuffer(4,ema1);
      SetIndexBuffer(5,ema2);
      SetIndexBuffer(6,trend);
      SetIndexBuffer(7,slope);
      
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();

               if (LevelDown>LevelUp)
               {
                  double temp = LevelUp;
                                LevelUp = LevelDown;
                                          LevelDown = temp;
               }
               if (LevelUp   < 0 || LevelUp   > 100) LevelUp   =  noCheckValue; SetLevelValue(0,LevelUp);
               if (LevelDown < 0 || LevelDown > 100) LevelDown = -noCheckValue; SetLevelValue(1,LevelDown);
            
         calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
         returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
         timeFrame         = stringToTimeFrame(TimeFrame);
         
      //
      //
      //
      //
      //
               
   IndicatorShortName(timeFrameToString(timeFrame)+" Smoothed Rsi IFT of oma ("+RsiPeriod+","+EmaPeriod+","+Filter+")");
   return(0);
}


//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
   int i,k,n,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { inv[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (calculateValue || timeFrame == Period())
   {
      if (slope[limit]==-1) CleanPoint(limit,invda,invdb);
      for(i=limit; i>=0; i--) rwm[i] = iOma(iMA(NULL,0,1,0,MODE_SMA,FilterPrice,i),Filter,FilterSpeed,FilterAdaptive,i,0);   

      //
      //
      //
      //
      //
      
      double alpha  = 2.0 / (1+EmaPeriod);
      for(i=limit; i>=0; i--)
      {
         double rsi      = 0.1 * (iRSIOnArray(rwm,0,RsiPeriod,i)-50.0);
                ema1[i]  = ema1[i+1]+alpha*(rsi    -ema1[i+1]);
                ema2[i]  = ema2[i+1]+alpha*(ema1[i]-ema2[i+1]);
         double zlema    = 2.0*ema1[i]-ema2[i];
                inv[i]   = NormalizeDouble(((MathExp(2.0*zlema)-1.0)/(MathExp(2.0*zlema)+1.0)+1.0)*50.0,Normalization);
                invda[i] = EMPTY_VALUE;
                invdb[i] = EMPTY_VALUE;
                trend[i] = trend[i+1];
                slope[i] = slope[i+1];
                     if (inv[i]>LevelUp  )                   trend[i] =  1;
                     if (inv[i]<LevelDown)                   trend[i] = -1;
                     if (inv[i]>inv[i+1])                    slope[i] =  1;
                     if (inv[i]<inv[i+1])                    slope[i] = -1;
                     if (inv[i]<LevelUp && inv[i]>LevelDown) trend[i] =  0;
                     if (slope[i]==-1) PlotPoint(i,invda,invdb,inv);
      }
      manageAlerts();
      return(0);
   }

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         inv[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,EmaPeriod,Filter,FilterSpeed,FilterAdaptive,FilterPrice,LevelUp,LevelDown,Normalization,alertsOn,alertsOnZoneEnter,alertsOnZoneExit,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,0,y);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,EmaPeriod,Filter,FilterSpeed,FilterAdaptive,FilterPrice,LevelUp,LevelDown,Normalization,alertsOn,alertsOnZoneEnter,alertsOnZoneExit,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,6,y);
         slope[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,EmaPeriod,Filter,FilterSpeed,FilterAdaptive,FilterPrice,LevelUp,LevelDown,Normalization,alertsOn,alertsOnZoneEnter,alertsOnZoneExit,alertsOnCurrent,alertsMessage,alertsSound,alertsEmail,7,y);
         invda[i] = EMPTY_VALUE;
         invdb[i] = EMPTY_VALUE;
            
         //
         //
         //
         //
         //
      
         if (!Interpolate || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,timeFrame,y);
            for(n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(k = 1; k < n; k++)
               inv[i+k] = inv[i] + (inv[i+n]-inv[i])*k/n;
   }
   for(i=limit; i>=0; i--) if (slope[i]==-1) PlotPoint(i,invda,invdb,inv);
   return(0);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; 
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (alertsOnZoneEnter && trend[whichBar]   == 1)                        doAlert(whichBar,DoubleToStr(LevelUp  ,2)+" crossed up");
         if (alertsOnZoneEnter && trend[whichBar]   ==-1)                        doAlert(whichBar,DoubleToStr(LevelDown,2)+" crossed down");
         if (alertsOnZoneExit  && trend[whichBar+1] == 1 && trend[whichBar]!=-1) doAlert(whichBar,DoubleToStr(LevelUp  ,2)+" crossed down");
         if (alertsOnZoneExit  && trend[whichBar+1] ==-1 && trend[whichBar]!= 1) doAlert(whichBar,DoubleToStr(LevelDown,2)+" crossed up");
      }         
   }
}

//
//
//
//
//

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())," Smoothed Rsi IFT level ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," Smoothed Rsi ift "),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);
}

//------------------------------------------------------------------
//                                                                  
//------------------------------------------------------------------
//
//
//
//
//

double workOma[][7];
#define F01 0
#define F02 1
#define F03 2
#define F04 3
#define F05 4
#define F06 5
#define prc 6

//
//
//
//
//

double iOma(double price, double averagePeriod, double constant, bool adaptive, int r, int s=0)
{
   if (averagePeriod <=1) return(price);
   if (ArrayRange(workOma,0) != Bars) ArrayResize(workOma,Bars); r=Bars-r-1; s *=7;
   if (r<=1) 
   {
      for (int i=0; i<6; i++) workOma[r][i  +s] = 0;
                              workOma[r][prc+s] = price;
                              return(price);
   }      
   double f01=workOma[r-1][F01+s];  double f02=workOma[r-1][F02+s];
   double f03=workOma[r-1][F03+s];  double f04=workOma[r-1][F04+s];
   double f05=workOma[r-1][F05+s];  double f06=workOma[r-1][F06+s];

   //
   //
   //
   //
   //

      if (adaptive && (averagePeriod > 1))
      {
         double minPeriod = MathMin(averagePeriod,r)/2.0;
         double maxPeriod = MathMin(minPeriod*5.0,r);
         int    endPeriod = (int)MathCeil(maxPeriod);
         double signal    = MathAbs((price-workOma[r-endPeriod][prc+s]));
         double noise     = 0.00000000001;

            for(i=1; i<endPeriod; i++) noise=noise+MathAbs(price-workOma[r-i][prc+s]);

         averagePeriod = ((signal/noise)*(maxPeriod-minPeriod))+minPeriod;
      }
      
      //
      //
      //
      //
      //
      
      double Kg = (2.0+constant)/(1.0+constant+averagePeriod);
      double Hg = 1.0-Kg;

      f01 = Kg * price + Hg * f01; f02 = Kg * f01 + Hg * f02; double v01 = 1.5 * f01 - 0.5 * f02;
      f03 = Kg * v01   + Hg * f03; f04 = Kg * f03 + Hg * f04; double v02 = 1.5 * f03 - 0.5 * f04;
      f05 = Kg * v02   + Hg * f05; f06 = Kg * f05 + Hg * f06; double v03 = 1.5 * f05 - 0.5 * f06;

   //
   //
   //
   //
   //

   workOma[r][F01+s] = f01;  workOma[r][F02+s] = f02;
   workOma[r][F03+s] = f03;  workOma[r][F04+s] = f04;
   workOma[r][F05+s] = f05;  workOma[r][F06+s] = f06;
   workOma[r][prc+s] = price;
   return(v03);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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;
      }
}

