MQL5 Algo Trading
541K subscribers
3.88K photos
6 videos
3.88K 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
Classical moving averages compress a window into one value and miss where the latest close sits within its own recent distribution. Bloch’s RMA ranks the current price inside a sliding window and outputs a fractile on a consistent [0,1] scale across instruments. This differs from Wilder-style “RMA” smoothing despite the shared acronym.

An MT5 port is structured as an engine indicator publishing multi-buffer outputs under a strict buffer-index contract, plus read-only panels and an EA. Core code computes SMA as local equilibrium, normalized deviations for window landmarks, then empirical fractiles for the current close and extremes.

A regime detector uses the window’s normalized-return range to classify expansion, contraction, and transition, feeding four cross-strategies implemented in the EA and validated in Strategy Tester.

👉 Read | Docs | @mql5dev
17👍92
MT5 EA Acceptance Harness is an MQL5 script that validates a bounded entry-state contract using deterministic synthetic fixtures. Eight scenarios are executed: valid closed-bar entry, duplicate signal bar, open-bar rejection, cooldown rejection, cooldown elapsed, no signal, daily lock, and new-day reset.

The report compares expected versus actual decisions and outputs a final pass/fail count. Optional outputs include writing a text report to the terminal Common\Files folder and printing results to the Experts log. The report file name is configurable.

The harness is isolated by design. It uses only synthetic case data, does not read market or account state, and never sends, modifies, or closes orders. Coverage is limited to the included state-transition examples and does not assess strategy quality, execution, profitability, or live-account behavior. Source...

👉 Read | Forum | @mql5dev
12👍5
A Kolmogorov-Arnold Network (KAN) is implemented in MQL5 as an interpretable next-bar predictor: instead of scalar weights and fixed activations, each connection learns a univariate curve. Those edge functions are modeled with cubic B-splines (De Boor–Cox recursion), making each edge linear in its coefficients.

Training becomes a deterministic ridge-regularized least-squares solve via Cholesky factorization, avoiding learning-rate tuning and gradient failures. The library is validated with unit tests (partition of unity, exact linear reproduction, fitting known functions, save/load roundtrip).

A shared feature pipeline converts bars into four normalized inputs (return, RSI, ATR/price, MA slope). The trained model runs as an indicator that plots both predictions and the learned curves, and as an EA tested out-of-sample with modest profit and contro...

👉 Read | AlgoBook | @mql5dev
17👍4👨‍💻3
Black–Scholes assumptions remain a weak fit for real markets: returns show fat tails, self-similarity across timeframes, and volatility clustering. These effects break independence assumptions and distort historical volatility estimates when news-driven outliers are included.

EA changes for long-option structures: add level-based expiration with a switch and an integer target level. When the rebalancing level reaches the specified number, positions are closed and trading pauses until the next day, subject to liquidity constraints in live venues.

Historical volatility is recalculated adaptively by selecting a window (3–40 days) that minimizes median absolute error versus realized daily ranges, using medians to suppress tail impact.

Written-option risk is capped by adding long wings, forming Short Straddle/Strangle Butterfly variants. Extra strikes and norma...

👉 Read | Signals | @mql5dev
26👍9
LightGTS forecasting is extended into a practical MT5/OpenCL pipeline by turning periodic patching into GPU-generated tokens. Dominant periods are detected via FFT, then each series is split into a fixed token count; patch length follows the current cycle while overlap preserves full coverage without dynamic allocation.

Instead of recomputing projection weights with a pseudoinverse when window sizes shift, a maximum-size weight matrix is kept and unused taps are masked via zero padding. This keeps memory layout stable while adapting to drifting market periodicity.

Three OpenCL kernels complete training: forward adaptive convolution per token, input-gradient accumulation that handles overlapping patches, and an Adam-based weight update over window/filter/channel dimensions. Result: frequency-aware embeddings suitable for Transformer blocks with predic...

👉 Read | Freelance | @mql5dev
17👍123
False breakouts often hit stops placed at obvious support or resistance. This is amplified by crowding: many traders see the same levels, and liquidity is concentrated around them.

