MQL5 Algo Trading
586K subscribers
4.89K photos
7 videos
4.89K 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
HistoryExportTester exports Strategy Tester price history to CSV: closed bars for any timeframe and optional tick-by-tick data.

Tester exports are useful because chart history is capped by the “Max bars in chart” setting. The tester is not, allowing multi-year M1 bars or full real-tick periods in a single run.

Usage: select the EA in Strategy Tester, pick symbol and date range. The test timeframe is irrelevant; the export timeframe is an input. For bars, any model works and “1 minute OHLC” is fastest. For ticks, use “Every tick based on real ticks”, otherwise ticks are generated. Output goes to Terminal\Common\Files, or the agent’s MQL5\Files if common folder is disabled.

Files: <symbol>_<timeframe>_bars.csv (time, OHLC, tick_volume, real_volume, spread), closed bars only. <symbol>_ticks.csv (time_msc, time, bid, ask, last, volume, flags).

A gap report lists g...

👉 Read | Quotes | @mql5dev
❤7🔥6🤩4👍1
Clipping was added as a first-class rendering constraint, targeting UI separation issues seen in dashboards: overflowing list rows, plot lines crossing axes, and text escaping button bounds. The mechanism limits drawing by a boundary owned by another widget, rather than modifying the shape.

The implementation reuses per-pixel coverage already produced by the rasterizer. Clip coverage and shape coverage are multiplied in the inner Fill loop, enabling anti-aliased rectangular and path clips, nesting via repeated multiplication, and predictable artifacts such as edge darkening from conflation in self-clips, thin geometry, and deep clip stacks.

Supporting pieces include SCairoRect for bounds, NaN-safe emptiness checks, half-open containment, rectangle intersection/union, exact path bounds from flattened vertices, and hit-testing using the same scanline crossing...

👉 Read | Freelance | @mql5dev
❤15🔥9👍7🤩4👨‍💻1
An educational example implements an opening-candle setup around the New York session open. The EA waits for the M5 bar aligned to 09:30 New York time (often 16:30 server time on NY-close brokers). A trade triggers when the candle body exceeds total wick size and tick volume is above 1.5x the 20-bar average, then a single position is opened in the candle direction.

Risk controls are straightforward: one trade per day, at most one open position, fixed SL/TP in price units (defaults 30/120, scaled by symbol price), and a time-based forced close. Position sizing can be risk-based via stop distance or fixed-lot, with margin-aware downscaling. No martingale, grid, averaging, or hedging logic is used.

Backtest notes: Strategy Tester results on USTEC M5 (every tick, 2025) show 91 trades, net +2,559 on 10,000 deposit with 100 risk per trade, PF 1.41, 29.7% win rate...

👉 Read | Docs | @mql5dev
👍9❤7🔥5🤩3🎉2
Multi-currency EAs are not a “trade more symbols” problem. Concurrent EURUSD and GBPUSD exposure concentrates USD risk, so portfolio allocation, correlation control, and unified limits become mandatory.

MetaTrader 5 build 6060 adds an AI Assistant in MetaEditor with MCP support. It can generate MQL5, compile, fix errors, and run Strategy Tester passes, turning EA prototyping into an iterative research loop with logged decisions.

A prototype portfolio EA was assembled: S1 breakout, S2 mean-reversion, and an experimental S6 pair module (disabled). Supporting scripts computed correlations, regime stats, and spread screening. Backtests produced mixed results, with the assistant rejecting weak configurations and fixing self-introduced defects.

Key outcome: a reproducible framework with risk layers and audit requirements, not a verified profitable system.

👉 Read | Docs | @mql5dev
👍13❤12🤩6🔥5🏆2
RoundNumbers plots horizontal price levels at round-number increments around the current visible range, such as 1.1000/1.1050 on EUR/USD, 2650.00 on gold, or 30500 on an index. These levels often align with clustered orders and can highlight areas where price action changes pace.

The indicator renders a dotted minor grid line at each step and a thicker solid line at every tenth step for major figures. Step size can be fixed or calculated automatically from the chart zoom, keeping the number of lines on screen under control. Levels update with scrolling and rescaling, and only the visible area is processed to limit resource use.

Configuration includes fixed step (0 for automatic), maximum on-screen lines for auto mode, and styling for minor/major lines. Installation: copy RoundNumbers.mq5 to MQL5\Indicators, compile, then attach to a chart. This is a ...

