MQL5 Algo Trading
586K subscribers
4.89K photos
7 videos
4.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
A risk-based lot sizing panel calculates volume from two inputs: risk amount (percent of balance, percent of equity, or fixed money) and stop loss in points. Loss per 1.00 lot at the selected stop is obtained via OrderCalcProfit, keeping results consistent across XAUUSD, indices, cross pairs, and crypto, not only major FX.

Trade buttons send market orders with stop loss and optional take profit already attached, after free margin validation and broker minimum stop-distance checks. Volume is rounded down to the broker step, capped by broker limits and an optional user maximum, with both target and real risk displayed. If calculated volume is below broker minimum, the trade is rejected unless “use minimum lot” is enabled, in which case the minimum is used and real risk is shown.

Supports hedging and netting accounts. Executes only on manual BUY/SELL input and...

👉 Read | AppStore | @mql5dev
❤12👍7🤩4✍2🏆1
Part 4 of Prop Firm Guard solves a common prop-firm rule: restricting trade actions around economic news, but only for news that matches the account’s actual risk exposure.

Instead of using the chart symbol, the EA scans all open positions, derives a unique set of exposed currencies, and uses that set to filter the MT5 Economic Calendar. Duplicate currencies are removed, and special handling is shown for an explicit XAU/USD model where USD exposure is inferred from broker base/profit currency properties.

A key implementation detail is fault-aware state modeling. The news subsystem distinguishes no supported exposure, a valid “no event” result, and genuinely unavailable data. Exposure collection can be partial (some positions unreadable), which correctly forces an “unavailable” outcome rather than a false-safe state.

The calendar search uses validated serve...

👉 Read | Forum | @mql5dev
❤13👍9🤩4😱2🔥1👌1
ReliableOutbox addresses a common failure mode in messaging integrations: a missing HTTP response does not prove the service did not accept the request. Automatic retries can therefore create duplicates. The queue persists state transitions so “unknown outcome” is explicit rather than hidden.

Each send is committed as IN_FLIGHT before the transport call. A verified Telegram JSON response results in SENT. Any unprovable outcome becomes UNCERTAIN and is never resent automatically, while other eligible items can continue. This is not guaranteed delivery or exactly-once; manual retry can duplicate, and discarding can leave an undelivered message unsent.

The package includes include files plus two example Expert Advisors. Core components cover state definitions, a checksummed two-slot store, queue transitions, simulation transport, JSON validation, and a Telegra...

👉 Read | AppStore | @mql5dev
❤12🔥9👍6🤩5🏆1
Part 2 turns the Part 1 time-based chart sync prototype into an interactive MQL5 indicator with visible reference objects.

V toggles a vertical line at the chart’s middle visible time. H toggles a horizontal line at the middle visible price. Presence of the object on the current chart acts as state; no separate enable flags are kept.

OnChartEvent() becomes the control path for CHARTEVENT_KEYDOWN and object-drag events. A chart must run the indicator to emit key and drag handling, but one instance can still create, update, or delete sync objects on other open charts of the same symbol.

Time sync propagates datetime, resolves bar positions per timeframe via iBarShift(false), then navigates to keep the time near chart center. Price sync propagates a price level without changing vertical scaling. Robust state/error handling is deferred to Part 3.

👉 Read | Forum | @mql5dev
❤19🔥13🤩8👍7✍5🏆1
Market microstructure can be treated as an event stream: sparse in price levels, dense in time. This makes bidirectional adaptive temporal correlation (BAT) a practical fit for tick-level inference, producing a dense direction field from fragmented impulses.

BAT combines forward and backward temporal correlation to stabilize direction and persistence estimates. This reduces the usual trade-off between reactive models that lag and predictive models that drift from observed behavior.

Adaptive temporal sampling adjusts the window to regime changes, limiting noise in low-activity periods and preserving detail during fast moves. SATMA-style aggregation downweights contradictory micro-signals and emphasizes consistent layers.

Implementation starts by voxelizing consecutive event intervals into 3D tensors, splitting into N temporal groups, extracting shar...

👉 Read | Signals | @mql5dev
❤19👍11🔥10🤩8
Live monitoring of Expert Advisors remains weak when limited to equity curves and simple averages. Degradation is often visible only after 10–15 losing trades, while earlier profits can mask a negative expectancy.

