MQL5 Algo Trading
579K subscribers
4.62K photos
7 videos
4.63K 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
Backtests can hide which part of an EA is failing when multiple entries share one magic number. In an order-block liquidity-sweep scalper, splitting results by setup showed most losses came from only one side, despite identical code and risk.

CSetupLedger fixes this by encoding a setup id into the magic number (not comments, which brokers overwrite), then rebuilding per-setup stats from account deal history so restarts, file loss, and manual closes don’t erase the record. Correct aggregation requires scoring by position id, summing partial fills, and using net P/L including commission and swap.

Instead of trusting raw win rate, it reports a Wilson confidence interval and compares it to the setup’s real breakeven rate derived from observed average wins/losses. The output becomes actionable: too few trades, undecided, trusted, or rejected.

👉 Read | AppStore | @mql5dev
❤14👍7🔥7🤩5🎉2👀1
A lightweight MT5 candle-close countdown indicator for any symbol and timeframe, including XAUUSD and EURUSD. The timer uses the broker trade-server clock, so it keeps updating during low-tick periods and aligns with broker candles rather than the local PC time.

Display supports either a price-attached mode (offset to the right of the last bar) or a fixed chart corner with configurable pixel offsets. Output formatting adapts to timeframe: mm:ss on intraday, hh:mm:ss from H1, and days+hours on D1 and higher. Optional spread display, optional symbol/timeframe prefix, and a last-seconds color change are available.

Alerts can trigger once per candle a configurable number of seconds before close, via pop-up and/or sound. Implementation uses a single text object created once and rewritten every 500 ms; no canvas or buffers. On weekends or outside sessions, ...

👉 Read | AlgoBook | @mql5dev
❤9👍5🔥5🤩4
Backtests built on smooth-volatility assumptions tend to fail when volatility shifts fast. Empirical realized-volatility studies (Gatheral, Jaisson, Rosenbaum, 2014) estimate the Hurst exponent for log volatility around H≈0.10, consistent with rough, anti-persistent dynamics that classical GBM/GARCH families cannot model.

A practical implementation is a moving-window Hurst estimator using R/S analysis with OLS in log-log space and logarithmically spaced scales. Non-overlapping subsample averaging improves stability; safeguards avoid degenerate R/S and regression cases.

Signal mapping is operational: H<0.3 indicates rough/mean-reverting conditions, 0.3–0.5 neutral, H>0.5 trending/persistent. The output is a regime filter for strategy selection and a risk metric for reducing exposure during regime transitions.

👉 Read | AlgoBook | @mql5dev
❤18👍10🔥6🤩3
CanvasTabs provides a lightweight tab bar for charts using the standard CCanvas class. Distributed as a single include file, it has no DLL dependencies, no trading logic, and no built-in persistence. Intended for panels that need basic tabs without a full GUI framework.

Supports tab titles, an active tab, and a minimal hover state. Tabs can be changed by mouse click or via SetActiveTab. Resize updates width without recreating the chart object. Long titles are truncated to fit, with an ellipsis when space permits.

Multiple independent instances are supported on the same chart, each with unique object and resource names. Height, padding, and font size are scaled once from screen DPI. Destroy() cleans up only the instance resources and is safe to call repeatedly. OnChartEvent returns true only when a click changes the selected tab.

A demo expert shows tw...

👉 Read | Quotes | @mql5dev
❤11👍8🤩4
Multiple regression is a baseline tool for trading models where returns respond to several drivers at once. Single-factor fits often shift missing effects into the error term, producing biased coefficients and unstable results when regimes change.

Core setup uses OLS with matrix notation: b = (XᵀX)⁻¹Xᵀy. This requires no multicollinearity; otherwise XᵀX becomes singular. Model building stays iterative: add, remove, and transform regressors, then re-run diagnostics.

Standard checks include residual plots, QQ/EPDF, autocorrelation tests, and stability tests. Factor diagnostics rely on correlation matrices, partial regression plots, VIF for multicollinearity, and Cook’s distance for influential observations. Formal testing typically adds Ljung–Box, Jarque–Bera, Breusch–Pagan, Ramsey, and F-tests.

👉 Read | Freelance | @mql5dev
❤13👍9🔥6🤩6
An H1 EURUSD pullback system combines a 14-period linear weighted moving average, Awesome Oscillator, and a daily reference level from three sessions back. Entries are never at market. Signals place stop orders at the prior daily low/high, so execution occurs only if price reclaims that level.

