Articles with MQL5 programming examples

icon

Access a huge collection of articles with code examples showing how to create indicators and trading robots for the MetaTrader platform in the MQL5 language. Source codes are attached to the articles, so you can open them in MetaEditor and run them to see how the applications work.

These articles will be useful both for those who have just started exploring automated trading and for professional traders with programming experience. They feature not only examples, but also contain new ideas.

Add a new article
latest | best
preview
From Novice to Expert: Statistical Validation of Supply and Demand Zones

From Novice to Expert: Statistical Validation of Supply and Demand Zones

Today, we uncover the often overlooked statistical foundation behind supply and demand trading strategies. By combining MQL5 with Python through a Jupyter Notebook workflow, we conduct a structured, data-driven investigation aimed at transforming visual market assumptions into measurable insights. This article covers the complete research process, including data collection, Python-based statistical analysis, algorithm design, testing, and final conclusions. To explore the methodology and findings in detail, read the full article.
preview
Market Simulation (Part 10): Sockets (IV)

Market Simulation (Part 10): Sockets (IV)

In this article, we'll look at what you need to do to start using Excel to manage MetaTrader 5, but in a very interesting way. To do this, we will use an Excel add-in to avoid using built-in VBA. If you don't know what add-in is meant, read this article and learn how to program in Python directly in Excel.
preview
Graph Theory: Traversal Breadth-First Search (BFS) Applied in Trading

Graph Theory: Traversal Breadth-First Search (BFS) Applied in Trading

Breadth First Search (BFS) uses level-order traversal to model market structure as a directed graph of price swings evolving through time. By analyzing historical bars or sessions layer by layer, BFS prioritizes recent price behavior while still respecting deeper market memory.
preview
Formulating Dynamic Multi-Pair EA (Part 6): Adaptive Spread Sensitivity for High-Frequency Symbol Switching

Formulating Dynamic Multi-Pair EA (Part 6): Adaptive Spread Sensitivity for High-Frequency Symbol Switching

In this part, we will focus on designing an intelligent execution layer that continuously monitors and evaluates real-time spread conditions across multiple symbols. The EA dynamically adapts its symbol selection by enabling or disabling trading based on spread efficiency rather than fixed rules. This approach allows high-frequency multi-pair systems to prioritize cost-effective symbols.
preview
Price Action Analysis Toolkit Development (Part 57): Developing a Market State Classification Module in MQL5

Price Action Analysis Toolkit Development (Part 57): Developing a Market State Classification Module in MQL5

This article develops a market state classification module for MQL5 that interprets price behavior using completed price data. By examining volatility contraction, expansion, and structural consistency, the tool classifies market conditions as compression, transition, expansion, or trend, providing a clear contextual framework for price action analysis.
preview
The MQL5 Standard Library Explorer (Part 6): Optimizing a generated Expert Advisor

The MQL5 Standard Library Explorer (Part 6): Optimizing a generated Expert Advisor

In this discussion, we follow up on the previously developed multi-signal Expert Advisor with the objective of exploring and applying available optimization methods. The aim is to determine whether the trading performance of the EA can be meaningfully improved through systematic optimization based on historical data.
preview
Risk Management (Part 3): Building the Main Class for Risk Management

Risk Management (Part 3): Building the Main Class for Risk Management

In this article, we will begin creating a core risk management class that will be key to controlling risks in the system. We will focus on building the foundations, defining the basic structures, variables and functions. In addition, we will implement the necessary methods for setting maximum profit and loss values, thereby laying the foundation for risk management.
preview
Price Action Analysis Toolkit Development (Part 56): Reading Session Acceptance and Rejection with CPI

Price Action Analysis Toolkit Development (Part 56): Reading Session Acceptance and Rejection with CPI

This article presents a session-based analytical framework that combines time-defined market sessions with the Candle Pressure Index (CPI) to classify acceptance and rejection behavior at session boundaries using closed-candle data and clearly defined rules.
preview
Developing Market Memory Zones Indicator: Where Price Is Likely To Return

Developing Market Memory Zones Indicator: Where Price Is Likely To Return

In this discussion, we will develop an indicator to identify price zones created by strong market activity, such as impulsive moves, structure shifts, and liquidity events. These zones represent areas where the market has left “memory” due to unfilled orders or rapid price displacement. By marking these regions on the chart, the indicator highlights where price is statistically more likely to revisit and react in the future.
preview
Market Simulation (Part 09): Sockets (III)

Market Simulation (Part 09): Sockets (III)

Today's article is a continuation of the previous one. We will look at the implementation of an Expert Advisor, focusing mainly on how the server code is executed. The code given in the previous article is not enough to make everything work as expected, so we need to dig a little deeper into it. Therefore, it is necessary to read both articles to better understand what will happen.
preview
Reimagining Classic Strategies (Part 21): Bollinger Bands And RSI Ensemble Strategy Discovery