A proposed approach is an Edge Drift Detector for MT5 that tests whether the average live result per closing deal has fallen below a configurable fraction of the backtest edge. The core is a CUSUM shortfall statistic with an alarm threshold calibrated by bootstrap resampling of backtest deals, avoiding normality assumptions.

The tool estimates a likely change point, reports short and long rolling means, decomposes expectancy changes into win/loss rate and payoff components, and checks volatility and trade frequency separately. It also flags dependence via autocorrelation and can use block bootstrap. Analysis stops if the live symbol mix diverges, sin...

👉 Read | Signals | @mql5dev
❤17👍12🔥8🤩8
Hjorth “Activity/Mobility/Complexity” from EEG is repurposed for trading by computing variances of returns and their first/second differences. Activity becomes volatility, Mobility implies lag-1 autocorrelation (used as an estimated ρ1), and Complexity measures path irregularity—three related signals from one consistent calculation.

The article implements this natively in MQL5 with an O(1) rolling variance engine (ring buffer + periodic recompute to limit float drift), shared formulas for batch/rolling paths, safety clamps for edge cases, and a regime dashboard exposing ρ1 plus percentile-ranked Activity/Complexity. A self-test suite validates math against known series and a Python mirror.

A Donchian-breakout EA uses the dashboard as a “Trend” gate (positive autocorrelation + volatility/complexity filters). Strategy Tester runs on real ticks show t...

👉 Read | AlgoBook | @mql5dev
❤15👍14🔥10🤩5
Gaussian Mixture Models bring probabilistic clustering to MetaTrader 5: each observation gets soft membership across multiple Gaussian components, capturing clusters with different shapes and correlations via full covariance matrices.

The article outlines an MQL5 CGMM class trained with EM using latent “responsibility” weights, supporting both MLE and MAP. MAP adds normal-inverse-Wishart regularization to keep covariance matrices well-conditioned, improving stability for small samples or higher dimensions.

The implementation mirrors common ML tooling: K-Means++ (Alglib) or random initialization, Predict/PredictProba, ScoreSamples, Sample, plus AIC/BIC to select K. A dedicated CMVN class accelerates multivariate normal pdf and sampling using OpenBLAS Cholesky and triangular solves, avoiding explicit matrix inversion.

👉 Read | CodeBase | @mql5dev
❤18👍15🔥11🤩10
A runs-test module for MQL5 checks whether EA trade outcomes behave like independent Bernoulli trials. It converts account or tester deal history into a win/loss sequence per closed position, then applies the Wald–Wolfowitz runs test plus streak-focused checks traders typically care about.

Implementation is split across TradeSequence.mqh (position grouping, commission handling, netting reversals, breakeven policy, deterministic close-time ordering), RunsTest.mqh (exact run-count distribution in log space, normal approximation with continuity correction, minimum-achievable p, four-state verdicts), and StreakStats.mqh (Fisher–Yates shuffles with unbiased indexing and reproducible seeds).

The report adds Monte Carlo checks for longest losing streak and loss rates after 3+ consecutive losses, plus a block win-rate test to separate clustering from time drif...

👉 Read | Docs | @mql5dev
🔥18❤14👍13🤩8🎉1
Regime switches break single-indicator logic. MA cross and RSI mean reversion alternate between working and failing, and hardcoded regime filters are usually another noisy rule.

Hedge (multiplicative weights, Freund/Schapire) combines a small set of fixed “experts” by updating weights each bar based on directional loss. It targets low regret versus the single best fixed expert in hindsight. This is an accuracy bound, not a profitability guarantee after spread, sizing, stops, and thresholds.

Implementation uses five discrete voters: MA cross, RSI reversion, Bollinger breakout, MACD histogram sign, Donchian channel. Votes are {-1,0,+1}; abstain/flat scores 0.5. No forgetting: it does not formally track changing regimes.

Testing compares three modes under identical risk/execution code: Hedge weighting, equal-weight blend, and single-expert. Key sensi...

👉 Read | VPS | @mql5dev
❤13🔥13👍12🤩11
Most native MQL5 momentum metrics use finite differences. This amplifies microstructure noise, with second differences compounding it further. A causal Savitzky-Golay approach replaces differencing with a trailing least-squares polynomial fit and extracts value, velocity, and acceleration from the fitted coefficients.

