MQL5 Algo Trading
548K subscribers
3.93K photos
6 videos
3.94K 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
Order reject 130 (β€œInvalid stops”) is often caused by server contract limits, not EA logic. Key constraints are stop level, freeze level, and volume rules (min/step/max lot). These values are per symbol, broker-specific, and can change without notice.

A lightweight script can print symbol specifications without placing, modifying, or closing trades, and without requiring algo trading to be enabled. It can read a comma-separated symbol list or use the current Market Watch set.

Output includes digits, point, tick size/value, contract size, lot limits, spread mode, execution mode, swaps, and margin required for one minimum lot vs free margin. The most actionable line computes the nearest stop level the server should accept, returned in price units to avoid pip/point mistakes on 5-digit symbols.

Stop validation should use the larger of stop level and freeze leve...

πŸ‘‰ Read | AppStore | @mql5dev
❀21πŸ‘4πŸ‘Œ3
DoEasy indicator handling in MQL5 received a custom indicator object to complement the standard indicator set.

Standard indicators use fixed, known inputs and can be instantiated via dedicated constructors. Custom indicators require an MqlParam[] passed to a creation method, including a mandatory TYPE_STRING element with the indicator path/name. A new indicator group β€œany” covers unknown type until the user assigns trend/oscillator/volume/arrow.

The indicator base class adds an ID property, ID-based sorting, and data access helpers that fetch a single value via CopyBuffer() by bar index or time. Parameter descriptions for custom indicators are printed sequentially from MqlParam[].

Indicator collection creation now checks ID uniqueness, supports custom indicator lookup by group+MqlParam[], and provides GetByID/SetID. On timeframe changes, duplicate handles...

πŸ‘‰ Read | AppStore | @mql5dev
❀54πŸ‘14πŸ‘€6πŸ‘Œ4⚑3πŸ‘¨β€πŸ’»2
A new MT5 chart wallpaper background indicator is available with BMP support.

Place an image named background.bmp in the terminal’s FILES directory, then attach the indicator to a chart. The indicator reads the BMP file and renders it as the chart background.

Two layout modes have been added to control scaling behavior: BMP_FIT and BMP_FILL. FIT keeps the entire image visible with possible margins, while FILL covers the full chart area and may crop edges.

πŸ‘‰ Read | Signals | @mql5dev
🀣16❀15πŸ‘15πŸ‘Œ4😁3
Neural-network trading workflow shifts from Matlab to Python, using TensorFlow plus Keras with MetaTrader 5 integration. Focus moves to input preparation, dataset splitting by direction, and training operations for EURUSD H1.

A two-stage model is used: Net1 reproduces indicator-like features from quotes, Net2 generates the signal target. The system runs four networks (buy/sell, max/min). MQL5 scripts export CSVs; daily extreme markers set -1 at first high/low touch. Net2 targets are hour open vs day open (or day close vs hour open), emphasizing achieved outcomes over event prediction.

Training is handled in a Python script: pandas ingestion, standardization, a Sequential model (22 inputs, 60 outputs), 10 epochs, batch 10, 30% validation, then saving .h5 models. Strategy Tester data generation feeds a separate test dataset.

Results are optimized via an EA ...

πŸ‘‰ Read | CodeBase | @mql5dev
❀59πŸ‘20πŸ†3⚑2πŸ‘Œ2πŸ‘1
Volume-Weighted Price Displacement Oscillator measures mean reversion against a rolling VWAP instead of a simple moving average. Higher-volume bars influence the anchor more, so the reference tracks where trading concentrated, not just closes.

The oscillator is Close minus rolling VWAP, normalized by a rolling standard deviation over a separate volatility window. This produces a z-score style histogram: near 0 indicates trading around volume-weighted fair value, beyond Β±1.0 indicates an impulse, and beyond Β±2.0 flags statistical stretch where consolidation or reversion becomes more likely.

Key inputs: VWAP period (default 20), volatility period (14), signal smoothing (5), impulse level (1.0), exhaustion level (2.0), applied price (typical). Practical use: in trends, sustained impulse readings can support continuation; in ranges, exhaustion plus the signa...

πŸ‘‰ Read | Freelance | @mql5dev
❀33πŸ‘9πŸ‘¨β€πŸ’»2πŸ‘Œ1
MetaEditor’s profiler finds slow code, but it won’t catch indicators that draw β€œcorrect-looking” lines with wrong values. This walkthrough focuses on the debugger: pausing execution at breakpoints, stepping line-by-line, inspecting variables in Watch, and using the call stack to trace how a bad state was reached.

