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
Automating Trading Strategies in MQL5 (Part 32): Creating a Price Action 5 Drives Harmonic Pattern System

Automating Trading Strategies in MQL5 (Part 32): Creating a Price Action 5 Drives Harmonic Pattern System

In this article, we develop a 5 Drives pattern system in MQL5 that identifies bullish and bearish 5 Drives harmonic patterns using pivot points and Fibonacci ratios, executing trades with customizable entry, stop loss, and take-profit levels based on user-selected options. We enhance trader insight with visual feedback through chart objects like triangles, trendlines, and labels to clearly display the A-B-C-D-E-F pattern structure.
preview
Developing a multi-currency Expert Advisor (Part 21): Preparing for an important experiment and optimizing the code

Developing a multi-currency Expert Advisor (Part 21): Preparing for an important experiment and optimizing the code

For further progress it would be good to see if we can improve the results by periodically re-running the automatic optimization and generating a new EA. The stumbling block in many debates about the use of parameter optimization is the question of how long the obtained parameters can be used for trading in the future period while maintaining the profitability and drawdown at the specified levels. And is it even possible to do this?
preview
Neural Networks in Trading: A Hybrid Trading Framework with Predictive Coding (StockFormer)

Neural Networks in Trading: A Hybrid Trading Framework with Predictive Coding (StockFormer)

In this article, we will discuss the hybrid trading system StockFormer, which combines predictive coding and reinforcement learning (RL) algorithms. The framework uses 3 Transformer branches with an integrated Diversified Multi-Head Attention (DMH-Attn) mechanism that improves on the vanilla attention module with a multi-headed Feed-Forward block, allowing it to capture diverse time series patterns across different subspaces.
preview
Mastering Fair Value Gaps: Formation, Logic, and Automated Trading with Breakers and Market Structure Shifts

Mastering Fair Value Gaps: Formation, Logic, and Automated Trading with Breakers and Market Structure Shifts

This is an article that I have written aimed to expound and explain Fair Value Gaps, their formation logic for occurring, and automated trading with breakers and market structure shifts.
preview
Dynamic mode decomposition applied to univariate time series in MQL5

Dynamic mode decomposition applied to univariate time series in MQL5

Dynamic mode decomposition (DMD) is a technique usually applied to high-dimensional datasets. In this article, we demonstrate the application of DMD on univariate time series, showing its ability to characterize a series as well as make forecasts. In doing so, we will investigate MQL5's built-in implementation of dynamic mode decomposition, paying particular attention to the new matrix method, DynamicModeDecomposition().
preview
Automating Trading Strategies in MQL5 (Part 31): Creating a Price Action 3 Drives Harmonic Pattern System

Automating Trading Strategies in MQL5 (Part 31): Creating a Price Action 3 Drives Harmonic Pattern System

In this article, we develop a 3 Drives Pattern system in MQL5 that identifies bullish and bearish 3 Drives harmonic patterns using pivot points and Fibonacci ratios, executing trades with customizable entry, stop loss, and take-profit levels based on user-selected options. We enhance trader insight with visual feedback through chart objects.
preview
Moving to MQL5 Algo Forge (Part 2): Working with Multiple Repositories

Moving to MQL5 Algo Forge (Part 2): Working with Multiple Repositories

In this article, we are considering one of the possible approaches to organizing the storage of the project's source code in a public repository. We will distribute the code across different branches to establish clear and convenient rules for the project development.
preview
Self Optimizing Expert Advisors in MQL5 (Part 14): Viewing Data Transformations as Tuning Parameters of Our Feedback Controller

Self Optimizing Expert Advisors in MQL5 (Part 14): Viewing Data Transformations as Tuning Parameters of Our Feedback Controller

Preprocessing is a powerful yet quickly overlooked tuning parameter. It lives in the shadows of its bigger brothers: optimizers and shiny model architectures. Small percentage improvements here can have disproportionately large, compounding effects on profitability and risk. Too often, this largely unexplored science is boiled down to a simple routine, seen only as a means to an end, when in reality it is where signal can be directly amplified, or just as easily destroyed.
preview
Developing a Custom Market Sentiment Indicator

Developing a Custom Market Sentiment Indicator

In this article we are developing a custom market sentiment indicator to classify conditions into bullish, bearish, risk-on, risk-off, or neutral. Using multi-timeframe, the indicator can provide traders with a clearer perspective of overall market bias and short-term confirmations.
preview
Statistical Arbitrage Through Cointegrated Stocks (Part 4): Real-time Model Updating

Statistical Arbitrage Through Cointegrated Stocks (Part 4): Real-time Model Updating

