MQL5 Algo Trading
581K subscribers
4.7K photos
7 videos
4.71K 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
Symbolic Aggregate approXimation (SAX) turns a rolling price window into a short word, enabling text-style matching over market history. The pipeline z-normalises to keep shape only, applies Piecewise Aggregate Approximation to reduce dimensionality, then discretises via Gaussian breakpoints so letters are equiprobable.

Historical search uses a two-stage process: prune candidates with MINDIST, which provably lower-bounds Euclidean distance on z-normalised series, then rank survivors by true Euclidean distance. A validation harness confirms the same matches as brute force while skipping most comparisons.

The indicator scans for prior analogs with strict no-lookahead, measures each analog’s forward path in ATR units, and projects a median plus interquartile band as a fan cone. A verdict panel reports the current word, analog count and distances, forwa...

πŸ‘‰ Read | Docs | @mql5dev
❀20πŸ‘5⚑1πŸ‘Œ1
Trade Analytics Dashboard indicator reads the terminal’s closed-deal history via HistorySelect() and HistoryDealGetTicket(), aggregates results, and renders a compact on-chart panel using CCanvas. No price analysis and no order placement, modification, or closure. Since it only reads existing deals, it does not require AutoTrading permission.

Panel fields summarize the selected lookback window: trade count, win rate (at/above break-even including swap/commission), profit factor (gross profit divided by gross loss), and net P/L with visual gain/loss coloring. It also reports current win/loss streak from the most recent deal, best and worst contributing symbols, and a simple cumulative equity curve line.

Inputs are grouped for layout, data scope, and colors: anchor corner and pixel offsets, panel size, refresh interval independent of ticks, history da...

πŸ‘‰ Read | AppStore | @mql5dev
❀24πŸ‘6πŸŽ‰2πŸ‘Œ2
Session Volatility Heatmap is a measurement indicator designed to map real, symbol-specific intraday movement instead of relying on textbook session times. It loads InpLookbackDays of history on the active timeframe, groups each bar’s (high βˆ’ low) range by the hour the bar closes, and averages all 24 hourly buckets.

Output is split into two aligned views. A compact heatmap panel shows 24 hourly columns of the broker/server day: higher, warmer columns indicate historically larger hourly ranges; lower, cooler columns indicate quieter periods. Session bands are also drawn behind candles for the last InpSessionDays, marking Asian, London, and New York windows in server time; overlaps typically align with the highest-liquidity hours.

Used together, the heatmap identifies the hour and the session shading provides context. If peak hours do not match sessi...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘13⚑3πŸ‘Œ1
Most risk tooling in MT5 assumes the next worst loss will resemble the worst already observed. ATR sizing, Monte Carlo reshuffles, and historical VaR all stay inside the sampled distribution and tend to understate fat-tailed crash risk.

A native MQL5 indicator applies Extreme Value Theory using Peaks-Over-Threshold. Closes are converted into a one-sided downside loss series, exceedances above a high quantile are extracted, and a Generalized Pareto Distribution is fit with maximum-likelihood optimisation via the terminal’s built-in constrained optimiser, with no external dependencies.

It reports rolling EVT VaR, EVT Expected Shortfall, and the fitted tail shape xi with regime colouring. The engine refuses to print numbers without enough exceedances (floor of 30) and withholds ES when the fitted shape makes the mean diverge. This is a magnitude gauge for ex...

πŸ‘‰ Read | Signals | @mql5dev
❀21πŸ‘4πŸ‘Œ2
Self-Organizing Maps (SOM) give MT5 traders a practical way to compress hundreds of market features into a 2D β€œstate map” where similar regimes land close together. Each tick finds a Best Matching Unit via Euclidean distance, then a Gaussian neighborhood update nudges nearby neurons, smoothing noise and forming stable clusters for trend, decline, and range conditions.

The EA implementation uses a 20Γ—20 grid with ~400 features per sample, trains on historical bars, and adds a supervised target by looking ahead (rise/fall/flat thresholds mapped to 0.8/0.2/0.5). Live signals are gated by a confidence model and no-position checks, with periodic retraining to adapt.

Interpretability comes from exporting an interactive HTML heatmap (U-matrix style intensity), helping developers see dense clusters vs unfamiliar zones and avoid low-similarity trades.

