MQL5 Algo Trading
503K subscribers
3.28K photos
2 videos
3.28K 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
The article outlines two non-standard money-management techniques aimed at improving exit quality and stabilizing performance in MetaTrader systems.

First, it proposes partial position closing driven by the previous bar’s impulse size. A power function maps last-bar movement (in points) to the volume to close, with parameters chosen so developers tune behavior via intuitive anchors rather than raw coefficients. The goal is to harvest rollbacks after strong candles and reduce spread impact when the final exit is uncertain.

Second, it describes a hybrid lot-variation model combining martingale and reverse-martingale logic based on equity “waves.” Lots are increased during drawdown phases and reduced during recovery, constrained within a min/max corridor and pulled back toward the midpoint to avoid sticking at extremes. Practical value depends on markets domin...

👉 Read | Forum | @mql5dev

#MQL5 #MT5 #EA
45👌6👍5
Панель «Калькулятор корреляции» представляет собой индикатор в формате таблицы для оценки взаимосвязей валютных пар и выбора точек входа без дополнительного набора инструментов. Подход ориентирован в первую очередь на кросс-курсы.

При закреплении панели на графике EURJPY сравниваются EURUSD и USDJPY. Если в таблице выше находится EURUSD, кросс, как правило, повторяет его движение. Если выше USDJPY, кросс чаще следует за этой парой. Сигналом считается момент, когда основные пары меняются местами в таблице, после чего открывается сделка по кроссу.

Рекомендуемые параметры: таймфрейм H4, глубина расчета 10 баров. Наиболее подходящие кроссы: GBPCHF, EURCHF, GBPCAD, EURCAD, AUDCHF, AUDJPY, EURJPY, GBPJPY, NZDJPY, NZDCHF. Такие кроссы формируются из валют с прямыми и обратными котировками и обычно повторяют динамику одной из базовых пар.

👉 Read | Freelance | @mql5dev

#MQL4 #MT4 #Indicator
286👌2🤡2
DoEasy’s next step toward Depth of Market in MT5 starts by modeling a single DOM entry as a first-class library object fed by MarketBookGet() on OnBookEvent() updates.

The article implements an abstract DOM order class backed by MqlBookInfo fields (type, price, volume, volume with extended precision) and adds an explicit side flag (Buy/Sell) to quickly split demand vs supply regardless of market/limit type.

Four derived classes represent the concrete book types (buy, buy market, sell, sell market), while the base class provides property enums, sorting criteria, full/partial comparison, and structured logging.

A test EA subscribes to book events, snapshots the book into a price-sorted list, and validates handling by printing the best bid/ask and dumping the first snapshot to the journal.

👉 Read | Forum | @mql5dev

#MQL5 #MT5 #AlgoTrading
63👍6👌4🏆4
An updated Rex indicator variant is available with an added Donchian-style channel layer. The channel is calculated from recent period highs and lows and plotted around the Rex output to provide a volatility-based envelope.

This extension is intended to help flag potential overbought and oversold conditions when values approach or exceed the channel boundaries. Persistent compression inside the channel can be treated as a possible ranging or low-momentum zone.

Usage remains consistent with standard Rex workflows, with the channel serving as an additional context filter rather than a standalone signal.

👉 Read | AlgoBook | @mql5dev

#MQL5 #MT5 #Indicator
242👌2👀2
CFTC COT and TFF reports remain underused inputs for FX modeling. They aggregate futures positioning by participant type and expose shifts in institutional risk, with TFF separating leveraged funds, asset managers, and dealers.

A practical workflow merges weekly positioning with MT5 quotes and derived features such as volatility, moving averages, and position deltas. Python tooling typically relies on requests plus pandas for report ingestion, local caching to reduce reload time, and MT5 APIs for historical bars.

Model output targets a 24h return estimate and can drive automated execution in MetaTrader 5 via rule gates on forecast magnitude and confidence. Key constraints include Tuesday-as-of data, Friday release latency, and evolving behavior from systematic strategies using the same reports.

👉 Read | Forum | @mql5dev

#MQL5 #MT5 #AlgoTrading
24👍32👌2
Single backtest equity is path-dependent. The same trade set can produce materially different drawdowns when reordered, including margin-call outcomes despite positive expectancy.

