MQL5 Algo Trading
580K subscribers
4.68K photos
7 videos
4.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
Automatic object placement removes the manual dependency from earlier chart-object pipelines. The system generates pitchforks, trendlines, Fibonacci, channels, and support/resistance directly from detected swing structure, then routes them through the same evaluators used for user-drawn objects.

A modular layout is used: swing detection, object placement, market data caching, signal evaluation, topology management, and adaptive execution. Swing detection relies on cached OHLC arrays to avoid repeated iHigh/iLow calls and identifies highs/lows via strict neighbor comparisons.

TopologyManager coordinates placement, scanning, evaluator lifecycle, and signal processing, with throttling to limit redraw and scan overhead. Chart events trigger immediate refresh to remove timer polling latency.

AdaptiveTrade calculates instrument-aware SL/TP using point size, s...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀31πŸ‘5πŸ‘Œ5πŸ”₯2
MetaTrader 5 keeps full tick history in its cache, but exporting it for external analysis is bottlenecked by CSV size, slow parsing, and rounding from text conversion. A binary export solves this with fixed-width records: ~48 bytes per tick versus ~60+ in CSV, faster loads, and exact IEEE-754 price preservation.

The script defines a simple file format: a 64-byte header (magic ID, version, symbol, digits, tick count, time range) followed by contiguous 48-byte tick records (time_msc, bid/ask/last, volume, flags, padding). This enables direct random access and zero-parse reading in Python via NumPy.

Implementation is modular: separate structs for header and tick layout, then an exporter that uses CopyTicksRange(COPY_TICKS_ALL), writes the header with FileWriteStruct, and writes tick batches with FileWriteArray for high throughput.

πŸ‘‰ Read | Freelance | @mql5dev
❀28πŸ‘8πŸ‘Œ4
Mean-variance allocators can become unstable when instruments are highly correlated, due to covariance matrix inversion. Small estimation noise can translate into large, leveraged long/short weights that flip across windows.

Hierarchical Risk Parity (Lopez de Prado, 2016) avoids inversion. The workflow converts prices to simple returns, builds covariance and correlation matrices, clusters instruments via a correlation-to-distance transform, then forms a binary merge tree using single-linkage.

Tree order drives quasi-diagonalization, pushing correlated instruments into blocks. Recursive bisection allocates capital across blocks using cluster variance from an inverse-variance sub-portfolio and a covariance quadratic form, producing long-only weights that sum to 1. A rebalancing EA can apply the output per basket.

πŸ‘‰ Read | Docs | @mql5dev
❀19πŸ‘10πŸ‘Œ1
ACCS (Artificial Coronary Circulation System) is a bio-inspired metaheuristic by Kaveh and Kooshkbaghi (2019). Candidate solutions are modeled as arteries/capillaries, with Coronary Growth Factor (CGF) used to weight solution quality and influence search dynamics.

Core mechanics: random population init, center position calculation, CGF normalization, then alternating global search (direction based on CGF vs center) and local search (update toward best and away from worst with an iteration-dependent factor). Pruning reverts worsening moves.

Implementation uses Heart Memory to retain the top solutions (default 25% of population, minimum 1). Data structures separate persistent best states from temporary trial positions, followed by a selection phase that commits global-search candidates and refreshes memory by fitness sorting.

πŸ‘‰ Read | Calendar | @mql5dev
❀24πŸ‘8πŸ‘€2πŸ‘Œ1
An indicator calculates the Asian session range (default 00:00–08:00 server time) and plots the high/low as horizontal levels. It then monitors the London session for confirmed breaks and retests of these levels, generating buy/sell signals intended for manual scalping around the London open.

The current session range is drawn on-chart with breakout and retest highlights. Signals are fixed on closed bars with no repainting. Supported timeframes include M1, M5, and M15 across any symbol.

Key inputs include SessionStartHour and SessionEndHour for range definition, optional EMA-based trend confirmation, and an optional volume filter to avoid low-activity moves. SignalMode supports alerts, push notifications, or arrows only. Default trade management levels can be set via StopLevelPips and TakeLevelPips.

πŸ‘‰ Read | Quotes | @mql5dev
❀24πŸ‘8🀣3πŸ‘¨β€πŸ’»2πŸ‘Ύ2⚑1πŸ‘Œ1
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