MQL5 Algo Trading
577K subscribers
4.56K photos
7 videos
4.57K 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
An ICT-style dealing range indicator calculates the current leg from confirmed swing points and plots premium/discount structure with non-repainting logic. The range starts at the older of the last confirmed swing high/low, then expands as new highs or lows print until a new confirmed swing resets it. Swings require N candles on both sides (default 10), confirmed only after right-side closes.

Rendered levels include equilibrium (50%), premium and discount zones, plus OTE as the 62%–79% band with a 70.5% line. Direction is classified as up leg when the low precedes the high, otherwise down leg, placing OTE in the expected zone per ICT conventions. Optional retracements and standard deviation projections are supported.

IPDA reference ranges (20/40/60 completed trading days) are plotted with merged labels for equal levels. Alerts fire on candle close fo...

πŸ‘‰ Read | Quotes | @mql5dev
❀7πŸ‘5🀩5πŸ”₯2
CMECalendar.mqh provides rule-based session halts for CME Globex equity index futures in New York time, aimed at EAs that must exit before the daily stop or avoid trading on short sessions. It covers regular 17:00 halts, full closures (New Year’s Day, Good Friday, Christmas), 13:00 early halts on major US holidays, 13:15 halts on 3 July, the day after Thanksgiving, and 24 December, plus the 09:15 Good Friday halt when it coincides with the US jobs report. Holiday observance shifts are handled, and Good Friday is computed via the Gregorian Easter algorithm.

Unpredictable one-offs are handled through a small CME_SPECIAL_DAYS string. All functions use New York dates/times; server time must be converted using the broker offset.

CMECalendarScan.mq5 validates the rules against M1 history by finding the last real trade per day, accounting for stray weekend/after-h...

πŸ‘‰ Read | Forum | @mql5dev
❀7πŸ‘7🀩4πŸ”₯3
An ICT Power of Three workflow relies on tracking higher-timeframe candle structure while executing on lower timeframes. This indicator renders one or two higher-timeframe candles at their real price levels beside the active chart, allowing an H4 or D1 candle to be monitored while trading M5 or M15.

It shows the last completed candles plus the live candle, with auto timeframe pairing (for example M5 -> H1 + H4, M15/M30 -> H4 + D1, H1 -> D1 + W1). Each set includes timeframe, time remaining to close, and whether price is above or below the open. Live candles project dashed open/high/low references back to where they formed. Labels avoid overlap, and hover displays OHLC. Optional prior candle high/low can be plotted.

Candles are synthesized from current-chart bars (first open, last close, max high, min low) with no external timeframe data loading, matc...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘8❀5🀩3πŸ”₯2πŸŽ‰2⚑1
RegimeHMM.mqh implements market regime detection using a Hidden Markov Model. Returns or custom feature vectors are modeled as emissions from a small set of Gaussian states, with state transitions governed by a Markov chain. The implementation supports multiple features, full covariance, and runs without DLL dependencies.

Model fitting uses Baum-Welch with scaled forward-backward to avoid underflow on long series. Initialization is based on k-means++ with multiple restarts, keeping the best likelihood. Covariance stability is enforced with a small variance floor, and states are sorted by the variance of the first feature so regime 0 is consistently the lowest-volatility state.

Outputs include filtered probabilities per bar for non-look-ahead use, smoothed posteriors for charting, the Viterbi path, expected state durations, transition-matrix forecasts, and l...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘11πŸ”₯5❀4🀩4
Margin Call Radar is a read-only risk panel for MetaTrader 5 focused on margin call and stop out proximity, plus projected margin level under adverse moves. It does not open, modify, or close orders, so it can run alongside EAs or manual trading.

It reports margin level (%) with status colors, and distance to margin call/stop out in account currency, % of equity, and points for the netted book. Hedge handling is net exposure per symbol; fully hedged books return points as n/a. Brokers with stop out in money or percent are supported.

Shock scenarios include adverse price moves of 1% and 3% across positions and a 5% equity drop, each returning the resulting margin level. A positions table shows symbol, side, volume, and P/L including swap.

Calculations use margin level = equity/margin*100, refreshed by timer. A separate core library ships with a test ...

