MQL5 Algo Trading
512K subscribers
3.44K photos
3 videos
3.44K links
The best publications of the largest community of algotraders.

Subscribe to stay up-to-date with modern technologies and trading programs development.
Download Telegram
Standard volatility bands such as Bollinger Bands and Keltner Channels often rely on symmetric, time-independent assumptions. Standard deviations around an arithmetic mean do not test whether price has a statistical tendency to revert, which can cause mean-reversion systems to keep trading into sustained drift and accumulate drawdowns.

A more robust filter is the Ornstein-Uhlenbeck process: dX_t = θ(μ − X_t)dt + σ dW_t. Estimating μ, θ, and σ turns “bands” into an equilibrium model: μ as the baseline, θ as the reversion or drift regime flag, and σ as diffusion limits derived from residual variance rather than rolling deviation.

Operationally, θ > 0 supports mean reversion, while θ < 0 indicates trend drift and should disable reversion logic. For liquid instruments on M30/H1, trades are taken only when price exceeds diffusion boundaries, targeting con...

👉 Read | CodeBase | @mql5dev
25👍52
Partial position closing in MQL5 is a position management method that closes a defined percentage of volume at intermediate Take Profit levels. It can lock profit earlier than breakeven or trailing stop logic, while keeping exposure for further movement.

Key constraints include extra commissions per partial close and missed execution if price never reaches the defined levels. Suitability depends on strategy horizon, with wider swing targets generally fitting better than tight scalping targets.

Implementation focuses on predefined TP percentages between entry and final TP, paired with volume percentages. A CPartials class can track positions by magic number, calculate TP1/TP2/TP3 prices, and call CTrade::PositionClosePartial.

Recent architecture changes include shared logging (CLoggerBase), a Utils library, risk management split into modules, Accou...

👉 Read | CodeBase | @mql5dev
24👍8🏆2
Extremal Optimization (EO) targets hard trading-style objective landscapes where gradients fail: discontinuities, multiple local optima, and non-differentiable regions. Inspired by the Bak–Sneppen model, it updates the worst parts of a solution rather than refining the best, using punctuated changes to escape stagnation.

The MT5-oriented implementation builds a population, ranks agents and their parameter “components,” then selects an agent and a component via a power-law (tau). The chosen component is replaced with a bounded random value, keeping step discretization, while Revision tracks the best global candidate.

Bench tests showed weak convergence (~25% overall score), leading to a revised variant: explicitly mutate selected components, tune selection/mutation distributions, and manage epochs to stabilize search and improve practical performance for pa...

👉 Read | Calendar | @mql5dev
21👍9🔥4
Growing EAs often devolve into hidden coupling via global state. Replacing globals with a publish/subscribe event bus makes dependencies explicit: modules publish typed events and subscribe to what they need, turning an N-to-N mesh into a star centered on the bus.

The design uses an enum for event routing (compile-time safety, O(1) lookup), a fixed-size payload passed by const reference to avoid copies, and an abstract listener interface for polymorphic dispatch. An MQL5 pointer-array limitation is handled with a slot wrapper struct per event type.

Dispatch is synchronous and validated with CheckPointer(), so handler cost impacts tick time and listener lifetimes must be managed carefully. In practice, signal, execution, and risk components stay independent while still coordinating reliably.

👉 Read | Docs | @mql5dev
16👍9
Part 2 extends MT5 EA restart recovery beyond SQLite persistence by handling virtual stop-loss and take-profit. When protection exists only in runtime memory, a terminal shutdown can leave positions unprotected and still open after price already crossed the intended exit.

The recovery flow adds broker-side position discovery using symbol and magic number, then restores virtual levels from SQLite and validates them against current price before resuming management. If a position exists without saved state, the EA switches to safe mode.

Testing uses controlled trades opened without broker SL/TP, builds initial virtual protection immediately, stores state, and recovers it on startup. A controlled close path updates SQLite from ACTIVE to CLOSED after the position is exited.

👉 Read | AlgoBook | @mql5dev
17👍6
MQL5 order submission starts with MqlTradeRequest, a 21-field struct with tight semantic coupling. The compiler checks types, not intent, so invalid combinations often pass build and fail at runtime, sometimes after broker-side normalization.

