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
Market Simulation (Part 13): Sockets (VII)

Market Simulation (Part 13): Sockets (VII)

When we develop something in xlwings or any other package that allows reading and writing directly to Excel, we must note that all programs, functions, or procedures execute and then complete their task. They do not remain in a loop, no matter how hard we try to do things differently.
preview
Using the MQL5 Economic Calendar for News Filtering (Part 1): Implementing Pre- and Post-News Windows in MQL5

Using the MQL5 Economic Calendar for News Filtering (Part 1): Implementing Pre- and Post-News Windows in MQL5

We build a calendar‑driven news filter entirely in MQL5, avoiding web requests and external DLLs. Part 1 covers loading and caching events, mapping them to symbols by currency, filtering by impact level, defining pre/post windows, and blocking new trades during active news, with optional pre‑news position closure. The result is a configurable, prop‑firm‑friendly control that reduces false pauses and protects entries during volatility.
preview
Market Simulation (Part 12): Sockets (VI)

Market Simulation (Part 12): Sockets (VI)

In this article, we will look at how to solve certain problems and issues that arise when using Python code within other programs. More specifically, we will demonstrate a common issue encountered when using Excel in conjunction with MetaTrader 5, although we will be using Python to facilitate this interaction. However, this implementation has a minor drawback. It does not occur in all cases, but only in certain specific situations. When it does happen, it is necessary to understand the cause. In today’s article, we will begin explaining how to resolve this issue.
preview
Risk Management (Part 5): Integrating the Risk Management System into an Expert Advisor

Risk Management (Part 5): Integrating the Risk Management System into an Expert Advisor

In this article, we will implement the risk management system developed in previous publications and add the Order Blocks indicator described in other articles. In addition, we will run a backtest so we can compare results with the risk management system enabled and evaluate the impact of dynamic risk.
preview
Automating Market Memory Zones Indicator: Where Price is Likely to Return

Automating Market Memory Zones Indicator: Where Price is Likely to Return

This article turns Market Memory Zones from a chart-only concept into a complete MQL5 Expert Advisor. It automates Displacement, Structure Transition (CHoCH), and Liquidity Sweep zones using ATR- and candle-structure filters, applies lower-timeframe confirmation, and enforces risk-based position sizing with dynamic SL and structure-based TP. You will get the code architecture for detection, entries, trade management, and visualization, plus a brief backtest review.
preview
Introduction to MQL5 (Part 40): Beginner Guide to File Handling in MQL5 (II)

Introduction to MQL5 (Part 40): Beginner Guide to File Handling in MQL5 (II)

Create a CSV trading journal in MQL5 by reading account history over a defined period and writing structured records to file. The article explains deal counting, ticket retrieval, symbol and order type decoding, and capturing entry (lot, time, price, SL/TP) and exit (time, price, profit, result) data with dynamic arrays. The result is an organized, persistent log suitable for analysis and reporting.
preview
MQL5 Trading Tools (Part 18): Rounded Speech Bubbles/Balloons with Orientation Control

MQL5 Trading Tools (Part 18): Rounded Speech Bubbles/Balloons with Orientation Control

This article shows how to build rounded speech bubbles in MQL5 by combining a rounded rectangle with a pointer triangle and controlling orientation (up, down, left, right). It details geometry precomputation, supersampled filling, rounded apex arcs, and segmented borders with an extension ratio for seamless joins. Readers get configurable code for size, radii, colors, opacity, and thickness, ready for alerts or tooltips in trading interfaces.
preview
Price Action Analysis Toolkit Development (Part 61): Structural Slanted Trendline Breakouts with 3-Swing Validation

Price Action Analysis Toolkit Development (Part 61): Structural Slanted Trendline Breakouts with 3-Swing Validation