πŸ‘‰ Read | VPS | @mql5dev
❀20πŸ‘8πŸ‘Œ1
Mantis treats market inputs as separate feature channels, then adds first-difference channels to make short-term direction and acceleration explicit. Convolution blocks extract stable micro-patterns per channel, after which the stream is split into fixed non-overlapping patches; mean-pooling turns each patch into a compact token representing a local market β€œscenario”.

Tokens are scaled, normalized, and merged into per-channel summaries, then attention lets distant patches influence each other, preserving local detail while building global context. The encoder output is used as an embedding for a trading agent rather than a pure classifier.

Decision-making is split into Encoder + Actor–Director–Critic: the Actor combines market embedding with account state to choose actions, the Director rejects unstable proposals, and the Critic scores strategic q...

πŸ‘‰ Read | Calendar | @mql5dev
❀22πŸ‘7πŸ‘Œ2πŸŽ‰1
Markov chain Monte Carlo generates samples from a target distribution by constructing a Markov chain with the desired stationary law. Unlike variational or Laplace methods, correctly configured MCMC converges in the limit to the exact target, even when only an unnormalized density is available.

Metropolis uses symmetric proposals q(x'|x)=q(x|x'), with acceptance A=min(1, p*(x')/p*(x)). Metropolis-Hastings generalizes to asymmetric proposals via A=min(1, p*(x')q(x|x')/(p*(x)q(x'|x))). Detailed balance is the core invariant.

Performance is driven by proposal tuning. Too small steps increase autocorrelation; too large steps increase rejections. Practical acceptance targets are typically 20–40%, monitored with trace plots, histograms, and ACF, plus burn-in and thinning.

An MQL5 implementation structures MH as MHSampler with LogPDF, PropRND, and optional LogPropPDF f...

πŸ‘‰ Read | CodeBase | @mql5dev
❀24πŸ‘7πŸ‘Œ3✍2πŸ‘€2
The article walks through automating the β€œJudas swing” session-open reversal in MQL5: treat the first kill-zone push as a liquidity grab, not a trend. Direction is filtered by a higher-timeframe daily bias, flipped only after a confirmed close beyond the last swing high/low.

Each kill zone (NY time with DST handling) builds a live session range, splits it into premium/discount around equilibrium, and arms only after a sweep of the session extreme into the correct zone. Entry is delayed until a market-structure shift: a close back through the last minor swing level in the bias direction.

Implementation highlights include pivot/fractal swing scanning, risk-based lot sizing, robust trade records to preserve original R for trailing/partials, session lifecycle state, and reusable chart drawing primitives. Visual backtesting validates arming, triggering, and...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘6πŸ‘Œ3
Standard indicators lag in fast markets, so this article builds a reusable Fair Value Gap (FVG) engine for MT5 that detects three-candle liquidity voids directly from price. It formalizes bullish/bearish FVG rules, computes zone boundaries plus midpoint, and avoids look-ahead by enforcing closed-bar scanning with clear series indexing and shift=1 handling.

Noise control is handled with a self-contained Simple True Range average filter, requiring gap height to exceed TR*multiplier. Zones persist until β€œmitigation,” with two configurable invalidation contracts: wick-touch or close-through.

The design is modular: an include-class core (detection, filtering, lifecycle), a diagnostic indicator that plots discrete zones using EMPTY_VALUE to prevent diagonal artifacts, and an EA template with a new-bar gate, CTrade execution, and magic-number position isolation...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀15πŸ‘4πŸ‘Œ2
Grid trading can be treated as an order-management problem: staged entries at fixed intervals, with exits defined by breakeven plus a profit target. The key variables are entry prices, lot sizing, and distance between levels, all tied to volatility and margin limits.

For a two-order grid, breakeven depends on weighted average entry and position volumes. With constraints focused on fast target hits and maximum spacing, the optimal distance scales linearly with profit but nonlinearly with volume step N, trending toward roughly half the target as N increases.

Extending to multiple pending orders adds scenarios and degrees of freedom: per-order distances, volumes, and arbitrary profit allocation. More orders can improve recovery but increases tail risk under one-way moves, requiring strict loss limits and automated management rules.

