MQL4 and MQL5 Programming Articles

icon

Study the MQL5 language for programming trading strategies in numerous published articles mostly written by you - the community members. The articles are grouped into categories to help you quicker find answers to any questions related to programming: Integration, Tester, Trading Strategies, etc.

Follow our new publications and discuss them on the Forum!

Add a new article
latest | best
preview
Automating Chart Patterns in MQL5 (Part 3): The Head and Shoulders and Inverse Head and Shoulders

Automating Chart Patterns in MQL5 (Part 3): The Head and Shoulders and Inverse Head and Shoulders

The article implements a deterministic MQL5 detector for head and shoulders and its inverse, validating structure from swing labels (HH, LH, HL, LL) rather than raw peak geometry. Seven ATR-aware checks enforce time order, pattern span, head clearance, shoulder symmetry, and height. A three-state lifecycle separates formation from neckline break, locks a setup, and prevents re-entry. Entries trigger only on a chart-timeframe close through the neckline.
preview
Buzzard Optimization Algorithm (BUZOA)

Buzzard Optimization Algorithm (BUZOA)

BUZOA is a population-based metaheuristic algorithm in which each agent randomly selects one of three hunting tactics at each iteration: a narrow search around its personal best, a classic PSO step toward the flock leader, or full teleportation to a random point in the search space. The article examines the implementation of the algorithm in MQL5, identifies a coefficient sign error in the original formulation, and presents benchmark results on a standard test bench.
preview
Building A Candlestick Trend Constraint Model (Part 11): Revealing Lower-Timeframe Triggers Within Higher-Timeframe Candle Relationships

Building A Candlestick Trend Constraint Model (Part 11): Revealing Lower-Timeframe Triggers Within Higher-Timeframe Candle Relationships

This article develops an A-B-C-D candlestick constraint model for MetaTrader 5. Candles A and B establish a completed D1 relationship, Candle C supplies a historical M1 setup, and closed M1 candles inside the developing Candle D either confirm or invalidate the sequence. We implement the design as a visual Expert Advisor with optional trading disabled by default, sequence-specific chart objects, restart-safe history reconstruction, spread and position gates, normalized trade parameters, and a reproducible testing plan.
preview
Bimodal Market Profile with Delta and Memory in MQL5

Bimodal Market Profile with Delta and Memory in MQL5

The classic Market Profile from forty years ago is still replicated in dozens of indicators that differ only in the color of their bars. In this article, I examine three conceptual blind spots in the original theory — the monolithic Value Area in bimodal distributions, TPO’s blindness to the aggressor, and the lack of memory between sessions — and build an indicator that addresses each of them: bimodality detection with a dead zone, order flow via CopyTicksRange with absorption detection, and composite market memory using Naked POC and HVN/LVN. The complete source code is included.
preview
Building a Prop Firm Compliance Monitor in MQL5 (Part 3): Daily Drawdown, Overall Drawdown, and Profit Targets

Building a Prop Firm Compliance Monitor in MQL5 (Part 3): Daily Drawdown, Overall Drawdown, and Profit Targets

This part turns stored account references into a financial monitoring engine for MetaTrader 5. It calculates daily drawdown from the confirmed session balance, overall drawdown from the initial challenge balance with a static equity floor, and profit‑target progress from realized balance. The EA derives usage, remaining allowance, and status for each rule, then aggregates them into a single guard state where risk conditions override target completion.
preview
Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Offline Reinforcement Learning in MQL5: Conservative Q-Learning from Historical Trade Logs Without Live Exploration

Build and deploy a conservative, offline‑trained policy entirely in MQL5. Logged trades become a fixed dataset for a two‑layer Q‑network trained with Conservative Q‑Learning, which pushes down Q‑values for poorly supported actions to limit extrapolation error. The EA loads the frozen weights and applies an out‑of‑distribution guard using saved feature statistics. This yields reproducible training and execution without live exploration.
preview
Automating Classic Market Methods in MQL5 (Part 9): Linda Bradford Raschke's 3/10 Oscillator System

Automating Classic Market Methods in MQL5 (Part 9): Linda Bradford Raschke's 3/10 Oscillator System