A fluent COrderBuilder shifts correctness from caller discipline to validated configuration. It keeps shadow fields plus validity flags and a single error string. Send() acts as a dispatch gate: mandatory flags, cross-field stop logic, OrderCheck(), then OrderSend(), returning one boolean and a diagnostic message.

Pointer-return chaining is the practical mechanism in MQL5 because method references are unsupported. Buy/Sell and pending variants set action and type as a pair, removing a common class of mismatches.

Stop-loss and take-profit checks are directional, deferred, and enforce SYMBOL_TRADE_STOPS_LEVEL befor...

👉 Read | Forum | @mql5dev
23👍5
MQL5 custom signals shift from multi-asset arbitrage to single-asset breakout handling under macro volatility. The earlier B-Tree plus Bayesian model fits cross-sectional lookup and uncertainty scoring, but is less suitable for localized, sequential shock detection.

The proposed stack pairs Disjoint Set Union (DSU) with a Deep Belief Network (DBN). DSU partitions adjacent bars into connected volatility components using MakeSet/Find/Union, driven by ATR expansion and Bollinger bandwidth change to avoid smoothing lag.

DBN (stacked RBMs) validates each DSU cluster via an energy score and a tanh-bounded output in [-1, 1]. Trades pass only when the DBN output exceeds a tuned threshold, targeting regime shifts while filtering stop-hunt noise.

👉 Read | Quotes | @mql5dev
14👍13
MetaTrader 5 generates rich tester logs and optimization data, but its built-in reports can’t answer portfolio-grade questions like cross-symbol robustness, drawdown recovery behavior, or session-based edge. The workaround is straightforward: log normalized trade and optimization fields to CSV from MQL5, then analyze in Python with pandas plus matplotlib/seaborn.

The article defines a reusable pipeline and five charts that fill key gaps: a multi-asset parameter match matrix for consistency checks, a lag-vs-whipsaw scatter to quantify filter efficiency, a walk-forward paired-slope view to expose overfitting, KDE distributions for drawdown depth and duration, and an hour-by-day heatmap to reveal intraday/intraweek alpha clusters.

A deployment wrapper runs the full suite against new exports, reading directly from the terminal’s MQL5\Files directory to a...

👉 Read | AppStore | @mql5dev
17👍9
Three FX setups were captured across multiple timeframes, highlighting current technical structure and key decision zones.

EURCAD on H1 shows a clearly defined range with repeated reactions at prior swing levels. Price action remains sensitive to nearby support and resistance, with short-term momentum shifting quickly after each rejection.

AUDUSD on D1 reflects a broader directional phase, with candles compressing around recent highs and lows. The next sustained move likely depends on a clean break and acceptance beyond the latest daily structure.

EURJPY on M15 presents faster rotation and tighter swings, typical of intraday conditions. Multiple retests suggest liquidity is being worked around local extremes, increasing the importance of confirmation before entry.

👉 Read | AlgoBook | @mql5dev
34👍42
This part refactors a simple candle-imbalance EA into a more adaptive series trader for MetaTrader, targeting stability without losing too many entries.

Key upgrade: replace a fixed “bull/bear excess” threshold with a probability-aware, non-linear threshold that decreases as the sample size grows. This keeps signal frequency roughly consistent across different window lengths and avoids unrealistic thresholds on large samples.

Signal quality is improved by treating the analysis window as a range, not a single N: use weighted aggregation across multiple sample lengths, and require the imbalance condition to appear in several samples to confirm a regime.

Risk control focuses on fewer, better-timed grid adds: open new positions only on counter candles (sell on bullish, buy on bearish) and/or only when the imbalance strengthens. This cuts position coun...

👉 Read | NeuroBook | @mql5dev
53👍13👀5🏆2🎉1👌1
An immediate stop-loss closure triggers an OnTradeTransaction event that can be used to react without polling.

A common approach is to detect the stop-loss deal, confirm the position was closed, and read the closed side, volume, and close price.

