MQL5 Algo Trading
574K subscribers
4.43K photos
7 videos
4.44K 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
A multi-symbol EA often keeps per-symbol globals and grows through duplication: separate bar times, magic numbers, failure flags, position checks, and event wiring. Adding instruments increases coupling between symbol state and MT5 event logic, which makes lifecycle paths fragile and hard to extend.

A scalable structure is an owning portfolio manager plus independent strategy nodes. Each CStrategyNode encapsulates one symbol-timeframe identity, including completed-bar gating, trading state, diagnostics, and permissions. CPortfolioManager routes OnTimer and trade-transaction events without touching node internals.

CArrayObj with FreeMode(true) provides an explicit ownership contract. Allocate an unowned node, Initialize() it, then Add() becomes the commit point where the collection assumes deletion responsibility. Failures before Add() must delete locally; Delete...

πŸ‘‰ Read | Forum | @mql5dev
❀10πŸ‘7πŸ”₯4🀩3πŸ‘Œ2
QCL Smoothed Heikin Ashi for MT4 renders calculated candles directly in the main chart window, using a two-stage smoothing pipeline. The first pass smooths price inputs, then a second pass smooths the derived Heikin Ashi OHLC, allowing separate periods and methods for each stage.

The implementation supports SMA, EMA, SMMA, and LWMA via a custom MovingAverage routine, maintaining intermediate arrays for base, HA, and final smoothed values. Only four indicator buffers are registered for the output OHLC; all other arrays remain internal.

Candles are drawn with per-bar chart objects and color-coded for bullish, bearish, or neutral states. Output values are synthetic and should not be treated as executable prices; the active bar can repaint until close.

πŸ‘‰ Read | Calendar | @mql5dev
❀13πŸ”₯5πŸ‘4🀩2πŸ‘Œ2πŸ‘¨β€πŸ’»2
This scalper EA is designed for M1 execution and depends on consistently tight spreads and fast order routing. An ECN environment with low commissions and minimal slippage is typically required to keep transaction costs predictable.

Hosting should be handled on a VPS located close to the broker’s trading servers, targeting up to 1 ms latency. Stable connectivity, low jitter, and uninterrupted uptime are critical, as brief delays can materially affect fills, stop execution, and overall results.

πŸ‘‰ Read | Signals | @mql5dev
❀11πŸ”₯4🀩2πŸ‘Œ2πŸ‘1
This article builds an MQL5 library for agent-based markets that lets strategies be tested on price series with known ground truth, avoiding the ambiguity of optimizing on real EURUSD history where β€œedge” can be pure search luck.

At its core is the Minority Game: agents pick buy/sell from fixed strategy tables and only learn which table to trust. Market quality is measured with volatility per agent (vs coin-flip baseline) and state-conditional predictability, then validated against the model’s published phase transition.

To make the synthetic series resemble real assets, the library adds a β€œsit out” option (grand canonical variant), producing variable participation, fat tails, and volatility clustering. A dedicated stylized-facts analyzer outputs assertable statistics (kurtosis, Ljung-Box, Hill tail index, variance ratio), enabling reproducible che...

πŸ‘‰ Read | Docs | @mql5dev
❀8πŸ‘5πŸ”₯5🀩2πŸ‘Œ2
StopDistance is an indicator that measures per-bar volatility as (High βˆ’ Low) in symbol points and visualizes it in a separate window. It adds an SMA or EMA of the range and a computed stop distance equal to average range multiplied by a configurable factor.

The goal is operational: quantify how far a symbol typically moves within one bar on the current timeframe, using the same unit used by stop-loss fields and many EAs. Unlike ATR, gaps between bars are excluded, so the metric reflects in-bar movement only.

Display logic is straightforward: blue histogram for each bar’s range, red line for the average over Period bars, and a green dashed line for Average Γ— StopFactor. Stops set below the average often sit inside normal bar noise.

For automation, three buffers are exposed for iCustom/CopyBuffer: range (0), average (1), suggested stop (2), all in ...

πŸ‘‰ Read | VPS | @mql5dev
❀13πŸ”₯5πŸ‘3🀩2πŸ‘Œ2
MQL5 can’t catch many critical VM faults (zero-divide, out-of-range, null access), so robust EAs need prevention, not recovery after the fact. This framework adds an exception-like discipline using precondition guards, typed error objects, cooperative TRY/CATCH macros, and consistent propagation.

