MQL5 Algo Trading
577K subscribers
4.54K photos
7 videos
4.54K 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
Spread Monitor is a lightweight information indicator for MetaTrader 5 focused on real-time spread visibility.

It shows the current spread in pips along with Bid and Ask values. The display uses configurable color states (green, yellow, red) to reflect low, medium, and high spread conditions. Language support is available in Russian and English. The UI is limited to a single text panel to keep chart rendering clean.

Key settings include language selection, X/Y offsets for panel placement, MidThreshold and HighThreshold in points, per-state colors (ColorLow/ColorMid/ColorHigh), and font size.

Typical use is spread verification before order placement, especially around news releases and during low-liquidity sessions where execution costs can change quickly.

πŸ‘‰ Read | NeuroBook | @mql5dev
❀18πŸ‘12πŸ”₯7🀩7πŸ‘Œ1
This EA builds signals on a classic two-brick Renko reversal. Oscillators update only on completed bricks, with one active mode: RSI Re-entry, RSI Midline, MACD Signal, or MACD Zero. RSI uses Wilder smoothing; MACD is EMA-diff with an SMA signal line. Periods count completed bricks. Multi-brick completion in one tick updates per brick, but only the last brick can trigger an entry. Orders execute at market quotes; blocked signals are not queued.

Entry is blocked if a position or order already exists for the symbol/Magic. Exits rely on virtual SL/TP or a holding-time limit; opposite signals do not close positions. A brick-based cooldown applies after exit; spread-to-brick filtering affects entries only.

A included test example reports XAUUSD M1 real-tick backtest results (Jan–Oct 2026): 178 trades, PF 1.49, max DD 5.99%, net profit $2,348.57. Parameters were chos...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘16❀15πŸ”₯11πŸŽ‰1🀩1
A Risk of Ruin script estimates the probability of hitting a defined drawdown floor before a strategy’s edge shows up. It reads closed trades from account history, converts each result into an R-multiple (net P&L divided by average absolute loss), then runs a bootstrap simulation.

Each simulated path resamples historical R-multiples with replacement, applies a user-selected risk % per trade, compounds equity trade by trade, and flags β€œruin” if equity drops below the configured floor. The method is independent of the original traded lot sizes; only the win/loss distribution and current risk settings drive outcomes.

Reported metrics include chance of hitting the floor, chance of ending profitable, median ending balance, and the 95% range of final balances. Median is used to reduce distortion from long-tail winners. Higher risk per trade typically increases th...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ‘14❀10πŸ”₯6🀩2πŸ†2
Prop Firm Guard is a risk-control Expert Advisor designed to enforce two common prop firm constraints: daily loss limit and maximum drawdown. It does not open trades and can run alongside manual trading or other EAs, attached to any single chart while monitoring the entire account.

Equity is checked every second. When a limit is reached, it closes all open positions, deletes pending orders, and can optionally close any new trade opened while the breach persists. Alerts and optional push notifications are supported, with all actions recorded in the Experts log.

Daily loss can reference either balance or the higher of balance and equity at the daily reset. Maximum drawdown supports static or trailing modes, with an optional safety margin to act before the threshold. State is persisted across restarts and reconnections, and the chart displays live usage plus n...

πŸ‘‰ Read | CodeBase | @mql5dev
❀11πŸ‘9🀩6πŸ”₯3
Failed Breakout Detector flags range breakouts and highlights those that reverse back into the prior range. It is a price-action utility focused on identifying trapped breakout traders, not forecasting direction.

The range is defined as the highest high and lowest low of the last N bars (default 12), filtered by range height (0.5–4.0 ATR). A breakout requires a close outside the range by an ATR-based buffer (default 0.1 ATR) and is marked with a blue dot.

If any of the next K bars (default 3) closes back inside the range, the breakout is classified as failed: red arrow for failed breakout up, green arrow for failed breakout down. If price holds outside for K bars, the breakout is confirmed and no further marks are added. Calculations use closed bars only, so signals do not repaint.

A corner label counts failed breakouts for the current day (up/down)...

πŸ‘‰ Read | AppStore | @mql5dev
❀12πŸ‘12πŸ”₯5🀩3⚑2
XlsxWriter.mqh generates valid .xlsx workbooks directly from MQL5. No DLL dependency and no local Excel installation are required. Output is a ZIP container of Office Open XML parts, stored uncompressed with CRC-32 per part.

Supports multi-sheet workbooks with text, numbers, and proper Excel date serials for correct sorting and filtering. Each sheet can be created with a bold header row, frozen panes, and auto-filters. Column widths are configurable, with eight built-in number formats: date-time, date, month, money, integer, price (5 decimals), percent, and 2-decimal.

Unicode text is handled as UTF-8. Designed to run in scripts, Expert Advisors, and the Strategy Tester, including writing to FILE_COMMON from OnTester.

Example: ExportDealsToXlsx.mq5 exports account history deals into a Deals sheet and aggregates daily results into a Daily sheet. Place XlsxWr...

πŸ‘‰ Read | Calendar | @mql5dev
❀15πŸ‘9πŸ”₯8🀩2πŸ‘¨β€πŸ’»2πŸ†1
Order blocks in SMC/ICT are typically defined as the last opposite candle before a displacement that breaks market structure. A bullish OB is the final down candle near the low of the leg that precedes a close above the last swing high. A bearish OB is the final up candle near the high of the leg that precedes a close below the last swing low. Swings are confirmed using an N-candle strength setting (default 10).

The indicator plots active OB zones as right-extended boxes (green bullish, red bearish) and tracks failures as breaker blocks (blue). Used and broken zones can be kept as grey boxes terminating at the touch/break candle for review. β€œUsed up” logic is configurable: touch, 50% mitigation, or only on a closing break.

Signals are non-repainting due to closed-candle swing and break confirmation. Zones can use full candle range or body, with an optiona...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀17πŸ‘11πŸ”₯9🀩8⚑1
ICT kill zones define time windows where higher activity is expected, expressed in New York local time: Asian 20:00-00:00, London 02:00-05:00, New York 07:00-10:00, and London Close 10:00-12:00. Each session window can be customized (HH:MM-HH:MM, NY time).

A common platform issue is broker server time versus New York time, including mismatched US and EU DST switch dates. The indicator converts candles to New York time so session boxes remain aligned year-round. Server clock handling supports Auto (reads terminal GMT offset), the typical β€œNew York + 7h” forex server setup (GMT+2/GMT+3 with EU DST rules), or a fixed GMT offset.

It draws each kill zone box from high to low with labels, extends finished session highs/lows until traded through, and marks the 00:00 New York open as a dashed line. It can display recent trading days, supports M1-H1, and show...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘13❀11πŸ”₯11🀩8⚑3
TesterStats.mqh computes Strategy Tester report statistics directly from deal history, including metrics not available via TesterStatistics(): Z-Score, AHPR, GHPR, LR Correlation, and LR Standard Error. Output can be used for custom optimization criteria or to match backtest report values on a live account.

Validation was done across 5 scenarios (EURUSD, USDJPY, XAUUSD; fixed lots and percent risk; with and without TesterWithdrawal) by comparing 44 fields against TesterStatistics() and the HTML report. With β€œ1 minute OHLC” and β€œEvery tick”, all 44 matched. With β€œEvery tick based on real ticks”, equity is sampled less frequently, producing equity drawdown 0.05%–0.26% deeper, while other values remained identical.

Report rules implemented: 0.00 result counts as profit; post-start deposits/withdrawals excluded from balance drawdown; equity drawdown re...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘16❀10πŸ”₯8🀩6
LLM-driven trading in MetaTrader breaks quickly when the EA only asks for BUY/SELL. Practical constraints include M15–H1 operation, 30–90s inference latency, upcoming news within 10 minutes, max 3 open positions, and ~1% risk per trade.

A workable design separates thinking from execution and enforces sequential filters: Signal β†’ News β†’ Risk. The MQL5 EA becomes pure I/O on new-bar events, while a local Python server (LangChain) handles indicators, agents, and SQLite logging with decision_id plus a RESULT feedback loop.

Transport runs over a persistent local WebSocket on 127.0.0.1:8977 using a small command set (ANALYZE, RESULT, MEM_STATUS, STATUS, STOP) with separate long/short timeouts. Every decision, including hold, is recorded, and closed-trade PnL (with swap/commission) is returned to update agent_stats.

πŸ‘‰ Read | CodeBase | @mql5dev
❀14πŸ‘14πŸ”₯9🀩7πŸŽ‰2πŸ‘Œ2🀝1
RAFT is adapted from optical-flow estimation to market time series by treating prices as continuous motion, focusing on direction and strength rather than isolated bars. Its recurrent refinement loop repeatedly updates the state, staying stable during volatility and regime shifts.

The implementation reframes RAFT’s correlation space into a temporal pyramid: multiscale correlations are computed along the time axis to capture both microstructure noise and longer trends. Recent state stacks replace a single initial state to preserve momentum and inertia.

