MQL5 Algo Trading
581K subscribers
4.7K photos
7 videos
4.71K 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 new MT5 indicator adds TradingView-style chart navigation by handling mouse input via chart events and disabling the platform’s default left-button scroll. Candles can be dragged freely in both axes, with vertical panning implemented through a fixed price scale derived from the current visible range to avoid jumps.

The price scale supports stretch/compress by dragging, and price zoom is available via Shift+wheel over the chart or wheel over the price scale. Time zoom maps to MT5’s discrete bar zoom levels and can also be controlled by dragging the time axis.

AUTO and ON/OFF controls restore auto-fit scaling and toggle the behavior without affecting trades or drawings. Order/SL/TP lines and selected objects remain draggable, and removing the indicator restores prior chart settings. Single-file MQL5 code is structured as a reference for mouse events...

πŸ‘‰ Read | Signals | @mql5dev
❀23πŸ‘9πŸ”₯9🀩5🀯1
Prop firms often restrict trading minutes around high-impact news. Prop News Countdown reads the MT5 built-in economic calendar and renders a chart overlay with the next event and a live hh:mm:ss countdown, plus a configurable list of upcoming releases.

A β€œNEWS WINDOW NOW” state is shown from X minutes before to Y minutes after each event, matching firm rules. Optional features include vertical dotted lines at news time and alerts (pre-news and window start) via popup and MT5 mobile push. The indicator is display-only and never opens, closes, or modifies trades.

Filtering supports AUTO currencies from the chart symbol or an explicit list, with importance and look-ahead controls. Error handling flags missing/unsynced calendar data, warns on unknown currencies, and ignores all-day/tentative times for window logic. All timing uses trade-server time and ...

πŸ‘‰ Read | Signals | @mql5dev
❀11πŸ‘8πŸ‘Œ7🀩6πŸ”₯4⚑1πŸ‘¨β€πŸ’»1
VrDz Bot v1.23 is a lightweight EA that combines scalp and swing workflows behind a panel-based control surface. It focuses on manual execution support with automated position management rather than fixed entry signals.

Core risk controls include fixed-lot or risk-percent sizing, max-lot caps, margin checks, and spread/slippage filters. SL/TP can be configured as fixed points or ATR-based, with enforcement of broker minimum stop distance.

A one-click Scalp/Swing toggle rewrites SL/TP across open positions, disables scalp-only functions in Swing mode, and restores prior state when switching back. Partial close, break-even, and trailing stop are configurable and automatically disabled in Swing mode.

The β€œSecure All” layer runs in both modes, moving stop loss to lock in profit on winning positions while skipping losers. The panel exposes live RSI/ATR/spread/Pn...

πŸ‘‰ Read | Signals | @mql5dev
❀17πŸ‘7πŸ”₯3😁1🀩1
Spread is a major execution cost factor for scalpers, automated systems, and news-driven trading. Standard terminal charts show only the current instant spread, while intra-bar widening during rollovers, session transitions, and macro releases remains hidden.

The Spread Monitor indicator adds a subwindow view for MT4/MT5 that records live ticks and plots two curves per candle: Max Spread for the bar and Avg Spread across captured ticks. This makes spread behavior measurable instead of anecdotal when assessing execution quality and setting risk constraints.

Max Spread highlights peak spikes used to configure Max Spread Allowed filters for EAs. Avg Spread provides a practical baseline for real transaction costs. A dashboard displays current spread, active-bar average, active-bar maximum, and tick count.

Works on FX, metals, indices, and crypto CFDs, wi...

πŸ‘‰ Read | VPS | @mql5dev
❀19πŸ‘11🀩7πŸ”₯4
Event streams in markets are irregular and bursty, so fixed-interval models often miss the underlying dynamics. The article maps this problem to event-based vision and the E-STMFlow framework, which treats data as a continuous process driven by micro-events.

Core idea: a spatio-temporal state-space model maintains a compact hidden state and updates it per event using efficient linear transitions. This avoids heavy correlation tensors and reduces compute while preserving long-range structure.

For trading systems, the same design fits tick/order-flow feeds: fast online updates, noise-robust behavior from small parameter counts, and better tracking of latent factors (momentum, liquidity pressure) without forcing data onto an artificial time grid.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘9πŸ”₯8🀩4
MQL5 resource handling changes how MT5 systems get packaged and maintained. The key split is internal resources embedded into the executable versus external resources loaded from files at runtime.

