MQL5 Algo Trading
574K subscribers
4.44K photos
7 videos
4.45K 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
MetaTrader derives TimeTradeServer() and TimeLocal() from the local Windows clock. When that clock drifts, any time-based logic in an EA drifts with it. Order expirations can trigger early or late, session/news filters shift, and end-of-week shutdown logic can miss the intended second. The terminal provides no warning.

A recent VPS case showed the Windows time service stopped and the clock ran 11 seconds slow. Limit orders configured to remain valid for 15 seconds were expiring after 4 seconds.

A script can measure this directly using tick timestamps. Each tick includes the server-stamped time with millisecond precision. The script compares that stamp to the local clock at tick arrival across 40 fresh ticks and uses the smallest non-negative gap, adjusted by half the current ping.

Run on an active symbol during open market hours. Output in Experts log and on...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀17πŸ‘13πŸ”₯6🀩3πŸ‘€2πŸ‘Œ1
Spiking neural networks fit event-driven financial ticks but break classic ResNet behavior. Binary activations destroy shortcut identity, causing unstable or vanishing gradients in deep SNN stacks.

SEW-ResNet restores depth by moving the shortcut outside spiking activation and combining paths with configurable element-wise functions, not only addition. This makes deep spiking residual models trainable and task-tunable.

Implementation work also targets GPU efficiency. OpenCL kernels for fully connected and convolution layers add zero-input checks to skip weight reads and multiplications, and restructure FC computation across work-items with local reductions.

Next step is SEW-style blocks integrated into a spiking ResNeXt bottleneck with dynamic module construction, supporting parallel feature paths for multi-scale market structure.

πŸ‘‰ Read | Forum | @mql5dev
❀26πŸ‘13πŸ”₯7πŸ‘Œ3πŸŽ‰1🀩1
Feature neutralization separates β€œreal” signal from hidden bets on volatility or trend. The approach regresses a raw trading signal on selected confounds in a rolling window, then trades the residual, making it linearly uncorrelated with those factors inside the fitted window.

A native MQL5 library implements rolling OLS with standardized factors and a Gauss-Jordan solver. It enforces minimum observations per parameter, hard-fails zero-variance factors, and tracks failed fits so an EA can avoid trading on stale coefficients.

The EA and indicator share the same engine and use strict bar handling (only closed bars, score-then-learn) to prevent lookahead. A Python companion validates numerical correctness against SVD-based least squares, stress-tests conditioning, and can replay backtests from CSV or MT5 data.

πŸ‘‰ Read | VPS | @mql5dev
❀12πŸ‘9πŸ”₯6🀩3✍1πŸ‘Œ1
This article shows a robustness check for MT5 backtests: vary the bar-opening grid and measure how indicators and trades change, even when using the same M1 history. For an M15 target, it enumerates all 15 integer-minute boundary offsets and runs an otherwise identical Strategy Tester pass per offset, focusing on dispersion rather than β€œbest” profitability.

Shifted M15 bars are rebuilt causally from completed M1 bars, with careful handling of startup warm-up, gaps (missing minutes), and end-of-test clipping where the final partial bucket may never publish. Controls isolate warm-up and common-end effects, and a validation series repeats all offsets using real ticks.

The deliverables include a reusable shifted-bar builder, an EA that profiles boundary sensitivity, a synthetic self-test for deterministic correctness, and an audit tool exporting gap and session...

πŸ‘‰ Read | Quotes | @mql5dev
❀12πŸ‘10πŸ”₯6🀩5πŸ‘Œ3
Single-symbol EAs often hardcode pip value, contract size, tick size, and min lot. In multi-asset portfolios (EURUSD, XAUUSD, US30, USDJPY), those assumptions fail and produce incorrect position sizing.

A robust approach is a runtime metadata layer fed by SymbolInfo* calls, deriving usable quantities such as account-currency tick value, tick-to-point scaling, and volume normalization (min/max/step with round-down). Tick value must be refreshed periodically because cross rates move.

The framework loads a symbol universe from an ANSI plain-text file, validates symbols via SymbolSelect and market watch, then centralizes specs in a registry struct with timestamps for staleness control. Agents consume registry data for lot limits and pip/point conversion, avoiding scattered SymbolInfo calls and preventing ERR_INVALID_VOLUME.

Known gaps include non-FX pip conven...

