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
Self Optimizing Expert Advisors in MQL5 (Part 12): Building Linear Classifiers Using Matrix Factorization

Self Optimizing Expert Advisors in MQL5 (Part 12): Building Linear Classifiers Using Matrix Factorization

This article explores the powerful role of matrix factorization in algorithmic trading, specifically within MQL5 applications. From regression models to multi-target classifiers, we walk through practical examples that demonstrate how easily these techniques can be integrated using built-in MQL5 functions. Whether you're predicting price direction or modeling indicator behavior, this guide lays a strong foundation for building intelligent trading systems using matrix methods.
preview
From Basic to Intermediate: Template and Typename (I)

From Basic to Intermediate: Template and Typename (I)

In this article, we start considering one of the concepts that many beginners avoid. This is related to the fact that templates are not an easy topic, as many do not understand the basic principle underlying the template: overload of functions and procedures.
preview
From Basic to Intermediate: Floating point

From Basic to Intermediate: Floating point

This article is a brief introduction to the concept of floating-point numbers. Since this text is very complex please, read it attentively and carefully. Do not expect to quickly master the floating-point system. It only becomes clear over time, as you gain experience using it. But this article will help you understand why your application sometimes produces results different from what you expect.
preview
From Basic to Intermediate: Overload

From Basic to Intermediate: Overload

Perhaps this article will be the most confusing for novice programmers. As a matter of fact, here I will show that it is not always that all functions and procedures have unique names in the same code. Yes, we can easily use functions and procedures with the same name — and this is called overload.
preview
From Basic to Intermediate: Definitions (II)

From Basic to Intermediate: Definitions (II)

In this article, we will continue our awareness of #define directive, but this time we will focus on its second form of use, that is, creating macros. Since this subject can be a bit complicated, we decided to use an application that we have been studying for some time. I hope you enjoy today's article.
preview
From Basic to Intermediate: Definitions (I)

From Basic to Intermediate: Definitions (I)

In this article we will do things that many will find strange and completely out of context, but which, if used correctly, will make your learning much more fun and interesting: we will be able to build quite interesting things based on what is shown here. This will allow you to better understand the syntax of the MQL5 language. The materials provided here are for educational purposes only. It should not be considered in any way as a final application. Its purpose is not to explore the concepts presented.
preview
Developing a Replay System (Part 76): New Chart Trade (III)

Developing a Replay System (Part 76): New Chart Trade (III)

In this article, we'll look at how the code of DispatchMessage, missing from the previous article, works. We will laso introduce the topic of the next article. For this reason, it is important to understand how this code works before moving on to the next topic. 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
Integrating MQL5 with data processing packages (Part 5): Adaptive Learning and Flexibility

Integrating MQL5 with data processing packages (Part 5): Adaptive Learning and Flexibility

This part focuses on building a flexible, adaptive trading model trained on historical XAUUSD data, preparing it for ONNX export and potential integration into live trading systems.
preview
Neural Networks in Trading: Enhancing Transformer Efficiency by Reducing Sharpness (Final Part)

Neural Networks in Trading: Enhancing Transformer Efficiency by Reducing Sharpness (Final Part)

SAMformer offers a solution to the key drawbacks of Transformer models in long-term time series forecasting, such as training complexity and poor generalization on small datasets. Its shallow architecture and sharpness-aware optimization help avoid suboptimal local minima. In this article, we will continue to implement approaches using MQL5 and evaluate their practical value.
preview
Formulating Dynamic Multi-Pair EA (Part 4): Volatility and Risk Adjustment

Formulating Dynamic Multi-Pair EA (Part 4): Volatility and Risk Adjustment

This phase fine-tunes your multi-pair EA to adapt trade size and risk in real time using volatility metrics like ATR boosting consistency, protection, and performance across diverse market conditions.
preview
Mastering Log Records (Part 10): Avoiding Log Replay by Implementing a Suppression

Mastering Log Records (Part 10): Avoiding Log Replay by Implementing a Suppression

We created a log suppression system in the Logify library. It details how the CLogifySuppression class reduces console noise by applying configurable rules to avoid repetitive or irrelevant messages. We also cover the external configuration framework, validation mechanisms, and comprehensive testing to ensure robustness and flexibility in log capture during bot or indicator development.
preview
From Novice to Expert: Animated News Headline Using MQL5 (VIII) — Quick Trade Buttons for News Trading

From Novice to Expert: Animated News Headline Using MQL5 (VIII) — Quick Trade Buttons for News Trading