On the MT5 side, a CNeuronMultiScaleStackCorrelation component extends stack correlation with OpenCL-backed aggregation, matrix products sized by (stackSizeΓ—levels), and optional activation. A dedicated backward path propagates gradients through both matmul and time aggregation, keeping training intact while remaini...

πŸ‘‰ Read | Calendar | @mql5dev
❀18πŸ‘15🀩12πŸ”₯8✍2
Session-filtered EAs often fail silently around DST. TimeCurrent() is broker server time, shifted by the broker, and it updates only on ticks. A hardcoded β€œLondon 10:00 server” can become one hour early or late after clock changes, with no Experts log errors.

The risk peaks when US and EU DST calendars diverge. US: second Sunday in March to first Sunday in November. EU: last Sunday in March to last Sunday in October. The mismatch windows are 2–3 weeks in spring and 1 week in late October, changing London/New York spacing from 5 hours to 4.

A practical fix is calendar-based offset calculation that works identically live and in Strategy Tester, where TimeGMT() equals server time. Build an include that computes broker DST state and converts UTC session definitions into broker-hour at runtime (London/New York/Tokyo), replacing fragile fixed-hour filters.

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘20❀18πŸ”₯15🀩14
MetaTrader 5 optimizations can β€œwin” by fitting noise, especially when a sweep evaluates thousands of parameter sets on the same history. This article implements Bailey et al.’s Probability of Backtest Overfitting (PBO) using Combinatorially Symmetric Cross-Validation (CSCV) to quantify that risk and reject an optimization when PBO exceeds 5%.

Instead of a single in/out split, the history is partitioned into 16 contiguous blocks and evaluated across all 12,870 half/half block combinations. For each split, the best in-sample parameter set is selected, then its out-of-sample rank among all candidates is measured; PBO is the frequency that this choice falls into the bottom half.

The MT5 implementation focuses on practical correctness and speed: log returns for additivity, signals lagged by one bar to avoid look-ahead, data-driven threshold ranges via ...

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘21πŸ”₯17❀14🀩13πŸ†1
Probability theory models data D given parameters ΞΈ via p(D|ΞΈ). Mathematical statistics inverts this: estimate ΞΈ from D. Bayesian inference treats ΞΈ as a random variable, updating prior P(ΞΈ) into posterior P(ΞΈ|D) using Bayes’ theorem, with today’s posterior becoming tomorrow’s prior.

In the discrete case, hypotheses H1..Hk get priors P(Hi) and likelihoods P(D|Hi). Posteriors follow from P(Hi|D) ∝ P(D|Hi)P(Hi), with normalization via total probability. A coin example shifts belief from 0.5 to 0.833 after one head.

For count data, a Poisson tick-rate model can combine an informative prior (e.g., mean 150) with new observations, using grid approximation, log-likelihoods, and logsumexp for numerical stability.

Continuous parameters replace sums with integrals, making evidence hard to compute at scale. Conjugate priors (e.g., beta-binomial) keep updates in closed ...

πŸ‘‰ Read | VPS | @mql5dev
πŸ‘29πŸ”₯21🀩15❀14
A PPO-based RL trading pipeline tested a behavioural-cloning loop that re-trains the policy from its own live demo trades. Over two months, models produced under heavier cloning degraded and shifted toward inaction, including cases where they stopped trading entirely.

Live decisions were logged as (observation, action) with outcome metadata. Cloning applied weighted cross-entropy after each rollout plus a two-epoch pre-training pass for final models. Weights came from trade R-multiples, spread across all steps in a trade.

Two failures surfaced. A feature-schema change invalidated most buffered episodes without purge. More materially, after usable episodes appeared, final-model evaluation showed higher Hold shares, far fewer Buy/Sell actions, more negative Sharpes, and 12 models that never traded. Trials using only the light callback did not show the same s...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘26πŸ”₯25🀩19❀12
Classic volatility indicators (EWMA, ATR, GARCH) collapse price action into squared returns, so a steady selloff and a noisy range can look identical. This article implements the Guyon–Lekeufack path-dependent volatility model in MQL5, explicitly retaining direction.

The model predicts volatility from two streaming features: a trend term (kernel-weighted signed returns) and an activity term (kernel-weighted squared returns). Both use a two-timescale exponential mixture (fast/slow half-lives). The per-bar update is O(1): four accumulators, cached decays, no lookback arrays or matrix work.

Calibration splits the problem: a simplex searches six kernel parameters while linear regression solves the three coefficients exactly, with leakage-safe, chronological out-of-sample testing against EWMA and GARCH(1,1). Results show the trend component materially impr...