A proposed approach overlays a prime-number density heat map onto price. Prices are converted to integers via a multiplier, then prime counts are computed within a radius using a cached Sieve of Eratosthenes. High density zones are marked blue, low density zones red.

Backtests over five months across FX, crypto, and commodities reported 55–58% alignment between blue zones and reversals versus a ~35% random baseline, with similar behavior across instruments. The tool is positioned as a context filter, not a standalone signal generator.

👉 Read | VPS | @mql5dev
24👍5
CPortfolioAnalyzer is extended beyond basic equity and correlation views to address multi-EA risk visibility and operational controls. Key additions include a strategy-level Drawdown Timeline Heatmap that logs peak-to-exit drawdowns per trade, plus a monitoring loop that enforces user thresholds without blocking the terminal UI.

A mitigation engine adds escalating actions: close positions and delete pending orders, persist strategy blocks via terminal Global Variables, or disable terminal AutoTrading through Windows API messaging. Export is upgraded with detailed CSV plus a styled multi-worksheet Excel XML workbook written directly from MQL5.

A hybrid MQL5-Python pipeline bypasses WebRequest sandbox limits by generating a temp CSV and a standard-library Python script, executing asynchronously via ShellExecuteW, and polling results on OnTimer. Retur...

👉 Read | AlgoBook | @mql5dev
18👍8
A new MT4 support/resistance indicator is available, based on swing-pivot detection rather than highest/lowest-over-N-bars. Nearby pivots are clustered into zones and ranked by verified touch count, shown directly on-chart (for example, “x8”) to distinguish frequently tested levels from recent ones.

Chart readability is handled with adaptive zone thickness to prevent overlap across timeframes, plus a distance-based filter that hides zones far from current price. An optional higher-timeframe overlay can display longer-period zones in a separate color and is automatically skipped when it would duplicate the active timeframe.

Proximity alerts are included (pop-up and sound) with a cooldown to reduce repeated triggers. Full source is provided. For information purposes only; no trade execution or management is performed.

👉 Read | AppStore | @mql5dev
24👍6👨‍💻2👀1
Rolling Return Autocorrelation Regime Oscillator reframes autocorrelation for live regime monitoring. Instead of plotting correlation by lag once, it fixes a lag (often 1) and recalculates Pearson autocorrelation each bar over a rolling window of returns, producing an oscillator-like series.

Positive values indicate statistically meaningful return persistence at that lag, which tends to align with trend-following conditions. Negative values indicate serial reversal, which tends to align with mean reversion and range behavior. Readings inside the significance bands suggest no reliable dependence for the chosen window and lag.

Significance bands are computed dynamically at ±Z/√N to separate signal from sampling noise. A raw per-bar estimate is shown alongside an EMA-smoothed line; the smoothed line is the practical regime filter, while the raw line hig...

👉 Read | Quotes | @mql5dev
13👍10🏆1
Order Block Mitigation Tracker focuses on what happens after an order block is drawn. Zones are treated as time-sensitive: once price trades back into the area, the block is marked as mitigated, the rectangle fades, and the exact mitigation bar is annotated. This makes “fresh vs already used” visible without relying on identical static boxes.

Detection uses an ATR-based impulse filter. On each closed candle, body size is compared to ATR times a configurable multiplier. A qualifying impulse confirms the prior opposite-color candle as the order block, keeping signals tied to displacement rather than minor swings.

Mitigation can be defined by wick touch or candle close. Active blocks can extend forward; mitigated blocks can remain on chart for a fixed bar count. Key inputs include lookback bars, ATR period, impulse multiplier, max tracked blocks, and re...

👉 Read | Freelance | @mql5dev
👍12112
The main highlight of MetaTrader 5 build 6140 is the expanded capabilities of the AI Assistant. We have added support for a wide range of new LLM providers, including Alibaba, Atomic Chat, Bitdeer AI, Cerebras, and others. You can now choose from an even broader choice of models and pick the one best suited to a particular task — market analysis, coding, or developing trading applications.

We have also optimized MCP Tools and added the ability to stop the Strategy Tester directly through an AI agent.

