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
From Basic to Intermediate: Objects (IV)

From Basic to Intermediate: Objects (IV)

This is perhaps the most entertaining article so far. The reason is that here we will modify an object already available in MetaTrader 5 in order to create another one that is not originally present on the platform. Of course, what we are going to look at here may seem a little crazy, but it works and serves a very interesting purpose.
preview
How to Connect AI Agents to MQL5 Algo Forge via MCP

How to Connect AI Agents to MQL5 Algo Forge via MCP

This article extends Part 1 by giving an AI access to the development lifecycle on MQL5 Algo Forge. We implement an MCP server over the Forgejo REST API so an agent can create repositories, commit Expert Advisors, branch from main, open pull requests, file issues, and tag releases. You will get a ready-to-run Python server, clear tools, and a safer, reversible workflow.
preview
MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems

MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems

The article builds a reusable validation layer for Expert Advisors in MQL5. It implements lot-size rules and normalization, SL/TP and freeze-level guards, price digit normalization, margin sufficiency checks, unchanged-level filtering on modifications, account order-limit control, new-bar detection, symbol tradability checks, economic-calendar news windows, and session detectors. The result is cleaner code and fewer terminal errors in live trading.
preview
MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

We add a pinned-tools ribbon: a floating bar that exposes frequently used tools for one-click access without reopening the sidebar. The article implements the ordered pin set and its API, an anti-aliased pushpin control in the flyout, and the ribbon with offscreen clipping, user-resizable width, and horizontal scrolling. The result is faster activation of favorite tools from a draggable, resizable ribbon on the chart.
preview
Implementing Walk-Forward Efficiency Ratio Scoring in MQL5 to Detect Over-Optimized Strategies

Implementing Walk-Forward Efficiency Ratio Scoring in MQL5 to Detect Over-Optimized Strategies

Parameter optimization inside MetaTrader 5's Strategy Tester routinely produces strategies that perform well in-sample and collapse on forward data. This article builds a native MQL5 Walk-Forward Efficiency scoring engine that quantifies how much of a strategy's in-sample Sharpe ratio transfers to each out-of-sample window. The distribution is rendered as a CCanvas histogram and validated against real EURUSD Daily backtest data.
preview
Building a Broker-Agnostic Symbol Resolution Layer in MQL5

Building a Broker-Agnostic Symbol Resolution Layer in MQL5

We implement a symbol resolution framework that abstracts broker naming differences in MetaTrader 5. Using a persistent mapping store, layered resolution with validation, a hash-indexed registry, and a cache, it returns selectable symbols with live market data and logs unresolved cases. Practically, you can deploy the same EA across brokers and keep symbol access consistent at low runtime cost.
preview
Persistent Homology in MQL5: The Reduction Algorithm and the Persistence Diagram

Persistent Homology in MQL5: The Reduction Algorithm and the Persistence Diagram

We complete persistent homology for MQL5 by reducing the Vietoris–Rips boundary matrix to a persistence diagram. The article implements Z/2 column reduction (CTDAReduction), a diagram container with analytics (CTDADiagram), and a facade that runs the six-stage pipeline in one call (CTDA). Outputs are cross-checked against Ripser to numerical agreement, enabling reliable diagram-based metrics.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (Part VI): Neural Command Integration

Overcoming Accessibility Problems in MQL5 Trading Tools (Part VI): Neural Command Integration

This article demonstrates a working prototype integrating Brain-Computer Interface technology with MetaTrader 5, proving thought-based trading is feasible at the software level. A Python Flask server simulates neural command generation, communicating with an MQL5 Expert Advisor via JSON-over-HTTP. The complete pipeline—from signal generation to trade execution—is validated through WebRequest and CTrade. While BCI hardware remains clinically restricted, this simulation establishes a reference architecture for future accessibility options, enabling direct intention-based trading that expands how traders can interact with financial markets.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

In this article, we introduce the Mamba4Cast framework and take a closer look at one of its key components: timestamp-based positional encoding. The article shows shows how time embedding is formed taking into account the calendar structure of the data.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

The article discusses the adaptation and practical implementation of the ACEFormer framework using MQL5 in the context of algorithmic trading. It presents key architectural decisions, training features, and model testing results on real data.
preview
Neural Networks in Practice: Practice Makes Perfect

Neural Networks in Practice: Practice Makes Perfect

In today's article, we will see how a simple code change that makes a neuron slightly more specialized can significantly speed up the training stage. After all, once a neuron or neural network, as we will see later, has been trained, the work it performs becomes much faster. We will also discuss a problem that exists but is rarely mentioned.
preview
From Basic to Intermediate: Object Events (III)

From Basic to Intermediate: Object Events (III)

