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
Random Matrix Theory: Denoising the Correlation Matrix for Multi-Symbol EAs

Random Matrix Theory: Denoising the Correlation Matrix for Multi-Symbol EAs

Sample correlation matrices can look precise yet be mostly noise. This article implements a dependency-free RMT cleaner in MQL5: Jacobi eigendecomposition, Marchenko–Pastur eigenvalue screening, and average-noise reconstruction that preserves the matrix trace and unit diagonal. It explains integration into a basket EA so the denoised matrix improves stability of hedge ratios and weights between rebalances, while keeping the code portable and auditable.
preview
Drawdown Duration Analysis Indicator in MQL5

Drawdown Duration Analysis Indicator in MQL5

We build a drawdown analytics dashboard that derives the equity curve from deals and finds every episode's depth and recovery duration. Results appear on a CCanvas timeline spaced by point index with alternating bold annotations, and in a terminal table sorted by duration, allowing you to prioritize risk by time spent underwater rather than depth alone.
preview
Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

Testing for Residual Autocorrelation with the Ljung-Box Portmanteau Test in MQL5

A complete MQL5 implementation of the Ljung-Box test helps verify independence in trading data and fitted-model residuals. It computes sample autocorrelations, the Q statistic over selected horizons, degrees of freedom with user-controlled adjustments, and right-tail p-values via the regularized incomplete gamma function. Run it on returns, deal outcomes, or external residuals and review decisions directly in the Experts tab.
preview
Neural Networks in Trading: The Adaptive Graph Diffusion Model (Conclusion)

Neural Networks in Trading: The Adaptive Graph Diffusion Model (Conclusion)

In this article, we conclude our work on building the SAGDFN framework using MQL5, summarizing the development process and presenting the results of its practical testing. Let's combine the modules we've already implemented into a single system, highlight the strengths of this approach, point out its weaknesses, and discuss possible ways to improve it.
preview
Building a Dynamic and Customizable Table in MQL5

Building a Dynamic and Customizable Table in MQL5

This article presents a reusable CTable class for building chart-based tables in MQL5. It covers table architecture, creation and destruction of objects, coordinates and sizing, cell properties, horizontal/vertical headers, dynamic row/column edits, object naming, index conversion, and efficient refreshing. You will be able to assemble consistent, aligned on-chart dashboards for market data, indicators, and signals with minimal boilerplate.
preview
Building AI-Powered Trading Systems in MQL5 (Part 11): Optimizing the UI with Frame Throttling and Partial Rendering

Building AI-Powered Trading Systems in MQL5 (Part 11): Optimizing the UI with Frame Throttling and Partial Rendering

We optimize an MQL5 canvas interface to stay responsive under rapid input without changing its appearance. The article adds a direct-buffer canvas for block region copies, caches text widths and glyph coverage, caps repaints at 60 fps (16 ms), and limits drawing to panes and regions that actually changed. As a result, hover, scroll, and popups render smoothly without full-panel redraws.
preview
Practical Modules from Other Languages in MQL5 (Part 07): The OS Module from Python

Practical Modules from Other Languages in MQL5 (Part 07): The OS Module from Python

This article introduces a lightweight OS-like helper for MQL5 that streamlines file and path operations using a Python-inspired interface. We implement getcwd, listdir, scandir with DirEntry, remove, rmdir, rename, mkdir, stat, and an os.path subset (exists, isfile, isdir, join, split, pardir). You will learn how to work consistently within the terminal Files/common sandbox and simplify everyday filesystem tasks.
preview
From Delta-Space Quotes to the FX Volatility Smile: Garman-Kohlhagen and the Convention Problem

From Delta-Space Quotes to the FX Volatility Smile: Garman-Kohlhagen and the Convention Problem

FX options are quoted in delta space, not by strike. This article implements an FX-native smile tool for MetaTrader 5: it converts ATM, risk reversal and butterfly quotes into strike-space pillars, prices with the Garman–Kohlhagen model, handles spot/forward and premium-adjusted delta conventions per pair, and draws the smile with a reconstructed strike ladder and Greeks.
preview
Uncertainty as a Model (Part 1): Random Variables — The Language of Uncertainty

Uncertainty as a Model (Part 1): Random Variables — The Language of Uncertainty

The article provides a systematic overview of the theory of random variables, which serves as the basis for analyzing and modeling uncertainty in financial markets. The article covers the definitions and properties of univariate random variables, cumulative distribution functions (CDFs) and probability density functions (PDFs), as well as the differences between discrete, continuous, and mixed models. The theoretical material is based on intuitive analogies with mass and density. The appendix to this article contains practical examples of using the standard MQL5 library to calculate probabilities, quantiles, and moments of distributions. It also demonstrates the graphical capabilities of the MetaTrader 5 platform for visual data analysis by plotting PDF and CDF curves and QQ plots.
preview
Building a Swing-Based Volume Profile Indicator in MQL5