👉 Read | Freelance | @mql5dev
👍9❤4🔥2🤩1👀1
Part 3 adds an alert layer to the existing managed-trendline lifecycle, reusing state transitions instead of re-detecting market events. Touch, bounce, break, and resurrection alerts are emitted only when the state machine moves between specific states, keeping lifecycle logic as the single source of truth.

The design records transitions inside CManagedTrendline (previous state + pending-change flag), then CTrendlineManager translates supported transitions into alert events and forwards them to a dedicated CTrendlineAlert component.

CTrendlineAlert focuses on filtering and delivery: per-event toggles, separate switches for manual vs auto-generated lines, and independent popup/push channels. Messages are standardized with symbol, timeframe, source, direction from slope, price context at dispatch, and object name, enabling actionable notifications w...

👉 Read | NeuroBook | @mql5dev
❤13👍9🤩5🔥4
MA Toolkit provides a reference implementation of SMA, EMA, and LWMA with explicit calculations instead of relying on built-in averaging calls. SMA uses the arithmetic mean of the last N prices, EMA applies the smoothing factor 2/(N+1) and initializes from the first historical price, and LWMA weights the newest bar at N down to 1 for the oldest.

Two lines are plotted simultaneously: a configurable fast MA and a slow MA. The fast line is slope-colored with a flat-threshold option, while the slow line can be hidden without disabling crossover logic. Crossover arrows mark fast/slow intersections, and an optional alert triggers once per bar based on the last closed candle only.

Computation is optimized to update only new and forming bars. Inputs cover MA types, periods, applied price, arrow offset, panel text, and display toggles. Notes include EMA histo...

👉 Read | Freelance | @mql5dev
👍7❤5🤩5🔥3
CDropList implements a drop-down list for MQL5 charts as a composite control, wrapping multiple chart objects behind a single API. It coordinates creation, positioning, visibility, and deletion for the main block (border, background, label, chosen item, button) and the opened list (background, arrows, item cells).

Lifecycle is handled via Create() and Destroy(), with CreateDrop()/DestroyDrop() controlling the opened state. Object naming is isolated through a required unique prefix to avoid collisions across instances.

Item management keeps m_items_names and m_current_mode consistent through AddItem(), DeleteItem(), and SelectedItem(). Layout and appearance changes go through Refresh(), which updates only changed properties and closes any open list to avoid stale geometry.

ChartEvents() integrates with OnChartEvent(), returning explicit action codes fo...

👉 Read | Signals | @mql5dev
👍13🤩12❤7🔥5
Position Tool adds a Long/Short Position drawing to MetaTrader 5 with visual trade planning and automatic position sizing. It renders entry, stop, and target zones and recalculates risk metrics on every mouse drag, including lot size, cash risk, projected reward, reward-to-risk, point distance, and margin impact.

P/L per lot is derived from OrderCalcProfit(), keeping calculations consistent across Forex, metals, indices, and crypto CFDs, regardless of account currency. Volume is rounded down to the symbol’s step to prevent configured risk from being exceeded, with a MIN LOT > RISK warning when applicable.

On attach, it initializes at current price with a 1x ATR(14) stop and a 2:1 target. Entry moves the whole structure; entry endpoints adjust width. Dragging target across entry flips Long/Short automatically. Controls include mirror (Long/Short) and ...

👉 Read | CodeBase | @mql5dev
❤6🔥6👍5🤩4🤓2
Stop-out risk is the one exit an EA cannot control when stop loss is missing or distant. The margin level is visible, but the price distance to stop-out and the effect of a new order are not. Grid and averaging systems need that threshold, and common linear estimates break on FX conversion and on margin behavior.

CStopOutGuard models positions for one symbol and computes the first tick-grid bid where the account model reaches the stop-out level. It uses OrderCalcProfit() and OrderCalcMargin(), scans within ±50% of current bid, then refines with bisection. Results include SOG_OUT_OF_RANGE and SOG_ALREADY_BELOW.

Tester runs on MetaQuotes-Demo showed key details: USDJPY profit conversion depends on the valuation price, margin tiers increase per-lot cost with total side volume, and Strategy Tester kept margin fixed at fill-time for open positions. A recorder...

👉 Read | Forum | @mql5dev
❤14👍7🤩6🔥5
Previous Day High, Low, and Close levels remain common intraday reference points. The prior day’s High and Low define the range extremes, while the Close indicates where the session settled. Price frequently reacts around these areas, making them practical for breakout, reversal, and target planning.

