MQL5 - Day of Week

 

Hello,

I would like to calculate yesterday and the day before yesterday dates. I use the below code for that. Yesterday (d_tarih) works well however the day before yesterday (e_tarih) also gives the same value.

Is there a way to calculate yesterday and the day before yesterday more smartly and correctly? I also don't want it to count Sunday and Saturday, the dates must be trading dates.

Thanks in advance

   string b_tarih_str = TimeToString(TimeCurrent(),TIME_DATE);
   datetime b_tarih = StringToTime(b_tarih_str);      // today              
   datetime d_tarih = b_tarih-1;       // yesterday
   datetime e_tarih = b_tarih-2;       // the day before yesterday

   Print("yesterday = ",d_tarih,"  the day before = ",e_tarih);

   MqlDateTime dow;
   TimeCurrent(dow);
   
   
   if(dow.day_of_week==1) { b_tarih=b_tarih-2;e_tarih=e_tarih-2;}
   if(dow.day_of_week==2) { e_tarih=e_tarih-2;}
 
Solved!
 
  datetime b_tarih = StringToTime(b_tarih_str);      // today              
  datetime d_tarih = b_tarih-1;       // yesterday
  datetime e_tarih = b_tarih-2;       // the day before yesterday
Wrong! d_tarih is only one second earlier. e_tarith is only 2 seconds earlier (definitely not the day before yesterday.)

Secondly you do not want yesterday, you want the previous trading day (not weekends and market holidays.)
#define HR2400 86400
#define SECONDS uint
SECONDS    time(datetime when=0){
      return SECONDS(when == 0 ? TimeCurrent() : when) % HR2400;               }
datetime   date(datetime when=0){
      return datetime( (when == 0 ? TimeCurrent() : when) - time(when) );      }
bool download_history(
      ENUM_TIMEFRAMES   period=PERIOD_CURRENT)  /**< Standard timeframe. */{
      return download_history(_Symbol, period);
}
#define SYMBOL string
bool download_history(
      SYMBOL            symbol,                 ///< The symbol required.
      ENUM_TIMEFRAMES   period=PERIOD_CURRENT)  /**< Standard timeframe. */{
   if(period == PERIOD_CURRENT)  period = ENUM_TIMEFRAMES(_Period);
   ResetLastError();
   datetime other = iTime(symbol, period, 0);
   return _LastError == 0;
}

datetime   tomorrow( datetime when=0){   // Weekends not accounted
      return date(when) + HR2400;                                              }
/// Returns previous trading day.
datetime   yesterday(datetime when=0)    /**< Previous relative to
                                          * when. */{
   if(when==0) when = TimeCurrent();
   // Make sure I have daily history.
   while(!download_history(_Symbol, PERIOD_D1) ){  Sleep(1000); RefreshRates(); }
   INDEX    iD1   = iBarShift(NULL, PERIOD_D1,  when);   // Find today.
   return iTime(NULL, PERIOD_D1, iD1 + 1);               // Return yesterday.
}
Reason: