MQL5 Algo Trading
588K subscribers
5.04K photos
7 videos
5.05K 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
Pacific Clock is an MT5 indicator that prints the current US Pacific time on a single line above the chart time scale, updated once per second with a PST/PDT suffix. It targets setups where trading decisions are made in Pacific time while the broker server runs another zone, with an optional broker-time field on the same line for quick comparison.

Hovering any candle shows the corresponding Pacific day/time. DST is handled automatically using the US rule (second Sunday in March to first Sunday in November), verified against official records for 2020–2030.

No signals are generated and no chart objects are drawn beyond two text labels. Accuracy depends on the local PC clock. Historical candle conversion is derived from the current broker-to-UTC offset, so past candles can be off by one hour if the broker shifted server time since then. Configuration include...

πŸ‘‰ Read | CodeBase | @mql5dev
πŸ‘8❀4😁1
OrderGuard is an MQL5 include file for custom Expert Advisors in MetaTrader 5, focused on safer order sending rather than signal generation. It ships with a small sample EA that places market buy/sell orders only, using an MA cross solely to produce test signals.

Core controls include persistent de-duplication of signals across restarts/reconnects, broker-side counting of open positions, blocking orders during disconnects with single-shot logging, and automatic adjustment of stops/targets to the symbol’s minimum distance with correct rounding. Per-order validation also fits lot size to symbol constraints without rounding up, checks free margin, market state, and trading permissions, selects an allowed filling mode, and applies backoff on broker rejections up to 15 minutes with single-shot logging per skipped signal.

Integration: place OrderGuard.mqh under MQL5\I...

πŸ‘‰ Read | Calendar | @mql5dev
❀11😁1
KeyLevelsSweeps.mq5 automates common reference levels used in intraday FX workflows and keeps them consistent across timeframes by building from M15 data. It plots PDH/PDL, PWH/PWL, PMH/PML, day/week/month opens, New York midnight open, and an Asian range window with configurable hours. Lines are drawn across their respective periods for a configurable lookback, with right-edge labels and collision-aware label merging.

Day boundary is selectable: broker midnight, New York 00:00, or 17:00 New York. For New York modes, broker time alignment and DST handling are derived from historical Friday closes, with an optional manual override.

Sweep and break logic is evaluated only on closed bars. Sweeps mark a bar that trades through a level and closes back inside; breaks require a close beyond. Only the first event per level per period triggers optional pop-up...

πŸ‘‰ Read | Forum | @mql5dev
❀16🀩3πŸ‘2πŸ†1
A divergence is flagged when price prints a new extreme and the oscillator fails to confirm it. Many indicators look correct on history but fail live due to swing hindsight and repainting. This implementation keeps historical display identical to what was available at the time.

It supports RSI (default), MACD histogram/line, Stochastic %K, CCI, or Momentum. Regular divergences are drawn with solid lines, hidden with dotted lines, plus an arrow on the confirmation bar in the oscillator and optionally on price.

Swings are confirmed only after N closed bars (default 3). Signals are emitted on the bar where the second swing becomes confirmed, never backfilled. Closed bars only; once plotted, signals are never moved or deleted.

Filters reduce false positives: swing alignment within a bar limit, no crossing of the swing-to-swing baseline, configurable swi...

πŸ‘‰ Read | Signals | @mql5dev
❀15🀩4πŸ‘3πŸ”₯2
Currency Strength Free MT4 is a standalone MQL4 indicator that displays relative strength for EUR, USD, GBP, JPY, CHF, AUD, CAD, and NZD, plus a ranking of up to 28 supported forex crosses. It targets discretionary analysis and education and does not perform automated order placement.

The dashboard shows eight color-coded strength bars sorted by current momentum, a pair list ranked by base/quote strength gap, and configurable context via timeframe and closed-bar lookback (defaults: H1, 12 bars). It includes symbol discovery for broker prefixes/suffixes and a Market Data Quality panel covering synchronized pair availability, data gaps, partial history, and stale quotes.

Calculations use completed candles only: recent log changes are scaled by observed return variability, contributions are assigned to base and quote currencies, then normalized to a 0–100 ...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘9❀7🀩4
StrictJson is a single include for MQL5 that reads and writes RFC 8259 compliant JSON with no external dependencies. Typical use cases include persisting EA settings/state between starts, parsing WebRequest responses, and generating outbound JSON.

Values can be accessed by key, array index, or path notation such as panel.theme and days.0. Output supports compact one-line JSON or indented formatting.

Parsing is strict: invalid JSON is rejected with line/column diagnostics and no partial reads. Conformance is validated against JSONTestSuite, accepting required inputs and rejecting prohibited ones. On failure, destination values remain unchanged, and APIs return JSON_OK or JSON_ERROR_* without printing.

Numeric handling preserves representation and range, including long up to 9223372036854775807. null, empty string, empty array, and empty object remain distinct, ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀18🀩10πŸ‘6πŸ”₯3
Break-Even Stop Mover is a lightweight Expert Advisor focused on protecting existing positions. When profit reaches InpTrigger points, stop loss is moved to entry price plus InpLock points. This prevents a winning trade from turning into a loss aside from gaps and slippage. The tool manages already open trades from manual execution, mobile terminals, or other EAs, and never opens or closes positions.

Positions for the chart symbol are checked on every tick and via a 1-second timer. Profit is calculated in points from the open price using the executable close price (Bid for buys, Ask for sells). Stop loss is only improved, never worsened, and positions already at or beyond break-even are left unchanged.

Broker constraints are respected, including stop level and freeze level. Take profit is not modified. Rejected modifications trigger a pause for InpRetrySec...

πŸ‘‰ Read | AppStore | @mql5dev
πŸ”₯7❀6πŸ‘4🀩4
Currency Strength Free is a standalone MQL5 indicator for MT5 that compares the eight major currencies (EUR, USD, GBP, JPY, CHF, AUD, CAD, NZD). It aggregates up to 28 FX crosses into an on-chart strength panel plus a ranked pair list, intended for relative momentum context and chart selection rather than entry/exit guidance.

For each pair, completed candles from a chosen timeframe are used to compute a log change over a lookback window, scaled by intervening closed-bar return variation. Contributions are applied with opposite signs to base and quote, averaged per currency across available coverage, normalized to a 0–100 scale around 50, then ranked. Pair gaps reflect score differences and can shift as history loads or bars update.

Operational details include symbol prefix/suffix detection, readiness and data-gap notices, navigation for the pair list, a...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘14❀13πŸ”₯6🀩6
Daily Loss Limit Guard is an Expert Advisor focused on enforcing a daily drawdown cap without placing trades. It monitors full-account exposure across all symbols, including manual orders and trades from other EAs.

At the configured reset hour (server time) it stores the day-start balance. Daily loss is calculated as day-start balance minus current equity, so floating P/L is included. When loss reaches the limit minus a configurable buffer (default 10% of the limit), it closes all open positions and removes all pending orders.

After triggering, the account is kept flat for the remainder of the day. Any new position, regardless of source, is closed immediately until the next reset. State is persisted via terminal global variables, so restarting the terminal does not clear the lock.

Key inputs: limit by percent or fixed currency amount, reset hour, buffer pe...

πŸ‘‰ Read | NeuroBook | @mql5dev
πŸ‘10❀7🀩3πŸ”₯2
CustomStopOut is a trading terminal script that applies user-defined margin call and stop-out thresholds in addition to broker settings. After being attached to a chart, it checks account margin level every 500 ms until removed.

If margin level drops below the configured margin call level, a single alert is generated per downward event, with a new alert only after recovery and another drop. If margin level falls below the stop-out level, the script closes positions incrementally, starting with the worst net result (profit + swap + commission), then re-reads margin level after each close and stops as soon as the threshold is restored.

Operation can be limited by symbol scope (all symbols or chart symbol) and by magic number. It supports hedging and netting accounts. Close failures are reported once per error and retried on subsequent checks. Alerts can b...

πŸ‘‰ Read | Forum | @mql5dev
πŸ‘17❀13🀩6
Inside-Bar Outcome Tracker quantifies inside-bar breakouts using only historical counts on the current symbol, timeframe, and broker feed. It defines a mother bar, consecutive inside bars (edge touches treated as inside within 0.5 point), then a breakout bar that exits the mother range. Breakouts are classified as up, down, or both-sides.

Outcomes are decided via a configurable hold window (N closes starting at the breakout close). If any close returns inside the mother range, the breakout is marked failed; otherwise it held. Pending cases are excluded from failure rate. Mother bars can be filtered by minimum ATR size, and results are bucketed by inside-bar count (1, 2, 3+) and by mother size (small/medium/large ATR ranges).

