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
Coral Reefs Optimization (CRO)

Coral Reefs Optimization (CRO)

The article presents a comprehensive analysis of the Coral Reef Optimization (CRO) algorithm, a metaheuristic method inspired by the biological processes of coral reef formation and development. The algorithm models key aspects of coral evolution: broadcast spawning, brooding, larval settlement, asexual reproduction, and competition for limited reef space. Particular attention is paid to the improved version of the algorithm.
preview
Creating Custom Indicators in MQL5 (Part 10): Enhancing the Footprint Chart with Per-Bar Volume Sentiment Information Box

Creating Custom Indicators in MQL5 (Part 10): Enhancing the Footprint Chart with Per-Bar Volume Sentiment Information Box

The article enhances an MQL5 footprint indicator with a compact box above each candle that summarizes net delta, total volume, and buy/sell percentages. We implement supersampled anti‑aliased rendering, rounded corners via arc and quadrilateral rasterization, and per‑pixel alpha compositing. Supporting utilities include ARGB conversion, scanline fills, and box‑filter downsampling. The box delivers fast sentiment reads that stay legible across zoom levels.
preview
Developing Market Entropy Indicator: Trading System Based on Information Theory

Developing Market Entropy Indicator: Trading System Based on Information Theory

This article explores the development of a Market Entropy Indicator based on principles from Information Theory to measure the uncertainty and information content within financial markets. By applying concepts such as Shannon Entropy to price movements, the indicator quantifies whether the market is structured (trending), transitioning, or chaotic.
preview
Introduction to MQL5 (Part 43): Beginner Guide to File Handling in MQL5 (V)

Introduction to MQL5 (Part 43): Beginner Guide to File Handling in MQL5 (V)

The article explains how to use MQL5 structures with binary files to persist Expert Advisor parameters. It covers defining structures, accessing members, and distinguishing simple from complex layouts, then writing and reading entire records using FileWriteStruct and FileReadStruct in FILE BIN mode. You will learn safe patterns for fixed-size data and how shared storage (FILE COMMON) enables reuse across sessions and terminals.
preview
Building a Research-Grounded Grid EA in MQL5: Why Most Grid EAs Fail and What Taranto Proved

Building a Research-Grounded Grid EA in MQL5: Why Most Grid EAs Fail and What Taranto Proved

This article implements a regime-adaptive grid trading EA based on the PhD research of Aldo Taranto. It presents a regime‑adaptive grid trading EA that constrains risk through restartable cycles and equity‑based safeguards. We explain why naive grids fail (variance growth and almost‑sure ruin), derive the loss formula for real‑time exposure, and implement regime‑aware gating, ATR‑dynamic spacing, and a live kill switch. Readers get the mathematical tools and production patterns needed to build, test, and operate a constrained grid safely.
preview
Neural Networks in Trading: Adaptive Detection of Market Anomalies (DADA)

Neural Networks in Trading: Adaptive Detection of Market Anomalies (DADA)

We invite you to get acquainted with the DADA framework, which is an innovative method for detecting anomalies in time series. It helps distinguish random fluctuations from suspicious deviations. Unlike traditional methods, DADA is flexible and adapts to different data. Instead of a fixed compression level, it uses several options and chooses the most appropriate one for each case.
preview
MetaTrader 5 Machine Learning Blueprint (Part 9): Integrating Bayesian HPO into the Production Pipeline

MetaTrader 5 Machine Learning Blueprint (Part 9): Integrating Bayesian HPO into the Production Pipeline

​This article integrates the Optuna hyperparameter optimization (HPO) backend into a unified ModelDevelopmentPipeline. It adds joint tuning of model hyperparameters and sample-weight schemes, early pruning with Hyperband, and crash-resistant SQLite study storage. The pipeline auto-detects primary vs. secondary models, prepends a fitted column-dropping preprocessor for safe inference, supports sequential bootstrapping, generates an Optuna report, and includes bid/ask and LearnedStrategy links. Readers get faster, resumable runs and deployable, self-contained models.
preview
Battle Royale Optimizer (BRO)

Battle Royale Optimizer (BRO)

The article explores the Battle Royale Optimizer algorithm — a metaheuristic in which solutions compete with their nearest neighbors, accumulate “damage,” are replaced when a threshold is exceeded, and periodically shrink the search space around the current best solution. It presents both pseudocode and an MQL5 implementation of the CAOBRO class, including neighbor search, movement toward the best solution, and an adaptive delta interval. Test results on the Hilly, Forest, and Megacity functions highlight the strengths and limitations of the approach. The reader is provided with a ready-to-use foundation for experimentation and tuning key parameters such as popSize and maxDamage.
preview
Creating Custom Indicators in MQL5 (Part 9): Order Flow Footprint Chart with Price Level Volume Tracking

