MQL5 Algo Trading
568K subscribers
4.26K photos
7 videos
4.26K 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
Backtests often flatten multiple entry conditions into one profit factor, which hides where losses originate. Splitting results by setup type can change the conclusion: on USDCAD M1 one side produced most of the drawdown while the other was near flat.

A small MT5 ledger can tag each order with a setup id by encoding it into the magic number at send time. After positions close, it aggregates by DEAL_POSITION_ID to avoid partial-close double counting, and reports per-setup wins/losses plus net P/L including swap and commission.

Beyond raw win rate, the report adds a Wilson score lower bound and compares it to the breakeven rate implied by the reward ratio. This keeps early samples honest and prevents β€œtrusted” labels based on a handful of trades.

Key constraints: registration order becomes a data format, new setups must be appended, and stacked entries into o...

πŸ‘‰ Read | Signals | @mql5dev
❀33πŸ”₯12πŸ‘10🀩6✍2πŸ‘2πŸ‘Œ2
RegimeRouter is an EA structure built around explicit regime classification plus per-regime performance accounting. The classifier runs on each closed bar and combines three independent signals: ADX for directional strength, Hurst exponent on log returns for persistence vs anti-persistence, and lag-1 autocorrelation for continuation vs snapback. Each voter assigns trend, range, or abstains; the regime is committed only when the summed votes clear a configurable minimum, otherwise the system stays neutral and does not trade.

Routing is split into two modules. TREND trades N-bar breakouts only when fast/slow EMAs agree on direction. RANGE trades mean reversion by fading a stretched z-score versus a moving average. NEUTRAL places no orders. Trades are stamped via magic numbers that include the regime id, and a startup rebuilds a ledger from deal histor...

πŸ‘‰ Read | CodeBase | @mql5dev
❀25πŸ”₯13🀩12πŸ‘8πŸ‘Œ4
Many execution errors in manual trading come from arithmetic. A lot size computed mentally, combined with a wider stop than intended, often pushes realized risk far beyond the plan. This panel focuses on risk calculation only and never opens trades without a button press.

It displays current risk percent and its value in account currency, stop distance (fixed points or ATR-based), the lot size that matches the selected risk, plus spread, open volume, and floating P/L. BUY/SELL sends a market order with stop and optional target attached; target is a stop multiple (2R default).

Lot sizing is rounded down to the volume step, capped by broker limits and free margin, and avoids server rejections. Stops respect trade stops and freeze levels, widened by spread. Netting-mode opposite orders are blocked with a warning to prevent unattached stops. Inputs cover rules ...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀19πŸ‘18πŸ”₯11🀩7πŸ‘Œ2
Convolutional neural networks are adapted from image recognition to price charts to improve pattern detection under shifts and scaling. The core idea is alternating convolution (feature extraction via learned kernels) and subsampling (dimension reduction and noise suppression), then feeding the resulting feature vector into a fully connected perceptron for decisions.

The article details MQL5-style implementation: virtualized neuron classes with dispatch logic so feed-forward, gradient computation, and weight updates work across fully connected, convolution, and subsample layers. Subsampling uses windowed averaging (or max) with no trainable weights.

Training follows backprop with CNN-specific gradient flow: pooling gradients are routed to max locations or evenly distributed for averaging, while convolution gradients use padding plus convolution with a 180Β°-rotate...

πŸ‘‰ Read | Calendar | @mql5dev
❀68πŸ‘23πŸ”₯15🀩6⚑5πŸ‘Œ4πŸ†3
Documentation published for a two-sided martingale grid EA intended for study and testing. No per-trade stop loss is used by default, and exposure can accelerate during sustained one-directional moves. BasketSL_USD provides an optional floating-loss cutoff but ships disabled, leaving basket-level profit taking as the primary exit.

Operation is split into three phases. Seed places symmetric pending stops on both sides. Bump increases the opposite-side L2 lot after the first fill. Martingale activates after two fills on either side, converts remaining levels to a doubling sequence, and adds extra levels, without resizing already-filled orders.

Execution is tick-driven with reconciliation each tick, including market fills when pending levels are skipped by fast price movement. BasketTP_USD closes all positions and cancels pendings when combined P/L hits target...

πŸ‘‰ Read | AppStore | @mql5dev
❀20πŸ”₯12πŸ‘8🀩4πŸ‘Œ4
PropFirm Equity Protector is a timeframe-independent Utility EA designed for continuous risk monitoring across any symbol, with a focus on volatile markets such as XAUUSD, GBPUSD, and major indices. It relies on a 1-second OnTimer() loop rather than OnTick(), maintaining supervision during low-liquidity periods and terminal stalls.

