MQL5 Algo Trading
540K subscribers
3.86K photos
6 videos
3.87K 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 indicator implementation that models support and resistance as price zones instead of single horizontal levels. Zones are seeded from confirmed pivot highs and lows, then nearby pivots are merged using an ATR-based distance so behavior scales across symbols and timeframes.

Each zone is ranked using three inputs: the number of grouped reactions, the subsequent price displacement, and the recency of the last test. Only top-ranked zones are rendered, with areas below current price labeled as support and areas above as resistance.

Current classification depends on position versus the latest price. A stricter approach could require a confirmed break and retest before switching a zone’s role. The strength value shown is an internal score, not a trade signal or success probability.

πŸ‘‰ Read | Freelance | @mql5dev
❀96πŸ‘14😎6πŸŽ‰5πŸ‘Œ4⚑3πŸ‘€3
FoxWave Pip Value Calculator is an MT5 indicator focused on risk sizing and live position monitoring via a persistent on-chart panel. It calculates real-time pip value for 1.00 lot in account currency across Forex, indices, commodities, and crypto, handling 3/4/5-digit pricing automatically.

Risk controls include suggested lot size based on configured risk percent and stop-loss distance in pips, recalculated on updates. A separate volume analysis mode accepts a custom lot size and reports pip value for that volume plus actual risk in percent and account currency, with green/orange/red status based on distance from the target.

When a position exists on the current symbol, the panel shows open volume, pips gained or lost, and floating P/L including swap. Configuration covers panel placement, refresh interval, stop-loss input, and full color settings, u...

πŸ‘‰ Read | Quotes | @mql5dev
❀37πŸ‘7πŸ‘Œ2⚑1
An include file adds an explicit value-or-error return type for MQL5, avoiding dependence on the global GetLastError() / ResetLastError() state. This reduces accidental overwrites, removes the need for out-parameters, and replaces sentinel return values with a strict contract.

Functions return a single object holding either a value or an Error that must be checked before consumption. ResultValue<T> targets value types (numbers, structs), while Result<T> supports pointer-held objects (classes).

Error is a lightweight struct with code and description; codes can be converted to readable names via EnumToString. MQLError wraps GetLastError / ResetLastError / SetUserError for compatibility.

Macros (TRY, RETURN_ON_ERROR, PRINT_ON_ERROR, RETURN_SAME_ON_ERROR, RESULT_ON_ERROR) support early-return propagation. Optional callbacks Then, Match, MapError accept top-level o...

πŸ‘‰ Read | Signals | @mql5dev
❀22πŸ‘4πŸ’―4πŸ‘Œ2
Equity Guard is an account-level risk manager for enforcing a daily loss cap. When loss reaches a configurable trigger, it closes all positions and pending orders, then keeps the account flat until the next daily reset.

The tool is broker- and account-agnostic and works on any symbol/timeframe because it monitors the entire account. It should be attached to one chart per account. Reset time is configurable and interpreted in broker server time, with day-start reference captured from balance or equity.

Limits can be set as a percentage of day-start value or as a fixed amount in account currency. A pre-limit lock trigger supports early locking before the hard limit is hit. While locked, any positions opened by other EAs are closed immediately.

Includes manual CLOSE ALL and LOCK/UNLOCK with two-click confirmation, a draggable panel with live gauge, state pers...

πŸ‘‰ Read | AppStore | @mql5dev
❀23πŸ‘7πŸ‘Œ1
Structural break detection from AFML Ch.17 is ported from Python to MetaTrader 5 as CStructuralBreaks.mqh, delivering CSW CUSUM, Chow-type Dickey-Fuller, SADF (six models), plus SM-Exp and SM-Powerβ€”six values per bar with a consistent sentinel for missing data.

The key engineering decision is SADF on a rolling lookback window, making per-bar EA recomputation feasible while shifting the question to β€œexplosive within the last L bars,” which better matches regime switching.

Most porting errors come from reversed indexing. The implementation keeps series in MT5 time-series order but computes in chronological space with explicit mapping, preventing silent sign inversions.

Regression kernels use inline OLS with correct intercept handling (Chow no-constant; SADF/SMT with intercept), guarded against singular denominators. A viewer indicator supports cali...

πŸ‘‰ Read | Quotes | @mql5dev
❀30πŸ‘5πŸ†5πŸ‘Œ2πŸ€”1
This article converts Stan Weinstein’s Stage Analysis into a disciplined MQL5 Expert Advisor that trades only when the market is statistically favorable: Stage 2 uptrends and Stage 4 downtrends.