Embedding allows shipping a single Expert Advisor that contains dependent assets, including indicators and data. This reduces failure modes caused by missing or deleted files and enables controlled configurability, including reset-by-reinstall workflows.

At compile time, a resource directive can read a file (for example a text file) and store its contents as a constant data block inside the EX5, effectively equivalent to a large in-code array.

For executable embedding, compiler path rules matter. Resource paths are resolved relative to the source file, while terminal loading uses sandbox-relative paths. With correct relative placement, compilation can also build th...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘14πŸ”₯13❀10🀩9
This article digs into a subtle MT5 behavior: graphical objects behave differently in the main chart versus indicator subwindows, especially when an indicator that β€œdraws in main window” is hosted inside another indicator’s subwindow.

A simple OBJ_CHART-based indicator is refactored into an OOP-friendly design, then embedded as a compiled resource inside a wrapper indicator. Even when the embedded indicator is shown in a subwindow, its OBJ_CHART can still appear in the main window, revealing that object placement depends on how MT5 resolves window context, not only where the indicator is listed.

The practical fix is to detect the actual subwindow index after the indicator is attached, then create objects using that resolved index, with proper cleanup and unique object naming to support multiple instances.

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘14🀩13πŸ”₯10❀7πŸ‘1
Part 5 moves eigenvalue-based risk concentration from a one-shot script into an MQL5 indicator. RiskConcentrationIndicator.mq5 plots the dominant eigenvalue as a percentage of total variance in a separate window, with blue bars below an alert level and red bars at or above it, updated per bar.

The calculation treats three instruments as an equally weighted, unit-exposure basket. It measures concentration in the covariance of the return series, not position sizing, contract multipliers, or currency exposure.

Core changes target live performance and data quality. A rolling prefix-sum engine keeps return sums, squares, and cross-products in persistent arrays, enabling O(1) window covariance via subtraction. Timestamp alignment uses iBarShift() exact matches; missing or asynchronous bars are excluded rather than zero-filled, with MinValidDataFraction gat...

πŸ‘‰ Read | Docs | @mql5dev
❀12πŸ‘12🀩8πŸ”₯7
Multi-position monitoring benefits from separating selected-position loss, stop-based estimates, and account-wide pressure.

A reusable MQL5 calculator is defined as a measurement layer for an existing EA. It builds a snapshot with explicit validity flags, quote freshness checks, and stop-estimate availability, then exposes selected_level and account_level with reason masks.

Measurements include net floating P/L plus swap, gross floating loss, two stop quantities (entry-to-stop loss and current-to-stop giveback), equity gap vs balance, margin level, and stop coverage. N/A is used when no stops exist; missing stops can optionally block new exposure.

OrderCalcProfit is used for stop estimation, with conservative diagnostics for stale ticks, missing properties, and crossed stops. The module does not trade; the host EA owns scheduling and responses.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀9πŸ‘8🀩5πŸ”₯4
Linear price charts distort percentage-based trends, making straight regression channels systematically misaligned. A log-price fit keeps constant-percent growth linear in the model, then renders the result back on a standard chart as a curve with adaptive banding.

The indicator re-evaluates only on bar close and selects its own look-back by testing 19 candidate windows and choosing the highest log-price correlation, with ties resolved toward the shorter window. Invalid windows (insufficient history or non-positive prices) are skipped.

Output includes a midline plus deviation-based edges that stay a fixed percentage from the trend, zone shading by distance from the midline, and a forward projection for 6–60 bars. A status card reports direction, best window, correlation grade, growth rate per calendar time, and live distance from the midline in devia...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘11❀5🀩4πŸ”₯2
A practical workflow for forecasting whether EURUSD will have an unusually large 08:00–16:00 session range, using only information available at 08:00. β€œLarge range” is defined relative to recent conditions: 25% above the mean range of the prior 20 valid target sessions.

A binary logistic regression is fit in SPSS on 2020–2023 data with two pre-session features: morning range relative to the historical scale, and the pre-session open-close move normalized by that range. The model is frozen and evaluated on a 2024 holdout.