Reimagining Classic Strategies (Part 21): Bollinger Bands And RSI Ensemble Strategy Discovery

This article explores the development of an ensemble algorithmic trading strategy for the EURUSD market that combines the Bollinger Bands and the Relative Strength Indicator (RSI). Initial rule-based strategies produced high-quality signals but suffered from low trade frequency and limited profitability. Multiple iterations of the strategy were evaluated, revealing flaws in our understanding of the market, increased noise, and degraded performance. By appropriately employing statistical learning algorithms, shifting the modeling target to technical indicators, applying proper scaling, and combining machine learning forecasts with classical trading rules, the final strategy achieved significantly improved profitability and trade frequency while maintaining acceptable signal quality.
preview
From Basic to Intermediate: Events (I)

From Basic to Intermediate: Events (I)

Given everything that has been shown so far, I think we can now start implementing some kind of application to run some symbol directly on the chart. However, first we need to talk about a concept that can be rather confusing for beginners. Namely, it's the fact that applications developed in MQL5 and intended for display on a chart are not created in the same way as we have seen so far. In this article, we'll begin to understand this a little better.
preview
Building Volatility models in MQL5 (Part I): The Initial Implementation

Building Volatility models in MQL5 (Part I): The Initial Implementation

In this article, we present an MQL5 library for modeling volatility, designed to function similarly to Python's arch package. The library currently supports the specification of common conditional mean (HAR, AR, Constant Mean, Zero Mean) and conditional volatility (Constant Variance, ARCH, GARCH) models.
preview
Market Simulation (Part 08): Sockets (II)

Market Simulation (Part 08): Sockets (II)

How about creating something practical using sockets? In today's article, we'll start creating a mini-chat. Let's look together at how this is done - it will be very interesting. Please note that the code provided here is for educational purposes only. It should not be used for commercial purposes or in ready-made applications, as it does not provide data transfer security and the content transmitted over the socket can be accessed.
preview
From Novice to Expert: Higher Probability Signals

From Novice to Expert: Higher Probability Signals

In high-probability support and resistance zones, valid entry confirmation signals are always present once the zone has been correctly identified. In this discussion, we build an intelligent MQL5 program that automatically detects entry conditions within these zones. We leverage well-known candlestick patterns alongside native confirmation indicators to validate trade decisions. Click to read further.
preview
Tables in the MVC Paradigm in MQL5: Customizable and sortable table columns

Tables in the MVC Paradigm in MQL5: Customizable and sortable table columns

In the article, we will make the table column widths adjustable using the mouse cursor, sort the table by column data, and add a new class to simplify the creation of tables based on any data sets.
preview
Reimagining Classic Strategies (Part 20): Modern Stochastic Oscillators

Reimagining Classic Strategies (Part 20): Modern Stochastic Oscillators

This article demonstrates how the stochastic oscillator, a classical technical indicator, can be repurposed beyond its conventional use as a mean-reversion tool. By viewing the indicator through a different analytical lens, we show how familiar strategies can yield new value and support alternative trading rules, including trend-following interpretations. Ultimately, the article highlights how every technical indicator in the MetaTrader 5 terminal holds untapped potential, and how thoughtful trial and error can uncover meaningful interpretations hidden from view.
preview
From Novice to Expert: Navigating Market Irregularities

From Novice to Expert: Navigating Market Irregularities

Market rules are continuously evolving, and many once-reliable principles gradually lose their effectiveness. What worked in the past no longer works consistently over time. Today’s discussion focuses on probability ranges and how they can be used to navigate market irregularities. We will leverage MQL5 to develop an algorithm capable of trading effectively even in the choppiest market conditions. Join this discussion to find out more.
preview
Tables in the MVC Paradigm in MQL5: Integrating the Model Component into the View Component

Tables in the MVC Paradigm in MQL5: Integrating the Model Component into the View Component

In the article, we will create the first version of the TableControl (TableView) control. This will be a simple static table being created based on the input data defined by two arrays — a data array and an array of column headers.
preview
From Novice to Expert: Automating Trade Discipline with an MQL5 Risk Enforcement EA

From Novice to Expert: Automating Trade Discipline with an MQL5 Risk Enforcement EA

For many traders, the gap between knowing a risk rule and following it consistently is where accounts go to die. Emotional overrides, revenge trading, and simple oversight can dismantle even the best strategy. Today, we will transform the MetaTrader 5 platform into an unwavering enforcer of your trading rules by developing a Risk Enforcement Expert Advisor. Join this discussion to find out more.
preview
The View and Controller components for tables in the MQL5 MVC paradigm: Resizable elements

The View and Controller components for tables in the MQL5 MVC paradigm: Resizable elements

