MQL5 Algo Trading
588K subscribers
5.04K photos
7 videos
5.05K 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
TrailGuard is an MT5 Expert Advisor focused on stop-loss management for existing positions. It never opens or closes trades on live or demo charts, and only adjusts stops in the trade’s favor.

Break-even logic triggers after 150 points of profit (default), moving the stop to entry plus 10 points. Trailing activates from 300 points profit, using either a fixed 200-point distance or an ATR-based distance set to 1.5x ATR(14) on H1. The chart timeframe is irrelevant because positions are managed directly.

Scope can be limited to the current symbol or applied across all symbols, and filtered by manual trades only, all trades, or a specific EA via magic number. Updates respect broker stop-distance rules, apply a minimum 20-point step, and retry after 60 seconds on rejection.

Strategy Tester results on EURUSD H1 (Oct 1 to Nov 20, 2026): 53 trades, 221 stop update...

πŸ‘‰ Read | Signals | @mql5dev
❀13🀩8πŸ‘6πŸ”₯4πŸ‘€1
Trade Journal and Performance Dashboard for MT4 records closed trades and consolidates key statistics in a single on-chart panel. Closed trades are saved to CSV automatically, with the journal updating as new positions are finalized.

Core metrics include net profit, win rate, profit factor, expected payoff, and drawdown. The panel also tracks streaks, average trade outcomes, and trade duration, alongside balance, equity, floating P/L, and open positions. Results can be broken down per symbol.

Trade history supports search, filtering, and sorting, with per-trade detail on selection. Exports are available for both history and statistics in CSV, including filtering by Magic Number. Optional alerts trigger on trade close, and the panel can be moved, minimized, or hidden.

MT4 limitation: only the currently selected Account History range is accessible; β€œAll Hist...

πŸ‘‰ Read | Freelance | @mql5dev
❀9πŸ‘8πŸ”₯3🀩2
Giano ATR Regime quantifies how current price ranges compare to their own recent history using an ATR ratio. A ratio of 1.00 means the last closed bar matches its baseline ATR, while 1.62 indicates 62% above baseline. The on-chart label reports the latest closed bar’s regime and ratio.

ATR is computed per closed bar as a 14-bar simple average of true range, then normalized by the mean of the latest 100 ATR values (including the classified bar). Results are tied to the current symbol and timeframe.

Regimes: FEAR (orange) if ratio > 1.50, NEUTRAL (gray) for 0.70–1.50 inclusive, COMPLACENCY (blue) if ratio < 0.70. This measures range expansion or contraction only, with no directional or trade signals.

Options include alerts on closed-bar regime changes and a toggle for the latest reading label. iCustom buffers: 0 ATR ratio, 1 color index (0/1/2), 2 regime c...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀16πŸ”₯5πŸ‘3🀩3
MetaTrader 5 build 6380 significantly expands what AI Assistant can do. With more than 40 new MCP tools, you can now use AI to do more directly in the trading platform:

β€’ Manage MQL5 services
β€’ Configure charts and graphical objects
β€’ Analyze market depth
β€’ Calculate margin requirements and potential profit
β€’ Check trading operation parameters
β€’ Work with alerts and financial news

For developers, MQL5 adds new functions for working with complex numbers and expands support for complex matrices and vectors. Mathematical calculations are now faster and more numerically stable.

The Strategy Tester also received extensive improvements to trade calculations, tick modeling, historical data handling, and task distribution among testing agents.

We've also updated the deposit and withdrawal interface and improved operations with custom symbols, charts, and MQL5.community services.

Read more...
❀12πŸ‘10🀩3
Core Idea Execution & Slippage Forensics is a standalone MT5 diagnostic script with no external include dependencies. It audits live account history by pairing each executed deal to its parent historical order via HistoryOrderSelect(), then compares ORDER_PRICE_OPEN (requested) to DEAL_PRICE (fill) to quantify execution quality in points and account currency. For market orders where the requested price is absent, it avoids synthetic calculations when Req=0.0.

Output uses a fixed sign convention: positive values indicate price improvement, negative values indicate adverse slippage. Results are grouped into ALL_MEASURED, ENTRIES (IN/INOUT), SL_EXITS (DEAL_REASON_SL), and OTHER_EXITS. Each bucket reports Count, Mean and Median points, Adverse/Positive percentages, and net slippage in currency.