πŸ‘‰ Read | Signals | @mql5dev
πŸ‘12πŸ”₯5❀4🀩3
Kalman.mqh provides a Kalman filter and smoother for linear Gaussian state space models with one observation per bar. It uses exact diffuse initialization (Durbin–Koopman), accepts missing values, and avoids ad-hoc β€œstarting variance” tuning. No DLL is required.

Three models can be fitted by maximum likelihood: local level, local linear trend, and time-varying regression (e.g., drifting hedge ratio). Custom models can be set via SetModel(Z,T,Q,H), then run with Filter(y) and Smooth(). SetDynamicRegression() runs with user-chosen variances.

Outputs include filtered and smoothed states with standard deviations, one-step forecast errors and variances, forecasts of y, exact diffuse log-likelihood, AIC/BIC, and diffuse-bar count. Variances are optimized on log scale using a multi-start grid plus BFGS and Nelder–Mead. Numerical stability is handled via rank-...

πŸ‘‰ Read | VPS | @mql5dev
❀10πŸ‘10πŸ”₯5🀩1🀣1
News Lines 1.30 for MetaTrader 5 adds an on-chart economic calendar with a movable event panel. Scheduled releases are rendered as vertical lines at exact timestamps, color-coded by impact, with tooltips showing time, currency, event name, forecast, previous, and actual values. Events sharing the same minute are consolidated into a single line and tooltip.

The panel lists upcoming and recent releases with countdowns, supports drag, resize, collapse, and scrolling, and includes quick filters for labels, impact level, instrument groups, source selection, and font size. Clicking an event focuses the chart to that event across occurrences, with a Reset control to restore defaults.

Data can be sourced from the terminal’s built-in calendar or a weekly JSON feed via WebRequest. Refresh is periodic, settings persist across restarts, no DLL imports are used, and no...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘6πŸ”₯5❀4πŸ‘1🀩1🀣1
Cointegration.mqh provides cointegration diagnostics for multi-series price data, targeting pairs and spread trading workflows. It includes ADF unit root testing, Engle-Granger cointegration for 2–6 series, and Johansen trace and max-eigen tests, with p-values and critical values. It also outputs the spread, half-life of mean reversion, and spread z-score. Operation is self-contained with no DLL dependency.

ADF supports no constant, constant, linear, or quadratic trend, with fixed lags or selection via AIC/BIC/last-lag t-stat and a statsmodels-style default cap. Lag search reuses a single QR factorization per run. Engle-Granger runs OLS on the first series against the rest plus trend, then ADF on residuals with series-count-specific cointegration tables. Johansen supports multiple lagged differences and deterministic options; eigenproblems are solved symmetr...

πŸ‘‰ Read | AlgoBook | @mql5dev
πŸ‘6❀5πŸ”₯3🀩3
AttachExpert.mqh enables attaching an Expert Advisor to a chart from MQL5 with specified inputs and an explicit β€œAllow Algo Trading” state. Since MQL5 lacks a native API for this, the library generates a chart template containing an <expert> block and applies it via ChartApplyTemplate().

Unset inputs remain at default values. Template application is asynchronous; AttachExpert() waits up to 10 seconds for CHART_EXPERT_NAME to report the EA is running, or returns immediately when waitMs = 0, which is suitable when called from another EA. Applying to the caller’s own chart is not supported because the template would replace it. Trade permission is also constrained by the terminal AutoTrading button.

A bundled example script opens a chart and attaches the standard Moving Average example EA with selected inputs. Validation across multiple timeframes confirmed correc...

πŸ‘‰ Read | Freelance | @mql5dev
❀8πŸ‘6🀩4
Meta-labeling often treats heuristic win/loss labels as ground truth, even when fixed-horizon returns create systematic mislabels that a meta-filter will learn without warning. This article adds a label audit step using confident learning, implemented natively in MQL5 as CConfidentLabelAuditor.

The EA generates RSI/trend crossover candidates, builds a compact 4-feature vector (direction-normalized for shared long/short training), and labels each sample by the close N bars ahead. The auditor cross-fits logistic regression to get out-of-fold probabilities, builds a calibrated β€œconfident joint” confusion matrix, then ranks and prunes likely mislabels by low self-confidence.