We present a slanted trendline breakout tool that relies on three‑swing validation to generate objective, price‑action signals. The system automates swing detection, trendline construction, and breakout confirmation using crossing logic to reduce noise and standardize execution. The article explains the strategy rules, shows the MQL5 implementation, and reviews testing results; the tool is intended for analysis and signal confirmation, not automated trading.
preview
Risk Management (Part 4): Completing the Key Class Methods

Risk Management (Part 4): Completing the Key Class Methods

This is Part 4 of our series on risk management in MQL5, where we continue exploring advanced methods for protecting and optimizing trading strategies. Having laid important foundations in earlier articles, we will now focus on completing all remaining methods postponed in Part 3, including functions for checking whether specific profit or loss levels have been reached. In addition, we will introduce new key events that enable more accurate and flexible risk management.
preview
Beginner to Intermediate Level: Struct (IV)

Beginner to Intermediate Level: Struct (IV)

In this article, we will explore how to create so-called structural code, where the entire context and methods for manipulating variables and information are placed within a structure to create a suitable context for implementing any code. Therefore, we will examine the necessity of using a private section of the code to separate what is public from what is not, thereby adhering to the rule of encapsulation and preserving the context for which the data structure was created.
preview
ARIMA Forecasting Indicator in MQL5

ARIMA Forecasting Indicator in MQL5

In this article we are implementing ARIMA forecasting indicator in MQL5. It examines how the ARIMA model generates forecasts, its applicability to the Forex market and the stock market in general. It also explains what AR autoregression is, how autoregressive models are used for forecasting, and how the autoregression mechanism works.
preview
Quantitative Analysis of Trends: Collecting Statistics in Python

Quantitative Analysis of Trends: Collecting Statistics in Python

What is quantitative trend analysis in the Forex market? We collect statistics on trends, their magnitude and distribution across the EURUSD currency pair. How quantitative trend analysis can help you create a profitable trading expert advisor.
preview
Optimizing Liquidity Raids: Mastering the Difference Between Liquidity Raids and Market Structure Shifts

Optimizing Liquidity Raids: Mastering the Difference Between Liquidity Raids and Market Structure Shifts

This is an article about a specialized trend-following EA that aims to clearly elaborate how to utilize trading setups after liquidity raids. This article will explore in detail an EA that is specifically designed for traders who are keen on optimizing and utilizing liquidity raids and purges as entry criteria for their trades and trading decisions. It will also explore how to correctly differentiate between liquidity raids and market structure shifts and how to validate and utilize each of them when they occur, thus trying to mitigate losses that occur from traders confusing the two.
preview
MQL5 Trading Tools (Part 17): Exploring Vector-Based Rounded Rectangles and Triangles

MQL5 Trading Tools (Part 17): Exploring Vector-Based Rounded Rectangles and Triangles

In this article, we explore vector-based methods for drawing rounded rectangles and triangles in MQL5 using canvas, with supersampling for anti-aliased rendering. We implement scanline filling, geometric precomputations for arcs and tangents, and border drawing to create smooth, customizable shapes. This approach lays the groundwork for modern UI elements in future trading tools, supporting inputs for sizes, radii, borders, and opacities.
preview
From Basic to Intermediate: Struct (VI)

From Basic to Intermediate: Struct (VI)

In this article, we will explore how to approach the implementation of a common structural code base. The goal is to reduce the programming workload and leverage the full potential of the programming language itself—in this case, MQL5.
preview
From Basic to Intermediate: Struct (V)

From Basic to Intermediate: Struct (V)

In this article, we will explore how to overload structural code. I know it can be quite challenging to understand at first, especially if you're seeing it for the first time. It is very important that you grasp these concepts and understand them well before attempting to delve into more complex and elaborate topics.
preview
Market Simulation: (Part 11): Sockets (V)

Market Simulation: (Part 11): Sockets (V)

