//+------------------------------------------------------------------+
//|                                               BreakOut_BOX_5.mq4 |
//|                                                        hapalkos  |
//|                                                       2007.02.16 |
//|      Code based on TIME1_modified.mq4 shown below                |
//|         posted to Forex Factory by glenn5t                       |
//|      Concept of the break-out box form by Markj                  |
//|                                                                  |
//|   ++ modified so that rectangles do not overlay                  |
//|   ++ this makes color selection more versatile                   |
//|  +++ code consolidated to facilitate changes                     |
//|  +++ changed Period B rectangle and added offset value           |
//|  +++ corrected error in bar selection code                       |
//| ++++ added ability to cross 00:00(nextDayA, nextDayB)            |
//| ++++ added Unique ID to allow for multiple indicators            |
//| ++++ added ability to delete rectangles specific to an indicator |
//|+++++ added Open/Close boxes and lines per Accrete                |
//|+++++ added Alerts - can be used with Tesla's Alerter EA          |
//|+++++ added Median Line - added by Accrete : )                    |
//|+++++ added maxbars to save cpu-RK 8-20-2013
//+------------------------------------------------------------------+
#property copyright "hapalkos"
#property link      ""

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Red
#property indicator_color2 LimeGreen
#property indicator_color3 Red
#property indicator_color4 LimeGreen  



extern string UniqueID              = "BreakOutBox";  
extern int    NumberOfDays          = 10;
extern int     maxBars              = 400;
extern bool   AutoAddSpread         = true;        // Added to compute Spread automatically         
extern string periodA_begin         = "00:00";     // Day0
extern string periodA_end           = "05:30";     // Day1
extern int    nextDayA              =  0;          // Set to zero if periodA_begin and periodA_end are on the same day.
extern string periodB_begin         = "00:00";     // Day0                                                 // Set to one if periodA_end is on the next day.
extern string periodB_end           = "05:30";      // Day1
extern int    nextDayB              =  0;           // Set to zero if periodA_begin and periodB_end are on the same day.                                                // Set to one if periodB_end is on the next day.
extern color  rectAB_color1         = DimGray; 
extern color  rectAB_color2         = Gray;         // second rectangle color to indicate relative position of Open/Close
extern bool   rectAB_background     = true;         // true - filled solid; false - outline
extern color  rectA_color           = Yellow;
extern bool   rectA_background      = false;        // true - filled solid; false - outline
extern color  rectB1_color          = DimGray;
extern bool   rectB1_background     = false;        // true - filled solid; false - outline
extern int    rectB1_band           = 10;           // Box Break-Out Band for the Period B rectangle
extern color  rectsB2_color         = SkyBlue;
extern bool   rectsB2_background    = false;        // true - filled solid, false - outline
extern int    rectsB2_band          = 0;            // Box Break-Out Band for the two upper and lower rectangles
extern int    Target                = 80; 
extern int    BoxBreakOut_Offset    = 0;        
extern color  UptargetLineColor     = Lime;
extern color  DowntargetLineColor   = Magenta;
extern color  EnterLineColor        = Yellow;
extern bool   rectA_close_begin     = true;         // false - period A close indication line begins at end of period A;  true - period A close line is drawn from beginning of period A
extern bool   periodB_ALERTS        = false;        // Alerts are set on the upper and lower sides of the upper and lower rectangles - rectsB2
                                                 // rectsB2_band determines the location of the Alerts
                                                 // Alert_xx added to the decription so that Alerts can be activated by Tesla's Alerter EA
                                                 
extern string HeikenAshiSetting     = "== Non Lag HeikenAshiSettings==";
extern bool   ShowHeikenAshi        = True;
extern int    NLMA_Length           = 9;   
extern int    NLMA_Displace         = 0;    
extern double NLMA_PctFilter        = 0;
extern int    Step                  = 1;
extern bool   BetterFormula         = true;
extern bool   T3Average             = true;
extern double T3Hot                 = 0.70;
extern bool   T3Original            = false;
extern bool   Alerts                = true;

extern string DailyRangeSetting      = "==DailyRangeSettings==";
extern bool   ShowDailyRange         = True;
extern color  DailyRangeColor        = Red;

extern string rangecomments          = "==Range Comments==";               
extern int    ShortRange             = 5;
extern int    InterRange             = 10;
extern int    LongRange              = 20;   

