MQL5 Algo Trading
574K subscribers
4.45K photos
7 videos
4.46K 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
Volatility Regime Shader classifies volatility into three regimes using the percentile rank of ATR over a rolling lookback, not a fixed threshold. An ATR percentile of 90 indicates current ATR exceeds 90% of values in the window, allowing the same logic to scale across symbols and timeframes.

Compression bars at or below the configured percentile are shaded light blue, Expansion bars at or above the threshold are shaded light red, and Normal bars remain unshaded unless enabled. A top-right label reports the active regime and current ATR percentile.

Key inputs include ATR period (default 14), percentile lookback (100), Compression (<=20), Expansion (>=80), and bars to calculate (3000), plus optional alerts on regime changes using closed bars.

For automation, two iCustom buffers are exposed: buffer 0 = ATR percentile (0–100), buffer 1 = regime code (0...

πŸ‘‰ Read | Freelance | @mql5dev
❀16πŸ‘6🀩4πŸ”₯3
Volatility Regime Shader segments volatility into Compression, Normal, and Expansion using an ATR percentile rank rather than a fixed ATR threshold. The current ATR is ranked against a configurable lookback window, allowing the same settings to adapt across symbols and timeframes.

Compression is identified at or below a user-defined percentile and shaded light blue. Expansion is identified at or above a percentile and shaded light red. Normal is unshaded by default, with an option to shade it as well. An upper-right label can display the active regime and current ATR percentile.

The regime output can be used as a strategy filter. Compression conditions are commonly used to gate breakout activation, while Expansion supports trend continuation logic and wider stop placement. Mean-reversion setups typically prefer Compression or Normal conditions.

For ...

πŸ‘‰ Read | VPS | @mql5dev
❀13πŸ‘8πŸ”₯3🀩3πŸ†3
Watchlist Chart Opener automates bulk chart creation in the terminal. A single run can open charts for every symbol in Market Watch or for a comma-separated custom list, using a selected timeframe or the current chart timeframe.

A named chart template can be applied to each new chart so indicators, colors, and layout remain consistent. Custom-list symbols can be added to Market Watch automatically, while unavailable symbols on the broker server are skipped and reported in the Experts log.

Symbol selection supports a text filter for matching names, including common suffix conventions. Duplicate control can prevent opening charts that already exist for the same symbol and timeframe. A maximum chart limit reduces the risk of opening excessive charts, and a final summary reports opened, skipped, and failed results.

πŸ‘‰ Read | Freelance | @mql5dev
❀11πŸ”₯8πŸ‘5🀩4πŸ‘Œ1
Closed Trades Exporter writes closed positions to a CSV compatible with Excel, Google Sheets, and other spreadsheet tools.

Alongside standard history fields, it computes Maximum Adverse Excursion (MAE) and Maximum Favorable Excursion (MFE) from M1 bars over each trade’s lifetime. MAE records the largest move against the position before close, while MFE records the largest move in favor. CapturedPct reports the share of MFE retained at exit, supporting analysis of stop-loss and take-profit placement across larger samples.

Each row represents one closed position: position ID, symbol, side, volume, open/close time and price, duration, profit, commission, swap, net profit, points result, MAE/MFE in points and currency, CapturedPct, magic number, and comment.

Filters include days, symbol, and magic number, plus optional MAE/MFE calculation. Output naming, sepa...

πŸ‘‰ Read | Forum | @mql5dev
❀16πŸ”₯10🀩8πŸ‘7πŸŽ‰1πŸ€“1
EAs that behave consistently on one broker can produce different results on another due to more than just spread. Trading hours, overnight sessions, and contract specifications can change how daily bars are built and how risk is priced for the same symbol.

This utility prints broker-specific parameters to the journal for side-by-side comparison. It reports server trading hours per weekday, including earliest open and latest close, highlighting differences that alter daily bar ranges.

It also outputs contract size, tick size, tick value, and the cash value of one price point, since equity-based position sizing depends on monetary point value rather than lot count.

Additional data includes long/short swap rates as nightly percent of price and annualised, M1 session coverage over the last N days to detect quote gaps, plus optional spread sampling with min/avg...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀16πŸ”₯10πŸ‘5🀩5πŸ€“2⚑1
An EA template implements an opening range breakout for US100/Nasdaq 100 CFD, with range levels calculated from M1 data regardless of chart timeframe. It records the high/low during the first minutes after the session open, then places a Buy Stop above and a Sell Stop below. Once one side fills, the opposite pending order is removed using OCO logic. Only one trade is allowed per day, and all positions are closed before the session end.

Key parameters include range start and length, last entry time, and close-all time in server time. Default values assume a GMT+3 server with a 16:30 US session open, requiring adjustment per broker. Controls cover trade direction, risk per trade, take profit as an R multiple, stop distance as a fraction of the range, and an ATR-based filter to skip abnormal days.

Account protection includes daily loss and maximum drawdown lim...

πŸ‘‰ Read | Freelance | @mql5dev
❀10πŸ‘8πŸ”₯8🀩2πŸ€“2
JPN225 Quiet Drift is a free, fully open Nikkei 225 EA designed for M15. It is long-only, allows one position at a time, requires all signals on the last closed bar, and forces a flat book by 17:00 server time. Entry is the next bar open with a 4 ATR stop and 3.5 ATR target.

The setup uses three filters: close > 0.5 standard deviations above the 34-bar mean, MACD histogram (in ATR units) < 0.2 to avoid stretched momentum, and tick volume < 60% of the normal level for that time of day (20-day baseline). Signals are evaluated 11:00–14:59 server time, targeting the post-cash-session window.

Backtest summary (10k, 15 lots): net +87.8%, ~18.5%/yr simple, max drawdown 8.5%, profit factor 1.68, win rate 61.8% over 309 trades (~65/yr). All years tested were positive (2022–2026 YTD). Stress checks included doubled fees, added slippage, and one-bar-late entries, with p...

πŸ‘‰ Read | Quotes | @mql5dev
❀18πŸ‘4πŸ”₯3🀩3πŸ€“2πŸŽ‰1
Memory Sequence is a same-symbol, multi-chart time-window sync indicator for MT4/MT5. One chart acts as the host, all other charts of the same symbol act as slaves. The host publishes a single candle’s open-to-close window, and slaves render that window and scroll it into view. The indicator uses chart objects and navigation only (indicator_plots = 0), with terminal global variables plus EventChartCustom (id 222). No DLL is required.

Typical workflow is one structural timeframe as host (often H1) with multiple slave timeframes (M1 through D1). A host click broadcasts the selected candle. Slaves draw an open-time vertical line, close-time vertical line, optional close-price line, and an optional filled rectangle covering the time span with high/low computed from local bars.

Host behavior includes a snapped crosshair and hover box on mouse move, and op...

πŸ‘‰ Read | Calendar | @mql5dev
❀11πŸ‘7🀩3πŸ”₯2πŸ€“2
Extrapolator is an MQL5 indicator that fits a truncated Fourier model to recent price history, then projects the fitted curve into future bars. The forecast is recalculated on each new model bar and the segment at the right edge is redrawn while the current bar is forming, so the line is inherently non-stationary.

Key controls include Npast/Nfut/Nharm to balance stability versus overfit, optional log-price fitting for proportional symmetry, and TrendDamp to reduce the carried-forward slope. Harmonic selection filters out periods below MinPeriod and above MaxPeriodFrac of the window, then stops when incremental variance reduction drops under MinHarmGain.

Visualization adds sigma-based channel bands (+/-1, +/-2) with optional filled zones. Internally, Quinn-Fernandes is used for frequency estimation, results are cached per model timeframe, and then mapped onto char...

πŸ‘‰ Read | Forum | @mql5dev
❀11πŸ‘5πŸ”₯2🀩2πŸ‘Œ2
This article replaces β€œtrust the ONNX class” with a robustness check: how much feature-space noise the input can tolerate before the prediction flips. Using randomized smoothing, the EA runs N Gaussian-perturbed inferences per bar, votes the winning class, and computes a certified radius via a Clopper–Pearson lower bound and the inverse normal CDF using only MQL5’s standard math functions.

The architecture is cleanly split: a feature engine builds a fixed 10-value normalized vector, a certifier owns the ONNX session and certification math, and the EA gates trades on the last closed bar. Shape mismatches are caught early, float32 tensors are handled correctly, and abstains occur when statistical support is weak.

Practically, the radius becomes a trading input: skip or downsize fragile signals, allocate size across symbols by robustness, and log radius history fo...

πŸ‘‰ Read | AppStore | @mql5dev
❀17πŸ‘5πŸ”₯5🀩3πŸ€“2
Tick volume on retail FX charts is mostly a proxy for time of day, and it is only complete at bar close. It also loses resolution when bursts and evenly spaced updates produce the same count. A quote-interval activity gauge addresses this by working on durations between quote changes and normalising out the intraday rhythm.

Quotes are converted into events by folding same-millisecond updates and resetting after long gaps (default 5 minutes) to avoid training on market closures. A 30-minute-bin diurnal profile is fitted and interpolated, then scaled to unit mean so 1.0 represents normal activity for that hour.

Residual clustering is modelled with an Engle-Russell ACD recursion, producing a per-quote activity ratio (mean/psi). Values near 2.0 indicate quotes arriving roughly twice as fast as usual; 0.5 indicates half speed. Additional outputs includ...

πŸ‘‰ Read | VPS | @mql5dev
❀24πŸ”₯7πŸ‘5πŸ‘¨β€πŸ’»4πŸ‘Œ3πŸŽ‰2🀩1
ATS_RiskLib.mqh is a single include file providing five risk-control classes for MQL5 EAs. The library does not open, modify, or close trades; it only calculates and validates conditions before an order is sent.

CAtsSizer computes volume from stop distance with modes for fixed lot, % balance, % equity, or fixed money risk. Volume is floored to the broker step and never rounded up. If the computed risk is below the broker minimum, Lots() returns 0.0 with a reason via LastReason(). Optional volume cap and free-margin validation use OrderCalcMargin.

CAtsDayGuard enforces daily loss (percent and/or money, using the smaller), optional profit target, and max trades per day. Day start is configurable by server hour and can include open P/L. State is persisted via GlobalVariables, so terminal restarts do not reset limits.

CAtsDrawdownGuard supports static max loss...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀25πŸ‘15πŸ”₯12🀩6πŸ†2πŸ‘Œ1
ATS Prop Rules Monitor aggregates five common prop challenge constraints in a single panel and shows remaining room for each rule, rather than only daily loss. Supported checks: daily loss (percent of day-start balance, optional floating P/L, configurable day-start server hour), max loss (static from initial balance or trailing on equity/balance), profit target, minimum trading days (days with at least one closed trade), and best-day consistency (disabled when not applicable). Status uses green/amber/red plus a summary badge: ALL CLEAR, WARNING, LIMIT BREACHED, TARGET MET.

A β€œOne More Trade” line calculates the largest lot size for the chart symbol that keeps a stop-out within a configurable share of the smaller remaining room. Lot sizing follows ATS Risk Library rules and never rounds up.

Implementation details: panel rendered via CCanvas with DPI scaling...

πŸ‘‰ Read | Docs | @mql5dev
🀩17❀12πŸ‘12πŸ”₯9
Naive label sampling in ML trading pipelines creates predictable failure modes: class imbalance during trend-heavy periods, feature/label autocorrelation that inflates fit quality, and heavy class overlap that forces unstable decision boundaries.

Dimensionality reduction (PCA) makes these issues visible: loop-shaped structures from autocorrelation and strong overlap between buy/sell regions, consistent with GIGO effects and poor out-of-sample behavior.

A practical mitigation is probabilistic resampling with Gaussian Mixture Models. GMM models density with full covariance, generates synthetic samples with fewer outliers, and reduces serial dependence. Labels are clustered jointly, then re-binarized.

An iterative loop generates GMM samples, trains CatBoost, and ranks runs by out-of-sample RΒ² across a longer test window than the training period. Supporting ch...

πŸ‘‰ Read | Docs | @mql5dev
❀28πŸ‘16πŸ”₯14🀩5🀯1
A chart indicator aimed at studying the ICT/Smart Money sequence on any symbol and timeframe. It is analysis-only, does not place trades, and does not claim performance.

It draws liquidity pools (previous day high/low, Asia session high/low), marks sweeps when price takes a pool and closes back inside, then detects MSS via an ATR-sized displacement candle and highlights the resulting FVG. Signals use WATCHING/CONFIRMED states.

Non-repainting is enforced by creating objects from closed bars only; recalculation rebuilds identical objects. Optional CSV logging writes each signal at creation time.

For confirmed setups it plots entry (FVG midpoint), SL (beyond sweep), TP (risk multiple), estimates lot size for a risk %, and tracks outcomes bar-by-bar (TP/SL/missed; TP+SL same bar counts as SL). A panel aggregates setups, fills, misses, win rate, and n...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘15πŸ”₯7🀩3πŸ‘Œ1
NewtonianMechanics.mq5 provides bid/ask tick kinematics with explicit uncertainty. Bid and ask are handled as separate streams, each fitted with a local quadratic and reported as position, velocity, acceleration, standard error, and z-score. Forecasts are then checked out of sample with a scoreboard (hit rate and R-squared), including a split by |z| >= 2.

Windows are counted in events rather than seconds, using exponential weighting so evidence stays comparable across quiet and active periods. Time is taken from MqlTick.time_msc, and each side advances only on its own updates; repeated quotes are not treated as new observations.

Error bars apply a random-walk floor to avoid overly optimistic OLS assumptions. A phase label is derived from the slowest window (256 updates): EXPANSION, RETRACEMENT, STRESSED, CONSOLIDATION, UNDETERMINED, WARMING. A spr...

πŸ‘‰ Read | CodeBase | @mql5dev
❀21πŸ‘17πŸ”₯6🀩3πŸ‘Œ3πŸ‘¨β€πŸ’»1
Chart patterns are visually clear but hard to define in code due to ambiguous start bars, low tolerances, neckline placement, and validation timing. A practical gap is the inability to preserve the exact candle sequence behind a marked formation for later reload, measurement, and comparison.

A six-module MQL5 recorder addresses collection, not detection. The trader manually labels a double-bottom candidate via a chart rectangle. The system extracts candles by time bounds only, derives candle features, normalizes OHLC as percentage displacement from the first close, then persists each sample as CSV and reloads the library after restart.

Architecture splits responsibilities across PatternData, Extractor, Storage, Library, Panel, and a thin EA integration layer. Storage uses strict schema/version headers, UTF-8 quoted fields, non-overwriting writes, and validation...

πŸ‘‰ Read | Freelance | @mql5dev
❀19πŸ‘15πŸ”₯12🀩2πŸ‘Œ2
This article turns two built-in MT5 indicators into a single, rule-driven decision aid by giving Envelopes the missing market-state context from Alligator. It highlights a key pitfall: Envelopes are fixed-percentage bands around an average, not a volatility measure, so boundary touches can mean range noise or trend continuation.

The strategy classifies Alligator line order (Lips/Teeth/Jaws) into neutral, unconfirmed, and confirmed states using persistence across completed bars (InpTrendMinBars). Only confirmed direction or neutral can authorize an Envelope close-cross event; counter-trend crossings are filtered, repeated arrows are throttled via cooldown, and optional alerts trigger on closed bars.

Implementation-wise, Envelope_Alligator_Strategy.mq5 composes four built-in handles (iEnvelopes + three unshifted iMA) to avoid re-implementing formulas, ...

πŸ‘‰ Read | Freelance | @mql5dev
❀17πŸ‘10πŸ”₯4🀩3πŸ‘¨β€πŸ’»2πŸ‘Œ1
PropFirmAwareSizer adds two modifiers on top of budget-based sizing: derisking_factor and news_window_factor.

derisking_factor reduces exposure as phase_progress approaches the profit target. It stays at 1.0 until 80% progress, then tapers to a floor at 100%. The floor is 0.30 before min trading days are met, and 0.10 after, so day-count compliance remains possible while still cutting risk near a pass.

Both modifiers multiply, not min(). Moderate constraints compound, and identical final sizes can come from different states, so diagnostics like cal_bet_size and derisking are required.

news_window_factor is funded-stage only. It uses a UTC-normalized economic calendar and applies a 5-minute half-window around high-impact events. It is a sizing heuristic, not profit accounting, and should be symbol-aware to avoid false haircuts.

πŸ‘‰ Read | Freelance | @mql5dev
❀21πŸ‘9🀩6πŸ”₯4⚑2🀣1
A native MQL5 port of Kronos can match PyTorch outputs and still fail as a forecaster. The article separates verification (tight numeric equivalence) from market evaluation, where misleading β€œgood-looking” results are easy to generate.

KronosForecast EA runs inference once per completed bar (never using the still-forming bar), then renders predicted candles via chart objects. Missing exchange volume/amount is approximated from tick volume and typical-price turnover, introducing a distribution shift. Future timestamps are projected on a fixed grid; weekend crossings are measured and shown not to explain poor accuracy.

Evaluation is built to prevent look-ahead by design: dump deterministic greedy forecasts to file, score them offline, then backtest using only forecast columns. On EURUSD H1 (256-bar context, 16-bar horizon), Kronos underperforms a random-walk ...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀19πŸ‘11πŸ”₯5πŸ‘¨β€πŸ’»3🀩2πŸ‘Œ1
Deep learning in trading hit a known limit: adding layers can stall or reduce accuracy due to optimization issues. Residual connections (ResNet) addressed this by preserving an identity path and stabilizing gradient flow.

Spiking neural networks (SNNs) better match event-driven market behavior by processing discrete spikes, with potential gains in real-time processing and efficiency. In practice, deep SNNs have been hard to train: identity mapping is non-trivial with spiking neurons, and surrogate gradients amplify vanishing or exploding gradients as depth grows.

SEW-ResNet (Spike-Element-Wise residuals) reframes residual learning for SNNs with element-wise spike-based gating that supports natural identity mapping and stable gradients. Reported results include stable training beyond 100 layers and improved accuracy versus prior deep spiking baselines, enab...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘15❀11🀩11πŸ”₯4πŸ‘¨β€πŸ’»3πŸŽ‰1πŸ‘Œ1