While algorithmic trading systems manage automated operations, many news traders and scalpers prefer active control during high-impact news events and fast-paced market conditions, requiring rapid order execution and management. This underscores the need for intuitive front-end tools that integrate real-time news feeds, economic calendar data, indicator insights, AI-driven analytics, and responsive trading controls.
preview
Self Optimizing Expert Advisors in MQL5 (Part 11): A Gentle Introduction to the Fundamentals of Linear Algebra

Self Optimizing Expert Advisors in MQL5 (Part 11): A Gentle Introduction to the Fundamentals of Linear Algebra

In this discussion, we will set the foundation for using powerful linear, algebra tools that are implemented in the MQL5 matrix and vector API. For us to make proficient use of this API, we need to have a firm understanding of the principles in linear algebra that govern intelligent use of these methods. This article aims to get the reader an intuitive level of understanding of some of the most important rules of linear algebra that we, as algorithmic traders in MQL5 need,to get started, taking advantage of this powerful library.
preview
Expert Advisor based on the universal MLP approximator

Expert Advisor based on the universal MLP approximator

The article presents a simple and accessible way to use a neural network in a trading EA that does not require deep knowledge of machine learning. The method eliminates the target function normalization, as well as overcomes "weight explosion" and "network stall" issues offering intuitive training and visual control of the results.
preview
Price Action Analysis Toolkit Development (Part 34): Turning Raw Market Data into Predictive Models Using an Advanced Ingestion Pipeline

Price Action Analysis Toolkit Development (Part 34): Turning Raw Market Data into Predictive Models Using an Advanced Ingestion Pipeline

Have you ever missed a sudden market spike or been caught off‑guard when one occurred? The best way to anticipate live events is to learn from historical patterns. Intending to train an ML model, this article begins by showing you how to create a script in MetaTrader 5 that ingests historical data and sends it to Python for storage—laying the foundation for your spike‑detection system. Read on to see each step in action.
preview
From Novice to Expert: Reporting EA — Setting up the work flow

From Novice to Expert: Reporting EA — Setting up the work flow

Brokerages often provide trading account reports at regular intervals, based on a predefined schedule. These firms, through their API technologies, have access to your account activity and trading history, allowing them to generate performance reports on your behalf. Similarly, the MetaTrader 5 terminal stores detailed records of your trading activity, which can be leveraged using MQL5 to create fully customized reports and define personalized delivery methods.
preview
Market Profile indicator (Part 2): Optimization and rendering on canvas

Market Profile indicator (Part 2): Optimization and rendering on canvas

The article considers an optimized version of the Market Profile indicator, where rendering with multiple graphical objects is replaced with rendering on a canvas - an object of the CCanvas class.
preview
From Novice to Expert: Animated News Headline Using MQL5 (VII) — Post Impact Strategy for News Trading

From Novice to Expert: Animated News Headline Using MQL5 (VII) — Post Impact Strategy for News Trading

The risk of whipsaw is extremely high during the first minute following a high-impact economic news release. In that brief window, price movements can be erratic and volatile, often triggering both sides of pending orders. Shortly after the release—typically within a minute—the market tends to stabilize, resuming or correcting the prevailing trend with more typical volatility. In this section, we’ll explore an alternative approach to news trading, aiming to assess its effectiveness as a valuable addition to a trader’s toolkit. Continue reading for more insights and details in this discussion.
preview
Price Action Analysis Toolkit Development (Part 33): Candle Range Theory Tool

Price Action Analysis Toolkit Development (Part 33): Candle Range Theory Tool

Upgrade your market reading with the Candle-Range Theory suite for MetaTrader 5, a fully MQL5-native solution that converts raw price bars into real-time volatility intelligence. The lightweight CRangePattern library benchmarks each candle’s true range against an adaptive ATR and classifies it the instant it closes; the CRT Indicator then projects those classifications on your chart as crisp, color-coded rectangles and arrows that reveal tightening consolidations, explosive breakouts, and full-range engulfment the moment they occur.
preview
Population ADAM (Adaptive Moment Estimation)

Population ADAM (Adaptive Moment Estimation)

The article presents the transformation of the well-known and popular ADAM gradient optimization method into a population algorithm and its modification with the introduction of hybrid individuals. The new approach allows creating agents that combine elements of successful decisions using probability distribution. The key innovation is the formation of hybrid population individuals that adaptively accumulate information from the most promising solutions, increasing the efficiency of search in complex multidimensional spaces.
preview
Reimagining Classic Strategies (Part 14): Multiple Strategy Analysis