This article describes a simple but comprehensive statistical arbitrage pipeline for trading a basket of cointegrated stocks. It includes a fully functional Python script for data download and storage; correlation, cointegration, and stationarity tests, along with a sample Metatrader 5 Service implementation for database updating, and the respective Expert Advisor. Some design choices are documented here for reference and for helping in the experiment replication.
preview
Elevate Your Trading With Smart Money Concepts (SMC): OB, BOS, and FVG

Elevate Your Trading With Smart Money Concepts (SMC): OB, BOS, and FVG

Elevate your trading with Smart Money Concepts (SMC) by combining Order Blocks (OB), Break of Structure (BOS), and Fair Value Gaps (FVG) into one powerful EA. Choose automatic strategy execution or focus on any individual SMC concept for flexible and precise trading.
preview
Moving to MQL5 Algo Forge (Part 1): Creating the Main Repository

Moving to MQL5 Algo Forge (Part 1): Creating the Main Repository

When working on projects in MetaEditor, developers often face the need to manage code versions. MetaQuotes recently announced migration to GIT and the launch of MQL5 Algo Forge with code versioning and collaboration capabilities. In this article, we will discuss how to use the new and previously existing tools more efficiently.
preview
Automating Trading Strategies in MQL5 (Part 30): Creating a Price Action AB-CD Harmonic Pattern with Visual Feedback

Automating Trading Strategies in MQL5 (Part 30): Creating a Price Action AB-CD Harmonic Pattern with Visual Feedback

In this article, we develop an AB=CD Pattern EA in MQL5 that identifies bullish and bearish AB=CD harmonic patterns using pivot points and Fibonacci ratios, executing trades with precise entry, stop loss, and take-profit levels. We enhance trader insight with visual feedback through chart objects.
preview
From Novice to Expert: Animated News Headline Using MQL5 (X)—Multiple Symbol Chart View for News Trading

From Novice to Expert: Animated News Headline Using MQL5 (X)—Multiple Symbol Chart View for News Trading

Today we will develop a multi-chart view system using chart objects. The goal is to enhance news trading by applying MQL5 algorithms that help reduce trader reaction time during periods of high volatility, such as major news releases. In this case, we provide traders with an integrated way to monitor multiple major symbols within a single all-in-one news trading tool. Our work is continuously advancing with the News Headline EA, which now features a growing set of functions that add real value both for traders using fully automated systems and for those who prefer manual trading assisted by algorithms. Explore more knowledge, insights, and practical ideas by clicking through and joining this discussion.
preview
Price Action Analysis Toolkit Development (Part 39): Automating BOS and ChoCH Detection in MQL5

Price Action Analysis Toolkit Development (Part 39): Automating BOS and ChoCH Detection in MQL5

This article presents Fractal Reaction System, a compact MQL5 system that converts fractal pivots into actionable market-structure signals. Using closed-bar logic to avoid repainting, the EA detects Change-of-Character (ChoCH) warnings and confirms Breaks-of-Structure (BOS), draws persistent chart objects, and logs/alerts every confirmed event (desktop, mobile and sound). Read on for the algorithm design, implementation notes, testing results and the full EA code so you can compile, test and deploy the detector yourself.
preview
Polynomial models in trading

Polynomial models in trading

This article is about orthogonal polynomials. Their use can become the basis for a more accurate and effective analysis of market information allowing traders to make more informed decisions.
preview
Market Simulation (Part 01): Cross Orders (I)

Market Simulation (Part 01): Cross Orders (I)

Today we will begin the second stage, where we will look at the market replay/simulation system. First, we will show a possible solution for cross orders. I will show you the solution, but it is not final yet. It will be a possible solution to a problem that we will need to solve in the near future.
preview
Big Bang - Big Crunch (BBBC) algorithm

Big Bang - Big Crunch (BBBC) algorithm

The article presents the Big Bang - Big Crunch method, which has two key phases: cyclic generation of random points and their compression to the optimal solution. This approach combines exploration and refinement, allowing us to gradually find better solutions and open up new optimization opportunities.
preview
Neural Networks in Trading: An Ensemble of Agents with Attention Mechanisms (MASAAT)

Neural Networks in Trading: An Ensemble of Agents with Attention Mechanisms (MASAAT)

We introduce the Multi-Agent Self-Adaptive Portfolio Optimization Framework (MASAAT), which combines attention mechanisms and time series analysis. MASAAT generates a set of agents that analyze price series and directional changes, enabling the identification of significant fluctuations in asset prices at different levels of detail.
preview
Overcoming The Limitation of Machine Learning (Part 3): A Fresh Perspective on Irreducible Error

Overcoming The Limitation of Machine Learning (Part 3): A Fresh Perspective on Irreducible Error