The article implements two swing setups in MQL5: Anti, which enters on the first 3/10 oscillator pullback after a signal line zero confirmation with price confirmation, and Holy Grail, which enters on the first pullback to the 20 EMA in a strong rising ADX trend. A single EA runs two independent state machines with precise entry and exit rules, ATR-based stops, and state recovery. You get runnable code and traceable logging.
preview
The Hilbert Spectrum in MQL5 — Live Time-Frequency-Energy Visualization of Market Cycles

The Hilbert Spectrum in MQL5 — Live Time-Frequency-Energy Visualization of Market Cycles

The article guides you through building a real‑time Hilbert Spectrum indicator in MQL5: EMD produces IMFs, a discrete FIR Hilbert transform yields analytical signals, and a CCanvas renderer draws a time–frequency–energy heatmap. Implementation details include extrema detection, SD stopping, phase unwrapping, Nyquist clipping, and bin accumulation. Use the panel to identify active cycle bands and regime shifts while keeping trade rules separate.
preview
Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

Online Portfolio Selection: A Provable Regret Bound, and the Cost That Eats It

The article implements Online Portfolio Selection in MQL5: exact simplex projection, four allocators (EG, Universal Portfolio, PAMR, OLMAR), and a BCRP solver on a concave objective. We verify weight paths against the published Python reference and self-check the optimizer. A drift-aware transaction cost model measures turnover and net wealth on a multi-asset basket. Readers get a tested library and evidence on when regret-bounded methods lose to costs.
preview
The Fractional Fourier Domain — A Chirp-Rate Adaptive Cycle Indicator for MetaTrader 5

The Fractional Fourier Domain — A Chirp-Rate Adaptive Cycle Indicator for MetaTrader 5

This article presents a native MQL5 Fractional Fourier indicator for measuring whether the dominant cycle is speeding up or slowing down. It searches for the rotation that maximizes spectral concentration in a detrended analytic window, using a unitary eigenvector FrFT and a golden‑section entropy search, and reconstructs a band‑limited cycle line. Results on known chirps and on real closes across symbols/timeframes show where the method is reliable, its bias, and its limited forward information in practice.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Conclusion)

The article continues the work on implementing the STE-FlowNet framework, which combines multi-stream processing with recurrent structures for accurate analysis of complex data. The tests conducted confirmed its stability and flexibility in various scenarios. This architecture speeds up computations and enables deeper modeling of dependencies in time series. This approach opens up new possibilities for practical application in trading and analytics.
preview
Using Renko-bar Regression with Error Correction

Using Renko-bar Regression with Error Correction

The article presents a regression-based approach to forecasting Renko bars using CatBoost: the model estimates the logarithmic return of the next bar and the uncertainty of the forecast. We will examine a cascade of residual models with OOF validation using TimeSeriesSplit, shrinkage, and overall early stopping, as well as conditional bias correction. On EURUSD D1, a reduction in OOF-MAE was achieved, along with approximately 65% directional accuracy. A working script for MetaTrader 5 is provided that generates a signal, position size, SL, and TP in brick units.
preview
Engineering Trading Discipline into Code (Part 9): Building a Trade Activity Audit Trail in MQL5

Engineering Trading Discipline into Code (Part 9): Building a Trade Activity Audit Trail in MQL5

Trade authorization controls what a cooperating Expert Advisor is permitted to send, but not every account action passes through that code. A trade may originate from the desktop terminal, a mobile device, the web terminal, or another Expert Advisor. This installment develops an independent auditor that records live transaction stages through OnTradeTransaction(), reconciles available historical orders and deals within a configured recovery window, and writes an account-bound CSV journal. An on-chart panel summarizes the selected period and provides refresh, detail, and export controls without modifying trades.
preview
Integrating News Sentiment to Avoid Strategy Disruption in MQL5

Integrating News Sentiment to Avoid Strategy Disruption in MQL5

We present a dynamic news‑sentiment filter for MQL5 Expert Advisors. It uses WebRequest to query a REST API, parses JSON sentiment and confidence, and gates entries and exits alongside Moving Average and RSI signals. You get an example EA, integration steps, timer‑based updates, and Strategy Tester workarounds. The outcome is fewer trades against dominant news flow and earlier risk reduction when sentiment flips.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (Encoder)

