MQL5 Algo Trading
509K subscribers
3.4K photos
3 videos
3.4K 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
The article contrasts “static” MT5 indicators built with compilation directives versus “dynamic” ones configured at runtime through standard library calls. Removing directive-based plot definitions compiles but produces no output until buffers, plots, and color palettes are explicitly set in OnInit.

A key takeaway: runtime configuration enables changing visual behavior without recompiling, but it can hide options in the indicator dialog until after the first attach, and user color changes may reset when the chart is rebuilt (e.g., timeframe change).

The approach becomes practical when an indicator must adapt to chart modes. By reading the current mode via ChartGetInteger (ENUM_CHART_MODE), the code can switch drawing logic so Inside Bar rendering matches candles, bars, or line charts, improving robustness across chart types.

👉 Read | Docs | @mql5dev
17👍12👌2
This part of the market simulation series shifts from basic SELECT queries to the core of relational design: primary and foreign keys, used to preserve data integrity and prevent duplicate or inconsistent records.

It also recommends moving beyond MetaEditor’s minimal SQLite support when learning database concepts, using DB Browser for SQLite to edit, save, and run SQL scripts in a database-focused environment.

The article ties SQL back to algorithmic trading infrastructure: MT5 tools can reach databases over sockets, enabling scalable data flows between terminals, Excel, and server-hosted SQL. The key takeaway is to rely on SQL and proper schema constraints instead of reinventing database behavior in code, keeping systems reusable across applications.

👉 Read | Calendar | @mql5dev
29👍9🔥4👌2
DEA (Dolphin Echolocation Algorithm) is a population-based optimizer aimed at trading-robot parameter tuning. Agents evaluate candidates, broadcast influence within an effective radius Re, and build an accumulated fitness (AF) prospectivity map. PP (predetermined probability) increases over epochs using Power to shift from wider sampling to stronger reuse of high-quality regions.

A key detail is AF reset for the current best location, which reduces early collapse into a single point and keeps neighborhood probing active. Re controls locality: small Re tightens search, mid values balance, large Re spreads influence but reduces precision.

Implementation notes cover S_Alternative and S_Coordinate storage, plus a DEA class with Init/Moving/Revision and internal routines for PP, AF, best-location reset, and next-location selection. Memory cost scales with...

👉 Read | Freelance | @mql5dev
54👍9💯54🏆4🔥3👀1
Nadaraya and Watson (1964) proposed estimating values as a locally weighted average using a kernel as the weighting function.

This approach produces a non-causal, recalculating smoothed series. The output can be treated as an estimate of the underlying trend component, not as a forward-looking projection.

No extrapolation is applied, specifically to avoid misinterpretation as predictive signaling. The implementation follows prior work by luxAlgo adapted across trading platforms.

Operational guidance: use for discretionary assessment only. Avoid using the output as a trigger in any automated or rule-based signaling mode.

👉 Read | Forum | @mql5dev
37👍10👌2
Algorithmic execution by large participants can create time gaps: price crosses a zone fast enough that the chart shows minimal time-in-zone and low follow-through activity.

A MetaTrader 5 indicator concept formalizes this via a volume-based impact coefficient (VIC), emphasizing high volume plus short traversal time. Detection uses an adaptive price grid, zone forensics over historical bars, and strict sufficiency checks on absence duration, max stay time, speed, and volume impact.

Zones are tracked with dynamic “memory strength” using decay plus session cyclicality, and marked closed when fully filled. Suggested tuning differs by asset class: FX lower thresholds, stocks session-aware, crypto higher thresholds with smaller minimum bars. Signals include boundary rebounds, full fills, and failed fill reversals.

👉 Read | Freelance | @mql5dev
29👍7🔥4👌2
This article shows how to build a candle/bar counter in MT5 without harming terminal performance. The key is treating OnCalculate as a high-frequency event: it can fire on every tick, so detection of new bars must be constant-time and avoid unnecessary data access.

