MQL5 Algo Trading
513K subscribers
3.47K photos
3 videos
3.48K 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
Many technical indicators are known to generate false signals. Geometric signal validation is used to filter these in real time, keeping valid signals unchanged while rejecting candidates that imply an impossible zigzag leg.

Signals from an indicator should be treated as candidate pivots, not immediate entries. Candidate highs and lows are connected using zigzag-based state logic. If accepting a candidate would create a geometric inconsistency, the candidate is classified as unsafe and the pivot search state does not change.

Pivot confirmation occurs only when a leg completes and the search state switches. Confirmed pivots are marked with arrows, while rejected candidates are marked with an arrow plus an X. The method is indicator-agnostic; Donchian channel signals are used here as an example.

๐Ÿ‘‰ Read | Signals | @mql5dev
โค30๐Ÿ‘6
Competitive Learning Algorithm (CLA) is a population-based optimizer that structures candidates as students grouped into classes. Updates combine three signals: movement toward the class teacher (best member), a delayed personal-best component, and optional inter-class guidance via an average-teacher vector.

A reference implementation (C_AO_CLA_l) exposes popSize, numClasses, beta, gamma, and deltaIter. Each iteration updates teachers, computes class costs and normalized ranks, then adjusts agent coordinates with progress-dependent Teaching/Confirmatory factors plus boundary and step constraints.

Benchmarks at 10,000 function runs show solid early convergence but frequent stagnation later from local trapping. Aggregate score reported: 3.96687 (44.08%), with results improving as dimension scales from 5 to 500 across Hilly, Forest, and Megacity suites.

๐Ÿ‘‰ Read | AlgoBook | @mql5dev
โค21๐Ÿ‘6
Directly calling the MT5 History API inside analytics methods creates hidden terminal-state dependencies: results silently break without the right connection, history cache, or HistorySelect() range. This makes unit tests, edge cases, and long-term maintenance costly, especially when brokers or deal classifications change.

The design is refactored using dependency inversion: analytics modules depend on an ITradeRepository interface, not the History API. A shared STradeRecord struct standardizes trade data and returns safe defaults on invalid access.

CLiveTradeRepository isolates all HistorySelect/HistoryDeal* usage behind two helpers, while CMockTradeRepository serves deterministic in-memory datasets for CI and edge-case simulation. Consumers (analytics engine, risk, equity curve panel) run unchanged, with comparable net-of-cost metrics and negligible dispa...

๐Ÿ‘‰ Read | Freelance | @mql5dev
โค33๐Ÿ‘8
This article outlines an MQL5 Expert Advisor that adds a quantitative filter to ICT-style setups. Instead of trading solely on Fair Value Gaps, Order Blocks, and liquidity pools, it measures whether price has enough โ€œpath capacityโ€ to actually reach the target liquidity.

Market structures are detected automatically (swings, FVGs, OBs, equal highs/lows) and converted into nodes of a directed graph. Edges between nodes get capacity scores from tick volume, prior reaction strength, travel distance, and structure importance, then Edmonds-Karp (Ford-Fulkerson) computes maximum flow from current price (source) to nearest liquidity (sink).

Trades require both: valid ICT direction and flow above a threshold. The EA skips bottlenecked paths, compares bullish vs bearish flow, supports multi-timeframe weighting, and sizes positions dynamically based on flow strength.

๐Ÿ‘‰ Read | Freelance | @mql5dev
โค29๐Ÿ‘5
Weekend gap fill logic can be formalized into an MQL5 indicator that detects Friday close vs Monday open gaps, tracks them until fully filled, then writes non-repainting buy/sell signals to EA-readable buffers via CopyBuffer().

Implementation uses four buffers (buy, sell, gap state, fill price), explicit buffer initialization with EMPTY_VALUE, and non-series indexing to avoid off-by-one errors. A gap record struct stores boundaries, direction, lifecycle state, fill time/price, and a โ€œsignal publishedโ€ flag.

Processing is split into historical reconstruction on first run and incremental updates on new bars. A simple state machine (fresh, partial, reaction, filled, historical) drives transitions and arrow plotting, with optional alerts and an InvertSignals switch for reversal vs continuation testing.

๐Ÿ‘‰ Read | Docs | @mql5dev
โค19๐Ÿ‘11๐Ÿ‘Œ3๐Ÿ‘€1
Multivariate market series now routinely exceed what ARIMA/SARIMA can handle under non-stationarity, regime shifts, and microstructure noise. RNNs improve sequence handling, while LSTM/GRU extend context but remain sensitive to feature quality and may miss decisive short-term spikes.

