MQL5 Algo Trading
510K subscribers
3.41K photos
3 videos
3.41K 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 OBJ_RECTANGLE is a static chart primitive. It provides no state, no breakout confirmation, no aging, and no distinction between manual edits and automated updates. This pushes ongoing chart maintenance into OnTick workflows.

A managed zone model wraps each rectangle in a CZone class stored in CArrayObj. The object holds cached coordinates, ATR-scaled sizing, breakout counters, source flags, and a structural state machine (VIRGIN, BROKEN, INACTIVE). A blacklist prevents deleted auto-zones from being recreated.

Synchronization can poll rectangles each tick (SyncHybridObjects) to adopt user objects, capture drags, and remove missing items. Production designs typically move this to OnChartEvent for create/drag/delete events to reduce GUI API overhead.

πŸ‘‰ Read | Signals | @mql5dev
❀29πŸ‘8πŸ‘Œ1
Dynamic Fair Value Gap (FVG) indicator for MetaTrader 4 focuses on identifying unmitigated price imbalances using a 3-candle pattern. Bullish gaps are calculated between Candle 1 high and Candle 3 low, while bearish gaps use Candle 1 low and Candle 3 high. Zones are plotted as rectangles with labels for quick validation.

Mitigated zones are removed automatically once price revisits the area, keeping charts limited to active FVG levels. Untouched zones extend forward by a configurable number of bars (default 18) to maintain visibility during live movement.

Additional context levels include previous daily high/low lines, refreshed at each day change. Alerting is supported via platform notifications when a new FVG forms. Key inputs include BarsToKeep (history scan), ForwardBars (projection length), and RectangleFill (filled vs outline).

πŸ‘‰ Read | NeuroBook | @mql5dev
❀20πŸ‘4πŸ‘Œ2✍1
Inside Bar pattern detection has been automated into a chart indicator focused on breakout setups and fixed signals after candle close.

The tool flags each Inside Bar, applies a directional bias from the small candle’s open/close (bullish, bearish, or neutral), and draws a projection rectangle based on the mother candle’s high/low with configurable forward extension. Optional chart labels are placed next to each zone.

Alerting is supported across common channels (popup and sound) with options to limit noise, including label-only-on-new-bar and filters that hide neutral signals. Chart clutter controls include keeping only the last N rectangles.

Configuration covers colors (auto by direction or manual), rectangle fill, forward bars, bars-to-keep, labels, alerts, and direction filtering. Works across symbols and timeframes, with an optimized loop targe...

πŸ‘‰ Read | Quotes | @mql5dev
❀17πŸ‘5πŸ‘Œ3
Retail pattern recognition often collapses into the gambler’s fallacy: after several bullish candles, a bearish reversal is treated as statistically β€œdue”. This is intuition-driven and ignores conditional probabilities.

Quant desks typically model price as a stochastic process. Markov chains apply the memoryless assumption: the next state depends on the current state plus an empirically measured transition matrix, not on the full sequence that led there.

Implementation focuses on state classification (bullish vs bearish expansion), a rolling transition matrix computed over a localized window, and a real-time probability readout for the next bar. Output is typically two percentage lines that quantify continuation vs reversal odds.

Operationally, it works best as a trade filter. If a strategy produces a sell signal while the matrix shows a high bul...

πŸ‘‰ Read | Calendar | @mql5dev
❀23πŸ‘5πŸ‘Œ2⚑1
A new MT5 Expert Advisor replaces the native chart panel with an embedded TradingView chart rendered through a WebView2-based HTML container using the official widget.

Symbol selection, seasonality view, and dark/light theme switching are handled inside the terminal, reducing the need to run a separate browser window.

The package also includes date-based licensing. If the current date falls outside the authorized period, the EA disables operation until a valid license window is restored.

πŸ‘‰ Read | AppStore | @mql5dev
❀30πŸ‘11πŸ‘Œ3πŸ‘1
This article replaces large indicator vectors with chart screenshots, letting a CNN learn directly from price context. Images are labeled Buy/Sell using trend-extreme events and daily highs/lows, then split into train/validation and a separate sequential β€œresponse” set for later strategy work.