A single input toggles training on raw vs cleaned rows, enabling Strategy Tester A/B runs. The system re-audits and refits on a rolling window, logs CSVs, and includes a FlagView indicator to ins...

πŸ‘‰ Read | AppStore | @mql5dev
❀12πŸ‘6πŸ”₯3🀩3
MetaTrader 5 custom symbols let developers generate synthetic instruments with their own ticks and bar history, but still use standard charts: indicators, objects, and even EAs. The article shows how to build derivative symbols from broker data or external feeds to add analysis types MT5 does not provide natively.

Equal-volume and equal-range bars are generated by reading M1 history or tick history (CopyTicks/CopyTicksRange) and writing bars via CustomRatesUpdate; live updates can be driven with CustomTicksAdd. This enables tick-count, real-volume (where available), or fixed-range bar formation, with history reset and incremental building handled in code.

Tick charts are upgraded into full-featured charts by storing each tick as an M1 bar, optionally using a ring buffer to keep a stable window size. A key engineering point is routing trade execution ...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀7πŸ‘5πŸ”₯3🀩3
A position manager for MT5 targets grid and martingale baskets on XAUUSD, forex, or indices by pairing one strong winner with one deep loser. It calculates profit plus swap and commission, then closes both when the combined result meets a configured minimum, closing the winner first to lock gains. No entries are opened.

Filtering can be limited to the chart symbol or applied across all symbols, and to a single magic number or all positions, including manual trades. Optional basket-level take profit and stop loss in account currency can flatten all managed positions.

Execution is defensive: each close checks the return code and retries after a pause. A minimal panel shows managed positions, floating result, best and worst tickets, pair sum versus the threshold, and controls for pair close, close all, and pause. Pair logic is isolated in XP_FindPair and XP_Clos...

πŸ‘‰ Read | AppStore | @mql5dev
❀14πŸ‘7🀩4πŸ”₯2⚑1
Major LLM vendors are aligning on shared expectations for model interoperability and evaluation. Gemini, Mistral, Claude, and Perplexity are signaling interest in common interfaces, clearer capability reporting, and more consistent safety and reliability testing.

For engineering teams, this can reduce integration friction across providers, improve portability of prompt/tooling stacks, and make vendor comparisons less ambiguous. Focus areas likely include standardized tool-calling schemas, response formatting guarantees, and reproducible benchmark disclosure.

If this coordination continues, procurement and architecture decisions may shift from vendor-specific adapters toward simpler abstraction layers, with more attention on latency, cost, context limits, and compliance.

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘8❀6πŸ”₯3
DataSnooping.mqh adds data-snooping controls to strategy and parameter optimizations, addressing whether the top result is statistically better than a benchmark or simply the best outcome among many trials.

It implements Hansen’s SPA test, White’s Reality Check, the Romano-Wolf StepM procedure, and the Hansen-Lunde-Nason model confidence set. Resampling is done with a stationary bootstrap to preserve dependence in daily returns, with a configurable seed and no DLL requirement.

Components include CSuperiorAbility (SPA p-values, Reality Check, critical values, and StepM results), CModelConfidenceSet (per-strategy p-values and best-set selection using R or max statistics), and CStationaryBootstrap (bootstrap indices and efficient mean computation). A provided example generates 100 moving-average rules or reads CSV returns, illustrating how single-test...

πŸ‘‰ Read | Calendar | @mql5dev
❀12πŸ‘5🀩3πŸ”₯2
Session Range Breakout displays the intraday high/low for up to three configurable sessions and keeps those levels visible after the session ends by extending them to the right.

Sessions are defined by start hour (inclusive) and end hour (exclusive) in server time. While a session is active, the running high and low are tracked. After the close, both levels are finalized and drawn as dotted lines, with optional β€œNAME H / NAME L” labels and an optional thin range rectangle. Values are not recalculated later, so the output does not repaint.

Configuration includes per-session enable/disable, name, hours, and color, plus history depth, extension length (bars), and line width. Optional features cover labels, the range rectangle, and alerts (popup, sound, push) when a bar closes outside a session range. An auto-zoom option can rescale the chart on load to ...

