MQL5 Algo Trading
553K subscribers
4.01K photos
6 videos
4.02K 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
MT5 Strategy Tester covers automated backtests, but manual price-action review still lacks an interactive bar-by-bar replay mode. A replay tool can hide future candles, reveal one bar at a time, and allow decision-making without hindsight bias.

A practical MQL5 design uses DRAW_COLOR_CANDLES with buffers initialized to EMPTY_VALUE, then progressively filled to reveal candles. Controls include an ON/OFF toggle, a draggable vertical anchor for the start point, Play/Pause, and Buy/Sell for a single paper trade with Entry/SL/TP lines.

Core logic combines OnChartEvent() for UI and drag handling with OnTimer() for timed playback, viewport tracking, price line updates, and TP/SL monitoring. Deactivation restores original chart properties and removes all replay objects.

πŸ‘‰ Read | VPS | @mql5dev
❀23πŸ‘6πŸ”₯3πŸ‘Œ2
Part II extends queues into LIFO behavior by converting a FIFO implementation into a stack with minimal changes: only the read/remove point is adjusted, while insertion order stays intact.

It also notes that stacks mirror how CPUs manage call frames, which makes the data structure relevant beyond textbook exercises.

The text then moves from arrays to lists in MQL5. Because pointers to structures are restricted, classes are used to model nodes, enabling a singly linked list that behaves like a stack without relying on arrays.

Key takeaway: internal implementation can vary, but a stable interface determines usability and outcomes.

πŸ‘‰ Read | Signals | @mql5dev
❀13πŸ‘9🀩1πŸ‘Œ1
MetaTrader 5 ZOrder cannot be overridden in a reliable way, so the focus shifts to using the platform event sequence to identify the real click target.

A minimal indicator shows the pattern: CHARTEVENT_MOUSE_MOVE is emitted before CHARTEVENT_OBJECT_CLICK. With overlapping objects, this order remains consistent and can be used to gate interaction.

Code updates consolidate priorities: keep default 0 and add ePriorityNull for non-interactive objects. This requires recompilation and small fixes in classes such as C_ChartFloatingRAD.

Input handling is adjusted by adding a state flag in C_Terminal and checking validity on MOUSE_MOVE, then accepting OBJECT_CLICK only when the click is marked valid and the object name matches. This avoids foreground checks and reduces dependency on manual ZOrder management.

Next step prepares multi-position and pending-ord...

πŸ‘‰ Read | Quotes | @mql5dev
❀12πŸ‘9πŸ”₯3🀩1πŸ‘Œ1
Prop-firm sizing is a constrained optimization problem: the trade size must reflect both signal strength and the remaining daily/overall drawdown budget. Because these limits are path-dependent and sometimes expand with locked-in profit, static fractional or Kelly-based sizing cannot react correctly without live account state.

The refactor takes a previously firm-specific PropFirmAwareSizer and separates program terms from sizing math. A frozen PropFirmRuleSet captures variable rules (phase targets, fixed vs dynamic daily cap, news profit-credit haircut, drawdown basis, overnight policy). PropFirmAccountState becomes stateful and rule-driven, while pure functions stay unit-testable.

Key technical gain: correct handling of equity- vs balance-based drawdown checks, and explicit branching for dynamic daily limits. Validation compares the new implement...

πŸ‘‰ Read | Quotes | @mql5dev
❀16πŸ‘10🀩2πŸ‘Œ2πŸ”₯1πŸ‘1πŸ‘¨β€πŸ’»1
A trade management panel defines batch order actions with configurable entry count for BUY and SELL buttons, opening positions based on lot size and selected entries.

Risk and cleanup controls include Close Profit (closes all profitable orders), Close Loss (closes all losing orders), and Close ALL (closes every open order). Set All TP and Set All SL apply a single take-profit or stop-loss value across all active orders.

Operational tools include trailing stop on/off, Buy Pending and Sell Pending using an input price to place limit orders, and Delete Pending to remove all pending orders. Close Above and Close Below close orders based on a user-defined price threshold.

Key parameters cover trailing timer frequency, optional break-even for orders without SL, default trailing behavior, pending-order TP/SL in pips, and a lot size calculator using risk percent a...

πŸ‘‰ Read | VPS | @mql5dev
❀17πŸ‘9πŸ”₯2πŸ‘Œ2🀩1
Classic fixed-size Renko is generated internally from BID ticks, using the standard two-brick reversal rule. SuperTrend ATR and band values are computed from completed Renko bricks rather than time-based candles.