extern string FiboPivotSetting       = "==FiboPivotSettings==";
extern bool   ShowLines              = True;
extern color  Resistance_3           = LimeGreen;
extern color  Resistance_2           = LimeGreen;
extern color  Resistance_1           = LimeGreen;
extern color  Pivot                  = Gold;
extern color  Support_1              = Red;
extern color  Support_2              = Red;
extern color  Support_3              = Red;

extern string MoneyManagementSetting = "==MoneyManagementSettings==";
extern double Risk                   = 10;



double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
double emas[][24];
double alpha;
double c1;
double c2;
double c3;
double c4;


int    ExtCountedBars=0;
double pointvalue=1;  
double Spread;
int    nDigits;
int    sRectABname;
      

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
void init() {

   DeleteObjects();

   if (Digits == 4 || Digits == 2) pointvalue = Point;
   else if (Digits == 5 || Digits == 3) pointvalue = 10.0 * Point;

//---- indicators
   IndicatorBuffers(4);
   SetIndexStyle(0,DRAW_HISTOGRAM, 0, 1, Red);
   SetIndexBuffer(0, ExtMapBuffer1);
   SetIndexStyle(1,DRAW_HISTOGRAM, 0, 1,  LimeGreen);
   SetIndexBuffer(1, ExtMapBuffer2);
   SetIndexStyle(2,DRAW_HISTOGRAM, 0, 3, Red);
   SetIndexBuffer(2, ExtMapBuffer3);
   SetIndexStyle(3,DRAW_HISTOGRAM, 0, 3,  LimeGreen);
   SetIndexBuffer(3, ExtMapBuffer4);
   
   
   double a  = T3Hot;
          c1 = -a*a*a;
          c2 =  3*(a*a+a*a*a);
          c3 = -3*(2*a*a+a+a*a*a);
          c4 = 1+3*a+a*a*a+3*a*a;

      NLMA_Length = MathMax(1,NLMA_Length);
      if (T3Original)
      alpha = 2.0/(1.0 + NLMA_Length);
      else alpha = 2.0/(2.0 + (NLMA_Length-1.0)/2.0);
   
  }
  