Market stage is derived from a 30-week MA concept adapted to Forex as a 150-day SMA. The EA classifies stages using MA slope (normalized by price), price position vs the MA, and recent higher-high/lower-low structure, with an enum-based state machine to act only on transitions.

Entries trigger on Stage 1β†’2 breakouts or Stage 3β†’4 breakdowns, validated by relative tick-volume expansion and RSI(14) momentum (>=50 for longs). Risk is managed with ATR-based stops, fixed R-multiple targets, and exits gated by MA breach plus high volume to avoid noise.

πŸ‘‰ Read | Calendar | @mql5dev
❀30πŸ‘6⚑2πŸ‘Œ2
Swiss Finance Institute tested Opening Range Breakout day trading on 7,000+ US stocks (2016–2023) and found performance improves sharply when trading only β€œstocks in play”: names with unusually high opening-range relative volume, consistent with institutional repositioning after overnight news.

The implementation filters for liquidity/volatility (price, ADV, ATR), then ranks symbols by 5‑minute relative volume versus a 14‑day baseline. Trades use stop entries at the first 5‑minute high/low with a simple bias rule, ATR‑scaled stops, 1% risk-based position sizing, and mandatory end‑of‑day exits to avoid overnight exposure.

In MQL5, the key engineering is time correctness: timer-driven scanning, NYSE session alignment across broker timezones with DST handling, plus a safety close for leftover positions. Backtests show controlled drawdowns and low trade frequen...

πŸ‘‰ Read | CodeBase | @mql5dev
❀37πŸ‘9πŸ‘Œ3πŸ”₯2πŸ‘2🀝2πŸ€”1
FoxWave SR Zone Scanner is an MT5 indicator that detects and draws supply and demand zones from multiple timeframes (M15, H1, H4, D1) on a single chart. Zones are derived from clustered pivot highs/lows to reflect repeated reaction structure rather than manual markings. Higher-timeframe zones are rendered with stronger color saturation for quick weighting on lower chart periods.

Each zone includes a touch-count label (for example, H1 [4x]) and supports a configurable minimum touch threshold to reduce noise. Zones are tracked as active or broken based on candle closes through the level, preventing outdated alerts and keeping the chart state current.

Alerts trigger when price approaches or enters a zone, with configurable distance in pips and independent popup, push, and email switches. An info panel summarizes nearest supply/demand levels, their timefr...

πŸ‘‰ Read | CodeBase | @mql5dev
❀30πŸ‘8πŸ”₯4πŸ‘Œ2
Multi-Timeframe Candle Map reports the current price location inside the active candle across four selectable timeframes. Instead of comparing raw points between M15, H1, H4, and D1, it normalizes position as: (price - low) / (high - low) * 100. Values near 0% indicate proximity to the candle low, near 100% to the high.

The panel renders each timeframe as a vertical gauge with Near Low / Lower Half / Upper Half / Near High classification, candle body direction, and time remaining to close. It also calculates the average position, the spread between highest and lowest readings, and a short alignment summary when multiple timeframes cluster near the same edge.

Key inputs include timeframe selection, Bid vs CopyRates close, edge threshold, alignment count, and optional alerts on new edge alignment. The implementation serves as a developer reference for ...

πŸ‘‰ Read | Calendar | @mql5dev
❀42πŸ‘10πŸ‘Œ3
Multi-broker MT5 analysis breaks the single-schema assumption. CSV exports can load cleanly while producing incorrect results due to mismatched pip precision, commission accounting, symbol aliases, server time zones, and account currencies.

A normalization contract mitigates silent corruption by emitting a canonical DataFrame: canonical symbol, UTC timestamps, 5-digit point convention, and net/gross/commission figures converted to USD. Broker-specific behavior is isolated in a profile registry, so adding a broker becomes a dictionary change, not a logic rewrite.

The export side extends the EA to include broker metadata per row (server, currency, symbol digits, commission inputs, measured slippage). The Python layer then scales points for 4-digit feeds, maps symbols, reconciles time offsets to UTC, computes commission in basis points, and logs anomalies f...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀31πŸ‘5πŸ‘Œ2
MetaTrader 5 lacks a native, structured daily trade report with formatted email delivery. An MQL5 Expert Advisor can automate this using SendMail() and history queries.