Trade entries are permitted only when the latest completed Renko brick direction matches the Renko-based SuperTrend direction. Position exits can be triggered by take-profit, stop-loss, a SuperTrend direction change, or a maximum holding-time limit. An optional short cooldown can be enforced before re-entry.

Risk controls include a strict one-position-per-symbol rule. The EA runs standalone with no external indicator, DLL, custom symbol, or offline chart requirement. A separate visual companion indicator is available at https://www.mql5.com/en/market/product/175340.

This is intended as an educational historical demonstration; default settings are not...

πŸ‘‰ Read | AppStore | @mql5dev
❀16πŸ‘7πŸ‘Œ3πŸ’―3
Spreads get checked routinely, swaps often get ignored. One overnight hold can exceed the entry spread, and long vs short swap can differ by an order of magnitude depending on the instrument.

A utility script prints swap cost in account currency within seconds. Per open position it shows tonight’s swap for the exact size, plus accumulated swap paid and holding days.

Per symbol (position symbols first, then visible Market Watch) it reports swap per night for 1.0 lot for long and short, the annualized cost using 360-day convention, the implied broker markup per side as (|long|+|short|)/2, and the triple-swap weekday.

Swap modes in points, deposit currency, or interest-rate formats are converted when reliable. Otherwise raw values are shown with currency notes or β€œn/a”. Optional inputs include Market Watch scanning, symbol cap, and an on-chart summary.

πŸ‘‰ Read | AppStore | @mql5dev
❀13πŸ‘8🀩2πŸ‘Œ2⚑1
Multi Timeframe Trend Matrix delivers a quick view of trend state from M5 through D1.

Each timeframe is computed from fast and slow EMAs, current price position, and ADX strength. Green tiles indicate price above both EMAs, fast EMA above slow EMA, and ADX at or above the configured threshold. Red tiles require the inverse conditions. Neutral tiles appear when neither full trend rule set is satisfied.

Implementation focuses on efficiency. Indicator handles are created once during initialization and reused. Panel updates run on a timer to keep charts responsive and prevent per-tick handle churn.

Key inputs cover fast/slow EMA periods, ADX period and minimum ADX, optional closed-bar confirmation, plus panel layout, colors, and refresh rate. This is an analysis dashboard only; it does not place trades or forecast results.

πŸ‘‰ Read | Freelance | @mql5dev
❀23πŸ‘9🀩2πŸ‘¨β€πŸ’»2πŸ‘Œ1
Market Structure Swing Map is a chart analysis tool designed to show price structure with minimal on-screen noise. It marks confirmed swing highs and swing lows, then classifies each new point versus the prior point of the same type as HH, HL, LH, or LL.

All calculations are based on closed candles. A swing is printed only after the configured number of candles confirms it on both sides, keeping past markings stable and avoiding forward-looking signals. An optional structure line can connect confirmed points to improve readability of the sequence.

Key settings include Swing Strength (confirmation candles per side), Maximum Bars (history scanned), optional swing price display, optional structure line, and alerts for newly confirmed structure points. The tool does not place, modify, or close trades.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀37πŸ‘9🀩2πŸ†2πŸ”₯1πŸ‘Œ1
Session Liquidity Map visualizes intraday structure by drawing separate boxes for the Asia, London, and New York sessions, then marking the high and low formed within each defined window. Session times are configured in broker/server time to avoid implicit timezone conversions.

Each session range can print its size in points. High and low levels can be extended beyond the session close for follow-up liquidity reference. Historical boxes are supported, and the active session updates on every new candle.

Key inputs include start/end times per session, Lookback Days for history depth, Show Range Text for point display, and Extend High Low plus extension length. Daylight saving and local time are not adjusted automatically, so session windows should be aligned to the trading server clock.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀31πŸ”₯5πŸ‘4🀩2πŸ‘¨β€πŸ’»2πŸ‘Œ1
Fair Value Gap Scanner identifies three-candle price imbalances and renders bullish and bearish gaps as chart zones based on completed candles only.

Zones can persist after mitigation or be removed automatically. Mitigation logic can be set to either first touch of the zone or full fill, depending on the trading plan. A minimum gap size filter helps exclude minor imbalances on noisier instruments.

The scanner processes new candles rather than recreating objects on every tick, keeping chart load stable while retaining historical context.

