MQL5 Algo Trading
560K subscribers
4.15K photos
6 videos
4.16K 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 update to the MT5 replay/simulation position indicator adds switchable display modes so traders can avoid focusing on monetary P/L while still monitoring risk during volatile periods.

A scoped enum inside the position structure defines modes (money, ticks, points, percent), letting the ViewValue routine format output via a clean switch and scope resolution. An extra “ticks-to-price” support value is computed once and passed into the class to keep formatting fast and consistent.

Mode changes are triggered by clicking the OBJ_EDIT field: a custom event cycles the enum and forces a refresh of all indicator segments (entry, SL, TP) to prevent mixed units. On hedging accounts, updates are isolated per position via a ticket check, with an easy path to broadcast changes if desired.

👉 Read | NeuroBook | @mql5dev
15👍8🤩6🔥42🤣1
This article digs into a practical pain point in MQL5 data structures: deleting nodes in a binary tree without corrupting links.

It starts by showing how traversal output (pre-order and post-order) can be used to reconstruct the tree shape, and why a small change in traversal logic produces different sequences—so reading output without checking the traversal code is unreliable.

A search routine is added by adapting the existing insertion-walk to return a node address. The article also highlights how seemingly equivalent loop conditions can trigger crashes due to compiler/short-circuit behavior, reinforcing the need for precise pointer checks.

Deletion is introduced with the simplest case: removing a leaf. The key rule is updating the parent’s child pointer before freeing memory; otherwise later traversals follow dangling pointers. An iterative de...

👉 Read | Calendar | @mql5dev
👍10🤩86🔥4🎉1
Nicolas Darvas’ box method can be coded with clear rules, but automation tends to fail on two mechanics: rolling box replacement and staircase pyramiding with a shared stop.

This EA confirms a box after a new N-bar extreme, three consecutive sessions without exceeding the top, contracted average volume, and a minimum height filter. Entry triggers only when the close breaks the box boundary with breakout volume above the box average by a configurable multiplier.

Trade management is state-driven. Each subsequent breakout adds a new unit, moves all stops to the latest box floor, and closes all units together on a stop violation. A stall timer exits if no new box forms within a set bar count.

Known constraints include repeated top resets on tight ranges, tick-volume calibration per broker, and premature exits in strong trends when no new box forms.

👉 Read | Forum | @mql5dev
12🤩6🔥3👀3🏆1
Pure MQL5 logistic regression built from scratch: no Python bridges, ONNX, DLLs, matrix classes, or external libraries. The core is a single-neuron classifier that maps a standardized feature vector to a probability via a numerically stable sigmoid, trained with stochastic gradient descent using cross-entropy where the gradient reduces to (prediction - label) * input.

The article emphasizes evaluation discipline over model complexity: standardize using only the training segment to prevent look-ahead leakage, split history into train/test blocks, and compare against a majority-class baseline.

Results illustrate why this matters: a small out-of-sample lift on EURUSD, but underperformance on XAUUSD, showing that clean testing can reveal when “working” ML has no tradable edge.

👉 Read | VPS | @mql5dev
13🤩5👌4
MSB Pro ALGO Neon Account Dashboard is a free on-chart account monitoring panel for MetaTrader 5. It shows key metrics including balance, equity, floating P/L, today’s realized P/L, closed trades today, daily win rate, open positions, and BUY/SELL counts.

The open positions table lists up to five entries with symbol, side, volume, open price, and current P/L. When more positions exist, an additional count is shown. Market open/closed status is derived from the attached symbol’s trading session. Data refresh runs automatically every second.

The tool is read-only and contains no trade execution or strategy logic. It works on demo and live accounts without DLLs, external APIs, or extra files. Settings include panel X/Y placement, refresh interval, max rows, table visibility, and color customization.

👉 Read | CodeBase | @mql5dev
13👌3👍2👨‍💻21🤩1
Beetle Swarm Optimization (BSO) merges Beetle Antennae Search (two-point probing without gradients) with Particle Swarm Optimization to reduce sensitivity to the initial point and improve performance on rugged, multi-dimensional objectives.

