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
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.
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.