Attention improves long-range dependency capture by reweighting relevant features and time steps, yet can still underreact to fast shocks. DA-CG-LSTM addresses this with dual-stage attention plus a Conversion-Gated LSTM that modifies input/forget gate activations to reduce saturation and improve responsiveness.

Implementation notes in MQL5/OpenCL: split CG-LSTM into (1) linear pre-activation generation and (2) a kernel applying custom activations and state updates. Use float4 loads for bandwidth efficiency. Backprop recomputes required intermediates from pre-activations to avoid extr...

๐Ÿ‘‰ Read | AppStore | @mql5dev
โค33๐Ÿ‘9๐Ÿ‘€3
An Expert Advisor is available as a research implementation of the Inside Bar continuation hypothesis. The setup requires a two-candle pattern: a Main Bar and a Signal Bar fully contained within the Main Bar range. On a bullish Main Bar close, a Buy Stop is placed above the Main Bar high; on a bearish close, a Sell Stop is placed below the Main Bar low.

Risk controls use Stop Loss as a fraction of Main Bar range and Take Profit via a configurable Risk/Reward ratio, with TP optional. Position sizing supports fixed lots or percent risk from the starting balance captured at EA launch.

Filters include an optional ATR condition requiring Main Bar size to exceed a multiple of recent volatility, plus constraints on Main Bar body and maximum Inside Bar size. Logic runs on new bars only, with one open position and one pending order per symbol, and automatic pending ...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค17๐Ÿ‘7๐ŸŽ‰1
AFML-style microstructure features are ported from Python to MetaTrader 5 as a single include file, CMicrostructureFeatures.mqh, so EAs can compute seven bar-level signals directly from OHLCV without external dependencies. It implements Roll spread/impact, Corwinโ€“Schultz spread and intraday volatility, plus Kyle, Amihud, and Hasbrouck lambdas.

A key constraint is MT5 โ€œtick volumeโ€: it counts price updates, not trades. Lambda estimators therefore use a bar-close tick rule and tick volume as approximations, making them best for regime ranking rather than broker-comparable impact levels. Roll and Corwinโ€“Schultz remain volume-free and robust.

The design emphasizes single-pass running sums (no temp arrays), strict new-bar execution to avoid look-ahead, and clean accessors for EA/ONNX pipelines. A companion MicrostructureViewer indicator plots all features wi...

๐Ÿ‘‰ Read | VPS | @mql5dev
โค25๐Ÿ‘7โœ2
High-volatility trading exposes a gap in accessibility: no standard hands-free, low-latency input path for MQL5 tools that works under motor impairments and market stress. Mouse, keyboard macros, hotkeys, and voice pipelines add delay or fail in noisy environments.

A gesture-controlled system is presented using a webcam with MediaPipe Hands and OpenCV in Python, sending gesture codes to MetaTrader via MQL5 Global Variables. An EA polls every 10 ms and executes via CTrade, using a busy-flag and neutral reset to avoid repeated orders.

Benchmarks on an i7-1165G7 laptop (30 FPS, 640ร—480, confidence 0.7) show mean end-to-end latency and accuracy over 100 runs: Buy (index) 68 ms, 97.2%; Sell (thumbs-up) 72 ms, 96.8%; Close-all (fist) 85 ms, 95.4%. 95th percentile stays within 110 ms.

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค19๐Ÿ‘8
This article turns the NLMS-based SAMA from a textbook update rule into a production-grade MQL5 indicator designed to behave predictably in live charts. The implementation avoids common pitfalls: it never trains on the still-forming candle, seeds weights to a neutral 1/N prior to prevent startup instability, and enforces a warm-up phase to reduce session-to-session re-render differences.

Robustness is handled explicitly: NLMS energy normalization is protected with an epsilon floor, extreme one-bar shocks are capped via ATR-based error clamping, and weight leakage adds controlled forgetting. An optional constraint normalizes weights to sum to 1.0, keeping outputs on the price scale.

Tuning is practical: inputs support PRICE/DIFF/RET training, an Efficiency-Ratio adaptive learning rate, and guidance to keep ฮผ โ‰ค 1.0 for stable tracking. Limitations are ...

๐Ÿ‘‰ Read | Docs | @mql5dev
โค28๐Ÿ‘7
Part 71โ€™s weekend-gap marker is upgraded into a rule-based, automatable signal model for MT5. The indicator defines each gap using Friday close and Monday open, filters by minimum tradable size, and only confirms entries on candle close (optionally requiring a price offset), keeping signals non-repainting.

