Fixed RSI/Stochastic thresholds break in trends because they ignore volatility, leaving oscillators pinned at extremes and triggering repeated counter-trend entries. A Z-Score normalizes price deviation by rolling standard deviation, giving a volatility-aware mean-reversion signal: (Price - SMA) / StdDev, with extremes treated as anomalies rather than guaranteed reversals.
The implementation defines a strict βsignal contractβ: symmetric Β±2.5 thresholds, calculations on closed bars only (shift=1), and safeguards for missing history and zero StdDev. The math is isolated in a CZScore class (include file) to reuse identical logic in both an indicator and an EA, avoid code duplication, and manage object lifetime to prevent memory leaks.
An indicator validates behavior visually and optimizes CPU using prev_calculated. The EA uses CTrade, runs once per ba...
π Read | AlgoBook | @mql5dev
The implementation defines a strict βsignal contractβ: symmetric Β±2.5 thresholds, calculations on closed bars only (shift=1), and safeguards for missing history and zero StdDev. The math is isolated in a CZScore class (include file) to reuse identical logic in both an indicator and an EA, avoid code duplication, and manage object lifetime to prevent memory leaks.
An indicator validates behavior visually and optimizes CPU using prev_calculated. The EA uses CTrade, runs once per ba...
π Read | AlgoBook | @mql5dev
β€22π12
This article builds an MT5 weekend-gap indicator that turns Friday-close vs Monday-open discontinuities into persistent chart structures, so older gaps stay readable as the week evolves.
Gaps are detected from session time breaks (>= 48 hours) rather than day-name rules, then filtered by a minimum pip threshold with digit-aware pip sizing. Each gap is stored as a record with boundaries, midpoint, and an active-week flag.
Instead of buffers, the framework uses chart objects (rectangles, lines, labels) to keep multiple gaps visible and independently editable. A simple state machine updates the active gap in real time (fresh, partial, reaction, filled) and restyles objects on transitions.
Lifecycle handling is explicit: one-time historical scan on first calculate, tick-by-tick state updates, week rollover promotion to historical zones, and full cleanup...
π Read | NeuroBook | @mql5dev
Gaps are detected from session time breaks (>= 48 hours) rather than day-name rules, then filtered by a minimum pip threshold with digit-aware pip sizing. Each gap is stored as a record with boundaries, midpoint, and an active-week flag.
Instead of buffers, the framework uses chart objects (rectangles, lines, labels) to keep multiple gaps visible and independently editable. A simple state machine updates the active gap in real time (fresh, partial, reaction, filled) and restyles objects on transitions.
Lifecycle handling is explicit: one-time historical scan on first calculate, tick-by-tick state updates, week rollover promotion to historical zones, and full cleanup...
π Read | NeuroBook | @mql5dev
β€21π8
Traditional money management in MT5 often reduces risk only after closed losses, which can be too slow for pattern-based strategies. The article builds CMoneySuffixAE, a custom Wizard-compatible money module that sizes positions proactively using current market structure instead of loss counters.
The model combines two real-time checks. A suffix automaton indexes βPrice DNAβ (Up/Down/Flat sequences) in linear time, letting the EA measure how familiar the latest 16-bar pattern is and scale lot size from exact historical repetition without expensive O(nΒ²) scans.
An autoencoder adds structural risk control. It reconstructs normalized recent prices and uses reconstruction error as an anomaly signal; when geometry breaks (news shocks), confidence collapses and position size is aggressively cut before losses accumulate.
π Read | Freelance | @mql5dev
The model combines two real-time checks. A suffix automaton indexes βPrice DNAβ (Up/Down/Flat sequences) in linear time, letting the EA measure how familiar the latest 16-bar pattern is and scale lot size from exact historical repetition without expensive O(nΒ²) scans.
An autoencoder adds structural risk control. It reconstructs normalized recent prices and uses reconstruction error as an anomaly signal; when geometry breaks (news shocks), confidence collapses and position size is aggressively cut before losses accumulate.
π Read | Freelance | @mql5dev
π22β€20π5
Quantum XAUUSD Silver Trader is a multi-indicator Expert Advisor for XAUUSD and XAGUSD on MT5, combining RSI, ADX, fast/slow moving averages, and a volatility filter into a single weighted decision. Separate presets are applied per metal to account for different volatility profiles, while a configurable threshold gates trade entries.
The weighting is adaptive: recent closed-trade outcomes adjust the contribution of each component, aiming to reduce overreliance on any single signal.
Risk controls are part of the core design. Orders use ATR-based stop loss and take profit, plus an adaptive ATR trailing stop. Account protection includes daily and total drawdown limits, daily loss limits, a position-size cap, and an optional hard stop. A micro/cent mode targets small deposits, with conservative defaults of 0.5% risk on Gold and 0.3% on Silver, typically on M15 an...
π Read | AlgoBook | @mql5dev
The weighting is adaptive: recent closed-trade outcomes adjust the contribution of each component, aiming to reduce overreliance on any single signal.
Risk controls are part of the core design. Orders use ATR-based stop loss and take profit, plus an adaptive ATR trailing stop. Account protection includes daily and total drawdown limits, daily loss limits, a position-size cap, and an optional hard stop. A micro/cent mode targets small deposits, with conservative defaults of 0.5% risk on Gold and 0.3% on Silver, typically on M15 an...
π Read | AlgoBook | @mql5dev
β€26π5π4
Exchange Market Algorithm (EMA) is a population metaheuristic modeled as a trading session: agents are ranked by fitness, split into elite, middle, and beginners, then updated with group-specific rules while elites remain fixed to preserve the best solutions.
Each iteration runs two modes. In a balanced market, the middle moves toward a random elite mentor, while beginners blend guidance from elite and middle. In a fluctuating market, the middle either copies the global best or samples around the elite centroid; beginners use resets, wide local searches, or opposition moves away from poor regions.
Exploration-to-exploitation is controlled by a sigmoid decay rate. An MQL5 C_AO_EMA class encapsulates parameters (r1/r2, riskAlpha), initialization, movement, and revision/sorting. Tests show modest but consistent improvement as problem size grows under a ...
π Read | Signals | @mql5dev
Each iteration runs two modes. In a balanced market, the middle moves toward a random elite mentor, while beginners blend guidance from elite and middle. In a fluctuating market, the middle either copies the global best or samples around the elite centroid; beginners use resets, wide local searches, or opposition moves away from poor regions.
Exploration-to-exploitation is controlled by a sigmoid decay rate. An MQL5 C_AO_EMA class encapsulates parameters (r1/r2, riskAlpha), initialization, movement, and revision/sorting. Tests show modest but consistent improvement as problem size grows under a ...
π Read | Signals | @mql5dev
β€22π6β3
Many EAs treat overnight swap as an afterthought, even though it can materially change expectancy on multi-day trades, especially on high-differential pairs like AUDJPY. Swap is effectively daily interest: long positions can earn credit, shorts often pay, and triple-swap rollovers must be projected inside the holding window.
The article shows how to make swap actionable in MQL5 by reading SYMBOL_SWAP_LONG/SHORT plus SYMBOL_SWAP_MODE, then converting broker-specific units into a per-lot, per-day value in account currency. It handles common retail modes (points, deposit currency, interest-based using the 360-day convention), warns and returns 0 for reopening/margin modes, and notes where currency conversion or open-price accuracy is required.
Four drop-in building blocks tie this into real EA decisions: daily swap calculation, expected swap over a planned hol...
π Read | CodeBase | @mql5dev
The article shows how to make swap actionable in MQL5 by reading SYMBOL_SWAP_LONG/SHORT plus SYMBOL_SWAP_MODE, then converting broker-specific units into a per-lot, per-day value in account currency. It handles common retail modes (points, deposit currency, interest-based using the 360-day convention), warns and returns 0 for reopening/margin modes, and notes where currency conversion or open-price accuracy is required.
Four drop-in building blocks tie this into real EA decisions: daily swap calculation, expected swap over a planned hol...
π Read | CodeBase | @mql5dev
β€23π5π2
This part turns multifractal diagnostics into simulation-ready inputs for MMAR. A new Spectrum Fitter converts the scaling curve Ο(q) into the singularity spectrum f(Ξ±) via a discrete Legendre transform (central differences, low-q filtering, and rejection of invalid negative f(Ξ±) points).
The empirical f(Ξ±) is then matched to four parametric cascade models (Normal, Binomial, Poisson, Gamma). Each fit minimizes SSE using ALGLIBβs BLEIC optimizer with strict parameter bounds to keep solutions physically meaningful.
A CSpectrumFitter class encapsulates the pipeline and selects the best distribution by lowest SSE. On EURUSD M10, the Binomial model wins, yielding Ξ±_min/Ξ±_max that quantify spectrum width and directly control cascade heterogeneity, supporting realistic volatility clustering with negligible extra runtime versus partition analysis.
π Read | Calendar | @mql5dev
The empirical f(Ξ±) is then matched to four parametric cascade models (Normal, Binomial, Poisson, Gamma). Each fit minimizes SSE using ALGLIBβs BLEIC optimizer with strict parameter bounds to keep solutions physically meaningful.
A CSpectrumFitter class encapsulates the pipeline and selects the best distribution by lowest SSE. On EURUSD M10, the Binomial model wins, yielding Ξ±_min/Ξ±_max that quantify spectrum width and directly control cascade heterogeneity, supporting realistic volatility clustering with negligible extra runtime versus partition analysis.
π Read | Calendar | @mql5dev
β€14π5
Cooperative MARL is moving toward offline multi-task training, driven by the cost of new environment interaction and poor scaling when agent counts or objectives change. Transformer-based models help, but many pipelines still miss task-specific structure and the temporal buildup of coordination.
HiSSD (Hierarchical and Separable Skill Discovery) proposes joint, hierarchical learning of shared cooperation skills and task-specific skills from offline datasets. Modules are trained end-to-end, with a multi-agent IQL-style value model, a planner selecting high-level skills, and a controller trained via VAE objectives plus contrastive separation across tasks.
An MQL5-oriented adaptation maps agents to univariate market sequences, adds controlled cross-sequence information exchange via masked attention (CATCH), then produces per-agent skill vectors with independent conv...
π Read | AlgoBook | @mql5dev
HiSSD (Hierarchical and Separable Skill Discovery) proposes joint, hierarchical learning of shared cooperation skills and task-specific skills from offline datasets. Modules are trained end-to-end, with a multi-agent IQL-style value model, a planner selecting high-level skills, and a controller trained via VAE objectives plus contrastive separation across tasks.
An MQL5-oriented adaptation maps agents to univariate market sequences, adds controlled cross-sequence information exchange via masked attention (CATCH), then produces per-agent skill vectors with independent conv...
π Read | AlgoBook | @mql5dev
β€25π4
This article adds βdisciplineβ to MetaTrader 5 EAs by separating strategy signals from an equity governance layer that supervises execution during stress. It tracks peak equity, drawdown, daily loss, and rapid equity drops, then drives a four-state machine: NORMAL, CAUTION, RESTRICTED, LOCKDOWN.
The design is modular: monitoring and analysis feed a state engine with cooldown and recovery checks (hysteresis to avoid flip-flopping). CAUTION scales risk via lot multipliers, position caps, and trade spacing; stricter states can block entries while still allowing position management.
Implementation uses a clean MQL5 library of specialized classes plus a thin EA wrapper. A single Authorize() call becomes the trade gate, with hard limits as an immediate backstop. A built-in SMA test engine and on-chart dashboard make behavior easy to validate in backtests.
π Read | Signals | @mql5dev
The design is modular: monitoring and analysis feed a state engine with cooldown and recovery checks (hysteresis to avoid flip-flopping). CAUTION scales risk via lot multipliers, position caps, and trade spacing; stricter states can block entries while still allowing position management.
Implementation uses a clean MQL5 library of specialized classes plus a thin EA wrapper. A single Authorize() call becomes the trade gate, with hard limits as an immediate backstop. A built-in SMA test engine and on-chart dashboard make behavior easy to validate in backtests.
π Read | Signals | @mql5dev
β€33π5π3
Long-only trend breakout EA for MetaTrader 5 with fixed-currency risk per trade and execution restricted to the open of a new bar.
Signal logic: on the last completed bar, a buy setup triggers when Close(Bar 1) is strictly above High(Bar 2). Stop loss is set at Low(Bar 1). Take profit is derived from a configurable risk-to-reward ratio. Designed for indices with persistent upside bias, including NAS100, and typically evaluated on H4.
Risk management uses tick value and tick size to convert the stop distance into position volume, normalized to broker volume steps. Trades are skipped if the required size is below the minimum.
Backtests referenced: NAS100, H4, ~3.5 years, M1 OHLC modelling. Real-tick validation and broker-specific spread/contract checks remain required before live use.
π Read | AppStore | @mql5dev
Signal logic: on the last completed bar, a buy setup triggers when Close(Bar 1) is strictly above High(Bar 2). Stop loss is set at Low(Bar 1). Take profit is derived from a configurable risk-to-reward ratio. Designed for indices with persistent upside bias, including NAS100, and typically evaluated on H4.
Risk management uses tick value and tick size to convert the stop distance into position volume, normalized to broker volume steps. Trades are skipped if the required size is below the minimum.
Backtests referenced: NAS100, H4, ~3.5 years, M1 OHLC modelling. Real-tick validation and broker-specific spread/contract checks remain required before live use.
π Read | AppStore | @mql5dev
β€23π9
Microstructural features treat each OHLCV bar as an aggregation of trades and attempt to recover spread, price impact, and order-flow imbalance at bar close.
A two-layer design is used. compute_all_microfeatures() runs on OHLCV only and produces Roll spread, Corwin-Schultz spread and sigma, plus Kyle, Amihud, and Hasbrouck lambdas with rolling t-stats where applicable. Kernels are Numba-accelerated and avoid Pandas in inner loops.
When tick data exists, bar_microstructure_features() and vpin() add per-bar imbalance stats and VPIN from volume-synchronized buckets. Tick preprocessing and bar boundary indexing via searchsorted enable parallel bar kernels while keeping VPIN bucket filling sequential.
Outputs converge to a bar-indexed feature frame suitable for downstream ML pipelines.
π Read | Signals | @mql5dev
A two-layer design is used. compute_all_microfeatures() runs on OHLCV only and produces Roll spread, Corwin-Schultz spread and sigma, plus Kyle, Amihud, and Hasbrouck lambdas with rolling t-stats where applicable. Kernels are Numba-accelerated and avoid Pandas in inner loops.
When tick data exists, bar_microstructure_features() and vpin() add per-bar imbalance stats and VPIN from volume-synchronized buckets. Tick preprocessing and bar boundary indexing via searchsorted enable parallel bar kernels while keeping VPIN bucket filling sequential.
Outputs converge to a bar-indexed feature frame suitable for downstream ML pipelines.
π Read | Signals | @mql5dev
β€16π6
Part 35 upgrades the custom MT5 canvas layer from simple two-point line tools to a full analytical toolkit with 15 new objects: channels (parallel, equidistant, regression), pitchforks (Andrews, Schiff, modified Schiff), Gann tools (line, fan, box), multiple Fibonacci variants, plus delete-all.
The core change is support for multi-anchor geometry, derived handles, and per-tool βlevel arraysβ (ratios, styles, visibility) stored with each object. Three-click placement and dual-state rubber-band previews standardize interaction across complex tools.
Key implementation details include OLS regression channels that recompute endpoints on redraw, sigma bands with proper alpha compositing, scanline quadrilateral fills, dashed/AA line reuse, and hit-testing that recalculates live geometry so tools stay aligned with evolving price data.
π Read | Forum | @mql5dev
The core change is support for multi-anchor geometry, derived handles, and per-tool βlevel arraysβ (ratios, styles, visibility) stored with each object. Three-click placement and dual-state rubber-band previews standardize interaction across complex tools.
Key implementation details include OLS regression channels that recompute endpoints on redraw, sigma bands with proper alpha compositing, scanline quadrilateral fills, dashed/AA line reuse, and hit-testing that recalculates live geometry so tools stay aligned with evolving price data.
π Read | Forum | @mql5dev
β€18π7
Part 2 extends an MQL5 chart object detector beyond basic time/price pairs to support complex analytical objects used in rule-based strategies.
Focus areas include extracting Fibonacci level arrays via OBJPROP_LEVELS and OBJPROP_LEVELVALUE, collecting three-point geometry for OBJ_CHANNEL and OBJ_PITCHFORK, and normalizing the results into an extended data structure suitable for deterministic checks such as 0.618 retracement alignment or median-line contact conditions.
Implementation targets OBJ_FIBO, OBJ_FIBOTIMES, OBJ_FIBOFAN, OBJ_FIBOARC, OBJ_CHANNEL, and OBJ_PITCHFORK, with the same approach applicable to cycles and Gann tools. Delivery consists of ComplexObjectDataCollector.mqh (derived from the Part 1 detector) and a timer-based TestComplexObjectsEA.mq5 that logs extracted levels and geometry for validation.
π Read | Signals | @mql5dev
Focus areas include extracting Fibonacci level arrays via OBJPROP_LEVELS and OBJPROP_LEVELVALUE, collecting three-point geometry for OBJ_CHANNEL and OBJ_PITCHFORK, and normalizing the results into an extended data structure suitable for deterministic checks such as 0.618 retracement alignment or median-line contact conditions.
Implementation targets OBJ_FIBO, OBJ_FIBOTIMES, OBJ_FIBOFAN, OBJ_FIBOARC, OBJ_CHANNEL, and OBJ_PITCHFORK, with the same approach applicable to cycles and Gann tools. Delivery consists of ComplexObjectDataCollector.mqh (derived from the Part 1 detector) and a timer-based TestComplexObjectsEA.mq5 that logs extracted levels and geometry for validation.
π Read | Signals | @mql5dev
β€14π8π3
Recurrence matrices in RQA are reinterpreted as adjacency matrices: each time index becomes a node, each recurrence becomes an undirected edge, and the diagonal is cleared to remove self-loops. This turns pattern counting into graph topology analysis, exposing structure like clustering, shortest paths, centrality, and degree correlation.
The MQL5 library adds CRNAMetrics to compute 12 network measures (degree stats, clustering/transitivity, path length/diameter, betweenness/closeness, assortativity, density). Rolling analyzers (CRNAWindow, CJRNAWindow) apply the metrics per window for single-series and joint recurrence, with facades (CRNA, CJRNA) for one-call use.
Two indicators plot five live metrics (ACC, transitivity, normalized APL, assortativity, avg betweenness). The approach is practical but CPU-bound; betweenness and triangle counting scal...
π Read | Docs | @mql5dev
The MQL5 library adds CRNAMetrics to compute 12 network measures (degree stats, clustering/transitivity, path length/diameter, betweenness/closeness, assortativity, density). Rolling analyzers (CRNAWindow, CJRNAWindow) apply the metrics per window for single-series and joint recurrence, with facades (CRNA, CJRNA) for one-call use.
Two indicators plot five live metrics (ACC, transitivity, normalized APL, assortativity, avg betweenness). The approach is practical but CPU-bound; betweenness and triangle counting scal...
π Read | Docs | @mql5dev
β€13π5
Regression replaces buy/sell labels with a continuous target: expected price change. This removes a key weakness of binary models in tradingβdirectional accuracy ignores move size, so it cannot rank opportunities or avoid low-payoff trades.
The article shows two target designs: point-to-point future delta and an averaged future-price delta over a horizon. Averaging captures intermediate excursions and reduced overfitting in tests.
A meta βcausal inferenceβ layer trains multiple regressors on random subsets and filters trades when the main forecast is likely to be unreliable, using a tolerance on prediction error.
Models are exported to MetaTrader 5 via ONNX (Random Forest used due to CatBoost ONNX limits). In-terminal thresholds for buy/sell magnitude and meta deviation turn raw regression outputs into tradable signals, improving forward stability.
π Read | Docs | @mql5dev
The article shows two target designs: point-to-point future delta and an averaged future-price delta over a horizon. Averaging captures intermediate excursions and reduced overfitting in tests.
A meta βcausal inferenceβ layer trains multiple regressors on random subsets and filters trades when the main forecast is likely to be unreliable, using a tolerance on prediction error.
Models are exported to MetaTrader 5 via ONNX (Random Forest used due to CatBoost ONNX limits). In-terminal thresholds for buy/sell magnitude and meta deviation turn raw regression outputs into tradable signals, improving forward stability.
π Read | Docs | @mql5dev
β€17π6
MetaTrader 5 Strategy Tester optimization output remains transient and fragmented, which complicates comparative studies across SMA, EMA, KAMA and other filter families. Native reports do not persist custom metrics and the XML report is not practical for downstream tooling.
A reusable include, CSVExportEngine.mqh, exports standard TesterStatistics() fields plus derived metrics such as Sortino Ratio from deal history, average trade duration via DEAL_POSITION_ID matching, and signal-quality measures tracked per bar (lag on turns, whipsaws, price-to-line distance, intersection frequency).
Multi-core optimization introduces file-lock contention: parallel agents can lose rows when FileOpen() returns INVALID_HANDLE, and Sleep() does nothing in the Tester. The fix is an iteration-based spin-lock retry around FileOpen(), with phase-aware filenames (Baselin...
π Read | Quotes | @mql5dev
A reusable include, CSVExportEngine.mqh, exports standard TesterStatistics() fields plus derived metrics such as Sortino Ratio from deal history, average trade duration via DEAL_POSITION_ID matching, and signal-quality measures tracked per bar (lag on turns, whipsaws, price-to-line distance, intersection frequency).
Multi-core optimization introduces file-lock contention: parallel agents can lose rows when FileOpen() returns INVALID_HANDLE, and Sleep() does nothing in the Tester. The fix is an iteration-based spin-lock retry around FileOpen(), with phase-aware filenames (Baselin...
π Read | Quotes | @mql5dev
β€14π5
Most MT5 EA reviews rely on account history or post-trade CSV exports. Both omit intratrade behavior because history stores only endpoints, not what happened while a position was open.
Tick-level maximum adverse excursion (MAE) and maximum favorable excursion (MFE) capture worst drawdown and best run-up in account currency. Trades with identical final PnL can have materially different MAE/MFE, changing conclusions about entry timing, stop placement, and whether mean reversion is doing the work.
A reusable MQL5 class, CTradeJournal, tracks all open positions on every tick, stores initial risk at entry for R-multiple normalization, and writes a structured CSV on close. Integration stays minimal: Init on OnInit, NotifyOpen on fill, Update on every tick, NotifyClose from OnTradeTransaction.
π Read | Freelance | @mql5dev
Tick-level maximum adverse excursion (MAE) and maximum favorable excursion (MFE) capture worst drawdown and best run-up in account currency. Trades with identical final PnL can have materially different MAE/MFE, changing conclusions about entry timing, stop placement, and whether mean reversion is doing the work.
A reusable MQL5 class, CTradeJournal, tracks all open positions on every tick, stores initial risk at entry for R-multiple normalization, and writes a structured CSV on close. Integration stays minimal: Init on OnInit, NotifyOpen on fill, Update on every tick, NotifyClose from OnTradeTransaction.
π Read | Freelance | @mql5dev
β€6π4β‘1
MetaTrader 5 custom symbols can turn raw market data into synthetic instruments, and 3DBarCustomSymbol.mq5 is a concrete example. It builds β3D barsβ that encode price action alongside volume behavior, time-cycle features, and volatility measures, making anomalies and regime shifts easier to spot than on standard candles.
The indicator is structured like a solid MQL5 project: init validates inputs and loads history; symbol-creation configures precision, sessions, and metadata; processing computes normalized metrics (returns/acceleration, volume changes, volatility); an update loop refreshes the current bar on a timer for near real-time use.
Practical benefits: traders can monitor volatility bursts, volume spikes, and acceleration changes on a dedicated custom chart, while developers can feed the synthetic symbol into indicators or EAs. Performance is...
π Read | CodeBase | @mql5dev
The indicator is structured like a solid MQL5 project: init validates inputs and loads history; symbol-creation configures precision, sessions, and metadata; processing computes normalized metrics (returns/acceleration, volume changes, volatility); an update loop refreshes the current bar on a timer for near real-time use.
Practical benefits: traders can monitor volatility bursts, volume spikes, and acceleration changes on a dedicated custom chart, while developers can feed the synthetic symbol into indicators or EAs. Performance is...
π Read | CodeBase | @mql5dev
β€11π2π1