MQL5 Algo Trading
579K subscribers
4.65K photos
7 videos
4.66K 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
S.M.A.R.T. ICT/SMC V3.0 Session Manipulation & Algorithmic Reaction Tracker is a free MT5 analytical indicator that scans three configurable symbols (defaults: EURUSD, GBPUSD, USDJPY). Internal analysis is M5 by default, while the indicator can run on any chart timeframe. All logic is based on closed bars and it never opens, modifies, or closes positions.

Validation is a strict sequence: sweep of a completed Asia or London range, close through a pre-sweep swing to form an MSS, minimum displacement on the MSS candle, a three-candle directional FVG, then a later bar retest that closes beyond the FVG midpoint. Breaching the frozen sweep extreme after MSS invalidates the sequence.

A Quality Score (80–100) is produced only after completion and represents confluence within this model, not win probability. Projections define entry at the FVG-retest close, S...

πŸ‘‰ Read | Calendar | @mql5dev
❀22πŸ‘7πŸŽ‰3πŸ‘Œ3✍2🀩1
MetaTrader 5 can run ONNX models, but treats them as opaque binaries, making it hard to validate inputs, outputs, and saved weights when predictions look wrong. The article solves this by decoding ONNX directly inside MT5 with pure MQL5, avoiding external libraries.

It builds a two-layer approach: a Protocol Buffers wire reader that can parse varints, fixed-width values, and length-prefixed blocks, plus an ONNX-aware parser that reconstructs the computation graph by matching shared tensor names between node outputs and inputs.

A Python script generates a known test model with branches, mixed tensor storage formats, and type conversions, then Netron provides ground truth. The MQL5 tool can list nodes, operators, connections, and inspect weight tensor shapes, types, and ranges before risking live trades.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀22πŸ‘10
VSA_Candles.mq5 adds native candlestick bar coloring on the main chart using volume confirmation. Green marks confirmed strength signals (Down Thrust/Spring, Selling Climax, Bag Holder, No Supply). Red marks confirmed weakness signals (Up Thrust, Buying Climax, Bag Seller, No Demand). Blue highlights dojis and spinning tops for balance zones. Yellow flags classic price-action shapes without volume extremes.

A SAR-style dot trail provides a dynamic trend/stop overlay that flips and tightens based on buy/sell exhaustion. Closed-bar hover tooltips show bar time, volume vs MA multiplier, spread, and expected reaction. A left-side on-chart glossary lists pattern short and full names.

VSA_Glossary.mq5 adds a dual-direction subwindow: upward color-graded volume columns with high/ultra background clouds, and inverted spread bars with auto-scaling fill. Zero-...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘14πŸ‘¨β€πŸ’»3✍2πŸ”₯2πŸ‘€1
Setup requires compiling the source and attaching the EA to a clean chart with no indicators or objects. Operation is intended for live charts only, not Strategy Tester. Configure historical start time, session duration, and Renko brick size in price units. Use LOAD, then PLAY or NEXT BRICK. Submit BUY or SELL and advance the replay to execute a virtual entry. END closes the session, NEW starts a fresh run, and EXPORT writes the current summary.

With start set to zero, the default anchor is 09:00 on the previous weekday in broker server time, with a six-hour duration. The interval must be fully historical with broker tick data available. The panel reports balance, equity, max drawdown, closed trades, win rate, profit factor, and R results. CSV trades and summaries are saved to MQL5/Files/GDS_Renko_Trainer.

Limits include one symbol, one virtual position, and f...

πŸ‘‰ Read | Quotes | @mql5dev
❀17πŸ‘7🀩3πŸ”₯2
SSCNN targets noisy, unstable market time series by working with segments instead of single points, after decomposing data into trend, seasonality, short-term moves, and residual noise. Forecasts are built by aggregating specialized models per component, improving interpretability.

This part focuses on AttnNorm: attention-weighted normalization that learns where to focus inside each segment, stabilizing mean/variance estimates during spikes. The implementation emphasizes GPU execution via OpenCL kernels, with careful CPU↔GPU buffer setup, kernel parameterization, synchronization, and data integrity checks.

Two MT5/OpenCL layer objects are detailed. CNeuronAttentNorm computes trainable attention weights, normalizes them with SoftMax, then runs AttentNorm and AttentNormGrad kernels for forward/backward passes, delegating weight updates to the attention modul...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘10πŸ†3
CRiskCalculator is an object-oriented MQL5 header library for risk management and volume sizing in EAs and trading utilities. It computes monetary pip value and lot size from a defined cash risk and Stop Loss distance in pips.