A compact CNN is built in Keras/TensorFlow (449x449 RGB input, 3 conv+pool blocks, 64-neuron dense layer, dropout, sigmoid output) and trained with binary cross-entropy. GPU support via Anaconda dramatically reduces iteration time, making architecture tuning practical.

Model outputs are exported to CSV, plotted in MT5 as an indicator, and converted into tradable signals (e.g., line crossover) for EA optimization. Feature-map visualization helps debug chart design; consistent, distinct colors improve what the CNN can separate.

πŸ‘‰ Read | AppStore | @mql5dev
❀45πŸ‘12πŸŽ‰2πŸ‘Œ2
Stochastic of Moving Average indicator implemented as a reusable class for EA integration. Intended for use as a filter and can be combined with the free HLPeak_Trend indicator.

No iCustom() dependency. Runtime updates are handled through .Update(int shift), with shift=0 typically used in Expert Advisors. The design supports access to current and previous values via buffer indexing (0=current, 1=previous).

Input parameters cover period configuration and price source: parPeriod, parKPeriod, parDPeriod, parSlowingPeriod, and parPrice (ENUM_APPLIED_PRICE).

Outputs include bufStoc (stochastic), bufStoK (K line), bufStoD (D line), and bufStoDir for directional state mapping: 2 strong up, 1 weak up, -1 weak down, -2 strong down.

πŸ‘‰ Read | VPS | @mql5dev
❀36πŸ‘11πŸ’―2πŸ‘Œ1
Multi-Head Attention extends self-attention by running several parallel attention β€œheads” with independent weights, then concatenating their outputs and applying a final projection matrix to combine perspectives. This helps a model capture different dependencies in market sequences before producing a single decision tensor.

The article shows a practical MT5/OpenCL implementation that reduces computation by removing the explicit Keys tensor and training a single matrix where possible, while noting the trade-off when dimension reduction makes separate matrices cheaper.

For time-series, positional encoding is added to preserve distance information between candles using deterministic sine/cosine vectors, summed with inputs to avoid widening tensors.

Implementation details include a dedicated multi-head class, OpenCL kernels for concatenation/deconcatenation, and opt...

πŸ‘‰ Read | Docs | @mql5dev
❀56πŸ‘11✍6πŸ‘Œ3⚑2
A common approach for consuming news in a trading or automation stack is a scheduled web request to a remote endpoint, followed by local persistence and XML export.

Implementation typically includes HTTP GET with explicit timeouts, response code validation, and UTF-8 handling. Payloads are parsed as JSON, XML, or HTML depending on the source, then normalized into a compact internal structure with stable keys, timestamps, and de-duplication based on ID or checksum.

Stored records can be exported to XML using a fixed schema, proper escaping, and deterministic ordering. Production setups also add retry with backoff, rate limiting, and a cache layer to reduce repeated downloads.

πŸ‘‰ Read | Signals | @mql5dev
❀21πŸ‘6
Part 2 extends the breakeven subsystem with two dynamic modes and a selector to standardize configuration.

CBreakEvenAtr implements ATR-based levels. Fixed-point distances are replaced by two ATR multipliers: one for activation distance and one for the final breakeven stop offset. The class manages an ATR handle, a one-element buffer, and an ATR index for CopyBuffer reads. SetSimple supports either a ready handle or period-based handle creation, while Set(MqlParam[]) switches using a HANDLE_INSTEAD_OF_PERIOD flag.

CBreakEvenRR adds an RRR trigger and optionally computes the breakeven offset via points or ATR, controlled by an enum. Add() validates StopLoss presence, reads ATR when enabled, checks stop distance vs activation distance, then computes break_even_price and price_to_beat.

A CBreakEven selector class stores per-mode MqlParam arrays, allocates th...

πŸ‘‰ Read | Signals | @mql5dev
❀32πŸ‘4✍3πŸ‘Œ3
The article moves a MetaTrader 5 market simulation project into a database-driven stage, using the platform’s built-in SQLite to avoid DLLs or sockets while keeping full SQL control.

It demonstrates creating/opening a database via DatabaseOpen, choosing storage scope (RAM vs terminal Files vs COMMON\Files) through flags, and handling failures cleanly. Table creation is then executed with DatabaseExecute, separating simple commands from future query workflows.

