//+------------------------------------------------------------------+
//|  ADR 1.00.mq4                                                    |
//| https://forex-station.com/viewtopic.php?p=1295464251#p1295464251 |
//+------------------------------------------------------------------+

#property indicator_chart_window

extern string             note1                 = "Fibonacci colors";
extern bool               DisplayUpperFibo      = true;
extern color              UpperFiboColor        = clrDarkGreen;
extern ENUM_LINE_STYLE    UpperFiboStyle        = STYLE_DASH;
extern int                UpperFiboWidth        = 1;
extern string             note2                 = "------------------------------";
extern bool               DisplayMainFibo       = true;
extern color              MainFiboColor         = clrRoyalBlue;
extern ENUM_LINE_STYLE    MainFiboStyle         = STYLE_DASHDOT;
extern int                MainFiboWidth         = 1;
extern string             note3                 = "------------------------------";
extern bool               DisplayLowerFibo      = true;
extern color              LowerFiboColor        = clrCrimson;
extern ENUM_LINE_STYLE    LowerFiboStyle        = STYLE_DASHDOTDOT;
extern int                LowerFiboWidth        = 1;

extern int TimeZoneOfData= 0;       // chart time zone (from GMT)
extern int TimeZoneOfSession= 0;   // dest time zone (from GMT) 

int ADROpenHour= 0;         // start time for range calculation (LEAVE AT 0. PROGRAM DOESN'T WORK PROPERLY OTHERWISE.)
int ADRCloseHour= 24;        // end time for range calculation  (LEAVE AT 24. PROGRAM DOESN'T WORK PROPERLY OTHERWISE.)

extern bool UseManualADR= false;    // allows use of manual value for range
extern int ManualADRValuePips= 0;   // manual value for range

int LineStyle= 2;
int LineThickness1= 1;       // normal thickness
color LineColor1= clrOrange;    // normal color
int LineThickness2= 2;       // thickness for range reached state
color LineColor2= clrBlue;       // color for range reached state


bool ShowLevelPrices= true;         // show prices on h-lines
extern int BarForLabels= -10;       // number of bars from right, where lines labels will be shown

extern bool DebugLogger = false;

//used for new adr calculation
extern int First_av = 5;
extern int Second_av = 10;
extern int Third_av = 20;
//template code start1
extern string             button_note1          = "------------------------------";
extern ENUM_BASE_CORNER   btn_corner            = CORNER_LEFT_UPPER; // chart btn_corner for anchoring
extern int                btn_Subwindow = 0;
extern string             btn_text              = "ADR Fibo";
extern string             btn_Font              = "Arial";
extern int                btn_FontSize          = 9;                             //btn__font size
extern color              btn_text_ON_color     = clrLime;
extern color              btn_text_OFF_color    = clrRed;
extern color              btn_background_color  = clrDimGray;
extern color              btn_border_color      = clrBlack;
extern int                button_x              = 20;                                     //btn__x
extern int                button_y              = 25;                                     //btn__y
extern int                btn_Width             = 80;                                 //btn__width
extern int                btn_Height            = 20;                                //btn__height
extern string             button_note2          = "------------------------------";
bool                      show_data             = true;
string IndicatorName, IndicatorObjPrefix;
//template code end1

double mPoint, today_high, today_low, today_range,
          adr_high= 0,
          adr_low= 0, adr_range = 0;
datetime startofday;
//+------------------------------------------------------------------+
string GenerateIndicatorName(const string target) //don't change anything here
{
   string name = target;
   int try = 2;
   while (WindowFind(name) != -1)
   {
      name = target + " #" + IntegerToString(try++);
   }
   return name;
}
//+------------------------------------------------------------------+
string buttonId;