The article presents the comprehensive architecture of the STE-FlowNet encoder, which combines stack memory, recurrent processing, and a correlation mechanism to extract hidden market dependencies. The article demonstrates how these modules are sequentially integrated into a single computational chain capable of performing comprehensive time-series analysis.
preview
Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

Real-Time Polynomial Regression: A Causal Savitzky-Golay Implementation for MQL5

We adapt the Savitzky–Golay filter to a strictly causal, real-time form for MQL5 and derive the fixed coefficients for end-point evaluation. The article provides a full indicator and an Expert Advisor, explains the edge-evaluation noise sensitivity, and implements a multi-bar confirmation safeguard. Backtests on several symbols are shown without cherry-picking. You get ready-to-compile code, parameter guidance, and a reduced-lag alternative to moving averages.
preview
Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

Machine Learning Under Constraint (Part 4): The Stop-Loss Ceiling Meets the Optimal Trading Rule Search

The article constrains the optimal trading rule by a prop-firm stop-loss ceiling and corrects OU fitting by pooling within-trade pairs per AFML eq. 13.6. We apply the ceiling as a feasibility mask on a shared PT–SL mesh, ensuring the constrained set is a subset of the baseline. Practical guidance covers when the ceiling binds, the Sharpe cost, and how exposure and live budget state affect the bound.
preview
Population-Based Optimization Algorithms: Building a Defense Against Cheaters

Population-Based Optimization Algorithms: Building a Defense Against Cheaters

The algorithms were rerun on the updated functions, and a method was proposed for quickly verifying their "honesty". The composite test combines five different landscapes and eliminates the possibility of gaining an advantage based on the geometry of individual problems, allowing for a quick assessment of the algorithm's actual search capability. A script is provided for preliminary validation of algorithms before they are applied to the optimization of trading strategies.
preview
Benchmark Champions vs. Real-World Optimization Problems

Benchmark Champions vs. Real-World Optimization Problems

We analyze why ratings may be inflated due to the alignment of algorithm trajectories with benchmark diagonals, and we supplement the testing methodology with a requirement to keep the global extremum away from the diagonals. We update Forest and Megacity, and perform RAW verification and calibration using VerifyExtremes.mq5. A drop in HHO and DOAm performance serves as a practical indicator of false leaders.
preview
Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

Hyperdimensional Computing: Learning in One Integer Add, and the Nulls That Judge It

A complete Hyperdimensional Computing library for MQL5 implements bind, bundle and permute over 4096‑bit hypervectors, graded level ladders for quantities, an encoder for bars and sequences, and a classifier trained by integer addition. It includes a purged, ordered validation split, online updates without refitting, a market scan with two nulls, and a Python reference that reproduces the MQL5 model bit for bit, so you can validate results and deploy a reproducible indicator and test suite.
preview
Diebold-Mariano Testing in MQL5: Validating Predictive Edge Across Instruments and Models

Diebold-Mariano Testing in MQL5: Validating Predictive Edge Across Instruments and Models

The article shows how to compare two trading forecasters in MQL5 using the Diebold–Mariano test with HAC‑corrected variance and the Harvey–Leybourne–Newbold adjustment. It explains implementation details, including loss choices, horizon‑dependent lag windows, rolling computation, verdict handling, and a manifest‑driven configuration, plus a Student‑t implementation without external libraries. An EA and an indicator provide a live dashboard and significance bands for practical, defensible model selection.
preview
Neural Networks in Trading: Adaptive Perception of Market Dynamics (STE-FlowNet)

Neural Networks in Trading: Adaptive Perception of Market Dynamics (STE-FlowNet)

The STE-FlowNet framework offers a new perspective on financial data analysis by responding to actual market events rather than fixed timeframes. Its architecture preserves local and temporal dependencies, making it possible to track even small impulses in price dynamics.
preview
Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

Native Gaussian Process Regression in MQL5: Short-Horizon Price Forecasting with Uncertainty Bands

The article rebuilds a Gaussian Process forecaster in native MQL5 around market-state inputs and direct horizon log-return targets. It employs a Matern 3/2 kernel, symmetric Cholesky with adaptive jitter, standardized targets, and a log‑space grid search that avoids state side effects. The EA trades only when az‑score over observed variance clears a threshold and the edge beats the live spread. Calibration is verified in Strategy Tester.
preview
The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