In this article, we will prepare the foundation for what will be covered in the next publication. We will also look at how to make an OBJ_LABEL object fully interactive for editing and moving. In other words, we can change both the text and the position of the OBJ_LABEL object without opening the Object Properties dialog.
preview
Detecting and Visualizing Outlier Bars in MQL5 Using Modified Z-Score on OHLCV Features

Detecting and Visualizing Outlier Bars in MQL5 Using Modified Z-Score on OHLCV Features

Abnormal bars inflate mean and standard deviation estimates, distorting ATR, Bollinger Bands, and moving averages. We implement a native MQL5 indicator that detects such bars with the Modified Z-Score applied to four features: body, upper wick, lower wick, and tick volume. The indicator marks flagged bars on the chart and plots a composite score in a separate subwindow, helping you diagnose contamination in rolling-window indicators.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

This article implements a real-time monitoring dashboard for a self-healing MetaTrader 5 Expert Advisor. The dashboard displays the current EA state, virtual stop-loss and take-profit levels, breakeven and trailing status, recovery state, synchronization status, and heartbeat information directly on the chart. By exposing the internal recovery state visually, the Expert Advisor becomes easier to monitor, verify, and troubleshoot while managing active trades.
preview
Building Automated Daily Trading Reports with the SendMail Function

Building Automated Daily Trading Reports with the SendMail Function

We build an MQL5 Expert Advisor that emails a structured daily trading report. The article shows how to configure SMTP in MetaTrader 5, collect and filter closed trades for the previous day, compute totals for profit, wins, losses, and trade count, and assemble account details into the subject and body. You also schedule one send per day and prevent duplicates using daily candle detection.
preview
CSV Data Analysis (Part 6): Multi-Broker Result Normalization and Cross-Platform CSV Reconciliation

CSV Data Analysis (Part 6): Multi-Broker Result Normalization and Cross-Platform CSV Reconciliation

This article presents a multi‑broker CSV normalization framework. An MQL5 include file enriches exports with broker metadata. A Python module resolves schema divergences — pip conventions, symbol aliases, time offsets, commission models, and currency denomination — producing a unified canonical dataset. Comparative visualizations of slippage distributions and net‑of‑cost performance enable reliable cross‑platform strategy analysis without silent data corruption.
preview
Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 4): A Volatility-Adjusted Momentum-Based Intraday System

Low-Frequency Quantitative Strategies in MetaTrader 5 (Part 4): A Volatility-Adjusted Momentum-Based Intraday System

We present a timer-based MQL5 EA for Opening Range Breakout aligned to NYSE hours. It screens “Stocks in Play” via opening-range relative volume, enforces price/volume/ATR minimums, sizes positions by risk, and exits at 16:00 ET. A Sharpe-ranked optimization across 30 liquid Nasdaq stocks and a single-symbol test are provided, together with backtest settings and an Excel report for verification.
preview
Automating Classic Market Methods in MQL5 (Part 3): Stan Weinstein Stage Analysis

Automating Classic Market Methods in MQL5 (Part 3): Stan Weinstein Stage Analysis

This article presents a complete Expert Advisor built around Stan Weinstein's Stage Analysis method. The EA classifies the market into one of four stages using the 30-week moving average slope and position and volume behavior, then trades only Stage 2 breakouts long and Stage 4 breakdowns short. It explains each stage, how to detect it programmatically, and why the method's discipline—trading only in the correct stage—is what produces the edge.
preview
Feature Engineering for ML (Part 10): Structural Break Tests in MQL5

Feature Engineering for ML (Part 10): Structural Break Tests in MQL5

We port AFML Chapter 17 structural break tests to MQL5 as a single include, CStructuralBreaks, delivering six bar-indexed features for EAs: CSW statistic and critical value, Chow-Type DFC, SADF with a rolling lookback (default 252), SM-Exp, and SM-Power. SADF uses O(L²) rolling windows for real-time viability. A companion StructuralBreaksViewer indicator plots all series with per‑series visibility and optional z‑score normalization. SB_EMPTY marks invalid values for safe integration.
preview
Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

The article presents an innovative hybrid system for forecasting exchange rates that combines a linear autoregressive model with a U-Transformer architecture for residual analysis. The system automatically switches between signal sources depending on their quality and includes complete trading logic with averaging/pyramiding strategies. The key advantage of this approach is that the neural network is trained on the residuals of the linear model, which simplifies the task and reduces the risk of overfitting. The implementation is done entirely in MQL5 and is ready for use in real trading with automatic adaptation to changing market conditions.
preview
Building a Viewport SnR Volume Profile Indicator in MQL5

Building a Viewport SnR Volume Profile Indicator in MQL5