In the article, we will add the functionality of resizing controls by dragging edges and corners of the element with the mouse.
preview
From Novice to Expert: Trading the RSI with Market Structure Awareness

From Novice to Expert: Trading the RSI with Market Structure Awareness

In this article, we will explore practical techniques for trading the Relative Strength Index (RSI) oscillator with market structure. Our focus will be on channel price action patterns, how they are typically traded, and how MQL5 can be leveraged to enhance this process. By the end, you will have a rule-based, automated channel-trading system designed to capture trend continuation opportunities with greater precision and consistency.
preview
Adaptive Smart Money Architecture (ASMA): Merging SMC Logic With Market Sentiment for Dynamic Strategy Switching

Adaptive Smart Money Architecture (ASMA): Merging SMC Logic With Market Sentiment for Dynamic Strategy Switching

This topic explores how to build an Adaptive Smart Money Architecture (ASMA)—an intelligent Expert Advisor that merges Smart Money Concepts (Order Blocks, Break of Structure, Fair Value Gaps) with real-time market sentiment to automatically choose the best trading strategy depending on current market conditions.
preview
Overcoming The Limitation of Machine Learning (Part 9): Correlation-Based Feature Learning in Self-Supervised Finance

Overcoming The Limitation of Machine Learning (Part 9): Correlation-Based Feature Learning in Self-Supervised Finance

Self-supervised learning is a powerful paradigm of statistical learning that searches for supervisory signals generated from the observations themselves. This approach reframes challenging unsupervised learning problems into more familiar supervised ones. This technology has overlooked applications for our objective as a community of algorithmic traders. Our discussion, therefore, aims to give the reader an approachable bridge into the open research area of self-supervised learning and offers practical applications that provide robust and reliable statistical models of financial markets without overfitting to small datasets.
preview
Fortified Profit Architecture: Multi-Layered Account Protection

Fortified Profit Architecture: Multi-Layered Account Protection

In this discussion, we introduce a structured, multi-layered defense system designed to pursue aggressive profit targets while minimizing exposure to catastrophic loss. The focus is on blending offensive trading logic with protective safeguards at every level of the trading pipeline. The idea is to engineer an EA that behaves like a “risk-aware predator”—capable of capturing high-value opportunities, but always with layers of insulation that prevent blindness to sudden market stress.
preview
The View and Controller components for tables in the MQL5 MVC paradigm: Containers

The View and Controller components for tables in the MQL5 MVC paradigm: Containers

In this article, we will discuss creating a "Container" control that supports scrolling its contents. Within the process, the already implemented classes of graphics library controls will be improved.
preview
From Novice to Expert: Developing a Geographic Market Awareness with MQL5 Visualization

From Novice to Expert: Developing a Geographic Market Awareness with MQL5 Visualization

Trading without session awareness is like navigating without a compass—you're moving, but not with purpose. Today, we're revolutionizing how traders perceive market timing by transforming ordinary charts into dynamic geographical displays. Using MQL5's powerful visualization capabilities, we'll build a live world map that illuminates active trading sessions in real-time, turning abstract market hours into intuitive visual intelligence. This journey sharpens your trading psychology and reveals professional-grade programming techniques that bridge the gap between complex market structure and practical, actionable insight.
preview
Reimagining Classic Strategies (Part 19): Deep Dive Into Moving Average Crossovers

Reimagining Classic Strategies (Part 19): Deep Dive Into Moving Average Crossovers

This article revisits the classic moving average crossover strategy and examines why it often fails in noisy, fast-moving markets. It presents five alternative filtering methods designed to strengthen signal quality and remove weak or unprofitable trades. The discussion highlights how statistical models can learn and correct the errors that human intuition and traditional rules miss. Readers leave with a clearer understanding of how to modernize an outdated strategy and of the pitfalls of relying solely on metrics like RMSE in financial modeling.
preview
The View and Controller components for tables in the MQL5 MVC paradigm: Simple controls

The View and Controller components for tables in the MQL5 MVC paradigm: Simple controls

The article covers simple controls as components of more complex graphical elements of the View component within the framework of table implementation in the MVC (Model-View-Controller) paradigm. The basic functionality of the Controller is implemented for interaction of elements with the user and with each other. This is the second article on the View component and the fourth one in a series of articles on creating tables for the MetaTrader 5 client terminal.
preview
From Basic to Intermediate: Structs (II)

From Basic to Intermediate: Structs (II)

In this article, we will try to understand why programming languages like MQL5 have structures, and why in some cases structures are the ideal way to pass values between functions and procedures, while in other cases they may not be the best way to do it.
preview
The MQL5 Standard Library Explorer (Part 5): Multiple Signal Expert

The MQL5 Standard Library Explorer (Part 5): Multiple Signal Expert