This article takes a fresh perspective on a hidden, geometric source of error that quietly shapes every prediction your models make. By rethinking how we measure and apply machine learning forecasts in trading, we reveal how this overlooked perspective can unlock sharper decisions, stronger returns, and a more intelligent way to work with models we thought we already understood.
preview
Building a Professional Trading System with Heikin Ashi (Part 1): Developing a custom indicator

Building a Professional Trading System with Heikin Ashi (Part 1): Developing a custom indicator

This article is the first installment in a two-part series designed to impart practical skills and best practices for writing custom indicators in MQL5. Using Heikin Ashi as a working example, the article explores the theory behind Heikin Ashi charts, explains how Heikin Ashi candlesticks are calculated, and demonstrates their application in technical analysis. The centerpiece is a step-by-step guide to developing a fully functional Heikin Ashi indicator from scratch, with clear explanations to help readers understand what to code and why. This foundational knowledge sets the stage for Part Two, where we will build an expert advisor that trades based on Heikin Ashi logic.
preview
Trend strength and direction indicator on 3D bars

Trend strength and direction indicator on 3D bars

We will consider a new approach to market trend analysis based on three-dimensional visualization and tensor analysis of the market microstructure.
preview
Price Action Analysis Toolkit Development (Part 38): Tick Buffer VWAP and Short-Window Imbalance Engine

Price Action Analysis Toolkit Development (Part 38): Tick Buffer VWAP and Short-Window Imbalance Engine

In Part 38, we build a production-grade MT5 monitoring panel that converts raw ticks into actionable signals. The EA buffers tick data to compute tick-level VWAP, a short-window imbalance (flow) metric, and ATR-based position sizing. It then visualizes spread, ATR, and flow with low-flicker bars. The system calculates a suggested lot size and a 1R stop, and issues configurable alerts for tight spreads, strong flow, and edge conditions. Auto-trading is intentionally disabled; the focus remains on robust signal generation and a clean user experience.
preview
Black Hole Algorithm (BHA)

Black Hole Algorithm (BHA)

The Black Hole Algorithm (BHA) uses the principles of black hole gravity to optimize solutions. In this article, we will look at how BHA attracts the best solutions while avoiding local extremes, and why this algorithm has become a powerful tool for solving complex problems. Learn how simple ideas can lead to impressive results in the world of optimization.
preview
Developing a Replay System (Part 78): New Chart Trade (V)

Developing a Replay System (Part 78): New Chart Trade (V)

In this article, we will look at how to implement part of the receiver code. Here we will implement an Expert Advisor to test and learn how the protocol interaction works. The content presented here is intended solely for educational purposes. Under no circumstances should the application be viewed for any purpose other than to learn and master the concepts presented.
preview
Neural Networks in Trading: A Multi-Agent Self-Adaptive Model (Final Part)

Neural Networks in Trading: A Multi-Agent Self-Adaptive Model (Final Part)

In the previous article, we introduced the multi-agent adaptive framework MASA, which combines reinforcement learning approaches and self-adaptive strategies, providing a harmonious balance between profitability and risk in turbulent market conditions. We have built the functionality of individual agents within this framework. In this article, we will continue the work we started, bringing it to its logical conclusion.
preview
Automating Trading Strategies in MQL5 (Part 29): Creating a price action Gartley Harmonic Pattern system

Automating Trading Strategies in MQL5 (Part 29): Creating a price action Gartley Harmonic Pattern system

In this article, we develop a Gartley Pattern system in MQL5 that identifies bullish and bearish Gartley harmonic patterns using pivot points and Fibonacci ratios, executing trades with precise entry, stop loss, and take-profit levels. We enhance trader insight with visual feedback through chart objects like triangles, trendlines, and labels to clearly display the XABCD pattern structure.
preview
Building a Trading System (Part 3): Determining Minimum Risk Levels for Realistic Profit Targets

Building a Trading System (Part 3): Determining Minimum Risk Levels for Realistic Profit Targets

Every trader's ultimate goal is profitability, which is why many set specific profit targets to achieve within a defined trading period. In this article, we will use Monte Carlo simulations to determine the optimal risk percentage per trade needed to meet trading objectives. The results will help traders assess whether their profit targets are realistic or overly ambitious. Finally, we will discuss which parameters can be adjusted to establish a practical risk percentage per trade that aligns with trading goals.
preview
Multi-module trading robot in Python and MQL5 (Part I): Creating basic architecture and first modules

Multi-module trading robot in Python and MQL5 (Part I): Creating basic architecture and first modules

