//+------------------------------------------------------------------+
//|                                                 Advanced ADX.mq4 |
//+------------------------------------------------------------------+
#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 4
#property indicator_color1  DeepSkyBlue
#property indicator_color2  PaleVioletRed
#property indicator_color3  DimGray
#property indicator_color4  DimGray
#property indicator_width1  2
#property indicator_width2  2
#property indicator_width3  2
#property indicator_width4  2

//
//
//
//
//

extern string TimeFrame           = "current time frame";
extern int    ADXPeriod           = 13;
extern double ADXLevel            = 25;
extern bool   Interpolate         = true;
extern bool   alertsOnLevelCross  = true;
extern bool   alertsOnTrendChange = true;
extern bool   alertsOn            = false;
extern bool   alertsOnCurrent     = true;
extern bool   alertsMessage       = true;
extern bool   alertsSound         = false;
extern bool   alertsEmail         = false;

//
//
//
//
//

double adxup[];
double adxdn[];
double adxno[];
double level[];
double trend[];
double state[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;
bool   calculateValue;
int    timeFrame;

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

int init()
{
   IndicatorBuffers(6);
      SetIndexBuffer(0, adxup); SetIndexStyle(0, DRAW_HISTOGRAM);
      SetIndexBuffer(1, adxdn); SetIndexStyle(1, DRAW_HISTOGRAM);
      SetIndexBuffer(2, adxno);
      SetIndexBuffer(3, level);
      SetIndexBuffer(4, trend);
      SetIndexBuffer(5, state);

      //
      //
      //
      //
      //
   
      indicatorFileName = WindowExpertName();
      returnBars        = TimeFrame=="returnBars";     if (returnBars)     return(0);
      calculateValue    = TimeFrame=="calculateValue"; if (calculateValue) return(0);
      timeFrame         = stringToTimeFrame(TimeFrame);

   //
   //
   //
   //
   //
   
   IndicatorShortName(timeFrameToString(timeFrame)+" Advanced ADX (" + ADXPeriod + ")");
   return(0);
}

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

int start()
{
   int i,limit,counted_bars = IndicatorCounted();
   
      if(counted_bars < 0) return(-1);
      if(counted_bars > 0) counted_bars--;
            limit = MathMin(Bars-counted_bars, Bars-1); 
            if (returnBars) { adxup[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (calculateValue || timeFrame==Period())
   {
      for(i = limit; i>=0; i--)
      {
         double ADX  = iADX(NULL, 0, ADXPeriod, PRICE_CLOSE, MODE_MAIN, i);
         double ADXP = iADX(NULL, 0, ADXPeriod, PRICE_CLOSE, MODE_PLUSDI, i);
         double ADXM = iADX(NULL, 0, ADXPeriod, PRICE_CLOSE, MODE_MINUSDI, i);
       
         //
         //
         //
         //
         //

         adxno[i] = ADX;
         level[i] = ADXLevel;         
         adxup[i] = EMPTY_VALUE;
         adxdn[i] = EMPTY_VALUE;
         trend[i] = trend[i+1];
         state[i] = state[i+1];
         
            if (ADXP > ADXM)    trend[i] =  1;
            if (ADXP < ADXM)    trend[i] = -1;
            if (trend[i] ==  1) adxup[i] = ADX;
            if (trend[i] == -1) adxdn[i] = ADX;
            if (alertsOnLevelCross)
            {
               if (ADX > ADXLevel) state[i] =  1;
               if (ADX < ADXLevel) state[i] = -1;
            }
      }
      manageAlerts();
      return(0);
   }      

   //
   //
   //
   //
   //

   limit = MathMax(limit,MathMin(Bars-1,iCustom(NULL,timeFrame,indicatorFileName,"returnBars",0,0)*timeFrame/Period()));
   for(i=limit; i>=0; i--)
   {
      int y = iBarShift(NULL,timeFrame,Time[i]);
         level[i] = ADXLevel;         
         adxno[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",ADXPeriod,ADXLevel,false,alertsOnLevelCross,alertsOnTrendChange,2,y);
         trend[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",ADXPeriod,ADXLevel,false,alertsOnLevelCross,alertsOnTrendChange,4,y);
         state[i] = iCustom(NULL,timeFrame,indicatorFileName,"calculateValue",ADXPeriod,ADXLevel,false,alertsOnLevelCross,alertsOnTrendChange,5,y);
         adxup[i] = EMPTY_VALUE;
         adxdn[i] = EMPTY_VALUE;
            if (trend[i] ==  1) adxup[i] = adxno[i];
            if (trend[i] == -1) adxdn[i] = adxno[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++)
               {
                  adxno[i+k] = adxno[i] + (adxno[i+n] - adxno[i])*k/n;
                  if (adxup[i+k] != EMPTY_VALUE) adxup[i+k]=adxno[i+k];
                  if (adxdn[i+k] != EMPTY_VALUE) adxdn[i+k]=adxno[i+k];
               }
   }
   
   //
   //
   //
   //
   //
   
   manageAlerts();
   return(0);

}

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

string   alertStates[2];
datetime alertTimes[2];

void manageAlerts()
{
   if (!calculateValue && alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1; whichBar = iBarShift(NULL,0,iTime(NULL,timeFrame,whichBar));
      
      //
      //
      //
      //
      //
      
      if (alertsOnLevelCross)
      if (state[whichBar] != state[whichBar+1])
      {
         if (state[whichBar] ==  1) doAlert(0,whichBar,"level "+DoubleToStr(ADXLevel,2)+" crossed up");
         if (state[whichBar] == -1) doAlert(0,whichBar,"level "+DoubleToStr(ADXLevel,2)+" crossed down");
      }
      if (alertsOnTrendChange)
      if (trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(1,whichBar,"trend direction changed to up");
         if (trend[whichBar] == -1) doAlert(1,whichBar,"trend direction changed to down");
      }
   }
}

//
//
//
//
//

void doAlert(int forAlert,int forBar, string doWhat)
{
   string message;
   
   if (alertStates[forAlert] != doWhat || alertTimes[forAlert] != Time[forBar]) {
       alertStates[forAlert]  = doWhat;
       alertTimes[forAlert]   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," ",timeFrameToString(timeFrame)," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," advanced ADX ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"advanced ADX"),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

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

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