//+------------------------------------------------------------------+
//|                                                           rsi ma |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "www.forex-station.com"
#property link      "www.forex-station.com"

//
//
//
//
//

#property indicator_separate_window
#property indicator_buffers    2
#property indicator_color1     DeepSkyBlue
#property indicator_color2     Red
#property indicator_width1     2
#property indicator_style2     STYLE_DASH
#property indicator_minimum    0
#property indicator_maximum    100
#property indicator_level1     25.0
#property indicator_level2     50.0
#property indicator_level3     75.0
#property indicator_levelcolor Olive

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern int    RsiPeriod        = 2;
extern int    Price            = PRICE_CLOSE;
extern int    MaPeriod         = 7;
extern int    MaType           = MODE_LWMA;
extern int    GaussLength      = 15;
extern int    GaussOrder       = 3;
extern bool   Interpolate      = true;

extern string _                = "alerts settings";
extern bool   alertsOn         = false;
extern bool   alertsOnCurrent  = false;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;

extern string  __              = "arrows settings";
extern bool   ShowArrows       = false;
extern string arrowsIdentifier = "rsima arrows";
extern color  arrowsUpColor    = Lime;
extern color  arrowsDnColor    = Orange;

//
//
//
//
//

double rsi[];
double ema[];
double prc[];
double trend[];
double coeffs[][3];

//
//
//
//
//

string indicatorFileName;
int    timeFrame;
bool   returnBars;
bool   calculateValue;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{

    IndicatorDigits(15);
    GaussLength = MathMax(GaussLength,1);
    GaussOrder  = MathMax(MathMin(GaussOrder,23),1);
    InitCoeffs(GaussLength,GaussOrder);
    
    IndicatorBuffers(3);
    SetIndexBuffer(0,rsi);
    SetIndexBuffer(1,ema);
    SetIndexBuffer(2,trend);
    
    //
    //
    //
    //
    //
      
      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="calculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);
      
    //
    //
    //
    //
    //
      
    IndicatorShortName(timeFrameToString(timeFrame)+"  rsi gaussian ma ("+RsiPeriod+","+MaPeriod+")");
 
   return(0);
}

//
//
//
//
//

int deinit()
{  
   if (!calculateValue && ShowArrows) deleteArrows(); 
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) { rsi[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      for (i=limit-1; i>=0; i--)
      {
         if (GaussLength>1 && GaussOrder > 0)
         {
            rsi[i] = iRsi(iMA(NULL,0,1,0,MODE_SMA,Price,i),RsiPeriod,i)*coeffs[GaussOrder][1];
            double sign  = 1;
            for (int r=1; r <= GaussOrder; r++, sign *= -1.0)
                     rsi[i] += sign*coeffs[r][0]*coeffs[r][2]*rsi[i+r];
         }                        
         else  rsi[i] = iRsi(iMA(NULL,0,1,0,MODE_SMA,Price,i),RsiPeriod,i);
      }
      for(i=limit; i >= 0; i--)
      {
         ema[i]   = iMAOnArray(rsi,0,MaPeriod,0,MaType,i);
         trend[i] = trend[i+1]; 
         
	        if (rsi[i] > ema[i]) trend[i]= 1; 
	        if (rsi[i] < ema[i]) trend[i]=-1;
	        if (!calculateValue) manageArrow(i);
      }
      manageAlerts();
      return(0);
   }
          
   //
   //
   //
   //
   //
  
          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]);
                 rsi[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,Price,MaPeriod,MaType,GaussLength,GaussOrder,0,y);
                 ema[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,Price,MaPeriod,MaType,GaussLength,GaussOrder,1,y);
                 trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",RsiPeriod,Price,MaPeriod,MaType,GaussLength,GaussOrder,2,y);
                 manageArrow(i);
            
                 //
                 //
                 //
                 //
                 //
            
                 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++)
                 {
  	                  rsi[i+k] = rsi[i] + (rsi[i+n] - rsi[i]) * k/n;
  	                  ema[i+k] = ema[i] + (ema[i+n] - ema[i]) * k/n;
  	          
                  }  	            
                  }
      
                  manageAlerts();
      
   return(0);
}
                                                     
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}

//
//
//
//
//

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      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(timeFrame)+" rsi ma ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol()," rsi ma "),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//
//
//
//
//

void manageArrow(int i)
{
   if (ShowArrows)
   {
      deleteArrow(Time[i]);
      if (trend[i]!=trend[i+1])
      {
         if (trend[i] == 1) drawArrow(i,arrowsUpColor,241,false);
         if (trend[i] ==-1) drawArrow(i,arrowsDnColor,242,true);
      }
   }
}               

//
//
//
//
//

void drawArrow(int i,color theColor,int theCode,bool up)
{
   string name = arrowsIdentifier+":"+Time[i];
   double gap  = iATR(NULL,0,20,i);   
   
      //
      //
      //
      //
      //
      
      ObjectCreate(name,OBJ_ARROW,0,Time[i],0);
         ObjectSet(name,OBJPROP_ARROWCODE,theCode);
         ObjectSet(name,OBJPROP_COLOR,theColor);
  
         if (up)
               ObjectSet(name,OBJPROP_PRICE1,High[i]+gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i] -gap);
}

//
//
//
//
//

void deleteArrows()
{
   string lookFor       = arrowsIdentifier+":";
   int    lookForLength = StringLen(lookFor);
   for (int i=ObjectsTotal()-1; i>=0; i--)
   {
      string objectName = ObjectName(i);
         if (StringSubstr(objectName,0,lookForLength) == lookFor) ObjectDelete(objectName);
   }
}
void deleteArrow(datetime time)
{
   string lookFor = arrowsIdentifier+":"+time; ObjectDelete(lookFor);
}

//
//
//
//
//

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

#define Pi 3.141592653589793238462643

void InitCoeffs(int length, int n)
{
   double b = (1.0 - MathCos(2.0*Pi/length))/(MathPow(MathSqrt(2.0),2.0/n) - 1.0);
   double a = -b + MathSqrt(b*b + 2.0*b);

   ArrayResize(coeffs,n+1);
   for(int r=0; r<=n; r++)
   {
       coeffs[r][0] = fact(n)/(fact(n-r)*fact(r));
       coeffs[r][1] = MathPow(    a,r);
       coeffs[r][2] = MathPow(1.0-a,r);
   }
}

//
//
//
//
//

double fact(int n)
{
  if(n==1||n==0)
        return(1);
  else  return(n*fact(n-1));
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//
//

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    r     = Bars-shift-1;
      double alpha = 1.0/period; 

   //
   //
   //
   //
   //
   
   workRsi[r][_price+z] = price;
         if (r<period)
            {
               int k; double sum = 0; for (k=0; k<period && (r-k-1)>=0; k++) sum += MathAbs(workRsi[r-k][z+_price]-workRsi[r-k-1][z+_price]);
                  workRsi[r][z+_change] = (workRsi[r][z+_price]-workRsi[0][z+_price])/MathMax(k,1);
                  workRsi[r][z+_changa] =                                         sum/MathMax(k,1);
            }
         else
            {
               double change = workRsi[r][z+_price]-workRsi[r-1][z+_price];
                               workRsi[r][z+_change] = workRsi[r-1][z+_change] + alpha*(        change  - workRsi[r-1][z+_change]);
                               workRsi[r][z+_changa] = workRsi[r-1][z+_changa] + alpha*(MathAbs(change) - workRsi[r-1][z+_changa]);
            }
         if (workRsi[r][z+_changa] != 0)
               return(50.0*(workRsi[r][z+_change]/workRsi[r][z+_changa]+1));
         else  return(50.0);
}


      