Position sizing on cross-currency symbols is handled with a dual-engine approach. The primary path uses terminal symbol properties such as SYMBOL_TRADE_TICK_VALUE and SYMBOL_TRADE_TICK_SIZE. When broker data is missing or uninitialized, it switches to manual base/quote parsing with conversion-rate queries to produce account-currency results.

Volume output is normalized to broker constraints by clamping to SYMBOL_VOLUME_MIN and SYMBOL_VOLUME_MAX and snapping to SYMBOL_VOLUME_STEP to reduce invalid volume rejections.

The class is encapsulated as CRiskCalculator, avoids global scope noise, and auto-detects ACCOUNT_CURRENCY on initializa...

πŸ‘‰ Read | Freelance | @mql5dev
❀10πŸ‘7
Finite Volume Elements (FVE) refines classic volume analysis by weighting volume with price location inside the bar and typical-price change, then applying a CutOff threshold to ignore small fluctuations. The result is a cleaner read of accumulation vs distribution, with support for both real and tick volume in MetaTrader 5.

An extended variant, FinVolEleLinRegSl, adds linear-regression slopes for both FVE and Close, making it easier to spot when price and volume momentum align or diverge. This turns FVE from a static pressure gauge into a tool for tracking acceleration, weakening trends, and early divergence cues.

The article also shows a practical EA integration: classify each slope line as rising, falling, or turning, combine both into a discrete β€œstate,” and use that state as a direction filter for existing signals (e.g., WPR + Bollinger), ignori...

πŸ‘‰ Read | VPS | @mql5dev
❀16πŸ‘6πŸ”₯1😁1πŸ‘¨β€πŸ’»1
Cricket Algorithm (CA) is a 2015 metaheuristic by Canayaz and Karci, combining update mechanics from Bat Algorithm, global-best guidance from PSO, and pairwise attraction from Firefly. Agent interaction is computed via acoustic propagation and atmospheric absorption, with chirp rate mapped to temperature using Dolbear’s law.

Each iteration samples chirps N, derives temperature and speed of sound, then sets frequency from distance to global best. Velocity/position updates add a sound-speed term, then a strategy switch uses an absorption-derived coefficient: either sequential attraction toward all better agents with decaying noise alpha, or a local random walk around the best.

Implementation notes highlight normalization of distance, speed, frequency, and absorption to keep values bounded. A class design uses a per-agent velocity structure, parameter...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀32πŸ‘6🀩3πŸ”₯2πŸ‘€1
This article finalizes an SSCNN-based market forecaster by assembling previously built modules into a single MQL5/OpenCL Encoder designed for noisy, regime-shifting price series.

The Encoder splits input into four parallel branches: long-term trend, seasonality (phase-aligned via cycle transposition), short-term dynamics, and cross-feature β€œspatial” structure. Each branch applies normalization (including attention-based normalization where useful), then extrapolates both residuals and their statistics into the forecast horizon.

Several engineering choices stand out: replacing a trainable extrapolation matrix with a linear convolution for shared weights and GPU efficiency; using tensor transposition to separate mean/variance streams without copying; zeroing gradient buffers to avoid variance-gradient contamination; and generating horizon-wide mean ...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀19πŸ‘11πŸ”₯7πŸŽ‰1🀩1πŸ‘Œ1πŸ‘€1
PropFirm account monitoring EAs often fail in three areas: inputs get reset across restarts, identical logins on different servers cause rule collisions, and invalid percentages or threshold ordering reach drawdown math.

Part 1 establishes a strict foundation before any compliance logic runs. Runtime account state is separated from persistent rule configuration, inputs are validated during OnInit with fail-fast errors, and SQLite persistence is keyed by account login plus trading server.

Implementation covers the EA lifecycle, shared enumerations, grouped Inputs, SAccountState and SAccountSettings, UpdateAccountState(), and ValidateComplianceInputs(). It then adds database globals, OpenDatabase()/CloseDatabase(), schema creation with a composite primary key, and prepared-statement helpers.

Startup order becomes: validate, read account identity, open DB, ensu...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀21πŸ‘11πŸ”₯7🀩3✍1πŸ‘Œ1🀑1
MetaTrader 5’s dataanalysis.mqh turns ALGLIB into a practical, in-terminal research stack: preprocessing, PCA, decision forests, clustering, and more, all usable directly from MQL5.

