MQL5 Algo Trading
529K subscribers
3.69K photos
5 videos
3.69K 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
MetaTrader 5’s built-in Expert Advisors are more useful than they look because the full MQL5 source is included. This walkthrough uses BullishBearish MeetingLines Stoch.mq5 as a practical template: it detects Three White Soldiers/Three Black Crows, confirms with Stochastic, then applies fixed SL/TP and a bar-based holding period.

Two customization paths are outlined. First, optimize exposed inputs in Strategy Tester (Stochastic periods, SL/TP, candle-body sensitivity, duration) to establish a baseline and reduce loss streaks without touching code.

Second, modify logic safely by cloning the EA and compiling a new build: externalize hard-coded Stochastic thresholds into inputs for proper optimization and debugging, then add an optional Moving Average trend filter using indicator handles and CopyBuffer on the last closed bar to avoid repainting. This reduces coun...

πŸ‘‰ Read | VPS | @mql5dev
❀26πŸ‘13πŸ”₯5πŸ‘Œ3πŸ‘¨β€πŸ’»2
An institutional-grade order flow and footprint chart indicator has been ported from Pine Script to MQL5, using lower timeframe volume to rebuild higher timeframe bars and compute buy/sell delta by price level. The implementation includes automatic timeframe selection, POC highlighting, stacked imbalances, absorption detection, and Unfinished Business tracking with live mitigation, plus real-time alert conditions.

Rendering is optimized for MT5 chart behavior. Footprint columns scale with zoom, fonts auto-resize and hide when unreadable, and background candles can be disabled with safe restoration on removal. CPU load is controlled via a configurable lookback window, while alerts are evaluated only on closed bars to avoid tick-driven noise.

Deployment follows standard MT5 workflow via MetaEditor as a custom indicator, with tuning for spacing, font...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀27πŸ‘10πŸ‘1πŸ‘Œ1🀣1
A trading signal model was tested using the Foster–Stewart criterion to estimate trend direction and strength, with reversal expected after the indicator reaches a defined threshold.

Separate parameter sets were used for buy and sell entries to reflect asymmetric upside/downside behavior. Each side applied three trend horizons: intraday, intra-week, and intra-month.

Risk controls used automatic stop-loss and take-profit derived from price levels. A best-price filter reduced exposure by allowing new buys only below the open price of existing buys, and new sells only above existing sells.

Optimisation was performed on EURUSD H1 from 2025-01-01 to 2026-05-31, with parameters selected independently per signal. Inputs include Slippage, PeriodBuy/PeriodSell (>=3), and LevelBuy/LevelSell (<= Period-1). The objective was criterion analysis rather than sta...

πŸ‘‰ Read | Forum | @mql5dev
❀21πŸ‘10πŸ‘Œ1
An intraday Asian-range indicator tracks the session high and low while the configured window is active, with the dashboard showing SESSION FORMING. After the session ends, levels are fixed and status is classified as Range Intact, Bullish Breakout, Bearish Breakout, Bullish Then Bearish, Bearish Then Bullish, or Both Sides Broken.

Breakout confirmation supports two modes. Closed-candle confirmation requires a candle close beyond the Asian High/Low and reduces wick-driven false signals. Wick confirmation triggers on a high/low breach and is earlier but less reliable.

Applicable to markets with clear session transitions: major FX pairs, JPY/AUD/NZD crosses, XAUUSD, and liquid indices. M15 is the default for signal quality; M5 is for entry refinement; M30 is slower but stronger; M1 is mainly noise.

Operational notes: align session times to broker serv...

πŸ‘‰ Read | Quotes | @mql5dev
❀19πŸ‘8πŸ‘Œ1
Static spread filters miss context: the same 3-pip spread can be a rare spike on EURUSD but normal on GBPJPY. This design replaces fixed limits with a rolling, per-symbol spread distribution, blocking trades only when the live spread is expensive relative to recent behavior.

CSpreadHistogram maintains a constant-time rolling histogram via bin counters plus a circular buffer for eviction, enabling percentile ranks and thresholds without sorting. A WARMING state prevents false alarms until enough ticks are collected, while GREEN/YELLOW/RED map to normal, elevated, and blocked execution conditions.