Creating Custom Indicators in MQL5 (Part 9): Order Flow Footprint Chart with Price Level Volume Tracking

This article builds an order-flow footprint indicator in MQL5 that aggregates tick-by-tick volume into quantized price levels and supports Bid vs Ask and Delta display modes. A canvas overlay renders color-scaled volume text aligned with the candles and updates on every tick. You will learn sorting of price levels, max-value normalization for color mapping, and responsive redraws on zoom, scroll, and resize to read volume distribution and aggressor dominance inside each bar.
preview
From Novice to Expert: Detecting Liquidity Zone Flips Using MQL5

From Novice to Expert: Detecting Liquidity Zone Flips Using MQL5

This article presents an MQL5 indicator that detects and manages liquidity zone flips. It identifies supply and demand zones from higher timeframes using a base–impulse pattern, applies objective breakout and impulse thresholds, and flips zones automatically when structure changes. The result is a dynamic support‑resistance map that reduces manual redraws and gives you clear, actionable context for signals and retests.
preview
MQL5 Trading Tools (Part 25): Expanding to Multiple Distributions with Interactive Switching

MQL5 Trading Tools (Part 25): Expanding to Multiple Distributions with Interactive Switching

In this article, we expand the MQL5 graphing tool to support seventeen statistical distributions with interactive cycling via a header switch icon. We add type-specific data loading, discrete and continuous histogram computation, and theoretical density functions for each model, with dynamic titles, axis labels, and parameter panels that adapt automatically. The result lets you overlay distribution models on the same sample and compare fit across families without reloading the tool.
preview
Neural Networks in Trading: Dual Clustering of Multivariate Time Series (Final Part)

Neural Networks in Trading: Dual Clustering of Multivariate Time Series (Final Part)

We continue to implement approaches proposed vy the authors of the DUET framework, which offers an innovative approach to time series analysis, combining temporal and channel clustering to uncover hidden patterns in the analyzed data.
preview
The MQL5 Standard Library Explorer (Part 10): Polynomial Regression Channel

The MQL5 Standard Library Explorer (Part 10): Polynomial Regression Channel

Today, we explore another component of ALGLIB, leveraging its mathematical capabilities to develop a Polynomial Regression Channel indicator. By the end of this discussion, you will gain practical insights into indicator development using the MQL5 Standard Library, along with a fully functional, mathematically driven indicator source code.
preview
Neuro-Structural Trading Engine — NSTE (Part I): How to Build a Prop-Firm-Safe Multi-Account System

Neuro-Structural Trading Engine — NSTE (Part I): How to Build a Prop-Firm-Safe Multi-Account System

This article lays the system architecture for a multi‑account algorithmic trading setup that operates cryptocurrency CFDs on MetaTrader 5 while respecting prop‑firm constraints. It defines three core principles—fixed dollar risk, one script per account, and centralized configuration—then details the Python–MQL5 split, the 60‑second processing loop, and JSON-based signaling. Readers get practical lot‑size computation, safety checks, and position management patterns for reliable deployment.
preview
MQL5 Trading Tools (Part 24): Depth-Perception Upgrades with 3D Curves, Pan Mode, and ViewCube Navigation

MQL5 Trading Tools (Part 24): Depth-Perception Upgrades with 3D Curves, Pan Mode, and ViewCube Navigation

In this article, we enhance the 3D binomial distribution graphing tool in MQL5 by adding a segmented 3D curve for improved depth perception of the probability mass function, integrating pan mode for view target shifting, and implementing an interactive view cube with hover zones and animations for quick orientation changes. We incorporate clickable sub-zones on the view cube for faces, edges, and corners to animate camera transitions to standard views, while maintaining switchable 2D/3D modes, real-time updates, and customizable parameters for immersive probabilistic analysis in trading.
preview
Integrating MQL5 with Data Processing Packages (Part 8): Using Graph Neural Networks for Liquidity Zone Recognition

Integrating MQL5 with Data Processing Packages (Part 8): Using Graph Neural Networks for Liquidity Zone Recognition

This article shows how to represent market structure as a graph in MQL5, turning swing highs/lows into nodes with features and linking them by edges. It trains a Graph Neural Network to score potential liquidity zones, exports the model to ONNX, and runs real-time inference in an Expert Advisor. Readers learn how to build the data pipeline, integrate the model, visualize zones on the chart, and use the signals for rule-based execution.
preview
Price Action Analysis Toolkit Development (Part 64): Synchronizing Manually Drawn Trendlines with Automated Monitoring