Building a Swing-Based Volume Profile Indicator in MQL5

This article presents a swing-based volume profile indicator in MQL5 that analyzes platform tick volume within completed high-to-low and low-to-high legs. It confirms swing points, partitions each leg's range into ATR(200)‑adaptive price bins, distributes tick volume, and marks the Point of Control. The indicator draws a ZigZag and renders the profile on chart rectangles, helping you study volume concentration within each swing relative to price structure.
preview
Automating Trading Strategies in MQL5 (Part 53): Double Top and Double Bottom Reversal Model

Automating Trading Strategies in MQL5 (Part 53): Double Top and Double Bottom Reversal Model

We build an MQL5 program that detects and trades Double Top and Double Bottom patterns from confirmed swing pivots with rule-based logic. The detector matches peaks within a tolerance, derives the neckline, and applies leg-balance and spacing filters to reject weak shapes. It supports entry on a neckline break or an optional pullback, with a stop beyond the extreme and targets by measured move or reward-to-risk.
preview
Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

Did Your Scale Outs Actually Help? A Scale Out Value Analyzer in MQL5

The article presents an MQL5 tool that tests whether scaling out improved results rather than only appearing disciplined. It reconstructs positions from closing-deal history and reprices the full volume at the first, last, and best exit rates actually achieved, producing a Value-Add Ratio, a Scale-Out Win Rate, and an Efficiency measure. A single-trade dependence check and a configurable A+ to F grade turn these into clear, decision-ready feedback.
preview
MetaTrader 5 Machine Learning Blueprint (Part 21): Feature Importance Analysis

MetaTrader 5 Machine Learning Blueprint (Part 21): Feature Importance Analysis

Feature importance often understates correlated predictors by spreading one signal across many engineered copies, while unrelated noise can appear higher. We measure this effect against a known ground truth and compare four remedies: permutation importance with purged cross-validation, single-feature models, and clustered impurity versus clustered accuracy. The results include per-method rankings and a per-cluster dilution ratio that help identify true signals and avoid deleting valuable features.
preview
The Dragonfly Algorithm (DA)

The Dragonfly Algorithm (DA)

In this article, we will examine the Dragonfly Algorithm (DA), inspired by the collective behavior of dragonflies in nature — their ability to coordinate flight in a swarm, avoid collisions, follow prey, and evade predators. Let's look at how five simple behavioral rules and an adaptive mechanism for transitioning from exploration to exploitation are implemented in MQL5, and test the algorithm on our test bench.
preview
Neural Networks in Trading: The Adaptive Graph Diffusion Model (Attention Module)

Neural Networks in Trading: The Adaptive Graph Diffusion Model (Attention Module)

In this article, we will take a detailed look at the practical implementation of the key components of the SAGDFN framework. We will show how sparse attention and the selection of significant neighbors are organized for time series forecasting. The approaches presented strike a balance between forecast accuracy and computational efficiency.
preview
How to Connect an LLM to an MQL5 Expert Advisor via a Python Server

How to Connect an LLM to an MQL5 Expert Advisor via a Python Server

The article examines three key obstacles to integrating LLMs with MetaTrader 5: the lack of direct access, strict rate limits, and API key security given the architectural limitations of MQL5. A configuration is proposed that uses a local Python server as a bridge between the Expert Advisor and OpenRouter. The article covers WebSocket and fallback to TCP, storing the key on the server, batch processing of multiple symbols, and constructing a technical prompt. Readers get a ready-made architecture that reduces latency and costs.
preview
Building a PDF Creation Library in MQL5 (Part1): Writing a PDF by Hand

Building a PDF Creation Library in MQL5 (Part1): Writing a PDF by Hand

This article shows how a PDF works as plain text by hand‑written two files: a 592‑byte page and an 885‑byte trade ticket. It explains the file structure (header, body, xref, trailer), the required page objects and resources, and the operators that draw text, then provides an MQL5 script to generate them. First part of a pure‑MQL5 PDF library series.
preview
Replay and Market Simulation: The Grand Finale

Replay and Market Simulation: The Grand Finale

I know that many of you may have thought I would publish a few more articles to explain other aspects of this system. The missing elements are easy to implement. Even so, developing them will let you see how prepared you really are.
preview
From Basic to Intermediate: Operator Overloading (V)

From Basic to Intermediate: Operator Overloading (V)

In this article, we will look at how to modify the code to implement a solution entirely unlike what many consider possible in MQL5. Important note: To fully understand this material, you must have a solid grasp of the concepts covered in the previous articles.
preview
MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

MQL5 Expert Advisor Builder (Part 1): A Simple Static Template