Core flow: define the prior completed D1 window via iTime (index 1 start, index 0 end), call HistorySelect(), iterate closed deals only, then aggregate totals for profit, trade count, wins, and losses.

Report composition uses a time-scoped subject and a body that includes account name, login, base currency, and the computed metrics. Delivery logic tracks the last sent D1 timestamp to ensure a single email per day, triggered on daily candle rollover.

πŸ‘‰ Read | Quotes | @mql5dev
❀34πŸ‘9πŸ‘Œ3πŸ”₯1
A runtime recovery system can be correct and still be opaque during live trading. State transitions mostly occur in memory, SQLite rows, and logs, which scales poorly as protection workflows and reconciliation logic grow.

A chart-level dashboard adds observability without changing the recovery architecture. It surfaces EA state, active ticket, symbol, direction, virtual SL/TP, breakeven and trailing flags, plus recovery indicators such as database status, sync status, and heartbeat age.

Implementation is straightforward: a prefixed panel, label helpers, enum-to-text converters, and an UpdateDashboard routine. Wire it into OnInit (create + initial render), OnTimer (refresh after management logic), and OnDeinit (cleanup). Safe-Mode becomes immediately visible when records are missing or integrity checks fail.

πŸ‘‰ Read | Calendar | @mql5dev
❀22πŸ‘14πŸ‘¨β€πŸ’»2⚑1πŸ‘Œ1
Outlier bars can quietly corrupt indicator inputs: one extreme candle inside a fixed lookback inflates mean and standard deviation, distorting ATR, Bollinger Bands, volatility filters, and any stop logic derived from them.

A native MQL5 indicator is designed to detect these anomalies with robust statistics. It models each bar using four features: body size, upper wick, lower wick, and tick volume, then replaces mean/std with rolling median and MAD to compute Modified Z-Scores.

Per-feature scores are merged into a composite via mean absolute deviation, with configurable mild/strong thresholds. The tool plots a histogram score and marks flagged bars, helping traders isolate news spikes, gaps, and feed artifacts without rewriting existing strategies.

πŸ‘‰ Read | Signals | @mql5dev
❀28⚑5πŸ‘5πŸ’―3πŸ‘Œ2
The article extends an MQL5 technique for editing chart text in-place: any OBJ_LABEL can be clicked and temporarily converted into an OBJ_EDIT, letting users change text without opening Object Properties.

A key fix is refining event handling so only one edit control exists at a time, avoiding multiple OBJ_EDIT instances caused by selection/deselection edge cases.

It also tackles the β€œcan’t move while editing” problem by toggling OBJPROP_SELECTABLE on the fly: one click enables MT5-driven dragging, the next disables selection to allow text input, and release events are used to finalize or revert back to OBJ_LABEL.

The next step previews mouse-based resizing without direct mouse hooks by steering standard MT5 object events.

πŸ‘‰ Read | AppStore | @mql5dev
❀16πŸ‘15πŸ‘Œ1
Small tweaks in neural-network training can explode runtime in MT5. Dropping the target error from 1e-3 to 1e-4 pushed a single-neuron trainer from under a second to ~80 seconds, showing how tighter tolerances amplify repeated cost evaluations.

The fix wasn’t GPU code or parallelism, but restructuring. By specializing the neuron for a known shape (2 inputs, 1 output) and replacing a generic Cost routine with a tailored Cost_2, the code avoids rescanning the training set multiple times per step and computes related errors in one pass, cutting runtime to ~18 seconds at the same precision.

Key takeaway for traders and MQL5 developers: profile training loops, reduce redundant passes over data, and specialize only where the model’s input/output structure is stable.

πŸ‘‰ Read | Calendar | @mql5dev
❀20πŸ‘11πŸ‘Œ1
ACEFormer extends time-series forecasting for noisy markets by pairing ACEEMD denoising (explicitly dropping the first IMF to reduce high-frequency noise while keeping turning points) with a Transformer distillation stack that mixes probabilistic attention for informative regions and standard self-attention for global context.

The article focuses on integrating the OpenCL probabilistic-attention kernels into an MT5-side module: CNeuronMHProbAttention. It inherits a residual two-convolution backbone, keeps internal components statically allocated for predictable lifetime, and centralizes setup in Init, including Top-K queries and random key counts computed from sequence length.

Key handling is practical: a single index buffer stores both sampled keys and selected queries sized by max(randomKeys, topK)*heads. Random key selection uses uniform stratif...

