//+------------------------------------------------------------------+
//|                                                Donchian channels |
//|                                            Donchian channels.mq4 |
//|                                                           mladen |
//+------------------------------------------------------------------+
#property copyright "mladen"
#property link      "mladenfx@gmail.com"

#property indicator_separate_window
#property indicator_buffers 6
#property indicator_color1 clrYellow
#property indicator_color2 clrRed
#property indicator_color3 clrDodgerBlue
#property indicator_color4 clrSandyBrown
#property indicator_color5 clrSandyBrown
#property indicator_color6 clrSilver
#property indicator_style1 STYLE_DOT
#property indicator_style2 STYLE_DOT
#property indicator_width3 3
#property indicator_width4 3
#property indicator_width5 3
#property indicator_width6 2


//
//
//
//
//

extern ENUM_TIMEFRAMES TimeFrame      = PERIOD_CURRENT;
extern int    ChannelPeriod           = 21;
extern int    HighLowShift            = 1;
extern ENUM_APPLIED_PRICE PriceToUseForBreakOut = PRICE_MEDIAN;
extern bool   ShowMiddle              = false;
extern bool   ZeroBind                = true;
extern bool   Normalize               = false;
extern bool   alertsOn                = false;
extern bool   alertsOnCurrent         = false;
extern bool   alertsOnDirectionChange = false;
extern bool   alertsOnBreakOut        = false;
extern bool   alertsMessage           = false;
extern bool   alertsSound             = false;
extern bool   alertsEmail             = false;
extern bool   Interpolate             = true;

//
//
//
//
//

double buffer1[];
double buffer2[];
double buffer3[];
double buffer4[];
double buffer5[];
double price[];
double trend[];
double trendp[];

//
//
//
//
//

string indicatorFileName;
bool   returnBars;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

int init()
{
   IndicatorBuffers(8);
   SetIndexBuffer(0,buffer1);
   SetIndexBuffer(1,buffer2);
   SetIndexBuffer(2,buffer3);
   SetIndexBuffer(3,buffer4);
   SetIndexBuffer(4,buffer5);
   SetIndexBuffer(5,price);
   SetIndexBuffer(6,trend);
   SetIndexBuffer(7,trendp);
   
      //
      //
      //
      //
      //
                  
         indicatorFileName = WindowExpertName();
         returnBars        = TimeFrame==-99;
         TimeFrame         = MathMax(TimeFrame,_Period);
   return(0);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

double work[][3];
#define _dcUpper  0
#define _dcMiddle 1
#define _dcLower  2

//
//
//
//
//

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) { buffer1[0] = limit+1; return(0); }

   //
   //
   //
   //
   //

   if (TimeFrame==Period())
   {
      if (ArrayRange(work,0)!=Bars) ArrayResize(work,Bars);
      if (trend[limit]==-1) CleanPoint(limit,buffer4,buffer5);
      for (i=limit,r=Bars-i-1;i>=0;i--,r++)
      {
         double cprice = iMA(NULL,0,1,0,MODE_SMA,PriceToUseForBreakOut,i);            
            work[r][_dcUpper]  = High[Highest(NULL,0,MODE_HIGH,ChannelPeriod,i+HighLowShift)];
            work[r][_dcLower]  = Low[Lowest(NULL,0,MODE_LOW,ChannelPeriod,i+HighLowShift)];
            work[r][_dcMiddle] = (work[r][_dcUpper]+work[r][_dcLower])/2.0;

         //
         //
         //
         //
         //
         
            if (ZeroBind)
            {
               if (Normalize)
               {
                  buffer1[i] =  1;
                  buffer2[i] = -1;
                  double diff = (work[r][_dcUpper]-work[r][_dcMiddle]);
                     if (diff != 0)
                           price[i] = (cprice-work[r][_dcMiddle])/diff;
                     else  price[i] = 0;              
               }
               else
               {
                  buffer1[i] = work[r][_dcUpper]-work[r][_dcMiddle];
                  buffer2[i] = work[r][_dcLower]-work[r][_dcMiddle];
                  price[i]   = (cprice-work[r][_dcMiddle]);
               }
            }
            else
            {
               buffer1[i] = work[r][_dcUpper];
               buffer2[i] = work[r][_dcLower];
               price[i]   = cprice;
            }               
         
         //
         //
         //
         //
         //
         
         buffer4[i] = EMPTY_VALUE;
         buffer5[i] = EMPTY_VALUE;
         trendp[i]  = trendp[i+1];
         trend[i]   = trend[i+1];

            if (work[r][_dcUpper]>work[r-1][_dcUpper]) trend[i] =  1;
            if (work[r][_dcLower]<work[r-1][_dcLower]) trend[i] = -1;
            if (ShowMiddle)
            {
               if (ZeroBind) 
                     buffer3[i] = 0;
               else  buffer3[i] = (buffer1[i]+buffer2[i])/2;
               if (trend[i]==-1) PlotPoint(i,buffer4,buffer5,buffer3);
            }
            if (cprice>work[r][_dcUpper])                             trendp[i] =  1;
            if (cprice<work[r][_dcLower])                             trendp[i] = -1;
            if (cprice<work[r][_dcUpper] && cprice>work[r][_dcLower]) trendp[i] =  0;
      }
      manageAlerts();
      return(0);
   }
   
   //
   //
   //
   //
   //
   
   limit = MathMax(limit,MathMin(Bars,iCustom(NULL,TimeFrame,indicatorFileName,-99,0,0)*TimeFrame/Period()));
   if (trend[limit]== 1) CleanPoint(limit,buffer4,buffer5);
   for (i=limit;i>=0;i--)
   {
      int y = iBarShift(NULL,TimeFrame,Time[i]);
         buffer1[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,0,y);
         buffer2[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,1,y);
         price[i  ] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,5,y);
         trend[i]   = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,6,y);
         trendp[i]  = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,7,y);
         if (ShowMiddle)
         {
            buffer3[i] = iCustom(NULL,TimeFrame,indicatorFileName,PERIOD_CURRENT,ChannelPeriod,HighLowShift,PriceToUseForBreakOut,ShowMiddle,ZeroBind,Normalize,alertsOn,alertsOnCurrent,alertsOnDirectionChange,alertsOnBreakOut,alertsMessage,alertsSound,alertsEmail,2,y);
            buffer4[i] = EMPTY_VALUE;
            buffer5[i] = EMPTY_VALUE;
         }            

         //
         //
         //
         //
         //
      
         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++)
            {
               if (ShowMiddle) buffer3[i+k] = buffer3[i] + (buffer3[i+n]-buffer3[i])*k/n;
                               buffer1[i+k] = buffer1[i] + (buffer1[i+n]-buffer1[i])*k/n;
                               buffer2[i+k] = buffer2[i] + (buffer2[i+n]-buffer2[i])*k/n;
                               price[i+k]   = price[i]   + (price[i+n]  -price[i])*k/n;
            }               
   }
   if (ShowMiddle) for (i=limit;i>=0;i--) if (trend[i]==-1) PlotPoint(i,buffer4,buffer5,buffer3);
   return(0);
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