Core pieces: CException as a structured error container (type, code, severity, context, timestamp), CResult<T> for explicit success/failure returns, CExceptionStack for manual call traces, and CLogger for durable terminal+file diagnostics.

Safety is enforced via GUARD_* (return Fail early) and CHECK_* (signal a THROW inside TRY). number<T> and array<T> wrappers validate division and indexing before execution. Practical benefit: predictable control flow and debuggable failures in complex trading systemsβ€”if wrappers/guards are used consistently.

πŸ‘‰ Read | Signals | @mql5dev
❀19πŸ‘7🀩5πŸ‘Œ3πŸ”₯2
ExportBars is a utility script for exporting bar history for any symbol and timeframe into a CSV ready for external analysis. The output is designed to load with a plain pandas.read_csv() call, without specifying encoding, separators, or date formats.

Default MQL5 file output creates friction: UTF-16 requires explicit encoding in pandas, timestamps come out as β€œYYYY.MM.DD HH:MM” and need a custom parser, and price formatting may vary by row if symbol digits are not enforced. ExportBars fixes these issues at the source.

The CSV is single-byte text, with one header row: time, open, high, low, close, tick_volume, spread, real_volume. Time is ISO 8601 β€œYYYY-MM-DD HH:MM:SS” in server time. Prices are formatted using SYMBOL_DIGITS and never in scientific notation. Rows are oldest-first, matching chart order.

Inputs include symbol, timeframe, last-N vs date-...

πŸ‘‰ Read | CodeBase | @mql5dev
❀13🀩5πŸ‘4πŸ‘Œ3πŸ”₯2
A practical way to expand EURUSD D1 direction models beyond classic TA features is to derive deterministic nonlinear features by mapping OHLC onto an elliptic curve (secp256k1). Each price is hashed (SHA-256) and converted to a valid curve point via try-and-increment; the number of attempts (nonce) becomes a feature, alongside x-bit statistics and curve point arithmetic such as Open+Close and High+Low.

The study builds 96 features (EC, TA, and cross-features) over multiple lookbacks and trains CatBoost with a strict time split, evaluated by AUC. On 2,000 daily candles, EC+TA improves test AUC to 0.6508 vs 0.5992 for TA alone, with x_slope and oc_x ranking among the most useful additions.

The key constraint is regime dependence: cross-validation averages do not consistently beat the baseline. The actionable takeaway is gating EC features with a tre...

πŸ‘‰ Read | NeuroBook | @mql5dev
🀩11❀9πŸ‘5πŸ‘Œ3πŸ”₯2
Most horizontal lines at prior highs are subjective. A higher-confidence level is a price band repeatedly validated by clustered pivots and repeated retests. This indicator aggregates recent swing highs/lows, groups nearby pivots into adaptive-width channels, assigns a score, and renders the strongest as background bands across the chart.

Pivots default to 10 bars left/right, taken from wicks or bodies, and remain eligible for 290 bars. Channel width is capped at 5% of the last 300 bars’ range, scaling with volatility. Scoring adds 20 points per pivot plus 1 point per bar whose high/low falls inside the band. Selection keeps the best, discards overlapping candidates, and repeats up to 10 channels, drawing the top 6 by default.

Channels update only on confirmed pivots; live ticks do not rewrite history. Bands switch role in real time based on current ...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ‘12❀10🀩7πŸ”₯2πŸ‘Œ2😁1
A set of EA input defaults defines an EMA-based signal on M15 using closed bars. Fast and slow EMA periods are set to 10 and 30, with the signal timeframe fixed to M15.

Trading is restricted to a WIB session window from 19 to 22. Position sizing uses a fixed 0.01 lot.

Risk parameters specify 70 points stop loss and 200 points take profit. The system limits exposure to 1 maximum open position.

Execution and filtering settings include a spread cap of 100 points, with 0 disabling the filter. Order tracking uses magic number 20260909, and maximum slippage is set to 10.

πŸ‘‰ Read | CodeBase | @mql5dev
❀16πŸ‘14πŸ”₯4πŸ‘4🀩1
QCL Heikin Flow for MT5 implements a two-stage smoothing pipeline for Heikin Ashi output. Stage one applies a selectable MA (EMA/SMA/SMMA/LWMA) to the underlying OHLC series. Stage two rebuilds Heikin Ashi values and smooths them again using an independent period and method, reducing short-term oscillation in candle bodies and wicks.

The indicator separates rendering into three DRAW_CANDLES plots: bullish, bearish, and neutral, each with its own buffer set. Calculation buffers are kept distinct from display buffers, and arrays are indexed chronologically (0 as oldest) to simplify iterative MA state.

