#property copyright "www.forex-tsd.com"
#property link      "www.forex-tsd.com"


#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Orange
#property indicator_color2 DarkTurquoise
#property indicator_color3 Red
#property indicator_color4 Navy
#property indicator_width1 1
#property indicator_width2 1
#property indicator_width3 2
#property indicator_width4 2

//
//
//
//
//  

//#include <TimeGMT.mqh>   

//
//
//
//
//      


extern string UniqueID                 = "BoxBreakout ";
extern bool   Platform_5_Digits        = false;
extern string TC_start                 = "00:00";
extern bool   Same_Day                 = true;
extern string TC_end                   = "06:00";
extern string TC_projection_end        = "17:00";
extern double TC_Breakout_Offset       = 0;
extern bool   TC_Breakout_box_solid    = false;
extern int    Past_Days                = 10;
extern bool   TC_price                 = true;
extern color  TC_color                 = NavajoWhite;
extern int    TC_style                 = 0;
extern int    TC_width                 = 0;
extern bool   TC_solid                 = false;
extern color  TC_Prj_Obj_HI_clr        = RoyalBlue;
extern int    TC_Prj_Obj_HI_width      = 0;
extern int    TC_Prj_Obj_HI_style      = 2;
extern color  TC_Prj_Obj_LO_clr        = Crimson;
extern int    TC_Prj_Obj_LO_width      = 0;
extern int    TC_Prj_Obj_LO_style      = 2;
extern color  TC_price_clr             = NavajoWhite;
extern bool   BrokerHasSundayData      = false;

extern string HeikenAshiSetting        = "HeikenAshi Settings";
extern bool   ShowHeikenAshi           = true; 

extern string MMSetting                = "Murray Math Settings";
extern int    P                        = 64;
extern int    MMPeriod                 = 1440;
extern int    StepBack                 = 0;
extern int    ShowDays                 = 1;
extern bool   babylines                = false;
extern int    babyLinesStyle           = STYLE_SOLID;
extern bool   fiftyPercentLine         = false;
extern int    fiftyPercentLineStyle    = STYLE_DASH;
extern bool   MMalertsOn               = true;
extern double MMalertsTolerance        = 1.0;
extern bool   touchChanell             = false;
extern bool   MMalertsOnCurrent        = false;
extern bool   MMalertsMessage          = true;
extern bool   MMalertsSound            = true;
extern bool   MMalertsEmail            = false;
extern bool   MMalertsShowTouched      = true;
extern int    barsToShowCandles        = 1000;
extern color  BarUpColor               = Green; 
extern color  BarDownColor             = Red; 
extern color  BabyBarUpColor           = Lime; 
extern color  BabyBarDownColor         = Pink; 
extern color  WickColor                = Gray;
extern int    CandleWidth              = 4;

extern string comments                 = "Comments on true or false"; 
extern bool   CommentsOn               = true;   
extern string rangecomments            = "Range Comments";               
extern int    ShortRange               = 5;
extern int    InterRange               = 10;
extern int    LongRange                = 20;  

extern string stime                    = "Trend determination timeframes using PA";
extern int    timeframe1               = PERIOD_D1;
extern int    timeframe2               = PERIOD_H1;
extern int    timeframe3               = PERIOD_M15;
extern int    shift                    = 1; 

extern color  mml_clr_m_2_8            = White;       // [-2]/8
extern color  mml_clr_m_1_8            = White;       // [-1]/8
extern color  mml_clr_0_8              = Aqua;        //  [0]/8
extern color  mml_clr_1_8              = Yellow;      //  [1]/8
extern color  mml_clr_2_8              = Red;         //  [2]/8
extern color  mml_clr_3_8              = Green;       //  [3]/8
extern color  mml_clr_4_8              = Blue;        //  [4]/8
extern color  mml_clr_5_8              = Green;       //  [5]/8
extern color  mml_clr_6_8              = Red;         //  [6]/8
extern color  mml_clr_7_8              = Yellow;      //  [7]/8
extern color  mml_clr_8_8              = Aqua;        //  [8]/8
extern color  mml_clr_p_1_8            = White;       // [+1]/8
extern color  mml_clr_p_2_8            = White;       // [+2]/8
 
extern int    mml_wdth_m_2_8           = 2;           // [-2]/8
extern int    mml_wdth_m_1_8           = 1;           // [-1]/8
extern int    mml_wdth_0_8             = 1;           //  [0]/8
extern int    mml_wdth_1_8             = 1;           //  [1]/8
extern int    mml_wdth_2_8             = 1;           //  [2]/8
extern int    mml_wdth_3_8             = 1;           //  [3]/8
extern int    mml_wdth_4_8             = 1;           //  [4]/8
extern int    mml_wdth_5_8             = 1;           //  [5]/8
extern int    mml_wdth_6_8             = 1;           //  [6]/8
extern int    mml_wdth_7_8             = 1;           //  [7]/8
extern int    mml_wdth_8_8             = 1;           //  [8]/8
extern int    mml_wdth_p_1_8           = 1;           // [+1]/8
extern int    mml_wdth_p_2_8           = 2;           // [+2]/8

extern color  MarkColor                = Lime;
extern int    MarkNumber               = 217;

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//


double Buffer1[];
double Buffer2[];
double Buffer3[];
double Buffer4[];

//
//
//
//
//

int      dig, modifier;
double   pointvalue = 1;
double   dmml = 0,
         dvtl = 0,
         sum  = 0,
         v1 = 0,
         v2 = 0,
         mn = 0,
         mx = 0,
         x1 = 0,
         x2 = 0,
         x3 = 0,
         x4 = 0,
         x5 = 0,
         x6 = 0,
         y1 = 0,
         y2 = 0,
         y3 = 0,
         y4 = 0,
         y5 = 0,
         y6 = 0,
         octave = 0,
         fractal = 0,
         range   = 0,
         finalH  = 0,
         finalL  = 0,
         mml[13];

string   ln_txt[13],        
         buff_str = "";
        