void manageAlerts()
{
   if (alertsOn)
   {
      if (alertsOnCurrent)
           int whichBar = 0;
      else     whichBar = 1;

      //
      //
      //
      //
      //
            
      static datetime alertTime1 = 0;
      static string   alertWhat1 = "";
      if (alertsOnDirectionChange && trend[whichBar] != trend[whichBar+1])
      {
         if (trend[whichBar] ==  1) doAlert(alertTime1,alertWhat1,whichBar,"dirrection changed to up");
         if (trend[whichBar] == -1) doAlert(alertTime1,alertWhat1,whichBar,"dirrection changed to down");
      }

      //
      //
      //
      //
      //
      
      static datetime alertTime2 = 0;
      static string   alertWhat2 = "";
      if (alertsOnBreakOut && trendp[whichBar] != trendp[whichBar+1])
      {
         if (trendp[whichBar] ==  1) doAlert(alertTime2,alertWhat2,whichBar,"price broke upper band");
         if (trendp[whichBar] == -1) doAlert(alertTime2,alertWhat2,whichBar,"price broke lower band");
      }
   }
}

//
//
//
//
//

void doAlert(datetime& previousTime, string& previousAlert, int forBar, string doWhat)
{
   string message;
   
   if (previousAlert != doWhat || previousTime != Time[forBar]) {
       previousAlert  = doWhat;
       previousTime   = Time[forBar];

       //
       //
       //
       //
       //

       message =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," ",timeFrameToString(_Period)+" Donchian channel ",doWhat);
          if (alertsMessage) Alert(message);
          if (alertsEmail)   SendMail(StringConcatenate(Symbol(),"Donchian channel"),message);
          if (alertsSound)   PlaySound("alert2.wav");
   }
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//

void CleanPoint(int i,double& first[],double& second[])
{
   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 (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;
      }
}

//+-------------------------------------------------------------------
//|                                                                  
//+-------------------------------------------------------------------
//
//
//
//
//

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("");
}