MQL5 Algo Trading
579K subscribers
4.64K photos
7 videos
4.65K 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
Part 5 packages the adaptive Parabolic SAR trailing stop as AdaptivePSARTrail.mqh, built for inclusion in existing MQL5 Expert Advisors. The module can trail positions it did not open, qualifying by symbol and magic number, while keeping its own SAR series and DivergenceEngine state.

Naive β€œset SL to last SAR” fails at SAR side flips and under broker constraints. The utility blocks wrong-side stops, enforces non-regression, and sequences checks for stop distance, freeze level, and tick grid to avoid silent stagnation and journal spam.

Integration is a four-call lifecycle: Init(cfg), Refresh() on new bars, ApplyToPositions() on ticks, and Deinit(). Trading calls are compile-guarded to allow indicator builds without CTrade. Acceleration adapts per bar using opposing divergence within a bar-age limit, with optional reset on trend change.

A demo EA runs...

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘9❀8🀩7πŸ”₯6πŸ†5
Automated trading often stops without visible errors due to PC sleep, terminal disconnects, algo trading being disabled, profile changes, or an EA being removed from a chart. BotWatchdog is designed to detect these conditions and send push notifications to a phone. It does not place trades.

Alerts include broker connection lost or restored, algo trading switched off or on, watched EAs missing from all charts with a comma-separated name list, terminal login changed to an unexpected account, open positions without a stop-loss for N minutes, equity falling by a configured percentage from the day’s starting balance, and margin level dropping below a defined threshold.

A daily scheduled β€œall OK” heartbeat can be configured; if it does not arrive, the terminal or host PC is likely offline. A final alert is triggered if the watchdog is removed.

Setup requires en...

πŸ‘‰ Read | CodeBase | @mql5dev
❀12πŸ‘10πŸ”₯10🀩4πŸ†4
SessionEdgeTester checks whether a fixed intraday rule survives real broker costs using only the terminal’s H1 history. The test is run locally and places no trades, returning results in roughly 20 seconds.

The rule is simple: enter at a specified hour on selected weekdays, then exit after a fixed number of hours. Each simulated trade is charged the larger of 1.5x the live spread and the entry-bar spread, plus optional commission, plus live swap for each server midnight crossed, including triple rollover.

Time alignment supports server, New York, or London clocks with daylight saving handling, so the entry remains at the same local hour across GMT and New York-close brokers. An optional percentage stop-loss is evaluated using H1 highs/lows.

Reporting includes all trades, a split of the first 60% versus last 40% for an out-of-sample check, plus PASS/WATCH/F...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀15πŸ‘11🀩9πŸ”₯7πŸŽ‰3
Indicators recalculate on every tick, so a simple β€œprice > level” check can trigger the same popup continuously while the condition remains true. This also causes a burst of stale alerts when an indicator is attached, because historical bars are processed immediately.

AlertKit is a lightweight class that suppresses duplicates by sending a single alert per event name and bar. It maintains separate state per event string so buy and sell signals do not block each other, and it ignores anything earlier than the bar where tracking started. Output can be routed to popup, push, email, or sound, with an optional cooldown.

Testing is addressed via CSV logging. Since alerts do not fire in the strategy tester, AlertKit can record every decision, including rejected alerts and reasons. In one EURUSD H1 run (Jun–Aug 2026), 6,419 alert checks resulted in 27 alerts, with ...

πŸ‘‰ Read | Freelance | @mql5dev
🀩16❀12πŸ‘10πŸ”₯6πŸ‘Œ3
Most VWAP tools reset per session, which limits usefulness on 24/5 markets. This implementation uses a rolling VWAP over a fixed bar count, sliding forward each bar to keep the anchor aligned with recent volume-weighted activity rather than a calendar boundary.

The close-to-VWAP deviation is normalized into a Z-Score using a rolling standard deviation of the same deviation series. This makes thresholds portable across instruments and volatility regimes, since the reading is expressed in standard deviations from rolling fair value.

Regime detection applies a two-step filter: the Z-Score must close beyond a configurable threshold and persist for N consecutive bars before switching state. The histogram mirrors the Z-Score but only changes color after confirmation, reducing noise-driven flips.