We are going to develop a modular trading system that combines Python for data analysis with MQL5 for trade execution. Four independent modules monitor different market aspects in parallel: volumes, arbitrage, economics and risks, and use RandomForest with 400 trees for analysis. Particular emphasis is placed on risk management, since even the most advanced trading algorithms are useless without proper risk management.
preview
MetaTrader Meets Google Sheets with Pythonanywhere: A Guide to Secure Data Flow

MetaTrader Meets Google Sheets with Pythonanywhere: A Guide to Secure Data Flow

This article demonstrates a secure way to export MetaTrader data to Google Sheets. Google Sheet is the most valuable solution as it is cloud based and the data saved in there can be accessed anytime and from anywhere. So traders can access trading and related data exported to google sheet and do further analysis for future trading anytime and wherever they are at the moment.
preview
From Novice to Expert: Mastering Detailed Trading Reports with Reporting EA

From Novice to Expert: Mastering Detailed Trading Reports with Reporting EA

In this article, we delve into enhancing the details of trading reports and delivering the final document via email in PDF format. This marks a progression from our previous work, as we continue exploring how to harness the power of MQL5 and Python to generate and schedule trading reports in the most convenient and professional formats. Join us in this discussion to learn more about optimizing trading report generation within the MQL5 ecosystem.
preview
Chart Synchronization for Easier Technical Analysis

Chart Synchronization for Easier Technical Analysis

Chart Synchronization for Easier Technical Analysis is a tool that ensures all chart timeframes display consistent graphical objects like trendlines, rectangles, or indicators across different timeframes for a single symbol. Actions such as panning, zooming, or symbol changes are mirrored across all synced charts, allowing traders to seamlessly view and compare the same price action context in multiple timeframes.
preview
Developing a Replay System (Part 77): New Chart Trade (IV)

Developing a Replay System (Part 77): New Chart Trade (IV)

In this article, we will cover some of the measures and precautions to consider when creating a communication protocol. These are pretty simple and straightforward things, so we won't go into too much detail in this article. But to understand what will happen, you need to understand the content of the article.
preview
Simplifying Databases in MQL5 (Part 1): Introduction to Databases and SQL

Simplifying Databases in MQL5 (Part 1): Introduction to Databases and SQL

We explore how to manipulate databases in MQL5 using the language's native functions. We cover everything from table creation, insertion, updating, and deletion to data import and export, all with sample code. The content serves as a solid foundation for understanding the internal mechanics of data access, paving the way for the discussion of ORM, where we'll build one in MQL5.
preview
Trend criteria in trading

Trend criteria in trading

Trends are an important part of many trading strategies. In this article, we will look at some of the tools used to identify trends and their characteristics. Understanding and correctly interpreting trends can significantly improve trading efficiency and minimize risks.
preview
Getting Started with MQL5 Algo Forge

Getting Started with MQL5 Algo Forge

We are introducing MQL5 Algo Forge — a dedicated portal for algorithmic trading developers. It combines the power of Git with an intuitive interface for managing and organizing projects within the MQL5 ecosystem. Here, you can follow interesting authors, form teams, and collaborate on algorithmic trading projects.
preview
Automating Trading Strategies in MQL5 (Part 28): Creating a Price Action Bat Harmonic Pattern with Visual Feedback

Automating Trading Strategies in MQL5 (Part 28): Creating a Price Action Bat Harmonic Pattern with Visual Feedback

In this article, we develop a Bat Pattern system in MQL5 that identifies bullish and bearish Bat harmonic patterns using pivot points and Fibonacci ratios, triggering trades with precise entry, stop loss, and take-profit levels, enhanced with visual feedback through chart objects
preview
Analyzing binary code of prices on the exchange (Part II): Converting to BIP39 and writing GPT model

Analyzing binary code of prices on the exchange (Part II): Converting to BIP39 and writing GPT model

Continuing tries to decipher price movements... What about linguistic analysis of the "market dictionary" that we get by converting the binary price code to BIP39? In this article, we will delve into an innovative approach to exchange data analysis and consider how modern natural language processing techniques can be applied to the market language.
preview
Neural Networks in Trading: A Multi-Agent Self-Adaptive Model (MASA)

Neural Networks in Trading: A Multi-Agent Self-Adaptive Model (MASA)

I invite you to get acquainted with the Multi-Agent Self-Adaptive (MASA) framework, which combines reinforcement learning and adaptive strategies, providing a harmonious balance between profitability and risk management in turbulent market conditions.
preview
Artificial Tribe Algorithm (ATA)

Artificial Tribe Algorithm (ATA)

The article provides a detailed discussion of the key components and innovations of the ATA optimization algorithm, which is an evolutionary method with a unique dual behavior system that adapts depending on the situation. ATA combines individual and social learning while using crossover for explorations and migration to find solutions when stuck in local optima.