//+------------------------------------------------------------------+
//| Custor indicator deinitialization function                       |
//+------------------------------------------------------------------+
void deinit() {

    ObjectDelete("S1");
    ObjectDelete("S2");
    ObjectDelete("S3");
    ObjectDelete("SS");   
    ObjectDelete("R1");
    ObjectDelete("R2");
    ObjectDelete("R3");
    ObjectDelete("SR");    
    ObjectDelete("PIVOT");
    ObjectDelete("Support 1");
    ObjectDelete("Support 2");
    ObjectDelete("Support 3");
    ObjectDelete("Pivot level");
    ObjectDelete("Resistance 1");
    ObjectDelete("Resistance 2");
    ObjectDelete("Resistance 3");  
    ObjectDelete("TDR2");
    ObjectDelete("TDR2 Line"); 
    ObjectDelete("BDR2");
    ObjectDelete("BDR2 Line");    
    Comment(" ");
    ObjectsDeleteAll(0,OBJ_RECTANGLE); 
    ObjectsDeleteAll(0,OBJ_TREND); 
    DeleteObjects();
}

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
void start() {

    datetime dtTradeDate=TimeCurrent();
    if (AutoAddSpread) Spread = (Ask - Bid);
  
    for (int i=0; i<NumberOfDays; i++) {
  
    DrawObjects(dtTradeDate, UniqueID + sRectABname+ TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectAB_color1,rectAB_color2, 0, 1, rectAB_background,nextDayA,nextDayB,Target,false);
    DrawObjects(dtTradeDate, UniqueID + " BoxUPtarget  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectAB_color1,rectAB_color2, 0, 6, false,nextDayA,nextDayB,Target, true);
    DrawObjects(dtTradeDate, UniqueID + " BoxLOWtarget  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectAB_color1,rectAB_color2,  0, 7, false,nextDayA,nextDayB,Target,true);
    DrawObjects(dtTradeDate, UniqueID + " BoxBO_High  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectsB2_color,rectAB_color2,  rectsB2_band,2,rectsB2_background,nextDayA,nextDayB,Target,false);
    if(periodB_ALERTS) DrawObjects(dtTradeDate, UniqueID + " BoxBO_HIGH ALERT " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectsB2_color,rectAB_color2,  rectsB2_band,8,false,nextDayA,nextDayB,Target,false);
    DrawObjects(dtTradeDate, UniqueID + " BoxBO_Low  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectsB2_color,rectAB_color2,  rectsB2_band,3,rectsB2_background,nextDayA,nextDayB,Target,false);
    if(periodB_ALERTS) DrawObjects(dtTradeDate, UniqueID + " BoxBO_LOW ALERT  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectsB2_color,rectAB_color2,  rectsB2_band,9,false,nextDayA,nextDayB,Target,false);
    DrawObjects(dtTradeDate, UniqueID + " BoxPeriodA  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodA_end, rectA_color,rectAB_color2,  0,4, rectA_background,nextDayA,nextDayB,Target,false);
    DrawObjects(dtTradeDate, UniqueID + " BoxPeriodB  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectB1_color,rectAB_color2,  rectB1_band,5, rectB1_background,nextDayA,nextDayB,Target, false);
    DrawObjects(dtTradeDate, UniqueID + " BoxHEnter  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectAB_color1,rectAB_color2,  0, 10, false,nextDayA,nextDayB,Target,true);
    DrawObjects(dtTradeDate, UniqueID + " BoxLEnter  " + TimeToStr(dtTradeDate,TIME_DATE), periodA_begin, periodA_end, periodB_end, rectAB_color1,rectAB_color2,  0, 11, false,nextDayA,nextDayB,Target,true);
    
    
    dtTradeDate=decrementTradeDate(dtTradeDate);
    while (TimeDayOfWeek(dtTradeDate) > 5 || TimeDayOfWeek(dtTradeDate) < 1 ) dtTradeDate = decrementTradeDate(dtTradeDate);     // Removed Sundays from plots
  }
}

//+------------------------------------------------------------------+
//| Create Objects - Rectangles and Trend lines                      |
//+------------------------------------------------------------------+

void DrawObjects(datetime dtTradeDate, string sObjName, string sTimeBegin, string sTimeEnd, string sTimeObjEnd, color cObjColor1, color cObjColor2, int iOffSet, int iForm, bool background, int tnextDayA, int tnextDayB, bool OpenClose, bool trectA_close_begin) {
  datetime dtTimeBegin, dtTimeEnd, dtTimeObjEnd;
  double   dPriceHigh,  dPriceLow,Sessionrange, dPriceuptarget, dPricehighenter,dPricelowenter, dPricedowntarget;
  double   swaplong=0, swapshort=0, PipValue=0; 
  int      iBarBegin,   iBarEnd;
  string   sObjDesc, TrendText="";

  dtTimeBegin = StrToTime(TimeToStr(dtTradeDate, TIME_DATE) + " " + sTimeBegin);
  dtTimeEnd = StrToTime(TimeToStr(dtTradeDate, TIME_DATE) + " " + sTimeEnd);
  dtTimeObjEnd = StrToTime(TimeToStr(dtTradeDate, TIME_DATE) + " " + sTimeObjEnd);
  
  if(tnextDayA == 1) dtTimeEnd = dtTimeEnd + 86400;
  if(tnextDayB == 1) dtTimeObjEnd = dtTimeObjEnd + 86400;
  if(tnextDayA == 1 && TimeDayOfWeek(dtTradeDate) == 5) dtTimeEnd = dtTimeEnd + (2 * 86400);
  if(tnextDayB == 1 && TimeDayOfWeek(dtTradeDate) == 5) dtTimeObjEnd = dtTimeObjEnd + (2 * 86400);
      
  iBarBegin = iBarShift(NULL, 0, dtTimeBegin)+1;                               
  iBarEnd = iBarShift(NULL, 0, dtTimeEnd)+1;
                              
  
  dPriceHigh  = High[Highest(NULL, 0, MODE_HIGH, (iBarBegin)-iBarEnd, iBarEnd)];
  dPriceLow   = Low [Lowest (NULL, 0, MODE_LOW , (iBarBegin)-iBarEnd, iBarEnd)];
  dPricehighenter = (dPriceHigh + BoxBreakOut_Offset* pointvalue + Spread);
  dPricelowenter = (dPriceLow - BoxBreakOut_Offset* pointvalue - Spread);
  dPriceuptarget  = (dPricehighenter + Target* pointvalue);                                             
  dPricedowntarget = (dPricelowenter - Target* pointvalue);
  Sessionrange = (dPriceHigh - dPriceLow)/ pointvalue;
 
double rates[1][6],yesterday_close,yesterday_high,yesterday_low;
ArrayCopyRates(rates, Symbol(), PERIOD_D1);

if(DayOfWeek() == 1)
{
   if(TimeDayOfWeek(iTime(Symbol(),PERIOD_D1,1)) == 5)
   {
       yesterday_close = rates[1][4];
       yesterday_high = rates[1][3];
       yesterday_low = rates[1][2];
   }
   else
   {
      for(int d = 5;d>=0;d--)
      {
         if(TimeDayOfWeek(iTime(Symbol(),PERIOD_D1,d)) == 5)
         {
             yesterday_close = rates[d][4];
             yesterday_high = rates[d][3];
             yesterday_low = rates[d][2];
         }
         
      }  
      
   }
}
else
{
    yesterday_close = rates[1][4];
    yesterday_high = rates[1][3];
    yesterday_low = rates[1][2];
}


//---- Calculate Pivots
double R = yesterday_high - yesterday_low;//range
double p = (yesterday_high + yesterday_low + yesterday_close)/3;// Standard Pivot
double r3 = p + (R * 1.000);
double r2 = p + (R * 0.618);
double r1 = p + (R * 0.382);
double s1 = p - (R * 0.382);
double s2 = p - (R * 0.618);
double s3 = p - (R * 1.000);



double day_high=0;
double day_low=0;
double nQ=0;
double nD=0;
double D=0;
double Q=0;


double seco= (Time[4]-Time[5])-MathMod(CurTime(),Time[4]-Time[5]);
double minu=seco/60;
seco=(minu-MathFloor(minu))*60;
minu=MathFloor(minu);

day_high = rates[0][3];
day_low = rates[0][2];
D = (day_high - day_low);
Q = (yesterday_high - yesterday_low);

if (Q > 5) 
{
	nQ = Q;
}
else
{
	nQ = Q*10000;
}

if (D > 5)
{
	nD = D;
}
else
{
	nD = D*10000;
}
 if (StringSubstr(Symbol(),3,3)=="JPY") {
 nQ=nQ/100;
 nD=nD/100;     
 }

if (ShowLines){
drawLine(r3,"R3", Resistance_3,1);
drawLabel("Resistance 3",r3,Resistance_3);
drawLine(r2,"R2", Resistance_2,2);
drawLabel("Resistance 2",r2,Resistance_2);
drawLine(r1,"R1", Resistance_1,0);
drawLabel("Resistance 1",r1,Resistance_1);

drawLine(p,"PIVOT",Pivot,1);
drawLabel("Pivot level",p,Pivot);

drawLine(s1,"S1",Support_1,0);
drawLabel("Support 1",s1,Support_1);
drawLine(s2,"S2",Support_2,2);
drawLabel("Support 2",s2,Support_2);
drawLine(s3,"S3",Support_3,1);
drawLabel("Support 3",s3,Support_3);
}
//+------------------------------------------------------------------+
//| Heiken Ashi indicator iteration function                              
//+------------------------------------------------------------------+
if (ShowHeikenAshi){

   double maOpen, maClose, maLow, maHigh;
   double haOpen, haClose, haLow, haHigh;
   int    counted_bars=IndicatorCounted();
   int    i,limit;

   //
   //
   //
   //
   //
   if(counted_bars<0) return;
   if(counted_bars>0) counted_bars--;
         limit = Bars-counted_bars;
         if (ArrayRange(emas,0) != Bars) ArrayResize(emas,Bars);          
      if ( maxBars > 0 )
   {
      limit = MathMin (maxBars, limit);   
   }        
   //
   //
   //
   //
   //
   
   for(int pos=limit; pos >= 0; pos--)
   {
      if (T3Average)
         {
            maOpen  = iT3(Open[pos] ,pos, 0);
            maClose = iT3(Close[pos],pos, 6);
            maLow   = iT3(Low[pos]  ,pos,12);
            maHigh  = iT3(High[pos] ,pos,18);
         }
      else
         {
           maOpen  = iCustom(NULL,0,"NonLagMA_v7.1.1",PRICE_OPEN, NLMA_Length,NLMA_Displace,NLMA_PctFilter,1,0,pos);
           maClose = iCustom(NULL,0,"NonLagMA_v7.1.1",PRICE_CLOSE,NLMA_Length,NLMA_Displace,NLMA_PctFilter,1,0,pos);
           maLow   = iCustom(NULL,0,"NonLagMA_v7.1.1",PRICE_LOW,  NLMA_Length,NLMA_Displace,NLMA_PctFilter,1,0,pos);
           maHigh  = iCustom(NULL,0,"NonLagMA_v7.1.1",PRICE_HIGH, NLMA_Length,NLMA_Displace,NLMA_PctFilter,1,0,pos);
         }
   
      //
      //
      //
      //
      //
        
         if (BetterFormula) {
               if (maHigh!=maLow)
                     haClose = (maOpen+maClose)/2+(((maClose-maOpen)/(maHigh-maLow))*MathAbs((maClose-maOpen)/2));
               else  haClose = (maOpen+maClose)/2; }
         else        haClose = (maOpen+maHigh+maLow+maClose)/4;
                     haOpen   = (ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2;
                     haHigh   = MathMax(maHigh, MathMax(haOpen,haClose));
                     haLow    = MathMin(maLow,  MathMin(haOpen,haClose));

         if (haOpen<haClose) { ExtMapBuffer1[pos]=haLow;  ExtMapBuffer2[pos]=haHigh; } 
         else                { ExtMapBuffer1[pos]=haHigh; ExtMapBuffer2[pos]=haLow;  } 
                               ExtMapBuffer3[pos]=haOpen;
                               ExtMapBuffer4[pos]=haClose;
      
      //
      //
      //
      //
      //

      if (Step>0)
      {
         if( MathAbs(ExtMapBuffer1[pos]-ExtMapBuffer1[pos+1]) < Step*pointvalue*Point) ExtMapBuffer1[pos]=ExtMapBuffer1[pos+1];
         if( MathAbs(ExtMapBuffer2[pos]-ExtMapBuffer2[pos+1]) < Step*pointvalue*Point) ExtMapBuffer2[pos]=ExtMapBuffer2[pos+1];
         if( MathAbs(ExtMapBuffer3[pos]-ExtMapBuffer3[pos+1]) < Step*pointvalue*Point) ExtMapBuffer3[pos]=ExtMapBuffer3[pos+1];
         if( MathAbs(ExtMapBuffer4[pos]-ExtMapBuffer4[pos+1]) < Step*pointvalue*Point) ExtMapBuffer4[pos]=ExtMapBuffer4[pos+1];
         
         }
       }
     }
  
  //+------------------------------------------------------------------+
//| Money management iteration function                              
//+------------------------------------------------------------------+     
   double lotMM;
   double lots=0.01;
   int PairsTraded;
   if(PairsTraded==0){
      lotMM = MathCeil(AccountFreeMargin() * Risk / 10000) / 10;
   } else {
      lotMM = MathCeil(AccountFreeMargin() * Risk / 10000 /PairsTraded) / 10 ;
   }
   if (lotMM < 0.01) lotMM = lots;
   if (lotMM < 0.1) lotMM = lots;
   if (lotMM > 1.0) lotMM  = MathCeil(lotMM);
   if  (lotMM > 100) lotMM = 100;
  //+------------------------------------------------------------------+
//| Daily Range iteration function                              
//+------------------------------------------------------------------+ 
  //+------------------------------------------------------------------+
//| Daily Range iteration function                              
//+------------------------------------------------------------------+ 
   int R1=0,R5=0,R10=0,R20=0,RAvg=0;
   int RoomUp=0,RoomDown=0,StopLoss_Long=0,StopLoss_Short=0;
   double SL_Long=0,SL_Short=0;
   double low0=0,high0=0,low1=0,high1=0;
   
   R1 =  (iHigh(NULL,PERIOD_D1,1)-iLow(NULL,PERIOD_D1,1))/pointvalue;
   for(i=1;i<=5;i++)
   R5 = R5  +  (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/pointvalue;
   for(i=1;i<=10;i++)
   R10 = R10 +  (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/pointvalue;
   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;
   RAvg  =  (R1+R5+R10+R20)/4;    

   low0  =  iLow(NULL,PERIOD_D1,0);
   high0 =  iHigh(NULL,PERIOD_D1,0);
   low1  =  iLow(NULL,PERIOD_D1,1);
   high1 =  iHigh(NULL,PERIOD_D1,1);
   RoomUp   =  RAvg - (Bid - low0)/pointvalue;
   RoomDown =  RAvg - (high0 - Bid)/pointvalue;
  
   if (haOpen < haClose)    
   {    
   TrendText="Today Market Sentiment is: UPTREND";    
   } else {    
   if (haOpen > haClose)     
   {    
   TrendText="Today Market Sentiment is: DOWNTREND";    
   }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");

   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. ";
   Spread = NormalizeDouble((Ask-Bid)/pointvalue,0);
   int Swaplong = NormalizeDouble(MarketInfo(Symbol(),18),2);
   int Swapshort = NormalizeDouble(MarketInfo(Symbol(),19),2); 
   if( StringFind( Symbol(), "JPY", 0) != -1 )
   { nDigits  = 2;}
   else { nDigits  = 4; }   
   
   string sComment   = "";
   string sp         = "---------------------------------------------------\n";
   string NL         = "\n";
   
   sComment = sComment + sp + NL;
   sComment = sComment + "Box Breakout System" + NL; 
   sComment = sComment + sp + NL;
   sComment = sComment + "Range Analysis" + NL;
   sComment = sComment + "Average Daily Range = " + RAvg + NL; 
   sComment = sComment + "Prev 01 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 = " + R5 + NL;
   sComment = sComment + "Room Down = " + RoomDown + NL;
   sComment = sComment + "Room Up = " + RoomUp + NL;
   sComment = sComment + sp + NL;
   sComment = sComment + "Market Analysis" + NL;
   sComment = sComment + "Swap favors " + swap + NL; 
   sComment = sComment + "Swap Long = " + DoubleToStr(Swaplong,nDigits) + NL; 
   sComment = sComment + "Swap Short = " + DoubleToStr(Swapshort,nDigits) + NL; 
   sComment = sComment + "Current Spread = " + DoubleToStr(Spread,nDigits) + NL;  
   sComment = sComment + sp + NL;
   sComment = sComment + "Trend Analysis" + NL;
   sComment = sComment + TrendText + NL;
   sComment = sComment + sp + NL;
   sComment = sComment + "Time Information" + NL;
   sComment = sComment + strLocalTimeZone + NL;
   sComment = sComment + "Time for next bar" + minu +  " min " + seco + " sec " + 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 + NL; 
   
   Comment(sComment);  
    
  
//---- High-Low Rectangle - Period A and B combined
   if(iForm==1){  
      ObjectCreate(sObjName, OBJ_RECTANGLE, 0, 0, 0, 0, 0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceHigh);  
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceLow);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DOT);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
   }
   
//---- Upper Rectangle  - Period B
  if(iForm==2){
      ObjectCreate(sObjName, OBJ_RECTANGLE, 0, 0, 0, 0, 0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceHigh);      
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceHigh + iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_SOLID);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
   }
 
 //---- Lower Rectangle - Period B
  if(iForm==3){
      ObjectCreate(sObjName, OBJ_RECTANGLE, 0, 0, 0, 0, 0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceLow - iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceLow);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_SOLID);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
   }

//---- Period A Rectangle
  if(iForm==4){
      ObjectCreate(sObjName, OBJ_RECTANGLE, 0, 0, 0, 0, 0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceHigh);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceLow);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DOT);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      sObjDesc = StringConcatenate("High: ",dPriceHigh,"  Low: ", dPriceLow,"  Box Range: ", (dPriceHigh-dPriceLow)/ pointvalue);  
      ObjectSetText(sObjName, sObjDesc,0,"Arial",Black);
   }   
//---- Period B Rectangle
  if(iForm==5){
      ObjectCreate(sObjName, OBJ_RECTANGLE, 0, 0, 0, 0, 0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceHigh + iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceLow - iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DOT);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
   }     
//---- Period A Up Target Line
  if(iForm==6){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceuptarget);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceuptarget);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DASH);
      ObjectSet(sObjName, OBJPROP_COLOR, UptargetLineColor);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
   }     
//---- Period A Down Target Line
rectA_close_begin = true;
  if(iForm==7){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      if(rectA_close_begin) ObjectSet(sObjName, OBJPROP_TIME1, dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPricedowntarget);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPricedowntarget);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DASH);
      ObjectSet(sObjName, OBJPROP_COLOR, DowntargetLineColor);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
   }        
   
   
   //---- Period High Enter Line

//rectA_close_begin = true;
  if(iForm==10){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      if(rectA_close_begin) ObjectSet(sObjName, OBJPROP_TIME1, dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPricehighenter);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPricehighenter);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DASH);
      ObjectSet(sObjName, OBJPROP_COLOR, EnterLineColor);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
   }
      //---- Period Low Enter Median Line

