Articles on the MQL5 programming and use of trading robots

icon

Expert Advisors created for the MetaTrader platform perform a variety of functions implemented by their developers. Trading robots can track financial symbols 24 hours a day, copy deals, create and send reports, analyze news and even provide specific custom graphical interface.

The articles describe programming techniques, mathematical ideas for data processing, tips on creating and ordering of trading robots.

Add a new article
latest | best
preview
Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

Hierarchical Risk Parity: A Robust Portfolio Allocator and Expert Advisor

We implement a Hierarchical Risk Parity allocator in MQL5 as a single class, validate each stage against an independent Python reference, and package it in a rebalancing Expert Advisor. The pipeline covers returns, covariance/correlation, clustering, quasi-diagonalization, and recursive bisection, and contrasts HRP with Markowitz on stressed data. You finish with a verified allocator and an EA ready for basket-level testing.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Building Objects)

Mantis is a versatile tool for in-depth time series analysis that can be flexibly scaled to accommodate any financial scenario. Learn how a combination of patching, local convolutions, and cross-attention enables a highly accurate interpretation of market patterns.
preview
Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Mantis)

Neural Networks in Trading: Effective Feature Extraction for Accurate Classification (Mantis)

Meet Mantis — a lightweight foundation model for time series classification based on a Transformer architecture, featuring contrastive pre-training and hybrid attention that deliver record-breaking accuracy and scalability.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Core Model Modules)

We continue our acquaintance with the Mamba4Cast framework. Today, we will delve into the practical implementation of the proposed approaches. Mamba4Cast was designed not for lengthy warm-up on every new time series, but for immediate deployment. Thanks to the concept of Zero-Shot Forecasting, the model can produce high-quality forecasts on real-world data without additional training or hyperparameter tuning.
preview
The Blue Monkey (BM) Algorithm

The Blue Monkey (BM) Algorithm

The article presents an implementation of the Blue Monkey metaheuristic algorithm, which is based on a model of the social behavior of blue monkeys. The article examines the key mechanisms of the algorithm — the group structure of the population, following local leaders, and generational renewal through the replacement of the worst adults with the best offspring — and analyzes the test results.
preview
Building Your Personal Expert Advisor (Part 1): From Fragile Script to Working EA

Building Your Personal Expert Advisor (Part 1): From Fragile Script to Working EA

This article focuses on EA architecture rather than signal design. Starting with a flawed Moving Average crossover EA, we add new‑bar detection to prevent duplicate entries, Magic Number and position awareness, ATR‑based risk levels, and data and trade result validation, along with basic safeguards. You obtain a practical base to build and test advanced systems.
preview
Trading Options Without Options (Part 3): Complex Option Strategies

Trading Options Without Options (Part 3): Complex Option Strategies

The article discusses flat (non-directional) and trend-following (directional) option strategies and their implementation in MQL5. The EA described in the previous article is updated. The display of option levels has been added. Now it is time to examine the strategies used by options traders in practice and put them into action.
preview
Formulating Dynamic Multi-Pair EA (Part 10): Asymmetric Stop-Loss Logic Based on Pair-Specific Volatility Signatures

Formulating Dynamic Multi-Pair EA (Part 10): Asymmetric Stop-Loss Logic Based on Pair-Specific Volatility Signatures

The EA learns each symbol's volatility profile before trading by processing 1000 bars and summarizing candle ranges, bodies and wicks, noise ratio, trend runs, pullback size, and true‑range dispersion. A classifier assigns regime and structure labels per pair. The stop‑loss optimizer maps those labels to a symbol‑specific ATR multiplier, and the risk module sizes lots to maintain constant percentage risk.
preview
Automating Classic Market Methods in MQL5 (Part 5): The Original Turtle Trading Rules

Automating Classic Market Methods in MQL5 (Part 5): The Original Turtle Trading Rules