A rolling z-score indicator is used with two intentional bugs: an off-by-one loop in the mean that can read past the array edge, and a variance formula dividing by period+1, producing a plausible yet consistently biased result.

Key workflow: start debugging on real data (F5) or in Strategy Tester history mode (Ctrl+F5), place breakpoints before suspect reads, then step until the exact variable (like an index) becomes invalid or the math deviates silently.

πŸ‘‰ Read | VPS | @mql5dev
❀21πŸ‘5πŸ‘Œ2
Partial position closing in MQL5 often fails in production due to three implementation errors: lot-step rounding, applying close percentages to remaining volume, and leaving the stop at the original risk after the first scale-out.

A CPartialCloseEngine design addresses these directly. It freezes entry state in CPositionRecord, drives an R-multiple profit ladder, normalizes and clamps volumes via CVolumeNormalizer, executes reductions with TRADE_ACTION_DEAL through a dedicated executor, and moves SL with TRADE_ACTION_SLTP in a breakeven manager.

The ladder applies percentages to the original entry volume, tracks per-level hit state, optionally triggers a one-time breakeven shift, and draws chart HLINE markers for verification. A companion script validates rounding rules, R calculations, trigger logic, and remainder clamping.

πŸ‘‰ Read | Docs | @mql5dev
❀26πŸ‘5😁2πŸ‘Œ2✍1
This article replaces fragile, hand-tuned trade filters and β€œtrain-once” ML with an online logistic regression that updates after every closed trade. The goal is simple: keep the EMA crossover, but adapt the filter when market behavior changes.

A shared MQL5 library implements logistic regression with a minimal SGD update, L2 regularization, optional learning-rate decay, and CSV persistence. The EA builds six explicitly scaled features, gates entries by predicted win probability, then labels outcomes using net profit (including costs) while handling partial closes via position IDs.

Validation uses a synthetic generator to prove the update rule learns, quantify warm-up needs, test feature ablations, check probability calibration, and compare online learning against frozen and periodic/rolling retrain baselines under regime shifts. Practical notes cover visualizati...

πŸ‘‰ Read | CodeBase | @mql5dev
❀17πŸ‘6🀯2πŸ‘Œ1
A causal trend-scanning engine was ported from Python to MQL5 as CTrendScanningFeatures.mqh, exposing four EA-friendly buffers (window, slope, t_value, RΒ²) via a standard iCustom-compatible indicator. The implementation replaces full window recomputation with O(1) per-horizon updates using running sums plus a ring buffer, while preserving numerical parity against the reference.

Building the port from first principles uncovered a sign inversion in the Python causal mode: reversing inputs without negating slope and t_value. The Part 13 wrapper is corrected by flipping both signs; most earlier conclusions remain unchanged because comparisons were sign-symmetric.

Two research-level caveats stand out. With volatility_threshold=0.0, β€œmasking” collapses to a simple running minimum. More importantly, selecting the max |t| across window lengths does not select th...

πŸ‘‰ Read | CodeBase | @mql5dev
❀57πŸ‘5πŸ‘Œ3πŸ†3⚑2
Volume-Weighted Delta Divergence Oscillator (VWDD) derives a delta proxy from each candle without requiring true order-flow. The close position inside the high-low range is mapped to a -1..+1 ratio and multiplied by volume (tick or real). Per-bar values are accumulated over InpDeltaPeriod, then normalized by a rolling standard deviation over InpNormPeriod to keep readings comparable across symbols and sessions. InpSmoothPeriod reduces noise.

The subwindow histogram shows net pressure: above zero suggests buy dominance, below zero suggests sell dominance. Divergence detection uses fractal-style swing confirmation with InpDivLookback bars on both sides and searches back up to InpDivSearchRange. Higher highs with lower oscillator highs flag bearish divergence; lower lows with higher oscillator lows flag bullish divergence. Arrows lag by roughly InpDivLoo...

πŸ‘‰ Read | Calendar | @mql5dev
❀22πŸ‘10πŸ‘Œ2πŸ‘¨β€πŸ’»2
Adaptive Volume Profile Node Tracker implements a rolling volume profile where bin size adapts to current volatility. On each rebuild it reads ATR(InpATRPeriod), derives a bin height from it, then clamps bin count between 5 and InpMaxBins. This keeps profiles granular in tight ranges and prevents over-fragmentation during fast markets.