A 24-hour broker server profile highlights hours with degraded ...

πŸ‘‰ Read | Freelance | @mql5dev
❀8πŸ‘4🀩3πŸ”₯2
Most market models lean on correlation: match the current state to prior states and extrapolate. That works in stable regimes but lags at turning points, where behavior changes.

EDCFlow adds a temporally dense difference map between adjacent event segments while keeping low-resolution correlation for longer dependencies. Similarity provides context; differences expose regime shifts and impulse moves earlier.

Architecture summary: event-stream tensorization, dual-resolution feature encoders, correlation volume plus multiscale difference layers, attention-based fusion, and iterative GRU flow updates.

For an MQL5 port, the bottleneck is repeated difference computations across multiple time lags. A practical implementation needs GPU-style parallelism to keep latency acceptable for live microstructure signals.

πŸ‘‰ Read | Signals | @mql5dev
❀14πŸ‘10πŸ”₯8🀩3πŸ‘€2
Tick-Based Spread Distribution Profiler is an MQL5 indicator that builds an empirical 24-hour spread distribution from real historical Bid/Ask ticks. Instead of relying on live spread or M1 bar minima, it queries tick history via CopyTicksRange() over a configurable lookback window and reports spread percentiles per broker server hour.

The subwindow shows hourly P50 (median) as a histogram, with P90 and P99 overlays to quantify session liquidity and tail risk during rollover or macro events. Memory usage is bounded with a deterministic, unbiased reservoir sample per hour (configurable max samples) to support multi-week histories without skewing early data.

A closed-bar spread/ATR friction ratio is calculated using iATR at shift=1 on a selectable timeframe, exposing when spread cost is a material fraction of typical range. An optional HUD summarizes p...

πŸ‘‰ Read | Docs | @mql5dev
❀10πŸ‘6🀩2
Multi-timeframe indicators can silently mix bars when separate reads occur around a timeframe rollover, creating look-ahead or stale-data bugs that still look β€œreasonable” in logs and backtests.

The library adds a gate: CMultiTFAggregator reads exactly one closed bar per timeframe and validates alignment using bar open times, not bar counts. It enforces grid placement, checks newest-bar recency against floor(F/p)*p, rejects closed bars whose end exceeds the base snapshot time, and never treats partial data as valid.

A bounded re-read detects races where the base bar changes mid-build. An abstract bar source enables deterministic tests with synthetic series, so alignment rules can be verified without terminal history. Includes a demo indicator that computes only when the bundle is valid, plus a test script that covers each status and edge case.

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘12❀9🀩8πŸ”₯5
Range Compression Zones Breakout detects narrowing ranges and renders each compression run as a single active chart zone. The zone is tracked until a closed candle breaks above or below its boundary, after which the breakout is validated by a higher-timeframe high/low filter and a rising-volume filter.

Confirmed breakouts generate BUY/SELL signals with a reference plan: next bar open as entry, stop at the opposite zone edge, and one target derived from a configurable reward-to-risk multiple. Breakouts that fail filters or produce an invalid plan are still recorded, marked, and the zone is closed.

Inputs cover High-Low or Wilder-smoothed ATR range modes, compression threshold, volume windowing, optional H1/D1/W1 reference timeframe checks, and display/alert controls. Outputs include on-chart boxes, arrows, entry/SL/TP levels, a status overlay, and buf...

πŸ‘‰ Read | CodeBase | @mql5dev
❀7πŸ‘5🀩5πŸ”₯4🀝2
This MQL5 model treats breakouts as hypotheses and requires evidence before entry: a validated consolidation, a confirmed break, and a rejected retest. Consolidations are filtered by edge-to-edge switches (both sides defended), height capped by typical candle size (symbol-scaled), and drift between early vs late closes to reject trending channels.

A breakout must close beyond the range edge by a candle-sized buffer and then move away. The setup only arms after price returns into a frozen retest zone, then triggers on a strong close back on the breakout side, using bar-strength criteria to avoid weak taps.

Risk is anchored to the deepest retest excursion, not box width: stop beyond the retest extreme, target as an R-multiple, plus one-way trailing. A state-machine tracks attempts, allows re-break/retest after losses, gates entries with explicit reasons, and ...

πŸ‘‰ Read | Freelance | @mql5dev
❀17πŸ‘9πŸ”₯9🀩5
Close All (Filtered) is a terminal script designed to close open positions and delete pending orders in a single run, with configurable filters to target specific subsets. Typical use cases include closing only losing sell positions linked to a specific magic number, or only profitable trades on the current chart symbol.