We are beginning to implement the connection between Excel and MetaTrader 5, but first we need to understand some key points. This way, you won't have to rack your brains trying to figure out why something works or doesn't. And before you frown at the prospect of integrating Python and Excel, let's see how we can (to some extent) control MetaTrader 5 through Excel using xlwings. What we demonstrate here will primarily focus on educational objectives. However, don't think that we can only do what will be covered here.
preview
Market Simulation (Part 14): Sockets (VIII)

Market Simulation (Part 14): Sockets (VIII)

Many programmers might assume we should abandon using Excel and move directly to Python, using some packages that allow Python to generate an Excel file for later analysis of results. However, as mentioned in the previous article, although this solution is the simplest for many programmers, it will not be accepted by some users. And in this particular case, the user is always right. As programmers, we must find a way to make everything work.
preview
From Basic to Intermediate: Struct (III)

From Basic to Intermediate: Struct (III)

In this article, we will explore what structured code is. Many people confuse structured code with organized code, but there is a difference between these two concepts. This is exactly what will be discussed in this article. Despite the apparent complexity you may feel when first encountering this type of code writing, I have tried to approach the topic as simply as possible. However, this article is just the first step toward something greater.
preview
Larry Williams Market Secrets (Part 11): Detecting Smash Day Reversals with a Custom Indicator

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

We convert Larry Williams’ Smash Day reversal rules into a practical MQL5 indicator that flags confirmed setups with arrows. Step by step, the text shows buffer binding, plot properties, historical mapping, and real‑time updates inside OnCalculate. Adjustable lookback parameters and clean chart rendering help you detect valid reversals quickly while keeping final trade decisions discretionary and context‑driven.
preview
Bivariate Copulae in MQL5: (Part 3): Implementation and Tuning of Mixed Copula Models in MQL5

Bivariate Copulae in MQL5: (Part 3): Implementation and Tuning of Mixed Copula Models in MQL5

The article extends our copula toolkit with mixed copulas implemented natively in MQL5. We construct Clayton–Frank–Gumbel and Clayton–Student–t–Gumbel mixtures, estimate them via EM, and enable sparsity control through SCAD with cross‑validation. Provided scripts tune hyperparameters, compare mixtures using information criteria, and save trained models. Practitioners can apply these components to capture asymmetric tail dependence and embed the selected model in indicators or Expert Advisors.
preview
Price Action Analysis Toolkit Development (Part 60):  Objective Swing-Based Trendlines for Structural Analysis

Price Action Analysis Toolkit Development (Part 60): Objective Swing-Based Trendlines for Structural Analysis

We present a rule-based approach to trendlines that avoids indicator pivots and uses ordered swings derived from raw prices. The article walks through swing detection, size qualification via ATR or fixed thresholds, and validation of ascending and descending structures, then implements these rules in MQL5 with non-repainting drawing and selective output. You get a clear, repeatable way to track structural support and resistance that holds up across market conditions.
preview
MQL5 Trading Tools (Part 16): Improved Super-Sampling Anti-Aliasing (SSAA) and High-Resolution Rendering

MQL5 Trading Tools (Part 16): Improved Super-Sampling Anti-Aliasing (SSAA) and High-Resolution Rendering

We add supersampling‑driven anti‑aliasing and high‑resolution rendering to the MQL5 canvas dashboard, then downsample to the target size. The article implements rounded rectangle fills and borders, rounded triangle arrows, and a custom scrollbar with theming for the stats and text panels. These tools help you build smoother, more legible UI components in MetaTrader 5.
preview
Integrating MQL5 with Data Processing Packages (Part 7): Building Multi-Agent Environments for Cross-Symbol Collaboration

Integrating MQL5 with Data Processing Packages (Part 7): Building Multi-Agent Environments for Cross-Symbol Collaboration

The article presents a complete Python–MQL5 integration for multi‑agent trading: MT5 data ingestion, indicator computation, per‑agent decisions, and a weighted consensus that outputs a single action. Signals are stored to JSON, served by Flask, and consumed by an MQL5 Expert Advisor for execution with position sizing and ATR‑derived SL/TP. Flask routes provide safe lifecycle control and status monitoring.
preview
From Basic to Intermediate: Indicator (IV)