Key inputs include Maximum Bars (scan depth), Minimum Gap Points, per-direction visibility toggles, Hide Mitigated, Use Full Fill, Extension Bars for zone length, and optional alerts triggered after candle confirmation. This is a visual analysis indicator and does not execute trades.

πŸ‘‰ Read | VPS | @mql5dev
❀17πŸ‘7✍5🀩3πŸ€”1πŸŽ‰1πŸ‘Œ1
SwiftDraw Starter shows a practical pattern for MT5 chart utilities: hotkey-driven object creation with a minimal indicator footprint (no buffers, no plots) and all interaction routed through OnChartEvent.

Hotkeys are mapped via StringGetCharacter to key codes, then used to arm one β€œpending” mode at a time (H/V lines, trendline, rectangle, Fibonacci, buy/sell arrows). ESC clears state and restores chart mouse scrolling to avoid input conflicts during drawing.

A compact i18n layer is implemented with enums and a Tr() switch, keeping UI prompts consistent across languages. The on-chart legend is rendered using OBJ_RECTANGLE_LABEL and OBJ_LABEL with a prefix for bulk cleanup, enabling a clean show/hide toggle without leaving orphaned objects.

Object creation follows a predictable naming scheme and sets selection/visibility flags for immediate editing after pl...

πŸ‘‰ Read | Signals | @mql5dev
❀12πŸ‘7πŸ‘Œ1
IronHawk SMC Trade Zones M5 is an M5 chart indicator that flags structured setups only on closed candles with non-repainting logic. It aggregates confirmed swing points, liquidity sweeps, BOS/CHoCH, displacement, Fair Value Gaps, Order Blocks, plus RSI, MACD and ATR-based risk metrics. No orders are sent or managed; Entry, Stop Loss, TP1 and TP2 are shown as proposed levels for manual validation.

Setup flow includes ARMED, ACTIVE, TP, SL, EXPIRED, INVALIDATED and AMBIGUOUS states, with up to five completed setups listed and color-coded outcomes. A clickable history jumps to the originating signal candle. Alerts and optional CSV journaling are available.

A retail-frequency mode prioritizes organic SMC. If fewer than two opportunities appear in a broker day, scheduled fallback signals after 09:00 and 14:00 server time can be generated via a closed-bar ...

πŸ‘‰ Read | Forum | @mql5dev
❀22πŸ‘4πŸ‘Œ1
Linked lists in MQL5 move beyond stack-style push/pop by supporting insert and delete at arbitrary positions without shifting large memory blocks.

ArrayInsert is efficient at the end, but mid-array inserts require new allocation plus multiple copy passes. Repeating this over thousands of operations becomes CPU and memory-bus heavy.

The next implementation step is pointer-only updates: add a node by relinking neighbors, remove a node by bypassing it. Code revisions progress from a singly linked list to a doubly linked list, enabling forward and backward traversal plus FIFO-style reads (SEEK_SET) versus LIFO-style reads (SEEK_END).

πŸ‘‰ Read | VPS | @mql5dev
❀17πŸ‘3πŸ”₯2πŸ‘1🀩1πŸ‘Œ1
MetaTrader 5 chart objects can be selected reliably via ZOrder, but horizontal price lines remain hard to hit when lines are close.

A practical workaround is adding a small OBJ_LABEL β€œmove handle” next to each SL/TP line. Selection is done by clicking the handle, not the line. DispatchMessage is adjusted to cascade events to redraw and to clear selection on generic chart clicks.

Moving a line requires minimal code: when a handle is selected and the next click occurs elsewhere, the indicator sends a custom message to the EA with the new price. The EA updates SL/TP on the server and returns the confirmed level for rendering.

To allow recreating SL/TP after removal, pointers are not dropped when values become zero. Instead, the handle remains and is relocated to the entry price line, enabling the same click-to-set flow.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀15πŸ‘6πŸ”₯3πŸ†2πŸ‘Œ1
First Fractal Breakout is an intraday, session-bound system that replaces fixed opening-range windows with the first confirmed Bill Williams fractals after the open. Those five-bar pivots define a price-driven breakout box that naturally widens or tightens with volatility, enabling up to one long and one short attempt per session.

Implementation details matter: fractals confirm with a two-bar delay, so the logic queries M5 data at shift 3 and starts scanning ~15 minutes after open to avoid noise and repaint risk. Stops scale using a fraction of D1 ATR, position size is computed from percent risk, and take-profit uses a fixed reward-to-risk multiplier (both optimized to reduce overfitting).

