MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
preview
Creating Three-Dimensional Bars in MQL5

Creating Three-Dimensional Bars in MQL5

Migrating 3D bars from Python to native MQL5: instead of Plotly and a bridge to the terminal — a scene using CCanvas3D and DirectX 11 directly on the chart. Price, time, and tick volume are plotted along three axes; the geometry is assembled manually from vertices and triangles; and a mouse-controlled orbit camera allows interactive exploration without external dependencies.
preview
Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

Forecasting Realized Volatility with Option-Implied Variance for Multiple Instruments in MQL5

A published daily history of option-implied variance is combined with a broker symbol's daily bars to fit a HAR model of realized volatility in MQL5; the implied term enters the regression as a predictor, not as a ready-made forecast. Out-of-sample tests on four funds paired with their Cboe indices, ten US equities, and two broker symbols show where it improves the forecast. A background service refits on the broker's bars and draws a five-session price range on the chart, and a self-test matches independent C++ and Python implementations.
preview
Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

Model Drift Watchdog: PSI-Based Auto-Retrain Alerts via a Lightweight Webhook

This article implements a PSI-based drift watchdog for MQL5 EAs. It compares a feature and the model's predicted probability against a quantile-based reference using a rolling window at a configurable cadence, applies hysteresis to avoid flapping, and raises a webhook on state transitions. You get tested math, an audit CSV and a plotting indicator, plus tuning guidance for thresholds, window size, and cooldown.
preview
Neural Networks in Practice: Activation Functions

Neural Networks in Practice: Activation Functions

This is, without a doubt, the article I've enjoyed writing the most so far. In it, I showed that we don't really need anything special to achieve a certain goal. We can achieve this in various ways, provided we have the necessary knowledge and are willing to learn and dedicate ourselves to the task. I would like to express my heartfelt thanks to everyone who helped me choose these functions. The material presented here is intended solely for educational purposes. Under no circumstances should this be viewed as intended for anything other than teaching and studying the concepts presented.
preview
From Basic to Intermediate: Subwindows (IV)

From Basic to Intermediate: Subwindows (IV)

In this article, we'll see that things aren't quite what many people initially think they are. One of the most interesting aspects of programming is that we can guarantee that everything will always turn out exactly as we planned. So please read this article carefully to understand some of the most confusing concepts related to the use of subwindows. If you understand what is explained here, you'll be able to understand much of what we'll be doing next.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (Encoder)

The article presents an adaptation of the SDformerFlow framework that achieves high adaptability by integrating spiking attention with multi-window convolution and weighted summation of query elements. The architecture allows each attention head to learn its own parameters, which improves the model's accuracy and sensitivity to the structure of the data being analyzed.
preview
Native MQL5 Prometheus Exporter: Real-Time Observability for Live Trading Models

Native MQL5 Prometheus Exporter: Real-Time Observability for Live Trading Models

This article shows how to build a fully native MQL5 metrics pipeline for a live EA without DLLs or sidecar processes. It implements counters, gauges, and histograms, safe text/label encoding, and an HTTP client that pushes one exposition payload to a Prometheus Pushgateway on a timer. You will wire metrics into OnTick/OnTimer, export equity, drawdown, trade P&L, and latency, and learn configuration, testing, and limitations for reliable observability.
preview
Probabilistic Sharpe Ratio and Minimum Track Record Length from Deal History

Probabilistic Sharpe Ratio and Minimum Track Record Length from Deal History

The article delivers a practical PSR/MinTRL workflow in MQL5: construct returns from deal history, compute SR/skew/kurtosis, and evaluate normal CDF/quantile via rational approximations with runtime self-tests. We apply it in an EA and a script and validate across 12 Strategy Tester runs on three symbols. This lets you verify a Sharpe ratio against a benchmark and quantify how many trades your strategy still needs.
preview
TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

TradeMux as a Quant Backbone: Connecting Institutional Python Pipelines to Different Terminals and Brokers

