//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1  clrLimeGreen
#property indicator_color2  clrPaleVioletRed
#property indicator_color3  clrPaleVioletRed
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_level1  0.3
#property indicator_level2  0.7
#property indicator_minimum 0
#property indicator_maximum 1

//
//
//
//
//
enum enTimeFrames
{
   tf_cu  = PERIOD_CURRENT, // Current time frame
   tf_m1  = PERIOD_M1,      // 1 minute
   tf_m5  = PERIOD_M5,      // 5 minutes
   tf_m15 = PERIOD_M15,     // 15 minutes
   tf_m30 = PERIOD_M30,     // 30 minutes
   tf_h1  = PERIOD_H1,      // 1 hour
   tf_h4  = PERIOD_H4,      // 4 hours
   tf_d1  = PERIOD_D1,      // Daily
   tf_w1  = PERIOD_W1,      // Weekly
   tf_mn1 = PERIOD_MN1,     // Monthly
   tf_n1  = -1,             // First higher time frame
   tf_n2  = -2,             // Second higher time frame
   tf_n3  = -3              // Third higher time frame
};
//
//

extern enTimeFrames    TimeFrame          = tf_cu;   // Time frame
extern double          DeMarkerPeriod = 14;
extern int             AdaptPeriod    = 21;
extern bool            Interpolate    = true;            // Interpolate in multi time frame mode?

double DeMarkerBuffer[],DeMarkerBufferDa[],DeMarkerBufferDb[],slope[],count[];
string indicatorFileName;
#define _mtfCall(_buff,_ind) iCustom(NULL,TimeFrame,indicatorFileName,0,DeMarkerPeriod,AdaptPeriod,_buff,_ind)

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   for (int i=0; i<indicator_buffers; i++) SetIndexStyle(i,DRAW_LINE);
   IndicatorBuffers(5);
   SetIndexBuffer(0, DeMarkerBuffer);
   SetIndexBuffer(1, DeMarkerBufferDa);
   SetIndexBuffer(2, DeMarkerBufferDb);
   SetIndexBuffer(3, slope);
   SetIndexBuffer(4, count);
      
   indicatorFileName = WindowExpertName();
   TimeFrame         = (enTimeFrames)timeFrameValue(TimeFrame);
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" DeMarker - adaptive smoother");
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); count[0] = limit;
            if (TimeFrame != _Period)
            {
               limit = (int)MathMax(limit,MathMin(Bars-1,_mtfCall(4,0)*TimeFrame/_Period));
               if (slope[limit]==-1) CleanPoint(limit,DeMarkerBufferDa,DeMarkerBufferDb);
               for(int i=limit; i>=0; i--)
               {
                  int y = iBarShift(NULL,TimeFrame,Time[i]);
                     slope[i]            = _mtfCall(3,y);
                     DeMarkerBuffer[i]   = _mtfCall(0,y);
                     DeMarkerBufferDa[i] = EMPTY_VALUE;
                     DeMarkerBufferDb[i] = EMPTY_VALUE;
                     
                  
                     //
                     //
                     //
                     //
                     //
                  
                     if (!Interpolate || (i>0 && y==iBarShift(NULL,TimeFrame,Time[i-1]))) continue;
                        #define _interpolate(buff) buff[i+k] = buff[i]+(buff[i+n]-buff[i])*k/n
                        int n,k; datetime ctime = iTime(NULL,TimeFrame,y);
                           for(n = 1; (i+n)<Bars && Time[i+n] >= ctime; n++) continue;
                           for(k = 1; k<n && (i+n)<Bars && (i+k)<Bars; k++) _interpolate(DeMarkerBuffer);
               }
               for(i=limit; i>=0; i--) if (slope[i]==-1) PlotPoint(i,DeMarkerBufferDa,DeMarkerBufferDb,DeMarkerBuffer);
   return(0);
   }

   //
   //
   //
   //
   //
   
   if (slope[limit]==-1) CleanPoint(limit,DeMarkerBufferDa,DeMarkerBufferDb);
   for(i=limit; i>=0; i--)
   {
      double dev = iStdDev(NULL,0,AdaptPeriod,0,MODE_SMA,PRICE_CLOSE,i);
      double avg = iSma(dev,AdaptPeriod,i,0);
         if (dev!=0) 
                double period = DeMarkerPeriod*avg/dev;
         else          period = DeMarkerPeriod; 
         if (period<3) period = 3;
         
      //
      //
      //
      //
      //
      
      double demH = 0; if(Open[i]  > Open[i+1])  demH = Open[i]    - Open[i+1];
      double demL = 0; if(Close[i] < Close[i+1]) demL = Close[i+1] - Close[i];
      double smtH = MathMax(iSmooth(demH,period,i,0),0);
      double smtL = MathMax(iSmooth(demL,period,i,1),0);
         if (smtH+smtL!=0)
               DeMarkerBuffer[i] = smtH/(smtH+smtL);
         else  DeMarkerBuffer[i] = 0;
            slope[i] = slope[i+1];
            DeMarkerBufferDa[i] = EMPTY_VALUE;
            DeMarkerBufferDb[i] = EMPTY_VALUE;
               if (DeMarkerBuffer[i]>DeMarkerBuffer[i+1]) slope[i]= 1;
               if (DeMarkerBuffer[i]<DeMarkerBuffer[i+1]) slope[i]=-1;
               if (slope[i]==-1) PlotPoint(i,DeMarkerBufferDa,DeMarkerBufferDb,DeMarkerBuffer);
   }   
   return(0);
}

//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

double workSmooth[][10];
double iSmooth(double price, double length, int r, int instanceNo=0)
{
   if (ArrayRange(workSmooth,0)!=Bars) ArrayResize(workSmooth,Bars); instanceNo *= 5; r = Bars-r-1;
 	if(r<=2) { workSmooth[r][instanceNo] = price; workSmooth[r][instanceNo+2] = price; workSmooth[r][instanceNo+4] = price; return(price); }
   
   //
   //
   //
   //
   //
   
	double alpha = 0.45*(length-1.0)/(0.45*(length-1.0)+2.0);
   	  workSmooth[r][instanceNo+0] =  price+alpha*(workSmooth[r-1][instanceNo]-price);
	     workSmooth[r][instanceNo+1] = (price - workSmooth[r][instanceNo])*(1-alpha)+alpha*workSmooth[r-1][instanceNo+1];
	     workSmooth[r][instanceNo+2] =  workSmooth[r][instanceNo+0] + workSmooth[r][instanceNo+1];
	     workSmooth[r][instanceNo+3] = (workSmooth[r][instanceNo+2] - workSmooth[r-1][instanceNo+4])*MathPow(1.0-alpha,2) + MathPow(alpha,2)*workSmooth[r-1][instanceNo+3];
	     workSmooth[r][instanceNo+4] =  workSmooth[r][instanceNo+3] + workSmooth[r-1][instanceNo+4]; 
   return(workSmooth[r][instanceNo+4]);
}

//-------------------------------------------------------------------
//
//-------------------------------------------------------------------
//
//
//
//
//

double workSma[][2];
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("");
}
int timeFrameValue(int _tf)
{
   int add  = (_tf>=0) ? 0 : MathAbs(_tf);
   if (add != 0) _tf = _Period;
   int size = ArraySize(iTfTable); 
      int i =0; for (;i<size; i++) if (iTfTable[i]==_tf) break;
                                   if (i==size) return(_Period);
                                                return(iTfTable[(int)MathMin(i+add,size-1)]);
}




