//+------------------------------------------------------------------+
//|                                                    adx trend.mq4 |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "www.forex-tsd.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 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] = work[r][pdi]-0.5;
         ptldn[i] = work[r][mdi]-0.5;
         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,0,y);
         pthdn[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,1,y);
         ptlup[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,2,y);
         ptldn[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,3,y);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"CalculateValue",PTPeriod,PTPrice,4,y);
         manageArrow(i);

         //
         //
         //
         //
         //
      
            if (timeFrame <= Period() || y==iBarShift(NULL,timeFrame,Time[i-1])) continue;
            if (!Interpolate) 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);
}