Another major focus of the update is the web terminal. We have improved chart scaling and controls, refined mouse interaction and symbol switching, and fixed issues with the Depth of Market. These changes make working with charts more accurate and convenient, especially when actively analyzing the market.

Read more...
👍147🔥21
A dynamic trend channel for MT5 can avoid the common weakness of fixed-level indicators by sizing its boundaries with volatility. This design builds a trend-following channel from True Range, then stabilizes ATR with two smoothing stages: Wilder’s RMA followed by an SMA, producing an adaptive width used to expand or contract with market conditions.

Channel levels are computed per bar from average highs/lows over a lookback window plus/minus the final ATR value. Trend state is derived from price interaction with these boundaries, while a trailing trend line switches between upper and lower levels to track direction.

On the chart, the indicator combines a filled region (trend line vs. HL2 midpoint), trend-colored candles, and arrows only when bullish/bearish transitions are confirmed—useful for clearer discretionary analysis and as a foundation for aut...

👉 Read | AlgoBook | @mql5dev
29👍81👏1
Machine learning expanded retail signal generation, but by the early 2010s automated mining increased low-value, short-lived alphas. Scale created noise, limited explainability, and weak audit trails.

In 2016, Zura Kakushadze proposed formulaic alphas: trading signals expressed as algebraic formulas that can be parsed, ranked, neutralized, and combined into a single aggregate signal, without embedding them into a full execution strategy.

A basic example is (close-open)/(high-low+0.001), producing a signed momentum score. The framework defines an expression language: operators, time-series transforms, cross-sectional rank, and group neutralization over inputs like OHLCV, returns, VWAP, cap, and ADV.