Forecast quality is measured as probabilities, compared against constant and rolling-frequency baselines using Brier score, log loss, and calibration groups. The same probability math is reproduced in MQL5 with a numerically stable sigmoid, plus auditing rules to ensure sessions are valid and results are reproducible.

πŸ‘‰ Read | Forum | @mql5dev
❀10πŸ‘10πŸ”₯6🀩4πŸ‘¨β€πŸ’»2πŸŽ‰1
A free MT5 Risk/Reward Calculator script is available for position sizing and risk control. It calculates lot size from a defined risk percentage and stop-loss distance, then renders an on-chart dashboard to avoid manual math.

The panel shows computed lot size, monetary risk in account currency, stop loss, take profit, and the resulting risk-to-reward ratio. Calculation can be based on account balance or equity.

Instrument handling is automatic by reading tick value, tick size, and broker lot step, with support across FX, metals, indices, and crypto.

Inputs cover risk percentage, stop-loss and take-profit distances, balance vs equity selection, and basic display options such as panel position and colors. The script is informational only and does not place orders.

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘7❀6πŸ”₯3🀩2
TradingCostPlanner is an MQL5 Expert Advisor that estimates how much of an expected favorable move remains after spread. It uses the chart symbol’s live Bid/Ask plus an exit-spread assumption, producing scenario outputs in points, not profit, and excluding commission, swap, and slippage.

Two spread-only estimates are compared. One assumes the current spread at exit. The other uses the greater of the current spread and a percentile computed from recent tick-history samples. Both apply the planned midpoint move, where entry and exit each contribute half of their assumed spreads.

The EA validates inputs, checks volume against symbol constraints, rejects stale quotes, and refreshes tick history on a timer. A collapsible panel separates unavailable data from valid projections and shows execution readiness independently.

An optional Execute action can submit a mar...

πŸ‘‰ Read | CodeBase | @mql5dev
❀12πŸ‘10🀩5πŸ”₯4
Financial tick streams remain difficult to model with fixed-interval sampling. Event-driven architectures fit better when activity is irregular and noise dominates.

SDformerFlow combines spiking neurons with windowed attention, using shifted windows to limit attention cost while still capturing broader dependencies. Spikes trigger computation only on significant changes, reducing redundant work.

During an MQL5 port, the windowed layout and sparse activation mapped well to OpenCL parallelization. Encoder work centered on SDSA blocks and SPM patch-merge stages.

Current work moves to a U-shaped design with symmetric encoder/decoder flow. Instead of separate branches, a nested U-block is used to simplify tensor routing and maintenance. A new CNeuronSDformerUBlock encapsulates encoder, neck recursion, concatenation, and decoder, terminating in an MS-ResBlock...

πŸ‘‰ Read | Freelance | @mql5dev
❀12🀩6πŸ”₯5
COA tackles trading-system parameter tuning where brute-force search fails: a noisy, multimodal profit landscape that punishes single-swarm convergence.

Instead of one population collapsing to one point, COA splits candidates into mostly stable packs. Each pack follows its own alpha (local best) and a β€œculture” defined by the coordinate-wise median, which resists outliers and keeps exploration grounded.

Updates combine two pulls: toward the alpha and toward the median, using random pack members as references. Step size shrinks naturally as a pack tightens, and moves are accepted only when fitness improves.

Diversity is reinforced by per-pack pup generation: crossover between two parents with a low, dimension-scaled mutation rate. Rare inter-pack swaps spread successful traits without homogenizing the search, making it practical for robust MT5 optimizations.

πŸ‘‰ Read | Forum | @mql5dev
❀15πŸ‘10πŸ”₯6🀩4πŸ‘¨β€πŸ’»2
Perceptron training is moved from least-squares updates to gradient-based updates, keeping the same squared-error loss while changing how weights and bias are adjusted.

The gradient is treated as a vector: it indicates steepest increase; using the negative direction reduces loss. Implementation relies on partial derivatives for bias and each weight, rather than a secant-style update often confused with a tangent approach.

Code changes focus on accumulating per-sample error, computing a shared term for bias/weights, then scaling weight gradients by the corresponding input value. Bias uses a constant derivative of 1.

Training loops until the loss drops below a threshold, applying a learning rate and tracking the maximum component error to avoid premature stopping and uniform weight steps.

