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 39): Statistical Mean Reversion with Confidence Intervals and Dashboard

Automating Trading Strategies in MQL5 (Part 39): Statistical Mean Reversion with Confidence Intervals and Dashboard

In this article, we develop an MQL5 Expert Advisor for statistical mean reversion trading, calculating moments like mean, variance, skewness, kurtosis, and Jarque-Bera statistics over a specified period to identify non-normal distributions and generate buy/sell signals based on confidence intervals with adaptive thresholds
preview
How can century-old functions update your trading strategies?

How can century-old functions update your trading strategies?

This article considers the Rademacher and Walsh functions. We will explore ways to apply these functions to financial time series analysis and also consider various applications for them in trading.
preview
Reimagining Classic Strategies (Part 18): Searching For Candlestick Patterns

Reimagining Classic Strategies (Part 18): Searching For Candlestick Patterns

This article helps new community members search for and discover their own candlestick patterns. Describing these patterns can be daunting, as it requires manually searching and creatively identifying improvements. Here, we introduce the engulfing candlestick pattern and show how it can be enhanced for more profitable trading applications.
preview
Formulating Dynamic Multi-Pair EA (Part 5): Scalping vs Swing Trading Approaches

Formulating Dynamic Multi-Pair EA (Part 5): Scalping vs Swing Trading Approaches

This part explores how to design a Dynamic Multi-Pair Expert Advisor capable of adapting between Scalping and Swing Trading modes. It covers the structural and algorithmic differences in signal generation, trade execution, and risk management, allowing the EA to intelligently switch strategies based on market behavior and user input.
preview
From Novice to Expert: Forex Market Periods

From Novice to Expert: Forex Market Periods

Every market period has a beginning and an end, each closing with a price that defines its sentiment—much like any candlestick session. Understanding these reference points allows us to gauge the prevailing market mood, revealing whether bullish or bearish forces are in control. In this discussion, we take an important step forward by developing a new feature within the Market Periods Synchronizer—one that visualizes Forex market sessions to support more informed trading decisions. This tool can be especially powerful for identifying, in real time, which side—bulls or bears—dominates the session. Let’s explore this concept and uncover the insights it offers.
preview
Bivariate Copulae in MQL5 (Part 2): Implementing Archimedean copulae in MQL5

Bivariate Copulae in MQL5 (Part 2): Implementing Archimedean copulae in MQL5

In the second installment of the series, we discuss the properties of bivariate Archimedean copulae and their implementation in MQL5. We also explore applying copulae to the development of a simple pairs trading strategy.
preview
Risk-Based Trade Placement EA with On-Chart UI (Part 1): Designing the User Interface

Risk-Based Trade Placement EA with On-Chart UI (Part 1): Designing the User Interface

Learn how to build a clean and professional on-chart control panel in MQL5 for a Risk-Based Trade Placement Expert Advisor. This step-by-step guide explains how to design a functional GUI that allows traders to input trade parameters, calculate lot size, and prepare for automated order placement.
preview
Developing a multi-currency Expert Advisor (Part 22): Starting the transition to hot swapping of settings

Developing a multi-currency Expert Advisor (Part 22): Starting the transition to hot swapping of settings

If we are going to automate periodic optimization, we need to think about auto updates of the settings of the EAs already running on the trading account. This should also allow us to run the EA in the strategy tester and change its settings within a single run.
preview
Neural Networks in Trading: Memory Augmented Context-Aware Learning (MacroHFT) for Cryptocurrency Markets

Neural Networks in Trading: Memory Augmented Context-Aware Learning (MacroHFT) for Cryptocurrency Markets

I invite you to explore the MacroHFT framework, which applies context-aware reinforcement learning and memory to improve high-frequency cryptocurrency trading decisions using macroeconomic data and adaptive agents.
preview
Price Action Analysis Toolkit Development (Part 49): Integrating Trend, Momentum, and Volatility Indicators into One MQL5 System

Price Action Analysis Toolkit Development (Part 49): Integrating Trend, Momentum, and Volatility Indicators into One MQL5 System

Simplify your MetaTrader  5 charts with the Multi  Indicator  Handler EA. This interactive dashboard merges trend, momentum, and volatility indicators into one real‑time panel. Switch instantly between profiles to focus on the analysis you need most. Declutter with one‑click Hide/Show controls and stay focused on price action. Read on to learn step‑by‑step how to build and customize it yourself in MQL5.
preview
Developing a Trading Strategy: The Butterfly Oscillator Method

Developing a Trading Strategy: The Butterfly Oscillator Method