Price Action Analysis Toolkit Development (Part 64): Synchronizing Manually Drawn Trendlines with Automated Monitoring

Monitoring manually drawn trendlines requires constant chart observation, which can cause important price interactions to be missed. This article develops a trendline monitoring Expert Advisor that synchronizes manually drawn trendlines with automated monitoring logic in MQL5, generating alerts when price approaches, touches, or breaks a monitored line.
preview
Larry Williams Market Secrets (Part 15): Trading Hidden Smash Day Reversals with Market Context

Larry Williams Market Secrets (Part 15): Trading Hidden Smash Day Reversals with Market Context

Build an MQL5 Expert Advisor that automates Larry Williams Hidden Smash Day reversals. It reads confirmed signals from a custom indicator, applies context filters (Supertrend alignment and optional trading‑day rules), and manages risk with stop‑loss models based on smash‑bar structure or ATR and a fixed or risk‑based position size. The result is a reproducible framework ready for testing and extension.
preview
MetaTrader 5 Machine Learning Blueprint (Part 8): Bayesian Hyperparameter Optimization with Purged Cross-Validation and Trial Pruning

MetaTrader 5 Machine Learning Blueprint (Part 8): Bayesian Hyperparameter Optimization with Purged Cross-Validation and Trial Pruning

GridSearchCV and RandomizedSearchCV share a fundamental limitation in financial ML: each trial is independent, so search quality does not improve with additional compute. This article integrates Optuna — using the Tree-structured Parzen Estimator — with PurgedKFold cross-validation, HyperbandPruner early stopping, and a dual-weight convention that separates training weights from evaluation weights. The result is a five-component system: an objective function with fold-level pruning, a suggestion layer that optimizes the weighting scheme jointly with model hyperparameters, a financially-calibrated pruner, a resumable SQLite-backed orchestrator, and a converter to scikit-learn cv_results_ format. The article also establishes the boundary — drawn from Timothy Masters — between statistical objectives where directed search is beneficial and financial objectives where it is harmful.
preview
From Novice to Expert: Enhancing Liquidity Strategies with Multi-Timeframe Structural Confirmation in MQL5

From Novice to Expert: Enhancing Liquidity Strategies with Multi-Timeframe Structural Confirmation in MQL5

The alignment of higher-timeframe liquidity structures with lower-timeframe reversal patterns can greatly influence both the likelihood and direction of the next price movement. By integrating structural liquidity zones from higher timeframes with precise reversal confirmations on lower timeframes, traders can improve entry timing and overall trade quality. This article demonstrates how to reinforce liquidity-based trading strategies through higher-timeframe structural confirmation—and how to implement this approach effectively using MQL5.
preview
Neural Networks in Trading: Dual Clustering of Multivariate Time Series (DUET)

Neural Networks in Trading: Dual Clustering of Multivariate Time Series (DUET)

The DUET framework offers an innovative approach to time series analysis, combining temporal and channel clustering to uncover hidden patterns in the analyzed data. This allows models to adapt to changes over time and improve forecasting quality by eliminating noise.
preview
Using the MQL5 Economic Calendar for News Filtering (Part 2): Stop Management Positions During News Releases

Using the MQL5 Economic Calendar for News Filtering (Part 2): Stop Management Positions During News Releases

In part 2, we extend the news filter to protect existing positions during news events. Instead of closing trades, we temporarily remove stop-loss and take-profit levels, storing them safely in memory. When the news window ends, stops are deterministically restored, adjusted if price has already crossed the original levels, while respecting broker minimum distance rules. The result is a mechanism that preserves trade integrity without interfering with entry logic, keeping the EA in control through volatility.
preview
Larry Williams Market Secrets (Part 14): Detecting Hidden Smash Day Reversals with a Custom Indicator

Larry Williams Market Secrets (Part 14): Detecting Hidden Smash Day Reversals with a Custom Indicator

This article develops a practical MQL5 indicator that identifies Hidden Smash Day bars by strict numeric criteria and optional confirmation on the following session. We cover detection routines, buffer registration, and plot configuration to place arrows at valid bars. The approach delivers stable, non-repainting signals for historical testing and real-time monitoring.
preview
Low-Frequency Quantitative Strategies in Metatrader 5: (Part 1) Setting Up An OLAP-Friendly Data Store