The profile is built from the last InpLookback completed bars, bucketing tick volume (or real volume when enabled) by each bar’s close. It then identifies the Point of Control, expands outward to capture InpValueAreaPercent for Value Area High/Low, and classifies High/Low Volume Nodes using a mean and standard deviation threshold (InpNodeStdDevMult). Levels update every InpRecalcBars bars.

Operationally, POC and Value Area define fair value vs extension, HVNs tend to behave as liquidity shelves, and LVNs often mark fas...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀27πŸ‘6πŸ‘Œ2
Multi-Symbol Correlation Divergence Meter quantifies when two typically linked instruments stop behaving alike. It calculates rolling Pearson correlation on bar-to-bar returns between the current chart and a user-defined reference symbol, plus a log-price spread converted into a rolling z-score.

A divergence event is signaled only when correlation drops below a configurable threshold and the spread z-score exceeds an extreme level. This filters for situations where decoupling and relative mispricing occur together, often preceding either mean reversion or a regime change.

Outputs include a correlation line bounded from -1 to +1 with a color change on breakdown, a spread z-score histogram, and optional up/down arrows for qualifying extremes. Typical use is risk tightening on correlation-dependent positions or conditional mean-reversion setups, validat...

πŸ‘‰ Read | Freelance | @mql5dev
❀15πŸ‘6πŸ”₯5πŸ‘Œ2
Candle Body-to-Wick Pressure Oscillator converts candle geometry into a bounded pressure score, then smooths it into an oscillator with an EMA signal line. Instead of relying on closes, it combines signed body ratio (|close-open| / range) with a wick imbalance term ((lower wick - upper wick) / range), weighted by InpWickWeight and normalized to stay near Β±1 before scaling to Β±100.

Histogram values above zero indicate bullish pressure dominance over the lookback; values below zero indicate bearish pressure. Crosses versus the signal line and the zero line help classify regime shifts and continuation.

Optional divergence marks are generated from confirmed price pivots (InpFractalRange) within InpDivergenceLookback, flagging higher oscillator lows vs lower price lows, or lower oscillator highs vs higher price highs. Defaults typically transfer across sy...

πŸ‘‰ Read | NeuroBook | @mql5dev
❀28πŸ‘7πŸ‘Œ3πŸ€”1
Currency Strength Meter computes relative strength for the 8 major currencies by aggregating percentage changes across all available broker pairs, rather than relying on a single cross. Each symbol contributes +change to the base currency and -change to the quote currency, then each currency score is averaged across the pairs it appears in. Missing crosses are skipped, keeping results usable without hard failures.

Output is a ranked list from strongest to weakest, with a per-currency average percent change over the selected lookback window. Bars are scaled to the largest absolute score on each refresh; colors differentiate positive versus negative readings.

Key inputs include calculation timeframe (independent of chart), lookback bars, and refresh mode (new bar only or every tick), plus panel layout and styling. Designed as read-only: no trade operat...

πŸ‘‰ Read | AppStore | @mql5dev
❀28πŸ‘6πŸ‘Œ2πŸ†2
Liquidity Void Decay Oscillator identifies gap-like displacements only when range expansion aligns with below-average tick volume, filtering for thin-participation moves rather than candle geometry alone.

Each detected void starts with a score of 100 and decays as later bars overlap the zone. Faster re-trading reduces the score quickly, while repeated approaches with limited overlap keep the charge elevated and signal an area still affecting order placement.

Outputs include a 0–100 histogram for the strongest active void, bar coloring to indicate whether the nearest void is below or above price, and a short SMA signal line. A cross below the signal line while still high indicates accelerating absorption.

Typical use on liquid FX pairs and lower timeframes. Scores holding 60–100 after multiple retests can define actionable levels; rapid decay toward...

πŸ‘‰ Read | Calendar | @mql5dev
❀25πŸ‘7πŸ‘Œ2
A compact MQL5 toolkit measures market β€œefficiency” by treating recent returns as a symbol string and scoring how well that string can be described by Lempel–Ziv phrase parsing. The LZ76 count is parameter-free and fast enough per bar; normalization maps values near 1 to noise-like behavior and lower values to repeatable structure.

Prices are not fed directly. The pipeline converts a trailing window of log-returns into symbols using SAX: z-normalize to remove scale, optionally aggregate, then quantize via Gaussian breakpoints so random data is uniformly distributed across the alphabet. Breakpoints are computed on the fly with a high-precision inverse normal approximation, and flat windows are handled explicitly to avoid divide-by-zero artifacts.

