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
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
This article extends MT5 money management beyond linear lot scaling by adding a regime-aware circuit breaker for tail-risk, high-volatility periods. The core idea is to size positions based on how close current conditions are to historical liquidity failures, not just per-trade risk percentages.

A KD-Tree maps market states into a 2D space (log returns, ATR) and uses fast nearest-neighbor queries to detect proximity to โ€œcrashโ€ clusters. An Echo State Network adds low-latency temporal context via reservoir dynamics, producing a bounded lot-size multiplier that dampens exposure when return sequences look unstable.

Implementation centers on an MQL5 CExpertMoney-derived class, using ATR for volatility normalization and MACD as a momentum vector to modulate behavior around detected risk zones, enabling modular switching between offensive and defensive siz...

๐Ÿ‘‰ Read | AppStore | @mql5dev
โค33๐Ÿ‘Œ1
Trading losses are usually tied to risk drift: daily limits get exceeded after a losing trade, drawdowns accumulate unchecked, and predefined rules are ignored at execution time.

A MetaTrader 5 risk layer can remove that failure mode. An include-based EnhancedRiskManager.mqh centers on CEnhancedRiskManager, enforcing per-trade risk, daily drawdown, and total drawdown with conservative/moderate/aggressive presets, plus adaptive balance/equity drawdown measurement and state persistence via terminal globals.

Stress test: an aggressive martingale grid (1.5x, 200-point steps, up to 8 positions, no SL). Baseline lifespan averaged 3.2 days with 100% drawdown. With limits (5% daily, 10% total, 2% per trade), the 9-year run stayed profitable: max daily DD 4.8%, max total DD 9.7%, total return 127%, using trade blocking, forced close near limits, and profit trailing.

๐Ÿ‘‰ Read | Docs | @mql5dev
โค30๐Ÿ‘จโ€๐Ÿ’ป4๐Ÿ‘Œ1
MT5 restarts clear an EAโ€™s in-memory state, resetting risk counters, regime flags, optimization schedules, and runtime toggles. Production systems need deterministic continuity, not a fresh start after every terminal interruption.

The article builds a native MQL5 persistence layer using a readable key=value flat file in MQL5/Files/, avoiding SQLite, terminal GlobalVariables, and external dependencies. Flat files stay inspectable and per-EA, while GlobalVariables are shared, double-only, and opaque.

The design is modular: a typed value wrapper with safe type inference, a strict line parser (whitespace, comments, key validation), a serializer for consistent formatting, and a CHashMap-backed cache for O(1) reads. Writes rewrite the small file (O(n)), trading simplicity for reliability and easy integration into existing EAs.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค31๐Ÿ‘Œ4
Four intrabar entropy estimatorsโ€”Shannon, Plug-In (w-grams), Lempelโ€“Ziv complexity, and Kontoyiannis entropy rateโ€”are ported from a NumPy/Numba Python reference to practical MQL5 code for MetaTrader 5.

The design works around MT5 constraints: intrabar ticks come only from the broker-limited CopyTicksRange() cache, so older bars are marked with a sentinel (ENT_EMPTY). Bars also require a minimum tick count to avoid meaningless estimates.

Tick directions are encoded from bid changes into a compact ternary uchar stream {0,1,2}. Sequential estimators avoid missing Python primitives by using a base-3 hash for overlapping w-gram counts and a bounded look-back window to cap Kontoyiannisโ€™ O(nยฒ) search.

Integration targets live use: a single Calculate() call per new bar updates feature arrays, with explicit sentinel checks to prevent trading on missing tick history....

๐Ÿ‘‰ Read | Signals | @mql5dev
โค35๐Ÿ‘Œ2