//+------------------------------------------------------------------+
//|                                                    adx trend.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers    6
#property indicator_color1     DeepSkyBlue  
#property indicator_color2     DeepSkyBlue  
#property indicator_color3     Orange
#property indicator_color4     Orange
#property indicator_color5     DeepSkyBlue  
#property indicator_color6     Orange
#property indicator_level1     0
#property indicator_width1     2
#property indicator_width3     2
#property indicator_width5     2
#property indicator_width6     2

//
//
//
//
//

enum enPrices
{
   pr_close,      // Close
   pr_open,       // Open
   pr_high,       // High
   pr_low,        // Low
   pr_median,     // Median
   pr_typical,    // Typical
   pr_weighted,   // Weighted
   pr_average,    // Average (high+low+open+close)/4
   pr_medianb,    // Average median body (open+close)/2
   pr_tbiased,    // Trend biased price
   pr_haclose,    // Heiken ashi close
   pr_haopen ,    // Heiken ashi open
   pr_hahigh,     // Heiken ashi high
   pr_halow,      // Heiken ashi low
   pr_hamedian,   // Heiken ashi median
   pr_hatypical,  // Heiken ashi typical
   pr_haweighted, // Heiken ashi weighted
   pr_haaverage,  // Heiken ashi average
   pr_hamedianb,  // Heiken ashi median body
   pr_hatbiased   // Heiken ashi trend biased price
};

//
//
//
//
//

extern ENUM_TIMEFRAMES TimeFrame        = PERIOD_CURRENT;
extern double          PTPeriod         = 10;
extern enPrices        PTPrice          = pr_hamedian; // Price to use 
extern double          SmoothLength     = 10.0;
extern double          SmoothPhase      = 0;
extern bool            SmoothDouble     = false;
extern bool            alertsOn         = false;
extern bool            alertsOnCurrent  = true;
extern bool            alertsMessage    = true;
extern bool            alertsSound      = false;
extern bool            alertsNotify     = false;
extern bool            alertsEmail      = false;
extern string          soundFile        = "alert2.wav";
extern bool            ShowArrows       = false;
extern string          arrowsIdentifier = "adxtrend Arrows";
extern double          arrowsUpperGap   = 1.0;
extern double          arrowsLowerGap   = 1.0;
extern color           arrowsUpColor    = LimeGreen;
extern color           arrowsDnColor    = Red;
extern color           arrowsUpCode     = 241;
extern color           arrowsDnCode     = 242;
extern bool            Interpolate      = true;

//
//
//
//
//

double ptlup[];
double ptldn[];
double pthup[];
double pthupd[];
double pthdn[];
double pthdnu[];
double trend[];
double slopeu[];
double sloped[];
string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(9);
   SetIndexBuffer(0,pthup);  SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,pthupd); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,pthdn);  SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(3,pthdnu); SetIndexStyle(3,DRAW_HISTOGRAM);
   SetIndexBuffer(4,ptlup);
   SetIndexBuffer(5,ptldn);
   SetIndexBuffer(6,trend);
   SetIndexBuffer(7,slopeu);
   SetIndexBuffer(8,sloped);

      //
      //
      //
      //
      //
      
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame==-99;
      TimeFrame         = MathMax(TimeFrame,_Period);
      
      //
      //
      //
      //
      //
   
   IndicatorShortName(timeFrameToString(TimeFrame)+" adx trend ("+DoubleToStr(PTPeriod,2)+")");
   return(0);
}
int deinit()
{
   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);
   }
   return(0);
}
 
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double  work[][5];
#define prc 0
#define pdm 1
#define mdm 2
#define pdi 3
#define mdi 4

//
//
//
//
//

