Discussing the article: "Feature Engineering for ML (Part 4): Implementing Time Features in MQL5"

 

Check out the new article: Feature Engineering for ML (Part 4): Implementing Time Features in MQL5.

Applying Python session boundaries to MQL5 broker timestamps misclassifies session membership by two to three hours on any non-UTC broker, corrupting session flags across the full backtest history. We implement CTimeFeatures.mqh, containing CRingBuffer and CTimeFeatures, with three EA-facing methods: Initialize (UTC offset capture and frequency gate configuration), Update (log return push to session-conditional ring buffers), and Calculate (cyclical encoding, session flags, and session volatility). The output is a flat double array drop-compatible with Python's get_time_features for sub-hourly, hourly, and daily timeframes.

Part 3 of this series built a Python function, get_time_features, that converts a DatetimeIndex into a structured feature matrix: Fourier-encoded cyclical variables for hour, day-of-week, and day-of-year; session membership flags for the four major forex trading sessions; a session overlap indicator; session-conditional rolling volatility; and calendar effects at period boundaries. The Python implementation operates on batch data with full vectorization. MQL5 operates bar by bar in real time.

This article implements the same feature set in MQL5 as a reusable include file, CTimeFeatures.mqh. Any EA can include it without modification. Three problems require solutions beyond the mechanical code translation. First, MQL5 provides broker time, not UTC — and most retail brokers offset their server clocks by two to three hours, which silently corrupts session boundary detection for every bar in the backtest. Second, Python computes rolling volatility in batch using pandas. In MQL5, volatility must be maintained incrementally per session using a circular buffer. Third, Python applies a frequency gate via a DataFrame.drop call. In MQL5, the gate must be set at initialization and mirrored in the feature-name registry used by downstream ONNX models.

The resulting class exposes three EA-facing methods — Initialize, Update, and Calculate — and produces a flat double array whose feature names and column order are identical to those of get_time_features. A model trained in Python on the Python features can be deployed in MQL5 via OnnxRun by passing the array from Calculate without any reordering.

Author: Patrick Murimi Njoroge