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 Basic to Intermediate: Operators

From Basic to Intermediate: Operators

In this article we will look at the main operators. Although the topic is simple to understand, there are certain points that are of great importance when it comes to including mathematical expressions in the code format. Without an adequate understanding of these details, programmers with little or no experience eventually give up trying to create their own solutions.
preview
Price Action Analysis Toolkit Development (Part 15): Introducing Quarters Theory (I) — Quarters Drawer Script

Price Action Analysis Toolkit Development (Part 15): Introducing Quarters Theory (I) — Quarters Drawer Script

Points of support and resistance are critical levels that signal potential trend reversals and continuations. Although identifying these levels can be challenging, once you pinpoint them, you’re well-prepared to navigate the market. For further assistance, check out the Quarters Drawer tool featured in this article, it will help you identify both primary and minor support and resistance levels.
preview
Anarchic Society Optimization (ASO) algorithm

Anarchic Society Optimization (ASO) algorithm

In this article, we will get acquainted with the Anarchic Society Optimization (ASO) algorithm and discuss how an algorithm based on the irrational and adventurous behavior of participants in an anarchic society (an anomalous system of social interaction free from centralized power and various kinds of hierarchies) is able to explore the solution space and avoid the traps of local optimum. The article presents a unified ASO structure applicable to both continuous and discrete problems.
preview
Build Self Optimizing Expert Advisors in MQL5 (Part 6): Stop Out Prevention

Build Self Optimizing Expert Advisors in MQL5 (Part 6): Stop Out Prevention

Join us in our discussion today as we look for an algorithmic procedure to minimize the total number of times we get stopped out of winning trades. The problem we faced is significantly challenging, and most solutions given in community discussions lack set and fixed rules. Our algorithmic approach to solving the problem increased the profitability of our trades and reduced our average loss per trade. However, there are further advancements to be made to completely filter out all trades that will be stopped out, our solution is a good first step for anyone to try.
preview
Master MQL5 from beginner to pro (Part IV): About Arrays, Functions and Global Terminal Variables

Master MQL5 from beginner to pro (Part IV): About Arrays, Functions and Global Terminal Variables

The article is a continuation of the series for beginners. It covers in detail data arrays, the interaction of data and functions, as well as global terminal variables that allow data exchange between different MQL5 programs.
preview
Creating a Trading Administrator Panel in MQL5 (Part IX): Code Organization (II): Modularization

Creating a Trading Administrator Panel in MQL5 (Part IX): Code Organization (II): Modularization

In this discussion, we take a step further in breaking down our MQL5 program into smaller, more manageable modules. These modular components will then be integrated into the main program, enhancing its organization and maintainability. This approach simplifies the structure of our main program and makes the individual components reusable in other Expert Advisors (EAs) and indicator developments. By adopting this modular design, we create a solid foundation for future enhancements, benefiting both our project and the broader developer community.
preview
Developing a Replay System (Part 59): A New Future

Developing a Replay System (Part 59): A New Future

Having a proper understanding of different ideas allows us to do more with less effort. In this article, we'll look at why it's necessary to configure a template before the service can interact with the chart. Also, what if we improve the mouse pointer so we can do more things with it?
preview
From Basic to Intermediate: Variables (III)

From Basic to Intermediate: Variables (III)

Today we will look at how to use predefined MQL5 language variables and constants. In addition, we will analyze another special type of variables: functions. Knowing how to properly work with these variables can mean the difference between an application that works and one that doesn't. In order to understand what is presented here, it is necessary to understand the material that was discussed in previous articles.
preview
Deconstructing examples of trading strategies in the client terminal

Deconstructing examples of trading strategies in the client terminal

The article uses block diagrams to examine the logic of the candlestick-based training EAs located in the Experts\Free Robots folder of the terminal.
preview
Robustness Testing on Expert Advisors

Robustness Testing on Expert Advisors

In strategy development, there are many intricate details to consider, many of which are not highlighted for beginner traders. As a result, many traders, myself included, have had to learn these lessons the hard way. This article is based on my observations of common pitfalls that most beginner traders encounter when developing strategies on MQL5. It will offer a range of tips, tricks, and examples to help identify the disqualification of an EA and test the robustness of our own EAs in an easy-to-implement way. The goal is to educate readers, helping them avoid future scams when purchasing EAs as well as preventing mistakes in their own strategy development.
preview
Mastering Log Records (Part 5): Optimizing the Handler with Cache and Rotation