Bullish logic: after a gap-down, a bullish close back above the gap low triggers a buy. Bearish logic: after a gap-up, a bearish close back below the gap high triggers a sell. Take-profit targets the opposite gap boundary; stop-loss anchors to the current weekโ€™s swing extreme with an optional buffer.

Implementation focuses on EA integration: six CopyBuffer-readable outputs (buy/sell arrows plus TP/SL for each), historical signal reconstruction, and a structured pipeline from gap detection to live updates and cleanup.

๐Ÿ‘‰ Read | NeuroBook | @mql5dev
โค21๐Ÿ‘6
Chart objects can now be edited after placement via a floating property ribbon. The update replaces fixed-at-creation styles with descriptor-driven editing and a snapshot-based preview/rollback model.

Four components back the system: per-tool property descriptors, engine get/set by string ID, widget renderers per property type, and a ribbon that binds widgets to the selected object and applies changes live.

Descriptors define type, label, range, defaults, and visibility for ribbon vs settings. Composite types cover compact rows, per-level lists for Fibonacci/Gann, and action entries.

Engine property access resolves object ID, dispatches by property ID, supports per-level arrays, and rejects non-applicable properties cleanly. Changes can be previewed immediately and reverted on cancel.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค18๐Ÿ‘6๐Ÿ˜ฑ3
Standard indicators capture level, range, and volatility, but miss trajectory shape. Two EURUSD windows can match mean close, average range, and realized volatility while producing different phase-space paths: an elongated arc versus a closed loop.

Topological Data Analysis focuses on invariants across scales and represents signal as birth-death pairs in a persistence diagram. The prerequisite step is converting a 1D series into a higher-dimensional point cloud, then defining a distance metric over that cloud.

Takens time-delay embedding constructs vectors (x[i], x[i+tau], โ€ฆ) with user-controlled embDim and delay. The implementation uses CTDAPointCloud as a flat buffer for cache-friendly access.

CTDADistance builds an NxN symmetric distance matrix under Euclidean, Manhattan, or Chebyshev norms, tracking max distance for later filtrations.

๐Ÿ‘‰ Read | CodeBase | @mql5dev
โค22๐Ÿ‘5
CoSO (Community of Scientists Optimization) is an optimization algorithm published in 2012 by A. Milani and V. Santucci. It models a research community: agents publish to journals, compete for limited funds, form local groups, and keep diversity via funded outsiders. Population size can change during runtime.

Each agent maintains position x, velocity v, personal best b, funds m, strategy s, and journal selection probabilities ฯ. Velocity update combines inertia, cognitive pull to b, and a weighted social term from journal entries; position updates as x(t)=x(t-1)+v(t).

Journals act as shared memory, storing the top-k solutions, updated only when a submission improves the worst entry. Funds are redistributed by rank roulette; inactive agents drop out when m reaches zero. Outsider share ฮฉ adapts using fitness standard deviation, while successful agent...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค34๐Ÿ‘7๐ŸŽ‰3
The SymbolInfo sample has been reworked from a single source file plus two headers into a three-file variant where each unit now contains two functions and explicit call sites. Output rendering was also redesigned to improve readability and consistency.

Nine output fields were added. Seven are standard symbol attributes, with two additional risk-related values: Margin Required (MT4 naming) and Standard Leverage. Margin Required is derived from the symbolโ€™s Margin Calc Mode, while Standard Leverage is derived from Margin Required and may differ by volume depending on broker rules.

All formulas and calculation steps follow the standard MQL5 documentation.

๐Ÿ‘‰ Read | AppStore | @mql5dev
โค18๐Ÿ‘3๐ŸŽ‰3๐Ÿ‘€3
MetaTrader 5 does not emit mouse events for chart apps by default to protect performance, so indicators and EAs must explicitly enable only the required mouse resources and reliably disable them on shutdown. Failing to โ€œturn off what was turned onโ€ can leave a chart generating unnecessary events and degrade responsiveness.

Mouse input is received through OnChartEvent, with separate handling for move and wheel actions. Mouse coordinates are reported only inside the chartโ€™s client area, using chart-local coordinates, and values often need explicit type conversion before display or logic.

The article also covers controlled capture of mouse buttons and related UI controls. Developers can temporarily block built-in chart behaviors (dragging, context menu, crosshair, keyboard scrolling/zoom, ENTER symbol input) to avoid conflicts, but must restore default...