Instead of comparing datetime values from the Time[] series, the article favors using rates_total and prev_calculated to detect when a new bar appears. This integer-based check is simpler and faster, and it keeps indicators responsive even on volatile symbols.

It then shifts to chart objects: everything drawn is an object, either chart-coordinate or screen-coordinate based. A practical example uses an indicator to create and update a Linear Regression Channel by setting anchor points, and removes it on deinit. Updating the object on each recalculation produces a highly reactive, self-adjus...

👉 Read | Freelance | @mql5dev
28👍10👌4
This article connects MT5 replication/simulation work to practical SQL use via SQLite, arguing that database features often replace large amounts of custom MQL5 state-handling code for orders and positions.

It contrasts SQLite’s small set of storage classes with MySQL/PostgreSQL’s extensive type systems. The key takeaway is SQLite’s flexible typing: columns don’t need rigid sizes, reducing schema maintenance while staying compatible with standard SQL patterns.

The example shifts from storing raw symbol strings in every quote record to a relational design using primary/foreign keys, so historical data remains stable even when tickers change. This lays groundwork for a command and order log suitable for strategy research and automation.

👉 Read | NeuroBook | @mql5dev
31👍20🎉42👌2
A new trading automation script supports creating multiple pending orders in a single run, focused on Buy Stop and Sell Stop entries. The order count is configurable, allowing batches such as 10 or 20 positions to be placed quickly and consistently.

Each pending order can be assigned risk controls and exit parameters at placement time, including Stop Loss and Take Profit levels. This reduces manual repetition, helps standardize execution rules, and limits configuration drift when placing multiple orders under the same setup.

Suitable for workflows that require scaling into breakouts with predefined targets and protective stops while maintaining consistent order parameters across a series.

👉 Read | CodeBase | @mql5dev
24👍13👌32🎉2
IMR combines Hurst Exponent, ADX, and linear regression (slope + R²) to help classify market phase and reduce timing errors in SMC/ICT execution. Many failures come from applying valid setups in the wrong regime: accumulation, distribution, or continuation.

RegScore expresses regression confidence: +100 or –100 implies a clean, disciplined move with R² ≥ 0.60. Treat extremes as context, not entries. With Hurst < 0.45 (mean reversion), +100 flags upside overextension and a higher probability of retracement; –100 does the same for downside, favoring reversal frameworks such as ChoCh plus order blocks/breakers.

With Hurst > 0.55 (trend persistence), +100 supports continuation bias; avoid fading and wait for pullbacks into aligned order blocks. ADX adds trend strength: <25 weak conditions, 25–50 workable expansion, >50 often climactic pressure where reve...

👉 Read | Signals | @mql5dev
27👍82👌2
Dynamic Fair Value Gap (FVG) is a custom MQL5 indicator built to detect unmitigated price imbalances based on a 3-candle pattern. It flags bullish gaps between Candle 1 High and Candle 3 Low, and bearish gaps between Candle 1 Low and Candle 3 High.

Mitigated zones are removed automatically once touched by later price action, keeping only active FVG areas on the chart. While untouched, each zone extends forward by a configurable number of bars (default 18) and remains labeled for monitoring.

The tool also plots previous daily high and low as horizontal liquidity references, refreshed at each new trading day. Alerting supports terminal pop-ups, sounds, and push notifications on new FVG formation, with scan depth controlled via BarsToKeep (default 300).

👉 Read | AlgoBook | @mql5dev
32👍9🎉2👌2
Backtracking Search Algorithm (BSA) is an evolutionary optimizer for real-valued problems that adds a simple but effective idea: keep a historical population (oldP) alongside the current population (P), and use that “memory” to guide exploration.

Each iteration optionally refreshes oldP from P with 50% probability, then shuffles it (Fisher–Yates) to avoid fixed pairings. Mutation generates one directional candidate per individual using M = P + F*(oldP - P), where F controls step amplitude. Crossover is driven by a binary mask: either mixed coordinates via mixrate or a minimal-change mode that alters only one coordinate.

