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.
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.
How to Research a Trading Idea: A Range Breakout Strategy Case Study
This article demonstrates a practical approach to researching trading ideas using a range breakout strategy as an example. We will go through the entire process, from formalizing trading rules and building a baseline model to parameter optimization, forward testing, and evaluating the robustness of the results. The main goal of the article is to develop an understanding of how statistics and testing can be used to identify, validate, and evaluate trading hypotheses.
Exporting MetaTrader 5 Open Positions to a Live-Refreshing HTML Dashboard
The article builds an MQL5 Expert Advisor that writes a self-refreshing HTML positions dashboard to MQL5/Files on every tick, so you can monitor open trades in any browser. It covers reading live position data, generating a complete page with inline CSS and a JavaScript reload timer, and writing the file atomically. The design escapes HTML in comments, shows an explicit empty state, and writes a clear offline page on EA shutdown.
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.
Forecasting a Conditional Distribution Using MLP
In this article, we will consider an MLP-based regression model that predicts not only the conditional expectation but also the conditional variance. In other words, we will train our network to predict the entire distribution of future prices based on the input feature vector. But for this purpose we will have to implement our own loss function.
Symbolic Aggregate Approximation (SAX) in MQL5: Historical Analog Search and Forecasting
Symbolic Aggregate approXimation (SAX) encodes price windows as short words to enable fast, sound similarity search on history. We implement SAX in pure MQL5, including Gaussian breakpoints, PAA, and the lower-bounding MINDIST, and validate it with a test harness. An indicator applies a no-lookahead, two-stage search, summarizes forward paths in ATR units, and draws a forecast fan, explicitly indicating when the sample shows no edge.
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.
CSV Data Analysis (Part 7): Statistical Robustness Testing on MQL5 CSV Exports with Monte Carlo Simulation
A statistically significant backtest is not proof of a robust edge. This article presents a three-part validation battery in Python that consumes an MQL5 trade-level CSV export. A sign-randomization permutation test evaluates whether the Sortino reflects real directional skill, bootstrap BCa intervals assess metric stability, and Monte Carlo trade-order shuffling tests sequence dependence of drawdowns. The results feed a five-condition framework for deployment decisions.
Bison Algorithm (BIA)
A new optimization method, the Bison Algorithm (BIA), uses two strategies, inspired by the behavior of bison, for solving continuous problems with a single objective function. The key features of BIA are two fundamental principles borrowed from the behavior of bison: the ability to move dynamically and a defensive strategy.
Defining your Edge (Part 2): Using Divergence Mapping and a Temporal Fusion Transformer in a Trading Robot
In this article we make the case for merging Divergence Mapping with a Temporal Fusion Proxy in a Trading Robot. Rather than depending on lagging price confirmations, the Divergence Mapping's thesis is that acting like a structural sensor can help identify hidden momentum shifts from price action and indicator anomalies. To establish how these anomalies are interpreted over time we use a Temporal Fusion Transformer proxy. This network incorporates historical context to weigh developing trends such that merging it with Divergence Mapping should set us up to spot shifts in accumulation and distribution before price breakouts.
Mapping the Shape of Price: The Mapper Lens and Cover in MQL5
The article introduces the Mapper pipeline in MQL5 by implementing the two fundamental components: CTDAMapperFilter (lens) and CTDAMapperCover (overlapping intervals). It explains three lens options—eccentricity, density, and coordinate—plus cover parameters (resolution and gain), and demonstrates how a price point cloud is reduced to one value per point and interval memberships. Readers obtain ready inputs for subsequent clustering and graph construction.
Building a JSON Trade Report Exporter in Pure MQL5
A refined MQL5 script exports trade history to a well‑formed JSON file in MQL5/Files/, reconstructing trades from deals by position ID and recovering stop loss and take profit via a two‑pass lookup that falls back closed to the originating order. It includes a dedicated JSON serializer and computes R‑multiple, pip profit, and duration. The result loads cleanly in Python, R, or Excel without custom parsing.
Symbolic Price Forecasting Equation Using SymPy
The article describes an interesting approach to algorithmic trading based on symbolic mathematical equations instead of traditional machine learning "black boxes". The author demonstrates how to transform opaque neural networks into readable mathematical equations using the SymPy library and polynomial regression, allowing for a full understanding of the logic behind trading decisions. The approach combines the computational power of ML with the transparency of classical methods, giving traders the ability to analyze, adjust, and adapt models in real time.
Ordinal Pattern Transition Networks in MQL5
We implement ordinal pattern transition networks in MQL5: a Lehmer-code encoder, a directed network over ordinal price patterns, and three complexity metrics. Two indicators expose a trend-versus-range regime from time-irreversibility and an efficiency gauge from permutation entropy, with a transparent parameter sweep showing how to tune settings on FX data.
Adaptive Spread Monitoring and Order Gating in MQL5
This article presents a distribution-adaptive spread monitor for MQL5 that replaces fixed thresholds with a rolling histogram of each symbol's recent spread. It explains percentile estimation from bins, a four-state GREEN/YELLOW/RED/WARMING classification, and a CCanvas dashboard rendered from real histogram data. You will get a ready workflow for per-symbol order gating and controlled alerting via arm/disarm hysteresis plus cooldown, with a verification script and clear calibration and resolution limits.
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.
Comparing Trade Return Distributions with Mann-Whitney U in MQL5
A native, dependency-free MQL5 implementation of the Mann-Whitney U test for comparing trade returns across two market regimes. It details rank calculation, tie correction, and a normal-approximation p-value, and pairs the test with a CCanvas box-and-whisker chart and a trade-history extraction script. A verification script is included, and the limits of the normal approximation and independence assumptions are clearly stated for informed use.
Defining your Edge (Part 1): Using a Discrete Fourier Transform and a Spiking Neural Network in a Trading Robot
In this article we make the case for pairing the Discrete Fourier Transform with a Spiking Neural Network in a Trading Robot. The Fourier Transform helps represent data as oscillations instead of its raw values. To govern how we interpret these cycles, we engage a Spiking Neural Network that unlike regular networks, uses time dependent electrical charges to accumulate potential and only "spike" when a target threshold is met. Combining these two engines allows us better control on the timing of discrete market movements, that in theory should give us entry signals with rigorous mathematical confirmation.
Dingo Optimization Algorithm Modification (DOAm)
The custom modification of the Dingo algorithm presented in the article has raised the bar for finding the best optimization algorithm. Are even better results possible?
Building a Correlation-Aware Portfolio Risk Monitor in MQL5
The article quantifies correlation and portfolio risk in MetaTrader 5: from time-aligned returns to a covariance matrix, true portfolio variance against the independent-sum assumption, and position-level risk attribution. A MetaTrader 5 service runs in the background, shows the metrics on a small chart panel, and pushes alerts when risk thresholds are crossed. Source code is provided for an example script, a reusable risk engine class, and the service.
Price Action Analysis Toolkit Development (Part 75): Building a Modular Multi-Symbol Trading Panel in MQL5
A structured MQL5 implementation of a multi‑symbol trading panel with clear separation of concerns: symbol handling, trading logic, and GUI. Integrated into an Expert Advisor, it validates symbols, exposes centralized controls for opening and positions managing across symbols, and applies SL/TP changes. Real‑time account and portfolio metrics help streamline routine operations from a single chart.
Digital Signal Processing for Traders (Part 2): The Dominant Cycle, MAMA, and a Regime-Switching Expert Advisor
In Part 2 we measure the market's dominant cycle using Ehlers' Hilbert-transform homodyne discriminator and wrap it as an indicator. We then build the MESA Adaptive Moving Average (MAMA) and its follower FAMA from that phase information. Finally, we combine MAMA/FAMA with the Even Better Sinewave to form a regime-switching Expert Advisor and test it on EURUSD in the Strategy Tester, giving you a complete, reproducible MQL5 implementation.
Execution Cost and Slippage Sensitivity Analyzer
Backtests often understate spread, commission, and slippage. This MQL5 analyzer loads closing deals and simulates rising execution costs to measure robustness. It computes the breakeven cost per deal, the cushion over an assumed cost, the net profit and profit factor at that cost, and how many winners turn into losers, then summarizes the result with an A+ to F grade and targeted guidance.
Multi-Threaded Trading Robot with Machine Learning: From Concept to Implementation
The article presents a step-by-step development of a multi-threaded trading robot with machine learning in Python and MetaTrader 5. The system architecture is considered – from data collection and creation of technical indicators to training XGBoost models with portfolio risk management. The implementation of data augmentation, feature clustering via Gaussian Mixture Models, and flow coordination for parallel trading of multiple currency pairs is described in detail.
A Symbol Metadata and Trading Hours Cache in MQL5: Eliminating Redundant SymbolInfo Calls in Multi-Symbol EAs
This article presents CSymbolMetaCache, an MQL5 layer that preloads contract specifications and trading-session schedules for monitored symbols at EA startup and then serves typed getters from memory. It explains which properties are safe to cache versus dynamic ones, including the semi-dynamic tick value on cross-currency pairs, and implements an in-memory IsMarketOpen() evaluator. A benchmark quantifies latency reduction across a set of twenty symbols.
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.
The MQL5 Standard Library Explorer (Part 14): Building a Dynamic Hedge EA with the ALGLIB Port (ap.mqh)
This article introduces ap.mqh, the ALGLIB port for MQL5, and demonstrates its use in multi‑asset workflows that require robust linear algebra. It covers why built-in indicators fall short, then implements polynomial regression, a rolling correlation matrix indicator, and an adaptive hedge ratio estimator using ridge regression with Cholesky. Practical code shows how to compute spread z‑scores and execute coordinated pairs trades entirely within MetaTrader 5.
Mapping Dealer Gamma Exposure (GEX) in MetaTrader 5: Walls, the Zero-Gamma Flip, and a Chart Overlay
In this article we build a dealer gamma-exposure map in MQL5. From an option chain, the tool computes per-strike GEX, finds the call and put walls, and solves for the zero-gamma flip that separates a mean-reverting regime from a trending one, then draws it all on the chart. CSV and native-symbol data paths included.
Constructing a Trade Replay Engine in MQL5: Stepping Through Historical Trades Bar by Bar for Manual Review
An MQL5 script reconstructs closed trades from raw deal history and replays them on the chart bar by bar, drawing entry, exit, stop, target, and an annotation with per‑trade statistics. Four classes separate concerns: a trade data record, history reconstruction with a two‑pass SL/TP lookup and partial‑close aggregation, chart rendering, and a controller with polling‑based keyboard navigation. This enables consistent, fast visual review of each trade in its original candlestick context.
Dingo Optimization Algorithm (DOA)
The article presents a new metaheuristic method based on the hunting strategies of Australian dingoes: group attack, chase, and scavenging. Let's see how the Dingo Optimization Algorithm (DOA) performs algorithmically.
Online Linear Regression with Recursive Least Squares in MQL5: A Parameter-Free Adaptive Trend Estimator
This article implements recursive least squares in native MQL5 with a constant O(1) update per bar, avoiding the per‑bar O(n) rebuild of a rolling OLS. It derives and codes the Sherman–Morrison rank‑1 update, explains the forgetting factor through its effective window, and provides a reusable class. Two coordinated indicators plot a 1‑step‑ahead price forecast on the chart and the signed slope in a correctly scaled subwindow for practical trend tracking.
How To Profile MQL5 Code in MetaEditor
This article profiles a rolling z-score indicator with bands using MetaEditor's built-in sampling profiler. We read the Total CPU and Self CPU columns and follow the heat‑mapped source to the true hotspots, replace window rescans with sliding accumulators, remove a redundant array copy, and honor prev_calculated. The result is the same output with measured samples reduced from roughly 7,050 to 59.
Creating a Profit Concentration Analyzer in MQL5
Net profit and win rate tell you how much a strategy made, not how the result is distributed. This article builds a native MQL5 script that reads your closed trades and measures profit concentration: the top-N trade share, the Gini coefficient of the winners, an outlier-dependence stress test that removes the best few winners, and the largest day against a prop-firm consistency limit. It combines these into one A+ to F score with recommendations, running inside MetaTrader 5.
Building a Hierarchical Market Structure Framework (Prototype) in MQL5 Using Modular Architecture and Event-Driven Design
This article describes a prototype reusable market structure framework for MQL5, built with a clean modular architecture and an internal event queue. It shows how to detect swing points, classify break-of-structure and change-of-character events, maintain a deterministic market state, and persist data to CSV. The focus is entirely on software engineering, component separation, and extensibility, not on trading signals. The prototype is a foundation for further development, not a production-ready library.
Trust Your Backtest Data First: Building a Reproducible Historical Data Audit in Python for MetaTrader 5
A reproducible, read-only Python audit for MetaTrader 5 that verifies history quality before any backtest. It exports M5 data from multiple terminals, detects gaps and synthetic bars by timestamp spacing, and reports coverage per year. The same deterministic strategy then runs on three broker feeds over a common window to quantify result drift and decompose it into spread, data/price, and trade effects.
Detecting Structural Breakpoints in Price Series Using CUSUM in MQL5 (Part 1): From Statistical Theory to a Working MQL5 Indicator
This article builds a sequential CUSUM breakpoint detector for MetaTrader 5, starting from the statistical construction and ending with a working indicator. It explains standardized log-returns, dual accumulators, the role of k and h, and the ARL₀ baseline from Siegmund. The code walkthrough covers buffer persistence, recalculation handling, idempotent chart objects, and a three-pass engine, so you can compile, attach, and use the detector to flag structural regime shifts earlier than fixed-window smoothers.
Market Microstructure in MQL5 (Part 8): Micro-Trend Strength
Part 8 adds bar-by-bar micro-trend scoring for NQ M1. GetMicroTrendStrength() builds a continuous [-1, +1] composite from EMA alignment, ATR‑normalized price position, slope consistency, and volume, with a contradiction penalty to suppress alignment/price conflicts. Session-adaptive thresholds scale by Part 7 confidence to modulate signal frequency across regimes. Outputs include a seven-state label, a binary signal, and a persistence check, calibrated on 514 New York sessions (May 2024–May 2026).
From Basic to Intermediate: Random Access (II)
In this article, we will examine how two slightly different approaches can significantly affect the overall implementation strategy, both in performance and in disk I/O design, while helping to prevent compatibility issues between applications.
MetaTrader 5 Machine Learning Blueprint (Part 19): Bagging Regimes
We test AFML's claim that the sequential bootstrap decorrelates bagged trees on overlapping triple‑barrier labels by isolating two levers: draw count and draw rule. One decision identical tree is bagged under four row‑sampling regimes and evaluated on EURUSD 2022–2023 for draw uniqueness, between‑tree correlation, AUC, and calibration. Decorrelation comes almost entirely from throttling max_samples to average uniqueness; the sequential draw adds little. Out-of-bag inflation is largest under full-count sequential sampling.