The article examines an example of a multipurpose trading robot template that is suitable both for creating your own strategies and as a codebase for freelance work. A key feature of the solution is bar-based trading; the code already includes built-in modes for averaging, martingale, and holding positions for extended periods. This material will be most useful to beginners who want to develop their own simple strategies or learn about common trading techniques.
preview
Market Simulation: Unity Is Strength (III)

Market Simulation: Unity Is Strength (III)

In this article, I will present our system for simulating market operations. Although everything is practically finished, there are still a few things to implement and a few changes to make. However, I have to admit that, after everything we've already developed, I'm tired of still being stuck on implementing this system.
preview
Developing a Multi-Currency Expert Advisor (Part 32): Secrets of the Optimization Project Creation Step (II)

Developing a Multi-Currency Expert Advisor (Part 32): Secrets of the Optimization Project Creation Step (II)

The article discusses the parameters of the second stage of the automatic optimization pipeline for a multi-currency Expert Advisor. We analyze the criteria for filtering first-stage passes and the rules for forming groups of trading strategies. The article demonstrates how settings affect optimization results, discusses aspects of process reliability, and examines the balance between selection strictness and having enough candidates for the algorithm.
preview
Python-MetaTrader 5 Strategy Tester (Part 06): MQL5-Style Backtesting for Python Expert Advisors

Python-MetaTrader 5 Strategy Tester (Part 06): MQL5-Style Backtesting for Python Expert Advisors

Code and build Python-based trading robots just like MQL5 Expert Advisors (EAs). In this article, we develop a Python-based replica of the MetaTrader 5 Python package, providing methods that closely resemble those of MetaTrader 5 during simulation. This allows us to backtest Python EAs in a simplified environment, using an approach similar to developing and testing Expert Advisors in MQL5.
preview
Building an Adaptive Fibonacci Volatility Band Indicator in MQL5

Building an Adaptive Fibonacci Volatility Band Indicator in MQL5

We build an adaptive Fibonacci volatility band indicator in MQL5 that centers on a smoothed price (SMMA) and scales band width with a smoothed ATR. The article covers inputs, buffer mapping, ATR handling, and SMMA formulas, then projects configurable Fibonacci ratios with filled zones. Readers get a ready workflow for visualizing volatility expansion/contraction and outlining dynamic support and resistance.
preview
Building AI-Powered Trading Systems in MQL5 (Part 10): A Resolution-Independent Vector Icon System

Building AI-Powered Trading Systems in MQL5 (Part 10): A Resolution-Independent Vector Icon System

We replace the embedded bitmap icons in our MQL5 canvas interface with a resolution-independent vector icon system. A small set of anti-aliased primitives (strokes, discs, rings, rounded rectangles, and polygons) draws every logo and sidebar glyph procedurally, then plugs into the header, sidebar, and theme toggle. You get smaller builds, theme-aware recoloring, and icons that stay sharp at any size.
preview
From Basic to Intermediate: Operator Overloading (IV)

From Basic to Intermediate: Operator Overloading (IV)

In this article, we will take a first step toward showing how to implement operator overloading for the index operator and the assignment operator, while striving to offer a practical and interesting approach for everyone. What we will see here is only part of what I still intend to show, and it is directly related to the overloading of these operators.
preview
Market Replay: Unity Is Strength (II)

Market Replay: Unity Is Strength (II)

Until now, the application being developed as part of this series of articles has focused exclusively on simulating the graphical part. However, to obtain a more complete system in which we can test the Expert Advisor within the replay/simulation service, we also need to simulate the trading server. You'll notice that this simulation will include only the most essential elements. Nevertheless, you, dear reader, will be able to fill in the missing parts. Since these additional components don't affect what I want to show, we already have more than enough to implement what we have in mind.
preview
Neural Networks in Trading: The Adaptive Graph Diffusion Model (SAGDFN)

Neural Networks in Trading: The Adaptive Graph Diffusion Model (SAGDFN)

In this article, we explore the architecture of SAGDFN — a modern framework capable of transforming the approach to processing spatiotemporal data. It preserves key information even in complex graphs while reducing computational costs.
preview
How to Use Finite Differences for Price Forecasting

How to Use Finite Differences for Price Forecasting

The article examines the practical application of finite differences in trading: types of differences, their relationship to price dynamics, and the binomial transform for noise filtering. The rules for encoding patterns based on difference levels and the application of these patterns to forecasting are described. This section presents naive, adaptive, and probabilistic approaches that help smooth time series, identify recurring patterns, and estimate future movements.
preview
LLM-Based Trading Agent with Embedded Top Trader Philosophy

LLM-Based Trading Agent with Embedded Top Trader Philosophy