A greedy second selection stage rolls back any trial that worsens fitness, making the method stable for tuning trading parameters. The MT5-style class design separates Init, Moving, and Revision, with explicit arrays for oldP/M/T, fitness snapsho...

👉 Read | VPS | @mql5dev
👍1613👌2
Seasonality can be quantified in MT5 by aggregating average returns across recurring time buckets: day-of-month (1–31), day-of-week (Mon–Sun), or hour-of-day (0–23). The output fits well in a separate indicator window to keep the main chart clean.

Implementation in MQL5 typically uses three buffers: a histogram for average returns per bucket, a line for the current/next periods, and arrow points for the next two expected values. Inputs control bucket type, lookback bars, percent vs points, positive-only filtering, and optional forecast rendering.

Core logic sits in OnCalculate: compute per-bar returns, map each bar time to a bucket via GetPeriodIndex, maintain sums and counts, then normalize to averages. Forecasting cycles buckets with modular arithmetic, and on-chart text can report lookback size, next periods, and best/worst buckets.

👉 Read | CodeBase | @mql5dev
32👍8🎉3👌1
Wyckoff remains one of the clearer cause-and-effect models for institutional supply and demand, but automation usually fails on context. Single events are easy to detect; the difficulty is validating the sequence that gives those events meaning.

An MQL5 EA can enforce that sequence with a finite state machine on H4: range after a prior trend, then spring or upthrust on low relative tick volume, then SOS or SOW on high relative volume, then LPS or LPSY pullback entries with ATR-based stops.

Tick volume is usable as a proxy because the logic relies on ratios versus a rolling baseline computed from the detected range, not absolute volume.

👉 Read | Docs | @mql5dev
28👍10👌1
This piece connects Python-side model validation to tick-accurate execution testing in MetaTrader 5, so edge is judged after spread, slippage, commission, and swap. The workflow exports a trained ONNX pipeline, probability calibrator parameters, feature ordering, and CPCV metadata, then runs each combinatorial path as a separate Strategy Tester agent to produce real-fill equity curves.

Key engineering constraints are made explicit: the StandardScaler is embedded in the ONNX graph, so MQL5 must feed raw features only; feature order must exactly match the recorded input tensor layout; and features must be computed on the last closed bar to avoid look-ahead.

CPCV logic stays in Python: it precomputes one timestamp mask per path, while the EA does fast membership checks, runs OnnxRun with correct (1, n_features) shape, applies isotonic or Platt calibration...

👉 Read | Forum | @mql5dev
👍1613👌1
MQL5 chart tools hit a ceiling when they rely on native objects. Placement is simple, but post-placement interaction is constrained: limited hit-testing, no custom handle drag, no rubber-band preview, and no precise deletion.

A canvas-based architecture replaces terminal-managed objects with a bitmap layer and an internal array of drawing structs. Redraw iterates the array and renders pixel-level primitives, enabling selection states, hover feedback, dragging, handle suppression during edits, and consistent styling.

Core components include ARGB opacity helpers, Porter-Duff pixel blending, anti-aliased thick lines with subpixel coverage, and scalable dash patterns. New circle primitives support filled handles and borders. Line tools render strokes first, then conditional handles with hover halos, while hit-testing covers segments and info panels.

👉 Read | Forum | @mql5dev
👍128👏3👌1
Value Charts and Price Action Profile, published in 2002 by Helweg and Stendhal, added volatility-adaptive context to traditional charts. In 2010, Abrams and Walker applied both to MR Swing, a mean-reversion swing system that reported strong equity results and portfolio-level drawdown reduction.

MR Swing is notable for asymmetric bull/bear logic and volatility-normalized signals. A 200-day SMA-based Hysteresis Channel classifies regime using a high/low buffer and increment-only updates to reduce whipsaws.