Mastering Log Records (Part 5): Optimizing the Handler with Cache and Rotation

This article improves the logging library by adding formatters in handlers, the CIntervalWatcher class to manage execution cycles, optimization with caching and file rotation, performance tests and practical examples. With these improvements, we ensure an efficient, scalable and adaptable logging system to different development scenarios.
preview
Creating a Trading Administrator Panel in MQL5 (Part IX): Code Organization (I)

Creating a Trading Administrator Panel in MQL5 (Part IX): Code Organization (I)

This discussion delves into the challenges encountered when working with large codebases. We will explore the best practices for code organization in MQL5 and implement a practical approach to enhance the readability and scalability of our Trading Administrator Panel source code. Additionally, we aim to develop reusable code components that can potentially benefit other developers in their algorithm development. Read on and join the conversation.
preview
Feature Engineering With Python And MQL5 (Part III): Angle Of Price (2) Polar Coordinates

Feature Engineering With Python And MQL5 (Part III): Angle Of Price (2) Polar Coordinates

In this article, we take our second attempt to convert the changes in price levels on any market, into a corresponding change in angle. This time around, we selected a more mathematically sophisticated approach than we selected in our first attempt, and the results we obtained suggest that our change in approach may have been the right decision. Join us today, as we discuss how we can use Polar coordinates to calculate the angle formed by changes in price levels, in a meaningful way, regardless of which market you are analyzing.
preview
Developing a Replay System (Part 58): Returning to Work on the Service

Developing a Replay System (Part 58): Returning to Work on the Service

After a break in development and improvement of the service used for replay/simulator, we are resuming work on it. Now that we've abandoned the use of resources like terminal globals, we'll have to completely restructure some parts of it. Don't worry, this process will be explained in detail so that everyone can follow the development of our service.
preview
Price Action Analysis Toolkit Development (Part 11): Heikin Ashi Signal EA

Price Action Analysis Toolkit Development (Part 11): Heikin Ashi Signal EA

MQL5 offers endless opportunities to develop automated trading systems tailored to your preferences. Did you know it can even perform complex mathematical calculations? In this article, we introduce the Japanese Heikin-Ashi technique as an automated trading strategy.
preview
Custom Indicator: Plotting Partial Entry, Exit and Reversal Deals for Netting Accounts

Custom Indicator: Plotting Partial Entry, Exit and Reversal Deals for Netting Accounts

In this article, we will look at a non-standard way of creating an indicator in MQL5. Instead of focusing on a trend or chart pattern, our goal will be to manage our own positions, including partial entries and exits. We will make extensive use of dynamic matrices and some trading functions related to trade history and open positions to indicate on the chart where these trades were made.
preview
Artificial Bee Hive Algorithm (ABHA): Theory and methods

Artificial Bee Hive Algorithm (ABHA): Theory and methods

In this article, we will consider the Artificial Bee Hive Algorithm (ABHA) developed in 2009. The algorithm is aimed at solving continuous optimization problems. We will look at how ABHA draws inspiration from the behavior of a bee colony, where each bee has a unique role that helps them find resources more efficiently.
preview
Build Self Optimizing Expert Advisors in MQL5 (Part 5): Self Adapting Trading Rules

Build Self Optimizing Expert Advisors in MQL5 (Part 5): Self Adapting Trading Rules

The best practices, defining how to safely us an indicator, are not always easy to follow. Quiet market conditions may surprisingly produce readings on the indicator that do not qualify as a trading signal, leading to missed opportunities for algorithmic traders. This article will suggest a potential solution to this problem, as we discuss how to build trading applications capable of adapting their trading rules to the available market data.
preview
Developing a Replay System (Part 57): Understanding a Test Service

Developing a Replay System (Part 57): Understanding a Test Service

One point to note: although the service code is not included in this article and will only be provided in the next one, I'll explain it since we'll be using that same code as a springboard for what we're actually developing. So, be attentive and patient. Wait for the next article, because every day everything becomes more interesting.
preview
From Basic to Intermediate: Variables (II)

From Basic to Intermediate: Variables (II)

Today we will look at how to work with static variables. This question often confuses many programmers, both beginners and those with some experience, because there are several recommendations that must be followed when using this mechanism. 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
Mastering Log Records (Part 4): Saving logs to files