Parameter validation caps periods to 1..10000. The MovingAverage routine handles EMA and other methods with partial-window seeding to avoid undefined startup values.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀12🀩12πŸ”₯6πŸ‘4⚑1πŸ‘Œ1
A standalone market-structure indicator for SMC-style analysis, built on a pullback swing detector and extended with structure state, validated extremes, and event tracking.

Two layers are processed per closed bar: a non-repainting pullback zig-zag that outputs alternating confirmed swings, then a structure engine that maintains exactly one active high, one active low, and a trend state (None/Up/Down). Structure is seeded from the first pullback high/low; after that, pullbacks only provide references.

Events are derived from one rule: closes break levels (BoS or CHoCH depending on trend), while wicks create pending sweep candidates. A sweep (x) is only confirmed when the next break occurs on the opposite side, and can relocate the prior structure point. Extremes are confirmed via IDM: after a break, the latest qualifying pullback becomes the referenc...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘22❀17πŸ”₯9🀩7✍2πŸ‘Œ1
Most momentum indicators rely on fixed lookbacks and constant smoothing, so the output reacts the same way in quiet ranges and during news-driven spikes. Volatility-Adjusted Momentum Decay Line (VAMD) addresses this by normalizing raw momentum (close change over InpMomentumPeriod) by ATR, expressing momentum in volatility units.

The normalized value is then passed through a recursive decay filter. The decay rate is adaptive: it scales with current ATR divided by ATR’s moving average over InpATRAvgPeriod. Higher-than-baseline volatility increases decay speed and forces faster convergence to new momentum; compressed volatility slows decay and preserves prior direction longer.

Interpretation is centered on a zero line. Persistent readings on one side suggest momentum with follow-through even when volatility expands. Rapid spikes away from zero followed ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀19πŸ‘10πŸ”₯9🀩7πŸ‘Œ1
DoEasy’s indicator layer is extended to cover the remaining complex MT5 standards: Ichimoku Kinko Hyo and Bill Williams’ Gator Oscillator, both usable as multi-symbol, multi-period objects.

Ichimoku support handles five plotted lines and adds two auxiliary histogram buffers to shade the area between Senkou Span A/B while preserving each line’s style and color. These β€œdesign buffers” are excluded from the Data Window, keeping output clean.

To manage compound indicators, buffer objects gain an β€œadditional line number” plus a new enum for unambiguous line identification, avoiding conflicts from shared enum values while keeping unified handlers. Data preparation/clearing and buffer lookup were updated to handle extra buffers and Gator’s nonstandard buffer indexing.

Tests confirm H4-calculated indicators render correctly on an H1 chart and match terminal...

πŸ‘‰ Read | Docs | @mql5dev
❀14πŸ‘13πŸ”₯9🀩8πŸ‘Œ2
Risk Calculator Panel is a position size calculator indicator for MetaTrader 5. Position sizing is done by dragging a Stop Loss line on the chart, with the panel updating lot size in real time for the selected risk. As an indicator, it does not open, close, or modify trades.

After attaching it to a chart, dashed SL and TP lines appear near the current price. Moving SL below price calculates a BUY from Ask; moving it above price calculates a SELL from Bid. Moving TP updates reward and the reward:risk ratio. Risk percentage can be edited directly in the panel without reopening inputs.

The panel shows entry direction and price, SL distance in points with minimum stop checks, target risk and rounded-down lot size by volume step, real risk after rounding, reward and R:R, plus margin when available. Calculations use tick size and tick value converted to ac...

πŸ‘‰ Read | Calendar | @mql5dev
πŸ‘19❀11πŸ”₯6🀩6πŸ‘¨β€πŸ’»3πŸ’―2πŸ‘Œ1
A fractal-dimension regime filter can separate trend and range by measuring path efficiency instead of directional strength. The value stays between 1.0 and 2.0: readings near 1.0 indicate clean directional movement, while readings toward 2.0 indicate repeated backtracking with limited net displacement.

The calculation follows a simplified Katz method over InpFractalPeriod bars: sum the absolute bar-to-bar changes (total path length) and compare it to the maximum displacement from the window’s first price, then apply a logarithmic ratio to derive the dimension. An EMA with InpSmoothPeriod reduces noise.

Zone logic uses two thresholds: at or below InpTrendThreshold (default 1.40) is trending, at or above InpChopThreshold (default 1.65) is choppy, with a neutral band between. Typical use is gating entries from a directional tool only when the line is i...