A key design choice is wrapping SQLite access in a class. This encapsulation centralizes the database handle, prevents misuse, and prepares the codebase to switch later from file-based SQLite to a DLL build or client-server databases over sockets with minimal refactoring.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀15πŸ‘4⚑2
CATCH extends multivariate time-series anomaly detection with frequency-domain processing. Data is transformed via FFT, partitioned into frequency patches, and analyzed to separate low-frequency structure from high-frequency deviations. Anomalies are flagged by reconstruction error after the inverse transform.

Channel dependencies are handled by an adaptive masked-attention module that learns inter-series correlations while suppressing noise. Attention is constrained to matching frequency patches across variables, improving robustness for coupled signals such as financial instruments.

An MQL5/OpenCL implementation continues with a complex-valued multi-head masked attention object. Q/K/V are generated by complex convolution, masks by a real-valued conv layer with sigmoid and zero-initialized weights. Kernel scheduling merges segment and head dimensions to apply at...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀24πŸ‘7
Fixed RSI/Stochastic thresholds break in trends because they ignore volatility, leaving oscillators pinned at extremes and triggering repeated counter-trend entries. A Z-Score normalizes price deviation by rolling standard deviation, giving a volatility-aware mean-reversion signal: (Price - SMA) / StdDev, with extremes treated as anomalies rather than guaranteed reversals.

The implementation defines a strict β€œsignal contract”: symmetric Β±2.5 thresholds, calculations on closed bars only (shift=1), and safeguards for missing history and zero StdDev. The math is isolated in a CZScore class (include file) to reuse identical logic in both an indicator and an EA, avoid code duplication, and manage object lifetime to prevent memory leaks.

An indicator validates behavior visually and optimizes CPU using prev_calculated. The EA uses CTrade, runs once per ba...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘12
This article builds an MT5 weekend-gap indicator that turns Friday-close vs Monday-open discontinuities into persistent chart structures, so older gaps stay readable as the week evolves.

Gaps are detected from session time breaks (>= 48 hours) rather than day-name rules, then filtered by a minimum pip threshold with digit-aware pip sizing. Each gap is stored as a record with boundaries, midpoint, and an active-week flag.

Instead of buffers, the framework uses chart objects (rectangles, lines, labels) to keep multiple gaps visible and independently editable. A simple state machine updates the active gap in real time (fresh, partial, reaction, filled) and restyles objects on transitions.

Lifecycle handling is explicit: one-time historical scan on first calculate, tick-by-tick state updates, week rollover promotion to historical zones, and full cleanup...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘8
Traditional money management in MT5 often reduces risk only after closed losses, which can be too slow for pattern-based strategies. The article builds CMoneySuffixAE, a custom Wizard-compatible money module that sizes positions proactively using current market structure instead of loss counters.

The model combines two real-time checks. A suffix automaton indexes β€œPrice DNA” (Up/Down/Flat sequences) in linear time, letting the EA measure how familiar the latest 16-bar pattern is and scale lot size from exact historical repetition without expensive O(nΒ²) scans.

An autoencoder adds structural risk control. It reconstructs normalized recent prices and uses reconstruction error as an anomaly signal; when geometry breaks (news shocks), confidence collapses and position size is aggressively cut before losses accumulate.

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘22❀20πŸ‘Œ5
Quantum XAUUSD Silver Trader is a multi-indicator Expert Advisor for XAUUSD and XAGUSD on MT5, combining RSI, ADX, fast/slow moving averages, and a volatility filter into a single weighted decision. Separate presets are applied per metal to account for different volatility profiles, while a configurable threshold gates trade entries.

The weighting is adaptive: recent closed-trade outcomes adjust the contribution of each component, aiming to reduce overreliance on any single signal.

Risk controls are part of the core design. Orders use ATR-based stop loss and take profit, plus an adaptive ATR trailing stop. Account protection includes daily and total drawdown limits, daily loss limits, a position-size cap, and an optional hard stop. A micro/cent mode targets small deposits, with conservative defaults of 0.5% risk on Gold and 0.3% on Silver, typically on M15 an...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀26πŸ‘5πŸ‘Œ4
Exchange Market Algorithm (EMA) is a population metaheuristic modeled as a trading session: agents are ranked by fitness, split into elite, middle, and beginners, then updated with group-specific rules while elites remain fixed to preserve the best solutions.

