MQL5 Algo Trading
534K subscribers
3.74K photos
6 videos
3.75K 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
Adaptive optimizers address uneven feature dynamics by changing per-parameter learning rates during training, reducing stalls near local minima seen with fixed-step SGD. Common options include AdaGrad, RMSProp, Adadelta, and Adam, with Adam combining moving averages of gradients and squared gradients using typical settings β1=0.9, β2=0.999, α=0.001, plus ε.

An Adam update path was added alongside existing backprop, focusing on weight updates. The OpenCL kernel keeps weight, gradient, input, and moment buffers, uses float4 vectorization, and applies a precomputed bias-correction factor from the host to avoid per-neuron recomputation.

Code changes include training-method selection, moment buffer lifecycle management, save/load compatibility, and matching logic in non-OpenCL classes. Network construction passes the chosen optimizer through layer descriptors.

Testin...

👉 Read | AlgoBook | @mql5dev
👍2523👀5👌1👨‍💻1
High win rate and a smooth equity curve do not reveal whether a system is increasing size after losses or averaging into a losing move. This script derives those behaviors directly from closed-trade history.

It reads a closed-position CSV and prints a report in the Experts tab covering: volume escalation after a loss (martingale signature), overlapping same-direction exposure (grid/averaging signature), payoff asymmetry (many small wins versus an outsized loss), and a heuristic risk-of-ruin estimate at the configured risk per trade. A composite A–F grade combines all dimensions and outputs recommendations.

Input expects a CSV in MQL5\Files named via InpCsvFileName (default RuinAuditorSample.csv) with header: OpenTime,CloseTime,Symbol,Type,Volume,OpenPrice,ClosePrice,Profit. If missing on first run, a reproducible demo trade book is generated and analyzed. A...

👉 Read | NeuroBook | @mql5dev
24👍4👌2
Thomas DeMark’s Sequential, as described in “The New Science of Technical Analysis”, models a trend from early acceleration through a potential reversal. The pattern uses four stages: Setup start (close vs. close 4 bars back), 9-bar Setup completion, an intersection (“crossover”) condition, then a 13-count Countdown with a signal arrow.

Implementation notes include MQL4/MQL5 indicators plus optional Murray-Gann or equivalent fractional levels (8 parts with ±1/8 and ±2/8 extensions). Levels are used to qualify where price sits inside a range rather than labeling direction only.

Practical trading rules commonly cited: stops at the most extreme candle in the full pattern; entries via next open, post-bounce open, or a 2-bar extreme break; exits on opposite Setup completion without breaking the signal extreme, or after breaking it with a new opposite signal...

👉 Read | Forum | @mql5dev
53👍11👨‍💻6👌43👀21
Trend validation can be tightened by measuring moving-average slope instead of relying on crossovers. A Simple Moving Average is sampled against a prior value, converted to an angle via arctangent, and used as a trend-strength gate. Angles near zero indicate range conditions and block trading.

Entries are evaluated only on candle close. A trade requires three concurrent filters: angle beyond a threshold (with a secondary minimum angle check), close positioned on the correct side of the SMA, and a capped percent deviation to avoid late entries during acceleration. Position sizing supports fixed lots or equity-based risk.

Risk control applies staged stop management: move to protected break-even after a profit threshold, tighten on rising deviation levels, add extreme-deviation protection, and relocate stops when price crosses the SMA against the posi...

👉 Read | Freelance | @mql5dev
17👍5🤔1👌1
A MetaTrader 5 Expert Advisor implements the original Turtle Trading rules with two breakout systems: System 1 uses 20-day entries with a “skip rule” after a profitable breakout, while System 2 trades every 55-day breakout. Both exit via shorter counter-breakouts (10/20 days) and share identical risk logic.

Risk control is volatility-based. N is computed as a Wilder-smoothed 20-day True Range, then used for 1% equity risk per unit, a 2N hard stop, and pyramiding up to four units by adding only after favorable moves (N/2 steps) with a unified stop that tightens as units are added.

The code is structured into clear modules (N calculator, system detectors, unit manager, exit monitor) with state tracking to keep signals, stops, and the skip rule consistent. Backtesting on EURUSD highlights expected trend-following traits: low win rate, larger winners, and drawd...