πŸ‘‰ Read | VPS | @mql5dev
❀15πŸ‘15πŸ”₯8🀩7πŸ‘Œ3
BotGuard is a lightweight monitoring Expert Advisor for VPS setups running trading robots. It does not open, close, or modify orders. Its role is terminal health reporting so outages are detected quickly.

Every 30 seconds it rewrites botguard_<login>.json in Terminal\Common\Files with UTC server time, login, server/company, connection and AutoTrading state, ping, balance/equity, margin level, open positions/orders, start-of-day equity, daily P/L %, and terminal build. It writes via temp file swap to avoid partial reads.

Every 5 minutes it appends botguard_<login>_log.csv (time, balance, equity, positions, connected) for equity curves and uptime checks. Push alerts and journal messages trigger on AutoTrading toggles, reconnection, and equity drawdown below a configured threshold.

External watchdogs can monitor file age and restart the terminal if updates stop. C...

πŸ‘‰ Read | Signals | @mql5dev
❀10🀩10πŸ‘9πŸ”₯6πŸ‘Œ2
Prop Firm Equity Guard monitors account equity continuously and enforces common prop firm risk rules. When a threshold is breached it closes all open positions, deletes pending orders, and blocks further trading until the lock condition expires. It does not open trades on a live chart and can run alongside manual execution or other EAs.

Supported limits include daily loss (based on balance, equity, or the higher of both at day start), maximum loss (based on initial balance), and an optional profit target that liquidates exposure once reached. Early warnings can trigger messages and MT5 push notifications at a configurable usage level.

A chart panel shows lock state, equity, daily and maximum loss usage, profit target, and the captured day-start value. State persistence relies on terminal global variables to survive restarts. Controls include reset hour in s...

πŸ‘‰ Read | VPS | @mql5dev
❀25πŸ‘16πŸ”₯9🀩8πŸ’―2πŸ‘Œ1
Session High Low plots the Asia, London, and New York trading sessions as colored boxes from session open to close, covering each session’s high and low. After the close, optional dotted extensions project the high/low levels for a configurable number of hours to track breakouts and retests.

Ranges are derived from M5 data, keeping session highs/lows consistent across M1 through H1. The active session box updates in real time as new extremes print. Tooltips provide high, low, and range in points, with labels for session name and prices; the New York label is positioned to avoid overlap with London.

Configuration includes per-session enable switches, start/end times, and colors, plus days to draw, maximum timeframe visibility, label toggle, and extension duration. Sessions crossing midnight are handled automatically, and weekends/holidays are skipped....

πŸ‘‰ Read | Forum | @mql5dev
❀22πŸ”₯11πŸ‘10🀩9πŸ‘Œ3
DailyPnLPct.mq5 adds an on-chart overlay that tracks today’s floating P&L as a percentage of a baseline balance and expresses daily-loss consumption in terms aligned with common prop firm rules.

The reset point is configurable via InpResetHour (server time). At each update, the script derives a reset timestamp, stores base_balance from ACCOUNT_BALANCE, then compares live ACCOUNT_EQUITY against that baseline to compute pnl_pct and β€œdaily loss used”.

A single OBJ_LABEL is maintained and refreshed on OnCalculate plus a 30-second timer. Status is color-coded based on consumption thresholds: under 50% of the limit, under 80%, or above. The text line reports Day P&L, loss used versus InpLimitPct, and remaining room before breach.

πŸ‘‰ Read | Quotes | @mql5dev
πŸ‘17πŸ”₯11❀9🀩5πŸ‘Œ3
ApexVelocity EA v1.0 targets volatility breakouts on XAUUSD with a fully dynamic parameter model rather than fixed point-based tuning. Execution logic is positioned as non-grid and non-martingale, built around price action, ATR-based volatility measures, and capital protection controls.

Broker-agnostic handling is implemented via ATR multipliers for buffers, break-even padding, trailing stops, and slippage tolerance, maintaining consistent behavior across 2/3-digit pricing. Risk sizing uses a TickSize/TickValue ratio approach to keep percentage risk aligned to account currency exposure.

Order management validates exits against SYMBOL_TRADE_STOPS_LEVEL to avoid invalid stop modifications during fast moves. Signal gating includes tick-volume acceleration, minimum ATR range, body-to-range quality filters, H1 MA-50 alignment, and session time windows. A peak-equi...

πŸ‘‰ Read | Docs | @mql5dev
πŸ‘17❀16πŸ”₯10🀩6