Each iteration runs two modes. In a balanced market, the middle moves toward a random elite mentor, while beginners blend guidance from elite and middle. In a fluctuating market, the middle either copies the global best or samples around the elite centroid; beginners use resets, wide local searches, or opposition moves away from poor regions.

Exploration-to-exploitation is controlled by a sigmoid decay rate. An MQL5 C_AO_EMA class encapsulates parameters (r1/r2, riskAlpha), initialization, movement, and revision/sorting. Tests show modest but consistent improvement as problem size grows under a ...

πŸ‘‰ Read | Signals | @mql5dev
❀22πŸ‘6✍3
Many EAs treat overnight swap as an afterthought, even though it can materially change expectancy on multi-day trades, especially on high-differential pairs like AUDJPY. Swap is effectively daily interest: long positions can earn credit, shorts often pay, and triple-swap rollovers must be projected inside the holding window.

The article shows how to make swap actionable in MQL5 by reading SYMBOL_SWAP_LONG/SHORT plus SYMBOL_SWAP_MODE, then converting broker-specific units into a per-lot, per-day value in account currency. It handles common retail modes (points, deposit currency, interest-based using the 360-day convention), warns and returns 0 for reopening/margin modes, and notes where currency conversion or open-price accuracy is required.

Four drop-in building blocks tie this into real EA decisions: daily swap calculation, expected swap over a planned hol...

πŸ‘‰ Read | CodeBase | @mql5dev
❀23πŸ‘5πŸ†2
This part turns multifractal diagnostics into simulation-ready inputs for MMAR. A new Spectrum Fitter converts the scaling curve Ο„(q) into the singularity spectrum f(Ξ±) via a discrete Legendre transform (central differences, low-q filtering, and rejection of invalid negative f(Ξ±) points).

The empirical f(Ξ±) is then matched to four parametric cascade models (Normal, Binomial, Poisson, Gamma). Each fit minimizes SSE using ALGLIB’s BLEIC optimizer with strict parameter bounds to keep solutions physically meaningful.

A CSpectrumFitter class encapsulates the pipeline and selects the best distribution by lowest SSE. On EURUSD M10, the Binomial model wins, yielding Ξ±_min/Ξ±_max that quantify spectrum width and directly control cascade heterogeneity, supporting realistic volatility clustering with negligible extra runtime versus partition analysis.

πŸ‘‰ Read | Calendar | @mql5dev
❀14πŸ‘5
Cooperative MARL is moving toward offline multi-task training, driven by the cost of new environment interaction and poor scaling when agent counts or objectives change. Transformer-based models help, but many pipelines still miss task-specific structure and the temporal buildup of coordination.

HiSSD (Hierarchical and Separable Skill Discovery) proposes joint, hierarchical learning of shared cooperation skills and task-specific skills from offline datasets. Modules are trained end-to-end, with a multi-agent IQL-style value model, a planner selecting high-level skills, and a controller trained via VAE objectives plus contrastive separation across tasks.

An MQL5-oriented adaptation maps agents to univariate market sequences, adds controlled cross-sequence information exchange via masked attention (CATCH), then produces per-agent skill vectors with independent conv...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀25πŸ‘4
This article adds β€œdiscipline” to MetaTrader 5 EAs by separating strategy signals from an equity governance layer that supervises execution during stress. It tracks peak equity, drawdown, daily loss, and rapid equity drops, then drives a four-state machine: NORMAL, CAUTION, RESTRICTED, LOCKDOWN.

The design is modular: monitoring and analysis feed a state engine with cooldown and recovery checks (hysteresis to avoid flip-flopping). CAUTION scales risk via lot multipliers, position caps, and trade spacing; stricter states can block entries while still allowing position management.

Implementation uses a clean MQL5 library of specialized classes plus a thin EA wrapper. A single Authorize() call becomes the trade gate, with hard limits as an immediate backstop. A built-in SMA test engine and on-chart dashboard make behavior easy to validate in backtests.

πŸ‘‰ Read | Signals | @mql5dev
❀33πŸ‘5πŸ†3