πŸ‘‰ Read | Freelance | @mql5dev
❀15πŸ‘5πŸ‘Œ2
This article shows how to push MT5 trade events to external tools in real time without blocking the EA. Trade confirmations are captured in OnTradeTransaction(), serialized to JSON, and queued immediately so the terminal never stalls during network problems.

Instead of WebRequest(), it calls WinINet (wininet.dll) via #import, avoiding URL whitelisting and reusing a single InternetOpen session handle for the EA lifetime. HTTP POST is executed from OnTimer() every 500 ms, keeping trade capture and delivery fully decoupled.

A fixed-size FIFO queue with peek-before-dequeue enables safe retries and controlled loss handling under overflow. Logging is designed around outage states: one failure message, per-trade enqueue notices during downtime, and a single recovery summary when HTTP 200 resumes.

πŸ‘‰ Read | AppStore | @mql5dev
❀20πŸ‘5πŸ‘Œ3
RSI Histogram for MT5 adds a momentum-coded histogram to a standard RSI pane, with optional display of the classic RSI line. Histogram colors reflect RSI direction: rising, falling, or flat, using a configurable Momentum_Filter to suppress noise-driven color flips.

Inputs cover RSI period, applied price, line color and width, plus histogram visibility and bar width. Level lines (upper/middle/lower) are optional, with automatic correction for invalid ordering or out-of-range values.

Performance settings include Maximum_Bars to limit recalculation on large histories while re-seeding Wilder averages at the boundary to avoid drift. Typical use remains RSI 70/30 extremes and 50 midline crosses, with the histogram highlighting sustained momentum, consolidation, and early weakening via color changes.

πŸ‘‰ Read | Signals | @mql5dev
❀16πŸ‘4πŸ‘Œ3
This article turns the Adaptive SuperTrend from a passive indicator into a self-contained MT5 Expert Advisor, embedding the full calculation engine inside the EA instead of relying on iCustom. That removes external file dependencies, improves testability in Strategy Tester, and avoids repeated buffer reads that can slow execution.

The EA is built around clean lifecycle design: structured inputs, strict handle validation in OnInit, and proper resource release in OnDeinit. It supports multi-timeframe SuperTrend computation, selectable divergence source (MPO4 or RSI), and an optional confirmation window to reduce repaint-style entries by waiting additional bars.

Core logic runs once per new bar: copy data into local arrays, compute oscillator and pivots, track divergence state, shrink the ATR multiplier only when opposing divergence is still β€œactive,” then upd...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀19πŸ‘7πŸ‘Œ4πŸ‘¨β€πŸ’»4
Gold London Breakout EA implements a session-range breakout for XAUUSD, designed around recurring Asian-session compression and early-London expansion. It records the Asian high/low between configurable server-time hours, then trades only when that window closes.

A volatility-aware filter compares the measured range to Daily ATR. If the range is below or above configurable ATR fractions, no orders are placed for the day. This avoids trading sessions with no compression or with prior expansion already in progress.

At the London start hour, the EA places OCO pending orders: BuyStop above the range and SellStop below, each offset by an ATR-scaled buffer. Once one side triggers, the other is cancelled. Stops and targets are derived from ATR at placement, with position sizing based on equity risk percent.

Orders expire at the London end hour if unfilled. Spread i...

πŸ‘‰ Read | Docs | @mql5dev
❀30πŸ‘8πŸ‘Œ2
Semi-supervised (transductive) learning uses unlabeled data to capture data structure and reduce overfitting. Vapnik argued for transduction over induction: solve the required prediction task directly, not an intermediate general function.

Practical semi-supervised setups rely on distributional assumptions: continuity (local smoothness, low-density separation), cluster structure, or low-dimensional manifolds. Common implementation is pseudo-labeling: infer labels for unlabeled samples, merge with true labels, retrain.

Active learning extends this with iterative label queries from an unlabeled pool. Standard scenarios include membership query synthesis, stream-based sampling, and pool-based sampling. Query criteria typically use uncertainty, margin, or entropy; batch variants add diversity/density or committee disagreement.

