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
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
Risk Lot Calculator is a MetaTrader 5 chart utility that calculates lot size from a target risk and stop-loss distance. It renders an on-chart panel and does not place, modify, or close orders.

The panel displays symbol/timeframe, equity and balance, and whether equity or balance is used as the risk reference. Risk can be a percent of the reference or a fixed money amount. Stop-loss is entered in points and also shown as a price distance.

It reports tick size/value, point and contract size, min/max lot and step, and broker StopsLevel. It calculates loss per 1.00 lot at the stop, then computes a raw lot, rounds it down to lot step, and clamps to symbol limits.

Margin is computed via OrderCalcMargin for a buy at current ask, including free margin checks. Warnings appear when StopsLevel is violated, risk is below minimum lot, lot is capped, or margin is insuf...

πŸ‘‰ Read | Quotes | @mql5dev
❀16πŸ‘14🀩6πŸ”₯5
A session/killzone indicator draws time windows defined in GMT on charts running on broker server time. Each window is converted to server time before rendering, covering Asian range, London open, New York open, and London close for a configurable lookback (default five days).

Boxes render as outlines by default (fill disabled) and sit in front of candles; enabling fill places the box behind price. Each window can also draw dashed high/low lines, and the newest box per session may print a two-line label (font 8) only when there are enough bars. Range is shown in pips for standard FX quotes, otherwise in price with symbol digits and profit currency.

Offset handling supports auto-detection by comparing server and GMT clocks (rounded, clamped to Β±14). When auto-detect is unavailable or in Strategy Tester, a manual offset is used. Window edges are resolv...

πŸ‘‰ Read | AlgoBook | @mql5dev
❀23🀩17πŸ‘11πŸ”₯6
Random position sizing remains a common reason for account drawdowns. A compact MQL5 script addresses this by calculating lot size from two inputs: acceptable account risk (%) if stop loss is hit, and stop-loss distance in pips.

The script reads tick value, tick size, and volume constraints directly from the broker. Loss per 1.00 lot is computed as: stop_distance / tick_size * tick_value. The target risk amount (equity or balance * risk%) is divided by loss per lot, then rounded down to the symbol’s volume step so effective risk does not exceed the limit.

Inputs include risk %, account value basis (equity or balance), stop distance (pip definition varies by digits), and optional symbol override. Output is shown via alert and logged. If minimum lot exceeds the risk cap, it reports that condition instead of rounding up.

πŸ‘‰ Read | NeuroBook | @mql5dev
🀩18πŸ‘16πŸ”₯10❀8
Session Range Box is an MT5 chart indicator that plots Asian, London, and New York trading sessions as range boxes. Each enabled session is shown from open to close, with high/low lines, an optional mid line, and a label displaying the session name and range in the symbol’s native price units. An optional fourth box marks the London/New York overlap when the time windows intersect.

A corner panel summarizes the latest session day with high, low, and range for Asia, London, New York, and the overlap, plus the clock mode in use. When attached on weekends, the panel reports the last day with available bars.

Default hours are defined in GMT and can be switched to broker server time. Inputs cover session visibility, start/end times, colors, the number of past days to draw (5 by default, up to 20), and panel placement. DST adjustments are manual; historical b...

πŸ‘‰ Read | AlgoBook | @mql5dev
🀩20❀18πŸ‘17πŸ”₯17🀯4πŸ‘€1
CreyesHistoryCSV exports closed trade history from a trading account into a CSV file compatible with Excel, LibreOffice, and similar tools. It also outputs a compact performance summary to the Experts tab. The script is read-only and does not open, modify, or close any trades.

Usage requires placing CreyesHistoryCSV.mq5 in MQL5\Scripts, compiling if needed, then running it from the Navigator on any chart. After selecting inputs, the CSV is written to MQL5\Files (accessible via File -> Open Data Folder).

Key inputs include export range in days (1–3650), optional symbol and magic number filters, output filename, and a configurable column separator. Exported fields cover timestamps, deal/position identifiers, symbol, side, volume, price, P&L components, net result, magic, and comment.

Export includes only position-closing deals; deposits and withdrawals ...

πŸ‘‰ Read | Freelance | @mql5dev
πŸ”₯17πŸ‘15🀩15❀14
PivotPoints indicator plots the daily pivot point plus three resistance and three support levels derived from the previous day’s high, low, and close. It renders several prior days, with each set of levels valid only for its own session. Levels are fixed at the daily open and do not repaint.

Displayed lines include PP (pivot), R1–R3 (resistance), and S1–S3 (support). Supported calculation modes cover Classic (PP and range-based extensions), Fibonacci (0.382/0.618/1.000 of prior range), and Camarilla (close-based levels using 1.1 Γ— range scaled by 12, 6, and 4).

Configuration options include formula selection, number of days to plot, optional text labels, and separate colors for pivot, resistance, and support. Designed as an information tool across any symbol and timeframe via daily candle data, without trade signals or profit guarantees.

πŸ‘‰ Read | CodeBase | @mql5dev
❀15πŸ‘12🀩12πŸ”₯9
An EA built around Supertrend flips that trigger only after candle close beyond the band. On each new candle it rebuilds Supertrend from closed bars (default 300), using ATR(10) and multiplier 3.0, then opens a single trade on the last confirmed trend change: buy on flip up, sell on flip down. One position per symbol and magic; new flips do not stack entries.

Position sizing supports fixed lot or risk percent of balance/equity (default 1%). Stop loss can track the Supertrend line plus buffer (default 50 points) or use a fixed distance; broker stop level and spread are enforced. Take profit is a stop multiple (default 2.0). Breakeven moves SL to entry plus offset after 1R (default 20 points). Optional opposite-flip exit is enabled by default.

Sideways markets can cause repeated losses; if computed volume is below broker minimum, minimum volume is used and risk...

πŸ‘‰ Read | VPS | @mql5dev
❀22πŸ‘10πŸ”₯10🀩7
True Trading Cost is a free MT4 chart indicator (source included) for estimating the monetary outcome of a planned Forex/CFD trade before any order is placed. It shows spread, position size, round-trip costs, break-even price, and gross vs net risk/reward. BUY, SELL, and RESET manage only a hypothetical plan; nothing is sent to the broker.

Entry/Stop/Target are set as draggable chart lines, with RESET pulling defaults from current Bid/Ask and ATR(14). Commission is entered as round-turn per lot in account currency. BUY is modeled at Ask to Bid, SELL at Bid to Ask, so spread is not double-counted. Net results can include commission, extra fees, slippage, and optional swap.

An optional panel tracks swap estimates and six-hour spread stats from live ticks only, stored in memory and resetting daily. Lot sizing supports risk-percent (rounded down, no forced ...

πŸ‘‰ Read | Forum | @mql5dev
❀8πŸ‘6🀩6πŸ”₯3