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
Engineering Trading Discipline into Code (Part 1): Creating Structural Discipline in Live Trading with MQL5

Engineering Trading Discipline into Code (Part 1): Creating Structural Discipline in Live Trading with MQL5

Discipline becomes reliable when it is produced by system design, not willpower. Using MQL5, the article implements real-time constraints—trade-frequency caps and daily equity-based stops—that monitor behavior and trigger actions on breach. Readers gain a practical template for governance layers that stabilize execution under market pressure.
preview
From Novice to Expert: Automating Intraday Strategies

From Novice to Expert: Automating Intraday Strategies

We translate the EMA‑50 retest idea into a behavior‑driven Expert Advisor for intraday trading. The study formalizes trend bias, EMA interaction (pierce and close), reaction confirmation, and optional filters, then implements them in MQL5 with modular functions and resource‑safe handles. Visual testing in the Strategy Tester verifies signal correctness. The result is a clear template for coding discretionary bounces.
preview
Market Simulation (Part 12): Sockets (VI)

Market Simulation (Part 12): Sockets (VI)

In this article, we will look at how to solve certain problems and issues that arise when using Python code within other programs. More specifically, we will demonstrate a common issue encountered when using Excel in conjunction with MetaTrader 5, although we will be using Python to facilitate this interaction. However, this implementation has a minor drawback. It does not occur in all cases, but only in certain specific situations. When it does happen, it is necessary to understand the cause. In today’s article, we will begin explaining how to resolve this issue.
preview
Risk Management (Part 5): Integrating the Risk Management System into an Expert Advisor

Risk Management (Part 5): Integrating the Risk Management System into an Expert Advisor

In this article, we will implement the risk management system developed in previous publications and add the Order Blocks indicator described in other articles. In addition, we will run a backtest so we can compare results with the risk management system enabled and evaluate the impact of dynamic risk.
preview
Automating Market Memory Zones Indicator: Where Price is Likely to Return

Automating Market Memory Zones Indicator: Where Price is Likely to Return

This article turns Market Memory Zones from a chart-only concept into a complete MQL5 Expert Advisor. It automates Displacement, Structure Transition (CHoCH), and Liquidity Sweep zones using ATR- and candle-structure filters, applies lower-timeframe confirmation, and enforces risk-based position sizing with dynamic SL and structure-based TP. You will get the code architecture for detection, entries, trade management, and visualization, plus a brief backtest review.
preview
MQL5 Trading Tools (Part 18): Rounded Speech Bubbles/Balloons with Orientation Control

MQL5 Trading Tools (Part 18): Rounded Speech Bubbles/Balloons with Orientation Control

This article shows how to build rounded speech bubbles in MQL5 by combining a rounded rectangle with a pointer triangle and controlling orientation (up, down, left, right). It details geometry precomputation, supersampled filling, rounded apex arcs, and segmented borders with an extension ratio for seamless joins. Readers get configurable code for size, radii, colors, opacity, and thickness, ready for alerts or tooltips in trading interfaces.
preview
Price Action Analysis Toolkit Development (Part 61): Structural Slanted Trendline Breakouts with 3-Swing Validation

Price Action Analysis Toolkit Development (Part 61): Structural Slanted Trendline Breakouts with 3-Swing Validation

We present a slanted trendline breakout tool that relies on three‑swing validation to generate objective, price‑action signals. The system automates swing detection, trendline construction, and breakout confirmation using crossing logic to reduce noise and standardize execution. The article explains the strategy rules, shows the MQL5 implementation, and reviews testing results; the tool is intended for analysis and signal confirmation, not automated trading.
preview
Risk Management (Part 4): Completing the Key Class Methods

Risk Management (Part 4): Completing the Key Class Methods

This is Part 4 of our series on risk management in MQL5, where we continue exploring advanced methods for protecting and optimizing trading strategies. Having laid important foundations in earlier articles, we will now focus on completing all remaining methods postponed in Part 3, including functions for checking whether specific profit or loss levels have been reached. In addition, we will introduce new key events that enable more accurate and flexible risk management.
preview
From Basic to Intermediate: Struct (IV)

From Basic to Intermediate: Struct (IV)

In this article, we will explore how to create so-called structural code, where the entire context and methods for manipulating variables and information are placed within a structure to create a suitable context for implementing any code. Therefore, we will examine the necessity of using a private section of the code to separate what is public from what is not, thereby adhering to the rule of encapsulation and preserving the context for which the data structure was created.
preview
From Basic to Intermediate: Struct (VI)

From Basic to Intermediate: Struct (VI)

In this article, we will explore how to approach the implementation of a common structural code base. The goal is to reduce the programming workload and leverage the full potential of the programming language itself—in this case, MQL5.
preview
From Basic to Intermediate: Struct (V)