Each beetle maintains position, velocity, personal best, and a shared global best. Per iteration it samples fitness at two antenna tips aligned with velocity, converts the better side into a BAS increment, updates velocity via PSO (inertia + cognitive/social pulls), then blends both moves using a λ coefficient to switch from pure BAS to pure PSO.

Exploration-to-exploitation is handled by linearly decreasing inertia and exponentially shrinking antenna step size and spacing.

The MQL5 implementation fits a standard Moving/Revision test bench using a phase-driven state machine, because each logical step needs three fitn...

👉 Read | Docs | @mql5dev
14👍13🤩7🔥6
MSB Pro ALGO Position Risk Monitor is a free visual risk monitoring indicator for MetaTrader 5. It evaluates currently open positions and renders stop-loss risk metrics directly on the chart, using broker symbol specifications and platform profit calculation functions.

The panel reports total known open risk, account risk percent (based on equity, with balance fallback), counts of positions with and without stop loss, total positions, total lot size, protected/breakeven stop-loss count, and maximum single-position risk. It also shows a per-position table with symbol, side, lot size, stop price, monetary risk, risk percent, and a LOW/MODERATE/HIGH status.

Positions with stop loss at or beyond entry are treated as protected with zero remaining entry-to-stop risk. Positions without stop loss trigger an unbounded downside warning while known stop-defined...

👉 Read | NeuroBook | @mql5dev
9🔥9🤩9👍8
HimNet tackles forecasting in trading data where behavior shifts across venues and over time, making “one model fits all” averages unreliable. It learns spatial and temporal context directly from data, so the model can adapt without relying on external metadata that is often missing or stale.

The core mechanism is trainable embeddings (time-of-day, day-of-week, and per-series location vectors) that form regime clusters. Those clusters query compact meta-parameter pools to generate context-specific weights as mixtures, keeping memory and latency practical.

On top of this, a graph-convolutional recurrent unit uses dynamically generated convolution parameters, letting cross-market influence change with regime. For traders and MT5 developers, this translates into more stable liquidity/volatility forecasts, better execution settings per session/venue, ...

👉 Read | Quotes | @mql5dev
20👍15🔥10🤩8😁2
DoEasy adds an indicator object layer to standardize storage and reuse of indicators across programs. The base model follows existing library objects: an abstract base with descendants for standard and custom indicators, plus classification by group (trend, oscillator, volumes, arrows) for filtering and sorting.

Library updates include new message indices/text, default indicator object parameters, a dedicated object ID, and enumerations for properties and sort criteria. A new CIndicatorDE class (IndicatorDE.mqh) derives from CBaseObj, adds an explicit destructor for releasing the created handle, and implements full-field equality, including MqlParam structure and array comparison.

Testing wires the object into CBuffersCollection via CreateAC(), uses IndicatorCreate() without parameters for AC, prints object data to the journal, then deletes the objec...

👉 Read | AlgoBook | @mql5dev
48👍14🔥9🤩7🎉51
John Ehlers’ HighPass-LowPass Roofing Filter, described in Cycle Analytics For Traders (p.78), is a roofing-filter variation designed to isolate trend direction by removing unwanted frequency components.

Interpretation is straightforward: readings below 0 indicate a downtrend, while values above 0 indicate an uptrend. Some implementations also color the line to reflect bias, commonly using green for bullish conditions and red for bearish conditions.

Practical signals are typically derived from zero-line crosses and sustained position on one side of 0, rather than single-bar color changes, to reduce noise-driven flips.

👉 Read | Freelance | @mql5dev
67👍21🤩14🔥8👨‍💻4🏆3👀2
Prop-firm equity guard utility targets challenge rule compliance by enforcing account-level risk limits from a single chart instance. It monitors equity in the background and triggers a shutdown sequence before daily or maximum drawdown thresholds are breached.

Daily loss control supports an optional buffer below the firm’s limit, closes all positions, and blocks new trading until the next server-day reset. Maximum drawdown monitoring applies the same logic at the account limit.