Key inputs include VWAP/StdDev periods (default 50), Z-Score...

πŸ‘‰ Read | Signals | @mql5dev
❀14πŸ”₯6🀩6πŸ‘5
TradeGuard separates execution safety from strategy logic. Strategy code decides what to trade and when; TradeGuard validates and normalizes every request to broker limits, retries only safe cases, blocks duplicate signals, isolates by symbol and magic, and rebuilds state after a restart. Delivery is a single include file with no DLL plus a Strategy Tester test suite.

Coverage includes permission and session checks, quote age and spread filters, margin and OrderCheck, volume/price/stop normalization, freeze level, filling mode, and expiration handling. Each request carries an intent key to ensure β€œone order per signal”, including after VPS restarts, and uncertain server replies are verified on the server before any resend.

Verification data comes from a bundled suite: 83 unit tests passing, thousands of key checks, and large randomized β€œbad request” runs sh...

πŸ‘‰ Read | Signals | @mql5dev
❀12πŸ‘8🀩6πŸ”₯4
Position sizing logic converts stop distance and account value into an allowed loss and a lot size via a single static call. Calculation divides risk money by the 1-lot loss at the provided stop, normalises to volume step and symbol min/max, then optionally caps size to fit 70% of free margin using a buy-at-ask margin check.

Supported risk bases: fixed lot (stop ignored), percent balance, percent equity, and fixed cash amount. Percent modes compute risk money as account value times risk/100; fixed amount uses the value as-is.

A daily loss baseline is set on first call, logged, and reset on server day change. Breach is detected when equity drops by the configured percentage from that base; zero or negative inputs disable breaches. Baseline is in-memory only and resets on restart.

Edge cases return minimum lot silently on invalid inputs, which can exceed una...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀11πŸ”₯5πŸ‘4🀩4
Auto Fibo Extended is an MT5 indicator that detects swing highs and lows over a configurable candle lookback and draws Fibonacci retracement and extension levels directly on the chart. Direction can be set to Auto based on which extreme occurs first, or forced Low-to-High / High-to-Low.

A key capability is running two independent Fibonacci structures at once from different timeframes, with separate styling. When higher-timeframe anchors are shown on a lower-timeframe chart, the tool aligns anchors to the exact candle containing the source high/low for cleaner placement.

Supported levels include negative extensions and targets up to 423.6%. Optional right-side price labels show percent and timeframe, track chart scaling/scrolling, and support color and layout customization. Updates are handled via ticks and timer events with reduced redraw when ancho...

πŸ‘‰ Read | NeuroBook | @mql5dev
🀩11❀9πŸ‘7πŸ”₯6
A chart panel provides seven one-click actions for position management: Close All, Close Buys, Close Sells, Close Winners, Close Losers, Close Chart Symbol, and Delete Pending Orders. It affects manual trades and positions opened by any EA, while never opening trades.

A magic number filter controls scope: 0 targets everything on the account, including manual trades; any other value limits actions to that magic. A symbol scope switch toggles between chart symbol only and all symbols, and an info line shows how many positions would be affected plus current floating P/L.

Optional confirmation prompts reduce misclick risk. Closures execute sequentially via market orders, so fills can differ per ticket in fast markets. Winners/losers are calculated as profit plus swap, excluding commission.

Config includes slippage limit, action logging, UI sizing/colors, and an ...

πŸ‘‰ Read | NeuroBook | @mql5dev
🀩8❀6πŸ‘6πŸ”₯6
Builds a minimal C_Neuron class in MQL5 that supports a variable number of inputs without rewriting code. The key shift is treating the weighted sum as a dot product over arrays, so changing input count becomes a constructor parameter and weights are allocated dynamically.

Training uses a simple squared-error loss (easy to differentiate, chosen for clarity over speed), with a single Train() method that hides internal changes so the caller won’t care if the implementation later switches to a gradient-based approach.