Mastering Log Records (Part 4): Saving logs to files

In this article, I will teach you basic file operations and how to configure a flexible handler for customization. We will update the CLogifyHandlerFile class to write logs directly to the file. We will conduct a performance test by simulating a strategy on EURUSD for a week, generating logs at each tick, with a total time of 5 minutes and 11 seconds. The result will be compared in a future article, where we will implement a caching system to improve performance.
preview
Gating mechanisms in ensemble learning

Gating mechanisms in ensemble learning

In this article, we continue our exploration of ensemble models by discussing the concept of gates, specifically how they may be useful in combining model outputs to enhance either prediction accuracy or model generalization.
preview
The Inverse Fair Value Gap Trading Strategy

The Inverse Fair Value Gap Trading Strategy

An inverse fair value gap(IFVG) occurs when price returns to a previously identified fair value gap and, instead of showing the expected supportive or resistive reaction, fails to respect it. This failure can signal a potential shift in market direction and offer a contrarian trading edge. In this article, I'm going to introduce my self-developed approach to quantifying and utilizing inverse fair value gap as a strategy for MetaTrader 5 expert advisors.
preview
Build Self Optimizing Expert Advisors in MQL5 (Part 4): Dynamic Position Sizing

Build Self Optimizing Expert Advisors in MQL5 (Part 4): Dynamic Position Sizing

Successfully employing algorithmic trading requires continuous, interdisciplinary learning. However, the infinite range of possibilities can consume years of effort without yielding tangible results. To address this, we propose a framework that gradually introduces complexity, allowing traders to refine their strategies iteratively rather than committing indefinite time to uncertain outcomes.
preview
From Basic to Intermediate: Variables (I)

From Basic to Intermediate: Variables (I)

Many beginning programmers have a hard time understanding why their code doesn't work as they expect. There are many things that make code truly functional. It's not just a bunch of different functions and operations that make the code work. Today I invite you to learn how to properly create real code, rather than copy and paste fragments of it. The materials presented here are 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
Monitoring trading with push notifications — example of a MetaTrader 5 service

Monitoring trading with push notifications — example of a MetaTrader 5 service

In this article, we will look at creating a service app for sending notifications to a smartphone about trading results. We will learn how to handle lists of Standard Library objects to organize a selection of objects by required properties.
preview
Master MQL5 from Beginner to Pro (Part III): Complex Data Types and Include Files

Master MQL5 from Beginner to Pro (Part III): Complex Data Types and Include Files

This is the third article in a series describing the main aspects of MQL5 programming. This article covers complex data types that were not discussed in the previous article. These include structures, unions, classes, and the 'function' data type. It also explains how to add modularity to your program using the #include preprocessor directive.
preview
MQL5 Trading Toolkit (Part 7): Expanding the History Management EX5 Library with the Last Canceled Pending Order Functions

MQL5 Trading Toolkit (Part 7): Expanding the History Management EX5 Library with the Last Canceled Pending Order Functions

Learn how to complete the creation of the final module in the History Manager EX5 library, focusing on the functions responsible for handling the most recently canceled pending order. This will provide you with the tools to efficiently retrieve and store key details related to canceled pending orders with MQL5.
preview
Developing a Calendar-Based News Event Breakout Expert Advisor in MQL5

Developing a Calendar-Based News Event Breakout Expert Advisor in MQL5

Volatility tends to peak around high-impact news events, creating significant breakout opportunities. In this article, we will outline the implementation process of a calendar-based breakout strategy. We'll cover everything from creating a class to interpret and store calendar data, developing realistic backtests using this data, and finally, implementing execution code for live trading.
preview
Implementing the SHA-256 Cryptographic Algorithm from Scratch in MQL5

Implementing the SHA-256 Cryptographic Algorithm from Scratch in MQL5

Building DLL-free cryptocurrency exchange integrations has long been a challenge, but this solution provides a complete framework for direct market connectivity.
preview
Adaptive Social Behavior Optimization (ASBO): Two-phase evolution

Adaptive Social Behavior Optimization (ASBO): Two-phase evolution