Reimagining Classic Strategies (Part 14): Multiple Strategy Analysis

In this article, we continue our exploration of building an ensemble of trading strategies and using the MT5 genetic optimizer to tune the strategy parameters. Today, we analyzed the data in Python, showing our model could better predict which strategy would outperform, achieving higher accuracy than forecasting market returns directly. However, when we tested our application with its statistical models, our performance levels fell dismally. We subsequently discovered that the genetic optimizer unfortunately favored highly correlated strategies, prompting us to revise our method to keep vote weights fixed and focus optimization on indicator settings instead.
preview
Self Optimizing Expert Advisors in MQL5 (Part 9): Double Moving Average Crossover

Self Optimizing Expert Advisors in MQL5 (Part 9): Double Moving Average Crossover

This article outlines the design of a double moving average crossover strategy that uses signals from a higher timeframe (D1) to guide entries on a lower timeframe (M15), with stop-loss levels calculated from an intermediate risk timeframe (H4). It introduces system constants, custom enumerations, and logic for trend-following and mean-reverting modes, while emphasizing modularity and future optimization using a genetic algorithm. The approach allows for flexible entry and exit conditions, aiming to reduce signal lag and improve trade timing by aligning lower-timeframe entries with higher-timeframe trends.
preview
From Basic to Intermediate: Recursion

From Basic to Intermediate: Recursion

In this article we will look at a very interesting and quite challenging programming concept, although it should be treated with great caution, as its misuse or misunderstanding can turn relatively simple programs into something unnecessarily complex. But when used correctly and adapted perfectly to equally suitable situations, recursion becomes an excellent ally in solving problems that would otherwise be much more laborious and time-consuming. The materials presented here are intended for educational purposes only. Under no circumstances should the application be viewed for any purpose other than to learn and master the concepts presented.
preview
Developing a Replay System (Part 75): New Chart Trade (II)

Developing a Replay System (Part 75): New Chart Trade (II)

In this article, we will talk about the C_ChartFloatingRAD class. This is what makes Chart Trade work. However, the explanation does not end there. We will complete it in the next article, as the content of this article is quite extensive and requires deep understanding. 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
Market Profile indicator

Market Profile indicator

In this article, we will consider Market Profile indicator. We will find out what lies behind this name, try to understand its operation principles and have a look at its terminal version (MarketProfile).
preview
From Basic to Intermediate: Union (II)

From Basic to Intermediate: Union (II)

Today we have a very funny and quite interesting article. We will look at Union and will try to solve the problem discussed earlier. We'll also explore some unusual situations that can arise when using union in applications. The materials presented here are intended for didactic purposes only. Under no circumstances should the application be viewed for any purpose other than to learn and master the concepts presented.
preview
From Novice to Expert: Animated News Headline Using MQL5 (V)—Event Reminder System

From Novice to Expert: Animated News Headline Using MQL5 (V)—Event Reminder System

In this discussion, we’ll explore additional advancements as we integrate refined event‑alerting logic for the economic calendar events displayed by the News Headline EA. This enhancement is critical—it ensures users receive timely notifications a short time before key upcoming events. Join this discussion to discover more.
preview
Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (3) — Weighted Voting Policy

Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (3) — Weighted Voting Policy

This article explores how determining the optimal number of strategies in an ensemble can be a complex task that is easier to solve through the use of the MetaTrader 5 genetic optimizer. The MQL5 Cloud is also employed as a key resource for accelerating backtesting and optimization. All in all, our discussion here sets the stage for developing statistical models to evaluate and improve trading strategies based on our initial ensemble results.
preview
Singular Spectrum Analysis in MQL5

Singular Spectrum Analysis in MQL5

This article is meant as a guide for those unfamiliar with the concept of Singular Spectrum Analysis and who wish to gain enough understanding to be able to apply the built-in tools available in MQL5.
preview
Master MQL5 from Beginner to Pro (Part VI): Basics of Developing Expert Advisors

Master MQL5 from Beginner to Pro (Part VI): Basics of Developing Expert Advisors

This article continues the series for beginners. Here we will discuss the basic principles of developing Expert Advisors (EAs). We will create two EAs: the first one will trade without indicators, using pending orders, and the second one will be based on the standard MA indicator, opening deals at the current price. Here I assume that you are no longer a complete beginner and have a relatively good command of the material from the previous articles.
preview
Developing a Replay System (Part 74): New Chart Trade (I)