We build a Support and Resistance Volume Profile indicator that adapts to the current viewport in MetaTrader 5. You will learn viewport detection, dynamic SnR identification, zoom‑driven bin sizing, min‑max volume scaling, and fast on‑chart rendering controlled by OnChartEvent. This approach expresses the relative strength of SnR levels with volume, keeping the chart focused on actionable reaction zones.
preview
Feature Engineering for ML (Part 9): Structural Break Tests in Python

Feature Engineering for ML (Part 9): Structural Break Tests in Python

We present a production‑ready implementation of AFML Chapter 17 structural break tests. The module includes Chu-Stinchcombe-White (one-/two-sided), Chow-type DFC, SADF across six models (linear, quadratic, sm poly 1, sm poly 2, sm exp, sm power), plus QADF (q, v) and CADF (q), returning bar-indexed scalar features. We address the book snippets' scaling issues and argument‑order pitfall, and show how a fixed lookback (L=504) bounds SADF cost to O(L²) per bar for regime detection.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

We invite you to explore the ACEFormer architecture — a modern solution that combines the effectiveness of probabilistic attention with adaptive time series decomposition. This article will be useful for those seeking a balance between computational performance and forecast accuracy in financial markets.
preview
Beyond Maximum Drawdown: Building a Drawdown DNA Analyzer in MQL5

Beyond Maximum Drawdown: Building a Drawdown DNA Analyzer in MQL5

Maximum drawdown is one number that hides what really matters: how often an equity curve declines, how long it stays below a previous peak, and how quickly it recovers. This article builds a native MQL5 tool that reconstructs the underwater curve, breaks it into individual drawdown episodes (depth, duration, recovery time), computes the Ulcer Index, Pain Index, and Recovery Factor, and combines them into a single resilience grade with practical recommendations. No external libraries, no Python, no AI.
preview
Building Volatility Models in MQL5 (Part IV): Implementing Long Memory Volatility Processes, FIGARCH, and HARCH

Building Volatility Models in MQL5 (Part IV): Implementing Long Memory Volatility Processes, FIGARCH, and HARCH

The article delivers MQL5 implementations of FIGARCH and HARCH and updates the volatility library for long‑memory processes. It provides code for Hurst and GPH testing, parameter setup (truncation and horizons), and scripts for fitting, forecasting, and simulations. Readers learn how to apply and compare the models on market data to select an appropriate specification.
preview
Building an Internal and External Market Structure Indicator

Building an Internal and External Market Structure Indicator

The article presents a structured approach to external and internal market structure in MQL5, from swing identification to CHoCH/BoS validation within an established trend. It explains refining true highs/lows, enforcing “first internal signal” logic, and rendering lines, labels, and markers on the chart. The outcome is a consistent indicator that converts price structure into defined entries, stop losses, and 1.5R targets.
preview
Dream Optimization Algorithm (DOA)

Dream Optimization Algorithm (DOA)

A population-based optimization algorithm inspired by a controversial and little-studied phenomenon - the mechanism of human dreams. Agent groups with different "memory", cosine-wave modulation of motion, and an unusual 99/1 phase distribution — learn how these features affect the optimization efficiency of your trading strategies.
preview
Creating an EMA Crossover Forward Simulation (Culmination): Interactive Synthetic Candles

Creating an EMA Crossover Forward Simulation (Culmination): Interactive Synthetic Candles

This article finalizes the Forward Simulation Engine for MetaTrader 5 by calibrating synthetic candles to recent market volatility instead of using slope-only sizing. It samples average body, upper wick, and lower wick from closed bars, applies a sine-envelope with decay, proportional wicks, gaps between candles, and periodic counter-trend injections. The result is a live projection that advances one bar ahead, with code you can reuse for calibrated, anchor-based forward rendering and automatic cleanup.
preview
MQL5 Wizard Techniques you should know (Part 100): Sliding Window Median and Bidirectional LSTM for a Custom Trailing Stop

MQL5 Wizard Techniques you should know (Part 100): Sliding Window Median and Bidirectional LSTM for a Custom Trailing Stop

CTrailingSlidingMedianBiLSTM is a custom MQL5 Wizard trailing module that combines robust median/MAD outlier filtering with a BiLSTM context score in the range [-1, 1]. Four algorithm modes (standard, bands, RSI, adaptive) target noise, mean-reverting bursts and liquidity spikes, reducing premature stop adjustments. This module is intended for side-by-side evaluation with diverse entry signals and money management settings.
preview
Automatic Session Volume Profile Builder in MQL5: Rendering POC and Value Area Without Third-Party Tools

Automatic Session Volume Profile Builder in MQL5: Rendering POC and Value Area Without Third-Party Tools

Implement a session-focused volume profile in MQL5: acquire ticks with CopyTicksRange(), bin prices, and compute POC, VAH, and VAL by the 70% approach. The indicator renders directly on the chart as native objects, supports fixed-width scaling for consistent geometry across timeframes, and refreshes on each new session. This provides objective reference levels without external dependencies.
preview
Duelist Algorithm