We continue dwelling on the topic of social behavior of living organisms and its impact on the development of a new mathematical model - ASBO (Adaptive Social Behavior Optimization). We will dive into the two-phase evolution, test the algorithm and draw conclusions. Just as in nature a group of living organisms join their efforts to survive, ASBO uses principles of collective behavior to solve complex optimization problems.
preview
The Liquidity Grab Trading Strategy

The Liquidity Grab Trading Strategy

The liquidity grab trading strategy is a key component of Smart Money Concepts (SMC), which seeks to identify and exploit the actions of institutional players in the market. It involves targeting areas of high liquidity, such as support or resistance zones, where large orders can trigger price movements before the market resumes its trend. This article explains the concept of liquidity grab in detail and outlines the development process of the liquidity grab trading strategy Expert Advisor in MQL5.
preview
Integration of Broker APIs with Expert Advisors using MQL5 and Python

Integration of Broker APIs with Expert Advisors using MQL5 and Python

In this article, we will discuss the implementation of MQL5 in partnership with Python to perform broker-related operations. Imagine having a continuously running Expert Advisor (EA) hosted on a VPS, executing trades on your behalf. At some point, the ability of the EA to manage funds becomes paramount. This includes operations such as topping up your trading account and initiating withdrawals. In this discussion, we will shed light on the advantages and practical implementation of these features, ensuring seamless integration of fund management into your trading strategy. Stay tuned!
preview
Mastering Log Records (Part 3): Exploring Handlers to Save Logs

Mastering Log Records (Part 3): Exploring Handlers to Save Logs

In this article, we will explore the concept of handlers in the logging library, understand how they work, and create three initial implementations: Console, Database, and File. We will cover everything from the basic structure of handlers to practical testing, preparing the ground for their full functionality in future articles.
preview
Price Action Analysis Toolkit Development (Part 7): Signal Pulse EA

Price Action Analysis Toolkit Development (Part 7): Signal Pulse EA

Unlock the potential of multi-timeframe analysis with 'Signal Pulse,' an MQL5 Expert Advisor that integrates Bollinger Bands and the Stochastic Oscillator to deliver accurate, high-probability trading signals. Discover how to implement this strategy and effectively visualize buy and sell opportunities using custom arrows. Ideal for traders seeking to enhance their judgment through automated analysis across multiple timeframes.
preview
Mastering Log Records (Part 2): Formatting Logs

Mastering Log Records (Part 2): Formatting Logs

In this article, we will explore how to create and apply log formatters in the library. We will see everything from the basic structure of a formatter to practical implementation examples. By the end, you will have the necessary knowledge to format logs within the library, and understand how everything works behind the scenes.
preview
Developing a Replay System (Part 56): Adapting the Modules

Developing a Replay System (Part 56): Adapting the Modules

Although the modules already interact with each other properly, an error occurs when trying to use the mouse pointer in the replay service. We need to fix this before moving on to the next step. Additionally, we will fix an issue in the mouse indicator code. So this version will be finally stable and properly polished.
preview
MQL5 Trading Toolkit (Part 6): Expanding the History Management EX5 Library with the Last Filled Pending Order Functions

MQL5 Trading Toolkit (Part 6): Expanding the History Management EX5 Library with the Last Filled Pending Order Functions

Learn how to create an EX5 module of exportable functions that seamlessly query and save data for the most recently filled pending order. In this comprehensive step-by-step guide, we will enhance the History Management EX5 library by developing dedicated and compartmentalized functions to retrieve essential properties of the last filled pending order. These properties include the order type, setup time, execution time, filling type, and other critical details necessary for effective pending orders trade history management and analysis.
preview
Adaptive Social Behavior Optimization (ASBO): Schwefel, Box-Muller Method

Adaptive Social Behavior Optimization (ASBO): Schwefel, Box-Muller Method

This article provides a fascinating insight into the world of social behavior in living organisms and its influence on the creation of a new mathematical model - ASBO (Adaptive Social Behavior Optimization). We will examine how the principles of leadership, neighborhood, and cooperation observed in living societies inspire the development of innovative optimization algorithms.
preview
Developing a Replay System (Part 55): Control Module

Developing a Replay System (Part 55): Control Module

In this article, we will implement a control indicator so that it can be integrated into the message system we are developing. Although it is not very difficult, there are some details that need to be understood about the initialization of this module. The material presented here is for educational purposes only. In no way should it be considered as an application for any purpose other than learning and mastering the concepts shown.