CSpreadMonitor orchestrates multiple symbols using SYMBOL_SPREAD for precision, exposing IsOrderAllowed() and live stats (median, rank, alert threshold). A CCanvas-based dashboard renders a summary table and per-symbol histogram on a timer, keeping tick-path logi...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘7πŸŽ‰1πŸ‘Œ1
This article replaces magnitude-based indicators with an ordinal view of price: each rolling window is reduced to the rank order of its values, preserving local shape while discarding scale and drift. The resulting ordinal patterns are stable under monotonic transforms and less sensitive to small noise.

Patterns are mapped to unique IDs using Lehmer code, enabling any embedding dimension d. Consecutive pattern IDs form a directed, weighted transition network (a Markov chain over shapes), stored efficiently and guarded by strict minimum-data checks and flat-window handling.

From this network, the implementation extracts bounded complexity metrics, including normalized permutation entropy as a market-efficiency gauge and time-irreversibility as a regime detector, then delivers them as MT5 indicators. A key takeaway is practical tuning: initial FX test...

πŸ‘‰ Read | AppStore | @mql5dev
❀15πŸ‘6πŸ‘Œ2πŸ‘€1
ML trading models often fail at the worst time because they are not interpretable. Backtests can look stable, then regime shifts make LSTM, SVM, Random Forest, or deep nets hard to diagnose or fix under pressure.

A practical alternative is symbolic modeling: train a regular model, then extract an explicit equation. With polynomial features plus Ridge for price and LogisticRegression for direction, SymPy can convert coefficients into readable formulas like f(RSI, MACD, volatility, interactions).

Once an equation exists, standard math tools apply: sensitivity via derivatives, stability checks via Hessians, and controlled edits when market structure changes. Tradeoffs remain: feature explosion, compute cost, noise sensitivity, and reduced clarity as expressions grow.

πŸ‘‰ Read | AppStore | @mql5dev
❀17πŸ‘6⚑1πŸ‘Œ1πŸ‘€1
In MetaTrader 5 build 6090, we've conducted an extensive analysis and audit of the platform's code, resolved identified issues, and implemented internal updates aimed at enhancing the stability, reliability, and performance of MetaTrader 5.

In addition, we've introduced several improvements to the desktop version of the platform:

β€’ Expanded the set of MCP methods available to the AI Assistant. In particular, it can now add indicators to charts and get a list of available indicators with their parameters.
β€’ Fixed bugs and improved built-in AI Assistant functionality.
β€’ Disabled AI Assistant support on Windows 7, as this OS version is outdated and does not support the necessary functions.
β€’ Fixed Windows 7 support. If the previous version of the platform does not launch, do not uninstall it β€” simply install the new version over the existing one. All settings will be preserved.
β€’ Fixed Signals showcase rendering.
β€’ Updated Python integration package.
β€’ Updated interface translations.

Discuss the update...
❀48πŸ‘15πŸ‘Œ1
Liquidity levels remain a core reference for short-term price action. Previous day high/low and previous week high/low are commonly watched areas where resting orders can accumulate, making them practical anchors for intraday context.

The Draw On Liquidity (DOL) indicator automates plotting of PDHL and PWHL and adds session β€œkill zone” windows for Tokyo, London, and New York. This reduces repetitive manual chart work and standardizes level placement across instruments.

Configuration covers visibility toggles for daily/weekly highs and lows, line style/width/color, and label size/color. Session markers use custom start/end times, with a selectable lookback for prior sessions. Output aims for a clean chart layout with grouped inputs and minimal visual noise.

πŸ‘‰ Read | Quotes | @mql5dev
❀24πŸ‘8⚑1πŸ‘Œ1
BreakoutDistance.mq5 adds an operational readout on top of a standard Donchian channel: current distance to each breakout level, shown in raw price units and normalized by ATR.

The panel prints upper and lower channel values, distance from the current bid to each edge, the same distance in ATR units, and a 10-cell proximity bar that fills as price approaches the trigger. Normalization via ATR makes readings comparable across volatility regimes and symbols, reducing false β€œclose/far” interpretations driven by session conditions.

Channel boundaries are computed from closed bars only (Shift >= 1), avoiding repainting. Visual state is managed via chart objects with a unique prefix per instance, optional background, and color thresholds for near (<= 1.0 ATR) and very near (<= 0.5 ATR). Optional alerts can fire when very near, with once-per-bar gating.