Buy setup: the open from two bars ago is below the WMA and AO is decreasing on the last closed bar. A buy stop is set at the daily low from three days back, only if that level is above current price. Sell setup mirrors this logic using the daily high, only if it is below current price.

Risk uses an internal ATR(24) with Wilder smoothing. Stop is 1.5 ATR from entry, target is 0.7% of entry, and volume is sized so a stop-out costs a fixed 20 USD by default. Pending orders expire after 12 bars and are replaced by newer same-side signals. Evaluation occurs once per bar; o...

👉 Read | Quotes | @mql5dev
❤11👍10🔥2👌2🎉1
MQL5 exposes AccountInfoInteger(ACCOUNT_FIFO_CLOSE) to detect FIFO close enforcement. On FIFO accounts, closing anything but the oldest ticket on a symbol can be rejected with TRADE_RETCODE_FIFO_CLOSE (10045), breaking exit logic that targets recent adds in pyramiding systems.

A practical approach is a two-part design. CFifoPositionQueue snapshots the EA’s own positions per symbol (magic-filtered), sorts by POSITION_TIME_MSC with ticket tie-breaks, and provides eligibility plus a required close sequence. CFifoComplianceGuard owns all CTrade calls, runs async off, rechecks eligibility before each step, and either rejects non-eligible requests or executes a cascade.

Included examples show an EA that intentionally requests the wrong ticket, plus synthetic tests for ordering, cascades, and volume normalization. Backtests validate decision logic, not broker...

👉 Read | Signals | @mql5dev
❤15👍10🔥5🤩2
Spread behavior is session-dependent: typically tighter during London and New York, wider at the daily rollover around 17:00 New York and in the first minutes after the weekend open. SpreadHeatmap visualizes this as a 24x8 table per chart symbol, with weekdays plus an “All” column. Each cell shows the typical spread for that hour/day in points, color-mapped from low to high cost.

Values come from historical bar data (MqlRates.spread). The chosen timeframe (M5 default) is sampled across the last N days (60 default). Per-cell statistics can be median, average, 90th percentile, or maximum. Coloring is relative to the symbol-wide median, with configurable thresholds; cells with fewer than 3 bars display “-”, and the current hour is marked.

Time display can switch between server time, UTC, and major market centers with DST handled per bar. Optional CSV expo...

👉 Read | Freelance | @mql5dev
❤8👍8🤩2
Weibull reliability can be applied to EAs by defining “failure” as trades survived until rolling profit factor falls below a configurable floor. Each failure logs a lifetime in trades, resets the age counter, and clears the rolling window; skipping the window reset biases the sample toward lifetime=1 artifacts.

An MQL5 implementation uses an MLE Weibull fit with Newton-Raphson on the shape parameter and a closed-form scale. The fitted beta informs hazard behavior: beta>1 implies rising hazard with age. A case study on XAUUSD M5 produced beta=5.34, scale=23.36 from 8 failures (20,21,20,22,20,20,31,20), but the detector design imposes a 20-trade minimum lifetime.

A governor reads conditional survival before entries, applies cooldown instead of permanent retirement, and publishes fit parameters via globals for an indicator. Limits remain: thin samples,...

👉 Read | Signals | @mql5dev
❤15👍8🤩4👌3🔥1
Trade results show the endpoint, not the path. Two excursion metrics fill the gap: MAE (maximum adverse excursion) and MFE (maximum favourable excursion). They help quantify how much drawdown winners typically require, how often losers moved in favor before reversing, and how much of the best move winners actually retained.

A script and reusable class generate a per-position report (ticket, symbol, side, volume, open/close, net result, MAE, MFE, stop distance) plus an on-chart summary with medians and 90th percentiles, winner capture, loser MFE stats, and the fraction of stopped losers that reached +1R at any time.

Computation aggregates all deals into a single position (partial closes included), uses VWAP for multi-entry opens, and derives MAE/MFE from 1-minute bid bars between entry and exit. Current positions and those opened before the history windo...

👉 Read | Freelance | @mql5dev
👍12🤩12❤7🔥5
Two-Pole Momentum Oscillator implementation in MQL5: momentum is derived from close minus a 25-period SMA, then normalized using the 25-period mean and standard deviation of that deviation series. This converts raw drift into a comparable, volatility-adjusted value.

The normalized stream is processed through two consecutive first-order EMA-style smoothing passes, producing a second-order response for a steadier oscillator around the zero line.