The library is split into symbolizer, complexity, NCD distance, and a facade class with reusable buffer...

πŸ‘‰ Read | Calendar | @mql5dev
❀16πŸ‘6πŸŽ‰1πŸ‘Œ1πŸ‘€1
Most automated chart pattern detectors validate geometry but ignore context. Reversal shapes inside ranges and continuation shapes without a prior impulse are routinely misclassified when prerequisite structure is not enforced.

A second failure mode is timeframe coupling. Swing logic computed on the same chart timeframe inherits intraday noise, causing trend state to flip repeatedly and invalidating context checks.

A proposed MQL5 approach fixes both issues by reading market structure from H4 regardless of the trading timeframe. H4 swing points are detected with a configurable strength window, labeled HH/LH/HL/LL, and the latest labels define trend state. Patterns on lower timeframes are evaluated only when the H4 prerequisite is met, while drawing remains correct via datetime anchoring.

πŸ‘‰ Read | Quotes | @mql5dev
❀14πŸ‘11πŸ‘Œ3
Entry filters are often judged by running an EA with and without enforcement, then comparing net profit, drawdown, and trade activity. That A/B test captures operational path changes from occupancy, compounding, sizing, and constraints, but it does not isolate whether accepted trades are an unusually favorable subset of base trades.

FilterEdgeAnalyzer.mqh separates these claims. A diagnostic run executes all base entries while tagging each position as accepted or rejected at entry. Completed positions are reconstructed from deals, net profit is aggregated per position, and accepted vs rejected mean outcomes are compared against fixed-count placebo selections that preserve the same acceptance count.

Three null models are supported: full mask permutation, equal-block permutation, and circular shifts. A finite-sample–corrected upper-tail p-value is report...

πŸ‘‰ Read | Freelance | @mql5dev
❀18πŸ‘6πŸ†2πŸ‘Œ1
This article turns the Oops gap reversal into a rule-complete MQL5 Expert Advisor, removing the common manual errors: missing the gap, confirming too early, letting setups run past validity, and inconsistent risk sizing. The EA detects gap-up and gap-down opens beyond the prior candle’s range, filters by a minimum gap in points, and tracks each setup for a fixed number of bars.

A shared state structure stores the gap bar time, reference levels, and lifecycle counters. Confirmation only happens on a later completed candle closing back into the prior range, preventing repeat signals and avoiding same-bar confirmation.

After confirmation, the EA rebuilds the gap-bar stop using iBarShift, projects take-profit from a risk-reward ratio, and sizes volume via fixed lots or percent-risk using OrderCalcProfit with broker step/limits. Execution is guarded by one-posit...

πŸ‘‰ Read | VPS | @mql5dev
❀25πŸ‘8πŸ†3πŸ‘€2πŸ‘Ύ2πŸ‘Œ1
EdgeMeter evaluates one question about any entry signal: after transaction costs, is there positive expectancy. It places no orders, reads history, tests the signal on each closed bar, and prints the result.

It reports gross edge across user-defined holding periods, net per-trade after costs (one position at a time), a t-statistic on non-overlapping trades, share of profitable months, and maximum drawdown. A random control with identical firing rate is included to validate the simulator and define the noise floor.

A common failure mode is overlap inflation. If forward windows overlap, treating samples as independent can overstate significance by roughly sqrt(horizon). EdgeMeter avoids this by simulating sequential, non-overlapping trades.

Pass criteria require net per trade > 0 after cost, |t| > 2, and at least 3 profitable months out of 4. Costs are e...

πŸ‘‰ Read | Docs | @mql5dev
❀20πŸ‘5πŸ‘Œ2
Stock CFDs continue to gain adoption, with broader platform support and FX brokers expanding availability. A common approach in equity intraday trading is the Opening Range Breakout (ORB), typically implemented around the NY cash session open.

A 5‑minute AAPL CFD algorithm based on ORB logic was built and tested. The entry module captures the early-session high/low range, then applies a volatility filter to qualify breakouts and reduce false triggers.

Risk management uses a fixed-risk stop loss, with take profit defined as a ratio of SL. Trailing and breakeven rules are included. Position sizing is derived from risk per trade relative to initial capital rather than floating equity, aligning with evaluation accounts where compounding can amplify drawdowns.

Session timing remains critical. The NY opening bell must be mapped to broker server time, with parame...

πŸ‘‰ Read | Calendar | @mql5dev
❀15πŸ‘10πŸ‘Œ4πŸ‘¨β€πŸ’»3✍2