From Basic to Intermediate: Struct (V)

In this article, we will explore how to overload structural code. I know it can be quite challenging to understand at first, especially if you're seeing it for the first time. It is very important that you grasp these concepts and understand them well before attempting to delve into more complex and elaborate topics.
preview
Market Simulation: (Part 11): Sockets (V)

Market Simulation: (Part 11): Sockets (V)

We are beginning to implement the connection between Excel and MetaTrader 5, but first we need to understand some key points. This way, you won't have to rack your brains trying to figure out why something works or doesn't. And before you frown at the prospect of integrating Python and Excel, let's see how we can (to some extent) control MetaTrader 5 through Excel using xlwings. What we demonstrate here will primarily focus on educational objectives. However, don't think that we can only do what will be covered here.
preview
Market Simulation (Part 14): Sockets (VIII)

Market Simulation (Part 14): Sockets (VIII)

Many programmers might assume we should abandon using Excel and move directly to Python, using some packages that allow Python to generate an Excel file for later analysis of results. However, as mentioned in the previous article, although this solution is the simplest for many programmers, it will not be accepted by some users. And in this particular case, the user is always right. As programmers, we must find a way to make everything work.
preview
From Basic to Intermediate: Struct (III)

From Basic to Intermediate: Struct (III)

In this article, we will explore what structured code is. Many people confuse structured code with organized code, but there is a difference between these two concepts. This is exactly what will be discussed in this article. Despite the apparent complexity you may feel when first encountering this type of code writing, I have tried to approach the topic as simply as possible. However, this article is just the first step toward something greater.
preview
Bivariate Copulae in MQL5: (Part 3): Implementation and Tuning of Mixed Copula Models in MQL5

Bivariate Copulae in MQL5: (Part 3): Implementation and Tuning of Mixed Copula Models in MQL5

The article extends our copula toolkit with mixed copulas implemented natively in MQL5. We construct Clayton–Frank–Gumbel and Clayton–Student–t–Gumbel mixtures, estimate them via EM, and enable sparsity control through SCAD with cross‑validation. Provided scripts tune hyperparameters, compare mixtures using information criteria, and save trained models. Practitioners can apply these components to capture asymmetric tail dependence and embed the selected model in indicators or Expert Advisors.
preview
Price Action Analysis Toolkit Development (Part 60):  Objective Swing-Based Trendlines for Structural Analysis

Price Action Analysis Toolkit Development (Part 60): Objective Swing-Based Trendlines for Structural Analysis

We present a rule-based approach to trendlines that avoids indicator pivots and uses ordered swings derived from raw prices. The article walks through swing detection, size qualification via ATR or fixed thresholds, and validation of ascending and descending structures, then implements these rules in MQL5 with non-repainting drawing and selective output. You get a clear, repeatable way to track structural support and resistance that holds up across market conditions.
preview
Integrating MQL5 with Data Processing Packages (Part 7): Building Multi-Agent Environments for Cross-Symbol Collaboration

Integrating MQL5 with Data Processing Packages (Part 7): Building Multi-Agent Environments for Cross-Symbol Collaboration

The article presents a complete Python–MQL5 integration for multi‑agent trading: MT5 data ingestion, indicator computation, per‑agent decisions, and a weighted consensus that outputs a single action. Signals are stored to JSON, served by Flask, and consumed by an MQL5 Expert Advisor for execution with position sizing and ATR‑derived SL/TP. Flask routes provide safe lifecycle control and status monitoring.
preview
From Basic to Intermediate: Indicator (IV)

From Basic to Intermediate: Indicator (IV)

In this article, we will explore how to easily create and implement an operational approach for coloring candles. This concept is highly valued by traders. When implementing such things, care must be taken to ensure that the bars or candles retain their original appearance and do not hinder reading candle by candle.
preview
The MQL5 Standard Library Explorer (Part 8) : The Hybrid Trades Journal Logging with CFile

The MQL5 Standard Library Explorer (Part 8) : The Hybrid Trades Journal Logging with CFile

In this article, we explore the File Operations classes of the MQL5 Standard Library to build a robust reporting module that automatically generates Excel-ready CSV files. Along the way, we clearly distinguish between manually executed trades and algorithmically executed orders, laying the groundwork for reliable, auditable trade reporting.
preview
From Basic to Intermediate: Indicator (III)

From Basic to Intermediate: Indicator (III)

In this article, we will explore how to declare various graphical representation indicators, such as DRAW_COLOR_LINE and DRAW_FILLING. Additionally, of course, we will learn how to plot graphs using multiple indicators in a simple, practical, and fast way. This can truly change your perspective on MetaTrader 5 and the market as a whole.
preview
Overcoming Accessibility Problems in MQL5 Trading Tools (I)