Developing a Replay System (Part 74): New Chart Trade (I)

In this article, we will modify the last code shown in this series about Chart Trade. These changes are necessary to adapt the code to the current replay/simulation system model. 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
Graph Theory: Dijkstra's Algorithm Applied in Trading

Graph Theory: Dijkstra's Algorithm Applied in Trading

Dijkstra's algorithm, a classic shortest-path solution in graph theory, can optimize trading strategies by modeling market networks. Traders can use it to find the most efficient routes in the candlestick chart data.
preview
Formulating Dynamic Multi-Pair EA (Part 3): Mean Reversion and Momentum Strategies

Formulating Dynamic Multi-Pair EA (Part 3): Mean Reversion and Momentum Strategies

In this article, we will explore the third part of our journey in formulating a Dynamic Multi-Pair Expert Advisor (EA), focusing specifically on integrating Mean Reversion and Momentum trading strategies. We will break down how to detect and act on price deviations from the mean (Z-score), and how to measure momentum across multiple forex pairs to determine trade direction.
preview
From Basic to Intermediate: Union (I)

From Basic to Intermediate: Union (I)

In this article we will look at what a union is. Here, through experiments, we will analyze the first constructions in which union can be used. However, what will be shown here is only a core part of a set of concepts and information that will be covered in subsequent articles. 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
From Novice to Expert: Animated News Headline Using MQL5 (IV) — Locally hosted AI model market insights

From Novice to Expert: Animated News Headline Using MQL5 (IV) — Locally hosted AI model market insights

In today's discussion, we explore how to self-host open-source AI models and use them to generate market insights. This forms part of our ongoing effort to expand the News Headline EA, introducing an AI Insights Lane that transforms it into a multi-integration assistive tool. The upgraded EA aims to keep traders informed through calendar events, financial breaking news, technical indicators, and now AI-generated market perspectives—offering timely, diverse, and intelligent support to trading decisions. Join the conversation as we explore practical integration strategies and how MQL5 can collaborate with external resources to build a powerful and intelligent trading work terminal.
preview
From Novice to Expert: Animated News Headline Using MQL5 (III) — Indicator Insights

From Novice to Expert: Animated News Headline Using MQL5 (III) — Indicator Insights

In this article, we’ll advance the News Headline EA by introducing a dedicated indicator insights lane—a compact, on-chart display of key technical signals generated from popular indicators such as RSI, MACD, Stochastic, and CCI. This approach eliminates the need for multiple indicator subwindows on the MetaTrader 5 terminal, keeping your workspace clean and efficient. By leveraging the MQL5 API to access indicator data in the background, we can process and visualize market insights in real-time using custom logic. Join us as we explore how to manipulate indicator data in MQL5 to create an intelligent and space-saving scrolling insights system, all within a single horizontal lane on your trading chart.
preview
Moving Average in MQL5 from scratch: Plain and simple

Moving Average in MQL5 from scratch: Plain and simple

Using simple examples, we will examine the principles of calculating moving averages, as well as learn about the ways to optimize indicator calculations, including moving averages.
preview
Price Action Analysis Toolkit Development (Part 29): Boom and Crash Interceptor EA

Price Action Analysis Toolkit Development (Part 29): Boom and Crash Interceptor EA

Discover how the Boom & Crash Interceptor EA transforms your charts into a proactive alert system-spotting explosive moves with lightning-fast velocity scans, volatility surge checks, trend confirmation, and pivot-zone filters. With crisp green “Boom” and red “Crash” arrows guiding your every decision, this tool cuts through the noise and lets you capitalize on market spikes like never before. Dive in to see how it works and why it can become your next essential edge.
preview
Mastering Log Records (Part 9): Implementing the builder pattern and adding default configurations

Mastering Log Records (Part 9): Implementing the builder pattern and adding default configurations

This article shows how to drastically simplify the use of the Logify library with the Builder pattern and automatic default configurations. It explains the structure of the specialized builders, how to use them with smart auto-completion, and how to ensure a functional log even without manual configuration. It also covers tweaks for MetaTrader 5 build 5100.
preview
Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (2)

Self Optimizing Expert Advisors in MQL5 (Part 8): Multiple Strategy Analysis (2)

Join us for our follow-up discussion, where we will merge our first two trading strategies into an ensemble trading strategy. We shall demonstrate the different schemes possible for combining multiple strategies and also how to exercise control over the parameter space, to ensure that effective optimization remains possible even as our parameter size grows.