Risk control is split into two tiers. A soft limit triggers at a warning drawdown and identifies the worst-performing open position for partial closure to reduce exposure and free margin. A hard limit activates at the maximum daily loss threshold and runs a forced close loop intended to complete liquidation under fast price movement and server errors.

Key inputs include max daily loss percent, mitigation threshold, partial close percent, slippage tolerance, retry count, push notifications, and options to auto-close and detach the...

πŸ‘‰ Read | Quotes | @mql5dev
❀43🀩13πŸ‘10πŸ”₯9πŸ‘¨β€πŸ’»5πŸ‘Œ3
RiskGuard Lite is a compact MQL5 Expert Advisor intended as an educational template for risk-controlled trade execution. The entry signal is kept intentionally basic via a fast/slow EMA crossover, keeping attention on stop placement, sizing, and execution checks.

On each new bar, the last two closed candles are evaluated for a crossover. Stop loss is set using an ATR multiple, with a floor at the broker stop level. Take profit is derived from a fixed reward:risk multiple of the stop distance.

Position volume is computed with OrderCalcProfit so a stop-out targets a defined percentage of equity, then aligned to volume step and broker limits. Pre-trade filters include spread limits and a check for an existing position on the symbol under the configured magic number. Rejections print the server return code for diagnostics.

Default inputs include EMA(20/50), AT...

πŸ‘‰ Read | Freelance | @mql5dev
❀33πŸ‘8πŸ”₯8πŸ‘Œ4🀩2πŸ‘€2πŸŽ‰1
A spread-monitor indicator for scalping that renders the live spread as a histogram in a dedicated sub-window, with a dashed horizontal threshold line and a stats panel for current, average, max, and min spread over a configurable lookback.

Spread is reported in pips via digit-aware conversion, so 5/3-digit and JPY symbols display correctly. The panel also shows round-trip spread cost per trade (spread Γ— 2), giving the break-even distance in pips for one entry and exit.

Alerts trigger when spread exceeds the configured threshold, with popup and log output and optional push notifications. A cooldown suppresses repeated alerts while spreads remain elevated.

MT5 provides no historical per-bar spread, so pre-attach bars remain empty rather than being synthesized. From attach time onward, each bar records its spread, with the current bar updating tick-by-...

πŸ‘‰ Read | Docs | @mql5dev
❀39πŸ‘11πŸ”₯9😈5πŸ‘Œ3πŸ‘¨β€πŸ’»2🀝2
Artificial Searching Swarm Algorithm (ASSA) targets global optimization cases where gradients are unusable: multimodal, discontinuous, and mixed-type spaces. Core idea is a one-iteration β€œcall” signal that propagates only when an agent improves, combined with a central Bulletin Board for global best and per-agent personal best storage.

Implementation details center on three exclusive moves in normalized space: synergistic step toward Xcall with probability Pc, a probe-driven search step using personal-best and global-best attraction with bound clipping to prevent step collapse, and a random move when the probe degenerates (NormDist < 1e-10). Agents always accept the new position, update personal best on improvement, and refresh Xcall and the Bulletin Board accordingly.

Testing typically uses fixed-budget comparisons on benchmarks such as Rosenbrock a...

πŸ‘‰ Read | Quotes | @mql5dev
❀24πŸ‘3πŸŽ‰3🀩3πŸ‘Œ3✍1πŸ”₯1
Forecasting in transport and markets increasingly looks like the same graph problem: nodes, edges, and signals evolving over time. Treating topology and time series as separate axes inflates compute and limits horizon, especially with attention at O(NT^2 + TN^2).

The Extralonger paper proposes a unified spatial-temporal representation. Each time step encodes all nodes, and each node encodes all time steps, reducing complexity to O(T^2 + N^2). Reported results extend traffic forecasting from hours to a week, with implications for longer-horizon market modeling.

Architecture details include learnable noise, periodicity embeddings (time-of-day, day-of-week), and a three-route Transformer. A Global-Local Spatial Transformer combines full-graph attention with adjacency-constrained attention to preserve both global correlations and local structure.

πŸ‘‰ Read | Signals | @mql5dev
❀15πŸ‘4πŸ”₯4πŸ†2🀩1πŸ‘Œ1
Part 4 upgrades the MT5 Cairo-style rasterizer by adding a single missing value: per-pixel coverage (0..1). Instead of a binary β€œpixel center inside” test, fills now compute how much of each pixel a shape actually occupies, eliminating jagged diagonals and preserving thin strokes without post-filters.