Before execution, the script counts all positions and orders matching the selected filters and prompts for confirmation. Close failures caused by requotes or trade context issues are retried for a defined number of passes, and each failure is logged with its return code in the Experts tab. A final summary reports closed/deleted items versus matched items.

Key inputs include symbol scope, magic number selection, side (buy/sell), profit or loss filtering (profit plus swap), toggles for closing positions and deleting pending orders, confirmation...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀8πŸ”₯5πŸ‘4🀩4
Part 4 extends an MQL5 PDF writer from β€œtext-only” output to real page layout with vector drawing. It switches to a top-left origin and millimeter-friendly sizing by applying a single PDF transform matrix once per page, avoiding repeated y-flips and reducing placement bugs.

Drawing is built on PDF paths: construct geometry, then apply a paint operator (stroke, fill, fill+stroke, or clip), including correct handling of nonzero vs even-odd fill rules for holes and self-intersections. Stroke control covers width, caps, joins, miter limits, and dash patterns; circles are approximated via cubic Beziers using the kappa constant.

Color support adds a byte-based RGB type that outputs PDF fractions, plus utilities for blending and readable ink selection, while addressing the common MQL5 BGR vs hex RGB ordering pitfall. The architecture splits responsibilit...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀16πŸ‘7πŸ”₯7🀩6⚑3πŸ‘¨β€πŸ’»2
Candle Timer and Spread is a lightweight chart indicator that displays the time remaining until the current bar closes, along with the current spread in points. It targets workflows where entries are executed on bar close and the spread cost needs to be visible without opening extra panels.

The countdown is driven by TimeTradeServer(), updating every second even during low-tick periods. During the final 10% of the bar, the label switches to a warning colour. If the bar time has elapsed but the next bar is not available yet, the display shows β€œwaiting for tick” instead of a negative value.

Configuration includes label corner placement, X/Y pixel offsets, normal and warning colours, font and size, and an option to hide the spread. Compatible across symbols and timeframes from M1 to MN1, implemented via a single label object with no indicator buffers and ...

πŸ‘‰ Read | Quotes | @mql5dev
❀8🀩4πŸ‘3
This package turns MetaTrader 5 calendar raw data into a usable news filter for EAs. CCalendarFeed wraps CalendarValueHistory() output, enriches it via event/country lookups, then stores only relevant items in a time-sorted CCalendarEvent array.

It filters by minimum importance, currencies implied by the traded symbol set, and time mode (default: exact-time only). It also merges revisions, removes duplicates deterministically, and computes β€œminutes/seconds to event” plus a symmetric pre/post news window using seconds for correct boundary behavior.

To stay testable and avoid Strategy Tester limitations, calendar access and β€œnow” are injected via abstract source/clock interfaces, with terminal and fake implementations. EAs query GetNextEvent() and IsInNewsWindow() with explicit status handling for failures or empty ranges.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀17πŸ”₯6πŸ‘3πŸŽ‰3🀩3
Lot Size Calculator is a non-trading script that computes position size from a defined risk limit and stop-loss distance. It can be run on any chart and does not open, modify, or close orders.

Stop-loss monetary value is derived via OrderCalcProfit(), matching terminal pricing for forex, cross pairs, metals, indices, and crypto across any account currency. If profit calculation is unavailable for a symbol, the script falls back to tick size and tick value. Output volume is rounded down to the symbol volume step and constrained by min/max lot limits.

Inputs include risk mode (percent of balance, percent of equity, or fixed amount), risk value, trade direction (buy at Ask or sell at Bid), stop distance in points, or an exact stop price.

Results include entry/stop prices, points distance, risk target, 1.0 lot stop value, calculated lot size, actual risk, ...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀9πŸ‘4πŸ”₯4🀩1
MT5 history stores executions as deals, so β€œone trade” must be rebuilt from multiple entries/exits. A naΓ―ve CSV export that writes one row per closing deal breaks win rate and average-trade stats: partial exits inflate trade count, scale-ins distort entry price, and netting reversals can merge two opposite trades under one position ID.

The TradeAudit library reconstructs one record per closed trade segment: on hedging, one position; on netting, each run from open until volume returns to zero, with reversals split into separate segments. It computes volume-weighted entry/exit prices across multiple deals, tracks deal counts, profit plus costs, and flags like close-by.