The indicator reads daily bars and draws PDH/PDL/PDC using chart objects rather than buffers. Levels are rebuilt only on the arrival of a new daily bar, which keeps runtime overhead low. Current-day levels can be extended right; historical levels are rendered as day-length segments when InpDaysBack is greater than 1. Labels print the level name and price at the left edge.

Key inputs include toggles for High/Low/Close, DaysBack (1–100), right extension, per-level colors, styles (dash for High/Low, dot for Close), width, and label settings. Operation follows br...

👉 Read | NeuroBook | @mql5dev
❤6👍6🔥6🤩4⚡2
Native SFTP over SSH-2 is implemented directly in MQL5 sockets, removing the need for external tools like WinSCP scripts. The client targets SFTP v3 with X25519, Ed25519 host keys, AES-128-CTR, HMAC-SHA2-256, and no compression, and rejects servers that disable required algorithms.

Security is enforced with host key fingerprint pinning and signature verification during KEX. Strict key exchange is advertised to mitigate Terrapin, but not required. Packet handling validates lengths before MAC checks and performs constant-time MAC comparison.

A reporting EA writes daily CSVs locally, while a separate service uploads completed files via a temp “.part” flow, logs SHA-256 and timings, and applies exponential backoff. Strategy Tester edge cases (missing OnTradeTransaction close) are handled via end-of-test reconciliation keyed by opening deals.

👉 Read | VPS | @mql5dev
👍12🤩12❤9🔥5
This article adapts the Bi-directional Adaptive Temporal (BAT) architecture from event-based vision to financial markets, treating ticks and microstructure reactions as an asynchronous event stream rather than fixed “frames”. Raw events are packed into voxel-style temporal layers so a model can operate on a dense, structured tensor instead of noisy irregular updates.

Key building blocks include multiscale encoding to capture micro-moves and regime shifts, bidirectional temporal correlation to align past and future segments, and adaptive temporal sampling to change the step size as volatility accelerates or slows. Spatially adaptive aggregation filters inconsistent signals into a stable motion feature, then iterative refinement progressively sharpens the movement estimate.

On the implementation side, a top-level MQL5 object (CNeuronBAT) integrates ...

👉 Read | Docs | @mql5dev
👍18🤩9❤8🔥8
This article implements a dead man’s switch for MetaTrader 5 EAs that fail silently: the host EA periodically sends a compact “health beat” to an external relay, while a separate guardian EA polls the relay and runs an independent state machine.

Unlike a simple “I’m alive” ping, the beat includes actionable vitals: health flags, tick age, AutoTrading/trading readiness indicators, and position metrics for a magic number. The relay timestamps beats on its own monotonic clock, persists state across restarts, tracks sequence gaps, and treats boot-id changes as clean restarts.

The guardian distinguishes “relay unreachable” from “host dead,” confirms over multiple polls, latches DEAD until rearmed by a run of advancing sequences, and can alert or execute breakeven/flatten using live PositionsTotal()/POSITION_MAGIC. A disarm/arm endpoint supports planned maintenan...

👉 Read | AlgoBook | @mql5dev
👍25❤10🔥5🤩5
This article builds a session volume profile for MT5 directly from live ticks, focusing on making per-price aggregation fast and reliable under real broker feeds.

The core improvement replaces O(n×m) bin searches with O(1) direct indexing on the tick-size grid: compute a bin index from (price - range_min) / bin_size and increment an array. Benchmarks on ~250k–400k ticks show 17–30x lower aggregation time while producing identical bin results.

A five-class EA pipeline separates concerns: session window resolution, resilient tick loading (fallback from trade ticks to all ticks, retries for history timeouts/small-buffer errors), constant-time histogram building with preallocated bins, value-area expansion around the POC, and chart rendering.

It also handles missing trade volume by counting ticks, logs partial/uncertain loads, and tracks skipped zero-pr...

👉 Read | AlgoBook | @mql5dev
👍14❤6🤩5🔥3🤯1
Financial return histories are non-stationary, so segmentation by mean and variance is treated as an optimization problem, not an event detector. The approach models each segment as Gaussian with its own MLE mean/variance, adds a fixed penalty per change point (BIC-style 2·ln(n) by default), and solves the optimal partitioning via PELT.

PELT pruning stays exact only when the segment cost satisfies the required inequality. A variance floor for near-constant data can break this, so the implementation validates pruning with an m-window variance check and disables pruning when the floor can bind. Minimum segment length is enforced to avoid degenerate one-bar segments.

The MQL5 design uses four classes: data/returns and cumulative stats, segment cost + pruning eligibility, PELT with deferred pruning, and an orchestrator that validates inputs and reports...