int     
         bn_v1   = 0,
         bn_v2   = 0,
         OctLinesCnt = 13,
         mml_thk = 8,
         mml_clr[13],
         mml_wdth[13],
         mml_shft = 0,
         nTime = 0,
         CurPeriod = 0;
int      NewPeriod=0;
int      ShowPeriod;
double   values[49];
int      totalCandles;
string   windowID;
   
//
//
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+

int init()
{
   dig = MarketInfo(Symbol(), MODE_DIGITS);
   if (dig == 4 || dig == 2) pointvalue = Point;
   else if (dig == 5 || dig == 3) pointvalue = 10.0 * Point;
   
   
   modifier = 1;
   if(dig == 3 || dig == 5) modifier = 10;
   
   SetIndexBuffer(0, Buffer1); SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexBuffer(1, Buffer2); SetIndexStyle(1,DRAW_HISTOGRAM);
   SetIndexBuffer(2, Buffer3); SetIndexStyle(2,DRAW_HISTOGRAM);
   SetIndexBuffer(3, Buffer4); SetIndexStyle(3,DRAW_HISTOGRAM);
   
   windowID  = "Mano MM"+MMPeriod;
   if(MMPeriod>0) NewPeriod   = P*MathCeil(MMPeriod/Period());
   else           NewPeriod = P;
   
   ln_txt[0]  = "[-2/8]P";  // "extremely overshoot [-2/8]";// [-2/8]
   ln_txt[1]  = "[-1/8]P";  // "overshoot [-1/8]";// [-1/8]
   ln_txt[2]  = "[0/8]P";   // "Ultimate Support - extremely oversold [0/8]";// [0/8]
   ln_txt[3]  = "[1/8]P";   // "Weak, Stall and Reverse - [1/8]";// [1/8]
   ln_txt[4]  = "[2/8]P";   // "Pivot, Reverse - major [2/8]";// [2/8]
   ln_txt[5]  = "[3/8]P";   // "Bottom of Trading Range - [3/8], if 10-12 bars then 40% Time. BUY Premium Zone";//[3/8]
   ln_txt[6]  = "[4/8]P";   // "Major Support/Resistance Pivotal Point [4/8]- Best New BUY or SELL level";// [4/8]
   ln_txt[7]  = "[5/8]P";   // "Top of Trading Range - [5/8], if 10-12 bars then 40% Time. SELL Premium Zone";//[5/8]
   ln_txt[8]  = "[6/8]P";   // "Pivot, Reverse - major [6/8]";// [6/8]
   ln_txt[9]  = "[7/8]P";   // "Weak, Stall and Reverse - [7/8]";// [7/8]
   ln_txt[10] = "[8/8]P";   // "Ultimate Resistance - extremely overbought [8/8]";// [8/8]
   ln_txt[11] = "[+1/8]P";  // "overshoot [+1/8]";// [+1/8]
   ln_txt[12] = "[+2/8]P";  // "extremely overshoot [+2/8]";// [+2/8]

   mml_thk  = 3;
   mml_clr[0]  = mml_clr_m_2_8;   mml_wdth[0] = mml_wdth_m_2_8; // [-2]/8
   mml_clr[1]  = mml_clr_m_1_8;   mml_wdth[1] = mml_wdth_m_1_8; // [-1]/8
   mml_clr[2]  = mml_clr_0_8;     mml_wdth[2] = mml_wdth_0_8;   //  [0]/8
   mml_clr[3]  = mml_clr_1_8;     mml_wdth[3] = mml_wdth_1_8;   //  [1]/8
   mml_clr[4]  = mml_clr_2_8;     mml_wdth[4] = mml_wdth_2_8;   //  [2]/8
   mml_clr[5]  = mml_clr_3_8;     mml_wdth[5] = mml_wdth_3_8;   //  [3]/8
   mml_clr[6]  = mml_clr_4_8;     mml_wdth[6] = mml_wdth_4_8;   //  [4]/8
   mml_clr[7]  = mml_clr_5_8;     mml_wdth[7] = mml_wdth_5_8;   //  [5]/8
   mml_clr[8]  = mml_clr_6_8;     mml_wdth[8] = mml_wdth_6_8;   //  [6]/8
   mml_clr[9]  = mml_clr_7_8;     mml_wdth[9] = mml_wdth_7_8;   //  [7]/8
   mml_clr[10] = mml_clr_8_8;     mml_wdth[10]= mml_wdth_8_8;   //  [8]/8
   mml_clr[11] = mml_clr_p_1_8;   mml_wdth[11]= mml_wdth_p_1_8; // [+1]/8
   mml_clr[12] = mml_clr_p_2_8;   mml_wdth[12]= mml_wdth_p_2_8; // [+2]/8
   
   switch(Period())
   {
      case PERIOD_MN1:
      case PERIOD_W1:  ShowPeriod = PERIOD_MN1; break;
      case PERIOD_D1:  ShowPeriod = PERIOD_W1;  break;
      default:         ShowPeriod = PERIOD_D1;
   }
   
   //
   //
   //
   //
   //
   
   return(0);
}

//
//
//
//
//

int deinit()
{
   for(int i=0;i<OctLinesCnt;i++) ObjectDelete("mml_txt"+i);
   for(    i=0;i<50;i++)          ObjectDelete("MMline"+i);
                              ObjectDelete("LR_LatestCulcBar");
                              
   Comment("");
   
   string lookFor       = UniqueID;
   int    lookForLength = StringLen(lookFor);   
   for(i = ObjectsTotal() - 1; i >= 0; i--)
   {
      string name = ObjectName(i);
         if(StringSubstr(name, 0, lookForLength) == lookFor) ObjectDelete(name);
   }         
   return(0);
}

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
//
//