CHistoryReader uses a two-pass scan to collect position IDs in a date range, then loads full deal history per position to avoid missing out-of-range entries. Scripts export CSV and validat...

πŸ‘‰ Read | VPS | @mql5dev
πŸ”₯9πŸ‘4🀩4❀3
Pacific Clock is an MT5 indicator that prints the current US Pacific time on a single line above the chart time scale, updated once per second with a PST/PDT suffix. It targets setups where trading decisions are made in Pacific time while the broker server runs another zone, with an optional broker-time field on the same line for quick comparison.

Hovering any candle shows the corresponding Pacific day/time. DST is handled automatically using the US rule (second Sunday in March to first Sunday in November), verified against official records for 2020–2030.

No signals are generated and no chart objects are drawn beyond two text labels. Accuracy depends on the local PC clock. Historical candle conversion is derived from the current broker-to-UTC offset, so past candles can be off by one hour if the broker shifted server time since then. Configuration include...

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘8❀4😁1
OrderGuard is an MQL5 include file for custom Expert Advisors in MetaTrader 5, focused on safer order sending rather than signal generation. It ships with a small sample EA that places market buy/sell orders only, using an MA cross solely to produce test signals.

Core controls include persistent de-duplication of signals across restarts/reconnects, broker-side counting of open positions, blocking orders during disconnects with single-shot logging, and automatic adjustment of stops/targets to the symbol’s minimum distance with correct rounding. Per-order validation also fits lot size to symbol constraints without rounding up, checks free margin, market state, and trading permissions, selects an allowed filling mode, and applies backoff on broker rejections up to 15 minutes with single-shot logging per skipped signal.

Integration: place OrderGuard.mqh under MQL5\I...

πŸ‘‰ Read | Calendar | @mql5dev
❀11😁1
KeyLevelsSweeps.mq5 automates common reference levels used in intraday FX workflows and keeps them consistent across timeframes by building from M15 data. It plots PDH/PDL, PWH/PWL, PMH/PML, day/week/month opens, New York midnight open, and an Asian range window with configurable hours. Lines are drawn across their respective periods for a configurable lookback, with right-edge labels and collision-aware label merging.

Day boundary is selectable: broker midnight, New York 00:00, or 17:00 New York. For New York modes, broker time alignment and DST handling are derived from historical Friday closes, with an optional manual override.

Sweep and break logic is evaluated only on closed bars. Sweeps mark a bar that trades through a level and closes back inside; breaks require a close beyond. Only the first event per level per period triggers optional pop-up...

πŸ‘‰ Read | Forum | @mql5dev
❀16πŸ‘2🀩2πŸ†1
A divergence is flagged when price prints a new extreme and the oscillator fails to confirm it. Many indicators look correct on history but fail live due to swing hindsight and repainting. This implementation keeps historical display identical to what was available at the time.

It supports RSI (default), MACD histogram/line, Stochastic %K, CCI, or Momentum. Regular divergences are drawn with solid lines, hidden with dotted lines, plus an arrow on the confirmation bar in the oscillator and optionally on price.

Swings are confirmed only after N closed bars (default 3). Signals are emitted on the bar where the second swing becomes confirmed, never backfilled. Closed bars only; once plotted, signals are never moved or deleted.

Filters reduce false positives: swing alignment within a bar limit, no crossing of the swing-to-swing baseline, configurable swi...

πŸ‘‰ Read | Signals | @mql5dev
❀15🀩4πŸ‘3πŸ”₯2
Currency Strength Free MT4 is a standalone MQL4 indicator that displays relative strength for EUR, USD, GBP, JPY, CHF, AUD, CAD, and NZD, plus a ranking of up to 28 supported forex crosses. It targets discretionary analysis and education and does not perform automated order placement.

The dashboard shows eight color-coded strength bars sorted by current momentum, a pair list ranked by base/quote strength gap, and configurable context via timeframe and closed-bar lookback (defaults: H1, 12 bars). It includes symbol discovery for broker prefixes/suffixes and a Market Data Quality panel covering synchronized pair availability, data gaps, partial history, and stale quotes.

Calculations use completed candles only: recent log changes are scaled by observed return variability, contributions are assigned to base and quote currencies, then normalized to a 0–100 ...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘9❀7🀩3