๐Ÿ‘‰ Read | Forum | @mql5dev
โค19๐Ÿ‘5๐Ÿ‘Œ1
This part extends an MQL5 replay/simulation stack by turning a SQLite helper class from โ€œrun scripts onlyโ€ into a component that can execute SELECT queries and expose result sets to MQL5 code.

It highlights a behavioral mismatch in MT5โ€™s built-in SQLite (Build 3815): dropping tables with active foreign-key relationships can fail when the same script is executed again shortly after, while standalone SQLite may succeed. A practical workaround is deleting the database file and recreating it from embedded SQL resources.

On the implementation side, the database is built from two embedded scripts: one for schema, one for seed data. Query support is added via DatabasePrepare for prepared statements, DatabaseFinalize to release prior statements, and a separate read step to consume results, avoiding redundant queries and improving performance for trading tools.

๐Ÿ‘‰ Read | Forum | @mql5dev
โค16๐Ÿ‘4๐Ÿ†2
DA-CG-LSTM targets dynamic multivariate time series where volatility and latent drivers degrade classical forecasting. The design combines dual attention with a modified CG-LSTM to separate relevant signals from noise while retaining both long-range dependencies and short-term reactions.

Feature attention reweights inputs per timestep, then temporal attention selects informative history windows. The CG-LSTM block adds control over memory updates using feature and time relevance, improving stability on long sequences and reducing stochastic artifacts.

Implementation work in MQL5 consolidates existing components: a linear attention module reused from Hidformer and a previously implemented CG-LSTM block. Model design extends beyond point forecasts by integrating an encoder latent space with an Actor-Director-Critic RL stack, plus a probabilistic trend m...

๐Ÿ‘‰ Read | Calendar | @mql5dev
โค18๐Ÿ‘6๐Ÿ”ฅ2
Adding timing, logging, or filtering directly into an RSI class turns one indicator into a shared container for unrelated concerns. Each edit increases regression risk, expands the test matrix across EAs, and raises merge-conflict probability. These concerns belong to usage context, not to RSI computation.

A decorator chain keeps the core indicator closed for modification. All components implement IIndicator with GetValue(shift) and GetName(). Decorators wrap an IIndicator pointer, delegate calls downward, then add behavior before or after the delegation. The EA holds only the outermost IIndicator*.

Typical stack: CTimingDecorator โ†’ CLoggingDecorator โ†’ CThresholdFilterDecorator โ†’ CRSIIndicator. Order matters: side-effect decorators observe; filters transform values. Ownership is hierarchical: deleting the outermost decorator frees the entire chain safely.

๐Ÿ‘‰ Read | AppStore | @mql5dev
โค23๐Ÿ‘7
AlternativeBarsViewer adds in-terminal inspection for the 10 alternative bar types from Lรณpez de Prado, using the same CBarConstructor hierarchy as BarBuilderEA to keep outputs consistent across EA, indicator, and Python checks.

Three data sources are supported: real ticks via CopyTicksRange with millisecond deduplication, synthetic ticks derived from chart OHLC, and replay from the EAโ€™s per-type CSV with auto reload on file size changes. Tick and OHLC modes also show the current forming bar.

Rendering uses DRAW_COLOR_CANDLES with buffers for OHLC plus a color index. Closed bars can be projected by time-slot alignment or packed sequentially by index. Colors separate bullish, bearish, and in-progress bars, and surface degenerate bars that close with minimal tick volume.

A lightweight subwindow panel reports bar stats, degenerate counts, last times...

๐Ÿ‘‰ Read | NeuroBook | @mql5dev
โค25๐Ÿ‘6
Part 2 moves from option emulation theory to a working MT5 EA that trades the underlying while tracking an emulated optionโ€™s delta. The EA converts โ€œemulation levelsโ€ into real positions and continuously rebalances to keep the synthetic exposure aligned with the selected construction (Long/Short Call/Put), using daily expiration.

The design introduces an option-construction base class built on MQL5โ€™s CList, letting developers compose portfolios and compute total delta by iterating contained options. A range-setting method normalizes delta behavior per strike, making future multi-leg strategies straightforward to extend.

On each tick, the EA updates the current level, adds or closes market positions when the level changes, and fully exits at level zero or at the forced expiration time. Practical details include lot-step normalization, magic-number encoding p...

๐Ÿ‘‰ Read | NeuroBook | @mql5dev
โค35๐Ÿ‘8