int OnInit()
{
   IndicatorName = GenerateIndicatorName(btn_text);
   IndicatorObjPrefix = "__" + IndicatorName + "__";
   IndicatorShortName(IndicatorName);
   IndicatorDigits(Digits);
   
   double val;
   if (GlobalVariableGet(IndicatorName + "_visibility", val))
      show_data = val != 0;

   ChartSetInteger(ChartID(), CHART_EVENT_MOUSE_MOVE, 1);
   buttonId = IndicatorObjPrefix + "ADRfiboButton";
   createButton(buttonId, btn_text, btn_Width, btn_Height, btn_Font, btn_FontSize, btn_background_color, btn_border_color, btn_text_ON_color);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_YDISTANCE, button_y);
   ObjectSetInteger(ChartID(), buttonId, OBJPROP_XDISTANCE, button_x);
// put init() here
   init2();
   return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//don't change anything here
void createButton(string buttonID,string buttonText,int width,int height,string font,int fontSize,color bgColor,color borderColor,color txtColor)
{
      ObjectDelete    (ChartID(),buttonID);
      ObjectCreate    (ChartID(),buttonID,OBJ_BUTTON,btn_Subwindow,0,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_COLOR,txtColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BGCOLOR,bgColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_BORDER_COLOR,borderColor);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XSIZE,width);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YSIZE,height);
      ObjectSetString (ChartID(),buttonID,OBJPROP_FONT,font);
      ObjectSetString (ChartID(),buttonID,OBJPROP_TEXT,buttonText);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_FONTSIZE,fontSize);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_SELECTABLE,0);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_CORNER,btn_corner);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_HIDDEN,1);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_XDISTANCE,9999);
      ObjectSetInteger(ChartID(),buttonID,OBJPROP_YDISTANCE,9999);
}
//+------------------------------------------------------------------+
int deinit()
{
   int obj_total= ObjectsTotal();
   
   ObjectsDeleteAll(ChartID(), IndicatorObjPrefix);
   for (int i= obj_total; i>=0; i--) {
      string name= ObjectName(i);
    
      if (StringSubstr(name,0,5)=="[ADR]") 
         ObjectDelete(name);
   }
   Comment("");
   ObjectDelete("ADRinsideDaily");
   ObjectDelete("ADRUpDaily");
   ObjectDelete("ADRDownDaily");
   return(0);
}
//+------------------------------------------------------------------+
//don't change anything here
bool recalc = true;