πŸ‘‰ Read | VPS | @mql5dev
❀8πŸ‘5🀩4πŸ”₯1
Swap is presented as a single value in the terminal, but it consists of two components: carry (interest-rate differential) and broker markup (financing fee). Carry changes sign between long and short, while markup is paid in both directions.

Given long and short swaps for a symbol, markup and carry can be derived as:
markup = -(long + short) / 2
carry = (long - short) / 2

The script normalizes all swap calculation modes into one comparable metric: annual percentage of the position notional. This enables direct comparison across FX, metals, indices, and commodities.

This matters for multi-week holding strategies where daily markup compounds into a material drag. A 0.75% annual markup on FX or 2.5% on index CFDs can eliminate expected returns even when price-only backtests look acceptable.

Output includes an on-chart table with risk bands, a full ranked...

πŸ‘‰ Read | VPS | @mql5dev
❀12πŸ‘5🀩4πŸ”₯3πŸŽ‰1
A non-repainting three-bar Fair Value Gap detector for MT5 is available, based strictly on closed-bar data. Each imbalance is drawn as a rectangle with an optional 50% Consequent Encroachment line. Gap levels are derived from three closed candles (pre-impulse, impulse, and the candle that leaves the imbalance) and are persisted without later rewriting.

The gap lifecycle is implemented as an explicit state machine. In TRIM mode, a gap is anchored to the first closed bar that trades into it, preventing rectangles from extending into future bars after mitigation. Mitigation display is selectable: TRIM shortens, DELETE removes, DIM greys out, and NONE leaves full length. Open gaps can be forward-extended via a configurable bar count.

Processing is incremental, scanning only newly closed bars instead of rebuilding history on each tick. A self-audit can re...

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘7❀6πŸ†3πŸ”₯2🀩2
A trade manager for MetaTrader 5 that splits take profit into up to five levels (TP1–TP5) for any existing position on XAUUSD, FX pairs, indices, or crypto. Distances can be set in points or as multiples of stop loss (R), with per-level close percentages and optional β€œclose remainder on last active level”.

The tool monitors manual trades and positions opened by other experts, with filtering by symbol scope and magic number. It never opens trades and performs partial closes immediately on level hits, rounding volumes to broker lot step and closing the position fully if the remainder would fall below minimum lot. Taken levels are persisted via terminal global variables to avoid repeats after restarts.

Risk controls include optional automatic stop loss assignment, breakeven move after a selected TP level with offset, and trailing stop that activates only after...

πŸ‘‰ Read | Signals | @mql5dev
❀10πŸ‘9🀩3
GM Matrix Monitor is a read-only dashboard for supervising multi-EA accounts without repeatedly opening the terminal. It aggregates per-magic net P/L by combining closed deals with current floating profit, and presents each EA’s running result in a single column.

Risk visibility is provided via real-time drawdown, calculated from current equity against a configurable reference balance. It also tracks realized losses since day start against a daily-loss cap, and signals proximity to freeze and liquidation thresholds using color states (green/amber/red) based on user-defined percentages.

Setup consists of attaching the panel to a chart, entering a comma-separated magic list, selecting a base equity (or current balance), and configuring freeze, liquidation, and daily-loss limits. The tool reads history and positions only; it does not send, modify, or close ord...

πŸ‘‰ Read | Forum | @mql5dev
❀6πŸ‘4🀩3πŸ”₯1
EAs that trade New York hours need a reliable broker server offset to UTC. Many brokers run UTC+2 in winter and UTC+3 in summer, but apply either US or EU daylight rules, creating 1-hour errors during the spring and autumn gaps between clock changes.

TimeTradeServer() - TimeGMT() works on live charts but depends on the local PC clock and becomes unusable in Strategy Tester, where TimeGMT() mirrors simulated server time. BrokerClock.mqh instead infers the offset from H1 history by using the known weekend close for CME-linked symbols: the last H1 bar before the weekend ends at 17:00 New York, which maps to a specific UTC instant.

The library scores candidate offset rules (fixed, US DST, EU DST) across up to 60 weekends, prioritizing the last 8 weeks, then breaks ties with the full set. It provides current server offset, live cross-check offset, calendar-based NY/L...

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘6❀4πŸ”₯1