πŸ‘‰ Read | CodeBase | @mql5dev
❀10πŸ‘9⚑1πŸ‘Œ1
Quant Pro Dashboard consolidates trading KPIs into a single on-chart panel, reducing context switching during analysis.

Account intelligence automatically reads account number and broker details. Performance tracking updates balance, equity, and floating PnL in real time. Trade management shows open positions and closed trade counts at a glance. Market awareness includes live spread, daily PnL percentage, and network latency (ping).

Implementation targets minimal overhead with sub-millisecond execution and layout rules designed to avoid text overlap. UI uses a high-contrast black panel with neon outline for consistent readability across chart themes, plus an optional quote section.

Deployment is drag-and-drop onto any chart, auto-aligned top-right with no additional configuration.

πŸ‘‰ Read | Quotes | @mql5dev
❀17πŸ‘7πŸ‘Œ1
BlueMoon EA is an MT5 Expert Advisor built around EMA Envelope boundary checks to trigger reversal-oriented entries, with automated basket recovery for adverse movement. Signal generation and basket control are combined with configurable risk limits and account protection.

Core functions include automatic BUY/SELL entries, adaptive basket management, progressive lot sizing, configurable grid distance, per-trade take-profit, and basket-level profit targets. Operational safeguards cover spread filtering, maximum basket size and lot caps, drawdown protection with optional trading lock, and state recovery after terminal restarts. Support is included for broker symbol suffixes and MT5 hedging.

A real-time dashboard reports EMA/envelope levels, spread, basket metrics, drawdown, status, and recent activity. Configuration covers EMA period, deviation, lot model, gr...

πŸ‘‰ Read | Signals | @mql5dev
❀18πŸ‘6πŸ‘Œ1
The article builds an MQL5 exporter that turns MetaTrader 5 history into a single JSON report of closed trades over a chosen date range, with optional symbol and magic filtering. It targets trade-level records (not raw deals) so the output loads directly in Python, R, or Excel.

Closed trades are reconstructed by pairing entry/exit deals via DEAL_POSITION_ID. Missing stop-loss or take-profit on deals is fixed with a reliable fallback: if DEAL_SL/DEAL_TP are zero, the script reads ORDER_SL/ORDER_TP from the originating order referenced by DEAL_ORDER.

The JSON includes metadata plus a trade array with ISO timestamps, readable direction, separated profit/commission/swap, and precomputed R-multiple and pip profit, using null when risk is undefined. File output uses ANSI text to avoid UTF-16 parsing issues.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘6πŸ‘Œ2πŸ‘¨β€πŸ’»1
Mapper converts a point cloud into a compact graph, but the highest sensitivity sits earlier: the lens and the cover. A lens assigns one scalar per point; a cover slices the lens range into overlapping intervals and records point membership.

Three lens options are used: eccentricity (mean distance), density (Gaussian-weighted neighborhood), and a coordinate projection. Intrinsic lenses cost O(N^2) over an existing distance matrix and can collapse on symmetric clouds, producing zero range and a single-bin cover.

The cover is controlled by resolution (interval count) and gain (overlap). With gain>0, points appear in multiple intervals and later become shared membership for edges. Practical starting values: resolution 5–15 and gain 0.2–0.5, with checks for degenerate lenses and expected double counting from overlap.

πŸ‘‰ Read | Signals | @mql5dev
❀14πŸ‘€4πŸ‘3⚑2✍1πŸ‘Œ1
False breakouts often occur during trend transitions, where velocity changes precede visible structure. A proposed approach pairs Divergence Mapping with a Temporal Fusion Transformer style attention layer to produce an alternative forecasting metric and a Trade Robot output.

The divergence engine computes a lookback slope for price and for momentum indicators, normalizes price slope by the window baseline, then takes the slope differential as a structural discrepancy. A sensitivity threshold gates signal validity rather than single-point breakout confirmation.

The TFT proxy consumes three time states and applies fixed attention weights (0.55/0.30/0.15) to form buy and sell scores with strict mutual exclusivity. An MQL5 implementation emphasizes passing arrays by reference to reduce memory churn.

RSI and DeMarker are used to separate closing consens...

πŸ‘‰ Read | Quotes | @mql5dev
❀29πŸ‘4πŸ‘Œ3
The article presents the Bison Algorithm (BIA), a population-based optimizer for single-objective continuous search, built around two behaviors: fast exploration and a defensive clustering phase that stabilizes and refines good candidates.

