//+------------------------------------------------------------------+
//|                                               SessionDayKey.mqh  |
//|       Computes which session-aligned day a timestamp belongs to  |
//+------------------------------------------------------------------+
#ifndef SESSIONDAYKEY_MQH
#define SESSIONDAYKEY_MQH

//+------------------------------------------------------------------+
//| CSessionDayKey                                                   |
//| Exposes one pure, directly testable method: Calculate().         |
//+------------------------------------------------------------------+
class CSessionDayKey
  {
public:
   static datetime   Calculate(const datetime bar_time,const int session_close_hour);
  };

//+--------------------------------------------------------------------+
//| CSessionDayKey::Calculate                                          |
//| Computes the session-aligned day key for bar_time using the        |
//| shift-truncate-restore technique: shift bar_time backward by the   |
//| session close offset, truncate to midnight on the shifted value,   |
//| then shift the truncated result forward by the same offset.        |
//| Assumptions: bar_time is a valid, non-negative datetime (seconds   |
//|              since 1970-01-01 UTC). session_close_hour is between  |
//|              0 and 23 inclusive, expressed as an offset from the   |
//|              terminal's own time handling for the price series     |
//|              being aggregated (that is, whatever time base         |
//|              CopyRates() returns for this symbol), not necessarily |
//|              true UTC if the broker's server time differs from it. |
//| Returns: a datetime representing the start of the session-aligned  |
//|          day that bar_time falls into. Two bar_time values that    |
//|          belong to the same session day always produce the exact   |
//|          same return value, which is what makes this function      |
//|          usable as a grouping key.                                 |
//+--------------------------------------------------------------------+
datetime CSessionDayKey::Calculate(const datetime bar_time,const int session_close_hour)
  {
//--- convert the session close hour into a seconds offset
   int offset_seconds=session_close_hour*3600;
//--- shift backward so the session boundary lines up with calendar midnight
   datetime shifted=bar_time-offset_seconds;
//--- truncate to midnight on the shifted value, discarding the time of day
   datetime truncated=shifted-(shifted%86400);
//--- shift forward by the same offset to restore the true session boundary
   datetime restored=truncated+offset_seconds;
   return(restored);
  }

#endif // SESSIONDAYKEY_MQH
//+--------------------------------------------------------------------+