The Kalman Filter for Price Smoothing: An Exact Implementation in MQL5

This article implements the scalar Kalman Filter for price smoothing in MQL5 using the standard local-level model and the exact prediction–update equations. It explains how process and measurement noise (Q, R) shape the Kalman gain, builds two independently configured filters into a fast/slow crossover, and provides a complete indicator and Expert Advisor that trade a stability-confirmed signal via iCustom, giving a reproducible baseline for testing and tuning.
preview
Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

Building a Position Lifecycle Manager in MQL5 (Part 2): Managing Manual and Multi-Symbol Positions

This update adds manual position adoption and multi-symbol lifecycle management. The manager detects and tracks positions regardless of the chart, applies initial protection, transitions to break-even under fixed or ATR triggers, and validates broker constraints per symbol. Using the MACD sample for context, it demonstrates reusable management across instruments and manually opened trades.
preview
Uncertainty as a Model (Part 5): The Basics of Regression

Uncertainty as a Model (Part 5): The Basics of Regression

A practical introduction to time series regression models: regression on a constant and simple regression with deterministic, exogenous, and endogenous regressors. It describes the key steps in the diagnostic process, including residual analysis and hypothesis testing, that are necessary for making informed trading decisions. MQL5 scripts for MetaTrader 5 are included; they implement tests and plots using real data.
preview
How to Set Up an AI Hedge Fund in MetaTrader 5

How to Set Up an AI Hedge Fund in MetaTrader 5

The article examines the architecture of a committee consisting of 15 AI agents: ten analysts and four risk officers vote in three parallel phases, and the Chair records the final result. Isolated pair contexts with separate reputations are used for eight currency pairs. The dynamic vote threshold depends on the daily PnL targets. The Expert Advisor uses only the signal, SL and TP, which allows for evaluation pf the quality of its decisions without any additional mechanics.
preview
Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

Chart Synchronization in MQL5 (Part 1): From a Simple Script to an Interactive Indicator

The article develops a practical MetaTrader 5 tool that synchronizes charts of the same symbol across timeframes, starting from a script and moving to an interactive indicator. It uses time as a common reference, converts it to bar indices with iBarShift(), and navigates charts with ChartNavigate(). The result is a synchronized workspace for efficient MTF analysis. This is Part 1 of a three-part development series.
preview
Where your backtest stops being real: Measuring the depth of your broker's tick history

Where your backtest stops being real: Measuring the depth of your broker's tick history

In the "Every tick based on real ticks" mode, the Strategy Tester's journal reports the minutes for which real ticks were absent or discarded and says that every tick generation was used for them. We show where the journal records this, measure how far back usable tick history goes on two demo servers, and check the ticks from inside an Expert Advisor, so a test range can be chosen by its real-tick share.
preview
Building a PDF Creation Library in MQL5 (Part 2): Why PDFs Break

Building a PDF Creation Library in MQL5 (Part 2): Why PDFs Break

Learn how a viewer opens a PDF backwards, why xref entries must be exactly 20 bytes, and how a two-character change falsifies multiple offsets. We reproduce three typical failures, compare results in PDFium and pypdf, and extract four strict checks a generator must pass. The included PdfValidate.mqh class for MQL5 applies these checks and returns actionable offsets and object numbers for reliable testing beyond “it opens”.
preview
Controlling MetaTrader 5 from Telegram with Hermes and MCP

Controlling MetaTrader 5 from Telegram with Hermes and MCP

Hermes Agent links a private Telegram bot to the MetaTrader 5 MCP interface, so natural-language requests call terminal tools under controlled permissions. The article shows how to install Hermes on Windows, configure an AI service and the Telegram gateway, authorize users, and add the MCP settings generated by the terminal. Readers learn to run read‑only checks, perform bounded MQL5 edits and compilation, launch Strategy Tester runs, inspect market and account data, and enable trading tools deliberately.
preview
The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The MQL5 Standard Library Explorer (Part 18): Building a Multi-Symbol Indicator Cache