Coverage is computed exactly in X by interval subtraction per span, and approximated in Y using N horizontal sub-scanlines (CairoAaSamples). That one runtime variable lives in Config.mqh, enabling a practical quality/speed switch (e.g., fast during drag, high quality when static).

Color compositing is unified with anti-aliasing via CairoBlendOver: coverage multiplies source alpha, then standard β€œover” blending produces correct translucent overlaps while avoiding accidental premultiplied-darkening in ARGB buffers.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀14πŸ”₯6πŸ‘5🀩4πŸ†2πŸ‘Œ1
Most regime detectors still ship a plain HMM, which implies geometric state durations. That makes β€œending now” the modal outcome on every bar, independent of how long the regime has persisted.

An HSMM separates regime identity from sojourn time by fitting an explicit duration distribution per state. Live inference then estimates both the current regime and expected remaining bars, enabling duration-gated entries and early exits before a label flip.

Pipeline is offline EM in Python with parameters exported to a JSON manifest, while the duration-aware forward filter runs fully native in MQL5. Target setup uses XAUUSD M5, with scale-free features and strict bar-close stepping to avoid recursive double-counting.

πŸ‘‰ Read | AppStore | @mql5dev
πŸ”₯12❀11πŸ‘8🀩6πŸŽ‰1πŸ‘Œ1
Rough volatility replaces β€œsmooth” EWMA/GARCH assumptions with evidence that log-volatility behaves like fractional Brownian motion with a very low Hurst exponent (often 0.05–0.15). The article turns that into an EA-ready feature by estimating a rolling local H via a structure-function log-log regression, using blocked realized variance (e.g., 6Γ—M5 bars) to reduce microstructure noise.

The core design is dependency-free: the H estimator runs natively in MQL5 via ring buffers and closed-form OLS accumulators, with guards (pair-count checks, log safety floors) and H clamped to a training-safe range. Features are [H, vol-of-vol, H momentum].

A GradientBoostingClassifier is trained offline in Python with bar-for-bar identical math, exported to ONNX with a fixed single-float probability output for clean MQL5 inference. The system is presented with honest te...

πŸ‘‰ Read | Forum | @mql5dev
πŸ”₯13❀12🀩11πŸ‘9πŸ‘Œ1πŸ†1🀝1
PropFirm Risk Guardian for MT5 is an account-wide risk protection EA aimed at prop-firm and personal accounts. It focuses on enforcing loss limits rather than generating trades, signals, or entries.

Account-level controls monitor daily drawdown and maximum total drawdown, with an adjustable safety buffer ahead of firm thresholds. When a limit is hit, open positions can be closed automatically and pending orders removed. Protection state persists after terminal restarts.

Position-level controls can cap loss per trade using a fixed-money limit, with an option to halt trading after a single-position loss. Monitoring runs every second and on every tick, supports broker-server rollover, and covers all symbols across the account. Coordination with other EAs is handled via a Terminal Global Variable. Defaults: 5% daily, 10% overall, 1% buffer, 1% single-position; ...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀13πŸ‘12πŸ”₯11🀩7⚑1πŸ‘Œ1πŸ‘¨β€πŸ’»1
TREND Follower (DAILY) is a lightweight Expert Advisor intended as a development code base for research and iterative improvement. The core signal uses a single rule: trade direction is derived from the relationship between price and Parabolic SAR, without claims of optimization or production readiness.

Logic is minimal: price above SAR sets BUY bias, price below SAR sets SELL bias. On direction change, the EA closes any opposing position before opening a new one, implementing a direct reversal model.

Baseline capabilities include fixed-lot sizing, maximum spread filtering, configurable trading hours, Magic Number isolation, optional SL/TP, execution checks, broker-compatible volume handling, and safer reversal flow.

The design targets extension: risk-based sizing, ATR-driven exits, trailing, break-even, partial closes, higher-timeframe filters, regime det...

πŸ‘‰ Read | Calendar | @mql5dev
❀20πŸ‘12πŸ”₯7🀩5πŸ’―2πŸ‘Œ1
Safe Risk Manager EA 1.02 is an educational, manually operated MT5 trade panel intended for hedging accounts. BUY/SELL actions place market orders with percent-of-equity sizing, broker-side stop loss, and optional take profit. It is not an automated signal system and provides no profit or maximum-loss guarantees.

Entries are blocked when spread exceeds a configured limit or when a daily-loss threshold is reached. The daily lock persists for the current broker-server day across restarts. It manages positions on the current symbol matching a configured magic number using break-even and trailing-stop rules, and can request closing those positions. Netting accounts are rejected, and volumes below broker minimum are rejected rather than rounded up.