A one-sided window avoids future bars, so closed-bar outputs remain immutable. The implementation focuses on proving non-repainting via closed-bar indexing and consistent array direction handling, not by assertion.

Core math is isolated in CSavGolFilter (SavGolCore.mqh). Init() solves convolution weights once per (window, order, dt); Apply() reduces to dot products. Three consumers use the same kernels: an indicator (velocity/acceleration plots), a demo EA (sign agreement), and a self-test script validating kernel identities and histori...

👉 Read | Signals | @mql5dev
🤩15👍10❤8🔥8
This article implements the Nawa–Furuhashi Bacterial Evolutionary Algorithm (BEA) in an MT5-style optimization framework, emphasizing bacterial horizontal gene transfer as a faster alternative to purely crossover-driven search. It also clarifies that “BEA” is commonly confused with Numaoka’s earlier artificial-life model, which behaves differently.

BEA combines two operators: segment-based bacterial mutation (a clone-and-select local search over contiguous coordinate blocks) and gene transfer (copying a coordinate block from a high-fitness individual into a low-fitness one). Mutation drives consistent improvement per individual; transfer rapidly propagates useful building blocks across the population.

A key engineering challenge is that mutation needs many nested fitness evaluations. The solution is a finite-state machine that maps each framework epo...

👉 Read | NeuroBook | @mql5dev
🤩12❤11👍10🔥9
Repaint Checker validates MT4 indicators that look stable in history but change in live conditions after bar close. It evaluates repainting per buffer and provides example dates for verification.

On each bar close, the EA records the visible values of every readable indicator buffer, matching what would have been available in real time. Afterward, it re-reads the same bars and compares results, counting changed values, late signals (empty at close, filled later), and vanished signals (present at close, removed later). Output includes a NO REPAINTING FOUND or REPAINTS verdict, journal entries, and a CSV report in the terminal Common\Files folder.

Configuration supports an indicator name, up to 8 numeric/boolean inputs, buffer scanning for the first 8 buffers that produce values, and a relative-change tolerance. Typical findings: Fractals flags as late-confi...

👉 Read | Signals | @mql5dev
👍19❤17🤩9🔥7👨‍💻3
Prop Risk Guard is an MT4 account risk control utility designed for prop-firm style rule sets. It monitors limits and triggers immediate enforcement by closing all open positions, deleting pending orders, and keeping the account flat until the lock resets. Compatible with any EA and with manual trading.

Supported controls include daily loss limits (percent or currency) based on starting balance, equity, or the higher of the two, with a configurable server-time day start. Closed and floating P/L are included. Max drawdown can be static or trailing from peak equity. An optional profit-target lock prevents giving back gains. Early warnings and a safety buffer reduce overshoot risk in fast markets.

When locked, new trades are force-closed within fractions of a second via frequent checks. Daily locks reset at the next day start; drawdown/target locks persist unt...

👉 Read | CodeBase | @mql5dev
❤22👍16🔥11🤩11
A minimal breakout Expert Advisor built for quick code review and controlled testing.

Logic: during the Asian session (server-time inputs), the daily range high/low is recorded. After the session ends and until the “no new entries” time, a trade is placed only when a closed bar breaks the range by a configurable buffer. Stop loss is set on the opposite side of the range plus buffer; take profit is RR-based on stop distance (default 1.5). One trade per day max; any open position is force-closed at a defined time.

Risk and filters: position size is computed from balance risk (0.5% default, capped at 2%). Trades are blocked on excessive spread, and the day is skipped if the stop exceeds 3 × ATR(H1, 14). No grid, no martingale, no averaging; every entry has a hard stop.

Testing notes: intended for liquid symbols on M5/M15; validate broker session times, run St...

👉 Read | Signals | @mql5dev
❤31👍21🤩12🔥9👨‍💻4
Many MT5 indicators look stable in backtests and then fail live because their buffer values change after a bar has closed. Repaint Checker is an EA that tests any indicator for repainting, buffer by buffer, and reports example dates.

On each bar close, it records every buffer value exactly as seen in real time. Later it rereads the same bars and compares results, counting changed values, late signals (empty at close, filled later), and vanished signals (present at close, removed later). Output includes a verdict on a panel and in the journal, plus a CSV report saved to the terminal Common\Files folder.