//rectA_close_begin = true;
  if(iForm==11){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      if(rectA_close_begin) ObjectSet(sObjName, OBJPROP_TIME1, dtTimeBegin);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPricelowenter);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPricelowenter);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_DASH);
      ObjectSet(sObjName, OBJPROP_COLOR, EnterLineColor);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
   }             
  
//---- Period B HIGH Alert
  if(iForm==8){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceHigh + iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceHigh + iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_SOLID);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
      sObjDesc = StringConcatenate("Period B - HIGH Alert_01 - ",dPriceHigh + iOffSet* pointvalue);  
      ObjectSetText(sObjName, sObjDesc,0,"Arial",Black);
//      if(Bid >= (dPriceHigh + iOffSet*Point)) Alert(sObjName," - ",dPriceHigh + iOffSet*Point);
   }     
//---- Period B LOW Alert
  if(iForm==9){
      ObjectCreate(sObjName,OBJ_TREND,0,0,0,0);
      ObjectSet(sObjName, OBJPROP_TIME1 , dtTimeEnd);
      ObjectSet(sObjName, OBJPROP_TIME2 , dtTimeObjEnd);
      ObjectSet(sObjName, OBJPROP_PRICE1, dPriceLow - iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_PRICE2, dPriceLow - iOffSet* pointvalue);
      ObjectSet(sObjName, OBJPROP_STYLE, STYLE_SOLID);
      ObjectSet(sObjName, OBJPROP_COLOR, cObjColor1);
      ObjectSet(sObjName, OBJPROP_WIDTH, 1);
      ObjectSet(sObjName, OBJPROP_BACK, background);
      ObjectSet(sObjName, OBJPROP_RAY,false);
      sObjDesc = StringConcatenate("Period B - LOW Alert_01 - ",dPriceLow - iOffSet* pointvalue);  
      ObjectSetText(sObjName, sObjDesc,0,"Arial",Black);  
//      if(Bid <= (dPriceLow - iOffSet*Point)) Alert(sObjName," - ",dPriceLow - iOffSet*Point);    
   }           
}
//+------------------------------------------------------------------+


