//+------------------------------------------------------------------+
//|                                                    adx trend.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-station.com"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  DeepSkyBlue  
#property indicator_color2  Orange
#property indicator_color3  DeepSkyBlue  
#property indicator_color4  Orange
#property indicator_level1  0
#property indicator_levelcolor DimGray

//
//
//
//
//

extern string TimeFrame        = "Current time frame";
extern double PTPeriod         = 10;
extern int    PTPrice          = PRICE_MEDIAN;
extern double SmoothLength     = 1.0;
extern double SmoothPhase      = 0;
extern bool   Interpolate      = true;
extern bool   alertsOn         = false;
extern bool   alertsOnCurrent  = false;
extern bool   alertsMessage    = true;
extern bool   alertsSound      = false;
extern bool   alertsEmail      = false;
extern bool   ShowArrows       = true;
extern string arrowsIdentifier = "adxtrend arrows";
extern color  arrowsUpColor    = DeepSkyBlue;
extern color  arrowsDnColor    = Red;

//
//
//
//
//

double ptlup[];
double ptldn[];
double pthup[];
double pthdn[];
double trend[];

//
//
//
//
//

string indicatorFileName;
bool   calculateValue;
bool   returnBars;
int    timeFrame;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(5);
   SetIndexBuffer(0,pthup); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1,pthdn); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2,ptlup);
   SetIndexBuffer(3,ptldn);
   SetIndexBuffer(4,trend);

   //
   //
   //
   //
   //

      indicatorFileName = WindowExpertName();
      calculateValue    = (TimeFrame=="CalculateValue"); if (calculateValue) return(0);
      returnBars        = (TimeFrame=="returnBars");     if (returnBars)     return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);

   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" adx trend ("+DoubleToStr(PTPeriod,2)+")");
   return(0);
}
int deinit()
{
   if (!calculateValue && ShowArrows) deleteArrows();
   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 (calculateValue || timeFrame == Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      
      //
      //
      //
      //
      //
      
      for(i = limit, r=Bars-i-1; i >= 0; i--,r++)
      {
         work[r][prc] = iMA(NULL,0,1,0,MODE_SMA,PTPrice,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] = iSmooth(work[r][pdi]-0.5,SmoothLength,SmoothPhase,i, 0);
         ptldn[i] = iSmooth(work[r][mdi]-0.5,SmoothLength,SmoothPhase,i,10);
         pthup[i] = EMPTY_VALUE;
         pthdn[i] = EMPTY_VALUE;
         trend[i] = trend[i+1];
            if (ptlup[i]>ptldn[i]) { pthup[i] = ptlup[i]; trend[i] =  1; }
            if (ptlup[i]<ptldn[i]) { pthdn[i] = ptldn[i]; trend[i] = -1; }
            if (!calculateValue) manageArrow(i);
      }
      if (!calculateValue) 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]);
         pthup[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,SmoothLength,SmoothPhase,0,y);
         pthdn[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,SmoothLength,SmoothPhase,1,y);
         ptlup[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,SmoothLength,SmoothPhase,2,y);
         ptldn[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,SmoothLength,SmoothPhase,3,y);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,SmoothLength,SmoothPhase,4,y);
         manageArrow(i);

         //
         //
         //
         //
         //
      
            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 (pthdn[i] != EMPTY_VALUE) pthdn[i+k] = ptldn[i+k];
            }
   }
   manageAlerts();
   
   //
   //
   //
   //
   //
      
   return(0);
         
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (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,"up");
         if (trend[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 =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," ",timeFrameToString(timeFrame)+" ADX trend changed to ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"ADX trend "),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  = 3.0*iATR(NULL,0,20,i)/4.0;   
   
      //
      //
      //
      //
      //
      
      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);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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);
}

//+------------------------------------------------------------------
//|                                                                 
//+------------------------------------------------------------------
//
//
//
//
//

double wrkj[][20];

#define bsmax  5
#define bsmin  6
#define volty  7
#define vsum   8
#define avolty 9

//
//
//
//
//

double iSmooth(double price, double length, double phase, int i, int s=0)
{
   if (ArrayRange(wrkj,0) != Bars) ArrayResize(wrkj,Bars);
   if (length <=1) return(price);
   
   int r = Bars-i-1; 
      if (r==0) { for(int k=0; k<7; k++) wrkj[0][k+s]=price; for(; k<10; k++) wrkj[0][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 - wrkj[r-1][bsmax+s];
      double del2   = price - wrkj[r-1][bsmin+s];
      double div    = 1.0/(10.0+10.0*(MathMin(MathMax(length-10,0),100))/100);
      int    forBar = MathMin(r,10);
	
         wrkj[r][volty+s] = 0;
               if(MathAbs(del1) > MathAbs(del2)) wrkj[r][volty+s] = MathAbs(del1); 
               if(MathAbs(del1) < MathAbs(del2)) wrkj[r][volty+s] = MathAbs(del2); 
         wrkj[r][vsum+s] =	wrkj[r-1][vsum+s] + (wrkj[r][volty+s]-wrkj[r-forBar][volty+s])*div;
         
         //
         //
         //
         //
         //
   
         wrkj[r][avolty+s] = wrkj[r-1][avolty+s]+(2.0/(MathMax(4.0*length,30)+1.0))*(wrkj[r][vsum+s]-wrkj[r-1][avolty+s]);
            if (wrkj[r][avolty+s] > 0)
               double dVolty = wrkj[r][volty+s]/wrkj[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) wrkj[r][bsmax+s] = price; else wrkj[r][bsmax+s] = price - Kv*del1;
         if (del2 < 0) wrkj[r][bsmin+s] = price; else wrkj[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);

         wrkj[r][0+s] = price + alpha*(wrkj[r-1][0+s]-price);
         wrkj[r][1+s] = (price - wrkj[r][0+s])*(1-beta) + beta*wrkj[r-1][1+s];
         wrkj[r][2+s] = (wrkj[r][0+s] + R*wrkj[r][1+s]);
         wrkj[r][3+s] = (wrkj[r][2+s] - wrkj[r-1][4+s])*MathPow((1-alpha),2) + MathPow(alpha,2)*wrkj[r-1][3+s];
         wrkj[r][4+s] = (wrkj[r-1][4+s] + wrkj[r][3+s]); 

   //
   //
   //
   //
   //

   return(wrkj[r][4+s]);
}