The article introduces a centralized cache that serves indicators to multiple strategy nodes. It encodes full indicator identity in keys, stores Standard Library objects in CArrayObj entries, reuses matching instances, verifies readiness, refreshes data, and deletes each indicator on final release. Readers gain a predictable resource lifecycle and reduced duplication in multi‑symbol Expert Advisors.
preview
Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

Neural Networks in Trading: A Spike-Semantic Approach to Spatiotemporal Identification (Conclusion)

In our interpretation, S3CE-Net skillfully translates the market into the language of events and captures early impulses that traditional indicators simply average out. STFS ensures robust training — the model sees the data from different perspectives and does not overfit to local anomalies. SSAM blocks and the OpenCL implementation deliver practical speed and accuracy, while the separation between training and deployment modes saves resources in production.
preview
The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The Hypothesis of Randomness: Searching for Hidden Patterns in Price Series

The article describes a test of the hypothesis of randomness for quotes based on a chi-square statistic derived from the frequencies of overlapping s-chains. The article shows how to define discrete states and compare observed and expected frequencies in order to detect Markov memory in price increments. This approach helps distinguish structural dependence from noise and formalize the testing of trading hypotheses.
preview
Nonlinear OHLC Features Derived from Elliptic Curves

Nonlinear OHLC Features Derived from Elliptic Curves

The article discusses the projection of EURUSD daily candlesticks onto the secp256k1 elliptic curve and the extraction of 96 features (EC+TA) to predict the direction of the next candlestick in CatBoost. The price mapping to the curve and the training pipeline on 2,000 D1 bars are shown; the full model achieves a test AUC of 0.6508, with EC features contributing 60.6%. The materials are suitable for reproduction in Python/MetaTrader 5.
preview
Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

Try/Catch style in MQL5: Bringing Modern Error Management to Algorithmic Trading

This article presents an exception-like model for MQL5 that prevents VM faults through defensive guards and cooperative TRY/CATCH/FINALLY macros. It introduces structured error objects (CException), result propagation (CResult), manual stack tracing, and integrated logging for clear diagnostics. Readers learn how to validate risky operations, propagate failures predictably, and keep EAs stable when facing zero‑divide, null access, invalid handles, and array‑bounds conditions.
preview
Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

Agent Based Market Simulation: Growing a Market From Rules, and Using It to Catch an Overfitted Strategy

A compact MetaTrader 5 library builds a synthetic market from agents: a minority game, a zero‑intelligence double auction, a stylized‑facts analyzer, and a parameter scanner. The result is a testbed with known answers, providing the control real price backtests lack. Each result is cross‑checked by the model's phase transition, a matching Python implementation, and detection of a planted edge.
preview
Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

Adaptive Trade Management in MQL5: Building a Broker-Aware, Deterministic, and Explainable Exit Engine

This article presents an MQL5 trade-management engine that converts exit rules into proposal generators. A policy engine ranks all proposals by a configurable reason priority with documented tie-breakers. A broker-aware validator checks the candidates in that order and falls back to the next one on rejection, and an execution adapter sends the first accepted request. Reconciliation confirms the result on the position before the internal state changes. The engine uses R-multiples for thresholds, persists intratrade state, and records a decision trace for each managed position on every tick.
preview
The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

The MQL5 Standard Library Explorer (Part 17): Building a Reusable Portfolio Manager with CArrayObj

We present a multi‑symbol EA structure that moves symbol‑specific state into independently initialized CStrategyNode objects and manages them with CPortfolioManager. Using CArrayObj with FreeMode, Add(), At(), Delete(), Total(), and Clear(), the manager ensures safe ownership and isolation, while timer‑driven routing and completed‑bar gates keep processing deterministic. This lets you scale portfolios, control risk per node, and avoid duplicated event handling.
preview
Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

Online False Discovery Rate Control: Putting an Error Budget on a Live Signal Stream

The article addresses online false discovery rate control for streaming signals, where fixed thresholds inflate noise discoveries. We port LORD3, LORD++ and SAFFRON into MQL5, construct a causal bootstrap p‑value source without a resolution floor, and verify correctness before market data. Dependence stress tests, a budget/level indicator and a two-arm Strategy Tester show how to configure, monitor and throttle streams to keep the acted-on noise fraction within target.