void handleButtonClicks()
{
   if (ObjectGetInteger(ChartID(), buttonId, OBJPROP_STATE))
   {
      ObjectSetInteger(ChartID(), buttonId, OBJPROP_STATE, false);
      show_data = !show_data;
      GlobalVariableSet(IndicatorName + "_visibility", show_data ? 1.0 : 0.0);
      recalc = true;
      start();
   }
}
//+------------------------------------------------------------------+
void OnChartEvent(const int id, //don't change anything here
                  const long &lparam,
                  const double &dparam,
                  const string &sparam)
{
   handleButtonClicks();
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init2()
{
   Print("Period= ", Period());
   Print("Point= ", Point);

  if(Point==0.00001) {mPoint=0.0001;}//Alpari
  else if(Point==0.001) {mPoint=0.01;}
  else {mPoint = Point;}//InterBankFX  
   
  if (First_av == 0 || Second_av == 0 || Third_av == 0)
      Alert("(First/Second/Third)_av inputs must not equal zero. Indicator will not run.");
   
   return(0);
}
//+------------------------------------------------------------------+
int DrawFibo()
{
	if(DisplayUpperFibo)
	{

	if(ObjectFind("ADRUpDaily") == -1)
      ObjectCreate("ADRUpDaily",OBJ_FIBO,0,startofday,adr_high+adr_range,startofday+PERIOD_D1*60,adr_high);
	else
	{
		ObjectSet("ADRUpDaily",OBJPROP_PRICE1,adr_high+adr_range);
		ObjectSet("ADRUpDaily",OBJPROP_PRICE2,adr_high);
   }
   ObjectSet("ADRUpDaily",OBJPROP_LEVELSTYLE,UpperFiboStyle);
   ObjectSet("ADRUpDaily",OBJPROP_LEVELWIDTH,UpperFiboWidth);
   ObjectSet("ADRUpDaily",OBJPROP_LEVELCOLOR,UpperFiboColor);
   ObjectSet("ADRUpDaily",OBJPROP_FIBOLEVELS,15);
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+0,0.0);	   
	if (!DisplayMainFibo)
       ObjectSetFiboDescription("ADRUpDaily",0,"(100.0%) -  %$"); 
   else    
       ObjectSetFiboDescription("ADRUpDaily",0,""); 

   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+1,0.236);	ObjectSetFiboDescription("ADRUpDaily",1,"(123.6%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+2,0.382); 	ObjectSetFiboDescription("ADRUpDaily",2,"(138.2%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+3,0.500); 	ObjectSetFiboDescription("ADRUpDaily",3,"(150.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+4,0.618); 	ObjectSetFiboDescription("ADRUpDaily",4,"(161.8%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+5,0.764); 	ObjectSetFiboDescription("ADRUpDaily",5,"(176.4%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+6,1.000); 	ObjectSetFiboDescription("ADRUpDaily",6,"(200.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+7,1.236);   ObjectSetFiboDescription("ADRUpDaily",7,"(223.6%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+8,1.500);   ObjectSetFiboDescription("ADRUpDaily",8,"(250.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+9,1.618);	ObjectSetFiboDescription("ADRUpDaily",9,"(261.8%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+10,2.000);	ObjectSetFiboDescription("ADRUpDaily",10,"(300.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+11,2.500);	ObjectSetFiboDescription("ADRUpDaily",11,"(350.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+12,3.000);	ObjectSetFiboDescription("ADRUpDaily",12,"(400.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+13,3.500);	ObjectSetFiboDescription("ADRUpDaily",13,"(450.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_FIRSTLEVEL+14,4.000);	ObjectSetFiboDescription("ADRUpDaily",14,"(500.0%) -  %$"); 
   ObjectSet("ADRUpDaily",OBJPROP_RAY,true);
   ObjectSet("ADRUpDaily",OBJPROP_BACK,true);
}
   else
	   ObjectDelete("ADRUpDaily");
//~~~~~~~~~~~~~~~
	if(DisplayLowerFibo)
	{
	if(ObjectFind("ADRDownDaily") == -1)
      ObjectCreate("ADRDownDaily",OBJ_FIBO,0,startofday,adr_low-adr_range,startofday+PERIOD_D1*60,adr_low);
	else
	{
		ObjectSet("ADRDownDaily",OBJPROP_PRICE1,adr_low-adr_range);
		ObjectSet("ADRDownDaily",OBJPROP_PRICE2,adr_low);
	}
   ObjectSet("ADRDownDaily",OBJPROP_LEVELSTYLE,LowerFiboStyle);
   ObjectSet("ADRDownDaily",OBJPROP_LEVELWIDTH,LowerFiboWidth);
   ObjectSet("ADRDownDaily",OBJPROP_LEVELCOLOR,LowerFiboColor);      
   ObjectSet("ADRDownDaily",OBJPROP_FIBOLEVELS,19);
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+0,0.0);	   
	if (!DisplayMainFibo)
       ObjectSetFiboDescription("ADRDownDaily",0,"(0.0%) -  %$"); 
   else
       ObjectSetFiboDescription("ADRDownDaily",0,""); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+1,0.236); 	ObjectSetFiboDescription("ADRDownDaily",1,"(-23.6%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+2,0.382); 	ObjectSetFiboDescription("ADRDownDaily",2,"(-38.2%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+3,0.500); 	ObjectSetFiboDescription("ADRDownDaily",3,"(-50.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+4,0.618); 	ObjectSetFiboDescription("ADRDownDaily",4,"(-61.8%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+5,0.764); 	ObjectSetFiboDescription("ADRDownDaily",5,"(-76.4%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+6,1.000);  	ObjectSetFiboDescription("ADRDownDaily",6,"(-100.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+7,1.236); 	ObjectSetFiboDescription("ADRDownDaily",7,"(-123.6%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+8,1.382);	   ObjectSetFiboDescription("ADRDownDaily",8,"(-138.2%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+9,1.500); 	ObjectSetFiboDescription("ADRDownDaily",9,"(-150.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+10,1.618);	ObjectSetFiboDescription("ADRDownDaily",10,"(-161.8%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+11,1.764);	ObjectSetFiboDescription("ADRDownDaily",11,"(-176.4%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+12,2.000);	ObjectSetFiboDescription("ADRDownDaily",12,"(-200.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+13,2.500);	ObjectSetFiboDescription("ADRDownDaily",13,"(-250.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+14,3.000);	ObjectSetFiboDescription("ADRDownDaily",14,"(-300.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+15,3.500);	ObjectSetFiboDescription("ADRDownDaily",15,"(-350.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+16,4.000);	ObjectSetFiboDescription("ADRDownDaily",16,"(-400.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+17,4.500);	ObjectSetFiboDescription("ADRDownDaily",17,"(-450.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_FIRSTLEVEL+18,5.000);	ObjectSetFiboDescription("ADRDownDaily",18,"(-500.0%) -  %$"); 
   ObjectSet("ADRDownDaily",OBJPROP_RAY,true);
   ObjectSet("ADRDownDaily",OBJPROP_BACK,true);
}
   else
	   ObjectDelete("ADRDownDaily");
//~~~~~~~~~~~
	if(DisplayMainFibo)
	{
		if (ObjectFind("ADRinsideDaily") == -1)
          ObjectCreate("ADRinsideDaily",OBJ_FIBO,0,startofday,adr_high,startofday+PERIOD_D1*60,adr_low);
		else
		{
			ObjectSet("ADRinsideDaily",OBJPROP_PRICE1,adr_high);
			ObjectSet("ADRinsideDaily",OBJPROP_PRICE2,adr_low);
		}
      ObjectSet("ADRinsideDaily",OBJPROP_LEVELSTYLE,MainFiboStyle);
      ObjectSet("ADRinsideDaily",OBJPROP_LEVELWIDTH,MainFiboWidth);
   	ObjectSet("ADRinsideDaily",OBJPROP_LEVELCOLOR,MainFiboColor); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIBOLEVELS,7);
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+0,0.0);	   ObjectSetFiboDescription("ADRinsideDaily",0,"ADR Low (0.0) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+1,0.236);	ObjectSetFiboDescription("ADRinsideDaily",1,"(23.6) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+2,0.382);	ObjectSetFiboDescription("ADRinsideDaily",2,"(38.2) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+3,0.500);	ObjectSetFiboDescription("ADRinsideDaily",3,"(50.0) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+4,0.618);	ObjectSetFiboDescription("ADRinsideDaily",4,"(61.8) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+5,0.764);	ObjectSetFiboDescription("ADRinsideDaily",5,"(76.4) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_FIRSTLEVEL+6,1.000);	ObjectSetFiboDescription("ADRinsideDaily",6,"ADR High (100.0) -  %$"); 
   	ObjectSet("ADRinsideDaily",OBJPROP_RAY,true);
   	ObjectSet("ADRinsideDaily",OBJPROP_BACK,true);
   }
   else
	   ObjectDelete("ADRinsideDaily");
	return (0);
}
//+------------------------------------------------------------------+
 
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
   static datetime timelastupdate= 0;
   static int lasttimeframe= 0,
              lastfirstbar= -1;
   
   int idxfirstbaroftoday= 0,
       idxfirstbarofyesterday= 0,
       idxlastbarofyesterday= 0;

   handleButtonClicks();
   recalc = false;
  
   //---- exit if period is greater than daily charts
   if(Period() > 1440) {
      Alert("Error - Chart period is greater than 1 day.");
      return(-1); // then exit
   }

   if (DebugLogger) {
      Print("Local time current bar:", TimeToStr(Time[0]));
      Print("Dest  time current bar: ", TimeToStr(Time[0]- (TimeZoneOfData - TimeZoneOfSession)*3600), ", tzdiff= ", TimeZoneOfData - TimeZoneOfSession);
   }


   // let's find out which hour bars make today and yesterday
   ComputeDayIndices(TimeZoneOfData, TimeZoneOfSession, idxfirstbaroftoday, idxfirstbarofyesterday, idxlastbarofyesterday);


   // no need to update these buggers too often (the code below is a bit tricky, usually just the 
   // timelastupdate would be sufficient, but when turning on MT after the night there is just
   // the newest bar while the rest of the day is missing and updated a bit later).  Don't mess
   // with this unless you are absolutely sure you know what you're doing.
   if (Time[0]==timelastupdate && Period()==lasttimeframe && lastfirstbar==idxfirstbaroftoday) {
   //    return (0);
   }
      
      
   lasttimeframe= Period();
   timelastupdate= Time[0];
   lastfirstbar= idxfirstbaroftoday;
   


   //
   // okay, now we know where the days start and end
   //
      
      
   int tzdiff= TimeZoneOfData + TimeZoneOfSession,
       tzdiffsec= tzdiff*3600;


   startofday= Time[idxfirstbaroftoday];  // datetime (x-value) for labes on horizontal bars

   double adr;
   if (UseManualADR)
      adr = ManualADRValuePips*Point;
   else
   {
      int R1=0,R5=0,R10=0,R20=0, i;

      R1 =  (iHigh(NULL,PERIOD_D1,1)-iLow(NULL,PERIOD_D1,1))/mPoint;
      for(i=1;i<=First_av;i++)
      R5    =    R5  +  (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/mPoint;
      for(i=1;i<=Second_av;i++)
      R10   =    R10 +  (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/mPoint;
      for(i=1;i<=Third_av;i++)
      R20   =    R20 +  (iHigh(NULL,PERIOD_D1,i)-iLow(NULL,PERIOD_D1,i))/mPoint;

      R5 = R5/First_av;
      R10 = R10/Second_av;
      R20 = R20/Third_av;
      adr  =  (R1+R5+R10+R20)/4;
      adr = adr * mPoint; //this indicator expects adr in Points not Pips
   }   

   // 
   // walk forward through today and collect high/lows within the same day
   //
   double today_open= 0,
          lasthigh, lastlow,
          to_long_adr= 0,
          to_short_adr= 0;
   bool adr_reached= false, lastreached;

   // new-start
   for (int j= idxfirstbaroftoday; j>=0; j--) {
      
      datetime bartime= Time[j]-tzdiffsec;
      
      if (TimeHour(bartime)>=ADROpenHour && TimeHour(bartime)<ADRCloseHour) {
      
         if (today_open==0) {
            today_open= Open[idxfirstbaroftoday];  // should be open of today start trading hour
            adr_high= today_open + adr;
            adr_low= today_open - adr;
            today_high= today_open;
            today_low= today_open;

         }

         for (int k= 0; k<3; k++) {
      
            double price;
         
            switch (k) {
               case 0: price= Low[j]; break;
               case 1: price= High[j]; break;
               case 2: price= Close[j]; break;
            }

            lasthigh= today_high;
            lastlow= today_low;
            lastreached= adr_reached;
                  
            today_high= MathMax(today_high, price);
            today_low= MathMin(today_low, price);
         
            today_range= today_high - today_low;
            adr_reached= today_range >= adr - Point/2;   // "Point/2" to avoid rounding problems (double variables)
         
         
            // adr-high
            if (!lastreached && !adr_reached) {
               adr_high= today_low + adr;
            }
            else
            if (!lastreached && adr_reached && price>=lasthigh) {
               adr_high= today_low + adr;
            }
            else
            if (!lastreached && adr_reached && price<lasthigh) {
               adr_high= lasthigh;
            }
            else {
               adr_high= adr_high;
            }
         

            // adr-low
            if (!lastreached && !adr_reached) {
               if (DebugLogger) {
                  Print("#: ", j, " ", "adr_low= today_high-adr ", today_high, "-", adr, "= ", today_high-adr);
               }
               adr_low= today_high - adr;
            }
            else
            if (!lastreached && adr_reached && price>=lastlow) {
               if (DebugLogger) {
                  Print("#: ", j, " ", "adr_low= today_low", today_low);
               }
               adr_low= today_low;
            }
            else
            if (!lastreached && adr_reached && price<lastlow) {
               if (DebugLogger) {
                  Print("#: ", j, " ", "adr_low= lasthigh-adr ", lasthigh, "-", adr, "= ", lasthigh-adr);
               }
               adr_low= lasthigh - adr;
            }
            else {
               if (DebugLogger) {
                  Print("#: ", j, " ", "adr_low= adr_low ", adr_low);
               }
               adr_low= adr_low;
            }

            to_long_adr= adr_high - Close[j];
            to_short_adr= Close[j] - adr_low;
            adr_range = adr_high - adr_low;
            
            if (DebugLogger) {
               Print("#:", j, " ", TimeToStr(bartime, TIME_MINUTES), " High-Low/adr-Reached ", today_high-today_low, "/", adr_reached);
            
               Print("#: ", j, " ", " Price= ", price, " (k= ", k, " [0=low, 1=high, 2=close]])");
         
               Print("#: ", j, " ", "ADR= ", adr, ", O= ", today_high, ", P= ", today_low, 
                              ", Q= ", today_high-today_low, ", R= ", adr_reached, 
                              ", S= ", adr_high, ", T= ", adr_low, ", U= ", to_long_adr, ", V= ", to_short_adr);
            }
         }
      }
   }
   // new-end
   
   if (DebugLogger) 
      Print("Timezoned values: t-open= ", today_open, ", t-high =", today_high, ", t-low= ", today_low);
      

      
   // draw the vertical bars that marks the time span
//   SetTimeLine("today start2", "ADR Start2", idxfirstbaroftoday, CadetBlue, Low[idxfirstbaroftoday]- 10*Point);
   
   color col= LineColor1;
   int thickness= LineThickness1;
   
   if (adr_reached) {
      col= LineColor2;
      thickness= LineThickness2;
   }
   
   DrawFibo(); 
   
   string reached_str= "Yes";
   if (!adr_reached)
      reached_str= "No";
      
      
      
      

   string comment=
          
            
            "ADR " + DoubleToStr(MathRound((adr/Point)),0) + 
                           "  Today " + DoubleToStr(MathRound(((today_high-today_low)/Point)),0) ;
                              
   Comment(comment);
      if (show_data)
      {
        ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_ON_color);
        DrawFibo();
      }
      else
      {
        ObjectSetInteger(ChartID(),buttonId,OBJPROP_COLOR,btn_text_OFF_color);
        ObjectDelete("ADRinsideDaily");
        ObjectDelete("ADRUpDaily");
        ObjectDelete("ADRDownDaily");
      }

   return(0);
}

 
//+------------------------------------------------------------------+
//| Compute index of first/last bar of yesterday and today           |
//+------------------------------------------------------------------+
void ComputeDayIndices(int tzlocal, int tzdest, int &idxfirstbaroftoday, int &idxfirstbarofyesterday, int &idxlastbarofyesterday)
{     
   int tzdiff= tzlocal + tzdest,
       tzdiffsec= tzdiff*3600,
       dayminutes= 24 * 60,
       barsperday= dayminutes/Period();
   
   int dayofweektoday= TimeDayOfWeek(Time[0] - tzdiffsec),  // what day is today in the dest timezone?
       dayofweektofind= -1; 

   //
   // due to gaps in the data, and shift of time around weekends (due 
   // to time zone) it is not as easy as to just look back for a bar 
   // with 00:00 time
   //
   
   idxfirstbaroftoday= 0;
   idxfirstbarofyesterday= 0;
   idxlastbarofyesterday= 0;
       
   switch (dayofweektoday) {
      case 6: // sat
      case 0: // sun
      case 1: // mon
            dayofweektofind= 5; // yesterday in terms of trading was previous friday
            break;
            
      default:
            dayofweektofind= dayofweektoday -1; 
            break;
   }
   
   if (DebugLogger) {
      Print("Dayofweektoday= ", dayofweektoday);
      Print("Dayofweekyesterday= ", dayofweektofind);
   }
       
       
   // search  backwards for the last occrrence (backwards) of the day today (today's first bar)
   for (int i= 0; i<=barsperday+1; i++) {
      datetime timet= Time[i] - tzdiffsec;
      // Print(Symbol(), " DayofWeek[", i, ,"]= ", TimeDayOfWeek(timet), " (", dayofweektoday, ") ", TimeToStr(timet));
      if (TimeDayOfWeek(timet)!=dayofweektoday) {
         idxfirstbaroftoday= i-1;
         break;
      }
   }
   

   // Print(Symbol(), " idxfirstoftoday ", idxfirstbaroftoday);

   // search  backwards for the first occrrence (backwards) of the weekday we are looking for (yesterday's last bar)
   for (int j= 0; j<=2*barsperday+1; j++) {
      datetime timey= Time[i+j] - tzdiffsec;
      if (TimeDayOfWeek(timey)==dayofweektofind) {  // ignore saturdays (a Sa may happen due to TZ conversion)
         idxlastbarofyesterday= i+j;
         break;
      }
   }


   // search  backwards for the first occurrence of weekday before yesterday (to determine yesterday's first bar)
   for (j= 1; j<=barsperday; j++) {
      datetime timey2= Time[idxlastbarofyesterday+j] - tzdiffsec;
      if (TimeDayOfWeek(timey2)!=dayofweektofind) {  // ignore saturdays (a Sa may happen due to TZ conversion)
         idxfirstbarofyesterday= idxlastbarofyesterday+j-1;
         break;
      }
   }


   if (DebugLogger) {
      Print("Dest time zone\'s current day starts:", TimeToStr(Time[idxfirstbaroftoday]), 
                                                      " (local time), idxbar= ", idxfirstbaroftoday);

      Print("Dest time zone\'s previous day starts:", TimeToStr(Time[idxfirstbarofyesterday]), 
                                                      " (local time), idxbar= ", idxfirstbarofyesterday);
      Print("Dest time zone\'s previous day ends:", TimeToStr(Time[idxlastbarofyesterday]), 
                                                      " (local time), idxbar= ", idxlastbarofyesterday);
   }
}    
//+------------------------------------------------------------------+
//| Helper                                                           |
//+------------------------------------------------------------------+
void SetTimeLine(string objname, string text, int idx, color col1, double vleveltext) 
{
   string name= "[ADR] " + objname;
   int x= Time[idx];

   if (ObjectFind(name) != 0) 
      ObjectCreate(name, OBJ_TREND, 0, x, 0, x, 100);

   ObjectMove(name, 0, x, 0);
   ObjectMove(name, 1, x, 100);
   ObjectSet(name, OBJPROP_BACK, true);
   ObjectSet(name, OBJPROP_STYLE, STYLE_DOT);
   ObjectSet(name, OBJPROP_COLOR, DarkGray);
   
   if (ObjectFind(name + " Label") != 0) 
      ObjectCreate(name + " Label", OBJ_TEXT, 0, x, vleveltext);

   ObjectMove(name + " Label", 0, x, vleveltext);
   ObjectSetText(name + " Label", text, 8, "Arial", col1);
}