πŸ‘‰ Read | Calendar | @mql5dev
❀27πŸ‘5πŸ‘€4⚑3πŸ‘Œ1
MQTTFive is an MQTT 5.0 client library for MQL5, delivered as an #include package for MetaTrader 5 expert advisors and scripts. It connects directly to MQTT brokers such as Mosquitto, EMQX, and HiveMQ, enabling outbound publishing of prices/signals and inbound command handling for EA control and status monitoring.

The implementation is pure MQL5 with an internal socket API and no DLL dependency. It supports QoS 0/1/2 with automatic retry, delayed publish queues, topic aliases, and flow control for receive quotas. MQTT v5 features include CONNECT/CONNACK properties (session expiry, packet limits, topic alias limits) and subscription options (no_local, retain_as_published, retain_handling). TLS/SSL, binary payloads, and UTF-8 are included.

Installation is file-copy based into MQL5/Include/MQTTFive/ and inclusion via MQTTClient.mqh. Core API: Connect, Disconnect...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀31πŸ‘8⚑2πŸ‘Œ1
Prop Firm Risk Dashboard is a lightweight, read-only account monitoring panel designed for prop-firm risk limits. Attach it to a single chart to monitor the entire trading account across any symbol and timeframe.

The panel displays balance and equity, floating P/L, today’s P/L based on equity change since the trading day start, daily loss usage versus a configurable daily-loss limit, max drawdown usage versus a configurable max-drawdown limit measured from a configurable starting balance, and current margin level. Status is color-coded (green/orange/red) as thresholds are approached.

Configuration inputs include daily-loss and max-drawdown percent limits, starting balance (0 uses current balance), warning and danger thresholds, and UI settings such as corner position, offsets, font, colors, and background. Day-start equity is stored in a terminal global var...

πŸ‘‰ Read | Calendar | @mql5dev
❀26πŸ‘10πŸ‘€2πŸ‘Œ1
Mamba4Cast targets real-time market forecasting where RNNs miss impulses and Transformers become too heavy. It combines Mamba state-space blocks (linear cost over sequence length) with Prior-data Fitted Networks, pretrained on many synthetic market-like tasks to enable zero-shot generalization across symbols and timeframes.

The pipeline normalizes inputs, adds timestamp-aware positional features (minute/hour/day/month/year) via multi-harmonic sine/cosine components, then uses causal and multi-kernel convolutions plus inception-style mixing before stacked Mamba blocks. It outputs multi-step forecasts in one pass, reducing autoregressive drift, with optional variance heads for uncertainty and regime classification losses.

The MQL5 implementation focuses on computing temporal encodings in an OpenCL kernel directly from timestamps, avoiding lookup t...

πŸ‘‰ Read | CodeBase | @mql5dev
❀22πŸ‘8πŸ‘Œ1
Brain-Computer Interfaces are moving from lab demos to clinical trials, with systems such as Neuralink N1 and the Blackrock Utah Array already decoding motor-cortex activity into discrete commands.

A practical gap remains: no standard software bridge from neural command streams into trading terminals such as MetaTrader 5.

A reference prototype can be built today using simulated neural commands. A Python Flask service emits BUY/SELL/CLOSE/HOLD over JSON via HTTP, while an MQL5 Expert Advisor polls with WebRequest, parses commands, deduplicates execution, and routes actions through CTrade.

This simulation validates integration points, safety behavior (reset-to-HOLD), and transport latency without requiring BCI hardware or clinical access.

πŸ‘‰ Read | Docs | @mql5dev
❀28πŸ‘5πŸ‘Œ1
This article implements the core step of persistent homology in MQL5: standard column reduction of a Vietoris–Rips boundary matrix over Z/2, turning sparse column relationships into a readable persistence diagram of (birth, death, dimension) pairs.

The reduction tracks each column’s pivot, uses a pivot-to-owner table for O(1) lookups, and performs fast XOR β€œadditions” via symmetric difference of two sorted face lists. Empty reduced columns mark feature creation; unique pivots mark feature death. Unpaired creators become essential features with infinite death.

A compact data model (SPersistencePair, CTDADiagram) enables persistence, Betti numbers at any epsilon, and barcode/diagram views. A CTDA facade runs the full pipeline (Takens embedding β†’ distances β†’ filtration β†’ boundary β†’ reduction) from a price window in one call.

Correctness is cross-chec...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀19πŸ‘5πŸ‘Œ2