In this article, we demonstrated how the fascinating mathematical concept of the Butterfly Curve can be transformed into a practical trading tool. We constructed the Butterfly Oscillator and built a foundational trading strategy around it. The strategy effectively combines the oscillator's unique cyclical signals with traditional trend confirmation from moving averages, creating a systematic approach for identifying potential market entries.
preview
Statistical Arbitrage Through Cointegrated Stocks (Part 7): Scoring System 2

Statistical Arbitrage Through Cointegrated Stocks (Part 7): Scoring System 2

This article describes two additional scoring criteria used for selection of baskets of stocks to be traded in mean-reversion strategies, more specifically, in cointegration based statistical arbitrage. It complements a previous article where liquidity and strength of the cointegration vectors were presented, along with the strategic criteria of timeframe and lookback period, by including the stability of the cointegration vectors and the time to mean reversion (half-time). The article includes the commented results of a backtest with the new filters applied and the files required for its reproduction are also provided.
preview
Optimizing Long-Term Trades: Engulfing Candles and Liquidity Strategies

Optimizing Long-Term Trades: Engulfing Candles and Liquidity Strategies

This is a high-timeframe-based EA that makes long-term analyses, trading decisions, and executions based on higher-timeframe analyses of W1, D1, and MN. This article will explore in detail an EA that is specifically designed for long-term traders who are patient enough to withstand and hold their positions during tumultuous lower time frame price action without changing their bias frequently until take-profit targets are hit.
preview
Automating Trading Strategies in MQL5 (Part 38): Hidden RSI Divergence Trading with Slope Angle Filters

Automating Trading Strategies in MQL5 (Part 38): Hidden RSI Divergence Trading with Slope Angle Filters

In this article, we build an MQL5 EA that detects hidden RSI divergences via swing points with strength, bar ranges, tolerance, and slope angle filters for price and RSI lines. It executes buy/sell trades on validated signals with fixed lots, SL/TP in pips, and optional trailing stops for risk control.
preview
Circle Search Algorithm (CSA)

Circle Search Algorithm (CSA)

The article presents a new metaheuristic optimization Circle Search Algorithm (CSA) based on the geometric properties of a circle. The algorithm uses the principle of moving points along tangents to find the optimal solution, combining the phases of global exploration and local exploitation.
preview
MetaTrader 5 Machine Learning Blueprint (Part 5): Sequential Bootstrapping—Debiasing Labels, Improving Returns

MetaTrader 5 Machine Learning Blueprint (Part 5): Sequential Bootstrapping—Debiasing Labels, Improving Returns

Sequential bootstrapping reshapes bootstrap sampling for financial machine learning by actively avoiding temporally overlapping labels, producing more independent training samples, sharper uncertainty estimates, and more robust trading models. This practical guide explains the intuition, shows the algorithm step‑by‑step, provides optimized code patterns for large datasets, and demonstrates measurable performance gains through simulations and real backtests.
preview
Reimagining Classic Strategies (Part 17): Modelling Technical Indicators

Reimagining Classic Strategies (Part 17): Modelling Technical Indicators

In this discussion, we focus on how we can break the glass ceiling imposed by classical machine learning techniques in finance. It appears that the greatest limitation to the value we can extract from statistical models does not lie in the models themselves — neither in the data nor in the complexity of the algorithms — but rather in the methodology we use to apply them. In other words, the true bottleneck may be how we employ the model, not the model’s intrinsic capability.
preview
Market Simulation (Part 05): Creating the C_Orders Class (II)

Market Simulation (Part 05): Creating the C_Orders Class (II)

In this article, I will explain how Chart Trade, together with the Expert Advisor, will process a request to close all of the users' open positions. This may sound simple, but there are a few complications that you need to know how to manage.
preview
The MQL5 Standard Library Explorer (Part 3): Expert Standard Deviation Channel

The MQL5 Standard Library Explorer (Part 3): Expert Standard Deviation Channel

In this discussion, we will develop an Expert Advisor using the CTrade and CStdDevChannel classes, while applying several filters to enhance profitability. This stage puts our previous discussion into practical application. Additionally, I’ll introduce another simple approach to help you better understand the MQL5 Standard Library and its underlying codebase. Join the discussion to explore these concepts in action.
preview
Price Action Analysis Toolkit Development (Part 48): Multi-Timeframe Harmony Index with Weighted Bias Dashboard

Price Action Analysis Toolkit Development (Part 48): Multi-Timeframe Harmony Index with Weighted Bias Dashboard

This article introduces the “Multi-Timeframe Harmony Index”—an advanced Expert Advisor for MetaTrader 5 that calculates a weighted bias from multiple timeframes, smooths the readings using EMA, and displays the results in a clean chart panel dashboard. It includes customizable alerts and automatic buy/sell signal plotting when strong bias thresholds are crossed. Suitable for traders who use multi-timeframe analysis to align entries with overall market structure.
preview
Neural Networks in Trading: A Multi-Agent System with Conceptual Reinforcement (Final Part)