The workflow builds a supervised dataset from bars: five numeric features per bar, then a label based on the next bar’s close-to-close return (bearish/neutral/bullish with a threshold). CBdSS standardizes only the inputs and keeps training statistics for consistent live normalization, avoiding data leakage.

PCA (CPCAnalysis) is used as a structural diagnostic to detect redundant features, not as a predictor. A random forest (CDForest) is trained via the builder API, producing OOB error for sanity checks and permutation importance to rank which measurements actually drive class separation.

The script is positioned as a template for an EA pipeline (features β†’ model β†’ decis...

πŸ‘‰ Read | AppStore | @mql5dev
🀩17❀13πŸ‘10πŸ”₯5🀑3πŸŽ‰2πŸ‘Œ1
Replay/simulation series update: position visualization is being moved out of Expert Advisors into a dedicated indicator, with a strict separation between server linkage and chart rendering.

A stability fix is added to EA initialization: on restart, stale position objects are purged to avoid mismatches after crashes or configuration changes such as contract type switches.

Interaction is implemented via custom chart events. OnTradeTransaction in the EA emits EventChartCustom on volume changes, SL/TP updates, and closures (NETTING), while initial position creation still triggers indicator placement.

The position indicator receives and filters these events in OnChartEvent, updating or deleting HLINE objects based on current position state, keeping logic testable and minimizing duplicated code across EAs.

πŸ‘‰ Read | Quotes | @mql5dev
❀23πŸ‘8πŸ”₯6🀩2
Reinforcement learning in trading remains unstable due to non-stationary regimes, sparse rewards, high-dimensional states, and costly exploration. Classical DQN can overfit to historical volatility, then fail when markets shift, with retraining downtime not viable.

A hybrid stack is proposed: quantum state encoding + Double DQN + an LLM adapted via MIT SEAL. Quantum circuits compress 6 market inputs into 6 distribution statistics; entropy is used as a regime-instability signal.

The LLM produces direction and confidence; SEAL keeps only top-reward forecasts for periodic fine-tuning, asynchronously. A minimal Q-table agent then filters signals with 27 discretized states and 3 actions: USE, SKIP, REDUCE, enabling low-risk integration into existing trading logic.

πŸ‘‰ Read | Docs | @mql5dev
❀16πŸ‘8🀩4πŸ”₯2
Index CFD backtests can look stable while quietly bleeding overnight financing. In MT5, swap modeling is hard to audit: brokers use POINTS (fixed points/night) or INTEREST (annual % of price), the optimizer cache doesn’t store swap per pass, and the tester applies today’s swap snapshot across the entire history.

A read-only MT5 script converts each symbol’s swap into an annualized % of position notional, making financing comparable across brokers and instruments. Real scans showed the same indices costing roughly -4.7% to -9.9% per year long, while shorts could be credited or charged depending on broker and symbol.

Deal-level analysis matters: in a multi-year swing test, swap consumed 44% of gross profit overall, and fully erased one index’s gains. Practical workflow: re-run best optimizer passes as single tests, inspect deals per symbol, distrust ...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀12πŸ‘5πŸ”₯2⚑1πŸ†1
MQL5 class lifetime can differ sharply between implicit instances and pointer-managed instances.

Declaring a class variable lets the compiler decide constructor/destructor timing. In an indicator, the constructor may run before OnInit and the destructor after OnDeinit, which reduces control over chart objects.

Switching to a pointer and using new/delete moves lifecycle control into OnInit/OnDeinit. Logged output confirms constructor runs after the OnInit log line and destructor runs before the OnDeinit log line.

In scripts, local scope adds another constraint: passing class instances into routines requires pass-by-reference, otherwise compilation fails. This raises API design questions around mutability and unintended state changes.

πŸ‘‰ Read | CodeBase | @mql5dev
❀9πŸ‘7πŸ”₯2πŸŽ‰2
Multi-timeframe Malaysian SNR can be automated without relying on lagging indicators. MSNR KeyLevels MultiTF scans closed candles and maintains four level types: A (bullish then bearish, close of bullish candle), V (bearish then bullish, close of bearish candle), plus SBR and RBS when a level is closed through and flips.

Levels are tracked from creation. A close through refreshes and changes the type. A touch without a break marks the level as tested and, by default, removes it so the chart keeps only untested zones. The unfinished candle is ignored to avoid repaint-style behavior.

A chart HUD controls six timeframes at once, with per-timeframe level counts and instant toggling. Line style encodes timeframe, color encodes type, and labels include timeframe and price. The design avoids tick-by-tick recalculation and rebuilds cleanly after timeframe ch...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀12πŸ‘6πŸŽ‰2
Update on the MT5 replay/simulation series focuses on why the system works: custom events are generated by indicators, routed through MetaTrader 5, and delivered to all apps on a chart via OnChartEvent.

Chart Trade, the Expert Advisor, the Position indicator, and Mouse Study remain decoupled. None of them require direct references to each other. Events are broadcast, and only modules implementing the corresponding handler react; others ignore them.

Two event categories are used: EA-originated update events after trade server replies, and UI-driven events from MT5/indicators (mouse move, click, ESC). Virtual SL/TP dragging is confirmed or canceled by subsequent events.

A requested extension is EA-controlled pause/play for the replay service. Since events are chart-scoped, the service must be reached via its control indicator by adding a custom even...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀16πŸ‘6πŸ‘¨β€πŸ’»3πŸ‘Œ2πŸ”₯1🀩1
Prop-firm risk limits add a second rulebook on top of the broker account: static and trailing drawdown from a fixed start, daily loss reset in the firm’s time zone, payout consistency, minimum trading days, news blackout, and weekend flat. Violations can void the account even when platform limits are not hit.

This library provides a reusable guard that compiles into any EA. It evaluates eight rules from one frozen account snapshot per pass and emits at most one directive, avoiding multiple reactions to the same event. It does not trade and can work alongside any EA, manual trading, or copied signals.

Archive contents: 24 .mqh headers, a facade class (CPropRulebook), and a demo EA (PropFirmDefense.mq5) with an on-chart panel. State is persisted across restarts, including trailing-floor anchoring and consumed budgets. Optional terminal Algo Trading switching ...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘8❀4🀩2πŸ†2
Colliding Bodies Optimization (CBO, 2014) is a population metaheuristic where candidate solutions are ranked, assigned normalized masses from inverse objective values, then split into stationary (best half) and moving (worst half) sets.

Each moving body pairs by rank with a stationary body. Velocities are computed from position differences, then updated with a restitution coefficient epsilon that decreases linearly from 1 to 0 across iterations to shift from broad search to refinement.

Enhanced CBO (ECBO) adds a Colliding Memory archive to reinsert elite solutions and an optional low-probability coordinate reset step to reduce stagnation. Per-iteration cost is dominated by sorting: O(n log n).

πŸ‘‰ Read | Freelance | @mql5dev
❀18πŸ‘8πŸ”₯4🀩2πŸ‘Œ2⚑1
Range volatility can be measured beyond ADR% by using an empirical percentile rank. The metric compares the current period’s range so far to the full ranges of the last N completed periods, reporting what percentage were smaller. This avoids mean-based distortion in instruments with occasional spike sessions.

Readings at or below the compression threshold (default 20) flag an unusually quiet period; readings at or above the expansion threshold (default 80) indicate a session already larger than most historical peers. A 12% value means the current range is smaller than 88% of the last 100 periods.

Key inputs include range timeframe (D1 by default), lookback (100), thresholds (20/80), and update mode (per bar or per tick). The panel includes a 0–100 gauge, uses only chart objects, and does not place or manage orders.

πŸ‘‰ Read | Signals | @mql5dev
❀14πŸ‘11πŸ”₯2🀩2πŸ†2
EMTOrdersUtility.mq5 implements an on-chart trade monitor that replaces terminal scrolling with a symbol grid. Each symbol is rendered as a button plus up to three stacked label lines, refreshed via EventSetTimer at a user-defined interval.

Symbols can be loaded from Market Watch or a manual CSV list, capped by InpMaxSymbols. Display names can be abbreviated by stripping common broker suffixes, and button width can be fixed or auto-sized based on the longest label.

Runtime updates aggregate positions per symbol, split by BUY and SELL, with swap included in P&L. Pending orders are counted separately and can be highlighted via border settings. Button background reflects net P&L state (profit, loss, flat), with a selected-symbol color override.

Version notes mention alphabetical symbol ordering and removal of the hide/show toggle.

πŸ‘‰ Read | Signals | @mql5dev
❀18πŸ‘10🀩3πŸ†2πŸ‘¨β€πŸ’»2πŸ‘Œ1