void drawLabel(string name,double lvl,color Color)
{
    if(ObjectFind(name) != 0)
    {
        ObjectCreate(name, OBJ_TEXT, 0, Time[10], lvl);
        ObjectSetText(name, name, 8, "Arial", EMPTY);
        ObjectSet(name, OBJPROP_COLOR, Color);
    }
    else
    {
        ObjectMove(name, 0, Time[10], lvl);
    }
}


void drawLine(double lvl,string name, color Col,int type)
{
         if(ObjectFind(name) != 0)
         {
            ObjectCreate(name, OBJ_HLINE, 0, Time[0], lvl,Time[0],lvl);
            
            if(type == 1)
            ObjectSet(name, OBJPROP_STYLE, STYLE_SOLID);
            else if(type == 2)
            ObjectSet(name, OBJPROP_STYLE, STYLE_DASHDOTDOT);
            else
            ObjectSet(name, OBJPROP_STYLE, STYLE_DOT);
            
            ObjectSet(name, OBJPROP_COLOR, Col);
            ObjectSet(name,OBJPROP_WIDTH,1);
            
         }
         else
         {
            ObjectDelete(name);
            ObjectCreate(name, OBJ_HLINE, 0, Time[0], lvl,Time[0],lvl);
            
            if(type == 1)
            ObjectSet(name, OBJPROP_STYLE, STYLE_SOLID);
            else if(type == 2)
            ObjectSet(name, OBJPROP_STYLE, STYLE_DASHDOTDOT);
            else
            ObjectSet(name, OBJPROP_STYLE, STYLE_DOT);
            
            ObjectSet(name, OBJPROP_COLOR, Col);        
            ObjectSet(name,OBJPROP_WIDTH,1);
          
         }
}