The MQL5 EA enforces session timing, validates broker constraints (stops/freeze, margin), handles bid-trigger vs ask execution, tracks per-direction outcomes, and ...

πŸ‘‰ Read | Quotes | @mql5dev
❀17πŸ‘5πŸŽ‰2🀩2πŸ‘Œ1
PropFirmGuard is a risk-control layer for prop firm constraints, focused on daily loss and maximum total drawdown. It monitors account equity on every tick and, near a breach, closes all open positions, removes pending orders, and blocks new trades until the daily reset. It does not place trades and can run alongside any EA or manual trading on any symbol/timeframe as a tick source.

Daily loss is measured from equity at the configured reset hour. Total drawdown is measured from the highest equity since start. A configurable buffer is subtracted from both limits to trigger earlier (e.g., 5% daily with 0.5% buffer enforces at 4.5%). Total drawdown breach locks trading permanently.

The guard polls account state, so it also covers manual trades and other EAs without integration hooks. State is in-memory only; tester behavior matches live. On terminal restart, t...

πŸ‘‰ Read | Forum | @mql5dev
❀8πŸ‘6πŸ”₯2🀩1πŸ‘Œ1
This article removes the usual β€œtranslation tax” when streaming MetaTrader 5 tick batches into Python by writing ticks directly in Apache Arrow’s columnar memory layout inside Windows shared memory. Instead of serializing rows and unpacking fields into Python objects, the reader can import the same buffers as an Arrow RecordBatch with zero deserialization.

On the MT5 side, ArrowBufferWriter.mqh builds 64-byte aligned validity/data buffers for six tick columns and publishes them via a double-buffered seqlock (odd/even generation counter) to guarantee consistent reads without mutexes. No pointers are shared; both sides recompute offsets from a fixed schema contract.

An EA batches ticks by size or timeout and flushes with a small, bounded set of memory copies per batch. A self-test script validates byte-level correctness before adding the Python reader...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘11❀9🀩1πŸ‘Œ1
Engineering workflow for suppressing noise in lagged MA features and converting regime structure into a deployable, risk-aware MQL5 system.

Pipeline uses MA lags, ICA embedding, and a linear classifier. Two issues surfaced: unstable out-of-sample gains and non-deployable spectral clustering due to skl2onnx limits.

Fixes include time-series CV for ICA tuning, a cluster-count search with a peak at 8 regimes, and a supervised surrogate to predict spectral regimes for ONNX export.

Validation highlights a common failure: per-cluster accuracy on one-hot labels is reward-hackable by predicting zeros. Joint accuracy and class-share checks are required.

MQL5 integration loads three ONNX models and applies regime-conditioned position sizing and stop width using expected return and risk per cluster, then backtests on the last three years with tick-accurate sett...

πŸ‘‰ Read | AppStore | @mql5dev
❀9πŸ‘6πŸ”₯2🀩1πŸ‘Œ1
Part 2 connects dynamic risk-budget computation to position sizing via WParamCalibrator.

The calibrator converts risk_budget_pct into a sigmoid w parameter, then PropFirmAwareSizer scales positions smoothly from full size to zero as the daily budget erodes. The sizing logic remains independent of the specific prop-firm rule set.

A sigmoid is used to avoid threshold discontinuities that cause abrupt sizing shutdowns and unstable behavior in path-dependent strategies. The chain computes cal_bet_size = (risk_budget_pct * safety_factor) / stop_loss_pct, then numerically inverts the sigmoid to get w. The 0.98 cap and 0.02 floor are arithmetic guards, not business rules.

Default parameters create a long flat sizing ceiling until roughly 1.4% budget remains, concentrating de-risking late. This requires strategy-specific tuning and backtesting.

A product...

πŸ‘‰ Read | Docs | @mql5dev
❀12πŸ‘4πŸ‘Œ1
The article completes a doubly linked list in MQL5 by adding safe deletion and insertion in the middle, avoiding array-style shifting and extra copying. The core technique is pointer rewiring: link a node’s prev directly to its next (and vice versa), then free the removed node.

Deletion evolves from value-based search to index-based removal, with a maintained element count to validate bounds and handle head/tail as fast paths. A further refinement accepts negative indexes to traverse from the end, requiring direction-aware pointer updates to prevent deleting the wrong node.

These patterns matter when building MT5 tools that process large, frequently changing datasets, such as order/price event buffers, where predictable runtime and minimal memory churn are critical.

πŸ‘‰ Read | VPS | @mql5dev
❀19πŸ‘7πŸ‘Œ1