int start()
{
   int counted_bars = IndicatorCounted();
   int i,r,limit;

   if(counted_bars<0) return(-1);
   if(counted_bars>0) counted_bars--;
           limit=MathMin(Bars-counted_bars,Bars-1);
           if (returnBars) { pthup[0] = limit+1; return(0); }

   //
   //
   //
   //
   //
   
   if (TimeFrame == Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      for(i = limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         work[r][prc] = getPrice(PTPrice,Open,Close,High,Low,i);
         
         //
         //
         //
         //
         //
            
         double diff = work[r][prc]-work[r-1][prc];
         double tpdm = 0;
         double tmdm = 0;
               if (diff>0)
                     tpdm =  diff;
               else  tmdm = -diff;          
         work[r][pdm] = ((PTPeriod-1.0)*work[r-1][pdm]+tpdm)/PTPeriod;
         work[r][mdm] = ((PTPeriod-1.0)*work[r-1][mdm]+tmdm)/PTPeriod;

         //
         //
         //
         //
         //

         double trueRange = work[r][pdm]+work[r][mdm];
         double tpdi      = 0;
         double tmdi      = 0;
               if (trueRange>0)
               {
                  tpdi = work[r][pdm]/trueRange;
                  tmdi = work[r][mdm]/trueRange;
               }            
         work[r][pdi] = ((PTPeriod-1.0)*work[r-1][pdi]+tpdi)/PTPeriod;
         work[r][mdi] = ((PTPeriod-1.0)*work[r-1][mdi]+tmdi)/PTPeriod;
   
         //
         //
         //
         //
         //
         
         ptlup[i]  = iDSmooth(work[r][pdi]-0.5,SmoothLength,SmoothPhase,SmoothDouble,i, 0);
         ptldn[i]  = iDSmooth(work[r][mdi]-0.5,SmoothLength,SmoothPhase,SmoothDouble,i,20);
         pthup[i]  = EMPTY_VALUE;
         pthupd[i] = EMPTY_VALUE;
         pthdn[i]  = EMPTY_VALUE;
         pthdnu[i] = EMPTY_VALUE;
         trend[i]  = trend[i+1];
         slopeu[i] = slopeu[i+1];
         sloped[i] = sloped[i+1];
            if (ptlup[i]>ptldn[i])   trend[i]  =  1;
            if (ptlup[i]<ptldn[i])   trend[i]  = -1;
            if (ptlup[i]>ptlup[i+1]) slopeu[i] =  1;
            if (ptlup[i]<ptlup[i+1]) slopeu[i] = -1;
            if (ptldn[i]>ptldn[i+1]) sloped[i] =  1;
            if (ptldn[i]<ptldn[i+1]) sloped[i] = -1;
            if (trend[i] == 1)
            {
               if (slopeu[i] ==  1) pthup[i]  = ptlup[i];
               if (slopeu[i] == -1) pthupd[i] = ptlup[i];
            }
            if (trend[i] == -1)
            {
               if (sloped[i] ==  1) pthdn[i]  = ptldn[i];
               if (sloped[i] == -1) pthdnu[i] = ptldn[i];
            }
            
            //
            //
            //
            //
            //
            
            if (ShowArrows)
            {
               ObjectDelete(arrowsIdentifier+":"+Time[i]);
               if (trend[i] != trend[i+1])
               {
                 if (trend[i] == 1)  drawArrow(i,arrowsUpColor,arrowsUpCode,false);
                 if (trend[i] ==-1)  drawArrow(i,arrowsDnColor,arrowsDnCode, true);
               }
            } 
      }
      
      //
      //
      //
      //
      //
      
      if (alertsOn)
      {
         if (alertsOnCurrent)
              int whichBar = 0;
         else     whichBar = 1;
         if (trend[whichBar] != trend[whichBar+1])
         {
            if (trend[whichBar] == 1)   doAlert(whichBar,"up");
            if (trend[whichBar] ==-1)   doAlert(whichBar,"down");
         }         
      }
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         pthup[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,0,y);
         pthupd[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,1,y);
         pthdn[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,2,y);
         pthdnu[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,3,y);
         ptlup[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,4,y);
         ptldn[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,5,y);
         trend[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,PTPeriod,PTPrice,SmoothLength,SmoothPhase,SmoothDouble,alertsOn,alertsOnCurrent,alertsMessage,alertsSound,alertsNotify,alertsEmail,soundFile,ShowArrows,arrowsIdentifier,arrowsUpperGap,arrowsLowerGap,arrowsUpColor,arrowsDnColor,arrowsUpCode,arrowsDnCode,6,y);

         //
         //
         //
         //
         //
      
            if (!Interpolate || y==iBarShift(NULL,TimeFrame,Time[i-1])) continue;

         //
         //
         //
         //
         //

         datetime time = iTime(NULL,TimeFrame,y);
            for(int n = 1; i+n < Bars && Time[i+n] >= time; n++) continue;	
            for(int k = 1; k < n; k++)
            {
               ptlup[i+k] = ptlup[i] + (ptlup[i+n]-ptlup[i])*k/n;
               ptldn[i+k] = ptldn[i] + (ptldn[i+n]-ptldn[i])*k/n;
                  if (pthup[i]  != EMPTY_VALUE) pthup[i+k]  = ptlup[i+k];
                  if (pthupd[i] != EMPTY_VALUE) pthupd[i+k] = ptlup[i+k];
                  if (pthdn[i]  != EMPTY_VALUE) pthdn[i+k]  = ptldn[i+k];
                  if (pthdnu[i] != EMPTY_VALUE) pthdnu[i+k] = ptldn[i+k];
            }
   }
   return(0);         
}


