MQL5 Algo Trading
568K subscribers
4.26K photos
7 videos
4.27K 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
Serial autocorrelation can remain hidden behind a clean equity curve. Lag-1 checks are insufficient; dependence often shows up at higher lags or across a block of lags.

The Ljung-Box portmanteau test addresses this by aggregating sample autocorrelations through horizon h into a single Q statistic and chi-square p-value. Residual diagnostics matter: if ARIMA/GARCH residuals remain autocorrelated, the model is leaving structure unmodeled, and downstream stats assuming independence can be biased.

An MQL5 toolkit (no external deps) implements ACF, Ljung-Box Q, df adjustment, and p-values via the regularized incomplete gamma function (MQL5 lacks a chi-square CDF). Inputs support three data sources: closed-bar price returns, closing-deal P/L sequences, or external residual files, with guards for zero variance, invalid df, and malformed lag sets.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘14πŸ”₯6🀩6πŸ‘Œ2✍1
Maximum drawdown reports miss a key variable: time underwater. Two systems can share the same 15% max drawdown and still differ materially in recovery duration.

A dashboard script reconstructs an equity curve from closed deals by summing profit, swap, and commission per exit, sorting by deal time, then folding into a running balance.

A single-pass analyzer segments drawdowns into start, trough, and recovery, flags still-open episodes, and computes duration in calendar days. Summary stats report deepest depth, longest duration, average recovery time (closed only), and open count.

Output includes a CCanvas timeline with shaded drawdown bands and alternating-row labels, plus a terminal table sorted by duration so long shallow drawdowns surface first.

πŸ‘‰ Read | Signals | @mql5dev
❀26πŸ‘14πŸ”₯8🀩7πŸ‘Œ3😁2
Multi-symbol EAs that size trades from a correlation matrix often show unstable weights across adjacent rebalance windows. With N symbols and T bars, correlation estimates become dominated by sampling error when T is not much larger than N, even if market structure is unchanged.

Random Matrix Theory offers a practical filter. Using the Marchenko–Pastur upper edge with Q=T/N, eigenvalues at or below lambda_max are treated as noise; only eigenvalues above the edge are retained as signal.

A native MQL5 implementation can run without ALGLIB or DLLs by using a symmetric Jacobi eigendecomposition and a flat-buffer matrix class. Noise eigenvalues are replaced by their average to preserve the trace, then the cleaned matrix is reconstructed for downstream sizing.

A useful runtime check is Frobenius distance between consecutive windows: denoised matrices ty...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘24❀22🀩15πŸ”₯8πŸ‘Œ2
Many lot size calculators hardcode pip value assumptions that break on gold, indices, JPY crosses, and non-USD account currencies. A sizing routine should use the tick and volume properties the trade server publishes per symbol, then compute risk from those inputs.

CalcLots() takes risk in account currency plus entry and stop prices, then returns the trade volume and the actual risk after broker constraints. Volume is always rounded down to the volume step. If requested risk is below the minimum lot, the minimum is returned, clamped_min is set, and the higher real risk is reported. The function is direction-agnostic and also provides stop distance in points and point value per 1.00 lot.

The sizing math is isolated in Calc.mqh with no terminal state. It consumes a SymbolSpec struct and can be tested offline. SpecFromSymbol() is the only live-data bridge and...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀26πŸ‘15🀩15πŸ”₯9πŸ‘Œ3🀯2πŸ‘¨β€πŸ’»2
MetaTrader 5 strategy optimization typically relies on brute-force sweeps or the built-in genetic algorithm, but GA behavior varies with implementation details. The article builds an alternative optimizer around Particle Swarm Optimization, treating EA inputs as coordinates and iteratively updating particle positions using inertia plus attraction to each particle’s best state and the best state within its social group.

Because EA parameters are discrete, particle coordinates are rounded to configured steps. To avoid wasting passes on repeated parameter sets, each candidate point is hashed (CRC64 over the parameter bytes) and tracked in a binary search tree for fast β€œseen/not seen” checks.

The PSO core is decoupled from any EA via a Functor interface returning a user-selected trading metric, then validated against benchmark functions. For parallel t...

πŸ‘‰ Read | Docs | @mql5dev
❀52πŸ‘20πŸ”₯19🀩15πŸ‘Œ5πŸ‘¨β€πŸ’»5
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🀩7⚑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