//------------------------------------------------------------------
#property copyright "mladen"
#property link      "www.forex-tsd.com"
//------------------------------------------------------------------
#property indicator_separate_window
#property indicator_buffers 9
#property strict

//
//
//
//
//

enum enColorOn
{
   col_colorOnSlope,  // Change color on slope change
   col_colorOnLevelo, // Change color on outer level cross
   col_colorOnLevelm  // Change color on middle level cross
};
extern double DeMarkerPeriod  = 14;           // DeMarker period
extern int    AdaptPeriod     = 21;           // Adapting period
extern int    flLookBack      = 25;           // Floating levels look back period
extern double flLevelUp       = 90;           // Floating levels up level %
extern double flLevelDown     = 10;           // Floating levels down level %
extern bool   alertsOn        = false;        // Turn alerts on?
extern bool   alertsOnCurrent = true;         // Alerts on currnt (still opened) bar?
extern bool   alertsMessage   = true;         // Alerts should show pop-up message?
extern bool   alertsSound     = false;        // Alerts should play alert sound?
extern bool   alertsPushNotif = false;        // Alerts should send push notification?
extern bool   alertsEmail     = false;        // Alerts should send email?
extern enColorOn colorOn      = col_colorOnLevelo; // Color change
extern color  colorUp         = clrLimeGreen; // Color for up
extern color  colorDown       = clrOrangeRed; // Color for down
extern color  colorNeutral    = clrDarkGray;  // Color for neutral
extern color  colorShadow     = clrDimGray;   // Color for "shadow"
extern int    linesWidth      = 3;            // Lines width


double DeMarkerBuffer[],shadow[];
double DeMarkerBufferDa[],DeMarkerBufferUa[];
double DeMarkerBufferDb[],DeMarkerBufferUb[],flu[],flm[],fld[];
double slope[];
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

int init()
{
   IndicatorBuffers(10);
   SetIndexBuffer(0, flu);              SetIndexStyle(0,EMPTY,STYLE_DOT,0,colorUp);
   SetIndexBuffer(1, flm);              SetIndexStyle(1,EMPTY,STYLE_DOT,0,colorNeutral);
   SetIndexBuffer(2, fld);              SetIndexStyle(2,EMPTY,STYLE_DOT,0,colorDown);
   SetIndexBuffer(3, shadow);           SetIndexStyle(3,EMPTY,EMPTY,linesWidth+6,colorShadow);
   SetIndexBuffer(4, DeMarkerBuffer);   SetIndexStyle(4,EMPTY,EMPTY,linesWidth,colorNeutral);
   SetIndexBuffer(5, DeMarkerBufferUa); SetIndexStyle(5,EMPTY,EMPTY,linesWidth,colorUp);
   SetIndexBuffer(6, DeMarkerBufferUb); SetIndexStyle(6,EMPTY,EMPTY,linesWidth,colorUp);
   SetIndexBuffer(7, DeMarkerBufferDa); SetIndexStyle(7,EMPTY,EMPTY,linesWidth,colorDown);
   SetIndexBuffer(8, DeMarkerBufferDb); SetIndexStyle(8,EMPTY,EMPTY,linesWidth,colorDown);
   SetIndexBuffer(9, slope);
   IndicatorShortName("DeMarker - adaptive smoother ("+(string)DeMarkerPeriod+","+(string)AdaptPeriod+")");
   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 (slope[limit]== 1) CleanPoint(limit,DeMarkerBufferUa,DeMarkerBufferUb);
   if (slope[limit]==-1) CleanPoint(limit,DeMarkerBufferDa,DeMarkerBufferDb);
   for(int i=limit; i>=0; i--)
   {
      double dev    = iStdDev(NULL,0,AdaptPeriod,0,MODE_SMA,PRICE_CLOSE,i);
      double avg    = iSma(dev,AdaptPeriod,i,0);
      double period = DeMarkerPeriod; 
         if (dev!=0) period = MathMin(DeMarkerPeriod*avg/dev,DeMarkerPeriod*2);
                     period = MathMax(period,3);
         
      //
      //
      //
      //
      //
      
      if (i<Bars-1)
      {
         double demH = (Open[i] > Open[i+1])  ? Open[i] - Open[i+1] : 0;
         double demL = (Close[i] < Close[i+1])? Close[i+1] - Close[i] : 0;
         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;
               shadow[i] = DeMarkerBuffer[i];
               slope[i]  = slope[i+1];
               double min = DeMarkerBuffer[i];
               double max = DeMarkerBuffer[i];
               for (int k=1; k<flLookBack && i+k<Bars; k++)
               {
                     min = MathMin(DeMarkerBuffer[i+k],min);
                     max = MathMax(DeMarkerBuffer[i+k],max);
               }
               double range = max-min;
               flu[i]              = min+flLevelUp*range/100.0;
               fld[i]              = min+flLevelDown*range/100.0;
               flm[i]              = min+0.5*range;
               DeMarkerBufferDa[i] = EMPTY_VALUE;
               DeMarkerBufferDb[i] = EMPTY_VALUE;
               DeMarkerBufferUa[i] = EMPTY_VALUE;
               DeMarkerBufferUb[i] = EMPTY_VALUE;
               switch (colorOn)
               {
                  case col_colorOnSlope :
                        if (DeMarkerBuffer[i]>DeMarkerBuffer[i+1]) slope[i]= 1;
                        if (DeMarkerBuffer[i]<DeMarkerBuffer[i+1]) slope[i]=-1;
                     break;
                  case col_colorOnLevelm :
                        if (DeMarkerBuffer[i]>flm[i]) slope[i]= 1;
                        if (DeMarkerBuffer[i]<flm[i]) slope[i]=-1;
                     break;
                  default :
                        slope[i] = 0;
                        if (DeMarkerBuffer[i]>flu[i]) slope[i]= 1;
                        if (DeMarkerBuffer[i]<fld[i]) slope[i]=-1;
               }                                             
         }               
         if (slope[i]== 1) PlotPoint(i,DeMarkerBufferUa,DeMarkerBufferUb,DeMarkerBuffer);
         if (slope[i]==-1) PlotPoint(i,DeMarkerBufferDa,DeMarkerBufferDb,DeMarkerBuffer);
   }   
   manageAlerts();
   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; int k;

   //
   //
   //
   //
   //
      
   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(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 (i>=Bars-3) return;
   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 (i>=Bars-2) return;
   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; }
}

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

void manageAlerts()
{
   if (alertsOn)
   {
      int whichBar = 1; if (alertsOnCurrent) whichBar = 0;
      if (slope[whichBar] != slope[whichBar+1])
      {
         if (slope[whichBar] ==  1) doAlert(whichBar,"up");
         if (slope[whichBar] == -1) doAlert(whichBar,"down");
      }
   }
}

//
//
//
//
//

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 = Symbol()+" at "+TimeToStr(TimeLocal(),TIME_SECONDS)+" DeMarker state changed to "+doWhat;
          if (alertsMessage)   Alert(message);
          if (alertsEmail)     SendMail(Symbol()+"DeMarker",message);
          if (alertsPushNotif) SendNotification(message);
          if (alertsSound)     PlaySound("alert2.wav");
   }
}