πŸ‘‰ Read | Calendar | @mql5dev
❀7🀩6πŸ‘5πŸ”₯5
Classic SuperTrend on MT5 is built on fixed ATR period and multiplier. When regime or volatility shifts, those constants produce narrow bands and whipsaws, or wide bands and delayed reversals. Manual retuning and one-shot optimizations both fail because parameters stay static while conditions change.

An adaptive design replaces constants with live calibration. A background probe matrix scores 5-bar outcomes, tracks MAE, and updates ATR period, multiplier, SL/TP with deadband control and EWM smoothing. A 2D regime grid (trend/sideways vs normalized volatility) stores decayed statistics per cell and returns stable 3x3 neighborhood recommendations.

Signal quality is gated by an accuracy layer: EMA8/EMA21 spread, ADX floor, Keltner squeeze block, candle body confirmation, plus a weighted confidence score. L1 regularization zeroes weak feature weights to ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀17🀩11πŸ”₯9πŸ‘5
Perceptron mechanics are often obscured by terminology. Forward propagation is the weighted sum plus bias followed by an activation function, producing an output passed to other units or exposed to callers.

Training adjusts weights and bias. With least squares on linear regression, the identity activation is the consistent choice; other activations change the problem definition. Test scaffolding can isolate training, logging, and convergence checks.

Learning rate remains the main stability control. Too high causes oscillation around minima; too low slows convergence. A max-iteration guard prevents non-terminating runs.

For gradient-based updates, the key addition is multiplying the backpropagated error term by the derivative of the activation function. This is the practical boundary between forward computation and backprop.

πŸ‘‰ Read | Signals | @mql5dev
πŸ”₯14❀12🀩7πŸ‘6
Trade refusals in MT5 often slip past logs, even after common β€œrulebook” checks. The article builds a drop-in preflight gate, CTradePreflight, that validates and optionally repairs trade requests before OrderSend(), with unit tests and a repeatable stress EA.

The pipeline separates broker-free rules (volume step/min/max, tick-size grid, stop/freeze constraints) from live-terminal checks (permissions, sessions, volume limits, margin) and finishes with OrderCheck(). Repairs round volume down without increasing risk, and can widen stops only when explicitly allowed. A ledger tracks every refusal reason.

A key finding: with tester execution delay, some requests still fail because price shifts between validation and server processing. A configurable delay buffer adds safety by requiring extra distance from market, trading fewer borderline orders to avoi...

πŸ‘‰ Read | VPS | @mql5dev
❀23🀩14πŸ”₯9πŸ‘6
A running CA with 10,000 MT5 agents hit two quality bottlenecks: 50 inputs treated as unrelated scalars, and a Moore lattice that spreads regime shifts slowly while connecting semantically unrelated cells. The upgrade targets only ExtractFeatures() plus neighbor selection and voting, keeping OnTick() fast and the EA interface unchanged.

Features become a 50-node graph: a lightweight diffusion step blends each feature with predefined semantic neighbors and a few small-world links. Implemented via index lists (no matrices, no training), this acts like a spectral filter that damps isolated indicator spikes and reinforces coherent multi-indicator structures.

Cells also move from pure geometry to a hybrid network: some local neighbors remain, but others are semantic (same feature group, similar strategy) plus long-range chords. Voting weights add a coherenc...

πŸ‘‰ Read | CodeBase | @mql5dev
❀14πŸ‘7🀩6πŸ”₯3
MetaTrader 5 ML workflows often end up with duplicated artifacts across dev machines and VPS instances. Centralizing models and feature snapshots in S3 is practical, but MQL5 has no AWS SDK and S3 requires SigV4 on every request.

A native SigV4 implementation can be built using only CryptEncode() and WebRequest(), avoiding DLL dependencies that are blocked in many sandboxed terminals. This still relies on WebRequest() allow-list and local TLS/network policy.

Scope is limited to PutObject, GetObject, and ListObjectsV2, implemented as three files: a signer (canonical request, manual HMAC-SHA256, signing-key derivation), an S3 client wrapper, and a script that uploads ONNX/CSV, downloads them back, and validates SHA-256 round trips. The signed headers set is minimal and excludes session tokens and service-specific headers.

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