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
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
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
❀60πŸ‘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
Price-series matching remains fragile under level shifts, time stretching, and noise. A practical alternative uses symbolic representations: z-normalize each window, keep low-frequency Fourier coefficients, then quantize them into short words via per-coefficient, data-fitted breakpoints (SFA with MCB).

BOSS converts a series into a sparse histogram of word counts using a sliding window. Numerosity reduction prevents consecutive identical words from dominating. Distance is asymmetric, summing squared count differences only over words present in the query, then applying 1-NN classification.

Single-window BOSS is parameter-sensitive, so an ensemble trains multiple window sizes, scores them with leave-one-out accuracy, retains members near the best, and votes. The approach is benchmarked against DTW for regime labeling such as trending, ranging, and vo...

πŸ‘‰ Read | Signals | @mql5dev
❀39πŸ‘20⚑2πŸ‘Œ2
Just three weeks after the official launch of MCP support and the built-in AI Assistant, MetaTrader 5 users have already processed more than 1 trillion tokens through the free MQL5 Lite model.

To understand the scale, 1 trillion tokens is roughly equivalent to:

β€’ 700–750 billion English words
β€’ 2.5–3 billion pages of text, assuming 250 words per page
β€’ Around 9 million books with 80,000 words each
β€’ Nearly 7,000 years of continuous reading at 200 words per minute

These figures show how actively thousands of MetaTrader 5 users are applying AI Assistant for a wide range of tasks β€” from market analysis to developing trading robots.

No API keys or third-party service setup are required to get started. Just sign in to MetaTrader 5 with your MQL5.com account, and the free MQL5 Lite model is available automatically.

Explore the capabilities of agentic AI for trading and programming.

Read more...
❀405πŸ‘54πŸ”₯21πŸ‘Œ21πŸ‘¨β€πŸ’»21✍16⚑15
MetaTrader 5 exposes OHLC and volume, but not exchange liquidation or open interest. Liquidity zones can only be estimated from on-chart data.

A Liquidity Heatmap approach flags candles where volume exceeds a moving average, then projects an estimated long/short liquidation price using candle direction plus an assumed leverage. Signals are ranked via a rolling buffer: HD mode uses raw volume, Normal mode uses volume delta.

Visualization relies on chart objects: lines for levels and tiered bubbles for strength. Levels extend forward until swept, then stop updating. Object limits, timestamp de-duplication, and per-bar processing reduce redraw and tick overhead. Output is probabilistic and should not be treated as confirmed liquidations.

πŸ‘‰ Read | AppStore | @mql5dev
❀70πŸ‘22✍5πŸ‘Œ4😁3πŸ”₯2πŸ€”2
Backtesting a custom MQL5 indicator in Python often forces a reimplementation that can drift due to bar indexing, rounding, or warm-up rules. A cleaner approach is to export the exact indicator buffers calculated by the terminal and read them in Python as-is.

An MQL5 script can attach via iCustom(), wait using BarsCalculated(), fetch rates with CopyRates() and buffers with CopyBuffer(), then write a locale-stable CSV to MQL5/Files/. Avoid FILE_CSV; format numbers with DoubleToString() and write full lines with FileWriteString().

Handle warm-up by converting EMPTY_VALUE to empty fields so pandas loads NaN. iCustom() parameter forwarding needs a fixed-arity dispatch block due to compile-time call signatures.

πŸ‘‰ Read | CodeBase | @mql5dev
❀45πŸ‘17✍5🀝4πŸ‘€3πŸ‘Œ2
TimeFound reframes forecasting as a foundation-model problem: a Transformer pre-trained on diverse time series can produce usable predictions even with little or no asset history, enabling zero-shot forecasts for newly traded instruments.

Core mechanics combine encoder–decoder attention with multi-resolution patching, capturing fast spikes and slow trends simultaneously. Standardization aligns scales across domains, while relative positional attention preserves temporal relevance and the decoder enforces causal generation.