The article describes TradeMux as a bridge between a Python pipeline and the MetaTrader 5 terminal for the seamless transfer of trading decisions without duplicating logic. The article examines a four-layer production architecture and a complete Python execution service: connection setup, reading account and position data, signal generation (including CatBoost), pre-trade risk control, kill_switch, and a supervisor. Practical benefits include cross-broker normalization (RoboForex, IC Markets, Alpari, OANDA) and scaling from a single account to multi-account broadcasting without changing the trading logic.
preview
Beluga Whale Optimization (BWO) Algorithm

Beluga Whale Optimization (BWO) Algorithm

A candidate for our ranking table is Beluga Whale Optimization, a metaheuristic based on three behavioral patterns of the beluga whale: pair swimming, hunting using Lévy flight, and population renewal through whale fall. During implementation, we discovered that the algorithm does not so much optimize as read the geometry of the test bench; we examine how this works and develop an honest, promising modification called BWOm.
preview
James-Stein Shrinkage: Estimating Many Numbers at Once, and Testing What It Buys

James-Stein Shrinkage: Estimating Many Numbers at Once, and Testing What It Buys

This article implements a James–Stein and empirical Bayes shrinkage library in MQL5, validates it against hand-checked arithmetic and a Python reference, and applies it to ten years of H1 data across eight symbols. It covers fixed-target and grand-mean forms, unequal variances with a fitted between-group spread, and a proportions wrapper. You finish with a reusable header, a reproducible test script, a walk-forward study, and a chart indicator that shrinks an hour-of-day table.
preview
Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

Integrating MQL5 with Data Processing Packages (Part 11): Multi-Timeframe Causality Detection using Granger Analysis

This article implements a multi‑timeframe Granger causality monitor for MetaTrader 5. A Jupyter notebook tests predefined timeframe pairs, selects lags, applies multiple‑testing control, and exports a calibration table. An MQL5 Expert Advisor reloads the setup, recomputes the F‑test live on rolling windows, and marks pairs VALID/INVALID to gate its vote‑based BUY/SELL generator. The workflow shows alignment rules, live/offline parity, and a filtered vs unfiltered comparison on EURUSD.
preview
Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

Developing a Quantitative Session Analysis Tool (Part 2): Building Universal Sessions and Analysing Session Relationships

The Session Analyzer is upgraded to define sessions by local market time and to translate those windows into broker/server time with date-aware DST logic. We describe the session model, broker offset treatment, and efficient bar selection, then add a relationship layer that measures temporal overlap, shared price range, range breaks, and size ratios. This provides a clear, reusable basis for session-based research and chart inspection
preview
Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

Building A Candlestick Trend Constraint Model (Part 13): Normalizing and Scoring Lower-Timeframe Trigger Quality

The EA now computes an equal-weight score at M1 confirmation from normalized body fraction, breakout relative to C's range, and elapsed time, while excursions are measured only afterward. We refine processing of closed minutes and export a typed CSV that distinguishes completed observations from snapshots. The result is a clearer, reproducible basis for analyzing confirmed-signal behavior.
preview
Neural Networks in Practice: ReLU Function Graph

Neural Networks in Practice: ReLU Function Graph

We will create an indicator written entirely in MQL5 to display the activation function and its derivative on the chart, using ReLU as an example. We will explain how derivatives affect the choice of activation function and what precautions are needed at nondifferentiable points. Readers will be able to interactively visualize the curves and gain a practical foundation for deciding when to use certain activation functions and when not to.
preview
From Basic to Intermediate: Subwindows (III)

From Basic to Intermediate: Subwindows (III)

This article takes a detailed look at using subwindows in MQL5 indicators: creating them, detecting instances, and preventing duplication. It also covers INDICATOR_SHORTNAME, querying information about chart windows and indicators, and the difference between displaying indicators in the main chart window and in a separate window. The article also shows how to set the height and boundaries of a subwindow to standardize the interface and simplify the placement of objects.
preview
Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)

Neural Networks in Trading: A Spiking Architecture for Spatio-Temporal Market Analysis (SDformerFlow)

The article presents an adaptation of the SDformerFlow spiking architecture for the task of dense analysis of price micro-movements. The spatio-temporal structure provides a high level of detail, while the spiking logic ensures computational efficiency and the ability to work with sparse, pulse-like data. As a result, traders gain access to a tool that detects even the slightest shifts in liquidity and provides the foundation for more accurate and consistent real-time decisions.
preview
Which Economic Releases Actually Move Your Symbol, and by How Much?