double iT3(double price,int shift,int buffer)
{
   int i = Bars-shift-1;
   if (i < 1)
      {
         emas[i][0+buffer] = price;
         emas[i][1+buffer] = price;
         emas[i][2+buffer] = price;
         emas[i][3+buffer] = price;
         emas[i][4+buffer] = price;
         emas[i][5+buffer] = price;
      }
   else
      {
         emas[i][0+buffer] = emas[i-1][0+buffer]+alpha*(price            -emas[i-1][0+buffer]);
         emas[i][1+buffer] = emas[i-1][1+buffer]+alpha*(emas[i][0+buffer]-emas[i-1][1+buffer]);
         emas[i][2+buffer] = emas[i-1][2+buffer]+alpha*(emas[i][1+buffer]-emas[i-1][2+buffer]);
         emas[i][3+buffer] = emas[i-1][3+buffer]+alpha*(emas[i][2+buffer]-emas[i-1][3+buffer]);
         emas[i][4+buffer] = emas[i-1][4+buffer]+alpha*(emas[i][3+buffer]-emas[i-1][4+buffer]);
         emas[i][5+buffer] = emas[i-1][5+buffer]+alpha*(emas[i][4+buffer]-emas[i-1][5+buffer]);
      }
   return(c1*emas[i][5+buffer] + c2*emas[i][4+buffer] + c3*emas[i][3+buffer] + c4*emas[i][2+buffer]);
}

  //+------------------------------------------------------------------+