👉 Read | AlgoBook | @mql5dev
14👍7👨‍💻2👌1
Managing many MT5 charts is slow with the default workflow: symbols are buried in Market Watch, opening a chart takes several steps, and closing or switching between dozens of charts quickly clutters the workspace.

The article builds a centralized chart dashboard EA that opens/closes charts and searches symbols from a single panel, reducing clicks and keeping multi-symbol analysis organized.

Implementation is modular: shared UI constants, a symbol manager that loads/sorts and case-insensitively filters instruments, a chart manager wrapping ChartOpen/ChartClose and scanning open charts, and a panel class handling rendering, scrolling, events, and cached open/closed status for fast refreshes.

👉 Read | Calendar | @mql5dev
28👍72👌1🏆1
A multi-pair MT5 EA can’t rely on one ATR multiplier: each symbol’s price behavior differs, so fixed stops end up too tight on volatile instruments and inefficient on calmer pairs.

This system solves it by learning a per-symbol “volatility signature” from 1000 H1 bars. It extracts range, body/wick structure, true range, close-to-close variance, gaps, pullback depth, trend persistence, and dispersion, then classifies the market regime (volatility, noise, trend, momentum).

Those labels feed a stop-loss optimizer that adjusts a base ATR multiplier with capped bounds, then uses live ATR for the final distance. Position sizing inverts stop distance to keep account risk constant. Entries stay independent: MACD crossover gated by EMA trend, processed per-symbol via isolated contexts, timers, and reusable indicator handles, with a dashboard for inspection/debugging.

👉 Read | AlgoBook | @mql5dev
29👍7👾4👨‍💻2👌1
The EA is extended with chart-side visibility of simulated option “levels”, so traders can track the current price relative to strike and rebalancing bands. Levels are plotted as intraday horizontal segments with numeric labels, rebuilt daily after recalculating historical volatility.

Option level prices are derived from target delta values by inverting a sigmoid-based delta model. Separate up/down solvers handle delta asymmetry around the strike, using a bisection search for stable, monotonic convergence instead of algebraic inversion.

Two practical structures are added for testing: Long Straddle (direction-agnostic breakout beyond the HV range, risk tied to rebalancing losses) and Short Straddle (range trading inside HV, profit from oscillations, theoretically unlimited loss if price trends out of range).

👉 Read | CodeBase | @mql5dev
47👍6👌5🏆4👨‍💻1
An indicator provides statistics on closed trades with filtering by magic number. The output is focused on finalized positions only, excluding open exposure and floating P/L.

Filtering by magic number allows separation of results across strategies, EAs, symbols, or account contexts that share the same history. This supports cleaner attribution of performance when multiple systems trade concurrently.

Configuration is handled through input parameters, typically covering the target magic number, the reporting range, and which metrics to display, such as trade count, net profit, profit factor, average win/loss, maximum drawdown on closed equity, and streak statistics.

👉 Read | Docs | @mql5dev
24👍5🎉21👌1
Channel logic uses a symmetric triangular-weighted moving average over 2×HalfLength+1 bars as the center line. Band width is derived from an adaptive, EMA-style variance of positive/negative deviations, plotting Center ± (Deviation multiplier × StdDev).

Signal rules are closed-form: Sell triggers when a bullish bar pushes High above the upper band, followed by a bearish close. Buy triggers when a bearish bar pushes Low below the lower band, followed by a bullish close. Arrow offsets scale with ATR(20) for consistent readability.

MTF mode computes the channel on a selectable higher timeframe via CopyRates(), with optional linear interpolation to avoid stair-stepped lines. Optional filters include minimum band width, tick-volume confirmation, and cooldown. Implementation is single-file MQL5, chart-window indicator, cached MTF updates, and proper handle...

👉 Read | AppStore | @mql5dev
29👍6👌2👨‍💻1
A reusable MQL5 include file (.mqh) targets risk management and position sizing across multi-asset portfolios, with consistent results on accounts using non-USD base currencies and on brokers that apply symbol suffixes such as .pro or .ecn.

The module uses a triangular currency conversion engine to translate the instrument’s profit currency into the account currency. It checks direct, inverse, and USD cross paths to produce an accurate tick value, reducing sizing errors caused by currency mismatches.