👉 Read | Docs | @mql5dev
🤩10👍9❤7🔥4🎉2👨‍💻1
Smart Liquidity Hunter v1.11 is an MT4 indicator that flags OHLC-based sweep events around previously confirmed swing highs and lows. It does not read order book data, does not infer real stop placement, and does not place trades.

Signals require a closed candle to break an eligible swing and close back across it. The sweep distance must exceed the larger of MinSweepPoints and a volatility threshold computed as the simple mean of prior true ranges, scaled by MinSweepVolRatio. Wick rejection, close-location, freshness, and optional candle-color filters must pass. Only pre-confirmed swings qualify; dual-direction candles are skipped; no arrows are drawn on the forming bar.

Defaults include SwingStrength=3, MaxSwingAge=100, MaxBarsToScan=1000, VolatilityPeriod=14, MinWickPercent=25, MinCloseLocationPct=60, and configurable arrows, dashboard, and alerts....

👉 Read | Quotes | @mql5dev
👍9❤6🔥6🤩4👌2
Part 10 adds two missing pieces to make the 2D renderer usable: affine transforms and a drawing context with Save/Restore state.

Affine transforms are represented as six doubles (a,b,c,d,e,f). Points use full Apply; distances use ApplyDistance to avoid classic translation bugs. Composition order is defined as this = this * m, matching common drawing APIs.

The path now stores device-space vertices while keeping the pen in user space. SetTransform affects future vertices; Transform rewrites stored vertices and must only be used on finished contours. Flattening tolerance is adjusted by the current scale factor to keep on-screen error stable.

CCairoContext centralizes transform, clip, source, and fill rule in a state struct. Save/Restore copies state by value, keeps clip copies in a bounded stack, and treats paints as borrowed pointers to avoid owner...

👉 Read | AppStore | @mql5dev
🤩14🔥11❤9👍5👌3🤯2
Spread and Daily ATR Risk Meter HUD is a lightweight, zero-buffer on-chart indicator for MetaTrader 5 focused on execution conditions and risk reference sizing. It renders a compact HUD on the main chart without subwindows and does not alter trade state.

Displayed metrics include live spread in points and standard pips with a configurable warning threshold, Daily ATR(14) in points, and today’s range usage as a percentage of average daily range. It also reads broker constraints via SYMBOL_TRADE_STOPS_LEVEL and SYMBOL_TRADE_FREEZE_LEVEL.

A reference 1R lot size is estimated from the chart using OrderCalcProfit(), with automatic tick-value fallback and SYMBOL_VOLUME_STEP normalization. Inputs cover risk percent, ATR period, ATR-based stop multiple, spread warning level, and HUD placement offsets.

Installation: copy SpreadATR_RiskMeter.mq5 into MQL5/Indicato...

👉 Read | VPS | @mql5dev
❤13👍12🤩9🔥6
Round-Number / Psychological Level Magnet implements an adaptive grid of round-number levels based on the symbol’s current price magnitude, avoiding hardcoded spacing per instrument. Big-figure steps are auto-selected to match the “00”-style levels commonly referenced on that market, with an optional manual override.

Dashed lines mark big figures, while optional dotted lines mark half-figures. The grid stays centered around current price and recenters only after a configurable drift threshold to reduce redraws and CPU load on fast feeds.

An on-chart panel reports the nearest magnet and distance in points, with a color change when inside the approach threshold. Optional one-shot alerts trigger on approach and re-arm only after price moves beyond a separate pullback distance.

Configuration includes levels per side, half-level visibility, recenter sens...

👉 Read | CodeBase | @mql5dev
❤21👍14🔥9🤩6
AlgoFX Session Liquidity Sweeps tracks common intraday reference levels and flags a sweep when price trades through a level and the candle closes back on the other side. Supported levels include PDH/PDL, Asian session high/low (00:00–08:00 server), and London session high/low (08:00–12:00 server), built from chart OHLC and broker server dates.

Sessions use bar open time with [start,end) membership and handle midnight crossing. Levels activate only after a session closes; partial first-loaded sessions are ignored. Sweep signals use an ATR filter: sell sweep requires high > level + MinPenetrationATR*ATR and close < level; buy sweep is symmetric. A close beyond a level marks a break and consumes the level; each level emits one event and the forming candle is never evaluated.

For EAs, read buffer 2 (Buy) and 3 (Sell) at shift 1 via iCustom/CopyBuffer; va...

👉 Read | AppStore | @mql5dev
👍12🔥10❤9🤩7