Bull entries use Value Charts on lows with a 5-bar floating axis and alpha 0.16, triggering at -7.5. Bear signals use DVO with Percent-Rank over 252 days as a Price Action Profile equivalent. Bull exits use SVAPO exhaustion with dynamic bands and limit orders.

👉 Read | Freelance | @mql5dev
35👍9👌32💯2
An optimized ZigZag implementation is available as a drop-in replacement for the legacy Zigzag.mq4 used since MT3-era MQL2. The goal is to reduce overhead when EAs rely on ZigZag values during strategy testing and live tick processing.

On the first run, the indicator computes the full visible history. On subsequent updates, it avoids full recalculation by locating the third extremum from the current bar and restarting from that point. Recalculation depth can be adjusted via the level parameter; setting it to 2 forces a restart from the second extremum.

External input names are preserved for compatibility. Minute-timeframe “floating” extremums have also been removed to stabilize plotted turning points.

👉 Read | Forum | @mql5dev
15👍9👌1
SQL foreign keys often look “wrong” until the result set logic is made explicit. A naive SELECT across tb_Quotes and tb_Symbols can produce a Cartesian product, multiplying rows (6 quotes x 4 symbols = 24), which is expected behavior.

A table diagram in tools like DBeaver helps confirm cardinality. The circle marker typically indicates one-to-many: tb_Symbols.id is referenced by tb_Quotes.fk_id, so one symbol can map to multiple quote rows.

Correct results require an explicit join condition. Using table aliases and a WHERE clause (or JOIN ... ON) constrains rows to fk_id = id, returning only matched quotes. Output can be tightened by selecting required columns, applying column aliases, and sorting with ORDER BY.

Updates become risky when fk_id is manually typed. A safer pattern is UPDATE with a subquery that resolves fk_id from symbol and date, avoiding har...

👉 Read | Signals | @mql5dev
19👍8👌1
MetaTrader 5 scripts cannot register OnChartEvent, so direct keyboard event handling is not available. A workable substitute is polling: filter key state inside a controlled loop and update chart objects between iterations.

A common pitfall is execution speed. A script can create, position, and delete objects before any interaction is visible. Keeping the script alive requires a loop with throttling to limit CPU use, plus explicit cleanup so objects do not persist after chart rebuilds (period change forces script removal).

The same pattern can be extended with function pointers in MQL5. Functions share a signature, a pointer type is declared, and an array of pointers enables selecting behavior without hardcoding function names.

👉 Read | Docs | @mql5dev
👍138👌1
This article builds a MetaTrader 5 heat map indicator that measures “time-at-price” to rank support/resistance by where the market actually lingers, complementing earlier time-gap detection. Price is split into micro-zones, time spent in each zone is accumulated, then normalized to a 1–100% presence scale and mapped to a smooth red-to-blue gradient.

The implementation emphasizes reliability and speed: a modular PriceLevel structure, a sliding window over recent history, an adaptive grid (50–1000 levels, tick-size aware), and an overlap test that avoids O(n²) scans. Updates run only on new bars, arrays are reused, and rectangles are efficiently managed on-chart.

For traders, blue zones act as “magnets” for mean reversion and range boundaries; red zones flag fast-through areas prone to whipsaws. Developers get a framework that integrates well with volu...

👉 Read | Signals | @mql5dev
18👍84👌1
The article shows why “having an id column that looks like a foreign key” does not make a database relational. Without an actual foreign key constraint, deleting a symbol can leave orphaned quote rows, and later reusing the freed id can silently attach old quotes to a different symbol.

It then rebuilds the schema with a real primary key/foreign key relationship, which blocks unsafe deletes and forces correct deletion order (remove dependent quotes first, then the symbol) to preserve consistency.

Finally, it introduces SQLite triggers to automate multi-step maintenance: a delete trigger can cascade cleanup from one command, and an insert trigger can enforce normalization (e.g., auto-uppercasing symbols). The key takeaway for trading data pipelines is to prefer constraints and carefully designed triggers over manual assumptions.

👉 Read | Forum | @mql5dev
21👍7👌1