Daily loss uses server-day realized P/L (profit, swap, commission, fees) with optional floating P/L. Commissions, g...

πŸ‘‰ Read | Signals | @mql5dev
❀19πŸ”₯9πŸ‘6πŸ‘Œ4🀩3πŸ‘€1
This article builds a self-calibrating scale-out system for MetaTrader 5 that replaces fixed 1R/2R/3R exit ladders with levels derived from actual trade behavior. It measures each trade’s maximum favorable excursion in R (entry-to-initial-stop distance) and uses those samples to compute percentile-based exit rungs.

The design splits responsibilities into three testable modules: CExcursionTracker records per-ticket MFE-in-R tick-by-tick and persists samples to CSV; CExitLadderCalibrator converts the most recent N samples into ordered rung thresholds with a minimum-sample gate and a fallback ladder; CLadderExecutor applies partial closes once per rung per ticket, handles volume rounding, and can move the stop to breakeven after the first fill.

An EA wires this together by reconstructing realized R from deal history (volume-weighted across multiple pa...

πŸ‘‰ Read | Freelance | @mql5dev
❀20πŸ‘7πŸ”₯3πŸ‘¨β€πŸ’»3πŸŽ‰1🀩1πŸ‘Œ1
Most live ONNX drift monitors in trading EAs track only feature mean and standard deviation. That misses distribution-shape changes that preserve first two moments, such as unimodal to bimodal shifts.

A per-feature detector based on 1D Wasserstein-1 compares a frozen reference window to a rolling live window. With equal sample sizes, W1 is computed by sorting both windows and averaging absolute rank-wise differences, with no iterative optimal transport solver.

The implementation targets MetaTrader 5: 8-feature vector shared by model and detector, circular buffers, reference stored pre-sorted, recompute on closed bars. W1 is normalized by reference IQR for scale comparability, and both composite and max-per-feature thresholds are enforced via a JSON manifest.

Offline validation shows mean/std monitors failing on bimodal shifts, while W1 remains sensiti...

πŸ‘‰ Read | VPS | @mql5dev
❀22πŸ‘9πŸ”₯5πŸ‘Œ2🀩1
An ONNX reader can produce accurate node and tensor reports, but a log list hides topology. Parallel branches and joins read like a linear chain because connections are only implicit via value names.

A visualization pipeline in MQL5 addresses this by extending the parser to keep tensor shapes, node attributes, and limited weight samples with statistics. Internal value shapes are recovered by parsing the graph’s value-info entries, not just exposed inputs/outputs.

Rendering uses a chart bitmap with anti-aliased primitives, clipping, and cached text measurement. Layout assigns node depth as one plus the maximum depth of its producers, found by matching outputs to inputs, excluding weights. Boxes are placed by rank, edges are labeled, and UI supports pan, zoom, and node inspection.

πŸ‘‰ Read | AppStore | @mql5dev
❀13πŸ‘9πŸ”₯3🀩3πŸ‘€2πŸ‘Œ1
Competitive Swarm Optimizer (CSO) is explored as a fix for classic PSO stagnation in parameter tuning: instead of pulling every particle toward a global best, agents compete in random pairs so only the loser updates, preserving diversity and delaying premature convergence.

The loser’s velocity blends inertia, attraction toward the paired winner, and a controlled pull toward the swarm centroid. The centroid is the only global reference; strong solutions propagate indirectly through repeated encounters rather than instant broadcast.

An MQL5 implementation is provided as a plug-in class for a unified test bench (Init/Moving/Revision), with practical details like zero-initialized velocities, per-axis velocity caps, boundary clamps, and Fisher–Yates pairing. Experiments on Hilly/Forest/Megacity across 5/25/500 dimensions evaluate solution quality under a fix...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀26🀩5πŸ‘4πŸ”₯4🀯2πŸ‘Œ2
Extralonger treats market time series and cross-asset structure as a single representation, avoiding the usual split between β€œtemporal” and β€œspatial” modeling. This drops complexity from exponential growth to quadratic, enabling faster training, lower memory use, and forecasts that extend from hours to multi-day or weekly horizons.

The architecture is a three-branch Transformer: a temporal route for long-range patterns via self-attention, a spatial route using global-plus-local attention to model cross-market dependencies, and a mixed route that fuses both into a unified signal.

On the MT5 side, the work ports these ideas to MQL5+OpenCL: a configurable temporal embedding layer (CNeuronTempEmbedding) that builds multi-period embeddings and concatenates them with inputs, plus a Global-Local Spatial Attention kernel that runs dense global heads and s...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘8πŸ”₯6🀩4πŸ‘Œ3