Inputs cover indicator path and parameters, buffer selection (0=all, up to 32), tolerance, panel, and CSV logging. Typical results: Fractals is flagged due to late confirmation; ZigZag is flagged due to last-leg redraw. The EA places no trades.

👉 Read | Docs | @mql5dev
❤20🤩11👍9👌3👀3🏆2👨‍💻1
Prop Risk Guard is an account-level risk controller for MT terminals that can monitor the full account, a single symbol, or a specific magic number. When a configured limit is hit it closes all positions, removes pending orders, and blocks new trades until the relevant lock resets. It is compatible with any EA and manual execution.

Daily loss is computed as today’s closed P/L plus floating P/L of protected trades versus the day’s starting balance, equity, or the higher of the two. The day boundary is defined by a user-selected server hour to match external rule sets.

Max drawdown can be static (vs starting balance) or trailing (vs peak equity). An optional profit target closes everything and locks the account to preserve gains. Warning alerts trigger at a configurable percentage of each limit, with an optional safety buffer to act early. State is stored in ...

👉 Read | Forum | @mql5dev
❤20🤩14👍11🔥10
BAT is implemented in MT5 as a lightweight, explainable sequence model: transform raw prices, split them into local segments, weight each segment by relevance, then recombine into a stable signal that suppresses noise while preserving structure.

The practical build starts with a terminal-native data pipeline that converts adjacent market states into a small “flow” event (a displacement), enabling the model to reason about direction and speed instead of static prices. Feature extraction is handled by a RAFT-style residual encoder.

For the Bidirectional Temporal Correlation module, the paper’s “future frame” requirement is replaced with a real-time friendly design: use the middle of an in-memory state stack as the reference, correlating both older and newer buffered frames without lookahead or extra latency. Missing MotionEncoder details are filled ...

👉 Read | Signals | @mql5dev
❤19👍11🤩9🔥8👌2
CDivergenceEnginePro updates a divergence engine to measure size instead of treating every signal as equal. It keeps all confirmed oscillator pivots in the lookback window and pairs each new pivot with up to PairingDepth earlier candidates.

Each candidate pair is scored from 0 to 100 using three components: price extension past the older pivot in ATR, oscillator disagreement in points, and separation in bars. The score is a normalized size metric based on configured references and weights, not a probability.

Pairs are filtered in a fixed order for minimum/maximum separation, minimum price extension, minimum oscillator delta, optional zone rules, and minimum score. When no pair passes, the nearest rejected pair is stored with the first failure reason for diagnostics.

Integration is reduced to Init(cfg), Refresh() per new bar, read-only queries (Typ...

👉 Read | Freelance | @mql5dev
🔥13❤12👍12🤩9
MQL5 custom indicators with input groups change the parameter slot order used by iCustom() and IndicatorCreate(). Each group line consumes a slot, even though the Inputs dialog suggests otherwise. Numeric-only shifts can stay silent and still create a valid handle.

Tests on terminal builds 6204 and 6230 show that passing values without group placeholders can remap periods, deviations, and other settings without journal errors. A BandsLite example produced 32 signals with intended inputs versus 0 signals with a shifted call over 4,577 EURUSD H1 bars in 2026.

CIndicatorInputs reads the slot layout from a running handle via IndicatorParameters(), maps “input number” to “slot number”, fills group slots, and verifies the created handle on charts. In Strategy Tester, slot order is not reported, so the class loads a saved layout file and creates an unverified...

👉 Read | Quotes | @mql5dev
👍15🔥14❤9🤩5⚡1
A 58% next-bar hit rate is meaningless without a baseline. This article implements the Pesaran–Timmermann test in plain MQL5 to compare the observed accuracy P to the “chance” rate implied by forecast bias (Px) and market direction imbalance (Py), producing a rolling PT statistic and right-tail p-value.

The Expert Advisor uses that p-value as a gate: it only trades one-bar direction forecasts when the latest window shows significance (p < α), with strict no-look-ahead scoring via a one-step-delayed evaluator and rolling 2×2 counts.

It includes an EMA-slope forecaster, an AR(1) option, and a coin-flip control, plus a self-test suite cross-checked against Python. Strategy Tester runs show the EMA signal often fails (sometimes significantly wrong-way), while pure noise can still pass the gate at expected rates—highlighting screening value, not proof of edge.

👉 Read | NeuroBook | @mql5dev
❤14🤩12🔥10👍9