From Basic to Intermediate: Indicator (IV)

In this article, we will explore how to easily create and implement an operational approach for coloring candles. This concept is highly valued by traders. When implementing such things, care must be taken to ensure that the bars or candles retain their original appearance and do not hinder reading candle by candle.
preview
Introduction to MQL5 (Part 39): Beginner Guide to File Handling in MQL5 (I)

Introduction to MQL5 (Part 39): Beginner Guide to File Handling in MQL5 (I)

This article introduces file handling in MQL5 using a practical, project-based workflow. You will use FileSelectDialog to choose or create a CSV file, open it with FileOpen, and write structured account headers such as account name, balance, login, date range, and last update. The result is a clear foundation for a reusable trading journal and safe file operations in MetaTrader 5.
preview
The MQL5 Standard Library Explorer (Part 8) : The Hybrid Trades Journal Logging with CFile

The MQL5 Standard Library Explorer (Part 8) : The Hybrid Trades Journal Logging with CFile

In this article, we explore the File Operations classes of the MQL5 Standard Library to build a robust reporting module that automatically generates Excel-ready CSV files. Along the way, we clearly distinguish between manually executed trades and algorithmically executed orders, laying the groundwork for reliable, auditable trade reporting.
preview
From Basic to Intermediate: Indicator (III)

From Basic to Intermediate: Indicator (III)

In this article, we will explore how to declare various graphical representation indicators, such as DRAW_COLOR_LINE and DRAW_FILLING. Additionally, of course, we will learn how to plot graphs using multiple indicators in a simple, practical, and fast way. This can truly change your perspective on MetaTrader 5 and the market as a whole.
preview
Algorithmic Trading Strategies: AI and Its Road to Golden Pinnacles

Algorithmic Trading Strategies: AI and Its Road to Golden Pinnacles

This article demonstrates an approach to creating trading strategies for gold using machine learning. Considering the proposed approach to the analysis and forecasting of time series from different angles, it is possible to determine its advantages and disadvantages in comparison with other ways of creating trading systems which are based solely on the analysis and forecasting of financial time series.
preview
Angular Analysis of Price Movements: A Hybrid Model for Predicting Financial Markets

Angular Analysis of Price Movements: A Hybrid Model for Predicting Financial Markets

What is angular analysis of financial markets? How to use price action angles and machine learning to make accurate forecasts with 67% accuracy? How to combine a regression and classification model with angular features and obtain a working algorithm? What does Gann have to do with it? Why are price movement angles a good indicator for machine learning?
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (I)

Overcoming Accessibility Problems in MQL5 Trading Tools (I)

This article explores an accessibility-focused enhancement that goes beyond default terminal alerts by leveraging MQL5 resource management to deliver contextual voice feedback. Instead of generic tones, the indicator communicates what has occurred and why, allowing traders to understand market events without relying solely on visual observation. This approach is especially valuable for visually impaired traders, but it also benefits busy or multitasking users who prefer hands-free interaction.
preview
Python-MetaTrader 5 Strategy Tester (Part 05): Multi-Symbols and Timeframes Strategy Tester

Python-MetaTrader 5 Strategy Tester (Part 05): Multi-Symbols and Timeframes Strategy Tester

This article presents a MetaTrader 5–compatible backtesting workflow that scales across symbols and timeframes. We use HistoryManager to parallelize data collection, synchronize bars and ticks from all timeframes, and run symbol‑isolated OnTick handlers in threads. You will learn how modelling modes affect speed/accuracy, when to rely on terminal data, how to reduce I/O with event‑driven updates, and how to assemble a complete multicurrency trading robot.
preview
Custom Indicator Workshop (Part 2) : Building a Practical Supertrend Expert Advisor in MQL5

Custom Indicator Workshop (Part 2) : Building a Practical Supertrend Expert Advisor in MQL5