πŸ‘‰ Read | Docs | @mql5dev
❀85πŸ‘29🀩27πŸ”₯23πŸ‘¨β€πŸ’»4πŸ†2πŸ‘€1
Educational example of a trend-following Expert Advisor in MQL5, focused on structure and runtime safety. Signals are generated on closed bars and evaluated only once per new bar: BUY when fast MA crosses above slow MA (bar 2: fast ≀ slow, bar 1: fast > slow), SELL on the inverse. The EA waits for the first new crossover after startup, maintains a single position, and reverses on an opposite signal.

Order logic includes free margin validation via OrderCalcMargin, lot normalization to symbol min/max/step, and SL/TP adjustment to SYMBOL_TRADE_STOPS_LEVEL. Execution applies a spread filter, slippage limit, and retries on requotes or price changes, but only until the signal bar ends. Indicator handles are released in OnDeinit, with English/Polish messages based on terminal language.

Runs only in Strategy Tester and on demo; live trading is blocked. Provided β€œas...

πŸ‘‰ Read | CodeBase | @mql5dev
❀21🀩7πŸ‘4πŸ”₯2😁2✍1πŸŽ‰1
Educational example of a trend-following Expert Advisor in MQL5, focused on structure and runtime safety. Signals are generated on closed bars and evaluated only once per new bar: BUY when fast MA crosses above slow MA (bar 2: fast ≀ slow, bar 1: fast > slow), SELL on the inverse. The EA waits for the first new crossover after startup, maintains a single position, and reverses on an opposite signal.

Order logic includes free margin validation via OrderCalcMargin, lot normalization to symbol min/max/step, and SL/TP adjustment to SYMBOL_TRADE_STOPS_LEVEL. Execution applies a spread filter, slippage limit, and retries on requotes or price changes, but only until the signal bar ends. Indicator handles are released in OnDeinit, with English/Polish messages based on terminal language.

Runs only in Strategy Tester and on demo; live trading is blocked. Provided β€œas...

πŸ‘‰ Read | Docs | @mql5dev
❀21πŸ‘9🀩5πŸ”₯4😐2✍1
Educational mean-reversion Expert Advisor built around Bollinger Bands, with an optional RSI filter. Entry logic uses two completed bars: BUY when bar 2 closes below the lower band and bar 1 returns inside the bands (optional RSI on bar 2 below 30). SELL mirrors this using the upper band (optional RSI above 70).

Exits trigger on a touch of the current middle band (BUY: Bid β‰₯ middle, SELL: Ask ≀ middle) or Stop Loss. Trading hours restrict only new entries, including overnight windows such as 22:00–06:00; closing always remains active. An option is provided to force closing outside the time window. Max concurrent positions is configurable.

Implementation details include indicator handles with CopyBuffer validation, switchable filters, server-time windows crossing midnight, free margin/lot/stop-level checks, spread filtering, and order retry logic. Demo and S...

πŸ‘‰ Read | VPS | @mql5dev
❀22🀩13πŸ‘11πŸ”₯9πŸ†2😁1😐1
Educational breakout Expert Advisor using pending orders and a daily range built from M1 bars. After the configured range window (for example 00:00–07:00 server time), the EA calculates High/Low and places one set of orders per day: BuyStop above High with spread/shift, and SellStop below Low with shift. SL is set beyond the opposite side of the range, while TP is computed via a configurable risk/reward ratio.

On fill, the opposite pending order is deleted. Unfilled orders are removed at a cancel time, and an open position can be closed at a specified time. Breakout sides are skipped when price is already beyond the trigger level, and ranges outside min/max width are ignored. After terminal restart, order history is used to restore state and prevent duplicate daily placement.

The code demonstrates CTrade BuyStop/SellStop, broker distance adjustments for SL/...

πŸ‘‰ Read | Forum | @mql5dev
πŸ”₯20πŸ‘16❀15🀩5🀣3😁2πŸ†1
Spread Monitor is a single-file MQL5 Expert Advisor that displays the current spread for the attached symbol in a chart-corner panel with color status.

The EA reads SYMBOL_SPREAD (points) on a throttled, user-defined interval and stores samples in a fixed-size rolling buffer. From this in-memory history it recalculates current, average, minimum, and maximum spread, and counts how many samples exceed a configurable warning level to quantify how often spreads are elevated.

The status row switches to red when the current spread is above the warning threshold and green otherwise. History resets when the EA is removed, the symbol changes, or the terminal restarts. Panel objects use a fixed name prefix, enabling clean removal on exit without touching unrelated chart objects.

No orders are placed, modified, or closed, and trading by other programs is not blocked. I...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘22❀19πŸ”₯11🀩9🀣2