A practical constraint is data layout: the training array must be shaped as rows of N inputs plus one final target value. If N changes, the dataset must change with it, or the neuron will learn from misaligned signals.

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘8❀6πŸ”₯5🀩3
A High-Volume Pivot indicator for MT5 can make pivots more meaningful by filtering them through activity, not just price extremes. It confirms pivot highs/lows using left/right bar windows, then evaluates the pivot using a rolling volume sum computed at the confirmation bar.

Volume strength is normalized against a 95th-percentile reference from recent history (up to ~1000 samples), producing an adaptive score that works across symbols and sessions. Only pivots above a configurable threshold are displayed.

Qualified pivots are rendered with ATR(500)-scaled concentric rings (count driven by normalized volume), plus a reaction level that extends until close-to-close crossing invalidates it, and a compact volume label. All drawings are placed retrospectively at the originating pivot bar.

πŸ‘‰ Read | Quotes | @mql5dev
❀5πŸ‘4πŸ”₯4πŸ‘¨β€πŸ’»2✍1
SessionRangeBreakout.mq5 is an MT5 chart-window indicator that derives a completed intraday session high/low from M1 data using broker server time. It can draw a session rectangle plus extension lines, fill two non-plotted iCustom buffers (0=high, 1=low), and issue a single breakout alert per direction on the most recent completed session with an active extension.

Configuration covers session start/end (end is exclusive), line extension end, and a lookback of 1–365 completed session start dates, counting dates even when bars are missing. The range is computed from available M1 bars in [start, end), tolerating market-closure gaps and skipping sessions with no M1 bars.

Break detection supports touch (live price strictly outside, tick-driven) or close (bar close strictly outside, timeframe-driven), with optional popup/push/email. History and restarts pr...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀8πŸ‘2🀩2
This article treats common indicator rules as noisy voters rather than truth. Five cheap, independent heuristics (RSI crossback, EMA cross, Bollinger reversion, MACD histogram flip, candle proxy) output buy/sell/abstain on closed bars, and abstain is preserved to avoid contaminating the statistics.

A Snorkel-style generative model in MQL5 fuses these votes without labels or outcome feedback. Using Expectation-Maximization on a rolling window, it learns a per-heuristic reliability score and a shifting buy/sell prior purely from agreement patterns, then produces P(Buy) via a log-space Naive Bayes posterior for numerical stability.

Benchmarks against an unweighted majority vote across symbols/timeframes show weighting can change results, usually by reducing losses, but not enough to be statistically distinct. The value is a reusable signal-fusion laye...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀9πŸ”₯3πŸ‘2
Trade Manager Utility is a position management EA for MT5 that runs on both ticks and a timer, with a shared minimum cycle interval. It only modifies and closes existing positions and never opens trades.

Core functions include adding missing initial SL/TP anchored to entry, break-even moves with optional lock points, and trailing stops with points or ATR modes. Stop updates only tighten protection and are skipped when invalid under current price, broker limits, freeze distance, or spread filters.

Scope controls cover magic number filtering (-1 all, 0 manual, >0 specific), single-symbol vs all-symbols management, and a position-count monitor with optional alerts and newest-first excess closes.

Daily account protection can pause management and attempt closes after configurable equity/balance gain or loss thresholds. State is stored in terminal globals using ...

πŸ‘‰ Read | Calendar | @mql5dev
❀5🀩1
Outlier filters based on global thresholds fail when the market shifts by session or volatility regime. Local Outlier Factor (LOF) addresses this by comparing a bar’s neighbourhood density to the densities of its nearest neighbours, allowing quiet and volatile regimes to be β€œnormal” at the same time.

An MQL5 implementation is built from scratch using native matrix/vector types. Each closed bar becomes a 5D point; the last 500 bars are the reference cloud. The newest bar is scored against the cloud without being added. The trigger is a quantile (default 97.5%) of reference LOF scores, so it adapts per symbol/timeframe.

Architecture uses a refit lane every 4 bars and a query lane on each close. Features: log return, range/ATR, log(1+volume), spread, close location in range. The LOF score gates entries of a simple EMA-cross EA; tests focus on which t...