πŸ‘‰ Read | Calendar | @mql5dev
❀13πŸ‘13πŸ”₯6🀩6πŸ‘Œ1
Part 85 adds a visual review layer for a double-bottom validator so indices and statuses can be checked directly on the historical chart, without re-deriving structure. SHOW ON CHART navigates to the stored interval and draws the range boundary, L1/L2, neckline, outcome marker (breakout/failure), status, and score; INVALID results keep their explanation but are intentionally not drawn.

The renderer enforces context: symbol/timeframe must match, and chart history is verified against stored OHLC within tolerance. It pauses auto-scroll during review, uses a strict object-name prefix for safe cleanup, and restores scrolling on Clear(), leaving unrelated drawings untouched.

Panel and renderer stay separated: the panel retains the sample plus validation result, while the renderer owns chart objects, navigation, defensive contract checks, and error reporting. This cre...

πŸ‘‰ Read | Forum | @mql5dev
❀15πŸ‘12πŸ”₯4🀩4πŸ‘¨β€πŸ’»2πŸ‘Œ1πŸ†1
Prop firms often close accounts immediately when a daily loss cap is hit. A chart indicator can reduce manual tracking by calculating key thresholds directly from account history and current equity.

It displays the day’s starting balance, the equity level where the daily loss limit is reached, loss used so far in currency and as a percentage of the limit, and remaining room before violation. An optional line can show the maximum loss limit level. Panel colors shift from green to orange to red as risk increases, with one popup warning per day at a configurable level (80% by default).

Inputs include daily and maximum loss limits (percent), challenge starting balance, server-time day start hour, warning level, and panel position. The tool is read-only and does not place or manage orders. Daily definitions vary by firm, so settings should match the firm’...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘9❀3🀩3πŸ‘¨β€πŸ’»3πŸ‘Œ2
This article proposes an MT5 trading architecture where strategy logic evolves in production: 20 Grok-powered LLM agents run with different system prompts, and a genetic algorithm selects winners every 20 trades. The bottom 25% are removed, the top 25% are cloned with controlled prompt mutations, and a chart leaderboard tracks fitness.

Fitness avoids naive PnL ranking by using Sharpe Γ— sqrt(trades), with a minimum of 3 personal trades to reduce statistical noise. Agent selection blends exploitation (softmax roulette) with exploration (quota for under-tested mutants).

Implementation focuses on practical MT5 reliability: Grok is called via plain REST + requests (no SDK), JSON output is made unambiguous, EVOLVE is handled synchronously with socket locking to prevent corrupted replies, and MQL5 attributes results using DEAL_POSITION_ID. Backtest on EU...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘14❀5πŸ”₯5πŸ‘2🀩2πŸ‘Œ2
Session filters in EAs are defined in server time, and brokers use different time zones and DST rules. A fixed β€œ10:00–13:00” window only stays aligned with London or New York while the server offset stays stable, which fails during the US/EU DST gap weeks.

A clock-audit tool can infer the server offset from symbol history instead of relying on broker notes. The weekly FX/CME close is 17:00 America/New_York; comparing that instant (converted to UTC with US DST rules) to the last H1 bar before each weekend/holiday gap yields one offset measurement per week. Over ~60 weeks this produces a sequence that detects clock moves, dates the switch between closes, and classifies the regime as fixed, US, EU, mixed, or untested.

Output includes irregular closes (for example early US holiday metals closes), counts of Sunday bars (relevant for D1 candles), and projections ...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘9❀7πŸ”₯4🀩2πŸ‘Œ2
Indicator readings like determinism, persistence entropy, or time-reversal asymmetry remain uninterpretable without a null model that preserves the relevant structure. Bar shuffling is typically the wrong null for indicators because it destroys arrival order and autocorrelation.

Surrogate testing keeps amplitude distribution and/or power spectrum while removing higher-order structure. Four nulls are outlined: FT (linear Gaussian), AAFT and IAAFT (static monotone transform of a linear process), and BLOCK (stationary bootstrap with finite dependence length). Each null answers a different β€œby chance” question.

Implementation notes: spectral surrogates require FFT on arbitrary lengths, handled via Bluestein chirp-z to avoid zero padding or truncation. IAAFT stops on rank fixed points to ensure exact amplitude matching, leaving residual spectral error ...

πŸ‘‰ Read | Quotes | @mql5dev
❀19πŸ‘9🀩7πŸ”₯5πŸ‘Œ2πŸŽ‰1
Many funded challenges fail due to violations of the daily loss rule. DailyLossGuard automates enforcement by tracking daily P/L on every tick against a configured limit, based on a percentage of day-start balance or a fixed amount.