This article builds a complete MQL5 Expert Advisor that implements the original Turtle Trading rules from Curtis Faith. It covers both systems: 20/55-day breakouts, the System 1 skip rule, N (Wilder ATR) for volatility-adjusted sizing, a four‑unit pyramid with N/2 adds, a unified 2N stop, and 10/20-day exits. You will get compilable code, implementation details, and a backtesting procedure on EURUSD.
preview
Automating Classic Market Methods in MQL5 (Part 4): Mark Minervini's Trend Template

Automating Classic Market Methods in MQL5 (Part 4): Mark Minervini's Trend Template

This article presents TrendTemplateEA, an Expert Advisor implementing Mark Minervini's eight-condition trend template for daily forex charts. It evaluates all conditions on every bar and enters only when they are simultaneously satisfied, using RSI above 50 in place of the stock market RS rating. The entry trigger is a 20-bar high breakout on expanding volume, with all rules coded and testable in MQL5.
preview
Developing a Multi-Currency Expert Advisor (Part 29): Improving the Conveyor

Developing a Multi-Currency Expert Advisor (Part 29): Improving the Conveyor

We are going to improve the usability of the automated optimization conveyor: we will explore the process from creating an optimization project to testing the final EA. For clarity, let us walk through the entire process step by step creating the final EA, while stopping to make any desired corrections.
preview
Where should your stop-loss really sit? An MAE/MFE excursion analyzer in MQL5

Where should your stop-loss really sit? An MAE/MFE excursion analyzer in MQL5

Stop-loss and take-profit placement is usually the least-measured decision in a trading system. This Expert Advisor reads your closed history, replays M1 price between each entry and exit to measure Maximum Adverse and Favorable Excursion per trade, and splits winners from losers. From the distributions and trade efficiency it derives data-driven stop and target levels - measured from your own account, not a rule of thumb. Analysis only; it does not trade.
preview
Developing a Manual Backtesting Expert Advisor: Additional Features

Developing a Manual Backtesting Expert Advisor: Additional Features

We enhance the manual backtesting EA with real-time lot adjustment, an order module for buy/sell stops and limits, and a Trade Manager to modify TP/SL and close positions individually. The article explains control setup with CButton/CBmpButton/CEdit, logic in OnTick, and workarounds for Strategy Tester input constraints. Readers can reuse these components to speed up testing workflows and implement robust trade management.
preview
How to Test and Customize Built-in MQL5 Programs:  Custom BullishBearish MeetingLines Stoch Expert Advisor

How to Test and Customize Built-in MQL5 Programs: Custom BullishBearish MeetingLines Stoch Expert Advisor

We demonstrate a practical customization path for a built-in MetaTrader 5 EA using BullishBearish MeetingLines Stoch. The workflow covers baseline testing in the Strategy Tester, parameter optimization, and code-level changes. Two modifications are implemented: exposing Stochastic thresholds as inputs and adding an optional Moving Average filter to limit counter‑trend signals. The article includes the full modified code for replication.
preview
Broker Reality Check (Part 1): Why Your EA Works on a Demo and Breaks on a Client's Broker

Broker Reality Check (Part 1): Why Your EA Works on a Demo and Breaks on a Client's Broker

Your Expert Advisor runs clean on your demo, then throws errors on a client's broker and quietly stops trading - and the code never changed. What changed is the broker's rulebook. This first article of the Broker Reality Check series builds a diagnostic EA that reads every relevant symbol trading condition - filling policy, stops and freeze levels, volume step, trade mode, swap and the triple-swap day - and flags the ones that silently break EAs, in plain language. It shows a green/amber/red panel, prints a report and dumps every Market Watch symbol to CSV, so you see why an OrderSend fails (10030, invalid stops, invalid volume) before it costs you a trade.
preview
Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

Monochronic Trading (Part 1): How to Detect Broker Timezone and DST in MQL5

We describe an MQL5 framework that aligns entries with session rhythms and scheduled clock events. A script identifies the broker's time zone and DST by detecting NFP spikes on EURUSD and matching them to EU/US/AU transition dates, producing EA‑ready settings. Session-to-broker time conversion and 15-minute marks constrain execution. A multi‑timeframe AMA signal aggregates trends for strategy selection and optimization.
preview
Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