Signal logic compares the current oscillator value to its value four bars earlier. Buy: rising while below zero. Sell: falling while above zero. Visual output uses a color-changing line plus arrow markers.

Dynamic control levels are calculated from the signal bar high/low plus a 100-period average candle range, managed as chart objects and removed on price breach.

👉 Read | Docs | @mql5dev
👍18🔥12❤9🤩6
MeanReversion.mqh implements mean-reverting spread logic by modeling the residual of a cointegrated pair (basis or z-score) as an Ornstein-Uhlenbeck process and computing entry/exit levels.

Fit(x, dt) performs exact maximum-likelihood estimation on equally spaced bars using the OU transition density, returning kappa, theta, sigma, plus standard errors from the likelihood Hessian. LogLikelihoodAt() evaluates the likelihood for arbitrary parameters. Derived metrics include half-life and long-run standard deviation.

Trading levels follow Bertram (2010): given a round-trip cost, compute expected cycle time via erfi and maximize expected return per unit time. OptimalSymmetric(c) enforces m = -a; Optimal(c) leaves it unconstrained (the optimum is symmetric). Levels in long-run SD units depend only on cost.

SpreadBands.mq5 builds a two-symbol log spread ...

👉 Read | Freelance | @mql5dev
❤22👍16🤩10🔥5
ANANTA is an intraday FX portfolio method that replaces carry-trade bond yields with 2-year interest rate swap differentials, aiming to trade market expectations of future policy rather than central-bank signaling. Positions are always on: capital is rotated across currencies via periodic rebalancing, without stop-losses or volatility sizing.

Implementation in MQL5 builds a yield-differential matrix, measures spread momentum versus a short SMA (2-day or 15-day), normalizes it, then filters noise by discarding the weakest half of signals using a median threshold. Remaining pair signals are netted into directional “points” per currency for USD-referenced rebalancing.

Using free IRS CSVs for USD, EUR, GBP, JPY, CHF and daily London-close rebalancing, backtests (2020–Oct 2026) show stable growth, Sharpe ~2.41 and ~11% max drawdown, with code structured...

👉 Read | Docs | @mql5dev
❤14👍9🔥5🤩2👨‍💻2
Supply/demand zones are derived from confirmed swing highs and lows on any symbol and timeframe. A swing high creates a supply zone, a swing low creates a demand zone. Zone height is normalized using ATR(period) x factor, keeping sizing consistent across markets.

Zones track retests: labels increment from fresh to tested 1x/2x/3x, with dimming colors after the first touch. A candle close through a zone invalidates it and removes it. Same-side overlaps can be merged, and the chart can be limited to the most recent N zones per side. Swings require N closed candles to the right, so zones appear with that delay. Processing runs once per closed bar.

Key settings include swing length, ATR period, zone factor, bars scanned, per-side limit, merge/remove toggles, fill/extend options, labels, and entry alerts when price first enters a zone. For automation, fiv...

👉 Read | Docs | @mql5dev
❤10👍7🔥4
Backtest max drawdown is a single realized path, not a sizing input by itself. Resampling trade returns with a stationary block bootstrap produces a drawdown distribution, while block permutation holds trades fixed and varies only order to isolate sequence risk from sampling variation.

Block length encodes an assumption about dependence, not a parameter to tune for better tails. Too-short blocks understate clustered losses; too-long blocks collapse into rotations of one path. For non-overlapping trades, results should be shown across a block-length range and paired with serial-correlation checks.

Prop-firm rules are path constraints with a basis, horizon, clock, and floating-equity definition. Breach probability should be estimated against those rules, using trade-exit paths as a lower bound and a calendar-day, mark-to-market version for server-tim...

👉 Read | Docs | @mql5dev
❤16🔥5🎉5👍4🤩1
Archimedes Optimization Algorithm (AOA), proposed in 2021, models each candidate as a position plus density, volume, and acceleration. Convergence is framed as reaching a zero-net-force state, with exploration and exploitation emerging from the same update loop.

State is initialized with X in bounds, den/vol in [0,1], and acc in bounds. Each iteration pulls den and vol toward the current best via a shared random convex update, keeping values stable and bounded.

A transfer factor TF grows toward 1, while a decreasing factor d shrinks step scales. Acceleration switches between a random neighbor (collision phase) and the global best (no-collision phase), then gets normalized to [0.1, 1.0] as a per-agent step regulator.

Position updates move toward a random peer early and around the leader later, with a sign switch to reduce premature collapse. Greedy accepta...

