MQL5 Algo Trading
534K subscribers
3.75K 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
MetaTrader 5 exposes open positions in the Trade tab, but that view stays inside the terminal and forces constant context switching in multi-monitor setups.

A practical workaround is an Expert Advisor that reads PositionsTotal() on every tick, collects each position via PositionGetTicket(), then pulls fields with PositionGetDouble/Integer/String. Live values like POSITION_PRICE_CURRENT and POSITION_PROFIT update without extra state.

The EA generates a complete HTML document in memory and writes it in one FileWriteString() call using FILE_WRITE to avoid partial renders during browser reloads. The page self-refreshes with a small JavaScript setInterval() timer.

Output is self-contained: inline CSS, no external assets, optional row tinting by profit sign, and HTML escaping for free-text comments to prevent markup breakage.

πŸ‘‰ Read | Signals | @mql5dev
❀28πŸ‘6πŸ‘Œ1
Range breakout research starts with formalization, not opinions. The key step is turning β€œtrade breakouts” into explicit rules for range construction, breakout validation, stops, exits, and position management.

A baseline model should stay minimal: build a time window range, place buy/sell stops outside bounds, then manage with trailing stop and time exit. Filters are excluded to measure whether the breakout mechanic has edge.

An effective framework separates range construction from execution. A dedicated CBoxSession module can encapsulate boundaries, timing, expiration, and breakout state, with GMT-based session inputs for broker portability and logic to skip weekend or irregular bars.

Testing should target trade count, not calendar years. Rough guidance: 300–700 trades for optimization, 50–100 for forward checks. For sizing, fixed risk per trade based on...

πŸ‘‰ Read | Freelance | @mql5dev
❀17πŸ‘15πŸ‘Œ2
The automated MT5 optimization pipeline for a multi-currency EA is refined to reduce friction in real use: cleaner project/library separation, faster iterations, and better visibility into long optimization runs.

A key fix removes hidden coupling between repositories by letting project code define default inputs (like DB name/path) via constants, while the Adwizard library provides safe fallbacks. This keeps the library reusable across strategies without edits.

Optimization tasks can now be time-boxed per stage. A new max-duration field is added to the SQLite tasks table, propagated through task creation, and enforced by checking elapsed time and forcing a stop when limits are exceeded. This trims wasted genetic runs.

Process monitoring is upgraded from Comment() to a full-chart scrollable console dialog, showing detailed current-task info and han...

πŸ‘‰ Read | AppStore | @mql5dev
❀26πŸ‘5πŸ‘Œ2πŸ‘€2✍1
This article ports Mark Minervini’s SEPA Trend Template into a rule-driven MetaTrader 5 EA, turning an 8-point discretionary checklist into a strict pass/fail filter. The core idea is structural selectivity: price and the 50/150/200 SMAs must align, the 200 SMA must be rising, and price must be both well off the yearly low and near the yearly high, filtering for sustained, leader-like trends.

For forex, the missing IBD Relative Strength condition is replaced with RSI(14) > 50, and the VCP entry is simplified to a close above the prior 20-bar high with volume at least 1.5x its 20-bar average. The EA logs exactly which condition blocks each setup, uses ATR-based stop sizing with fixed risk, and exits on a close below the 50 SMA with volume confirmation. Backtests highlight the expected behavior: few signals on D1, long idle periods, and occasional qualified tr...

πŸ‘‰ Read | Freelance | @mql5dev
❀35πŸ‘18πŸ‘¨β€πŸ’»5πŸ‘Œ3😁2
Trading plan outline based on the Asian session range (01:00–05:00 GMT). The range is defined during this window, with execution reserved for the London or New York session open to avoid low-liquidity conditions.

Entry is placed at the 60% (0.6) Fibonacci retracement of the established range. Risk is controlled with a stop loss set below the 80% (0.8) Fibonacci level to limit invalidation.

Profit taking targets a fixed 1:5 risk-to-reward multiple. This structure standardizes entries, enforces consistent risk parameters, and supports repeatable backtesting across instruments and days.

πŸ‘‰ Read | Forum | @mql5dev
❀39πŸ‘10πŸ‘¨β€πŸ’»2πŸ‘Œ1
Smart Trend Score is a lightweight MT5 indicator that reports market state in a single text line at the chart’s upper-left corner. It avoids arrows, trend lines, and extra objects, focusing on BUY, SELL, or NO SIGNAL with a confidence score and computed trade levels.

Signal logic uses multiple filters to limit false positives: fast/slow linear weighted moving averages, trend confirmation, market structure (HH/HL/LH/LL), ADX strength, ATR volatility, and price action checks. Signals are produced only after candle close, with a multi-factor score from 0 to 100 and a configurable minimum threshold.

Risk parameters are calculated automatically: entry, stop loss in points, and take profit based on the selected risk/reward ratio. Configuration includes text placement, Arial font sizing, colors, and optional popup, push, and email alerts limited to one per ...

πŸ‘‰ Read | Quotes | @mql5dev
❀29πŸ‘10😱3πŸ†2πŸ‘1πŸ‘Œ1
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
πŸ‘25❀23πŸ‘€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
❀25πŸ‘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πŸ‘Œ4⚑3πŸ‘€2✍1
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πŸ‘8πŸ‘¨β€πŸ’»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
❀29πŸ‘7⚑2πŸ‘Œ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πŸŽ‰3⚑1πŸ‘Œ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
❀30πŸ‘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
πŸ‘9❀8πŸ‘Œ3⚑1
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
❀19πŸ”₯6πŸ‘3πŸ†3πŸ‘Œ2⚑1🀣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