int start()
{     
      if (!IsDllsAllowed()) 
      {
      Alert("DLLs are disabled.  To enable check the checkbox in the Common Tab of indicator");
      return(0);
      }
      
      int counted_bars=IndicatorCounted();
      int limit;

      if(counted_bars<0) return(-1);
      if(counted_bars>0) counted_bars--;
         limit = MathMin(Bars-counted_bars,Bars-1);
         
      //
      //
      //
      //
      //
      
      for(int pos=limit; pos>=0; pos--)
      {
         if (ShowHeikenAshi)
         {           
         
          double haClose = (Open[pos]+High[pos]+Low[pos]+Close[pos])/4;
          double haOpen  = (Buffer3[pos+1]+Buffer4[pos+1])/2;
          double haHigh  = MathMax(High[pos], MathMax(haOpen,haClose));
          double haLow   = MathMin(Low[pos],  MathMin(haOpen,haClose));

          if (haOpen<haClose) 
          { 
            Buffer1[pos] = haLow;  
            Buffer2[pos] = haHigh; 
          } 
          else              
          { 
            Buffer1[pos] = haHigh; 
            Buffer2[pos] = haLow;  
          } 
            Buffer3[pos] = haOpen;
            Buffer4[pos] = haClose;     
          }
       
      }
 
      //
      //
      //
      //
      //
      
      if((nTime != Time[0]) || (CurPeriod != Period()))
      {
      ArrayInitialize(values,0.00);
      bn_v1 = iLowest( NULL,0,MODE_LOW, NewPeriod+StepBack,StepBack);
      bn_v2 = iHighest(NULL,0,MODE_HIGH,NewPeriod+StepBack,StepBack);
      v1    = Low[bn_v1];
      v2    = High[bn_v2];
      while (true)
      {
         if( v2 > 25000 )    { fractal=100000;    break; }
         if( v2 > 2500 )     { fractal=10000;     break; }
         if( v2 > 250 )      { fractal=1000;      break; }
         if( v2 > 25 )       { fractal=100;       break; }
         if( v2 > 6.25 )     { fractal=12.5;      break; }
         if( v2 > 3.125 )    { fractal=6.25;      break; }
         if( v2 > 1.5625 )   { fractal=3.125;     break; }
         if( v2 > 0.390625 ) { fractal=1.5625;    break; }
         if( v2 > 0 )        { fractal=0.1953125; break; }
                                                  break;
      }                                            
      
      range  = (v2-v1);
      sum    = MathFloor(MathLog(fractal/range)/MathLog(2));
      octave = fractal*(MathPow(0.5,sum));
      mn     = MathFloor(v1/octave)*octave;

      if( (mn+octave)>v2 )
            mx=mn+octave; 
      else  mx=mn+(2*octave);


       
            if( (v1>=(3*(mx-mn)/16+mn)) && (v2<=(9*(mx-mn)/16+mn)) )
                 x2=mn+(mx-mn)/2; 
            else x2=0;
      
            if( (v1>=(mn-(mx-mn)/8))&& (v2<=(5*(mx-mn)/8+mn)) && (x2==0) )
                 x1=mn+(mx-mn)/2; 
            else x1=0;
      
            if( (v1>=(mn+7*(mx-mn)/16))&& (v2<=(13*(mx-mn)/16+mn)) )
                 x4=mn+3*(mx-mn)/4; 
            else x4=0;
     
            if( (v1>=(mn+3*(mx-mn)/8))&& (v2<=(9*(mx-mn)/8+mn))&& (x4==0) )
                 x5=mx; 
            else x5=0;
     
            if( (v1>=(mn+(mx-mn)/8))&& (v2<=(7*(mx-mn)/8+mn))&& (x1==0) && (x2==0) && (x4==0) && (x5==0) )
                 x3=mn+3*(mx-mn)/4; 
            else x3=0;
     
            if( (x1+x2+x3+x4+x5) ==0 )
                 x6=mx; 
            else x6=0;

      //
      //
      //
      //
      //
      
      finalH = x1+x2+x3+x4+x5+x6;

         if( x1>0 )
              y1=mn; 
         else y1=0;
     
         if( x2>0 )
              y2=mn+(mx-mn)/4; 
         else y2=0;
     
         if( x3>0 )
              y3=mn+(mx-mn)/4; 
         else y3=0;
      
         if( x4>0 )
              y4=mn+(mx-mn)/2; 
         else y4=0;
      
         if( x5>0 )
              y5=mn+(mx-mn)/2; 
         else y5=0;
      
         if( (finalH>0) && ((y1+y2+y3+y4+y5)==0) )
              y6=mn; 
         else y6=0;

      //
      //
      //
      //
      //
    
      finalL = y1+y2+y3+y4+y5+y6;

      ArrayInitialize(mml,0); 
      dmml   = (finalH-finalL)/8;
      mml[0] = (finalL-dmml*2); 
      for(int i=1; i<OctLinesCnt; i++)
      {
        mml[i] = mml[i-1] + dmml;
      }
        
      //
      //
      //
      //
      //
           
      for( i=0; i<OctLinesCnt; i++ )
      {
         CreateBaby(i,mml[i],STYLE_SOLID,mml_clr[i],mml_wdth[i]);
         buff_str = "mml_txt"+i;
            if(ObjectFind(buff_str) == -1)
               ObjectCreate(buff_str, OBJ_TEXT, 0, Time[mml_shft], mml_shft);
               ObjectSetText(buff_str, "                              "+ln_txt[i]+" @ "+DoubleToStr(mml[i],Digits), 8, "Arial", mml_clr[i]);
               ObjectMove(buff_str, 0, Time[mml_shft],  mml[i]);
      }

      //Babylines
      double b222,b224,b226;
      double b112,b114,b116;
      double b02,b04,b06;
      double b12,b14,b16;
      double b22,b24,b26;
      double b32,b34,b36;
      double b42,b44,b46;
      double b52,b54,b56;
      double b62,b64,b66;
      double b72,b74,b76;
      double b82,b84,b86;
      double b92,b94,b96;

      double x0 = mml[0];
      double x1 = mml[1];
      double x2 = mml[2];
      double x3 = mml[3];
      double x4 = mml[4];
      double x5 = mml[5];
      double x6 = mml[6];
      double x7 = mml[7];
      double x8 = mml[8];
      double x9 = mml[9];
      double x10 = mml[10];
      double x11 = mml[11];
      double x12 = mml[12];

      b222 = ((x1-x0)/4)+x0;
      b224 = ((x1-x0)/2)+x0;
      b226 = ((x1-x0)/4)*3+x0;

      b112 = ((x2-x1)/4)+x1;
      b114 = ((x2-x1)/2)+x1;
      b116 = ((x2-x1)/4)*3+x1;

      b02 = ((x3-x2)/4)+x2;
      b04 = ((x3-x2)/2)+x2;
      b06 = ((x3-x2)/4)*3+x2;

      b12 = ((x4-x3)/4)+x3;
      b14 = ((x4-x3)/2)+x3;
      b16 = ((x4-x3)/4)*3+x3;

      b22 = ((x5-x4)/4)+x4;
      b24 = ((x5-x4)/2)+x4;
      b26 = ((x5-x4)/4)*3+x4;

      b32 = ((x6-x5)/4)+x5;
      b34 = ((x6-x5)/2)+x5;
      b36 = ((x6-x5)/4)*3+x5;

      b42 = ((x7-x6)/4)+x6;
      b44 = ((x7-x6)/2)+x6;
      b46 = ((x7-x6)/4)*3+x6;

      b52 = ((x8-x7)/4)+x7;
      b54 = ((x8-x7)/2)+x7;
      b56 = ((x8-x7)/4)*3+x7;

      b62 = ((x9-x8)/4)+x8;
      b64 = ((x9-x8)/2)+x8;
      b66 = ((x9-x8)/4)*3+x8;

      b72 = ((x10-x9)/4)+x9;
      b74 = ((x10-x9)/2)+x9;
      b76 = ((x10-x9)/4)*3+x9;

      b82 = ((x11-x10)/4)+x10;
      b84 = ((x11-x10)/2)+x10;
      b86 = ((x11-x10)/4)*3+x10;

      b92 = ((x12-x11)/4)+x11;
      b94 = ((x12-x11)/2)+x11;
      b96 = ((x12-x11)/4)*3+x11;
      //---------------------------------------------------------
      if (babylines)
      {
      CreateBaby(14,b222,babyLinesStyle);
      CreateBaby(15,b226,babyLinesStyle);
      CreateBaby(16,b112,babyLinesStyle);
      CreateBaby(17,b116,babyLinesStyle);
      CreateBaby(18,b02,babyLinesStyle);
      CreateBaby(19,b06,babyLinesStyle);
      CreateBaby(20,b12,babyLinesStyle);
      CreateBaby(21,b16,babyLinesStyle);
      CreateBaby(22,b22,babyLinesStyle);
      CreateBaby(23,b26,babyLinesStyle);
      CreateBaby(24,b32,babyLinesStyle);
      CreateBaby(25,b36,babyLinesStyle);
      CreateBaby(26,b42,babyLinesStyle);
      CreateBaby(27,b46,babyLinesStyle);
      CreateBaby(28,b52,babyLinesStyle);
      CreateBaby(29,b56,babyLinesStyle);
      CreateBaby(30,b62,babyLinesStyle);
      CreateBaby(31,b66,babyLinesStyle);
      CreateBaby(32,b72,babyLinesStyle);
      CreateBaby(33,b76,babyLinesStyle);
      CreateBaby(34,b82,babyLinesStyle);
      CreateBaby(35,b86,babyLinesStyle);
      CreateBaby(36,b92,babyLinesStyle);
      CreateBaby(37,b96,babyLinesStyle);
      }
      if (fiftyPercentLine)
      {
      CreateBaby(38,b224,fiftyPercentLineStyle);
      CreateBaby(39,b114,fiftyPercentLineStyle);
      CreateBaby(40,b04 ,fiftyPercentLineStyle);
      CreateBaby(41,b14 ,fiftyPercentLineStyle);
      CreateBaby(42,b24 ,fiftyPercentLineStyle);
      CreateBaby(43,b34 ,fiftyPercentLineStyle);
      CreateBaby(44,b44 ,fiftyPercentLineStyle);
      CreateBaby(45,b54 ,fiftyPercentLineStyle);
      CreateBaby(46,b64 ,fiftyPercentLineStyle);
      CreateBaby(47,b74 ,fiftyPercentLineStyle);
      CreateBaby(48,b84 ,fiftyPercentLineStyle);
      CreateBaby(49,b94 ,fiftyPercentLineStyle);
      }

      nTime    = Time[0];
      CurPeriod= Period();
   
      string tbuff_str = "LR_LatestCulcBar";
      if(ObjectFind(tbuff_str) == -1) {
         ObjectCreate(tbuff_str, OBJ_ARROW,0, Time[StepBack], Low[StepBack]-2 * pointvalue);
         ObjectSet(tbuff_str, OBJPROP_ARROWCODE, MarkNumber);
         ObjectSet(tbuff_str, OBJPROP_COLOR, MarkColor);
      }
      else 
      {
      ObjectMove(tbuff_str, 0, Time[StepBack], Low[StepBack]-2 * pointvalue);
      }
      
      //
      //
      //
      //
      //
      
      datetime TradeDate = TimeCurrent();
      for (int d = 0; d < Past_Days; d++)
      {       
         DrawTC(TradeDate, UniqueID + "_TC00 " + TimeToStr(TradeDate,TIME_DATE), TC_start, TC_end, TC_projection_end, 0, Same_Day);
         DrawTC(TradeDate, UniqueID + "_TC01 " + TimeToStr(TradeDate,TIME_DATE), TC_start, TC_end, TC_projection_end, 1, Same_Day);
         DrawTC(TradeDate, UniqueID + "_TC02 " + TimeToStr(TradeDate,TIME_DATE), TC_start, TC_end, TC_projection_end, 2, Same_Day);
         
         TradeDate = decrementTradeDateb(TradeDate);
         while (TimeDayOfWeek(TradeDate) > 5 || TimeDayOfWeek(TradeDate) < 1 ) TradeDate = decrementTradeDateb(TradeDate);       
      }
      }
      
      if (MMalertsOn)          CheckTouches();
      if (MMalertsShowTouched) ShowCandles();
      if (CommentsOn)          ShowComments();
   return(0);
}
   