Which Economic Releases Actually Move Your Symbol, and by How Much?

A calendar release is not a category but a number against a consensus. In MQL5 we build a robust, standardized surprise (actual minus forecast scaled by each indicator's own dispersion), recover the broker's daylight saving schedule from price to anchor each release on the bar that moved, and regress price response by symbol and horizon. The result is a measurable profile in pips per sigma showing which events actually move your market.
preview
Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

Building AI-Powered Trading Systems in MQL5 (Part 13): Letting the Assistant Execute Trades Behind an Approval Card

We extend an MQL5 AI assistant from read-only tools to safe trade execution with a human-in-the-loop gate. The article defines action tools for placing, closing, modifying, and deleting trades and for drawing on the chart, validates each request, sizes volume to broker limits, and scopes ownership. We pause the tool loop behind an approval card, queue actions, and resume execution only after approval, which holds while auto-approval stays off, as it is by default.
preview
Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

Local Outlier Factor: Density-Based Anomaly Detection in Native MQL5

This article builds a native MQL5 LOF engine without DLLs, ALGLIB or ONNX. Bars are mapped to five standardized features; k‑NN reachability and density produce a scale‑free LOF score, and the alarm level is a moving quantile of the reference cloud. The score gates only new entries in an EMA‑cross EA, with an indicator for charting and a script for independent checks on XAUUSD, EURUSD and GBPUSD.
preview
Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

Weak Supervision for Traders: Combining Several Noisy Labeling Heuristics into One Probabilistic Label (Snorkel-Style)

The article builds an MQL5‑native weak‑labeling engine that infers per‑indicator trust from vote agreement, then fuses five noisy signals into P(Buy) using Expectation‑Maximization. We describe the EA architecture, rolling‑window refits, abstain handling, diagnostics, and a majority‑vote baseline used for comparison. Readers can reuse the EM library, swap in their own labeling functions, and obtain a transparent, probability‑based entry filter.
preview
Building a High-Volume Pivot Indicator in MQL5

Building a High-Volume Pivot Indicator in MQL5

This article presents a high-volume pivot indicator in MQL5 that identifies confirmed pivot highs and lows using surrounding price bars and normalized volume strength. It calculates rolling volume sums, determines a 95th-percentile volume reference, and filters pivot points based on their relative volume. The indicator uses ATR(500) to scale concentric rings around qualifying pivots and draws reaction levels, pivot markers, and formatted volume labels on the chart, helping you study high-volume pivot areas and their interaction with price structure and market volatility.
preview
Neural Networks in Practice: The Birth of C_Neuron

Neural Networks in Practice: The Birth of C_Neuron

This article demonstrates how to encapsulate a neuron in MQL5 using the C_Neuron class, with weights, a bias, and a parameter specifying the number of inputs. We will take a detailed look at how to compute the loss function based on the least squares method and how to organize training data in arrays. This makes it easy to change the inputs and repeat experiments without modifying the implementation.
preview
Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

Building a Divergence System (Part V): Adaptive Parabolic SAR Trailing Stop Utility

The article delivers AdaptivePSARTrail.mqh: a reusable header that lets an EA trail positions (its own or external, by symbol/magic) with an adaptive Parabolic SAR. The utility adapts the step from divergence, guards flips with a side check, and orders broker and improvement gates (stops/freeze, tick grid, break‑even, start and step thresholds). A calculation‑only build serves indicators, result codes aid logging, and a demo EA verifies the integration.
preview
MetaTrader 5 Machine Learning Blueprint (Part 26): Process Permutation

MetaTrader 5 Machine Learning Blueprint (Part 26): Process Permutation

We introduce the permutation process for backtest validation: permute bars, rerun the complete development process, and compare the observed Sharpe to the null distribution it produces. Outputs include one-sided p-values, robust z, and quantile confidence intervals, plus a spurious performance curve that quantifies selection versus trial budget. A cache-isolation check prevents false passes. The EURUSD H1 case shows how to set a tolerance and assess whether performance is distinguishable from selection.
preview
A Categorical Hidden Markov Model in MQL5

A Categorical Hidden Markov Model in MQL5

The article provides a detailed examination of the theoretical foundations and practical implementation of the hidden Markov model with categorical emissions (Categorical HMM) in the MQL5 language. Specific examples are used to demonstrate the processes of inference, iterative parameter learning, and online filtering, as well as the methodology for selecting the optimal model architecture based on the AIC/BIC information criteria.
preview
Active Learning: An EA That Only Asks for Human Confirmation on Its Most Uncertain Trades

Active Learning: An EA That Only Asks for Human Confirmation on Its Most Uncertain Trades

This article builds an uncertainty-based routing layer for an EA: an online logistic regression scores P(up), Shannon entropy measures uncertainty, and a streaming P² quantile enforces a fixed review budget. Signals auto-trade, auto-skip or go to a human checkpoint, replaced by proxy modes in the Strategy Tester. It is judged on a held-out window against a trade-everything baseline, matched-frequency and seeded controls, and an exact profit split. No edge is claimed.
preview
Efficient Volatility Estimation with Garman–Klass: From Theory to a Percentile-Based Trading Tool in MQL5

Efficient Volatility Estimation with Garman–Klass: From Theory to a Percentile-Based Trading Tool in MQL5

This article implements the Garman–Klass volatility estimator as an MQL5 indicator that uses OHLC data for higher statistical efficiency than close-to-close measures. A percentile-based squeeze/expansion detector produces breakout signals, and a companion Expert Advisor executes them via iCustom. Implementation details include series-aware indexing, recursive squeeze-state handling in indicator buffers, and a baseline-on-attach rule for the EA, giving a ready-to-use toolkit for volatility-regime trading.
preview
How to Build a 29-Pair Portfolio with an L1 Filter and VaR-based Allocation of Lots

How to Build a 29-Pair Portfolio with an L1 Filter and VaR-based Allocation of Lots

The article explores the practical application of the L1 Trend Filter for noise reduction and the construction of structural features suitable for live trading. The full workflow is presented: H1 data for 29 instruments from MetaTrader 5, causal filtering, CatBoost with a horizon of three L1 bars, rigorous walk-forward testing, and VaR-based allocation of lots. The reader is provided with a reproducible code pipeline and a portfolio evaluation methodology.
preview
Creating Custom Indicators in MQL5 (Part 13): An Accelerating Trend Stop Confirmed by VWAP

Creating Custom Indicators in MQL5 (Part 13): An Accelerating Trend Stop Confirmed by VWAP

We implement an adaptive trend stop indicator in MQL5 that reseeds on every flip, then accelerates toward price, with speed boosted by distance from VWAP and all distances scaled by ATR. The article covers the acceleration engine, the VWAP agreement filter that grades each flip, the anti-aliased stop line with its cloud, and persistent flip levels and arrows. The result highlights where the trend turned and whether VWAP agreed.
preview
MetaTrader 5 Machine Learning Blueprint (Part 25): Live Monitoring

MetaTrader 5 Machine Learning Blueprint (Part 25): Live Monitoring

The article shows why a fixed posterior threshold, checked trade by trade, lacks error control and retires healthy strategies far too often on a real EURUSD case. It introduces WinRateSPRT (with Page's CUSUM for continuous use) and a permutation-tested profit factor trend to cover distinct failure modes. LiveStrategyMonitor integrates both and reports a normalized retirement-progress measure for operational decisions.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Conclusion)

Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Conclusion)

The implementation of the EV-MGRFlowNet framework demonstrates its key advantages: modularity, resilience to market fluctuations, and the ability to develop strategies independently. These features make the framework a powerful tool for analysis, forecasting, and the development of autonomous trading strategies.
preview
Use of WinAPI—Implementing Text-to-Speech in MQL5

Use of WinAPI—Implementing Text-to-Speech in MQL5

This article presents a single MQL5 include file that adds runtime text-to-speech through Windows SAPI. The library starts a hidden PowerShell process through WinAPI and exposes one function, Speak(), with control of voice, speed, volume, XML tags, and a timeout. It also covers the limits: Windows only, DLL imports required, a blocking call, and refusal in indicators and the tester.
preview
From Novice to Expert: Using Market Structure to Validate RSI Signals

From Novice to Expert: Using Market Structure to Validate RSI Signals

Oscillator thresholds are often treated as direct reversal instructions, causing traders to sell strong bullish markets or buy persistent bearish declines too early. We develop an analytical Expert Advisor that interprets Relative Strength Index events through confirmed swing structure. The model distinguishes continuation, reversal, pending, and expired conditions by combining closed-bar RSI crossings with higher highs, higher lows, lower highs, lower lows, and breaks of structure. It displays each validated interpretation without placing trades.
preview
RSI Divergence Grid Expert Advisor with Risk Manager in MQL5

RSI Divergence Grid Expert Advisor with Risk Manager in MQL5

A simple grid trading strategy becomes a resilient system thanks to three components: an entry filter based on RSI divergence, a strict limit on the number of grid levels, and an independent risk manager that monitors equity on every tick and blocks trading when the daily limit or maximum drawdown is reached. The article examines the mathematics behind the classic martingale trap, the implementation of pivot point and RSI divergence detection in MQL5, the complete code for the CRiskManager class with protection against floating losses, and the architecture of the grid itself, with TP based on the weighted average entry price.
preview
Self-Optimizing Expert Advisors in MQL5 (Part 20): Causality Regularization With Time-Lagged Independent Components Analysis (3)

Self-Optimizing Expert Advisors in MQL5 (Part 20): Causality Regularization With Time-Lagged Independent Components Analysis (3)

The article presents a piecewise workflow that forecasts growth in ICA components as surrogate targets and then reconstructs smoothed returns from these forecasts. We analyze dominant-component effects and apply Shapley Additive Explanations to assess feature importance. The approach is implemented end to end, from data preparation to ONNX export and MQL5 integration, providing a practical pipeline for noise reduction and model interpretability.
preview
Markowitz Mean-Variance Optimization for MQL5: A Native Efficient-Frontier Portfolio Builder

Markowitz Mean-Variance Optimization for MQL5: A Native Efficient-Frontier Portfolio Builder

This article shows how to implement a native MQL5 portfolio optimizer for multi-symbol baskets. It derives a covariance matrix from bar log-returns, inverts it via Gauss–Jordan, and solves the global minimum-variance, tangency, and target-return portfolios without external libraries. You will build an EA that rebalances positions long-only with clip-and-renormalize and a read‑only dashboard that tracks drift versus targets, plus learn Strategy Tester setup and common pitfalls.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Encoder)