👉 Read | AppStore | @mql5dev
❤9🤩6👍2
Risk metrics in MT5 often hide a modelling choice: a rolling lookback is just a probability vector that weights recent bars equally and older bars as exactly zero. That can underprice regime shifts (e.g., pre‑March 2020 calm), exclude known upcoming risk, and makes old crises impossible to “reconsider” because their weight is forced to zero.

Entropy pooling keeps the full historical scenario set intact and reassigns probabilities by minimizing relative entropy to a prior (typically time‑decay), while enforcing explicit constraints: state conditioning (today’s volatility regime), higher USDJPY volatility, minimum tail risk for CHF shocks, or capped cross‑pair correlation. The solution is an exponential tilt solved in the low‑dimensional dual, so thousands of bars reduce to a handful of multipliers.

The article delivers a pure MQL5 library (solver, view types...

👉 Read | Calendar | @mql5dev
❤12👍6🤩4🔥1
Most MT5 EAs drift because filters get added without knowing how the strategy actually behaves. This article proposes building a non-trading “evidence logger” for a Range Breakout: it follows the original rules, measures every component, and exports a CSV for structured analysis with the MT5 AI Assistant.

The logger separates what’s knowable at entry (range + breakout-candle features) from what’s only knowable later (retests, excursion, outcomes), preventing accidental lookahead. It handles session windows (including midnight wrap), freezes range context (ATR, prior-day/session levels), records accurate entry price for close vs wick triggers, then tracks 24 bars with a state-machine retest model and strict first-touch outcome labels plus ambiguity flags.

A Tokyo M15 run on GBPUSD logged 419 events; a 10% systematic sample showed false breakouts exceeding wi...

👉 Read | Docs | @mql5dev
👍11🔥7❤6🤩3
ACA (Andean Condor Algorithm, 2018/2019) was evaluated as a two-phase metaheuristic for rugged, multimodal objective landscapes typical in EA parameter tuning. Reproducibility is a key issue: core control logic is split across papers, requiring reconstruction before benchmarking.

Each iteration ranks the population by fitness. A DP threshold assigns top-ranked agents to intensification and the rest to exploration, then a PC probability can flip statuses to reduce early lock-in. Exploration resets about half the coordinates uniformly within bounds; intensification perturbs one coordinate using one of four step scales. Updates use greedy acceptance with rollback.

Testing targets three benchmarks (Hilly, Forest, Megacity) at 10, 50, and 1,000 dimensions. Population size tuning becomes decisive; recommended defaults do not hold on harder cases. A C_AO_...

👉 Read | AppStore | @mql5dev
👍16❤11🤩7🔥5
Polling an EA against an external signal service works until restarts, retries, and ambiguous broker replies appear. Without stable IDs and acknowledgments, “processed” and “never seen” become indistinguishable, invalid records keep resurfacing, and partial fills or margin errors trigger unsafe retries.

A Redis Streams prototype hardens delivery using consumer groups, PEL tracking, and explicit XACK. BLOCK 0 is avoided due to gateway single-threading. Group creation ignores BUSYGROUP only; other errors must surface.

Execution authority remains in MQL5. Python can emit SIGNAL_GENERATED, but order sizing, risk checks, and OrderSend decisions stay in an EA-side guard. Dedup uses event_id; acknowledgments use stream_id. A durable EA journal records ATTEMPTING/ACCEPTED/REJECTED, flushes before ACK, and reconciles on redelivery by matching broker state via magic and...

👉 Read | Calendar | @mql5dev
👍16❤14🔥12🤩6😁2👀2
Trading logic often assumes either mean reversion or continuation, but price charts and common indicators do not test the required serial structure in returns.

The Lo–MacKinlay Variance Ratio (1988) checks whether Var(k-period returns) scales proportionally with k under a random-walk or martingale-difference null. VR(k) near 1 aligns with variance scaling; below 1 indicates net negative autocorrelation, above 1 net positive. Z-statistics are required due to sampling noise.

Two statistics matter: a homoskedastic test for iid increments, and a heteroskedasticity-robust test for uncorrelated returns with time-varying volatility. Short timeframes can show VR<1 from microstructure effects.

An MQL5 implementation is split into a zero-dependency CVarianceRatio engine and a script that retrieves data, runs multiple horizons, and logs results for on-demand diag...

👉 Read | Forum | @mql5dev
❤20👍18🤩15🔥8