//+-------------------------------------------------------------------------------------------+
//| DrawTC sub-routine to draw custom Time Channels                                           |
//+-------------------------------------------------------------------------------------------+
//
//

void DrawTC(datetime TradeDate, string TCObj, string TCstart, string TCend, string TCprjend, int ID, bool tSame_Day)
{
                
                datetime TimeBegin    = StrToTime(TimeToStr(TradeDate, TIME_DATE) + " " + TCstart);
   if(tSame_Day)         TimeBegin    = StrToTime(TimeToStr(TradeDate, TIME_DATE) + " " + TCstart)  + 86400;
                datetime TimeEnd      = StrToTime(TimeToStr(TradeDate, TIME_DATE) + " " + TCend)    + 86400;
                datetime TCobjprjend  = StrToTime(TimeToStr(TradeDate, TIME_DATE) + " " + TCprjend) + 86400;

   //
   //
   //
   //
   //
      
   if(TimeDayOfWeek(TradeDate) == 5)
   {
      if (BrokerHasSundayData)
            int timeDiff = 2*PERIOD_D1*60;
      else      timeDiff = 3*PERIOD_D1*60;
      TimeBegin   = TimeBegin   + timeDiff;
      TimeEnd     = TimeEnd     + timeDiff;
      TCobjprjend = TCobjprjend + timeDiff;
   }
   
   
   int BarBegin     = iBarShift(NULL, 0, TimeBegin) + 1;
   int BarEnd       = iBarShift(NULL, 0, TimeEnd)   + 1;  
   
   double PriceHigh    = High[Highest(NULL, 0, MODE_HIGH, (BarBegin - BarEnd), BarEnd)];
   double PriceLow     = Low [Lowest (NULL, 0, MODE_LOW , (BarBegin - BarEnd), BarEnd)];
   double bo           = TC_Breakout_Offset * (Point * modifier);
   double range1       = PriceHigh - ((PriceHigh - PriceLow) / 2);
   double range2       = (PriceHigh - PriceLow) / (Point * modifier);
   string TCObj_Hprice = UniqueID + "_TC10 " + TimeToStr(TradeDate,TIME_DATE);
   string TCObj_Lprice = UniqueID + "_TC11 " + TimeToStr(TradeDate,TIME_DATE);
   string TCObj_range  = UniqueID + "_TC12 " + TimeToStr(TradeDate,TIME_DATE);
   string Hprice       = DoubleToStr(PriceHigh, dig);
   string Lprice       = DoubleToStr(PriceLow,  dig);
   int    round        = 0;
   
   if(Platform_5_Digits) round = 1;
   string range3       = DoubleToStr(range2,  round);
   
   //
   //
   //
   //
   //
 
   
 
   
   if(ID == 0)
   {  
   ObjectCreate(TCObj, OBJ_RECTANGLE,  0, 0, 0, 0, 0);
      ObjectSet(TCObj, OBJPROP_TIME1,  TimeBegin);
      ObjectSet(TCObj, OBJPROP_TIME2,  TimeEnd);
      ObjectSet(TCObj, OBJPROP_PRICE1, PriceHigh);  
      ObjectSet(TCObj, OBJPROP_PRICE2, PriceLow);
      ObjectSet(TCObj, OBJPROP_STYLE,  TC_style);
      ObjectSet(TCObj, OBJPROP_COLOR,  TC_color);
      ObjectSet(TCObj, OBJPROP_BACK,   TC_solid);
      ObjectSet(TCObj, OBJPROP_WIDTH,  TC_width);
   }
   
   if(TC_Breakout_Offset <= 0)
   {
      if(ID == 1)
      {
         ObjectCreate(TCObj, OBJ_TREND,      0, 0, 0, 0);
            ObjectSet(TCObj, OBJPROP_TIME1,  TimeEnd);
            ObjectSet(TCObj, OBJPROP_TIME2,  TCobjprjend);
            ObjectSet(TCObj, OBJPROP_PRICE1, PriceHigh);  
            ObjectSet(TCObj, OBJPROP_PRICE2, PriceHigh);
            ObjectSet(TCObj, OBJPROP_STYLE,  TC_Prj_Obj_HI_style);
            ObjectSet(TCObj, OBJPROP_COLOR,  TC_Prj_Obj_HI_clr);      
            ObjectSet(TCObj, OBJPROP_WIDTH,  TC_Prj_Obj_HI_width);
            ObjectSet(TCObj, OBJPROP_BACK,   false);
            ObjectSet(TCObj, OBJPROP_RAY,    false);
      }

      if(ID == 2)
      {
         ObjectCreate(TCObj, OBJ_TREND,      0, 0, 0, 0);
            ObjectSet(TCObj, OBJPROP_TIME1,  TimeEnd);
            ObjectSet(TCObj, OBJPROP_TIME2,  TCobjprjend);
            ObjectSet(TCObj, OBJPROP_PRICE1, PriceLow);  
            ObjectSet(TCObj, OBJPROP_PRICE2, PriceLow);
            ObjectSet(TCObj, OBJPROP_STYLE,  TC_Prj_Obj_LO_style);
            ObjectSet(TCObj, OBJPROP_COLOR,  TC_Prj_Obj_LO_clr);      
            ObjectSet(TCObj, OBJPROP_WIDTH,  TC_Prj_Obj_LO_width);
            ObjectSet(TCObj, OBJPROP_BACK,   false);
            ObjectSet(TCObj, OBJPROP_RAY,    false);
      }
   
      if(TC_price)
      {
         
         ObjectCreate  (TCObj_Hprice, OBJ_TEXT, 0, TimeBegin - 3600, PriceHigh);
         ObjectSet     (TCObj_Hprice, OBJPROP_BACK, false);
         ObjectSetText (TCObj_Hprice, Hprice, 9, "Verdana Italic", TC_price_clr);
         ObjectMove    (TCObj_Hprice, 0, TimeBegin - 3600, PriceHigh);
         
         ObjectCreate  (TCObj_Lprice, OBJ_TEXT, 0, TimeBegin - 3600, PriceLow);
         ObjectSet     (TCObj_Lprice, OBJPROP_BACK, false);
         ObjectSetText (TCObj_Lprice, Lprice, 9, "Verdana Italic", TC_price_clr);
         ObjectMove    (TCObj_Lprice, 0, TimeBegin - 3600, PriceLow);
         
         ObjectCreate  (TCObj_range, OBJ_TEXT, 0, TimeBegin - 3600, range1);
         ObjectSet     (TCObj_range, OBJPROP_BACK, false);
         ObjectSetText (TCObj_range, range3, 11, "Verdana Bold Italic", TC_price_clr);
         ObjectMove    (TCObj_range, 0, TimeBegin - 3600, range1);
      }
   }
   
   else
   {
      Hprice = DoubleToStr(PriceHigh + bo, dig);
      Lprice = DoubleToStr(PriceLow  - bo, dig);
      if(ID == 1)
      {
         ObjectCreate(TCObj, OBJ_RECTANGLE,  0, 0, 0, 0, 0);
            ObjectSet(TCObj, OBJPROP_TIME1,  TimeEnd);
            ObjectSet(TCObj, OBJPROP_TIME2,  TCobjprjend);
            ObjectSet(TCObj, OBJPROP_PRICE1, PriceHigh);  
            ObjectSet(TCObj, OBJPROP_PRICE2, PriceHigh + bo);
            ObjectSet(TCObj, OBJPROP_COLOR,  TC_Prj_Obj_HI_clr);
            ObjectSet(TCObj, OBJPROP_BACK,   TC_Breakout_box_solid);
      }

      if(ID == 2)
      {
         ObjectCreate(TCObj, OBJ_RECTANGLE,  0, 0, 0, 0, 0);
            ObjectSet(TCObj, OBJPROP_TIME1,  TimeEnd);
            ObjectSet(TCObj, OBJPROP_TIME2,  TCobjprjend);
            ObjectSet(TCObj, OBJPROP_PRICE1, PriceLow);  
            ObjectSet(TCObj, OBJPROP_PRICE2, PriceLow - bo);
            ObjectSet(TCObj, OBJPROP_COLOR,  TC_Prj_Obj_LO_clr);
            ObjectSet(TCObj, OBJPROP_BACK,   TC_Breakout_box_solid);
      }
   
      if(TC_price)
      {
         
         ObjectCreate  (TCObj_Hprice, OBJ_TEXT, 0, TimeEnd - 3600, PriceHigh + 1.5 * bo);
         ObjectSet     (TCObj_Hprice, OBJPROP_BACK, false);
         ObjectSetText (TCObj_Hprice, Hprice, 9, "Verdana Italic", TC_Prj_Obj_HI_clr);
         ObjectMove    (TCObj_Hprice, 0, TimeEnd - 3600, PriceHigh + 1.5 * bo);
         
         ObjectCreate  (TCObj_Lprice, OBJ_TEXT, 0, TimeEnd - 3600, PriceLow - bo);
         ObjectSet     (TCObj_Lprice, OBJPROP_BACK, false);
         ObjectSetText (TCObj_Lprice, Lprice, 9, "Verdana Italic", TC_Prj_Obj_LO_clr);
         ObjectMove    (TCObj_Lprice, 0, TimeEnd - 3600, PriceLow - bo);
         
         ObjectCreate  (TCObj_range, OBJ_TEXT, 0, TimeBegin - 3600, range1);
         ObjectSet     (TCObj_range, OBJPROP_BACK, false);
         ObjectSetText (TCObj_range, range3, 11, "Verdana Bold Italic", TC_price_clr);
         ObjectMove    (TCObj_range, 0, TimeBegin - 3600, range1);
      }
   }
}