The article provides a critical analysis of an LLM strategy in which forecasting the direction is separated from trading decisions, and demonstrates why this leads to a disconnect between metrics and PnL. We will describe procedures for dataset balancing, feature engineering, prompt and response preparation, fine-tuning configuration in Ollama, and reliable parsing. Backtesting and forward testing reveal systematic degradation. The practical conclusion is that the problem must be formulated as a direct optimization of trading outcomes.
preview
Developing a Reusable Dynamic Volatility Trailing Stop Engine in MQL5

Developing a Reusable Dynamic Volatility Trailing Stop Engine in MQL5

This article presents a modular, object-oriented volatility trailing stop engine for MQL5 packaged as a reusable include class, it calculates dynamic stop-loss levels using a True Range average filter on closed bars, supports step-based trailing, includes a visual diagnostic indicator, and provides an Expert Advisor execution template.
preview
From Basic to Intermediate: Operator Overloading (III)

From Basic to Intermediate: Operator Overloading (III)

In this article, we will examine how to implement overloading for both logical operators and comparison operators. This requires a certain amount of caution and a fair amount of attention. Even a minor oversight when implementing the overloading of these operators can render the entire code completely unusable. If any problems arise in the overloading, the entire database created from the results generated by the code will have to be either discarded completely or, at the very least, reviewed in full.
preview
Market Replay: Unity Is Strength (I)

Market Replay: Unity Is Strength (I)

We're entering the home stretch. The development of the replay/simulation system is nearly complete. Of course, we still have a few things left to finish, but compared to everything we've already done, completing what's left won't be difficult. However, it is essential to fully absorb and understand everything covered in this article. So I hope you enjoy reading this and, above all, that you enjoy this final stage of the journey.
preview
Building a Session Performance Analytics Dashboard in MQL5

Building a Session Performance Analytics Dashboard in MQL5

This article builds an MQL5 dashboard that classifies closed deals into Sydney, Tokyo, London, and New York trading sessions by UTC close time. It computes per-session P&L, win rate, and average hold time, then renders the results as a persistent CCanvas bar chart with an account-wide summary row, alongside an Experts tab summary table. A verification script confirms the classification and metrics logic behaves correctly.
preview
Defining your Edge (Part 6): Harnessing Fourier Transform and a Spiking Neural Network in an Expert Advisor

Defining your Edge (Part 6): Harnessing Fourier Transform and a Spiking Neural Network in an Expert Advisor

Article revisits Trading Robot that merged Discrete Fourier Transform with Leaky Integrate-and-Fire Spiking Neural Network. Evaluation is made over the seven operating modes with different symbols, timeframes, and test windows. We use two-thirds of the test window to optimize while the one-third does a forward walk run. This study tries to detail parameter interactions, input scaling, gating effects, and outlines practical checks that include rolling windows, frozen inputs, and others. The goal remains identifying settings worth further testing or paper trading.
preview
From Basic to Intermediate: Operator Overloading (II)

From Basic to Intermediate: Operator Overloading (II)

At first, this article may seem rather confusing because of the material I'm going to cover in it. Nevertheless, I've tried to explain everything as simply and clearly as possible. I hope you'll understand what I'm about to show you here, and that it will come in handy someday.
preview
Market Simulation: Position View (XIX)

Market Simulation: Position View (XIX)

One of the issues that bothered me the most was that the `C_ElementsTrade` class contains code for accessing positions. Don't take this as a mistake, because it really isn't one. However, this increases the risk of errors in some of the tasks we will need to handle later. All work on implementing the position indicator was carried out with a view to its use in the replay/simulation service. However, when running in this environment, we will have no access to actual positions. Consequently, any call to the MQL5 library intended to retrieve position data will have no effect in this environment.
preview
Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Conclusion)

Neural Networks in Trading: Heterogeneity-Informed Meta-Parameter Learning (Conclusion)

The article describes a practical implementation of the HimNet framework based on MQL5, ready for integration into automated trading. We demonstrate how heterogeneity-adapted meta-parameters transform the model into a universal tool capable of handling fluctuating volatility.
preview
How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

How to Obtain Synchronized Arrays for Use in Portfolio Trading Algorithms

The article describes a practical approach to synchronizing bars between instruments in a portfolio in MQL5. Classes are provided for loading, storing, and aligning OHLCV data, with options to use an empty bar or carry over values from the previous bar, select a synchronization symbol, and process new bars asynchronously. Examples of use in multi-chart and basket indicators are shown. Readers receive a ready-to-use API for reliable portfolio calculations.
preview
From Option Chain to Risk-Neutral Density: The Market's Own Probability Distribution

From Option Chain to Risk-Neutral Density: The Market's Own Probability Distribution

The article builds an MQL5 indicator that recovers the risk-neutral density from an option chain via the Breeden–Litzenberger identity. Quotes are inverted to implied volatilities, the smile is smoothed and priced back to arbitrage‑free calls, and the second derivative yields the density. The tool reports probabilities above any level, the expected move, skew and kurtosis, and overlays the realized-return distribution for comparison.