//
//
//
//
//

double wrk[][40];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iDSmooth(double price, double length, double phase, bool isDouble, int i, int s=0)
{
   if (isDouble)
         return (iSmooth(iSmooth(price,MathSqrt(length),phase,i,s),MathSqrt(length),phase,i,s+10));
   else  return (iSmooth(price,length,phase,i,s));
}

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (length <=1) return(price);
   if (ArrayRange(wrk,0) != Bars) ArrayResize(wrk,Bars);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrk[r][k+s]=price; for(; k<10; k++) wrk[r][k+s]=0; return(price); }

   //
   //
   //
   //
   //
   
      double len1   = MathMax(MathLog(MathSqrt(0.5*(length-1)))/MathLog(2.0)+2.0,0);
      double pow1   = MathMax(len1-2.0,0.5);
      double del1   = price - wrk[r-1][bsmax+s];
      double del2   = price - wrk[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrk[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrk[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrk[r][volty+s] = MathAbs(del2); 
         wrk[r][vsum+s] =	wrk[r-1][vsum+s] + (wrk[r][volty+s]-wrk[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrk[r][avolty+s] = wrk[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrk[r][vsum+s]-wrk[r-1][avolty+s]);
            if (wrk[r][avolty+s] > 0)
               double dVolty = wrk[r][volty+s]/wrk[r][avolty+s]; else dVolty = 0;   
	               if (dVolty > MathPow(len1,1.0/pow1)) dVolty = MathPow(len1,1.0/pow1);
                  if (dVolty < 1)                      dVolty = 1.0;

      //
      //
      //
      //
      //
	        
   	double pow2 = MathPow(dVolty, pow1);
      double len2 = MathSqrt(0.5*(length-1))*len1;
      double Kv   = MathPow(len2/(len2+1), MathSqrt(pow2));

         if (del1 > 0) wrk[r][bsmax+s] = price; else wrk[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrk[r][bsmin+s] = price; else wrk[r][bsmin+s] = price - Kv*del2;
	
   //
   //
   //
   //
   //
      
      double R     = MathMax(MathMin(phase,100),-100)/100.0 + 1.5;
      double beta  = 0.45*(length-1)/(0.45*(length-1)+2);
      double alpha = MathPow(beta,pow2);

         wrk[r][0+s] = price + alpha*(wrk[r-1][0+s]-price);
         wrk[r][1+s] = (price - wrk[r][0+s])*(1-beta) + beta*wrk[r-1][1+s];
         wrk[r][2+s] = (wrk[r][0+s] + R*wrk[r][1+s]);
         wrk[r][3+s] = (wrk[r][2+s] - wrk[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrk[r-1][3+s];
         wrk[r][4+s] = (wrk[r-1][4+s] + wrk[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrk[r][4+s]);
}

//+------------------------------------------------------------------
//|                                                                  
//+------------------------------------------------------------------
//
//
//
//
//
//

double workHa[][4];
double getPrice(int price, const double& open[], const double& close[], const double& high[], const double& low[], int i, int instanceNo=0)
{
  if (price>=pr_haclose && price<=pr_hatbiased)
   {
      if (ArrayRange(workHa,0)!= Bars) ArrayResize(workHa,Bars);
         int r = Bars-i-1;
         
         //
         //
         //
         //
         //
         
         double haOpen;
         if (r>0)
                haOpen  = (workHa[r-1][instanceNo+2] + workHa[r-1][instanceNo+3])/2.0;
         else   haOpen  = (open[i]+close[i])/2;
         double haClose = (open[i] + high[i] + low[i] + close[i]) / 4.0;
         double haHigh  = MathMax(high[i], MathMax(haOpen,haClose));
         double haLow   = MathMin(low[i] , MathMin(haOpen,haClose));

         if(haOpen  <haClose) { workHa[r][instanceNo+0] = haLow;  workHa[r][instanceNo+1] = haHigh; } 
         else                 { workHa[r][instanceNo+0] = haHigh; workHa[r][instanceNo+1] = haLow;  } 
                                workHa[r][instanceNo+2] = haOpen;
                                workHa[r][instanceNo+3] = haClose;
         //
         //
         //
         //
         //
         
         switch (price)
         {
            case pr_haclose:     return(haClose);
            case pr_haopen:      return(haOpen);
            case pr_hahigh:      return(haHigh);
            case pr_halow:       return(haLow);
            case pr_hamedian:    return((haHigh+haLow)/2.0);
            case pr_hamedianb:   return((haOpen+haClose)/2.0);
            case pr_hatypical:   return((haHigh+haLow+haClose)/3.0);
            case pr_haweighted:  return((haHigh+haLow+haClose+haClose)/4.0);
            case pr_haaverage:   return((haHigh+haLow+haClose+haOpen)/4.0);
            case pr_hatbiased:
               if (haClose>haOpen)
                     return((haHigh+haClose)/2.0);
               else  return((haLow+haClose)/2.0);        
         }
   }
   
   //
   //
   //
   //
   //
   
   switch (price)
   {
      case pr_close:     return(close[i]);
      case pr_open:      return(open[i]);
      case pr_high:      return(high[i]);
      case pr_low:       return(low[i]);
      case pr_median:    return((high[i]+low[i])/2.0);
      case pr_medianb:   return((open[i]+close[i])/2.0);
      case pr_typical:   return((high[i]+low[i]+close[i])/3.0);
      case pr_weighted:  return((high[i]+low[i]+close[i]+close[i])/4.0);
      case pr_average:   return((high[i]+low[i]+close[i]+open[i])/4.0);
      case pr_tbiased:   
               if (close[i]>open[i])
                     return((high[i]+close[i])/2.0);
               else  return((low[i]+close[i])/2.0);        
   }
   return(0);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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("");
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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()," ",timeFrameToString(_Period)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," adx trend smoothed ",doWhat);
             if (alertsMessage) Alert(message);
             if (alertsNotify)  SendNotification(message);
             if (alertsEmail)   SendMail(StringConcatenate(Symbol(), Period(), " adx trend smoothed "),message);
             if (alertsSound)   PlaySound("alert2.wav");
      }
}

//
//
//
//
//

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] + arrowsUpperGap * gap);
         else  ObjectSet(name,OBJPROP_PRICE1,Low[i]  - arrowsLowerGap * gap);
}