Neural Networks in Trading: A Multi-Agent System with Conceptual Reinforcement (Final Part)

We continue to implement the approaches proposed by the authors of the FinCon framework. FinCon is a multi-agent system based on Large Language Models (LLMs). Today, we will implement the necessary modules and conduct comprehensive testing of the model on real historical data.
preview
Self Optimizing Expert Advisors in MQL5 (Part 16): Supervised Linear System Identification

Self Optimizing Expert Advisors in MQL5 (Part 16): Supervised Linear System Identification

Linear system identifcation may be coupled to learn to correct the error in a supervised learning algorithm. This allows us to build applications that depend on statistical modelling techniques without necessarily inheriting the fragility of the model's restrictive assumptions. Classical supervised learning algorithms have many needs that may be supplemented by pairing these models with a feedback controller that can correct the model to keep up with current market conditions.
preview
Neural Networks in Trading: A Multi-Agent System with Conceptual Reinforcement (FinCon)

Neural Networks in Trading: A Multi-Agent System with Conceptual Reinforcement (FinCon)

We invite you to explore the FinCon framework, which is a a Large Language Model (LLM)-based multi-agent system. The framework uses conceptual verbal reinforcement to improve decision making and risk management, enabling effective performance on a variety of financial tasks.
preview
From Novice to Expert: Revealing the Candlestick Shadows (Wicks)

From Novice to Expert: Revealing the Candlestick Shadows (Wicks)

In this discussion, we take a step forward to uncover the underlying price action hidden within candlestick wicks. By integrating a wick visualization feature into the Market Periods Synchronizer, we enhance the tool with greater analytical depth and interactivity. This upgraded system allows traders to visualize higher-timeframe price rejections directly on lower-timeframe charts, revealing detailed structures that were once concealed within the shadows.
preview
Introduction to MQL5 (Part 27): Mastering API and WebRequest Function in MQL5

Introduction to MQL5 (Part 27): Mastering API and WebRequest Function in MQL5

This article introduces how to use the WebRequest() function and APIs in MQL5 to communicate with external platforms. You’ll learn how to create a Telegram bot, obtain chat and group IDs, and send, edit, and delete messages directly from MT5, building a strong foundation for mastering API integration in your future MQL5 projects.
preview
Black-Scholes Greeks: Gamma and Delta

Black-Scholes Greeks: Gamma and Delta

Gamma and Delta measure how an option’s value reacts to changes in the underlying asset’s price. Delta represents the rate of change of the option’s price relative to the underlying, while Gamma measures how Delta itself changes as price moves. Together, they describe an option’s directional sensitivity and convexity—critical for dynamic hedging and volatility-based trading strategies.
preview
Machine Learning Blueprint (Part 4): The Hidden Flaw in Your Financial ML Pipeline — Label Concurrency

Machine Learning Blueprint (Part 4): The Hidden Flaw in Your Financial ML Pipeline — Label Concurrency

Discover how to fix a critical flaw in financial machine learning that causes overfit models and poor live performance—label concurrency. When using the triple-barrier method, your training labels overlap in time, violating the core IID assumption of most ML algorithms. This article provides a hands-on solution through sample weighting. You will learn how to quantify temporal overlap between trading signals, calculate sample weights that reflect each observation's unique information, and implement these weights in scikit-learn to build more robust classifiers. Learning these essential techniques will make your trading models more robust, reliable and profitable.
preview
Automating Trading Strategies in MQL5 (Part 37): Regular RSI Divergence Convergence with Visual Indicators

Automating Trading Strategies in MQL5 (Part 37): Regular RSI Divergence Convergence with Visual Indicators

In this article, we build an MQL5 EA that detects regular RSI divergences using swing points with strength, bar limits, and tolerance checks. It executes trades on bullish or bearish signals with fixed lots, SL/TP in pips, and optional trailing stops. Visuals include colored lines on charts and labeled swings for better strategy insights.
preview
Building a Smart Trade Manager in MQL5: Automate Break-Even, Trailing Stop, and Partial Close

Building a Smart Trade Manager in MQL5: Automate Break-Even, Trailing Stop, and Partial Close

Learn how to build a Smart Trade Manager Expert Advisor in MQL5 that automates trade management with break-even, trailing stop, and partial close features. A practical, step-by-step guide for traders who want to save time and improve consistency through automation.
preview
Price Action Analysis Toolkit Development (Part 47): Tracking Forex Sessions and Breakouts in MetaTrader 5

Price Action Analysis Toolkit Development (Part 47): Tracking Forex Sessions and Breakouts in MetaTrader 5