MonteCarlo_RiskAssessor.mq5 runs 1000 bootstrap resamples of historical trade P&L from trades.csv, building synthetic equity curves from the same outcomes. Output includes a 5/25/50/75/95 percentile fan chart via CCanvas plus CSV export of percentile curves and summary metrics.

Key metrics: median max drawdown, 95th-percentile stress drawdown, 5% VaR on final equity, and probability of breaching a configurable ruin threshold. Optional execution stress applies per-trade commission and conservative slippage.

Operational notes: script mode (OnStart), reads from MQL5\Files, supports single-column P&L or date+P&L, and typically needs profit-column remap for Strategy Tester ex...

👉 Read | CodeBase | @mql5dev

#MQL5 #MT5 #AlgoTrading
296👌3👍2
The article walks through a practical MT5 + Python workflow that keeps research and execution connected: pull market data from the terminal, validate it visually, test statistical ideas, then move toward deployable models.

Setup focuses on reproducibility: isolate dependencies with venv, point MetaEditor to the virtual-env interpreter, and use a standard data stack (NumPy, Pandas, Matplotlib/Seaborn, scikit-learn, TA). Time handling is treated as critical engineering: MT5 timestamps are UTC, so Python datetime must be explicitly UTC to avoid silent bias.

On data and hypotheses, it shows how to request H1 EURUSD history, plot price with volume cleanly, then quantify “trend continuation” using shifted returns and Pearson correlation. Results reject bar-to-bar momentum and reveal weak, structured mean reversion when averaging over mid-size windows, motivat...

👉 Read | Signals | @mql5dev

#MQL5 #MT5 #Python
56👍8👌4🏆32
Most retail algos still hardcode lookback periods such as RSI(14) or MA(20). This assumes cycle length is constant. In live markets the dominant cycle contracts or expands with liquidity and regime changes, so static windows create phase lag and systematic late entries.

A DSP approach replaces fixed periods with cycle estimation via a rolling Discrete Fourier Transform. The scan measures amplitudes across frequencies, isolates the dominant component, and keeps its phase aligned with current price action. Peaks and troughs are identified by the extracted wave rather than by delayed crossovers.

Implementation details matter. Naive DFT is CPU heavy, so practical engines rely on tight loops and array-level memory handling to keep latency low. The extracted dominant frequency can then be fed back into an EA to adapt indicator periods dynamically and re...

👉 Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
405👌43👍3
Algorithmic trading systems need fast feedback loops. With higher trade frequency, data becomes stale quickly, and manual journaling adds latency and errors.

MetaTrader 5 ships with native SQLite support, turning the journal into an in-terminal component. Queries run in milliseconds, stats update automatically, and analysis stays next to execution.

A practical “minimum working set” is a three-table schema: DEALS (trade history), SIGNALS (indicator/system signals), EVENTS (macroeconomic context). Indexed fields like symbol, magic, and time keep analytics responsive.

In MQL5, DatabaseOpen/Execute/Close covers most use cases. Prepared statements plus transactions materially improve throughput and reduce risk versus ad-hoc SQL or spreadsheet pipelines.

👉 Read | Quotes | @mql5dev

#MQL5 #MT5 #AlgoTrading
51👍12👌4👀43🔥3🤝3
The December 2020 issue of TASC featured John Ehlers’ MyRsi with Noise Elimination Technology (NET). The design applies a Kendall-style autocorrelation approach to reduce noise and suppress low-quality RSI swings.

This variant allows selecting the input price series instead of relying on a fixed close, enabling alignment with different data conventions such as typical price or weighted close.

Operationally it can be treated like a standard RSI, with the added NET line as a second confirmation layer. In comparative chart reviews, the NET line often reacts earlier while keeping fewer false transitions, which can improve signal clarity when combined with traditional RSI thresholds.

👉 Read | AlgoBook | @mql5dev

#MQL4 #MT4 #Indicator
332👍2🎉2👌2🤔1
Moving MQL5 workloads from CPU to GPU with OpenCL only pays off when the problem is naturally parallel and executed in large batches. Otherwise, kernel launch, data transfers, and synchronization overhead can erase any gains and add architectural complexity.

A disciplined OpenCL setup matters: create and reuse the context, compile kernels once, reuse buffers, and avoid frequent CPUGPU exchanges. GPU performance is often limited by memory behavior, so minimizing global memory traffic and reducing tiny kernel launches is key.