Training blends point accuracy (MSE) with quantile loss to output uncertainty bands alongside forecasts.

The MQL5 implementation replaces costly patch replication with parallel multi-window convolution for aligned multi-scale features, then uses a multi-head residual feed-forward block and convolution/max-pooling aggregation for low-l...

πŸ‘‰ Read | VPS | @mql5dev
❀32πŸ‘9πŸ‘Œ3πŸ”₯1
MQL evolved from early β€œExpert Advisor” concepts into an integrated environment where strategy code runs inside the terminal, with direct access to market series, indicators, and order execution. The key shift was treating automation as native, not an external add-on.

Early MQL was minimal, but MetaTrader 2 introduced MQL II with loops, arrays, richer types, and math functions, enabling real program logic per tick. MetaTrader 3 then expanded beyond execution into research by adding custom indicators and file I/O.

MetaTrader 4 and MQL4 completed the transition to a developer workflow: a structured language with user functions, scripts, libraries, DLL calls, plus MetaEditor bundling compiler, help, and tooling. Community infrastructure (MQL4.COM, Code Base, forums) and the automated trading championship validated autonomous trading at scale and push...

πŸ‘‰ Read | AppStore | @mql5dev
❀31πŸ‘15πŸ”₯3πŸ‘Œ2😁1
Reinforcement learning in algo trading shifts strategy creation from fixed rules to continuous updating from trade outcomes. An MQL5/MetaTrader 5 implementation uses a multi-agent layout with experience stored as discrete β€œmemory neurons” and aggregated into independent decision agents.

Each neuron encodes a quantized 32-bit market state, a continuous action value (sell to buy), activation stats, and a score combining hit rate and usage frequency. Inputs are built from mostly stationary features (RSI, CCI, stochastics, MACD, ATR, Bollinger position, MA relations, fractals, ADX, WPR, normalized returns).

Learning is modified Q-learning with staged exploration, epsilon control, class-balance correction, and pruning when memory exceeds 1,000 nodes. Ensemble voting weights agents by recent success to reduce single-model bias.

πŸ‘‰ Read | Forum | @mql5dev
❀37πŸ‘11✍2πŸ‘Œ2πŸ‘¨β€πŸ’»2πŸ‘€2
Indicator architecture follows an event-driven, sequential pipeline split across OnInit, OnCalculate, and OnTimer, with additional tick-level checks for alerts.

OnInit sets chart precision from _Digits, removes legacy objects prefixed with β€œSMC_OB_”, and initializes buffers plus state arrays.

OnCalculate iterates from prev_calculated - 1 for incremental updates. A price-boundary filter skips non-essential work when price remains between prev_valid_high and prev_valid_low, reducing CPU usage.

Market structure uses a rolling 3-bar window (vb1/vb2/vb3) keyed by datetime for stable swing tracking across reloads and timeframe changes. Order blocks are derived from swing confirmation plus displacement and a measurable FVG. Nested zones are filtered by comparing FVG size and deactivating weaker blocks.

Mitigation scans bars against active zones with body ...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘18❀17πŸ”₯4πŸ‘€2⚑1πŸ‘Œ1
A mean-reversion signal indicator pairs Bollinger Bands with an embedded Stochastic RSI and triggers only after a close returns inside the band following an oscillator extreme.

Bearish logic: the prior bar closes above the upper band while StochRSI %K and %D are above the upper limit, then the current bar closes back inside. Bullish logic mirrors this below the lower band with both lines under the lower limit. Arrows are plotted on the signal bar and offset by a fraction of ATR(14) to avoid candle overlap.

Everything is calculated in a single .mq5 file: Bollinger Bands with shaded fill and basis line, StochRSI built from RSI plus rolling stochastic and double SMA smoothing, and an on-chart panel with live BB/ATR values, %K/%D zone, armed setup flags, and last signal details. Signals are evaluated on closed bars, with no trade execution or order manag...

πŸ‘‰ Read | Docs | @mql5dev
❀32πŸ‘10πŸ‘Œ2πŸ†2