//| Remove all indicator Rectangles                                  |
//+------------------------------------------------------------------+
void DeleteObjects() {
      datetime dtTradeDate=TimeCurrent();

  for (int i=0; i<NumberOfDays; i++) {
  
    ObjectDelete(UniqueID + sRectABname + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxUPtarget  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxLOWtarget  " + TimeToStr(dtTradeDate,TIME_DATE));    
    ObjectDelete(UniqueID + " BoxBO_High  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxBO_HIGH ALERT " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxBO_Low  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxBO_LOW ALERT  " + TimeToStr(dtTradeDate,TIME_DATE));    
    ObjectDelete(UniqueID + " BoxPeriodA  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxPeriodB  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxHEnter  " + TimeToStr(dtTradeDate,TIME_DATE));
    ObjectDelete(UniqueID + " BoxLEnter  " + TimeToStr(dtTradeDate,TIME_DATE));
    
 
    
    dtTradeDate=decrementTradeDate(dtTradeDate);
    while (TimeDayOfWeek(dtTradeDate) > 5 || TimeDayOfWeek(dtTradeDate) < 1 ) dtTradeDate = decrementTradeDate(dtTradeDate);     // Removed Sundays from plots
    } 
    ObjectsDeleteAll(0,OBJ_LABEL);    
}


//+------------------------------------------------------------------+
//| Decrement Date to draw objects in the past                       |
//+------------------------------------------------------------------+

datetime decrementTradeDate (datetime dtTimeDate) {
   int iTimeYear=TimeYear(dtTimeDate);
   int iTimeMonth=TimeMonth(dtTimeDate);
   int iTimeDay=TimeDay(dtTimeDate);
   int iTimeHour=TimeHour(dtTimeDate);
   int iTimeMinute=TimeMinute(dtTimeDate);

   iTimeDay--;
   if (iTimeDay==0) {
     iTimeMonth--;
     if (iTimeMonth==0) {
       iTimeYear--;
       iTimeMonth=12;
     }
    
     // Thirty days hath September...  
     if (iTimeMonth==4 || iTimeMonth==6 || iTimeMonth==9 || iTimeMonth==11) iTimeDay=30;
     // ...all the rest have thirty-one...
     if (iTimeMonth==1 || iTimeMonth==3 || iTimeMonth==5 || iTimeMonth==7 || iTimeMonth==8 || iTimeMonth==10 || iTimeMonth==12) iTimeDay=31;
     // ...except...
     if (iTimeMonth==2) if (MathMod(iTimeYear, 4)==0) iTimeDay=29; else iTimeDay=28;
   }
  return(StrToTime(iTimeYear + "." + iTimeMonth + "." + iTimeDay + " " + iTimeHour + ":" + iTimeMinute));
}

//
//
//
//
//

#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);
}