Learn how to build a Supertrend-driven Expert Advisor in MQL5 from the ground up. The article covers embedding the indicator as a resource, reading buffer values on closed bars, detecting confirmed flips, aligning and switching positions, and configuring stop-loss modes and position sizing. It concludes with Strategy Tester setup and reproducible tests, leaving you with a configurable EA and a clear framework for further research and extensions.
preview
From Basic to Intermediate: Indicator (II)

From Basic to Intermediate: Indicator (II)

In this article, we will examine how to implement a moving average calculation and what precautions should be taken when performing this calculation. We will also discuss overloading the OnCalculate function to know when and how to work with one model or another.
preview
Analyzing Overbought and Oversold Trends Via Chaos Theory Approaches

Analyzing Overbought and Oversold Trends Via Chaos Theory Approaches

We determine the overbought and oversold condition of the market according to chaos theory: integrating the principles of chaos theory, fractal geometry and neural networks to forecast financial markets. The study demonstrates the use of the Lyapunov exponent as a measure of market randomness and the dynamic adaptation of trading signals. The methodology includes an algorithm for generating fractal noise, hyperbolic tangent activation, and moment optimization.
preview
Price Action Analysis Toolkit Development (Part 59): Using Geometric Asymmetry to Identify Precision Breakouts from Fractal Consolidation

Price Action Analysis Toolkit Development (Part 59): Using Geometric Asymmetry to Identify Precision Breakouts from Fractal Consolidation

While studying a wide range of breakout setups, I noticed that failed breakouts were rarely caused by a lack of volatility, but more often by weak internal structure. That observation led to the framework presented in this article. The approach identifies patterns where the final price leg shows superior length, steepness, and speed—clear signs of momentum accumulation ahead of directional expansion. By detecting these subtle geometric imbalances within consolidation, traders can anticipate higher-probability breakouts before price exits the range. Continue reading to see how this fractal-based, geometric framework translates structural imbalance into precise breakout signals.
preview
From Basic to Intermediate: Indicator (I)

From Basic to Intermediate: Indicator (I)

In this article, we will create our first fully practical and functional indicator. The goal is not to show how to create an application, but to help you understand how you can develop your own ideas and give you the opportunity to apply them in a safe, simple, and practical way.
preview
The MQL5 Standard Library Explorer (Part 7): Interactive Position Labeling with CCanvas

The MQL5 Standard Library Explorer (Part 7): Interactive Position Labeling with CCanvas

In this article, we explore how to build a position information visualization tool using the MQL5 Standard Library’s CCanvas. This project strengthens your skills in working with library modules while providing traders with a practical tool to visualize and interact with open positions directly on a live chart. Join the discussion to learn more.
preview
Larry Williams Market Secrets (Part 10): Automating Smash Day Reversal Patterns

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

We implement Larry Williams’ Smash Day reversal patterns in MQL5 by building a rule-based Expert Advisor with dynamic risk management, breakout confirmation logic, and one trade at a time execution. Readers can backtest, reproduce, and study parameter effects using the MetaTrader 5 Strategy Tester and the provided source.
preview
Integrating Computer Vision into Trading in MQL5 (Part 1): Creating Basic Functions

Integrating Computer Vision into Trading in MQL5 (Part 1): Creating Basic Functions

The EURUSD forecasting system with the use of computer vision and deep learning. Learn how convolutional neural networks can recognize complex price patterns in the foreign exchange market and predict exchange rate movements with up to 54% accuracy. The article shares the methodology for creating an algorithm that uses artificial intelligence technologies for visual analysis of charts instead of traditional technical indicators. The author demonstrates the process of transforming price data into "images", their processing by a neural network, and a unique opportunity to peer into the "consciousness" of AI through activation maps and attention heatmaps. Practical Python code using the MetaTrader 5 library allows readers to reproduce the system and apply it in their own trading.