Based on those values, logic can place an opposite-side pending order right away, with predefined distance, expiration, and risk limits.

Key points include filtering only the relevant transaction types, avoiding duplicate submissions on partial fills, validating symbol trading conditions, and enforcing spread and freeze-level checks before sending the pending order.

👉 Read | Forum | @mql5dev
36👍8🤔3
Brute-force pattern search for Expert Advisors can remain competitive when combined with strict sample segmentation. Compute limits on multi-year M5 data make full-pass searches impractical even on multi-core hardware.

Segmenting by day of week and intraday time corridors reduces data volume and exposes time-quantized effects. Predictability varies by segment; expected payoff and profit factor often peak in different windows, requiring trade-off analysis.

Algorithm updates add fixed time-interval search, selectable or randomized day sets, randomized server-time windows with duration bounds, and multi-threaded optimization. Templates were adjusted to write day/time fields into quote files to avoid terminal time-function overhead and inconsistencies.

Testing on 2010–2020 with 2020 as forward period shows higher quality patterns with fewer trades. A ...

👉 Read | VPS | @mql5dev
69👍134😐2
Universal Breakout Study is an open-source Expert Advisor for systematic breakout research on H1. It forms a range (“box”) from a configurable number of hourly candles using GMT-adjusted session time, then places Buy Stop and Sell Stop orders beyond the boundaries with an optional distance shift and order expiration.

Trade protection supports disabled, fixed-point, or box-coefficient Stop Loss and Take Profit. Position sizing is risk-based via a configurable percent of balance. Post-entry management includes breakeven, classic trailing stop with start/step rules, and time-based exits conditioned on minimum profit.

Testing controls include a weekday enable/disable filter to isolate calendar effects. The tool targets hypothesis testing and parameter studies, with forward validation required before any live deployment.

👉 Read | Quotes | @mql5dev
43👍114
Frequent new/delete inside OnCalculate() adds measurable overhead in MT5, mainly from allocation bookkeeping and constructor/destructor work, plus timing jitter that hurts latency consistency during high tick rates. For single-object-per-tick logic, the simplest fix is reusing a persistent object and calling Reset().

When many short-lived objects coexist, a fixed-capacity object pool moves all heap activity to OnInit(). A free-list built from an index stack enables O(1) Acquire/Release without scans, supports ownership validation, and guards against double-release. On exhaustion, Acquire() returns NULL by design to avoid reintroducing heap calls in the hot path.