Python tooling often centers on modAL (...

πŸ‘‰ Read | Forum | @mql5dev
❀60πŸ‘14πŸ‘Œ3
Conventional bounded oscillators such as RSI, Stochastic, and CCI often lose sensitivity during trend expansion. Under heavy volume, values can remain pinned near their limits, producing repeated reversal signals that do not reflect dominant order flow. A key limitation is distributional: many classic indicators implicitly assume near-normal behavior, while market returns are non-linear and frequently non-Gaussian.

A DSP-based approach using John F. Ehlers’ Fisher Transform addresses the boundary-flattening problem by reshaping the price PDF toward a Gaussian form. Routine noise is compressed near the zero baseline while statistically extreme moves become sharper peaks. The transform is unbounded, so momentum is not clipped at arbitrary ceilings, and turning behavior is detected without moving-average phase lag.

Implementation details include a rolli...

πŸ‘‰ Read | VPS | @mql5dev
❀45πŸ‘6πŸ‘¨β€πŸ’»3πŸ€”2πŸ‘Œ2
Running multiple EAs on one account should be evaluated by risk overlap, not by isolated PnL. A practical metric is drawdown compression: sum each system’s worst losing stretch, then compare it to the worst losing stretch of the combined account over the same period. The gap between those numbers is the measurable diversification benefit, and it is typically not shown in terminal reports.

A script can compute this from closed-trade history grouped by magic number. Output includes per-system trade count, net result, and max drawdown; portfolio compression ratio; and a full pairwise Pearson correlation matrix on period PnL with summary stats and optional heat map plus CSV export.

Monte Carlo reshuffling of period results adds percentile drawdowns (50/90/95) to quantify ordering risk. Position sizing should reference the tail of that distribution, not the sing...

πŸ‘‰ Read | Quotes | @mql5dev
❀33πŸ‘4πŸ‘Œ2πŸ”₯1
Learning-rate selection remains a practical constraint in gradient-descent training: high values can cause oscillation or divergence, while very low values slow convergence and can stall in local minima. Stepwise decay is often suggested, but results vary by task.

OpenCL-based EA tests on EURUSD H1 with ~12.4k bars compared eta=0.1/0.01/0.001 and a 10x decay from 0.01 every 10 epochs. Eta=0.1 failed (error near 1). Others stabilized near 0.42; 0.001 showed marginally lower loss but missed nearly all fractals, while 0.01 produced slightly better signal behavior.

A class-imbalance adjustment (labeling β€œno fractal” as 0.5 instead of 1) reduced error to ~0.34, cut missed fractals to ~51%, and raised hits to ~9.88%, indicating data weighting can dominate eta tweaks.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀61πŸ‘13πŸ‘¨β€πŸ’»6πŸ‘Œ4🀯2πŸ†1
GoldScalpBot is an MT5 Expert Advisor for XAUUSD scalping on M5, intended for the London and New York sessions, including the overlap window.

Entries use EMA momentum with short breakout and retest filters. Exits are managed via ATR-based Stop Loss and Take Profit, with an optional time-based stop.

Risk is set as a fixed percent of equity per base trade. Position sizing scales up only after consecutive wins, with a hard cap and no martingale behavior after losses. Safety controls include a daily loss stop and a maximum spread filter.

An optional local HTTP bridge can support a companion mobile/web app for monitoring, pausing, closing trades, and adjusting SL/TP. Recommended: ECN conditions with tight XAUUSD spreads, demo-first testing, Algo Trading enabled, and WebRequest allowed to http://127.0.0.1:8765 if the bridge is used. Automated trading can result i...

πŸ‘‰ Read | VPS | @mql5dev
❀58πŸ‘5⚑3πŸ€”3✍1πŸ‘Œ1πŸ‘¨β€πŸ’»1
Crystal Structure Algorithm (CryStAl) adapts crystal formation into a population optimizer: candidate solutions act like β€œatoms” updated by four equally likely strategies that shift toward the population mean, the best solution, or the average of random neighbors (Fc). This mix targets exploration and exploitation without complex control logic.

An MT5-oriented implementation wraps it in a C_AO_CryStAl class with explicit parameter validation, mean/Fc computation, discrete step mapping, and a Revision pass that tracks both per-crystal and global bests.

Baseline tests landed near random-walk quality (~26%), exposing weak interaction and boundary handling. A revised variant changes the update formulation, adds a 10% probabilistic perturbation using power-distributed sampling around the current best, and avoids full re-randomization on bounds, improving ...

πŸ‘‰ Read | Docs | @mql5dev
❀40πŸ‘15πŸ†3πŸ‘Œ1