Key methods include CalculateLotSize for risk-percent sizing from balance and stop distance, GetConversionRate for automatic path resolution, ExtractSuffix to normalize broker symbols during lookups, and CheckDrawdownLimit to block new trades when equity drawdown exceeds configured limits.

Deployment is via MQL5\Include\, then include the header, create the cl...

👉 Read | Quotes | @mql5dev
18👍5👀2👌1
Crow Search Algorithm (CSA) is presented as a swarm-based global optimizer inspired by crows that remember good “cache” locations, follow other agents, and sometimes force random detours to prevent premature convergence. Its appeal is a small parameter set and straightforward implementation, making it suitable for iterative tuning problems in trading.

The MQL5 design centers on S_CrowMemory to persist each agent’s best position and fitness, plus a C_AO_CrowSearchAlgorithm class with configurable population size, flight length, and awareness probability. Core methods cover initialization, randomized opponent selection, position updates via either guided moves toward another crow’s cached best or full random relocation, and a revision step that updates both per-crow memory and the global best solution.

👉 Read | NeuroBook | @mql5dev
👍98👌31
Media is too big
VIEW IN TELEGRAM
Introducing metatrader.com — a new destination for traders, investors, and MetaTrader users.

The homepage gives you a complete view of the markets at a glance. Track U.S. stocks, forex, indices, metals, and commodities from a single hub.

Every instrument comes with a fully featured interactive chart. Use drawing tools, including trend lines, channels, Fibonacci levels, and other analytical objects.

Read news and analysis from more than 30 international providers, including Reuters, Bloomberg, Yahoo Finance, and others.

Visit the portal today and discover a new hub for financial analysis and trading.

Discuss the video:
👉 MQL5.community for traders
👉 MetaQuotes official YouTube channel
18🔥6👍3🏆3👌21🤣1
Market-neutral trading can be built on empirical return distributions instead of directional forecasts. Returns are computed over a fixed horizon, collected from history, sorted, and converted into percentiles to place a two-sided grid at statistically likely price levels without assuming a Gaussian model or ignoring fat tails.

Order sizing uses inverse probability weighting: frequent, near-mean levels trade small; rare tail levels trade larger, tempered with a square-root factor and an aggressiveness multiplier. In MT5 terms, BUY LIMITs map to negative-return percentiles, SELL LIMITs to positive ones, with optional BUY/SELL/NEUTRAL bias.

The system stays adaptive by expiring and rebuilding grids as distributions drift, and manages risk via side-specific and global profit targets, order timeouts, position/volume caps, deviation limits, and news-awa...

👉 Read | Signals | @mql5dev
15👍5🎉3👌2
Most MT5 change detectors label regime breaks after they’re visible. This article targets live trading with Bayesian Online Change-Point Detection (BOCPD), updating each bar using only past data and returning a calibrated probability that the current regime just ended.

BOCPD tracks a posterior over run length (bars since last change). A constant hazard rate sets expected regime duration, while a conjugate Normal-Gamma model yields a fast Student-t predictive score that reacts to shifts in mean or volatility.

Implementation is a standalone MQL5 CBOCPD class: capped run-length to keep cost bounded, log-space math to avoid underflow, and a warm-up status to prevent misleading early signals. Uses include a live regime monitor, a self-resetting adaptive average, and a risk overlay that reduces exposure on detected instability.

👉 Read | Calendar | @mql5dev
16👍12👌4👨‍💻1
MetaTrader 5 keeps closed-trade details in History, but built-in export emits HTML that Excel imports as text, triggers conversion prompts, and forces manual date and numeric cleanup. Copy-paste loses structure and does not scale.

An MQL5 script can export directly to XLSX by reconstructing trades from deal history. Trades are paired via DEAL_POSITION_ID, with SL/TP retrieved using a two-pass lookup: read DEAL_SL/DEAL_TP first, then fall back to ORDER_SL/ORDER_TP via DEAL_ORDER.

XLSX avoids CSV type inference by writing explicit cell types, Excel date serials with styles, and a bold header row. The implementation separates trade reconstruction, SpreadsheetML XML generation, and ZIP packaging into distinct modules, producing a file that opens in Excel or Google Sheets without conversion steps.