datetime decrementTradeDateb(datetime TimeDate)
{
   return(TimeDate-PERIOD_D1*60);
}

//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
//
//
//
//
//
  
void CreateBaby(string ID, double value,int style=STYLE_SOLID,color clr=DarkSlateGray,int width=0)
{
   string name = "MMline"+ID;

   if (ObjectFind(name) == -1)
      ObjectCreate(name,OBJ_TREND,0,0,0,0,0);
         ObjectSet(name,OBJPROP_COLOR,clr);
         ObjectSet(name,OBJPROP_STYLE,style);
         ObjectSet(name,OBJPROP_WIDTH,width);
         ObjectSet(name,OBJPROP_RAY,false);
         ObjectMove(name,0,Time[0],value);
         ObjectMove(name,1,iTime(NULL,ShowPeriod,ShowDays),value);

   //
   //
   //
   //
   //

   values[StrToInteger(ID)] = value;         
}

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
//
//
//
//
//

void CheckTouches()
{
   for (int i=0;i<50;i++) { if (CheckIfTouched(values[i])!=0) break; }         
}
int CheckIfTouched(double compareTo,bool checking=false,int forBar=0)
{
   int    answer = 0;
   double diff   = NormalizeDouble(MMalertsTolerance*pointvalue,Digits);
   double correction;
   double highDiff;
   double lowDiff;
   
   if (touchChanell)
      {
         correction = NormalizeDouble(MMalertsTolerance*pointvalue,  Digits);
         diff       = NormalizeDouble(MMalertsTolerance*pointvalue*2,Digits);
      }         
   else  correction = 0.00;    
   //
   //
   //
   //
   //
      
   int add;
      if (MMalertsOnCurrent) add = 0;
      else                 add = 1;      
      double value = NormalizeDouble(compareTo,Digits);
          highDiff = NormalizeDouble((value+correction)-High[add+forBar],Digits);
          lowDiff  = NormalizeDouble(Low[add+forBar]-(value-correction),Digits);
          
   //
   //
   //
   //
   //
   
   if (checking)
      {
         if ((highDiff >= 0) && (highDiff <= diff)) answer = -1;
         if ((lowDiff  >= 0) && (lowDiff  <= diff)) answer =  1;
      }
   else
      {
         while (true)
         {
            if ((highDiff >= 0) && (highDiff <= diff)) { answer = -1; doMMAlert("MM line touched from down"); break; }
            if ((lowDiff  >= 0) && (lowDiff  <= diff)) { answer =  1; doMMAlert("MM line touched from up");   break; }
                                                                                               break;
         }            
      }
   return(answer);
}

