MQL4 and 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
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.
preview
From Polling to Events: Building a Reactive MQL5 Trading System with Python and Redis Streams

From Polling to Events: Building a Reactive MQL5 Trading System with Python and Redis Streams

An Expert Advisor that takes signals from an external process must know which messages were delivered, which were acknowledged, and which orders reached the broker. This article builds that confirmation protocol on Redis Streams: MQL5 publishes market events, Python suggests trades, and MQL5 alone decides what is executed. Live tests on a demo account show duplicate detection, guard refusals, and dead-lettering; crash recovery is verified with unit tests.
preview
From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI

From Evidence to Execution (Part 1): How to Log, Measure, and Decode a Trading Strategy Inside MetaTrader 5 AI

An evidence-first workflow for Range Breakout in MQL5: a non-trading logger captures session/time windows and records 61 fields per breakout to CSV, with a strict split between entry features and hindsight labels. The MT5 AI Assistant processes the dataset in nine phases, helping validate data, quantify baselines, and locate stable, entry-usable thresholds for subsequent EA coding.
preview
Archimedes Optimization Algorithm (AOA)

Archimedes Optimization Algorithm (AOA)

The article examines the Archimedes Optimization Algorithm — a metaheuristic in which an agent is represented as a physical object with density, volume, and acceleration, and the search itself is reinterpreted as the tendency of bodies submerged in a fluid to reach equilibrium. The balance between exploration and exploitation is not dictated by an external schedule here, but rather stems from the physics of decaying turbulence. We will implement the algorithm in MQL5, test it on a standard test bench, and analyze where this approach works.
preview
Andean Condor Algorithm (ACA)

Andean Condor Algorithm (ACA)

The article implements the Andean Condor Algorithm (ACA) for MQL5 — a compact optimizer with a multiscale intensification operator. A significant improvement in solution quality was observed with a small population: a single adjustment to the settings propels it into the top 45 — and behind this lies a distinctive feature of the algorithm worth knowing about. This resource provides ready-to-use code and practical guidelines for its application.
preview
Entropy Pooling and Scenario Budgets for Expected-Shortfall Sizing

Entropy Pooling and Scenario Budgets for Expected-Shortfall Sizing

Rolling lookback windows implicitly fix a probability vector over past bars. We implement entropy pooling in MQL5 to keep all historical scenarios, reweight them by conditioning on today's volatility under an effective‑scenarios budget, and add views on volatility, tails and correlation. A walk‑forward test, a chart indicator and an ES‑based sizing EA demonstrate how to calibrate risk forecasts and position size to the current regime.
preview
MetaTrader 5 Machine Learning Blueprint (Part 24): Sequence Risk

MetaTrader 5 Machine Learning Blueprint (Part 24): Sequence Risk

Realized backtests reflect a single ordering of trades, so their maximum drawdown and prop‑firm breach risk are often understated. We resequence trade returns via a stationary bootstrap with a derived block length to estimate the drawdown distribution and a sequence risk ratio, compute path‑dependent breach probabilities for drawdown and daily‑loss limits, and replace WFE with a paired IS–OOS degradation statistic. The tools are demonstrated on a real EURUSD RSI strategy to guide sizing and risk limits.
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 6): A Constant-Dollar Exposure FX Trading System Based on Fixed-Income Interest Rate Yield Differentials

Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 6): A Constant-Dollar Exposure FX Trading System Based on Fixed-Income Interest Rate Yield Differentials

We describe ANANTA, a rules-based FX portfolio model that measures deviations in Interest Rate Swap differentials via moving averages and rebalances constant-dollar exposure across G10 currencies. Designed for intraday operation, it complements or substitutes carry logic without relying on trade volume. Performance is examined from January 2020 to October 2026 for five of the most liquid currencies. Code and free data pipelines are included.
preview
Neural Networks in Trading: Recurrent Modeling of Market Micromovements (EV-MGRFlowNet)

Neural Networks in Trading: Recurrent Modeling of Market Micromovements (EV-MGRFlowNet)

