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
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
This article digs into a common MT5 pitfall when building indicators for subwindows: calculation direction inside OnCalculate. A simple moving average can work on volumes, yet “vanish” when applied to another indicator’s buffer because the loop runs from oldest to newest, propagating bad intermediate values and producing invalid output with no terminal errors.

Reversing the iteration to process newest bars first fixes the plot and matches MetaTrader’s built-in MA behavior. The takeaway is that buffer integrity depends on update order, especially when an indicator consumes another indicator’s data.

It also explains MT5’s subwindow “data queue”: FIRST INDICATOR’S DATA reads the oldest indicator in that pane, PREVIOUS INDICATOR’S DATA reads the most recently added one. Chaining indicators becomes a controlled way to smooth or amplify signals, and MT5 au...

👉 Read | Quotes | @mql5dev
👍24🤩13❤9🔥9👨‍💻4🏆1
EV-MGRFlowNet reframes motion estimation as event-stream modeling, which maps cleanly to tick-level market data where each trade and quote update is a micro-event. Its encoder-decoder pipeline builds temporal representations from irregular, high-density sequences without forcing fixed time bars, staying robust across volatility spikes and quiet periods.

A key upgrade is ST-ConvGRU inside the FERE-Net encoder: each layer updates state using both its own past and feedback from the higher layer, preserving cross-scale context that classic ConvGRU drops. The decoder then reconstructs fine-grained “motion” signals from coarse structure, supported by a hybrid loss designed to enforce temporal consistency.

The implementation focus is practical: an MT5/OpenCL ST-ConvGRU class organizes concatenation, multi-window convolutions, gating, normalization, and optional sp...

👉 Read | Calendar | @mql5dev
❤14👍14🤩12🔥9
An MQL5 basket EA applies Markowitz weights rather than single-symbol signals. Core logic stays native: Gauss-Jordan inversion, covariance estimation, and closed-form frontier solvers, with Strategy Tester results reported even when mixed.

CMatrixOps inverts Σ once and reuses it across GMV, tangency, and target-return solvers. The inversion exits on singular pivots; fixed 10x10 buffers avoid MQL5 dynamic 2D allocation issues. A constant epsilon remains a stability risk across volatility regimes.

CMarkowitzEngine builds μ and Σ from bar closes, computes only the upper triangle, and currently samples the forming bar. GMV/tangency/target-return outputs are clipped to long-only via floor-and-renormalize, which is not a constrained QP solution.

Execution converts weights to lots, trims via partial close, and rebalances on timer or drift. Limitations include cur...

👉 Read | Calendar | @mql5dev
❤15👍13🤩11🔥8✍2
Classic grid EAs often look stable until a strong trend turns averaging into runaway exposure. The article quantifies how Martingale-style sizing compounds drawdown fast, leading to margin calls long before any “eventual” retracement.

GridSurvivor improves survivability with three constraints: start grids only on regular RSI divergence (pivot-based, confirmation via left/right lookback, plus oversold/overbought gating), cap grid depth to a fixed level count to make worst-case loss measurable, and enforce an equity-based risk manager that can lock trading and force-close positions.

Implementation stays beginner-friendly (pure MQL5, CTrade, single file) while keeping components modular: isolated CRiskManager, separated entry filter, and clear grid helpers (level counting, average price, outermost order). Backtests show the full stack surviving 2020–2...

👉 Read | AppStore | @mql5dev
❤21👍12🔥10🤩7👨‍💻2⚡1
Daily Loss Guard enforces an account-level daily loss cap by closing exposure when the configured limit is reached. It can be attached to any single chart, on any symbol and timeframe, and operates independently from trade entry logic. A timer is used, so tick activity on the host chart is not required.

Daily P/L is computed from today’s closed trades plus the change in open positions since the defined day start. Deposits and withdrawals are excluded. On limit hit, all positions are closed, pending orders are removed, and any newly opened trade is closed until the next trading day.

The trading day start is set by server hour. Start balance and limit-hit state are stored in terminal global variables to survive restarts and re-attaches, then reset automatically on the next day.

Configuration supports percent or fixed-currency limits, symbol filtering, magic ...

👉 Read | Signals | @mql5dev
❤18👍8🔥8🤩4⚡2🤯1
Session Range and Spread is a chart annotation tool that marks the Asia, London, and New York sessions. Each day it draws a box from the session high to low and prints the range on the box. A compact panel shows current spread and which sessions are currently open.

Session times are entered in UTC. On live charts, the broker UTC offset is detected from server time versus GMT, with an option to set it manually. Sessions crossing midnight are supported. Range labels can be Auto, Price, Points, or Pips; forex pairs use pips by default, while metals and indices use price units.

The active session updates on every tick and is marked with an asterisk. Labels are positioned to reduce overlap. Boxes render on H1 and lower; higher timeframes show only the panel. The indicator draws objects only and provides no trading signals.

👉 Read | Freelance | @mql5dev
❤16👍13🔥5🤩5👌2
Currency Exposure and Leverage Monitor aggregates every open position into currency legs and reports net exposure per currency in account currency. It highlights when several trades that look unrelated are effectively the same directional risk, such as multiple USD shorts created via EURUSD, GBPUSD, and XAUUSD.

The panel ranks currencies by gross contribution and visualizes long vs short exposure around a zero axis. It also calculates effective leverage as gross notional divided by equity, compared with broker leverage, with configurable warning thresholds and concentration flags when a single currency exceeds a set share of total exposure.

For the three largest exposures, a sensitivity section estimates equity impact for a configurable currency move (default 1%), in money and as a percentage of equity. Opposing legs are netted to expose hidden offse...

👉 Read | Quotes | @mql5dev
❤18🔥8🤩8👍7