On breach, it can close all open positions immediately, trigger an alert and push notification, and display a persistent BREACHED status panel until the next trading day. A Magic Number filter allows protection for a single EA or the entire account.

A top-center dashboard shows daily P/L, limit, and ARMED/BREACHED state, with automatic recovery on timeframe changes and chart resizes. Intended for prop-firm and funded accounts, multi-EA setups, and manual trading requiring a strict daily stop.

Due to platform API constraints, it cannot prevent other EAs from sending new orders; it reacts by closing positions and notifying instan...

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘9🀩8❀7πŸ”₯5πŸ‘Œ2
Multi-timeframe dashboards often emit conflicting forecasts for the same price window. Weighted voting forces agreement but provides no error guarantee.

Forecast reconciliation treats coherence as a linear constraint. When targets are linearly related by construction, an orthogonal projection can enforce consistency without increasing total squared error under the chosen metric, given a coherent truth.

An MQL5 implementation builds a summing matrix for two cases: timeframe aggregation on one symbol, and cross-currency identities in log space. Independent models per node are reconciled into a coherent set.

Weighting matters. Options range from identity and structural diagonals to MinT covariance-based schemes with correlation shrinkage. Walk-forward tests measure squared error only; results do not imply a trading edge.

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘19❀8πŸ”₯8🀩7πŸ‘¨β€πŸ’»2πŸ‘Œ1
A script exports the full trading specification for each symbol into a CSV file.

The output includes digits, point, tick size/value, volume min/max/step, contract size, stops and freeze levels, current spread, spread type (floating or fixed), allowed filling modes, execution mode, trade mode, initial margin, swap long/short, and profit currency.

These parameters commonly change between brokers or instruments and can cause Expert Advisors to fail without clear errors. Volume step, filling mode, and stops level are frequent sources of silent order rejections. A one-time export makes incompatibilities visible before placing the first trade.

Inputs cover Market Watch only or all broker symbols, optional use of the common Files folder, and a configurable file name (empty for automatic naming). Symbols not in Market Watch are added temporarily for reading, t...

πŸ‘‰ Read | Signals | @mql5dev
❀12πŸ‘11πŸ”₯8🀩6⚑2πŸ‘Œ2
Manual Trade Pad for MT5 is a chart-based manual trading panel built as an MQL5 EA for order execution and basic position management directly from the terminal. It runs in two modes: Live Market for manual trading, and Strategy Tester for manual historical testing and workflow practice. No external DLLs, libraries, indicators, or custom GUI frameworks are required.

Core functions include BUY/SELL market orders with automatic Stop Loss and optional Take Profit based on a configurable Risk/Reward ratio. Position sizing supports fixed lot input or risk-percentage sizing, with volume normalized to broker constraints and validated against symbol stop-level rules.

Trade management covers Break-Even with offset, partial close with step/min volume checks, and closing by direction (BUY, SELL, or all managed). Scope is limited to the chart symbol and a configured Magic Nu...

πŸ‘‰ Read | Docs | @mql5dev
❀24πŸ‘11🀩8πŸ”₯4πŸ‘Œ2πŸ‘€2
AI agents and other automated systems execute trades at machine speed, while platform safety settings can miss operational errors. AgentGuard adds an independent risk layer by polling all open positions every five seconds and enforcing four hard limits.

Controls include maximum total volume, maximum position count, mandatory stop-loss on every position, and a daily-loss circuit breaker that closes all positions and remains locked until the next trading day.

The tool operates alongside any EA, manual trading, or AI agent. It evaluates compliance only, regardless of how a position was opened. A status panel and intervention alerts provide visibility, with a monitor-only mode for calibration. No DLLs. Free. Risk management only; no signal generation.

πŸ‘‰ Read | VPS | @mql5dev
❀18πŸ”₯11πŸ‘9🀩4πŸ‘Œ2
Broker Basket Preflight is a standalone MT5 script intended to verify a broker’s multi-symbol setup before portfolio EA work. It reads the exact symbols currently selected in Market Watch and writes a diagnostic report to the Experts journal. The source includes an MIT license and relies on no external libraries, DLLs, or network calls.

The script is installed by copying BrokerBasketPreflight.mq5 into MQL5/Scripts, compiling, then running it from a separate chart. InpSymbols can be left empty to test the chart symbol, or set to a 1–64 entry comma-separated basket using broker-exact names. Unknown, unselected, empty, and duplicate entries are skipped independently.