The article discusses the adaptation of the EV-MGRFlowNet architecture — originally developed for processing event-based video data — to the field of financial time series. The approach presented here offers a new perspective on the market as a stream of micro-movements, where price, volume, and liquidity form a dynamic structure that lends itself to recurrent analysis without explicit supervision.
preview
Building a Two-Pole Momentum Oscillator in MQL5

Building a Two-Pole Momentum Oscillator in MQL5

We build a Two‑Pole Momentum Oscillator in MQL5 that measures deviation from a 25‑period SMA, normalizes it by its mean and standard deviation, and smooths the result with two EMA‑style passes. The code defines inputs, buffers, warm‑up and recalculation logic, signal rules, and colorized plots, and derives dynamic targets from the 100‑period average range. It helps detect momentum shifts around the zero line and display price levels tied to recent volatility.
preview
Weibull Reliability Analysis for Strategy Lifespan: Estimating When an EA Is Likely to "Fail"

Weibull Reliability Analysis for Strategy Lifespan: Estimating When an EA Is Likely to "Fail"

We implement a native Weibull maximum-likelihood fit in MQL5 and use it to model strategy wear-out from trade history. Failures are defined as the rolling profit factor dropping below a floor, producing lifetimes in trades. The article wires a survival-based governor into an EA and a companion indicator, so you can estimate conditional survival over the next N trades and apply explicit retirement thresholds with cooldown.
preview
Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts

Building a FIFO-Compliant Position Management Layer for NFA-Regulated MQL5 Accounts

This article shows how to make EA close operations comply with broker-enforced FIFO (ACCOUNT FIFO CLOSE) on hedging accounts, so naive exits stop failing. It introduces CFifoPositionQueue to order an EA's own tickets by time and CFifoComplianceGuard to execute closes in two modes: strict reject or auto-cascade, with optional per-direction scope. The guard re-verifies eligibility before each step, normalizes volumes, and inspects real server retcodes. You get reusable code, tests, and clear limits.
preview
Uncertainty as a Model (Part 6): Multiple Regression and Diagnostics

Uncertainty as a Model (Part 6): Multiple Regression and Diagnostics

A practical introduction to multiple regression with deterministic factors for financial time series. Topics covered include the formulation and matrix form of ordinary least squares (OLS), residual diagnostics, EDA/CDA, R-squared and adjusted R-squared, the F-test, RESET, the Breusch–Pagan test, VIF, and Cook’s distance. Techniques for working with regressors are demonstrated: dummy variables, nonlinear transformations, and interaction terms. Examples involving trends, days of the week, and news help select factors and build models suitable for forecasting.
preview
How to Implement R/S Analysis and the Hurst Indicator in MQL5

How to Implement R/S Analysis and the Hurst Indicator in MQL5

The Hurst exponent indicator for MQL5 is based on R/S analysis using OLS regression in log-log space. The theoretical basis is the findings of Gatheral–Jaisson–Rosenbaum (2014), according to which volatility follows fractional Brownian motion with H ≈ 0.10. The indicator estimates H within a moving window, identifies anti-persistent (H < 0.3), neutral, and trending (H > 0.5) market regimes, colors the line, and triggers an alert upon a regime change, helping you choose a strategy type and manage risk.
preview
Per-Setup Trade Ledger in MQL5: Find Out Which of Your EA's Entries Is Losing Money

Per-Setup Trade Ledger in MQL5: Find Out Which of Your EA's Entries Is Losing Money

Most EAs trade more than one setup, yet the Strategy Tester judges them all by a single equity curve. CSetupLedger is a small MQL5 class that stores each trade's setup in its magic number and rebuilds the per-setup record from the account's deal history, so a restart never wipes it. It compares a Wilson interval of each setup's win rate with the breakeven rate implied by that setup's own average win and loss, and gives no verdict before 30 closed trades. Each setup ends up trusted, rejected or still undecided. In two backtests the per-setup totals match the tester exactly. Full source and two working EAs are attached.
preview
Property-Based Testing for Trading Rules in MQL5 (Part 1): Generate Market Scenarios, Test Invariants, Find Edge Cases

Property-Based Testing for Trading Rules in MQL5 (Part 1): Generate Market Scenarios, Test Invariants, Find Edge Cases