In this session, we will build a sophisticated, multi-signal Expert Advisor using the MQL5 Standard Library. This approach allows us to seamlessly blend built-in signals with our own custom logic, demonstrating how to construct a powerful and flexible trading algorithm. For more, click to read further.
preview
The View component for tables in the MQL5 MVC paradigm: Base graphical element

The View component for tables in the MQL5 MVC paradigm: Base graphical element

The article covers the process of developing a base graphical element for the View component as part of the implementation of tables in the MVC (Model-View-Controller) paradigm in MQL5. This is the first article on the View component and the third one in a series of articles on creating tables for the MetaTrader 5 client terminal.
preview
The MQL5 Standard Library Explorer (Part 4): Custom Signal Library

The MQL5 Standard Library Explorer (Part 4): Custom Signal Library

Today, we use the MQL5 Standard Library to build custom signal classes and let the MQL5 Wizard assemble a professional Expert Advisor for us. This approach simplifies development so that even beginner programmers can create robust EAs without in-depth coding knowledge, focusing instead on tuning inputs and optimizing performance. Join this discussion as we explore the process step by step.
preview
From Basic to Intermediate: Struct (I)

From Basic to Intermediate: Struct (I)

Today we will begin to study structures in a simpler, more practical, and comfortable way. Structures are among the foundations of programming, whether they are structured or not. I know many people think of structures as just collections of data, but I assure you that they are much more than just structures. And here we will begin to explore this new universe in the most didactic way.
preview
Market Simulation (Part 07): Sockets (I)

Market Simulation (Part 07): Sockets (I)

Sockets. Do you know what they are for or how to use them in MetaTrader 5? If the answer is no, let's start by studying them. In today's article, we'll cover the basics. Since there are several ways to do the same thing, and we are always interested in the result, I want to show that there is indeed a simple way to transfer data from MetaTrader 5 to other programs, such as Excel. However, the main idea is not to transfer data from MetaTrader 5 to Excel, but the opposite, that is, to transfer data from Excel or any other program to MetaTrader 5.
preview
Price Action Analysis Toolkit Development (Part 52): Master Market Structure with Multi-Timeframe Visual Analysis

Price Action Analysis Toolkit Development (Part 52): Master Market Structure with Multi-Timeframe Visual Analysis

This article presents the Multi‑Timeframe Visual Analyzer, an MQL5 Expert Advisor that reconstructs and overlays higher‑timeframe candles directly onto your active chart. It explains the implementation, key inputs, and practical outcomes, supported by an animated demo and chart examples showing instant toggling, multi‑timeframe confirmation, and configurable alerts. Read on to see how this tool can make chart analysis faster, clearer, and more efficient.
preview
Table and Header Classes based on a table model in MQL5: Applying the MVC concept

Table and Header Classes based on a table model in MQL5: Applying the MVC concept

This is the second part of the article devoted to the implementation of the table model in MQL5 using the MVC (Model-View-Controller) architectural paradigm. The article discusses the development of table classes and the table header based on a previously created table model. The developed classes will form the basis for further implementation of View and Controller components, which will be discussed in the following articles.
preview
Analytical Volume Profile Trading (AVPT): Liquidity Architecture, Market Memory, and Algorithmic Execution

Analytical Volume Profile Trading (AVPT): Liquidity Architecture, Market Memory, and Algorithmic Execution

Analytical Volume Profile Trading (AVPT) explores how liquidity architecture and market memory shape price behavior, enabling more profound insight into institutional positioning and volume-driven structure. By mapping POC, HVNs, LVNs, and Value Areas, traders can identify acceptance, rejection, and imbalance zones with precision.
preview
Price Action Analysis Toolkit Development (Part 51): Revolutionary Chart Search Technology for Candlestick Pattern Discovery

Price Action Analysis Toolkit Development (Part 51): Revolutionary Chart Search Technology for Candlestick Pattern Discovery

This article is intended for algorithmic traders, quantitative analysts, and MQL5 developers interested in enhancing their understanding of candlestick pattern recognition through practical implementation. It provides an in‑depth exploration of the CandlePatternSearch.mq5 Expert Advisor—a complete framework for detecting, visualizing, and monitoring classical candlestick formations in MetaTrader 5. Beyond a line‑by‑line review of the code, the article discusses architectural design, pattern detection logic, GUI integration, and alert mechanisms, illustrating how traditional price‑action analysis can be automated efficiently.
preview
Automating Black-Scholes Greeks: Advanced Scalping and Microstructure Trading

Automating Black-Scholes Greeks: Advanced Scalping and Microstructure Trading

Gamma and Delta were originally developed as risk-management tools for hedging options exposure, but over time they evolved into powerful instruments for advanced scalping, order-flow modeling, and microstructure trading. Today, they serve as real-time indicators of price sensitivity and liquidity behavior, enabling traders to anticipate short-term volatility with remarkable precision.