Building a Synthetic Custom Symbol in MQL5 Using Multi-Symbol Price Averaging

This article shows how to build a synthetic custom symbol in MQL5 by averaging OHLC data from multiple instruments into a single derived price series. It covers symbol collection and validation, custom symbol creation and configuration, timestamp alignment, historical reconstruction, and lightweight live updates. The result is a reusable method for creating synthetic instruments suitable for correlation analysis, index-style modeling, indicator development, and strategy testing.
preview
Beyond the Clock (Part 4): Efficacy of Bars on Trending and Mean-Reversion Strategies

Beyond the Clock (Part 4): Efficacy of Bars on Trending and Mean-Reversion Strategies

Does better return conditioning buy strategy performance? We hold bar count fixed across time, tick, tick-imbalance, and tick-runs on 60.5 million EURUSD ticks, then meta-label RSI, Bollinger, and ADX/DI entries and score with purged cross-validation. No family delivers a consistent edge; efficacy varies narrowly and the best case fails a permutation test. Readers learn how to control overlap, leakage, and multiple testing in bar studies.
preview
Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

Custom Indicator Workshop (Part 4) : Automating UT Bot Alerts into a Trading Expert Advisor

This article shows how to build an MQL5 Expert Advisor around the UT Bot Alerts indicator. The EA reads custom indicator signals via iCustom() and CopyBuffer(), evaluates entries only on new bars, using the last closed candle at index 1, and enforces a one-direction-at-a-time model by closing opposite positions before taking new entries. It also adds optional ATR-based stop-losses, reward-to-risk take-profits, dedicated buy/sell execution functions, magic-number tracking, and basic backtesting for repeatable evaluation.
preview
N-BEATS Network-Based Forex EA

N-BEATS Network-Based Forex EA

Implementation of the N-BEATS architecture for Forex trading in MetaTrader 5 with quantile forecasting and adaptive risk management. The architecture is adapted through bilinear normalization and specialized loss functions for financial data. Backtesting on 2025 data shows inability to generate profits, confirming the gap between theoretical achievements and practical trading performance.
preview
Building an Object-Oriented Order Block Engine in MQL5

Building an Object-Oriented Order Block Engine in MQL5

The article presents a production-oriented Order Block engine for MQL5 packaged as an include class, it validates zones via displacement and market structure break, maintains mitigation state only on closed bars, and avoids heavy copies by passing data by reference. A diagnostic indicator plots zones, and an EA gates logic to new bars for stable performance and reproducible tests.
preview
Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps

Automating Trading Strategies in MQL5 (Part 50): Turtle Soup Liquidity Sweeps

We build an automated MQL5 program that trades Turtle Soup by fading false breakouts of the N-bar high and low. The article implements liquidity-sweep detection, confirmation closes back inside the level, sweep-depth and extreme-age filters, and an optional reversal-candle body check. It adds configurable dynamic or static stops, two take-profit modes, points-based trailing, and clear chart visuals, providing a ready baseline for backtesting and further customization.
preview
Reimagining Classic Strategies (Part 22): Ensemble Mean Reverting Strategy

Reimagining Classic Strategies (Part 22): Ensemble Mean Reverting Strategy

This article will illustrate to the reader how to implement a mean-reverting strategy for the EURUSD pair. The strategy follows contrarian trading rules. Our strategy implements a weekly moving average channel, with one moving average on the high-price feed and the latter on the low-price feed. We enter short positions when the price falls beneath the low moving average and long positions when the price rises above the high moving average. Additionally, we will export daily market data to build a simple ONNX model of the market to provide an additional filter for our entries. This provides the reader with a reproducible template for strategy development and backtesting.
preview
MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems

MQL5 Bootstrap (II): Essential Validators for Robust Trading Systems