For evaluation at scale, backtests mix alpha quality with execution choices. Information Coefficient (Pearson correlation between alpha scores and forwar...

👉 Read | AppStore | @mql5dev
20👍4
Bonobo Optimizer (BO) is a population-based optimization method published in 2021 by Amit Kumar Das and Dilip Kumar Pratihar. Each individual represents a candidate solution, with an alpha individual tracking the current best.

Core mechanics use fission-fusion subgroups and three update strategies: randomized mating toward alpha plus a subgroup partner (scab/scsb may exceed 1), low-probability extra-group mating using boundary extremes with heavy-tailed beta coefficients, and consortship mating with a direction flag based on relative fitness and exp(-rand) decay.

Selection applies a strict acceptance rule: always accept improvements, otherwise accept with small probability to retain diversity. Parameters adapt via positive/negative phases, shifting subgroup size, randomized mating rate, and extra-group probability.

A reference implementation (C_AO_B...

👉 Read | Quotes | @mql5dev
17👍5👏2
LightGTS tokenizes time series by FFT-based period patching, then applies flexible projection to handle variable-length cycles. Transformer Encoder blocks consume these tokens, and Periodical Parallel Decoding emits the forecast in one pass, with a resize stage preserving periodic consistency.

Rotary Positional Encoding replaces additive position vectors by rotating Q/K coordinate pairs. It is parameter-free, requires even embedding size, and improves relative shift handling under variable windowing.

An OpenCL RoPE implementation maps work-items over (D/2, tokens, variables), uses float2 pairs, precomputed sin/cos tables, and minimizes global reads. A backward kernel applies the inverse rotation to propagate gradients.

In MQL5, a CNeuronRoPE wrapper validates even dimensions, builds a cos/sin matrix once on CPU, and queues forward/backward kernels. Encoder...

👉 Read | VPS | @mql5dev
👍98🏆2
The project evolves from a basic FastAPI + Jinja2 MT5 process controller into a terminal manager that can surface live trading-account metrics in the UI. Hard-coded terminal paths are replaced by startup-selectable configuration, preparing the app for real deployments with many instances.

A new endpoint (/instances/{name}) returns per-terminal status as JSON, with request handlers organized into a dedicated controller class. The UI is refined using Bootstrap and jQuery, enabling simple periodic polling to refresh terminal data without manual page reloads.

Account and terminal characteristics are read via the MetaTrader5 Python library by connecting to a specific terminal executable (portable mode), using a short initialize() timeout to avoid blocking on disconnected terminals, then querying terminal_info(), account_info(), and last_error() before ...

👉 Read | VPS | @mql5dev
👍106
SuperTrend is a volatility-band indicator rendered as a single line that flips sides by trend. It combines ATR with a ratchet that preserves prior band state, so each bar depends on the stored state of the previous bar.

Most “repainting” reports are state-management faults: closed bars changing due to broken recursion, series/normal indexing mismatches, or buffer history being reset. In MT5 this is amplified by call-based execution, so recursive state must persist across calls.

A robust approach uses calculation buffers (sUp, sDn, sTrend) instead of manually resized arrays, creates the ATR handle once in OnInit, and copies ATR data defensively. Live updates typically reprocess only the forming bar and the last closed bar.

Arrows should be delayed until reversals are no longer at risk of being invalidated by the next ticks.

👉 Read | CodeBase | @mql5dev
20👍5
MetaTrader 5 positions are isolated, which makes basket-level risk control awkward when trades are correlated. The article solves this with CBasketManager: positions are grouped by a basket ID stored in POSITION_COMMENT using a simple “BASKET:ID” convention, enabling basket-wide P&L tracking and coordinated exits.

The design separates concerns cleanly: a scanner aggregates state into a single CBasketInfo snapshot (sum P&L, long/short volume, volume-weighted pips, distance to stop), an executor handles order sends and closes legs safely in reverse order, and a stop registry enforces a unified equity threshold via a callback so risk logic stays decoupled from execution.

Practical details target real brokers: filling mode is resolved from SYMBOL_FILLING_MODE to avoid common retcode failures, symbols like gold are configurable and selected early to ensure prope...

👉 Read | VPS | @mql5dev
15👍4
Broker Execution Diagnostics MT5 is a read-only script that reports symbol constraints commonly linked to invalid volume, invalid stops, and inconsistent risk calculations.

Output includes digits, point, tick size, tick value, current spread (points), min/max/step volume, and a conservative normalized volume for a requested size. It also reports stops and freeze levels in points and price distance, plus trade mode and execution mode values. Optional checks cover entry-to-Stop-Loss distance and an OrderCalcProfit estimate in account currency.

Inputs: InpRequestedVolume for normalization, optional InpEntryPrice and InpStopLossPrice for distance and P/L checks, plus InpShowOnChart to print the report on-chart.

Usage: compile in MetaEditor, attach to the target symbol, and read results in Experts log or chart comment. No orders are sent or modified. Sui...

👉 Read | Forum | @mql5dev
11👍61
Session Sweep Reversal Detector flags intraday reversals around completed session boundaries. It plots the finished session high/low as forward reference lines, then monitors post-session price action for a liquidity sweep.

A sweep requires price to breach the frozen high/low by more than a configurable buffer, then close back inside the range within a limited number of bars. Breaches that fail to reverse in time are treated as breakouts and ignored.

Signals are shown as arrows: bullish when the session low is swept and price closes back above it, bearish when the session high is swept and price closes back below it. Key inputs include session start/end hours, sweep buffer in pips, reversal bar limit, and the number of prior sessions displayed. Most relevant on M5–M30, commonly aligned to London or New York hours on major FX pairs.

👉 Read | VPS | @mql5dev
23👍5👨‍💻2
Trade Transaction Trace Logger is a read-only MT5 Expert Advisor designed to diagnose the lifecycle of orders, deals, and positions. It records OnTradeTransaction events in arrival order to a local CSV file and can optionally mirror a compact line to the Experts Journal.

Captured fields include a monotonic event sequence with server time, transaction type, symbol, resolved magic number, and order/deal/position tickets. It also logs order type and state, deal type, price, trigger, SL/TP, volume, plus request action and server retcode/comment. If an event lacks context, the core attempts resolution via request data, live orders, order history, deal history, or current positions.

Configuration covers symbol scope (chart or all), magic filtering (-1 or exact), CSV filename, Common Files storage, and Journal printing. The module sends no trade requests, uses no DLL/W...

👉 Read | AppStore | @mql5dev
14👍8👌1