On trigger, the kill-switch closes active trades and removes all pending orders across symbols to prevent accidental fills during volatility or spread widening. No multi-chart setup is required; all symbols and timeframes are covered.

For automation, a global flag is set so other EAs can halt execution with a single conditional check.

👉 Read | Quotes | @mql5dev
26🔥6🤩3
Risk Guard is an account-level risk control utility, not a trading system. It never opens positions. A single chart instance can monitor manual trades and other EAs, with each rule configurable or disabled.

Core functions include on-chart risk-based lot sizing using tick value, tick size, and volume step; a daily loss limit that can close all positions and then auto-close any new trades until the next server day, with the lock persisted via a terminal global variable; maximum open positions with newest-over-cap closures; oversized-trade trimming based on actual SL distance; forced stop-loss insertion; and a spread status warning.

Enforcement is triggered via OnTradeTransaction on deal-add for same-tick intervention, with daily P/L computed from closed results since server midnight plus floating P/L, checked on tick and timer. All actions are logged and can ...

👉 Read | Docs | @mql5dev
19👍4🔥3🤩3👌3
Position view updates for an MT5 replay/simulation stack focus on robustness and data completeness.

Open-position volume is added to the indicator via an OBJ_EDIT element, favoring X/Y placement over price/time anchoring. Formatting adapts to fractional volumes by suppressing decimals when the value is effectively an integer. Viewport updates are reordered to keep the volume field aligned, and dynamic sizing is adjusted to prevent background clipping.

Object deletion is handled through CHARTEVENT_OBJECT_DELETE. Internal deletes temporarily disable event handling to avoid false recovery. A small helper centralizes this toggle. Segment restoration is refined by allowing a negative sentinel in m_Info.price so missing SL/TP segments recreate only the move handle, not the full segment UI.

👉 Read | NeuroBook | @mql5dev
22🎉2
Tree performance depends on the path length, not on a generic “imbalance” label. Height differences between subtrees can lengthen specific traversals, while other operations remain fast.

Balanced search trees reduce comparisons sharply. A million keyed records can be located in under 20 steps in a well-balanced binary tree, based on the per-level growth rule for P-ary branching.

Balancing is handled via local balance factors and rotations. Rotations rewire parent-child links while preserving in-order key ordering, but global balance requires validating all nodes.

Recomputing subtree heights by traversal after each update is costly. A practical optimization is storing subtree height per node to update balance factors incrementally.

👉 Read | Freelance | @mql5dev
21👍2👨‍💻2🔥1
This article dissects a fragile point in an MT5 automated optimization pipeline built on Adwizard: a multi-stage process can finish “successfully” yet silently skip tester passes, leaving no final EA database. The root cause may be terminal-side issues (history loading, beta instability), not strategy code.

The key debugging method is database-driven: inspect stages/jobs/tasks/passes in SQLite, detect near-zero task durations and missing passes, then recover by re-queuing an entire stage (status Done -> Queued) so triggers propagate to jobs and tasks.

It also validates the generated final EA and shows how risk/close managers can distort expected drawdown when equity grows fast, highlighting the need to align normalization and live lot-sizing. Finally, it outlines practical prep for project creation: pre-run optimizations and choose parameter ranges from dat...

👉 Read | Calendar | @mql5dev
21🔥5🤩2👍1
Ed Seykota implemented an early computerized trend system in 1970 using FORTRAN on mainframes. Core logic: dual EMA crossover for direction, daily execution, multi-week holding, no intraday monitoring.

Key rules: fast/slow EMA (commonly ~20/200) plus an ADX filter to avoid range conditions (ADX > 20). Position sizing uses ATR-based risk parity: equity risk % divided by ATR stop value (typical ATR(20) with 3–5x multiplier). Exits use EMA reversal or ATR stop, no fixed take profit.

Main differentiator is portfolio heat. Residual risk is summed across all open positions and capped (often 10–20%); new entries are blocked when the cap is reached, limiting correlated drawdowns in multi-symbol portfolios. MQL5 EA architecture monitors a symbol list on D1, computes heat first, then evaluates exits and entries per symbol.