👉 Read | CodeBase | @mql5dev
15👍8👌1
Beginner MQL5 EAs often compile, trade, and backtest, yet still fail live due to missing architecture around execution, validation, and risk controls.

A moving-average crossover example highlights four common issues: repeated entries from per-tick evaluation, no position awareness, fixed SL/TP that ignores volatility, and no result checking on trade operations.

Key hardening steps: add new-bar detection, isolate trades with a Magic Number, count positions by symbol and direction with optional hedging rules, and replace static stops with ATR-based distances.

Production readiness also requires validation of indicator buffers and BarsCalculated(), CopyBuffer() checks, SymbolInfoTick() pricing snapshots, NormalizeDouble() on levels, and detailed error logging when orders are rejected.

👉 Read | NeuroBook | @mql5dev
45👍101
Mediana & Parallel Lines MTF is an MT5 indicator that plots higher-timeframe parallel channels on the current chart using only the last two closed candles of each selected timeframe (MN1, W1, D1, H4, H1, M30, M15).

For each timeframe, three lines are drawn with identical slope: a Median line through (Open+Close)/2, plus High and Low lines offset from the second-to-last candle’s High and Low. The slope is derived from the median change between the two reference candles and is extended to the right as a projection.

Timeframes can be enabled independently with per-timeframe colors, plus global line width and style. A safety rule hides channels that are not higher than the current chart timeframe. Calculations run once per new bar, objects are cleaned up on deinit, an info panel lists active channels, and the logic avoids repainting by using closed bars ...

👉 Read | CodeBase | @mql5dev
18👍5👌5👨‍💻2
Clock (Spread).mq5 is an MT5 chart utility indicator that places a corner label with two live metrics: time remaining until the current bar closes and the current spread in points (Ask − Bid) shown in parentheses.

The timer is updated once per second via EventSetTimer(1), keeping the countdown active even without incoming ticks, and it also refreshes on each tick through OnCalculate. Output follows formats like “04:32 (12)”, indicating 4 minutes 32 seconds to bar close with a 12‑point spread.

No plots are drawn on the chart (indicator_plots 0). A single OBJ_LABEL is created, with a per chart/symbol/timeframe unique name derived from a configurable prefix to prevent object collisions across multiple instances.

Configurable inputs cover font name, size, color, and X/Y pixel offsets from the top-left corner.

👉 Read | CodeBase | @mql5dev
29👍6👌1
SniperGold SMC ProPlus is an MT5 chart indicator that renders Smart Money Concepts structure and an optional setup readout. All BOS, CHoCH, sweeps, and signals are confirmed on fully closed candles, so plotted output does not change after bar close.

Chart objects include internal and swing structure lines, HH/HL/LH/LL labeling with strong/weak highs and lows, internal and swing order blocks (optionally volume-weighted), fair value gaps on the current timeframe or projected from a higher timeframe, equal highs/lows with resting liquidity levels, sweep markers, premium/equilibrium/discount zones, and prior day/week/month highs and lows. A multi-timeframe bias panel supports three higher timeframes.

The setup panel outputs BUY/SELL/WAIT with entry, SL/TPs, R:R, and a confluence score. Signals are gated by objective steps such as sweep, CHoCH, OB/FVG tap in t...

👉 Read | Signals | @mql5dev
22👍13👨‍💻2🎉1👌1
The article breaks down the Blue Monkey metaheuristic for optimizing discrete trading robots, mapping the method’s “teams, leaders, offspring, and migration” into a structured search process. A population is split into groups that explore in parallel, while a separate offspring set injects new candidates and replaces weak adults when it improves fitness.

Implementation details focus on an MT5-ready design: a C_AO_BM class extends a base optimizer, exposes tunable population size, group count, and offspring ratio, and manages per-agent state via arrays for position, fitness, velocity (Rate), and adaptive weights.

Core iteration alternates between Moving and Revision: initialize bounded discrete parameters, then update positions by steering each agent toward its group leader (offspring toward the best child) using velocity-based updates plus random factors...

👉 Read | AppStore | @mql5dev
21👍7👏1👌1