Low-Frequency Quantitative Strategies in Metatrader 5: (Part 1) Setting Up An OLAP-Friendly Data Store

The article outlines a practical data pipeline for quantitative analysis based on Parquet storage, Hive-style partitions, and DuckDB. It details migrating selected SQLite tables to Parquet, structuring market data by source, symbol, timeframe, and date, and querying it with SQL window functions. A Golden Cross example illustrates cross‑symbol evaluation of forward returns. Accompanying Python scripts handle data download, conversion, and execution.
preview
Unified Validation Pipeline Against Backtest Overfitting

Unified Validation Pipeline Against Backtest Overfitting

This article explains why standard walkforward and k-fold CV inflate results on financial data, then shows how to fix it. V-in-V enforces strict data partitions and anchored walkforward across windows, CPCV purges and embargoes leakage while aggregating path-wise performance, and CSCV measures the Probability of Backtest Overfitting. Practitioners gain a coherent framework to assess regime robustness and selection reliability.
preview
Graph Theory: Traversal Depth-First Search (DFS) Applied in Trading

Graph Theory: Traversal Depth-First Search (DFS) Applied in Trading

This article applies Depth-First Search to market structure by modeling swing highs and lows as graph nodes and tracking one structural path as deeply as conditions remain valid. When a key swing is broken, the algorithm backtracks and explores an alternative branch. Readers gain a practical framework to formalize structural bias and test whether the current path aligns with targets like liquidity pools or supply and demand zones.
preview
Engineering Trading Discipline into Code (Part 3): Enforcing Symbol-Level Trading Boundaries with a Whitelist System in MQL5

Engineering Trading Discipline into Code (Part 3): Enforcing Symbol-Level Trading Boundaries with a Whitelist System in MQL5

This article details an MQL5 framework that restricts trading to an approved set of symbols. The solution combines a shared library, a configuration dashboard, and an enforcement Expert Advisor that validates each trade against a whitelist and logs blocked attempts. It includes fully functional code examples, a clear explanation of the structural design decisions, and validation tests that confirm reliable symbol filtering, controlled market exposure, and transparent monitoring of rule enforcement.
preview
MQL5 Trading Tools (Part 23): Camera-Controlled, DirectX-Enabled 3D Graphs for Distribution Insights

MQL5 Trading Tools (Part 23): Camera-Controlled, DirectX-Enabled 3D Graphs for Distribution Insights

In this article, we advance the binomial distribution graphing tool in MQL5 by integrating DirectX for 3D visualization, enabling switchable 2D/3D modes with camera-controlled rotation, zoom, and auto-fitting for immersive analysis. We render 3D histogram bars, ground planes, and axes alongside the theoretical probability mass function curve, while preserving 2D elements like statistics panels, legends, and customizable themes, gradients, and labels
preview
Implementing the Truncated Newton Conjugate-Gradient Algorithm in MQL5

Implementing the Truncated Newton Conjugate-Gradient Algorithm in MQL5

This article implements a box‑constrained Truncated Newton Conjugate‑Gradient (TNC) optimizer in MQL5 and details its core components: scaling, projection to bounds, line search, and Hessian‑vector products via finite differences. It provides an objective wrapper supporting analytic or numerical derivatives and validates the solver on the Rosenbrock benchmark. A logistic regression example shows how to use TNC as a drop‑in alternative to LBFGS.
preview
Mastering PD Arrays: Optimizing Trading from Imbalances in PD Arrays

Mastering PD Arrays: Optimizing Trading from Imbalances in PD Arrays

This is an article about a specialized trend-following EA that aims to clearly elaborate how to frame and utilize trading setups that occur from imbalances found in PD arrays. This article will explore in detail an EA that is specifically designed for traders who are keen on optimizing and utilizing PD arrays and imbalances as entry criteria for their trades and trading decisions. It will also explore how to correctly determine and profile premium and discount arrays and how to validate and utilize each of them when they occur in their respective market conditions, thus trying to maximize opportunities that occur from such scenarios.
preview
Package-based approach with KnitPkg for MQL5 development

Package-based approach with KnitPkg for MQL5 development

For maximum reliability and productivity in MetaTrader products built with MQL, this article advocates a development approach based on reusable “packages” managed by KnitPkg, a project manager for MQL5/MQL4. A package can be used as a building block for other packages or as the foundation for final artifacts that run directly on the MetaTrader platform, such as EAs, indicators, and more.
preview
MQL5 Trading Tools (Part 22): Graphing the Histogram and Probability Mass Function (PMF) of the Binomial Distribution