Property-based tests exercise a sizing rule across thousands of generated scenarios instead of a few hand-picked cases. A deterministic MQL5 runner creates seeded symbol contracts, checks eight risk-volume properties, and writes text and CSV reports for reproducible evidence. A second script intentionally rounds volume the wrong way, replays the failing seed, and shrinks the counterexample to the half-step boundary, making the defect minimal and diagnosable.
preview
Neural Networks in Practice: When to Use an Artificial Neuron and How It Works in MQL5

Neural Networks in Practice: When to Use an Artificial Neuron and How It Works in MQL5

We implemented a neuron in MQL5 that was trained using stochastic gradient descent and compared its loss function to that of linear regression. Using code and graphs, we demonstrate how normalization, the choice of learning rate, and the structure of the problem affect convergence. This article provides guidance on debugging the training process, interpreting error behavior, and selecting the appropriate architecture or activation function.
preview
From Basic to Intermediate: Subwindows (I)

From Basic to Intermediate: Subwindows (I)

In this article, we'll start exploring how to work with subwindows in MetaTrader 5 using MQL5. This is a broad topic with several practical aspects that may prove challenging, so we'll start with a brief introduction. And yet, dear reader, it’s important that you understand what we’re going to discuss here, because it could play an important role in your future.
preview
Neural Networks in Practice: Stochastic Gradient Descent

Neural Networks in Practice: Stochastic Gradient Descent

This article uses practical examples to explain how to calculate and apply gradients of the weights and bias (intercept) in a linear neuron implemented in MQL5, and also discusses a stochastic variant of gradient descent. We analyze stopping criteria, iteration limits, and the effects of training on data subsets. The results are displayed in the MetaTrader 5 terminal, where a simple chart is also plotted. Readers are invited to modify the training set and analyze the model's behavior.
preview
Neural Networks in Trading: Temporal Motion Aggregation (Conclusion)

Neural Networks in Trading: Temporal Motion Aggregation (Conclusion)

Introducing the TMA framework — an intelligent system capable of forecasting market dynamics with sufficient accuracy. In this article, we have integrated all the components into a single architecture and transformed it into a fully-fledged trading agent that analyzes the market and makes decisions in real time.
preview
Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)

Practical Modules from Other Languages in MQL5 (Part 09): MATPLOTLIB (II)

Learn how to create advanced visualizations in MetaTrader 5 using a Matplotlib-like API from MQL5 while Python handles rendering. We implement key chart types—scatter, bar, horizontal bar, histogram, pie, and hexbin—and show how to control axes, legends, colorbars, and styles. The result is a consistent workflow for exploring trading and financial datasets.
preview
Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier

Confident Learning: Finding Mislabeled Trades Before They Poison Your Classifier

The article focuses on label-auditing for meta-labeling, not on a new entry signal. It presents a native MQL5 implementation of confident learning with out-of-fold scoring and calibrated pruning, plus an EA switch that trains the meta-filter on raw or cleaned datasets. A controlled Strategy Tester comparison helps you quantify noise and choose a pruning level that preserves generalization.
preview
How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5

How to Replace a WebSocket EA with TradeMux REST in MetaTrader 5

The article continues the series on AI Hedge Fund and addresses three limitations of v4: analysts' reputation scores are now stored persistently in SQLite, the EA has been removed from the critical execution path, and signals from the council of fifteen are distributed to multiple brokers via the TradeMux REST API. The logic behind the council and risk management has remained the same: Python retrieves data via the MetaTrader 5 SDK and executes orders directly. The result is resilience to restarts and scalability across multiple terminals.
preview
Crypto Exchange Integration with MQL5 (Part 1): Connecting to MEXC Futures

Crypto Exchange Integration with MQL5 (Part 1): Connecting to MEXC Futures

This article introduces the foundations of connecting MetaTrader 5 to a cryptocurrency exchange using MQL5 and the MEXC Futures API. It covers terminal configuration, JSON response processing, WebRequest() execution and validation, and conversion of API data into native MQL5 types. Practical examples demonstrate retrieving and processing exchange data. These components establish the basis for a reusable MEXC Futures client, developed progressively throughout the series. The series focuses exclusively on exchange integration; how readers use the retrieved data remains outside its scope.