Overcoming Accessibility Problems in MQL5 Trading Tools (I)

This article explores an accessibility-focused enhancement that goes beyond default terminal alerts by leveraging MQL5 resource management to deliver contextual voice feedback. Instead of generic tones, the indicator communicates what has occurred and why, allowing traders to understand market events without relying solely on visual observation. This approach is especially valuable for visually impaired traders, but it also benefits busy or multitasking users who prefer hands-free interaction.
preview
From Basic to Intermediate: Indicator (II)

From Basic to Intermediate: Indicator (II)

In this article, we will examine how to implement a moving average calculation and what precautions should be taken when performing this calculation. We will also discuss overloading the OnCalculate function to know when and how to work with one model or another.
preview
Price Action Analysis Toolkit Development (Part 59): Using Geometric Asymmetry to Identify Precision Breakouts from Fractal Consolidation

Price Action Analysis Toolkit Development (Part 59): Using Geometric Asymmetry to Identify Precision Breakouts from Fractal Consolidation

While studying a wide range of breakout setups, I noticed that failed breakouts were rarely caused by a lack of volatility, but more often by weak internal structure. That observation led to the framework presented in this article. The approach identifies patterns where the final price leg shows superior length, steepness, and speed—clear signs of momentum accumulation ahead of directional expansion. By detecting these subtle geometric imbalances within consolidation, traders can anticipate higher-probability breakouts before price exits the range. Continue reading to see how this fractal-based, geometric framework translates structural imbalance into precise breakout signals.
preview
From Basic to Intermediate: Indicator (I)

From Basic to Intermediate: Indicator (I)

In this article, we will create our first fully practical and functional indicator. The goal is not to show how to create an application, but to help you understand how you can develop your own ideas and give you the opportunity to apply them in a safe, simple, and practical way.
preview
The MQL5 Standard Library Explorer (Part 7): Interactive Position Labeling with CCanvas

The MQL5 Standard Library Explorer (Part 7): Interactive Position Labeling with CCanvas

In this article, we explore how to build a position information visualization tool using the MQL5 Standard Library’s CCanvas. This project strengthens your skills in working with library modules while providing traders with a practical tool to visualize and interact with open positions directly on a live chart. Join the discussion to learn more.
preview
From Basic to Intermediate: Events (II)

From Basic to Intermediate: Events (II)

In this article, we will see that not everything always needs to be implemented in a certain specific way. There are alternative approaches to problem-solving. To properly understand this article, it is necessary to grasp the concepts described in the previous articles. The materials presented here are for educational purposes only. Do not regard it as a finished application. Its purpose is to study the concepts presented here.
preview
Integrating External Applications with MQL5 Community OAuth

Integrating External Applications with MQL5 Community OAuth

Learn how to add “Sign in with MQL5” to your Android app using the OAuth 2.0 authorization code flow. The guide covers app registration, endpoints, redirect URI, Custom Tabs, deep-link handling, and a PHP backend that exchanges the code for an access token over HTTPS. You will authenticate real MQL5 users and access profile data such as rank and reputation.
preview
From Novice to Expert: Developing a Liquidity Strategy

From Novice to Expert: Developing a Liquidity Strategy

Liquidity zones are commonly traded by waiting for the price to return and retest the zone of interest, often through the placement of pending orders within these areas. In this article, we leverage MQL5 to bring this concept to life, demonstrating how such zones can be identified programmatically and how risk management can be systematically applied. Join the discussion as we explore both the logic behind liquidity-based trading and its practical implementation.
preview
From Novice to Expert: Creating a Liquidity Zone Indicator

From Novice to Expert: Creating a Liquidity Zone Indicator

The extent of liquidity zones and the magnitude of the breakout range are key variables that substantially affect the probability of a retest occurring. In this discussion, we outline the complete process for developing an indicator that incorporates these ratios.
preview
Visualizing Strategies in MQL5: Laying Out Optimization Results Across Criterion Charts

Visualizing Strategies in MQL5: Laying Out Optimization Results Across Criterion Charts

In this article, we write an example of visualizing the optimization process and display the top three passes for the four optimization criteria. We will also provide an opportunity to select one of the three best passes for displaying its data in tables and on a chart.
preview
Database Is Easy (Part 1): A Lightweight ORM Framework for MQL5 Using SQLite

Database Is Easy (Part 1): A Lightweight ORM Framework for MQL5 Using SQLite

This article presents a structured way to manage SQLite data in MQL5 through an ORM layer for MetaTrader 5. It introduces core classes for entity modeling and database access, a fluent CRUD API, reflection hooks for OnGet/OnSet, and macros to define models quickly. Practical code shows creating tables, binding fields, inserting, updating, querying, and deleting records. Developers gain reusable, type-safe components that minimize repetitive SQL.
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.