//
//
//
//
//

void doMMAlert(string MMdoWhat)
{
   static string   MMpreviousAlert="nothing";
   static datetime MMpreviousTime;
   string MMmessage;

      if (MMpreviousAlert != MMdoWhat || MMpreviousTime != Time[0]) {
          MMpreviousAlert  = MMdoWhat;
          MMpreviousTime   = Time[0];

          //
          //
          //
          //
          //

          MMmessage =  StringConcatenate(Symbol()," at ",TimeToStr(TimeLocal(),TIME_SECONDS)," Murrey math ",MMdoWhat);
             if (MMalertsMessage) Alert(MMmessage);
             if (MMalertsEmail)   SendMail(StringConcatenate(Symbol()," Murrey math line crossing"),MMmessage);
             if (MMalertsSound)   PlaySound("alert2.wav");
      }
}

//+------------------------------------------------------------------+
//|
//+------------------------------------------------------------------+
//
//
//
//
//

void deleteCandles()
{
   while(totalCandles>0) { ObjectDelete(StringConcatenate(windowID,"c-",totalCandles)); totalCandles -= 1; }
}

//
//
//
//
//

void ShowCandles()
{
   deleteCandles();
   for (int i = 0;i<barsToShowCandles;i++)
   {
      if (iTime(NULL,ShowPeriod,ShowDays)<Time[i])
         for (int k=0; k<50; k++) if(CheckSingle(values[k],i,k)) break;
   }
      
}

