MQL5 Algo Trading
542K subscribers
3.88K photos
6 videos
3.89K 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
DI crossover signals (+DI 14 vs -DI 14) work in trends but fail in ranges, where repeated crossings occur inside a tight band and cannot cover spread and slippage. Wilder’s ADXR filter reduces this, but a single threshold misses key context such as ADX slope, DI separation, dominance duration, and volatility state.

A two-layer setup addresses this. Layer 1 replaces fixed ADXRβ‰₯25 with an Optuna-optimized gate over ADXR threshold, DI lookback, and minimum DI separation, maximizing precision on a validation split. Layer 2 adds a Random Forest meta-label that scores each gated signal using 11 ADX-derived features, then sizes positions by confidence.

Tested on 7 years of EURUSD H1 (MT5), the approach targets higher precision by suppressing low-quality crossover trades rather than adding new entries.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀34πŸ‘7✍4πŸ‘Œ2
Market nonstationarity creates volatility and liquidity regimes where fixed-parameter systems break. A static SMA crossover with fixed periods and a point threshold tends to overtrade in high volatility and miss signals in low volatility, forcing reactive manual re-optimization.

A practical adaptive approach is to re-fit the decision boundary on each new bar using MQL5 solvers.mqh. CNlEq (Levenberg–Marquardt) can update a volatility-scaled threshold using ATR and a rolling window least-squares objective with light regularization.

Implementation centers on an EA class with NewBar detection, Optimize() using the reverse-communication loop (m_needf, m_needfij), numerical residual/Jacobian evaluation, and CTrade execution with ATR-based SL/TP constrained by SYMBOL_TRADE_STOPS_LEVEL.

Typical convergence is a few iterations per bar with sub-millisecond ...

πŸ‘‰ Read | Freelance | @mql5dev
❀39πŸ‘10πŸ‘Œ3πŸ†1
Bollinger Bands and Donchian Channels describe past price behavior but don’t provide model-based coverage. A fixed β€œ2σ” Bollinger width is a convention, and Donchian width is driven by realized extremes.

The article replaces heuristics with a rolling OLS regression channel and computes confidence intervals (mean uncertainty) and prediction intervals (future observation range) using Student’s t with nβˆ’2 degrees of freedom. It also distinguishes an in-window edge band from a true one-step-ahead forecast at x=n.

Key implementation notes for MT5: interval widening at window edges comes from OLS leverage, not data scarcity; t-values matter for typical window sizes; and MT5 DRAW_FILLING limitations make five line plots (fit + 4 bounds) the most reliable rendering.

πŸ‘‰ Read | Signals | @mql5dev
❀31πŸ‘7✍2πŸ‘Œ2
The article completes a Gaussian Process library for MQL5 by formalizing three core extension points: IKernel (covariance + analytic hyperparameter derivatives), ILikelihood (noise/class model with gradients and Hessians), and IInference (pluggable posterior inference returning NLML, gradients, and cached matrices for prediction).

It implements RBF, Linear, and Periodic kernels plus Sum/Product composites that correctly route or combine derivatives (including product rule for gradients). Likelihoods cover Gaussian regression and logit binary classification, with numerically stable sigmoid/softplus and higher-order derivatives where needed.

