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
Equal highs and equal lows can be tracked as liquidity lines: two or more confirmed swing points that finish within an ATR-based tolerance, with no intervening candle taking the level first. Each additional matching swing adds another touch to the same line. Swings are confirmed on closed bars, so the objects appear with a delay and do not repaint.

When price trades beyond the line and closes back inside, the level is classified as swept, indicating buy-side or sell-side liquidity was taken and price returned. When the candle closes beyond the line, the level is marked as taken to separate breakouts from sweeps. A sweep is descriptive only and does not predict direction.

Key settings include swing length (default 3), tolerance (default 0.10 ATR), ATR period (14), max bars between swings (100), and scan depth (1500). Options cover active/swept/taken lim...

๐Ÿ‘‰ Read | Forum | @mql5dev
โค13๐Ÿ‘8๐Ÿ”ฅ7๐Ÿคฉ5
Trading-terminal optimization typically depends on gradients. Hand-coded derivatives are fast but brittle. Finite differences require step-size selection and trade truncation against cancellation. Automatic differentiation removes that parameter and yields derivatives accurate to floating-point rounding.

Forward mode propagates value and derivative together using dual numbers and per-function chain rules. It requires one pass per input, with a small set of elementary functions.

Reverse mode records a tape of parent slots and local partials during evaluation, then sweeps backward once to accumulate adjoints. The implementation uses flat arrays, amortized growth, and skips zero adjoints to avoid unnecessary NaNs.

Bench results: reverse mode is a poor fit for least-squares Jacobians, finite differences can be faster under ~5 parameters, and exact Jac...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค14๐Ÿ‘14๐Ÿ”ฅ4๐Ÿคฉ4
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