//
//
//
//
//

bool CheckSingle(double array,int tshift,int k)
{
   int result = CheckIfTouched(array,true,tshift);
   if (result != 0)
      {
         if (MMalertsOnCurrent) DrawCandle(tshift  ,result,k);
         else                 DrawCandle(tshift+1,result,k);
         return(true);
      }
   else
      {
         return(false);
      }         
}

//
//
//
//
//

void DrawCandle(int tshift,int upDown,int index)
{
   datetime time  = Time[tshift];
   double   high  = iHigh (NULL,0,tshift);
   double   low   = iLow  (NULL,0,tshift);
   double   open  = iOpen (NULL,0,tshift);
   double   close = iClose(NULL,0,tshift);
   string name;


   
   totalCandles += 1;
   name    = windowID+"c-"+totalCandles;
      ObjectCreate(name,OBJ_TREND,0,time,high,time,low);
         ObjectSet(name,OBJPROP_COLOR,WickColor);
         ObjectSet(name,OBJPROP_RAY  ,false);
      
   //
   //
   //
   //
   //
         
   totalCandles += 1;
   name    = windowID+"c-"+totalCandles;
      ObjectCreate(name,OBJ_TREND,0,time,open,time,close);
         ObjectSet(name,OBJPROP_WIDTH,CandleWidth);
         ObjectSet(name,OBJPROP_RAY  ,false);
         if (index > 12)
            {
               if (upDown>0)
                     ObjectSet(name,OBJPROP_COLOR,BabyBarUpColor);
               else  ObjectSet(name,OBJPROP_COLOR,BabyBarDownColor);
            }               
         else
            {
               if (upDown>0)
                     ObjectSet(name,OBJPROP_COLOR,BarUpColor);
               else  ObjectSet(name,OBJPROP_COLOR,BarDownColor);
            }               
                     
}

//
//
//
//
//
//------------------------------------------------------------------
//
//------------------------------------------------------------------
//
//
//
//
//