Inference is split into ExactInference for Gaussian likelihood (fast NLML + analytic gradients via Cholesky-based cho_solve) and LaplaceInference for non-Gaussian cases (Newton updates, GPML-style gradient computation, optimize...

πŸ‘‰ Read | VPS | @mql5dev
❀45πŸ‘8✍2πŸ‘Œ2
RealCost Spread P95 Logger for MT5 is an open source utility for monitoring spread behavior on the active chart symbol. It samples the live spread and shows a compact panel with current and average spread, p50/p90/p95/p99, maximum spread, sample count, alert state, and the share of samples above a configured threshold. Optional logging writes local CSV output for later review.

p95 is useful because average spread can mask short spikes around rollover, news windows, session transitions, or low-liquidity periods. p95 approximates the spread level covering most observations while reducing the impact of a single worst outlier. p99 and max provide additional tail context.

The EA is read-only by design: no trading, no order changes, no position management, no external data transmission, and no signals. Configuration includes sampling cadence, in-memory sample cap, ...

πŸ‘‰ Read | VPS | @mql5dev
❀29πŸ‘7πŸ‘Œ3πŸ†2
Spread Meter by Fox Wave is a single-symbol spread dashboard for the active chart. It shows the current live spread in real time and retains the historical extremes with exact timestamps.

The panel maintains separate MAX (widest) and MIN (tightest) spread records. Values change only when a new extreme is set, preserving a stable reference for best and worst spread conditions. A visual flash highlights record updates at the moment they occur.

Configuration includes panel position, color scheme, and refresh rate. The design uses a modern dark panel and is intended to be lightweight enough to run across multiple charts with minimal CPU load.

This setup helps identify spread spikes during news events and thin-liquidity sessions, and provides an at-a-glance view of pricing consistency for the monitored symbol.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀17πŸ‘13πŸ‘Œ2πŸ‘1πŸŽ‰1
Swap Meter provides a live monitor of BUY and SELL swap rates for the active chart symbol, presented in a compact color-coded panel with continuous refresh.

Positive values render in green, negative in red, and zero in neutral gray to make overnight financing impact visible at a glance. A change-detection layer triggers alerts as soon as the broker updates either swap rate.

Notifications can be enabled independently via popup, terminal log, or mobile push, with an adjustable threshold to reduce rounding noise. Each detected update can also trigger a brief visual highlight.

The panel supports configurable colors, placement, and refresh interval, with low CPU overhead and a dark UI aligned with FoxWave Spread Meter. Suitable for carry and swing workflows where swap changes affect holding costs.

πŸ‘‰ Read | CodeBase | @mql5dev
❀24πŸ‘10πŸ‘Œ2
FoxWave Daily Range Tracker provides a real-time view of today’s price range versus the symbol’s Average Daily Range (ADR), helping assess whether current movement is still within normal bounds or nearing exhaustion.

The panel shows today’s high and low for the active chart symbol and calculates the current range in pips with correct handling for 3/5-digit pricing and JPY pairs. ADR is computed over a configurable lookback (default 14 days) using only fully closed daily candles.

A β€œRange Used %” indicator adds a color-coded progress bar: green below 60%, yellow 60–90%, red above 90%. The tool runs as a single-symbol panel with customizable colors, position, and refresh rate, designed for low CPU use across multiple charts.

πŸ‘‰ Read | VPS | @mql5dev
❀25πŸ‘7⚑2πŸ‘Œ2πŸ‘¨β€πŸ’»2
As an MQL5 neural-network library grows to include more classes and OpenCL kernels, understanding object relationships and inheritance becomes harder than following individual code paths. The article shows how to regain architectural visibility by generating structured API docs directly from annotated source.

Doxygen is presented as a practical fit for MQL5 due to its C++-like syntax and support for hyperlinks and MathJax formulas. Key techniques include marking doc comments, building navigable groups/subgroups, creating cross-references, documenting kernel indices and parameters, and describing classes, methods, and interfaces with clear input/output and return semantics.

It also covers wiring Doxygen to parse .mqh and .cl files, mapping extensions, enabling MathJax, and producing a main page plus hierarchy and file viewsβ€”useful for team coordination, m...

πŸ‘‰ Read | Forum | @mql5dev
❀38πŸ‘13πŸ‘¨β€πŸ’»4⚑3πŸ‘Œ3
Confirmed Swing Points Helper is an educational indicator for MetaTrader 5 that plots confirmed swing highs and swing lows on-chart, with optional HH, HL, LH, and LL labeling.

A pivot is accepted only after the current bar’s high/low is validated against a configurable number of bars on both the left and right side. This produces confirmed, non-predictive signals and introduces an expected delay due to the right-side requirement.

The implementation tracks the most recent accepted high and low pivots. Each new high is compared to the prior high and classified as HH or LH. Each new low is compared to the prior low and classified as HL or LL.

Key inputs include depth per side, optional minimum distance between same-type pivots, label visibility, colors, font size, and an object-name prefix. This is not a trading system and provides no buy/sell output.

πŸ‘‰ Read | Calendar | @mql5dev
❀48πŸ‘9✍2πŸ‘Œ2🀯1
Maximum drawdown is commonly used as a single risk figure, but it omits frequency, time spent below prior peaks, and recovery speed. Equity curves with identical maximum drawdown can still produce very different holding risk.

DrawdownDNA processes a daily equity series and analyzes the full drawdown structure. It rebuilds equity and underwater curves, segments the underwater curve into distinct drawdown episodes, and aggregates multiple risk metrics into a resilience grade.

Each run prints to the Experts tab: a text underwater curve; an episode table with depth, drawdown duration, recovery time, and underwater length; max and average drawdown, episode count, longest underwater period, and total time underwater; Ulcer Index, Pain Index, and Recovery Factor; plus a composite score (depth, recovery, stability) graded from A+ to F with recommendations.

Inp...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀44πŸ‘13πŸ‘Œ4πŸ‘€3
Net profit and win rate can hide where returns actually come from. A strategy may look stable while a small set of outlier trades carries most of the result.

Profit Concentration Analyzer processes closed trades from a CSV (Date, Profit) and prints a report in the Experts tab. It quantifies concentration via the gross-profit share from the top 1%, 5%, 10%, 25% and 50% of winners, plus the net-profit share from the Top-N largest trades. It also calculates the Gini coefficient for winner inequality.

Robustness checks include a survival test that removes the best winners by a configurable percentage and recomputes net profit and profit factor, and a day-consistency check that compares the best day against a prop-firm-style limit (PASS/FAIL). A composite A+ to F score summarizes concentration, consistency, and survival, with targeted recommendations.

Input exp...

πŸ‘‰ Read | CodeBase | @mql5dev
❀39πŸ‘6πŸ‘Œ4
Systematic trading based on price-only signals remains under-specified compared with HFT, arbitrage, options, or spread frameworks. Two practical directions are usually considered: ML β€œblack box” models with ongoing retraining, or an explicit theory of price formation with factors encoded into rules.

A baseline empirical observation is that, across instruments and timeframes, bullish and bearish candles tend toward a 50/50 split on large samples. Short windows deviate, and the mean-reversion speed back to that balance appears instrument-specific and relatively stable.

A prototype EA design uses this imbalance: scan N within MinBars..MaxBars, trigger when bullish/bearish share exceeds OpenPerc, trade contrarian in a position series, size lots by expected series length, and exit via profit-per-lot, imbalance normalization (ClosePerc), or equity floor.

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘31❀26πŸ†5πŸ‘Œ3πŸ‘€3πŸ’”2
Grey models (GM) are being used as forecasting and smoothing tools when market data is limited, noisy, or non-stationary. Core requirements are minimal: at least 4 points, strictly positive values, equal sampling intervals, and no gaps.

GM(1,1) applies an Accumulated Generating Operation (AGO) to reduce noise, then fits parameters via a discretized form and OLS. The same closed-form allows both smoothing and multi-step forecasts, with strong behavior on linear trends.

Extensions include Rolling GM (averaging multiple GM windows) and adaptive weighting based on forecast error. GM(1,1) can also build trend channels by deriving bounds from parameter ranges.

Discrete variants avoid fragile symbolic math and enable GM(0,2), GM(1,2), and GM(2,1) style models. They are typically most reliable for 1-step-ahead forecasts, with higher horizons adding compl...

πŸ‘‰ Read | Signals | @mql5dev
❀33πŸ†4πŸ‘Œ2πŸ”₯1
Entropy features for ML can be derived from the information content of tick-rule direction sequences inside each bar. Four estimators are commonly used: Shannon (marginal distribution), plug-in block entropy (w-grams), Lempel-Ziv complexity (compressibility), and Kontoyiannis entropy (entropy rate via average match length).

A production issue in afml.features.entropy was traced to Numba usage: applying @njit to functions consuming Python strings forced silent object-mode fallback, leaving interpreter overhead while appearing JIT-accelerated. Converting messages to uint8 at the boundary and running pure nopython kernels removed the bottleneck.

Three fixes were applied: a corrected Kontoyiannis match-length kernel (including overlap handling), a Lempel-Ziv phrase-library membership check aligned with the greedy parsing definition, and a plug-in trunca...

πŸ‘‰ Read | Quotes | @mql5dev
❀34πŸ‘Œ3πŸ‘2
Standard moving averages miss a key intraday detail in MT5: they ignore tick volume, so a high-impact news candle can distort β€œfair value” and trick EAs into pullbacks far from where real liquidity concentrated.

This article implements a daily-reset VWAP with volume-weighted deviation bands, using typical price (HLC/3) and tick volume. It enforces closed-bar calculations (shift=1) and a hard reset at 00:00 broker time, treating VWAP as a liquidity anchor rather than fixed support/resistance.

The core is a reusable VWAP_Engine.mqh class: midnight is found via MqlDateTime (robust to missing bars), rates are loaded with CopyRates and ArraySetAsSeries, and a two-pass loop computes VWAP then volume-weighted variance with zero-volume safeguards.

The same engine powers both an indicator (fast updates via prev_calculated) and a pullback EA (new-bar gate, CTrade, mean-...

πŸ‘‰ Read | Forum | @mql5dev
❀30πŸ‘€3πŸ‘Œ2
Breakeven and trailing stops are dynamic, so an MT5 terminal restart can break trade management even when the position stays open. The missing pieces are not just virtual SL/TP levels, but the decision history: whether breakeven already fired, whether trailing is active, and the last price that advanced the trail.

This part extends the recovery architecture by persisting that state in SQLite. Breakeven becomes a one-time transition tracked by a breakevenActivated flag, saved immediately when the virtual stop is upgraded.

Trailing is treated as an evolving workflow. A lastTrailPrice marker plus step/distance rules prevents repeated updates and lets the EA resume trailing from the exact progression point after restart.

Runtime management centralizes breakeven, trailing, virtual exits, and heartbeat updates, continuously saving state so recovery restores cont...

πŸ‘‰ Read | Forum | @mql5dev
❀38πŸ‘Œ3
Multi-timeframe EAs can require hundreds of indicator handles when monitoring many symbols and timeframes. Eager creation in OnInit() forces the terminal to connect feeds, sync history, allocate buffers, and register every handle upfront, which increases startup latency and wastes memory on rarely used combinations.

A lazy-loading handle manager reduces this cost by creating handles only when requested, sharing identical configurations via reference counting, and centralizing cleanup through a single FlushAll() in OnDeinit().

The cache uses a composite key: symbol + EnumToString(timeframe) + integer indicator type + serialized parameters. Parameters should be serialized with IntegerToString() and fixed DoubleToString() to avoid locale-dependent keys. Release decrements ref counts and calls IndicatorRelease() only at zero, preventing orphaned handles across relo...

πŸ‘‰ Read | Quotes | @mql5dev
❀45πŸ‘Œ3✍2πŸ‘€1
Premium Discount Range Mapper is an educational indicator for MT5 that maps a user-defined price range into Premium, Equilibrium, and Discount zones to support market context analysis.

The active range can be set manually or calculated automatically from a lookback period. With automatic mode, leaving Range High and Range Low at 0 makes the tool use the highest high and lowest low in the selected window. With manual mode, custom inputs define the zone boundaries.

Output includes Range High/Low, the 50% Equilibrium level, and optional 25% and 75% reference levels. The zones are visual references only and are not trade signals.

The indicator does not place orders, does not generate buy/sell calls, does not forecast direction, and does not guarantee outcomes.

πŸ‘‰ Read | VPS | @mql5dev
❀34πŸ‘Œ2πŸ†1
A single profitable MT5 backtest can hide whether an EA would survive prop-style constraints. This article adds a reusable MQL5 evaluation module that simulates challenge rules during Strategy Tester runs: profit target, daily loss, overall drawdown, minimum trading days, and optional time limits.

It normalizes tester balance/equity to a configurable β€œvirtual” challenge account, then evaluates either one attempt or rolling attempts that restart daily/weekly/monthly to expose start-date sensitivity. Each attempt tracks state (dates, trading days, daily reference, status, failure/incomplete reason) and confirms breaches before marking a pass.

Results are surfaced as an Experts journal summary plus an HTML dashboard with stats, attempt history, and optional charts, helping traders and developers diagnose whether failures come from daily limits, overall draw...

πŸ‘‰ Read | Calendar | @mql5dev
❀26πŸ‘Œ2
Part 2 extends the Wyckoff EA from entry logic to exits using Wyckoff’s Law of Cause and Effect with a point-and-figure horizontal count.

A self-contained MQL5 Expert Advisor is built with a finite state machine: range detection, spring→SOS→LPS for longs, and upthrust→SOW→LPSY for shorts. Sequencing is enforced to reduce false positives; invalidation resets to idle.

Take profit is computed from P&F: count line at LPS/LPSY, columns counted at that level, box size derived from range ATR (~0.25 ATR), and a 1-box reversal. Targets outside bounds fall back to 2R. Only Trade/Trade.mqh is required.

πŸ‘‰ Read | Calendar | @mql5dev
❀29πŸ‘Œ1