//------------------------------------------------------------------
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 5
#property indicator_color1  Silver
#property indicator_color2  Silver
#property indicator_color3  PaleVioletRed
#property indicator_color4  EMPTY
#property indicator_color5  EMPTY
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2
#property indicator_width5  2
#property indicator_level1  0

//
//
//
//
//

extern string TimeFrame       = "Current time frame";
extern double FastPeriod      = 14;
extern double SlowPeriod      = 34;
extern int    SignalPeriod    =  9;
extern int    SignalMethod    = MODE_EMA;
extern int    RsiPeriod       = 14;
extern int    Price           = PRICE_CLOSE;
extern bool   ColorSignalLine = true;
extern color  ColorUp         = LimeGreen;
extern color  ColorDown       = DarkOrange;
extern color  ColorMacd       = Silver;
extern color  ColorSignal     = Silver;

//
//
//
//
//

double macd[];
double macdl[];
double signal[];
double colorDa[];
double colorDb[];
double slope[];

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(6);
   SetIndexBuffer(0,macd); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,macdl);
   SetIndexBuffer(2,signal);
   SetIndexBuffer(3,colorDa); SetIndexStyle(3,DRAW_LINE,EMPTY,EMPTY,ColorDown);
   SetIndexBuffer(4,colorDb); SetIndexStyle(4,DRAW_LINE,EMPTY,EMPTY,ColorDown);
   SetIndexBuffer(5,slope);
   
      //
      //
      //
      //
      //
      
         indicatorFileName = WindowExpertName();
         calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) { return(0); }
         returnBars        = TimeFrame=="returnBars";     if (returnBars)     { return(0); }
         timeFrame         = stringToTimeFrame(TimeFrame);
         if (ColorSignalLine)
               { SetIndexStyle(2,DRAW_LINE,EMPTY,EMPTY,ColorUp); SetIndexStyle(1,DRAW_LINE,EMPTY,EMPTY,ColorMacd);   }
         else  { SetIndexStyle(1,DRAW_LINE,EMPTY,EMPTY,ColorUp); SetIndexStyle(2,DRAW_LINE,EMPTY,EMPTY,ColorSignal); }
      
      //
      //
      //
      //
      //
      
      IndicatorShortName(timeFrameToString(timeFrame)+" MACD rsi adaptive ("+DoubleToStr(FastPeriod,2)+","+DoubleToStr(SlowPeriod,2)+","+SignalPeriod+","+RsiPeriod+")");
   return(0);
}
int deinit() { return(0); }

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int start()
{
   int counted_bars=IndicatorCounted();
      if(counted_bars < 0) return(-1);
      if(counted_bars>0) counted_bars--;
         int limit = MathMin(Bars-counted_bars,Bars-1);
         if (returnBars) { macd[0] = MathMin(limit+1,Bars-1); return(0); }
         
   //
   //
   //
   //
   //
    
   if (calculateValue || timeFrame == Period())
   {
      if (slope[limit]==-1) CleanPoint(limit,colorDa,colorDb);
      for(int i = limit; i>=0; i--)
      {
         double rsi   = iRSI(NULL,0,RsiPeriod,Price,i);
         double price = iMA(NULL,0,1,0,MODE_SMA,Price,i);
         macd[i]  = iREma(price,FastPeriod,RsiPeriod,rsi,i,0)-iREma(price,SlowPeriod,RsiPeriod,rsi,i,1);
         macdl[i] = macd[i];
      }            
      for(i = limit; i>=0; i--)
      {
         if (SignalMethod==4)
               signal[i] = iREma(macd[i],SignalPeriod,RsiPeriod,iRSI(NULL,0,RsiPeriod,price,i),i,2);
         else  signal[i] = iMAOnArray(macd,0,SignalPeriod,0,SignalMethod,i);
         
         //
         //
         //
         //
         //
         
            colorDa[i] = EMPTY_VALUE;
            colorDb[i] = EMPTY_VALUE;
            slope[i]   = slope[i+1];
            if (ColorSignalLine)
            {
               if (signal[i]>signal[i+1]) slope[i] =  1;
               if (signal[i]<signal[i+1]) slope[i] = -1;
                  if (slope[i]==-1) PlotPoint(i,colorDa,colorDb,signal);
            }
            else
            {
               if (macd[i]>macd[i+1]) slope[i] =  1;
               if (macd[i]<macd[i+1]) slope[i] = -1;
                  if (slope[i]==-1) PlotPoint(i,colorDa,colorDb,macd);
            }
      }         
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   if (slope[limit]==-1) CleanPoint(limit,colorDa,colorDb);
   for (i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         macd[i]    = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",FastPeriod,SlowPeriod,SignalPeriod,SignalMethod,RsiPeriod,Price,ColorSignalLine,0,y);
         signal[i]  = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",FastPeriod,SlowPeriod,SignalPeriod,SignalMethod,RsiPeriod,Price,ColorSignalLine,2,y);
         slope[i]   = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",FastPeriod,SlowPeriod,SignalPeriod,SignalMethod,RsiPeriod,Price,ColorSignalLine,5,y);
         macdl[i]   = macd[i];
         colorDa[i] = EMPTY_VALUE;
         colorDb[i] = EMPTY_VALUE;
            if (ColorSignalLine)
                  { if (slope[i]==-1) PlotPoint(i,colorDa,colorDb,signal); }
            else  { if (slope[i]==-1) PlotPoint(i,colorDa,colorDb,macd);   }
   }
   return(0);         
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double ema[][3];
double iREma(double price, int emaPeriod, int rsiPeriod, double rsi, int i, int instanceNo=0)
{
   if (ArrayRange(ema,0)!=Bars) ArrayResize(ema,Bars); int r=Bars-i-1;
   
   //
   //
   //
   //
   //
   
   double RSvoltl = MathAbs(rsi-50)+1.0;
   double multi   = (5.0+100.0/rsiPeriod)/(0.06+0.92*RSvoltl+0.02*MathPow(RSvoltl,2));
   double alpha   = 2.0 /(1.0+multi*emaPeriod);
           ema[r][instanceNo] = ema[r-1][instanceNo]+alpha*(price-ema[r-1][instanceNo]);
   return( ema[r][instanceNo]);           
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

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);
}