| # Article-24340-ONNX-Models-Python-Training-And-Live-MQL5
|
|
|
| This repository is an article-derived reference project based on the original MQL5 article. It does not claim to reproduce the full original source code unless files are explicitly attached.
|
|
|
| 
|
|
|
| ## Overview
|
|
|
| This reference project is derived from an MQL5 article demonstrating an end-to-end machine learning pipeline: retrieve MetaTrader 5 price history, train a neural network in Python, export it to ONNX, and run inference on closed bars in MQL5.
|
|
|
| The central objective is verification rather than profitability. The article checks that Python and MQL5 construct matching inputs, compares ONNX inference with a manual forward pass through parsed weights, and benchmarks held-out trading results against directional and chance baselines.
|
|
|
| The reported model demonstrates a working pipeline, **not a profitable trading edge**.
|
|
|
| ## Original Article
|
|
|
| - **Article ID:** 24340
|
| - **Title:** Working with ONNX Models in MQL5 (Part 4): Training a Model in Python and Running It Live in MQL5
|
| - **Author:** Allan Munene Mutiiria
|
| - **Publication date:** Not available
|
| - **Category:** Machine Learning
|
| - **Article:** https://www.mql5.com/en/articles/24340
|
| - **Author profile:** https://www.mql5.com/en/users/29210372
|
|
|
| ## Repository Purpose
|
|
|
| This repository documents the article’s architecture and provides a reference for reconstructing or studying the workflow using the author-provided files.
|
|
|
| Readers can learn how to:
|
|
|
| - Build price-level-independent market features.
|
| - Train and export a small PyTorch classifier for MQL5 inference.
|
| - Preserve feature formulas, ordering, and normalization across languages.
|
| - Validate raw inputs using timestamped proof data.
|
| - Inspect intermediate neuron activations and check inference agreement.
|
| - Separate classification performance from trading performance after costs.
|
|
|
| The viewer builds on the parser and visualization work introduced in [Part 3](https://www.mql5.com/en/articles/24337).
|
|
|
| ## Key Concepts
|
|
|
| - Machine Learning
|
| - Python–MetaTrader 5 data integration
|
| - ONNX export and native MQL5 inference
|
| - Volatility-normalized feature engineering
|
| - Volatility-scaled barrier labeling
|
| - Chronological training, validation, and test splits
|
| - Training-only standardization and early stopping
|
| - Cross-language numerical verification
|
| - Neural network activation visualization
|
| - Out-of-sample evaluation and baseline comparisons
|
|
|
| ## Algorithm / Architecture Summary
|
|
|
| 1. **Retrieve broker history.**
|
| Python connects to an open, logged-in terminal through the `MetaTrader5` package. The example requests `XAUUSDm` M15 history and estimates typical trading spread from historical bars.
|
|
|
| 2. **Construct 16 features.**
|
| Inputs include five momentum measurements, positions within 20- and 50-bar ranges, relative volatility, body and wick proportions, distances from moving averages, moving-average separation, and sine/cosine encoding of the bar’s opening hour.
|
|
|
| 3. **Assign three outcome labels.**
|
| Upper and lower barriers are placed at `2.5 ×` the 14-bar mean true range from the current close. The next 33 bars determine down, flat, or up. If both barriers are touched within one bar, the upper barrier takes precedence.
|
|
|
| 4. **Split and normalize the data.**
|
| The chronological allocation is 65% training, 15% validation, and 20% testing. Feature means and standard deviations are calculated from training data only.
|
|
|
| 5. **Train and export the network.**
|
| The dense architecture is **16 → 24 → 12 → 3**, with ReLU hidden activations and a Softmax output. Validation performance selects the retained weights; training stops after 40 epochs without improvement. Export uses ONNX opset 13 and the legacy PyTorch tracing path.
|
|
|
| 6. **Verify MQL5 feature reconstruction.**
|
| `COmvFeatures` reproduces the Python formulas, including rolling true-range averages and EMA initialization. A separate checker compares timestamped raw features against Python’s proof CSV, using a default tolerance of `1e-6`.
|
|
|
| 7. **Run inference once per closed bar.**
|
| `COmvRunner` keeps the model open, loads its scaling data, standardizes inputs, and calls `OnnxRun` with input shape `[1, 16]` and output shape `[1, 3]`.
|
|
|
| 8. **Inspect and cross-check activations.**
|
| The viewer performs a second forward pass through parsed weights to populate hidden neurons. Its output is compared with native ONNX inference using an agreement threshold of `1e-4`. Neuron brightness is scaled within each layer.
|
|
|
| **Environment:** The workflow requires MetaTrader 5 with available history, Python with PyTorch, NumPy, and the `MetaTrader5` package, plus the viewer components described by the article.
|
|
|
| ## Mentioned or Attached Files
|
|
|
| ### Author-listed attachments
|
|
|
| An attached ZIP archive is available according to the article metadata. The article’s attachment table lists the following files; the downloaded archive contents were not independently inspected in the processed input.
|
|
|
| | File | Role |
|
| |---|---|
|
| | `make_model.py` | Retrieves history, builds features and labels, trains the network, evaluates results, and exports artifacts. |
|
| | `OMV Protobuf.mqh` | Protobuf wire-format constants and byte decoding. |
|
| | `OMV Model.mqh` | ONNX model structures and parser. |
|
| | `OMV Canvas.mqh` | Drawing surface and rendering utilities. |
|
| | `OMV Features.mqh` | MQL5 reconstruction of the 16 input features. |
|
| | `OMV Panel.mqh` | Viewer layout, model execution, manual forward pass, and activation rendering. |
|
| | `ONNX Feature Check Part 4.mq5` | Expert Advisor for timestamped feature comparisons. |
|
| | `ONNX Model Viewer Part 4.mq5` | Main viewer Expert Advisor and event forwarding. |
|
| | `MQL5.zip` | Ready-to-extract archive described by the author. |
|
|
|
| The article instructs users to extract `MQL5.zip` into the terminal data folder. It describes the code location as `MQL5\Experts\ONNX Model Viewer Part 4\` and the Python script location as `MQL5\Files\ONNX Model Viewer Part 4`.
|
|
|
| ### Mentioned generated artifacts
|
|
|
| - `model.onnx` — exported trained network.
|
| - `model_proof.csv` — timestamped raw features for comparison.
|
| - A scaling file containing training means and standard deviations; its filename is not provided in the supplied text.
|
|
|
| These generated artifacts are not confirmed as present in this repository.
|
|
|
| ## Statistics
|
|
|
| ### Content and repository metrics
|
|
|
| | Metric | Value |
|
| |---|---|
|
| | Word count | Not available |
|
| | Reading time | Not available |
|
| | Image count | Not available |
|
| | Code block count | Not available |
|
| | Verified repository file count | Not available |
|
|
|
| ### Article-reported experimental results
|
|
|
| These are reported outcomes, not independently reproduced repository results.
|
|
|
| | Metric | Reported value |
|
| |---|---|
|
| | Dataset | 121,687 bars covering 8.0 years |
|
| | Training / validation / test bars | 79,041 / 18,241 / 24,321 |
|
| | Training stopped / retained epoch | 58 / 18 |
|
| | Feature verification | All 300 proof bars matched |
|
| | Largest raw feature difference | `5.01e-10` |
|
| | Test score averaged over three classes | 45.71%, versus a 33.33% chance baseline |
|
| | Up-call trades | 499, with a 49.9% win rate |
|
| | Up-call average result after spread | −0.422 price units per trade |
|
| | Down-call average result after spread | −0.867 price units per trade |
|
| | Always-long / always-short baseline | −0.289 / −0.511 price units per trade |
|
|
|
| ## Tags
|
|
|
| `mql5` `metatrader-5` `machine-learning` `difficulty-advanced`
|
|
|
| ## Difficulty
|
|
|
| **Advanced**
|
|
|
| The workflow combines Python training, ONNX export, custom MQL5 feature reconstruction, model parsing, numerical validation, and interactive visualization. It also requires careful handling of temporal leakage and trading evaluation.
|
|
|
| ## Limitations
|
|
|
| - The processed input contains article excerpts and an attachment listing, not an inspected complete source tree. Full original source availability within this repository is therefore unverified.
|
| - Reconstruction and execution depend on files actually attached or provided by the author, including the earlier viewer components.
|
| - The chronological splits retain overlapping label horizons at their boundaries. The article recommends removing 33 bars on each side of each boundary for stricter separation.
|
| - Same-bar barrier ambiguity is resolved in favor of the upper barrier rather than reconstructed from intrabar prices.
|
| - Results cover one symbol, one timeframe, and one forward split. Broker history and symbol naming may differ.
|
| - Cost estimates use typical spread only; other execution costs are not modeled.
|
| - Softmax outputs are not calibrated probabilities.
|
| - The reported signals lost money after spread. Walk-forward evaluation across additional symbols and periods is needed before considering trading use.
|
| - This is an educational reference, not a production-ready trading system or investment recommendation.
|
|
|
| ## Reference
|
|
|
| - [Original article](https://www.mql5.com/en/articles/24340)
|
| - [Allan Munene Mutiiria — author profile](https://www.mql5.com/en/users/29210372)
|
| - [Previous article: Part 3](https://www.mql5.com/en/articles/24337)
|