A matrix-multiplication example contrasts a naive GPU kernel (one thread per output) with an optimized tiled version using local workgroups and shared local memory. On RTX 4060, global groups ran ~38 ms vs ~11 ms with local groups; Iris Xe improved ~213 ms to ~45 ms. Initialization cost (up to ~99 ms) makes batching essential for...

👉 Read | Forum | @mql5dev

#MQL5 #MT5 #AlgoTrading
23👌2
Fractional differentiation (FFD) is brought from an AFML-style Python pipeline into MetaTrader 5 with a production-ready MQL5 design: precompute the weight vector once, use a bounded lookback window, and compute each new value as a single dot product.

The core is a header-only CFFDEngine class that avoids per-tick allocation, minimizes CopyClose overhead, and supports both EA and indicator workflows. A companion FFD custom indicator wraps the engine and uses prev_calculated to recompute only new/changed bars, keeping runtime O(width) per bar.

Key implementation details include threshold-terminated weight generation (no fixed cap), safe log handling to match Python outputs, and new-bar timing to avoid look-ahead bias. A validation script confirms numerical parity with Python to ~1e-12, enabling reliable reuse of offline-optimized d values in live t...

👉 Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
294👍3👌2
RSI confirmation often sits in a separate subwindow, forcing attention shifts during execution-heavy workflows such as scalping or manual trade management.

A chart-embedded RSI panel addresses this by attaching directly to the active price level and updating on every tick. It renders the current RSI value, a state label (OVERBOUGHT/OVERSOLD/NEUTRAL), and a slope-derived strength rating (WEAK/STRONG/EXTREME), with optional Bid/Ask anchoring.

Implementation centers on MQL5 chart objects plus ChartTimePriceToXY for time/price-to-pixel mapping. Position clamping keeps the panel on-screen during zoom, scroll, resize, and timeframe changes. RSI handle lifecycle is managed in OnInit/OnDeinit; CopyBuffer feeds updates; alert spam is avoided via state flags.

👉 Read | VPS | @mql5dev

#MQL5 #MT5 #Indicator
57👌91😈1
An MT4 port of the MyRsi variant originally described by John Ehlers has been released, matching the behavior of the earlier MT5 build.

This RSI formulation differs from the platform’s built-in RSI in both scaling and signal interpretation. Output is normalized to the -1 to 1 range, making the zero line a practical reference for directional bias and cross-based signals.

Because the value distribution is not comparable to the standard 0–100 RSI, common thresholds such as 50 do not translate directly. Any rule set based on built-in RSI levels should be recalibrated for this implementation.

Operational guidance remains straightforward: treat it as an RSI-style oscillator, but validate levels and crossings against the new range before using it in automation.

👉 Read | Forum | @mql5dev

#MQL4 #MT4 #Indicator
30👌2👍1🔥1🏆1
Distance-based trailing stops process every tick and remain memoryless, which increases sensitivity to micro-noise and CPU load on lower timeframes. High-frequency bar/tick loops can also limit the feasibility of heavier models due to latency and terminal–server desync risk.

A proposed MQL5 trailing module, CTrailingBloomRNN (inherits CExpertTrailing), adds a dual-gate path: an O(1) Bloom filter for price deduplication using a packed uchar bitset, then a lightweight RNN with persistent hidden state for sequence-aware moderation. Unique prices update m_hidden_state via tanh(0.5*h + 0.5*normalized_input).

Trailing overrides (CheckTrailingStopLong/Short) early-return on duplicate ticks, then apply an optional RNN threshold before computing broker-compliant stop levels and NormalizeDouble rounding.

👉 Read | AppStore | @mql5dev

#MQL5 #MT5 #AI
2351🎉1👌1
This article turns market structure into something an EA can reason about: validated swing highs/lows become graph nodes, and price movement becomes weighted edges. Edge costs are volatility-aware (ATR-normalized distance) and include real frictions like spread plus penalties for noisy, same-type transitions.

On each new bar, the system rebuilds the graph from unbreached swings, then runs A* to find the lowest-cost route from the node nearest current price to a directionally consistent goal capped by ATR. The resulting path is filtered by directional strength, total cost, and structural “blockers” before any trade is allowed.