MQL5 Trading Tools (Part 22): Graphing the Histogram and Probability Mass Function (PMF) of the Binomial Distribution

This article develops an interactive MQL5 plot for the binomial distribution, combining a histogram of simulated outcomes with the theoretical probability mass function. It implements mean, standard deviation, skewness, kurtosis, percentiles, and confidence intervals, along with configurable themes and labels, and supports dragging, resizing, and live parameter changes. Use it to assess expected wins, likely drawdowns, and confidence ranges when validating trading strategies.
preview
Engineering Trading Discipline into Code (Part 2): Building a Daily Trade Limit Enforcer for All Trades in MQL5

Engineering Trading Discipline into Code (Part 2): Building a Daily Trade Limit Enforcer for All Trades in MQL5

We have developed a system that enforces a daily trade limit to keep you aligned with your trading rules. It monitors all executed trades across the account and automatically intervenes once the defined limit is reached, preventing any further activity. By embedding control directly into the platform, the system ensures discipline is maintained even when market pressure rises.
preview
Larry Williams Market Secrets (Part 13): Automating Hidden Smash Day Reversal Patterns

Larry Williams Market Secrets (Part 13): Automating Hidden Smash Day Reversal Patterns

The article builds a transparent MQL5 Expert Advisor for Larry Williams’ hidden smash day reversals. Signals are generated only on new bars: a setup bar is validated, then confirmed when the next session trades beyond its extreme. Risk is managed via ATR or structural stops with a defined risk-to-reward, position sizing can be fixed or balance-based, and direction filters plus a one-position policy ensure reproducible tests.
preview
Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Final Part)

Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Final Part)

We continue to integrate methods proposed by the authors of the Attraos framework into trading models. Let me remind you that this framework uses concepts of chaos theory to solve time series forecasting problems, interpreting them as projections of multidimensional chaotic dynamic systems.
preview
The MQL5 Standard Library Explorer (Part 9): Using ALGLIB to Filter Excessive MA Crossover Signals

The MQL5 Standard Library Explorer (Part 9): Using ALGLIB to Filter Excessive MA Crossover Signals

During sideways price movements, traders face excessive signals from multiple moving average crossovers. Today, we discuss how ALGLIB preprocesses raw price data to produce filtered crossover layers, which can also generate alerts when they occur. Join this discussion to learn how a mathematical library can be leveraged in MQL5 programs.
preview
Formulating Dynamic Multi-Pair EA (Part 7): Cross-Pair Correlation Mapping for Real-Time Trade Filtering

Formulating Dynamic Multi-Pair EA (Part 7): Cross-Pair Correlation Mapping for Real-Time Trade Filtering

In this part, we will integrate a real-time correlation matrix into a multi-symbol Expert Advisor to prevent redundant or risk-stacked trades. By dynamically measuring cross-pair relationships, the EA will filter entries that conflict with existing exposure, improving portfolio balance, reducing systemic risk, and enhancing overall trade quality.
preview
Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Attraos)

Neural Networks in Trading: Integrating Chaos Theory into Time Series Forecasting (Attraos)

The Attraos framework integrates chaos theory into long-term time series forecasting, treating them as projections of multidimensional chaotic dynamic systems. Exploiting attractor invariance, the model uses phase space reconstruction and dynamic multi-resolution memory to preserve historical structures.
preview
Price Action Analysis Toolkit Development (Part 63): Automating Rising and Falling Wedge Detection in MQL5

Price Action Analysis Toolkit Development (Part 63): Automating Rising and Falling Wedge Detection in MQL5

In this part of the Price Action Analysis Toolkit Development series, we develop an MQL5 indicator that automatically detects rising and falling wedge patterns in real time. The system confirms pivot structures, validates boundary convergence mathematically, prevents overlapping formations, and monitors breakout and failure conditions with precise visual feedback. Built using a clean object-oriented architecture, this implementation converts subjective wedge recognition into a structured, state-aware analytical component designed to strengthen disciplined price action analysis.
preview
Overcoming Accessibility Challenges in MQL5 Trading Tools (Part II): Enabling EA Voice Using a Python Text-to-Speech Engine

Overcoming Accessibility Challenges in MQL5 Trading Tools (Part II): Enabling EA Voice Using a Python Text-to-Speech Engine

Let's discuss how we can make our Expert Advisors speech‑capable using text‑to‑speech technology, partnering Python and MQL5. After reading this article, you will walk away with a working example of an EA that speaks dynamic market information. You will master the application of TTS, the WebRequest function, and learn how Python libraries integrate with the MQL5 language to create a truly voice‑aware trading tool.