πŸ‘‰ Read | Signals | @mql5dev
❀9🀩3
A grid EA for XAUUSD that starts each basket from an RSI reversal on a closed candle. Buy when RSI crosses back above oversold, sell when it crosses back below overbought. A Reverse switch flips both signals. One-direction mode prevents a new basket in the opposite direction while one is active.

When price moves against an open basket, new grid levels are added every N points, using a lot multiplier up to a maximum level count. The initial lot can be fixed or sized from a percent of balance or equity. No per-trade stop loss is used.

The basket exits as a group via a money target or points from the average price, with optional basket stop loss and optional trading-hours filter. Margin usage increases with each level; disabling the basket stop allows deep drawdowns during sustained adverse moves. Strategy Tester validation and conservative sizing are required; ...

πŸ‘‰ Read | Docs | @mql5dev
❀8πŸ”₯4
This MQL5 workflow closes the gap between analysis and execution by treating trade actions as proposals, not immediate commands. Read-only tools run instantly, while order placement/close/modify/delete calls are queued and blocked behind a single human approval step.

Each proposed action is rendered as an approval card describing the exact operation, volume, stops/targets, and affected tickets. The tool loop pauses mid-turn until approve/reject, then resumes so the assistant can react to the outcome.

Execution is centralized in one dispatcher + validated executors: typed JSON argument readers prevent crashes, a safety gate enforces symbol/lot/position limits, lots are normalized to broker steps, and ownership scoping restricts bulk actions to allowed trades. Broker-specific constraints are left to the trade server, with refusals reported back for iterative corr...

πŸ‘‰ Read | VPS | @mql5dev
❀12πŸ‘5πŸ”₯3✍2🀩2
Terminal deal history is not position history. Partial closes often appear as multiple lines, and netting reversals can collapse close and open into a single deal. This exporter reconstructs positions from deals and writes one CSV row per closed position for external analysis.

Each row includes ticket, symbol, magic, comment, side, opened volume, entry/exit time and volume-weighted prices, duration, initial SL/TP (only if set on the opening order), and aggregated P&L components (gross, commission, swap, net). Risk metrics include risk_money and R-multiple when an initial SL exists.

Optional MFE/MAE are computed from M1 bars between entry and exit (Bid high/low), producing points and account-currency excursions plus bar count, session/weekday tags, and close reason. Limits: bar-based estimates, empty excursions if M1 history is missing, no export of open position...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘7πŸ”₯6❀5🀩4πŸŽ‰2
Most EAs treat calendar releases as categories and block trading by importance and time window. That ignores what drives price: actual versus forecast, scaled so surprises are comparable across indicators.

MqlCalendarValue supports actual/forecast/previous, but forecast history starts May 2017. Central bank rate decisions and most speeches have no forecasts, so surprise-based models cannot cover them. Large currency-wide CalendarValueHistory calls can timeout; querying per event avoids silent zero-row returns.

Standardizing surprise with mean/stdev fails due to mis-scaled forecasts. Median and MAD (1.4826 scaled) with expanding history avoids look-ahead bias, plus a hard gate (10 robust sigma) removes impossible rows.

Release timestamps often miss the bar that moved due to startup GMT/server-time flips and DST shifts. Offsets can be recovered from price by...

πŸ‘‰ Read | Signals | @mql5dev
❀11🀩10πŸ‘7πŸ†2πŸ”₯1
An MT4/MT5 indicator processes only closed bars and flags five candle patterns: bullish/bearish engulfing, bullish/bearish pin bar, and inside bar. Pin bars are defined by configurable wick and body percentages, inclusive at the limits. Inside bar direction follows the mother bar; doji mother bars are skipped. Signals require a minimum bar range expressed as a multiple of Wilder ATR, with an optional EMA trend filter.

Each signal opens a case at the signal bar close. Take and adverse levels are set at entry Β± X*ATR and βˆ“ Y*ATR using the signal bar ATR. Resolution is the first subsequent bar to hit either level; a bar touching both counts as a miss. Unresolved cases after a fixed wait are discarded.

A panel reports rolling hit rate per pattern over the last N resolved cases, plus sample size. Values are non-repainting and deterministic, with iCustom b...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀14πŸ‘8πŸ”₯3🀩2✍1