A benchmark indicator compares pooled vs unpooled paths using GetMicrosecondCount(), with careful buffer handling (EMPTY_VALUE sentinel, no ArraySetAsSeries on INDICATOR_DATA, and DRAW_SECTION for ...

👉 Read | VPS | @mql5dev
41👌6👍5
A Multi Forex Scanner indicator has been ported to MT5 from an earlier MT4 version, targeting faster identification of potentially tradable FX pairs.

The scanner reads symbols directly from the Market Watch list and displays the currently available currencies without requiring separate configuration.

Visibility is controlled through the platform: to exclude a currency or pair from the output, hide the corresponding symbol in Market Watch. This keeps the scanner aligned with the active watchlist and reduces manual filtering.

👉 Read | Signals | @mql5dev
28👍6👌6
Part 36 turns the MT5 canvas from pure “analysis lines” into a full annotation surface by adding 17 tools: 8 filled/reshapable shapes (rectangle with 8 handles, triangle, rotated rectangle/ellipse, circle, N-point path, arc, curve) and 9 text-driven markers (text, multiple arrows, note, price note, callout, comment).

The core upgrade is an in-place text editor rendered entirely on the canvas: caret/timer blinking, click-to-caret mapping, multi-line wrap via prefix measurement with binary search, keycode-to-Unicode input, arrow navigation with shift-selection, and anti-aliased text via supersampling and alpha extraction.

Implementation keeps the existing tool pipeline (hit testing, selection, handles, rubber-band preview) and extends the class chain (Fibonacci → shapes → annotations). Shapes use signed-distance anti-aliasing, point-in-polygon tests, a...

👉 Read | AppStore | @mql5dev
20👍9
Fixed-period SMA/EMA filters fail when regime changes: short periods amplify noise, long periods add lag, and manual retuning becomes constant maintenance.

A Self-Adaptive Moving Average (SAMA) in MQL5 can be implemented as an adaptive FIR filter using NLMS. Core loop per closed bar: compute input energy, predict via dot product, measure error, clamp error by ATR on spikes, then update weights with a normalized step. No repainting when updates are restricted to finalized bars.

Stability controls include weight leakage to limit drift, optional weight-sum normalization to keep output on price scale, and adaptive learning rate via Efficiency Ratio to reduce overfitting in ranges and tighten tracking in trends. Input modes can train on price, differences, or returns with reconstruction back to price.

Part 2 covers the full indicator build; Part 3 ben...

👉 Read | Quotes | @mql5dev
11👍11🏆4
A structure-based MT5 EA can detect swings and pullbacks yet still fail because it treats every retracement the same. The core upgrade here is volatility-normalized pullback analysis: retracement depth is measured relative to the prior impulse and evaluated against an ATR regime, so the same point pullback can be “too deep” in low volatility and acceptable during expansion.

The system is layered: swing candidates are validated via structure break, displacement, liquidity sweep, and time-respect; a state machine classifies accumulation/expansion/distribution/reversal; liquidity zones track equal highs/lows and untouched swings. Pullbacks are scored using depth, ATR-normalized distance, candle overlap, momentum decay, and volatility compression.

Trades require alignment between market state and a high-scoring pullback, plus sweep or displacement confirmat...

👉 Read | NeuroBook | @mql5dev
12👍5🤯2
MT5 Strategy Tester scales well for parameter sweeps, but the output layer becomes limiting in multi-asset, multi-timeframe work with custom counters. Treat MT5 as compute and export only, then run ranking, mapping, visualization, and reporting in Python.

A strict CSV schema is the contract. Required fields include Test_Phase (Baseline/InSample/OutSample), Symbol, Timeframe, Indicator_Name, Filter_Period, optional Param_SAMA_LR, Net_Profit_$, Sortino_Ratio, plus custom counters like False_Flips_Whipsaws and Avg_Lag_On_Turn_Bars.

Two Python modules cover baseline comparisons (phase filter plus cross-timeframe averaging) and walk-forward validation (pick best InSample by Sortino, lock parameters, report matched OutSample and profit_drop). Outputs stay reproducible, auditable, and consistent for publication constraints such as 980px figures.

👉 Read | NeuroBook | @mql5dev
22👍7
Actor–Director–Critic extends Actor–Critic with a Director that provides binary action fit/no-fit feedback alongside the Critic’s continuous reward estimate. This reduces early-training instability, which is critical in trading where random actions are costly.

A practical implementation adapts ADC to a HiSSD multi-agent setup. Critic and Director train on latent skill representations from the shared encoder, not raw market features, improving generalization and feedback stability under uncertainty.

Training is split into offline pretraining on a fixed dataset, then online fine-tuning with live interaction. Offline uses replay-buffer sampling, recurrent-state resets per minibatch, and strict chronological sequences for RNN components.

Offline targets use a “near-perfect” trajectory built with limited look-ahead, requiring consistent recalculation o...

👉 Read | Signals | @mql5dev
14👍8
Gaussian Process classification shifts from closed-form regression to approximate inference. With logit likelihood, the posterior over latent f is non-Gaussian, so Laplace approximation is used to fit a Gaussian around the posterior mode via Newton iterations on log p(y|f)+log p(f|X). The Hessian yields the covariance of the approximation.

Prediction becomes two-stage: compute a Gaussian predictive distribution for f* at x*, then integrate σ(f*) over that distribution to obtain π*. Averaged predictive probability accounts for uncertainty, unlike σ(E[f*]) MAP.

An MQL5 modular GP library is outlined, centered on GaussianProcess plus a GPOptimizationObjective for Alglib integration, with multiple π* approximations (probit, numeric integration, Monte Carlo) and LML-based hyperparameter optimization with analytic gradients.

👉 Read | CodeBase | @mql5dev
30👍8🤡4🏆2