The article builds a reusable validation layer for Expert Advisors in MQL5. It implements lot-size rules and normalization, SL/TP and freeze-level guards, price digit normalization, margin sufficiency checks, unchanged-level filtering on modifications, account order-limit control, new-bar detection, symbol tradability checks, economic-calendar news windows, and session detectors. The result is cleaner code and fewer terminal errors in live trading.
preview
MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

MQL5 Trading Tools (Part 39): Adding a Pinned-Tools Ribbon for Quick Access to Favorite Tools

We add a pinned-tools ribbon: a floating bar that exposes frequently used tools for one-click access without reopening the sidebar. The article implements the ordered pin set and its API, an anti-aliased pushpin control in the flyout, and the ribbon with offscreen clipping, user-resizable width, and horizontal scrolling. The result is faster activation of favorite tools from a draggable, resizable ribbon on the chart.
preview
Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

Neural Networks in Trading: Generalizing Time Series Without Data-Specific Dependence (Mamba4Cast)

In this article, we introduce the Mamba4Cast framework and take a closer look at one of its key components: timestamp-based positional encoding. The article shows shows how time embedding is formed taking into account the calendar structure of the data.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (Final Part)

The article discusses the adaptation and practical implementation of the ACEFormer framework using MQL5 in the context of algorithmic trading. It presents key architectural decisions, training features, and model testing results on real data.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

Engineering a Self-Healing Expert Advisor in MQL5 (Part 5): Real-Time Recovery Dashboard (Final Part)

This article implements a real-time monitoring dashboard for a self-healing MetaTrader 5 Expert Advisor. The dashboard displays the current EA state, virtual stop-loss and take-profit levels, breakeven and trailing status, recovery state, synchronization status, and heartbeat information directly on the chart. By exposing the internal recovery state visually, the Expert Advisor becomes easier to monitor, verify, and troubleshoot while managing active trades.
preview
Building Automated Daily Trading Reports with the SendMail Function

Building Automated Daily Trading Reports with the SendMail Function

We build an MQL5 Expert Advisor that emails a structured daily trading report. The article shows how to configure SMTP in MetaTrader 5, collect and filter closed trades for the previous day, compute totals for profit, wins, losses, and trade count, and assemble account details into the subject and body. You also schedule one send per day and prevent duplicates using daily candle detection.
preview
Automating Classic Market Methods in MQL5 (Part 3): Stan Weinstein Stage Analysis

Automating Classic Market Methods in MQL5 (Part 3): Stan Weinstein Stage Analysis

This article presents a complete Expert Advisor built around Stan Weinstein's Stage Analysis method. The EA classifies the market into one of four stages using the 30-week moving average slope and position and volume behavior, then trades only Stage 2 breakouts long and Stage 4 breakdowns short. It explains each stage, how to detect it programmatically, and why the method's discipline—trading only in the correct stage—is what produces the edge.
preview
Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

Training a nonlinear U-Transformer on the residuals of a linear autoregressive model

The article presents an innovative hybrid system for forecasting exchange rates that combines a linear autoregressive model with a U-Transformer architecture for residual analysis. The system automatically switches between signal sources depending on their quality and includes complete trading logic with averaging/pyramiding strategies. The key advantage of this approach is that the neural network is trained on the residuals of the linear model, which simplifies the task and reduces the risk of overfitting. The implementation is done entirely in MQL5 and is ready for use in real trading with automatic adaptation to changing market conditions.
preview
Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

Neural Networks in Trading: Time Series Forecasting Using Adaptive Modal Decomposition (ACEFormer)

We invite you to explore the ACEFormer architecture — a modern solution that combines the effectiveness of probabilistic attention with adaptive time series decomposition. This article will be useful for those seeking a balance between computational performance and forecast accuracy in financial markets.
preview
Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

Automating Trading Strategies in MQL5 (Part 49): The Quasimodo (QM) Reversal Pattern