Display includes a histogram at each breakout, optional boxes on the chart, and a stats panel with direction shares, failure ra...

πŸ‘‰ Read | Signals | @mql5dev
πŸ”₯7❀5πŸ‘3🀩3
Candle streak behavior can be measured instead of argued. The method is to detect every completed run of N same-color bars, then classify what the next closed bar did: continuation, reversal, or doji. Doji is defined by an open-close body up to a configurable point threshold and always terminates a run.

For each run length, the key metric is cont%: the probability that a run of length N becomes N+1. This is compared to a baseline derived from the unconditional share of up/down bars in the loaded history. A z-score flags run lengths where cont% deviates materially, subject to a minimum case count.

The table also tracks the average next-bar move in run direction, normalized by prior-bar ATR. Updates are incremental with no look-ahead, and results are specific to symbol, timeframe, and broker feed. Low-frequency long runs require substantial history; sp...

πŸ‘‰ Read | AppStore | @mql5dev
❀24πŸ‘7πŸ”₯6🀩6
MT5 terminal history is deal-based rather than trade-based. Trade History Exporter reconstructs each closed position from its underlying deals and writes one CSV row per closed trade for spreadsheet analysis, including partial closes consolidated into a single row.

Exported fields include position, symbol, side, volume, open/close time and price, points, P/L, commission, swap, fee, net, duration, initial SL, gross R multiple, MAE/MFE points, magic number, and comment. Open/close prices are volume-weighted; commission/swap/fees are aggregated across all deals to produce a true net result.

R multiple is calculated from points vs initial SL distance and remains empty when no SL existed at entry. MAE/MFE are approximated from M1 Bid bars between entry and exit, blanked when data is missing. Output uses server time, UTF-8 BOM, optional decimal comma, separator se...

πŸ‘‰ Read | Forum | @mql5dev
❀9πŸ‘4πŸ”₯4🀩3
EDCFlow reframes market modeling around transitions, not just states. It keeps correlation as a stabilizing β€œmemory” of what remains consistent, then adds dense difference maps to capture how movement changes between adjacent segments: direction, intensity, and local heterogeneity.

The implementation focus is the Multi-Scale Difference Layer, built to extract changes at multiple horizons without averaging them away and without leaking future data. This matches real markets where noise at one scale can be signal at another.

Instead of expensive self-attention, EDCFlow uses scale-level attention: a lightweight excitation block that normalizes per-scale weights (SoftMax) and applies them via element-wise scaling. The result is a causal, compute-efficient pipeline that adapts to regime shifts traders care about.

πŸ‘‰ Read | Calendar | @mql5dev
❀10πŸ‘9🀩8πŸ”₯5
Close By Filter provides selective position management with safety checks, avoiding blanket closes. Selection is based on side (buy/sell/both), symbol scope (current chart or all), magic number (any, manual-only, or a specific value), and floating result filter (any, profit-only, loss-only using profit plus swap).

Matching positions and orders are listed before any action. A confirmation dialog shows counts and current floating result, then filters are revalidated before each close to account for price changes. Pending orders can be deleted first to prevent fills during execution.

Execution uses position IDs to avoid ticket-related mismatches, prevents duplicate closes on netting accounts, and applies the symbol’s filling mode. Retries handle requotes, price moves, timeouts, and connection faults, while non-recoverable errors stop immediately. Full reporting ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀9πŸ‘6πŸ”₯4🀩3
Cassandra trade logging from MQL5 can run without a REST/gRPC gateway by speaking CQL v4 directly over SocketConnect/SocketSend/SocketRead. This removes a sidecar service but requires manual byte-level framing inside the terminal.

Implementation includes a reusable CCassandraClient (CassandraCore.mqh), a Donchian/ATR EA that batches closed deals into Cassandra, and a separate dashboard script that reads back and reconciles row counts against terminal deal history using an independent connection.

Two failures were isolated with reproducible data: prepared-statement ids use [short bytes] (2-byte length), not [bytes] (4-byte length), corrupting EXECUTE/BATCH if encoded incorrectly; and a lot-sizing rule that rounded up to minimum volume, producing catastrophic risk on large tick-value symbols.