Neural Networks in Trading: Recurrent Modeling of Market Micromovements (Encoder)

The article takes readers deep into the heart of the EV-MGRFlowNet framework, showing how its architecture is applied in a practical implementation for financial forecasting tasks. Step by step, we build a carefully designed combination of modules capable of detecting subtle temporal patterns and translating them into meaningful market signals.
preview
From Basic to Intermediate: Subwindows (II)

From Basic to Intermediate: Subwindows (II)

This article examines the use of subwindows in MetaTrader 5 in detail and shows how the calculation direction in OnCalculate affects indicator buffers and the plotting of averages. Practical examples explain how indicators are linked using FIRST INDICATOR’S DATA and PREVIOUS INDICATOR’S DATA, the effect of cascading removal of dependent indicators, and how indicator_separate_window behaves. Readers will learn how to diagnose display issues and create indicators that work correctly in subwindows.
preview
Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test

Testing Random Walk vs Mean Reversion in MQL5: Implementing the Lo-MacKinlay Variance Ratio Test

Implements the Lo–MacKinlay Variance Ratio Test in MQL5 to assess serial dependence via random‑walk variance scaling. Provides a reusable CVarianceRatio class with classical (homoskedasticity) and heteroskedasticity‑robust statistics, plus a script that scans multiple horizons and logs VR and Z‑values. Shows how to embed the test in an Expert Advisor as a statistical gate for mean‑reversion logic.