BIA splits the population into a swarm group (about 80%) that moves toward a target and a runner group (about 20%) that probes new regions with a slightly perturbed direction vector. If a runner outperforms the swarm’s weakest member, it is promoted into the swarm.

The MT5-style implementation exposes clear controls (population size, swarm ratio, elite size, max step). Iterations combine weighted elite-centroid tracking, bounded step updates with rollback on worse fitness, and sorting to preserve top solutionsβ€”useful for robust parameter optimization in trading systems.

πŸ‘‰ Read | Forum | @mql5dev
❀27πŸ‘5⚑3πŸ‘Œ1
A trend identification indicator is available for classifying buy-side and sell-side conditions using signals derived from the stochastic oscillator.

The logic relies on stochastic readings to determine direction and potential turning points, helping separate upward momentum phases from downward momentum phases.

Typical usage includes filtering entries to align with the detected direction, combining with a separate confirmation method, and validating behavior across multiple market regimes. Parameters such as %K, %D, smoothing, and threshold levels should be reviewed for the target instrument and timeframe.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22✍1πŸ‘1πŸ‘Œ1
Deterministic backtests produce a single realized path and can overstate risk-adjusted metrics. A validation battery addresses this by evaluating distributions, not one sequence.

Permutation testing uses sign-randomization on per-trade P&L to build a no-edge null for order-independent statistics like Sortino. Bootstrap resampling estimates metric stability via percentile and BCa confidence intervals. Monte Carlo trade-sequence shuffling keeps trade outcomes fixed but randomizes order to quantify drawdown sensitivity to sequencing.

All modules consume a trade-level CSV exported from MT5 deal history. An EA-side include writes one row per closed trade and supports multi-core optimization via a contention-safe file-open. Only Trade_Profit_USD and Indicator_Name are required; no strategy logic changes needed.

πŸ‘‰ Read | Freelance | @mql5dev
❀18πŸ‘Œ1
Chart Replay Pro (MT5 Strategy Tester, visual mode) received a major update focused on manual backtesting parity with live-trading controls.

Changes include runtime lot adjustment without restarting tests, per-position trade management, and an order workflow supporting buy/sell stop and buy/sell limit orders. UI is built with bitmap-based CbmpButton plus #resource inclusion, and a read-only edit field for lots.

Key implementation notes: OnChartEvent is not processed in Strategy Tester, so entry and TP/SL are adjusted via plus/minus buttons instead of draggable lines. Global state variables are used to prevent tick-driven UI bugs and to keep selected ticket, TP, and SL stable while actions execute.

πŸ‘‰ Read | Quotes | @mql5dev
❀20⚑1πŸ‘Œ1
Symbolic Aggregate approXimation (SAX) converts a price window into a short word via z-normalization, PAA segmentation, and Gaussian breakpoint discretization. The result is countable patterns with a lower-bounding distance (MINDIST) for pruning similarity search.

A practical MQL5 implementation fills missing platform primitives: probit-based Gaussian breakpoints, robust PAA for non-divisible lengths, flat-window rejection, and integer-coded symbols to keep distance math stable.

Applied to markets, normalization removes level and volatility, which can invalidate naive trading use. This is handled by evaluating forward outcomes in ATR units and enforcing a strict no-lookahead constraint when collecting precedents.

The analog search uses MINDIST as a fast filter, then computes full distances only for survivors, producing a distribution-based forecas...

πŸ‘‰ Read | Calendar | @mql5dev
❀17⚑1πŸ‘Œ1
Forex returns rarely have constant variance, so MSE-based regressors silently optimize the wrong objective. This article replaces that assumption with a probabilistic MLP that outputs both the conditional mean and a feature-dependent variance, trained via Gaussian negative log-likelihood.

The network uses a linear head for the mean and Softplus for strictly positive variance. Backprop is extended with explicit gradients for both outputs, enabling custom-loss training instead of relying on built-in MQL5 loss helpers.

Training is integrated with ALGLIB’s L-BFGS through parameter packing/unpacking plus a separate callback to log true per-iteration loss. A sample MT5 indicator trains on normalized price increments and plots forecasts with 95% confidence intervals, giving traders risk-aware signals, not just point estimates.

πŸ‘‰ Read | VPS | @mql5dev
❀15πŸ‘Œ2