Global market sessions shape the rhythm of the trading day, and understanding their overlap is vital to timing entries and exits. In this article, we’ll build an interactive trading sessions  EA that brings those global hours to life directly on your chart. The EA automatically plots color‑coded rectangles for the Asia, Tokyo, London, and New York sessions, updating in real time as each market opens or closes. It features on‑chart toggle buttons, a dynamic information panel, and a scrolling ticker headline that streams live status and breakout messages. Tested on different brokers, this EA combines precision with style—helping traders see volatility transitions, identify cross‑session breakouts, and stay visually connected to the global market’s pulse.
preview
Statistical Arbitrage Through Cointegrated Stocks (Part 6): Scoring System

Statistical Arbitrage Through Cointegrated Stocks (Part 6): Scoring System

In this article, we propose a scoring system for mean-reversion strategies based on statistical arbitrage of cointegrated stocks. The article suggests criteria that go from liquidity and transaction costs to the number of cointegration ranks and time to mean-reversion, while taking into account the strategic criteria of data frequency (timeframe) and the lookback period for cointegration tests, which are evaluated before the score ranking properly. The files required for the reproduction of the backtest are provided, and their results are commented on as well.
preview
Introduction to MQL5 (Part 26): Building an EA Using Support and Resistance Zones

Introduction to MQL5 (Part 26): Building an EA Using Support and Resistance Zones

This article teaches you how to build an MQL5 Expert Advisor that automatically detects support and resistance zones and executes trades based on them. You’ll learn how to program your EA to identify these key market levels, monitor price reactions, and make trading decisions without manual intervention.
preview
From Novice to Expert: Parameter Control Utility

From Novice to Expert: Parameter Control Utility

Imagine transforming the traditional EA or indicator input properties into a real-time, on-chart control interface. This discussion builds upon our foundational work in the Market Period Synchronizer indicator, marking a significant evolution in how we visualize and manage higher-timeframe (HTF) market structures. Here, we turn that concept into a fully interactive utility—a dashboard that brings dynamic control and enhanced multi-period price action visualization directly onto the chart. Join us as we explore how this innovation reshapes the way traders interact with their tools.
preview
From Basic to Intermediate: Template and Typename (V)

From Basic to Intermediate: Template and Typename (V)

In this article, we'll explore one last simple use case for templates, and discuss the benefits and necessity of using typename in your code. Although this article may seem a bit complicated at first, it is important to understand it properly in order to use templates and typename later.
preview
Overcoming The Limitation of Machine Learning (Part 6): Effective Memory Cross Validation

Overcoming The Limitation of Machine Learning (Part 6): Effective Memory Cross Validation

In this discussion, we contrast the classical approach to time series cross-validation with modern alternatives that challenge its core assumptions. We expose key blind spots in the traditional method—especially its failure to account for evolving market conditions. To address these gaps, we introduce Effective Memory Cross-Validation (EMCV), a domain-aware approach that questions the long-held belief that more historical data always improves performance.
preview
Neural Networks in Trading: A Multimodal, Tool-Augmented Agent for Financial Markets (Final Part)

Neural Networks in Trading: A Multimodal, Tool-Augmented Agent for Financial Markets (Final Part)

We continue to develop the algorithms for FinAgent, a multimodal financial trading agent designed to analyze multimodal market dynamics data and historical trading patterns.
preview
Mastering Quick Trades: Overcoming Execution Paralysis

Mastering Quick Trades: Overcoming Execution Paralysis

The UT BOT ATR Trailing Indicator is a personal and customizable indicator that is very effective for traders who like to make quick decisions and make money from differences in price referred to as short-term trading (scalpers) and also proves to be vital and very effective for long-term traders (positional traders).
preview
Market Simulation (Part 04): Creating the C_Orders Class (I)

Market Simulation (Part 04): Creating the C_Orders Class (I)

In this article, we will start creating the C_Orders class to be able to send orders to the trading server. We'll do this little by little, as our goal is to explain in detail how this will happen through the messaging system.
preview
Introduction to MQL5 (Part 25): Building an EA that Trades with Chart Objects (II)

Introduction to MQL5 (Part 25): Building an EA that Trades with Chart Objects (II)

This article explains how to build an Expert Advisor (EA) that interacts with chart objects, particularly trend lines, to identify and trade breakout and reversal opportunities. You will learn how the EA confirms valid signals, manages trade frequency, and maintains consistency with user-selected strategies.
preview
Neural Networks in Trading: A Multimodal, Tool-Augmented Agent for Financial Markets (FinAgent)

Neural Networks in Trading: A Multimodal, Tool-Augmented Agent for Financial Markets (FinAgent)

We invite you to explore FinAgent, a multimodal financial trading agent framework designed to analyze various types of data reflecting market dynamics and historical trading patterns.