Output covers symbol specification and quote integrity: contract size, volume limits/step, point/tick sizes, digits, stops/freeze distances, calc/trade modes, execution and filling policies, p...

πŸ‘‰ Read | Forum | @mql5dev
❀19πŸ‘13🀩5πŸ”₯2
Portfolio Allocation Planner is a free open-source MT5 utility for checking whether target weights are feasible under broker minimum lots. It converts an explicit notional budget and percentage weights into a dashboard showing minimum-lot notional, lots rounded down, resulting allocation, target shortfall, and per-row status. Snapshots can be recalculated on demand, inspected via hover details, paginated for larger baskets, and optionally exported to CSV.

Setup: copy PortfolioAllocationPlanner.mq5 to MQL5/Experts, compile, select exact broker symbols in Market Watch, then attach to a separate chart. Configure InpBudget, InpBudgetCurrency, InpSymbols, and matching InpWeightsPct (not normalized; total > 0 and <= 100). It is an interface EA with no trading; no account data is read and no orders are sent.

Notional is computed as Ask Γ— contract size with explici...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀19πŸ‘11🀩9πŸ”₯4
SEW ResNet concepts were implemented for MQL5 time-series work using a spiking ResNeXt baseline with energy-balanced learning. The design targets bursty market streams by using discrete spikes, adaptive thresholds, and gating to reduce sensitivity to noise while staying responsive under volatility.

Core modules include Spike ResNeXt Bottleneck and Spike ResNeXt Residual blocks, assembled via programmatic layer creation with convolution, normalization, spiking activation, and grouped convolutions. A zero-input check skips compute during low-activity intervals.

To capture cross-feature dependencies, a second Bottleneck operates on a transposed tensor per time step, while residual usage is limited to avoid over-amplification. Multi-stream fusion avoids element-wise multiplication due to blocked gradients; normalized summation plus spiking activation ...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ”₯10πŸ‘9❀8🀩2
Part V adds persistence to the Supply/Demand Zone Manager so zone state survives EA or terminal restarts per symbol+timeframe.

A plain-data snapshot (SZonePersist) stores identity, geometry/timing, scores/telemetry, lifecycle flags, interaction history, and user anchors. Runtime behavior stays in CZone; persistence only captures durable state.

Startup flow restores saved properties, rebuilds CZone instances from records, runs existing relevance checks, then reconciles chart rectangles. User zones restore left anchor and price bounds; right edge remains framework-managed and extends at runtime.

Persistence uses Terminal\Common\Files\DynamicSR\V5 with filenames derived from symbol+timeframe. Changes mark a dirty flag; SavePersistState writes snapshots via CZonePersistence.

Scope note: restart-safe only. No atomic writes, checksums, or crash-safe transact...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀16πŸ‘11🀩7πŸ”₯6
Part 86 extends the double-bottom pattern tool with library-wide validation. A new VALIDATE ALL action reuses the existing ValidateDoubleBottom() rule engine to classify every stored sample into INVALID, CANDIDATE, CONFIRMED, or FAILED, while keeping single-sample validation and chart rendering separate for accurate visual review.

The batch run works on stored candle arrays (symbol/timeframe included), supports non-consecutive sample IDs, and produces a consolidated UTF-8 CSV without modifying original SAMPLE_<ID>.csv files. The report embeds totals, validator settings, schema/revision metadata, and one detailed row per sample (indices, prices, score, reason), preserving 17-digit floating-point precision.

Export adds defensive engineering: per-run filenames, temp-file write + byte-for-byte readback verification, explicit status accounting, and error diagnos...

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘11❀10🀩4πŸ”₯2😁1
This article implements Variational Mode Decomposition (VMD) for MetaTrader 5 as a rigorously causal tool, not a hindsight-heavy chart smoother. It contrasts VMD with MAs, FFT, and EMD, then frames VMD as an explicit optimization solved by ADMM: K modes that sum to price, each constrained to be narrowband around an estimated center frequency.

Key engineering details: FFT is done once in/out of the loop; ADMM updates are closed-form Wiener filters in the frequency domain; windows are mirrored to reduce boundary discontinuities; analytic-signal handling is implemented correctly; log-prices and mean removal prevent the DC spike from corrupting modes; rolling buffers keep memory small enough for per-bar execution.

The indicator plots a denoised signal, trend mode, and a β€œrandom wander” band, plus per-mode periods, energy shares, and solve-quality flags. Cruci...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘10❀8πŸ”₯6πŸŽ‰2🀩2