void ShowComments()
{ 
   string TrendText="";
   
   //
   //
   //
   //
   //
   
   int R   =        (iHigh(NULL,PERIOD_D1,0) - iLow(NULL,PERIOD_D1,0))/pointvalue;
   
   int R1  =        (iHigh(NULL,PERIOD_D1,1) - iLow(NULL,PERIOD_D1,1))/pointvalue;
   
   int R5 = 0;
   for(int i=1;i<=5;i++)
   R5  = R5  +  (iHigh(NULL,PERIOD_D1,i) - iLow(NULL,PERIOD_D1,i))/pointvalue;
   
   int R10 = 0;
   for(i=1;i<=10;i++)
   R10 = R10 +  (iHigh(NULL,PERIOD_D1,i) - iLow(NULL,PERIOD_D1,i))/pointvalue;
   
   int R20 = 0;
   for(i=1;i<=20;i++)
   R20 = R20 +  (iHigh(NULL,PERIOD_D1,i) - iLow(NULL,PERIOD_D1,i))/pointvalue;

       R5   =  R5 / ShortRange;
       R10  =  R10/ InterRange;
       R20  =  R20/ LongRange;
   int RAvg = (R1 + R5 + R10 + R20)/4; 
      
   double low0     =  iLow(NULL, PERIOD_D1,0);
   double high0    =  iHigh(NULL,PERIOD_D1,0);
   int    RoomUp   =  RAvg - (Bid - low0)/pointvalue;
   int    RoomDn   =  RAvg - (high0 - Bid)/pointvalue;
   
   //
   //
   //
   //
   //
   
   double pred1trend = iOpen(NULL,timeframe1,shift+1);
   double curd1trend = iOpen(NULL,timeframe1,shift);
   double preh1trend = iOpen(NULL,timeframe2,shift+1);
   double curh1trend = iOpen(NULL,timeframe2,shift);
   double prem5trend = iOpen(NULL,timeframe3,shift+1);
   double curm5trend = iOpen(NULL,timeframe3,shift);
   
   double TrendType = 0;
   if (curd1trend < pred1trend && curh1trend < preh1trend && curm5trend < prem5trend) { TrendType=1; } //downtrend
   if (curd1trend > pred1trend && curh1trend > preh1trend && curm5trend > prem5trend) { TrendType=2; } //uptrend
  
   if (TrendType==2)    
   {    
   TrendText="Today Market Sentiment is: Bullish";    
   } else { 
      
   if (TrendType==1)     
   {    
   TrendText="Today Market Sentiment is: Bearish";    
   }else { 
       
   TrendText="Today Market Sentiment is: Undefined, Ranging";    
   }
   }
   
   //
   //
   //
   //
   //
   
   string strLocal  = TimeToStr(TimeLocal(),TIME_DATE|TIME_MINUTES|TIME_SECONDS);
	string strServer = TimeToStr(TimeCurrent(),TIME_DATE|TIME_MINUTES|TIME_SECONDS);
	string strGMT    = TimeToStr(TimeGMT(),TIME_DATE|TIME_MINUTES|TIME_SECONDS);
	
	string strLocalTimeZone;
	if (TimeZoneLocal() > 0)   strLocalTimeZone  = StringConcatenate("Local timezone: GMT plus ",TimeZoneLocal()," hours");
	if (TimeZoneLocal() == 0)  strLocalTimeZone  = "Local timezone: GMT";
	if (TimeZoneLocal() < 0)   strLocalTimeZone  = StringConcatenate("Local timezone: GMT minus ",-TimeZoneLocal()," hours");
	
	string strServerTimeZone;
	if (TimeZoneServer() > 0)  strServerTimeZone = StringConcatenate("Server timezone: GMT plus ",TimeZoneServer()," hours");
	if (TimeZoneServer() == 0) strServerTimeZone = "Server timezone: GMT";
  	if (TimeZoneServer() < 0)  strServerTimeZone = StringConcatenate("Server timezone: GMT minus ",-TimeZoneServer()," hours");
  	
  	//
  	//
  	//
  	//
  	//
  	
  	string symbol   = Symbol(); if (StringSubstr(symbol,0,2)=="_t") symbol = StringSubstr(symbol,2);
  	double tmodifier = 1;
  	int    digits   = MarketInfo(symbol,MODE_DIGITS);
   if (digits==3 || digits==5) tmodifier = 10.0;
  	
   //
   //
   //
   //
   //

   if(MarketInfo(Symbol(),MODE_SWAPLONG)>0) string swap="longs,";
   else swap="shorts.";
   if(MarketInfo(Symbol(),MODE_SWAPLONG)<0 && MarketInfo(Symbol(),MODE_SWAPSHORT)<0) swap="your broker. ";
   
   //
   //
   //
   //
   //  
   
   string sComment   = "";
   string sp         = "---------------------------------------------------\n";
   string NL         = "\n";
   
   sComment = sComment + sp;
   sComment = sComment + "Box Breakout System" + NL; 
   sComment = sComment + sp;
   sComment = sComment + "Range Analysis" + NL;
   sComment = sComment + "Avg Daily Range = " + RAvg + NL; 
   sComment = sComment + "Prev Day Range = " + R1   + NL;
   sComment = sComment + "Short Term Range = " + R5   + NL;
   sComment = sComment + "Intermediate Range = " + R10  + NL;
   sComment = sComment + "Long Term Range = " + R20  + NL;
   sComment = sComment + "Todays Range = " + R + NL;
   sComment = sComment + "Room Dn = " + RoomDn + NL;
   sComment = sComment + "Room Up = " + RoomUp + NL;
   sComment = sComment + sp;
   sComment = sComment + "Market Analysis" + NL;
   sComment = sComment + "Swap favors " + swap + NL; 
   sComment = sComment + "Swap Long      = " + DoubleToStr(MarketInfo(symbol,MODE_SWAPLONG),2) + NL; 
   sComment = sComment + "Swap Short     = " + DoubleToStr(MarketInfo(symbol,MODE_SWAPSHORT),2) + NL; 
   sComment = sComment + "Current Spread = " + DoubleToStr(MarketInfo(symbol,MODE_SPREAD)/ tmodifier,2) + NL;  
   sComment = sComment + sp;
   sComment = sComment + "Trend Analysis" + NL;
   sComment = sComment + TrendText + NL;
   sComment = sComment + sp;
   sComment = sComment + "Time Information" + NL;
   sComment = sComment + strLocalTimeZone  + NL;
   sComment = sComment + strServerTimeZone + NL;
   sComment = sComment + "Local time from PC clock = " +strLocal+ NL;
   sComment = sComment + "Broker server time       =  " +strServer+ NL;
   sComment = sComment + "GMT time                 =  " +strGMT+ NL;
   sComment = sComment + sp + NL;
   sComment = sComment + "Have a great trading day" + NL;
   sComment = sComment + sp; 
   
   Comment(sComment);  
}

//
//
//
//
//

#import "kernel32.dll"
int  GetTimeZoneInformation(int& TZInfoArray[]);
#import

#define TIME_ZONE_ID_UNKNOWN   0
#define TIME_ZONE_ID_STANDARD  1
#define TIME_ZONE_ID_DAYLIGHT  2

// Local timezone in hours, adjusting for daylight saving
double TimeZoneLocal()
{
	int TZInfoArray[43];

	switch(GetTimeZoneInformation(TZInfoArray))
	{
	case TIME_ZONE_ID_UNKNOWN: 
		Print("Error obtaining PC timezone from GetTimeZoneInformation in kernel32.dll. Returning 0");
		return(0);

	case TIME_ZONE_ID_STANDARD:
		return(TZInfoArray[0]/(-60.0));
	
	case TIME_ZONE_ID_DAYLIGHT:
		return((TZInfoArray[0]+TZInfoArray[42])/(-60.0));
		
	default:
		Print("Unkown return value from GetTimeZoneInformation in kernel32.dll. Returning 0");
		return(0);
	}
}

// Server timezone in hours
double TimeZoneServer()
{
	int ServerToLocalDiffMinutes = (TimeCurrent()-TimeLocal())/60;
	
	// round to nearest 30 minutes to allow for inaccurate PC clock
	int nHalfHourDiff = MathRound(ServerToLocalDiffMinutes/30.0);
	ServerToLocalDiffMinutes = nHalfHourDiff*30;
	return(TimeZoneLocal() + ServerToLocalDiffMinutes/60.0);
}