Duelist Algorithm

What if your trading strategies could learn from each other, like real fighters? Duelist Algorithm is a new optimization method where trading system parameters literally duel for the right to be called the best.
preview
Code, Tears, and Algo Forge

Code, Tears, and Algo Forge

This article discusses the transition to MQL5 Algo Forge as a modern and convenient format for publishing program code and article attachments. Using repositories instead of traditional ZIP archives and source code allows you to keep projects up-to-date, make edits quickly, and professionally interact with your readers. Recommendations are provided for quickly migrating developments to the cloud environment via the MetaEditor interface.
preview
Implementation of the Quantum Reservoir Computing (QRC) circuit

Implementation of the Quantum Reservoir Computing (QRC) circuit

A revolutionary approach to machine learning in trading through quantum computing. The article demonstrates a practical implementation of an adaptive QRC system with continuous retraining for predicting market movements in real time.
preview
Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5

Beyond GARCH (Part VII): Monte Carlo Volatility Forecasting in MQL5

We implement the CMonteCarlo module that turns the fitted MMAR parameters into a volatility forecast via Monte Carlo. It runs N independent simulations over a chosen horizon and reports mean, median, standard deviation, and a percentile-based 95% confidence interval, with access to per-run values if needed. Adaptive cascade depth selects the minimal k such that b^k covers the horizon, keeping the run fast and consistent.
preview
Digital Signal Processing for Traders: Building Ehlers' Filter Library in MQL5

Digital Signal Processing for Traders: Building Ehlers' Filter Library in MQL5

We implement Ehlers-style DSP filters in a single reusable MQL5 library and use it to build two indicators. The Roofing Filter applies a 2‑pole high‑pass followed by a Super Smoother to isolate the tradeable 10–48‑bar band. The Even Better Sinewave normalizes the wave to about ±1, oscillating in cycle regimes and railing in trends, so you can read cycles and detect regime shifts in charts and EAs.
preview
Heatmap Visualization of Intraday Return Patterns in MQL5 Using CCanvas

Heatmap Visualization of Intraday Return Patterns in MQL5 Using CCanvas

MetaTrader 5 provides no native tool for visualizing intraday return patterns across time dimensions simultaneously. This article implements a custom indicator that aggregates historical bar returns into a 5×24 matrix indexed by weekday and hour of day, then renders the result as a color-interpolated heatmap inside an indicator subwindow using CCanvas. Green cells represent positive average returns, red cells negative, with color intensity encoding return magnitude.
preview
Market Microstructure in MQL5 (Part 7): Regime Classification

Market Microstructure in MQL5 (Part 7): Regime Classification

We integrate eleven one-minute microstructure measurements from Parts 2–6 into a composite regime label with confidence and direction. A rule-based RegimeClassifier() assigns one of six regimes—Normal, Stressed, Noisy, Informed, Trending, Mean-Reverting—using empirically derived thresholds from 514 NQ M1 sessions (May 2024–May 2026). The deliverable includes MARKET_REGIME, RegimeAnalysis, and PopulateRegimeAnalysis(), enabling position sizing, stop placement, and signal filtering from a single call.
preview
Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

In this article, we build an automated trading program in MQL5 that detects the Quasimodo reversal pattern from a zig-zag of confirmed swing pivots. We work through swing detection, pattern arming, retrace entries at the QM line, and structural stop placement with risk-based sizing. We also add trade management with breakeven, trailing, and partial closing to handle open positions.
preview
Developing a Neural Network Trading Robot Based on Mamba with Selective State Space Models

Developing a Neural Network Trading Robot Based on Mamba with Selective State Space Models

The article explores the revolutionary Mamba/SSM neural network architecture for financial time series forecasting. We will consider a complete MQL5 implementation of a modern alternative to Transformer with linear complexity O(N) instead of quadratic O(N²). Selective State Space Models, hardware-aware optimizations, patching techniques, and advanced AdamW training methods are covered in detail. Practical test results showing an increase in accuracy from 62% to 71% while reducing training time from 45 to 8 minutes are included. A ready-made trading EA with auto learning and adaptive risk management for MetaTrader 5 is presented.
preview
Engineering Trading Discipline into Code (Part 8): Building a Setup Confirmation and Trade Authorization Layer in MQL5

Engineering Trading Discipline into Code (Part 8): Building a Setup Confirmation and Trade Authorization Layer in MQL5

This article introduces an MQL5 trade authorization framework built around CDisciplineLayer, CDisciplineGuardian, and CDisciplinePanel. The framework manages setup lifecycles, signal freshness, session restrictions, setup expiry, and global trading locks through a centralized authorization layer. It also provides automated enforcement of violations and a real-time dashboard, enabling consistent trade validation and monitoring before and after execution.