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 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
Association rules replace a neural “filter” with simple, explainable statistics computed directly inside an MT5 Expert Advisor. Market context is discretized into a small set of events (e.g., RSI_LOW, PRICE_BELOW_EMA, ATR_HIGH, SESSION_EU), then the EA counts how often each event combination is followed by an up or down move after a fixed horizon.

Rule quality is judged by support, baseline rate, lift, and probabilistic edge, not raw win percentage. Minimum support, Laplace smoothing, and comparison to the base rate reduce overfitting, while time-split validation avoids regime leakage.

Implementation stays lightweight: encode events as a bitmask, store per-mask counters, and select the best matching rule by edge weighted by sample size. In practice, rules work best as a final gate that confirms or rejects an existing BUY/SELL setup, improving transparenc...

👉 Read | Docs | @mql5dev
❤18🔥13👍11🤩4👨‍💻3
Session_Liquidity_Boxes_HUD renders non-repainting intraday range boxes for Tokyo/Asia, London, and New York sessions on the chart, and maintains running session High/Low series via indicator buffers for EA consumption.

Each session is independently configurable with enable toggles, server-time start/end hours, overnight wraparound support, and custom fill colors. A calendar-day lookback limit keeps rendering bounded for performance.

EA integration is handled through Buffer 0 (Session High) and Buffer 1 (Session Low), designed for iCustom/CopyBuffer with chronological indexing and EMPTY_VALUE outside active hours.

Chart objects use a per-instance unique prefix to prevent collisions across multiple indicator instances or other tools. An optional HUD shows SYMBOL_SPREAD, SYMBOL_TRADE_STOPS_LEVEL, and ATR(14) in points for live stop-distance and volati...

👉 Read | Quotes | @mql5dev
❤22👍10🔥8🤩5🎉1
Spread Session Recorder logs bid/ask spread data for one or multiple symbols into CSV from a single chart. It is tick-driven, so chart timeframe does not affect results. Symbols are configured via a comma-separated list, left empty for the chart symbol, or set to “*” to process up to 50 Market Watch symbols.

Each row (default 60s) stores tick count, seconds covered, min, time-weighted average, and max spread in points, plus last bid/ask. Rows are labeled by session (ASIA, LONDON, LONDON_NY, NEWYORK, ROLLOVER, OFF) using GMT-based session hours with automatic or manual GMT offset.

Restart handling rebuilds state from existing CSV and backfills missing periods from terminal tick history (bounded by Backfill hours), avoiding duplicates. Locked-file writes are buffered. Stale quotes beyond a threshold are ignored.

Output files: MQL5\Files\SpreadRecorder\SYMBOL_...

👉 Read | Forum | @mql5dev
❤20👍16🔥10🤩9
Session range breakout indicator for XAUUSD and other symbols builds an opening range from candles that open inside a configurable window (default 30 minutes). It draws a box from highest high to lowest low, then projects both edges forward as breakout levels, with optional buffer in points.

Up to three independent sessions can run on one chart with separate names, start times (server time), and colours. Default presets target London 10:00 and New York 16:30 on GMT+2 servers, with Asia 02:00 off. Levels remain active after the window (default 240 minutes) and only one confirmed breakout per side is counted, requiring a candle close beyond the level.

Target lines are plotted at configurable multiples of the range height (defaults 1.0 and 2.0), and breakout candles can be marked with arrows plus optional popup, push, or sound alerts. Designed for timefra...

👉 Read | Forum | @mql5dev
👍19🔥16❤15🤩12
TradePermissionChecker is a read-only MT5 script that generates a compact permission report on the chart and in the Experts tab. Results are shown per line as PASS, FAIL, INFO, or UNKNOWN, including a reason and the next corrective action. The report is ordered to highlight the first item to fix and ends with a failed-check count.

Checks include terminal Algo Trading state, script-level algo permission, account trading permission (including investor/read-only login), broker-side automated trading permission, symbol trade mode, and a dry-run OrderCheck for minimum lot size with translated return codes such as 10026 (server disabled) and 10027 (terminal disabled). No orders are sent.

Failure handling avoids duplicate causes: if Algo Trading is off, the dry-run is skipped. When offline, relevant items switch to UNKNOWN. Market-closed conditions are marked INFO a...

👉 Read | Freelance | @mql5dev
❤13🔥13👍12🤩6⚡2
Prop Firm Guardian is a risk control utility for funded and challenge accounts with FTMO-style limits. It does not place trades. Attached to a single chart, it monitors account-wide equity on every tick plus a 1-second timer, then closes positions and pending orders before limits are exceeded.

Daily loss protection closes everything at the daily equity floor and blocks trading until the next day. Max loss protection closes everything at the max-loss floor and blocks trading until reset, with static (initial balance) or trailing (highest closed balance) modes. An optional profit target can close and lock the account to preserve a passed challenge.

A configurable safety buffer triggers action ahead of limits to account for spread and slippage. While blocked, any new trades are closed immediately and PFG_BLOCKED is set (1 daily, 2 permanent). Day-start balance is ...

👉 Read | Forum | @mql5dev
❤12👍11🔥9🤩2👨‍💻2
SimpleLicense.mqh is a lightweight include for controlling private distribution of MT5 EAs and indicators. Configuration is compiled into the .ex5 and the customer receives only the binary. When validation fails, the reason is shown and trading or calculation logic is blocked.

Validation options include allowed account numbers (comma-separated, empty allows any), expiry date (0 disables expiry), demo-only mode for trial builds, and a broker server substring filter (empty allows any). Checks run in OnInit and then periodically (hourly, or minutely while invalid) to detect account changes or expirations without restarting the terminal. The failure alert is shown once per event, not per tick.

Usage pattern: place SimpleLicense.mqh beside the program or under MQL5\Include, include it, create CSimpleLicense, set the four parameters in OnInit, fail init on lic.Chec...

👉 Read | AppStore | @mql5dev
❤15🔥12👍9🤩7👌4👾1