In this article, we build an automated trading program in MQL5 that detects the Quasimodo reversal pattern from a zig-zag of confirmed swing pivots. We work through swing detection, pattern arming, retrace entries at the QM line, and structural stop placement with risk-based sizing. We also add trade management with breakeven, trailing, and partial closing to handle open positions.
preview
Engineering Trading Discipline into Code (Part 8): Building a Setup Confirmation and Trade Authorization Layer in MQL5

Engineering Trading Discipline into Code (Part 8): Building a Setup Confirmation and Trade Authorization Layer in MQL5

This article introduces an MQL5 trade authorization framework built around CDisciplineLayer, CDisciplineGuardian, and CDisciplinePanel. The framework manages setup lifecycles, signal freshness, session restrictions, setup expiry, and global trading locks through a centralized authorization layer. It also provides automated enforcement of violations and a real-time dashboard, enabling consistent trade validation and monitoring before and after execution.
preview
Measuring What Matters (Part 1) : Portfolio Risk Decomposition in MQL5

Measuring What Matters (Part 1) : Portfolio Risk Decomposition in MQL5

The article establishes a reproducible method to measure portfolio risk for multiple symbols using MQL5 matrices and OpenBLAS. It covers computing log returns, building a covariance matrix, and evaluating wᵀΣw instead of summing individual variances. A complete script prints naive versus true volatility and the cross‑term contribution, enabling you to detect when correlated instruments inflate exposure beyond single‑asset estimates.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery

Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery

This article adds trade-state reconciliation and Safe Mode recovery to a MetaTrader 5 Expert Advisor. The EA continuously validates recovery integrity by comparing the live broker position with the persisted SQLite state and the in-memory runtime state. Detected inconsistencies trigger an automatic transition to Safe Mode, suspending virtual protection, breakeven, and trailing management until the recovery state can be trusted again.
preview
MQL5 Wizard Techniques you should know (Part 99): Using a KD-Tree and an Echo State Network in a Custom Money Management Class

MQL5 Wizard Techniques you should know (Part 99): Using a KD-Tree and an Echo State Network in a Custom Money Management Class

This article lays out 'CMoneyKDTreeESN' custom money management class usable with the MQL5 Wizard, that combines the KD-Tree algorithm and the Echo State Network. We use the KD-Tree on log returns and ATR to give us a risk score, while the ESN tracks recent flow to give us a bounded lot size multiplier. Our class is usable in a variety of Wizard assembled Expert Advisors as shown here with the Envelopes and RSI signals, with a broad objective of modulating exposure in high-volatility and tail-risk environments.
preview
Creating an HTML Dashboard for Strategy Tester and Prop Firm Challenge Analysis in MQL5

Creating an HTML Dashboard for Strategy Tester and Prop Firm Challenge Analysis in MQL5

This article demonstrates how to build a reusable prop‑firm evaluation module for MQL5 Expert Advisors and export results to an HTML dashboard. The module monitors balance and equity during backtests, simulates single or rolling challenges, checks profit target, daily and overall drawdown, and minimum trading days, then outputs both a terminal summary and a browser‑readable report.
preview
Engineering a Self-Healing Expert Advisor in MQL5 (Part 3): Restart-Aware Breakeven and Trailing Systems

Engineering a Self-Healing Expert Advisor in MQL5 (Part 3): Restart-Aware Breakeven and Trailing Systems

Building on Part 2, the implementation introduces restart-aware breakeven and trailing-stop systems for MetaTrader 5. The EA persists the state, such as breakeven activation, last trailing price, and virtual SL in SQLite, then restores them on startup. This preserves dynamic protection flow and prevents lost progress after terminal interruptions.
preview
MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

MQL5 Trading Tools (Part 38): Adding a Tabbed Settings Window for Editing Object Properties

We add a tabbed settings window opened from the ribbon and bound to the selected object. The tabs — Style, Text, Coordinates, and Visibility — are built from the same descriptor system, with scrolling, per-level rows, and shared color/width/style popovers. The article covers layout, rendering, interaction, and inline price/time and numeric editing. You get one place to edit every property with live preview and commit-or-discard on close.