Validation combines an 8-case wire self-test and a live smoke tes...

πŸ‘‰ Read | Signals | @mql5dev
❀11πŸ‘10πŸ”₯8🀩5
Gold MACD Divergence Map is a chart study that marks regular and hidden MACD divergences only on closed bars. The current forming bar is excluded. It does not trade, does not generate entries, and does not place orders.

Swing points are confirmed after a fixed delay (5 bars by default) and remain locked once validated. Divergence scoring is based on the MACD line with defaults 12/26/9, not the histogram.

A corner panel reports how many completed events are eligible for scoring, how often price reached 1Γ—ATR in the reversal direction, and how often the reversal arrived before the first-touch. Events are evaluated only after the full forward window closes (default 24 bars on H1, configurable).

Defaults use a light palette (#EEF2FA background, #183AC7 accent). Panel language supports English and Russian. On a 2020–2026 XAUUSD sample, the 1Γ—ATR first-touch ...

πŸ‘‰ Read | Freelance | @mql5dev
❀6πŸ”₯5🀩4πŸ‘2
ExternalIndicatorBacktest.mq5 provides signal backtesting for MT5 indicators without modifying the indicator source or writing a dedicated EA per tool. Signals are read either from indicator buffers or from time-anchored chart objects, then evaluated through a single OHLC reconstruction engine.

The package includes the EA plus demo indicators for both paths: DemoSignals (buffers) and ObjectSignals / RSIDivergenceObjects (objects). No orders are sent; results are rendered as exit segments and statistics in-chart or in the visual Strategy Tester.

Core configuration focuses on consistent entry timing and position management: InpSignalShift and InpHistoryBars define the eligible closed-bar window, with optional date boundaries. The engine supports one active virtual position, conflict handling when buy and sell coincide, and optional reversal on opposite signal...

πŸ‘‰ Read | AppStore | @mql5dev
❀9🀩8πŸ‘7πŸ”₯5
A position-management utility for MetaTrader 5 that operates only on already open trades, regardless of whether they were opened manually or by another EA. No trade entry or forced exit logic is included; only stop loss and take profit levels are modified.

Trailing activates when price reaches a configurable portion of the entry-to-TP distance (default 90%). The take profit can be kept, removed, or extended by a percentage of the original distance. The stop trails at a fixed point distance or as a percentage of the original TP distance, never moves backward, advances only if the minimum step is met, and respects broker stop-level constraints.

Scope and controls include symbol selection (current or all), magic-number filtering (-1 any, 0 manual only), and an optional on-chart status panel. Positions without a TP are skipped. State is persisted via terminal g...

πŸ‘‰ Read | Freelance | @mql5dev
❀7πŸ”₯4πŸ‘2🀩2
HalfTrend Channel for MT5 combines a state-driven HalfTrend baseline with ATR-based channel offsets.

Core logic tracks rolling highs/lows over a configurable amplitude, derives average high/low, and flips the internal trend state only when both confirmation conditions match (avg vs reference plus close vs prior high/low). The baseline steps and never behaves like an SMA.

Volatility uses True Range with Wilder smoothing to produce ATR(100). Channel distance is (ATR * multiplier) / 2, applied symmetrically around the baseline.

A separate direction flag changes only on close crossings beyond the upper/lower boundary and controls which band is rendered as the main line, with optional opposite band, shaded fill, and mode-switch dots.

πŸ‘‰ Read | AlgoBook | @mql5dev
❀10🀩5πŸ‘4πŸ”₯3πŸ†1
Trade code that modifies stops or closes positions is difficult to verify in the Strategy Tester or on demo accounts because server-side rejections arrive only when the server decides to send them. TradeGateway addresses this by putting trade-changing calls behind an interface, ITradeGateway, so rule logic can be executed against either a live adapter or a deterministic fake.

CLiveGateway forwards requests to the standard trading API and position functions, while CFakeGateway acts as an in-memory broker. Tests populate it with symbols, quotes, positions, and time; each request returns a server-like retcode, optionally forced via a queue. Every request is logged with Bid/Ask at arrival, enabling assertions on what was sent, when, and how often, without contacting a trade server.

An example consumer, CBreakEvenRule, moves stop loss to entry plus/minu...

πŸ‘‰ Read | Quotes | @mql5dev
❀7πŸ”₯6πŸ‘2🀩1