MT5 Session Overlap Trading Windows
Detecting session overlaps in MetaTrader 5 requires reliable hour extraction.
The deprecated TimeHour(datetime) function should be replaced with TimeToStruct
for modern builds.
Modern hour extraction
Instead of the deprecated call:
// Deprecated — do not use on modern builds
int hour = TimeHour(now);
Use the current standard:
datetime now = TimeCurrent();
MqlDateTime dt;
TimeToStruct(now, dt);
int hour = dt.hour;
Safe modulo handling for hour inputs
When calculating offsets or accepting user-defined hours, always wrap to the valid 0–23 range:
int offset = -5; // example negative shift
int targetHour = ((hour + offset) % 24 + 24) % 24; // Always 0–23
This handles negative values correctly, which is common when shifting across midnight.
Session overlap detector
//+------------------------------------------------------------------+
//| Session Overlap Detector |
//+------------------------------------------------------------------+
bool IsOverlapSession(int londonStart, int londonEnd,
int nyStart, int nyEnd)
{
datetime now = TimeCurrent();
MqlDateTime dt;
TimeToStruct(now, dt);
int h = dt.hour;
int ls = ((londonStart % 24) + 24) % 24;
int le = ((londonEnd % 24) + 24) % 24;
int ns = ((nyStart % 24) + 24) % 24;
int ne = ((nyEnd % 24) + 24) % 24;
bool londonActive = (ls < le) ? (h >= ls && h < le)
: (h >= ls || h < le);
bool nyActive = (ns < ne) ? (h >= ns && h < ne)
: (h >= ns || h < ne);
return londonActive && nyActive;
}
This pattern keeps your educational code copy-paste valid on current MetaTrader 5 builds.