//+------------------------------------------------------------------+
//|                            Pivot Points                          |
//|                        Created by Shimodax                       |
//|                           Modified by vS                         |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "vS"

#property indicator_chart_window

extern int LocalTimeZone= 0;
extern int DestTimeZone= 0;
extern int BarForLabels= 0;     // number of bars from right, where lines labels will be shown
extern int LineStyle= 2;        // style of smaller resistance lines.
extern int LineStyleSR= 2;      // style of support and resistance.
extern int LineStyleY= 2;       // style of yesterday's High and Lows.
extern int LineStyleP= 2;       // style of pivot point line.
extern int LabelsFontSize = 7;
extern color LabelsColor = DarkGray;
extern bool ShowComment = true;
extern bool ShowLevelPrices = false;
extern bool ShowHighLowOpen = true;
extern bool ShowSweetSpots = false;
extern bool ShowPivots = true;
extern bool ShowFibos= false;
extern bool ShowMidPitvot = true;
extern bool ShowCamarilla = false;
extern bool DebugLogger = false;

int TradingHoursFrom= 0;
int TradingHoursTo= 24;
       
//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int init()
{
   return(0);
}

int deinit()
{
   int obj_total= ObjectsTotal();
   
   for (int i= obj_total; i>=0; i--) {
      string name= ObjectName(i);
    
      if (StringSubstr(name,0,7)=="[PIVOT]") 
         ObjectDelete(name);
   }
   
   return(0);
}
  