Execution uses the final node as take-profit and a prior opposite swing as a structural stop, with ATR fallback when structure is missing. Risk is position-sized from stop distance, and chart rendering shows nodes, edges, and ...

👉 Read | Quotes | @mql5dev

#MQL5 #MT5 #AlgoTrading
30👌31🤯1🤩1
AutoARIMA for MQL5 targets a common terminal-side constraint: ARIMA forecasting without manual (p,d,q) selection or heavyweight estimation code. Input is a single Close[] array (Close[0] newest). Output is a one-step-ahead close forecast as a double.

Pipeline is fully automated: d is chosen via a variance-change heuristic, the series is differenced, ARMA(p,q) candidates are fit by SSE minimization using gradient updates with Adam, and coefficients are clipped to [-0.99, 0.99] for stability. Model selection uses AICc over a bounded (p,q) grid (defaults such as max p/max q = 5).

Forecasting reconstructs residuals, predicts the next differenced value, inverts differencing back to price space, and rounds to tick size. Diagnostics printed include best ARIMA(p,d,q), AICc, SSE, last price, and forecast.

👉 Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
48👌73👀1
The December 2020 TASC issue covered John Ehlers’ MyRsi with Noise Elimination Technology (NET), an RSI variant that applies a Kendall-style autocorrelation approach to reduce noisy signals.

A practical adaptation is support for configurable input prices rather than a fixed close-only feed, which can be useful when testing on typical price, median price, or custom series.

Operationally, it can be treated like a standard RSI, with an additional NET line available for confirmation. In comparative chart reviews, the NET line often shows earlier turns and cleaner transitions, while RSI provides the familiar baseline for thresholds and divergence analysis.

👉 Read | Forum | @mql5dev

#MQL5 #MT5 #Indicator
33👀2
An object-oriented FVG scanner in MQL5 starts with strict three-candle geometry: bullish gaps form when candle 3 high is below candle 1 low; bearish gaps invert that relationship. This removes indicator lag by working directly on OHLC microstructure.

The implementation centers on a CFVGScanner class that pulls data via CopyRates into an MqlRates array (series-indexed), validates bar count to avoid out-of-range crashes, and supports multiple timeframe instances without shared global state.

A mitigation pass filters stale zones by scanning forward after detection and discarding gaps already touched by later highs/lows. Performance stays near O(N) with early breaks, and the EA runs scans only on new bars, not every tick.

Rendering uses OBJ_RECTANGLE with a unique name prefix plus targeted cleanup/deletion to prevent chart-object buildup and preserve user draw...

👉 Read | NeuroBook | @mql5dev

#MQL5 #MT5 #EA
3232👌1
MetaTrader 5 lacks account-level validation after trade entry. Positions can be modified, partially closed, or opened by multiple EAs and manual actions, creating gaps between intended risk and real exposure.

An enforcement engine treats risk as continuously verifiable conditions: SL present, TP defined, equity-based risk within limits, and a maintained risk-to-reward ratio. Violations trigger reporting or correction depending on mode.

Core modules: trade monitor, risk evaluator, enforcement, dashboard/alerts, and session configuration. MQL5 uses OnInit() with EventSetTimer(), OnTimer() to scan positions, broker stop-level checks, tolerance-based comparisons, lot-size reduction, and TRADE_ACTION_SLTP updates.

Modes: passive, assisted, strict. Logging and on-chart state tracking support testing and auditability.

👉 Read | CodeBase | @mql5dev

#MQL5 #MT5 #EA
14👍5🎉3👌1
Candle Range Theory levels on H1/H4/D1 often disappear on execution charts, causing lower-timeframe moves to be misclassified. A practical fix is an MTF overlay that plots higher-timeframe candle range, body, and wicks directly on the active chart.

An MQL5 indicator addresses this by mapping each lower-timeframe bar to its parent HTF candle with time-accurate anchoring, confirming setups only after the HTF candle closes to avoid repainting, and rendering the full OHLC structure as persistent zones.

Implementation details include HTF data loading via Copy* calls, a binary-search index map, CRT pattern checks evaluated only on HTF-close bars, and automatic drawing of range rectangles plus entry/TP/SL lines. Optional filters handle Sundays and small-gap candles, with alerts and performance safeguards for large histories.

👉 Read | Freelance | @mql5dev

#MQL5 #MT5 #Indicator
20👌2