👉 Read | VPS | @mql5dev
22👍8🤣5🔥4🤩1
High-impact economic releases routinely cause spread expansion and slippage that invalidate clean backtests. Event timing is known in advance; the failure point is delivering a reliable schedule into an EA.

Web scraping breaks on HTML changes. Paid calendar APIs add cost and require runtime connectivity, which is fragile on VPS setups. A file-based news filter avoids both by loading a Forex Factory CSV export from MQL5/Files at startup and running fully offline.

Core components: typed CNewsEvent records with an impact enum, a quote-aware CSV parser, symbol currency extraction that handles broker suffixes, and an inclusive time-window checker with CheckAt for boundary tests. Optional chart rectangles visualize pre/post buffers for qualifying events.

👉 Read | Freelance | @mql5dev
21🔥11👍9🤩5🤣1
This article builds a MetaTrader 5 indicator that extracts the full risk-neutral distribution from an option chain, answering questions like P(close above X), expected move, tail thickness, and confidence bands.

The core method fits a smooth implied-volatility smile (using liquid OTM quotes), reconstructs clean call prices, then applies Breeden–Litzenberger (second strike-derivative) to recover the density. It avoids the common failure mode where differentiating noisy quotes produces spiky, negative “probabilities.”

Implementation details emphasize numerical reliability: a bracketed Newton/bisection IV solver, forward-price cross-checks via put-call parity regression, spline extrapolation that preserves slope continuity to prevent boundary spikes, and diagnostics like clipped-negative counts and pre-normalization integral error.

For traders, it overl...

👉 Read | AppStore | @mql5dev
19🔥7👍6🤩5🤡1💯1
Portfolio trading logic breaks quickly when OHLCV series are not time-aligned, especially with illiquid instruments that produce missing bars. A synchronizer should output equal-length arrays with identical bar open times over a selected interval.

Two fill modes are typically required: keep gaps as explicit empty bars, or forward-fill prices from the previous Close with zero volume. Both are needed for different research and execution workflows.

A practical design uses MetaTrader 5 Standard Library CSortedMap keyed by bar open time, backed by red-black trees. A CSymbolData container stores OHLCV plus bar type (real/empty/interpolated), while a manager layer handles loading, updates, direction normalization, and asynchronous bar arrival policies (wait for all symbols vs incremental recalculation).

👉 Read | Signals | @mql5dev
20🔥12👍64🤡2🤩1
Smart Loss Exit is an exit manager, not a strategy. It does not open trades; it monitors selected positions (manual or EA) by symbol and magic number and only closes positions that are currently in floating loss. Positions in profit are never modified.

The design targets a common backtest failure mode: high win rate but low profit factor because a small number of losing trades reach full stop. The goal is to close trades that are likely to hit the stop while avoiding premature exits on recoveries. Each rule is configurable, supports a grace period, and logs the first rule that triggers.

Five loss-only rules are available: ATR adverse excursion, time-in-trade while losing, EMA trend invalidation (20/50 default), RSI momentum thresholds (optional), and an account-currency loss cap (optional). Tick-based checks are used for ATR and time; EMA/RSI use last cl...

👉 Read | Forum | @mql5dev
19👍7🤩5🔥2
HimNet targets market robustness over flashy complexity: a lean Encoder–Decoder that limits trainable parameters to reduce overfitting while staying adaptable to regime changes. It combines graph recurrent units with Chebyshev polynomial aggregation to model structured dependencies without slowing execution.

The Temporal Encoder runs two parallel time-scale embedding dictionaries. Each timestamp produces compact embedding “queries” that select a suitable meta-parameter subspace, letting the model switch behavior by time context instead of retraining. These embeddings are concatenated and fed through a stacked GCRU pipeline where the first layer builds context and deeper layers refine it.

Implementation details emphasize reliability: strict layer validation, centralized Init, OpenCL binding, pointer sharing to avoid tensor copies, and careful backp...

👉 Read | Docs | @mql5dev
18👍7🔥5👌3🤩1