//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int start()
{
   static datetime timelastupdate= 0;
   static datetime lasttimeframe= 0;
   
   datetime startofday= 0,
            startofyesterday= 0;

   double today_high= 0,
            today_low= 0,
            today_open= 0,
            yesterday_high= 0,
            yesterday_open= 0,
            yesterday_low= 0,
            yesterday_close= 0;

   int idxfirstbaroftoday= 0,
       idxfirstbarofyesterday= 0,
       idxlastbarofyesterday= 0;

   
   // no need to update these buggers too often   
   if (CurTime()-timelastupdate < 600 && Period()==lasttimeframe)
      return (0);
      
   lasttimeframe= Period();
   timelastupdate= CurTime();
   
   //---- 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(iTime(NULL, PERIOD_H1, 0)));
      Print("Dest  time current bar: ", TimeToStr(iTime(NULL, PERIOD_H1, 0)- (LocalTimeZone - DestTimeZone)*3600), ", tzdiff= ", LocalTimeZone - DestTimeZone);
   }


   // let's find out which hour bars make today and yesterday
   ComputeDayIndices(LocalTimeZone, DestTimeZone, idxfirstbaroftoday, idxfirstbarofyesterday, idxlastbarofyesterday);

   startofday= iTime(NULL, PERIOD_H1, idxfirstbaroftoday);  // datetime (x-value) for labes on horizontal bars
   startofyesterday= iTime(NULL, PERIOD_H1, idxfirstbarofyesterday);  // datetime (x-value) for labes on horizontal bars

   

   // 
   // walk forward through yestday's start and collect high/lows within the same day
   //
   yesterday_high= -99999;  // not high enough to remain alltime high
   yesterday_low=  +99999;  // not low enough to remain alltime low
   
   for (int idxbar= idxfirstbarofyesterday; idxbar>=idxlastbarofyesterday; idxbar--) {

      if (yesterday_open==0)  // grab first value for open
         yesterday_open= iOpen(NULL, PERIOD_H1, idxbar);                      
      
      yesterday_high= MathMax(iHigh(NULL, PERIOD_H1, idxbar), yesterday_high);
      yesterday_low= MathMin(iLow(NULL, PERIOD_H1, idxbar), yesterday_low);
      
      // overwrite close in loop until we leave with the last iteration's value
      yesterday_close= iClose(NULL, PERIOD_H1, idxbar);
   }


   // 
   // walk forward through today and collect high/lows within the same day
   //
   today_open= iOpen(NULL, PERIOD_H1, idxfirstbaroftoday);  // should be open of today start trading hour

   today_high= -99999; // not high enough to remain alltime high
   today_low=  +99999; // not low enough to remain alltime low
   for (int j= idxfirstbaroftoday; j>=0; j--) {
      today_high= MathMax(today_high, iHigh(NULL, PERIOD_H1, j));
      today_low= MathMin(today_low, iLow(NULL, PERIOD_H1, j));
   }

   //
   //---- Calculate Levels
   //
   double p, q, d, r1,r2,r3, s1,s2,s3;
   
   d = (today_high - today_low);
   q = (yesterday_high - yesterday_low);
   p = (yesterday_high + yesterday_low + yesterday_close) / 3;
   
   r1 = (2*p)-yesterday_low;
   r2 = p+(yesterday_high - yesterday_low);              //	r2 = p-s1+r1;
	r3 = (2*p)+(yesterday_high-(2*yesterday_low));
   s1 = (2*p)-yesterday_high;
   s2 = p-(yesterday_high - yesterday_low);              //	s2 = p-r1+s1;
	s3 = (2*p)-((2* yesterday_high)-yesterday_low);


   //---- High/Low, Open
   if (ShowHighLowOpen) {
      SetLevel("YH", yesterday_high,  C'120,64,17', LineStyleY, startofyesterday);
      SetLevel("YL", yesterday_low,   C'120,64,17', LineStyleY, startofyesterday);
   }

   //---- High/Low, Open
   if (ShowSweetSpots) {
      int ssp1, ssp2;
      double ds1, ds2;
      
      ssp1= Bid / Point;
      ssp1= ssp1 - ssp1%50;
      ssp2= ssp1 + 50;
      
      ds1= ssp1*Point;
      ds2= ssp2*Point;
      
      SetLevel(DoubleToStr(ds1,Digits), ds1,  Purple, LineStyle, Time[10]);
      SetLevel(DoubleToStr(ds2,Digits), ds2,  Purple, LineStyle, Time[10]);
   }

   //---- Pivot Lines
   if (ShowPivots==true) {
      SetLevel("R1", r1,      C'155,6,6', LineStyleSR, startofday);
      SetLevel("R2", r2,      C'155,6,6', LineStyleSR, startofday);
      SetLevel("R3", r3,      C'155,6,6', LineStyleSR, startofday);
      
      SetLevel("PV", p,       C'150,6,150', LineStyleP, startofday);

      SetLevel("S1", s1,      DarkGreen, LineStyleSR, startofday);
      SetLevel("S2", s2,      DarkGreen, LineStyleSR, startofday);
      SetLevel("S3", s3,      DarkGreen, LineStyleSR, startofday);
   }
   
   //---- Fibos of yesterday's range
   if (ShowFibos) {
      // .618, .5 and .382
      SetLevel("L62", yesterday_low - q*0.618,      C'75,75,75', LineStyle, startofday);
      SetLevel("L38", yesterday_low - q*0.382,      C'75,75,75', LineStyle, startofday);
      SetLevel("LH5", yesterday_low + q*0.5,        C'75,75,75', LineStyle, startofday);
      SetLevel("H38", yesterday_high + q*0.382,     C'75,75,75', LineStyle, startofday);
      SetLevel("H62", yesterday_high +  q*0.618,    C'75,75,75', LineStyle, startofday);
   }


   //----- Camarilla Lines
   if (ShowCamarilla==true) {
      
      double h4,h3,l4,l3;
	   h4 = (q*0.55)+yesterday_close;
	   h3 = (q*0.27)+yesterday_close;
	   l3 = yesterday_close-(q*0.27);	
	   l4 = yesterday_close-(q*0.55);	
	   
      SetLevel("H3", h3,   DarkSlateBlue, LineStyle, startofday);
      SetLevel("H4", h4,   DarkSlateBlue, LineStyle, startofday);
      SetLevel("L3", l3,   DarkSlateBlue, LineStyle, startofday);
      SetLevel("L4", l4,   DarkSlateBlue, LineStyle, startofday);
   }


   //------ Midpoints Pivots 
   if (ShowMidPitvot==true) {
      // mid levels between pivots
      SetLevel("mR3", (r2+r3)/2,    C'75,75,85', LineStyle, startofday);
      SetLevel("mR2", (r1+r2)/2,    C'75,75,85', LineStyle, startofday);
      SetLevel("mR1", (p+r1)/2,     C'75,75,85', LineStyle, startofday);
      SetLevel("mS1", (p+s1)/2,     C'75,75,85', LineStyle, startofday);
      SetLevel("mS2", (s1+s2)/2,    C'75,75,85', LineStyle, startofday);
      SetLevel("mS3", (s2+s3)/2,    C'75,75,85', LineStyle, startofday);
   }


   //------ Comment for upper left corner
   if (ShowComment) {
      string comment; 
      
      comment= comment + "Range: Yesterday "+DoubleToStr(MathRound(q/Point),0)   +" pips, Today "+DoubleToStr(MathRound(d/Point),0)+" pips" + "\n";

      Comment(comment); 
   }

   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;
   
   int dayofweektoday= TimeDayOfWeek(iTime(NULL, PERIOD_H1, 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=1; i<=25; i++) {
      datetime timet= iTime(NULL, PERIOD_H1, i) - tzdiffsec;
      if (TimeDayOfWeek(timet)!=dayofweektoday) {
         idxfirstbaroftoday= i-1;
         break;
      }
   }
   

   // search  backwards for the first occrrence (backwards) of the weekday we are looking for (yesterday's last bar)
   for (int j= 0; j<=48; j++) {
      datetime timey= iTime(NULL, PERIOD_H1, 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<=24; j++) {
      datetime timey2= iTime(NULL, PERIOD_H1, 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(iTime(NULL, PERIOD_H1, idxfirstbaroftoday)), 
                                                      " (local time), idxbar= ", idxfirstbaroftoday);

      Print("Dest time zone\'s previous day starts:", TimeToStr(iTime(NULL, PERIOD_H1, idxfirstbarofyesterday)), 
                                                      " (local time), idxbar= ", idxfirstbarofyesterday);
      Print("Dest time zone\'s previous day ends:", TimeToStr(iTime(NULL, PERIOD_H1, idxlastbarofyesterday)), 
                                                      " (local time), idxbar= ", idxlastbarofyesterday);
   }
}


//+------------------------------------------------------------------+
//| Helper                                                           |
//+------------------------------------------------------------------+
void SetLevel(string text, double level, color col1, int linestyle, datetime startofday)
{
   int digits= Digits;
   string labelname= "[PIVOT] " + text + " Label",
          linename= "[PIVOT] " + text + " Line",
          pricelabel; 

   // create or move the horizontal line   
   if (ObjectFind(linename) != 0) {
      ObjectCreate(linename, OBJ_TREND, 0, startofday, level, Time[0],level);
      ObjectSet(linename, OBJPROP_STYLE, linestyle);
      ObjectSet(linename, OBJPROP_COLOR, col1);
   }
   else {
      ObjectMove(linename, 1, Time[0],level);
      ObjectMove(linename, 0, startofday, level);
   }
   

   // put a label on the line   
   if (ObjectFind(labelname) != 0) {
      ObjectCreate(labelname, OBJ_TEXT, 0, Time[BarForLabels], level);
   }
   else {
      ObjectMove(labelname, 0, Time[BarForLabels], level);
   }

   pricelabel= "                                                     " + text;
   if (ShowLevelPrices && StrToInteger(text)==0) 
      pricelabel= pricelabel + ": "+DoubleToStr(level, Digits);
   
   ObjectSetText(labelname, pricelabel, LabelsFontSize, "Arial", LabelsColor);
}