MQL5 Algo Trading
489K subscribers
3.1K photos
3.1K 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
Markets often look random, but chaos theory frames them as systems with hidden structure: mean reversion, sensitivity to initial conditions, and fractal self-similarity across timeframes.

The article builds a MetaTrader-style Neural Attractor Oscillator: a small feedforward network trained on price history, using tanh for bipolar dynamics and normalization for stable learning. It predicts a moving β€œattractor” level, then outputs an oscillator as percent deviation from that attractor to flag overextension and potential snap-back.

Signal quality is gated by a Lyapunov exponent to quantify how chaotic the market is, with optional fractal noise (Midpoint Displacement) and momentum optimization to improve training. Practical use includes adaptive overbought/oversold bands, divergence detection, and smoothing choices (EMA/SMA) based on regime.

πŸ‘‰ Read | AppStore | @mql5dev

#MQL5 #MT5 #AITrading
❀29✍2πŸ‘Œ2πŸ‘€2πŸ€”1🀩1
MetaTrader 5 indicators and EAs ship with a standard settings dialog built from default tabs. Most UI additions seen in custom tools duplicate what the platform already provides, and increase maintenance without adding capability.

The first tab can be adjusted via #property directives, including icon, purpose text, and a URL. These values are compiled into the binary and rendered by the terminal, with link details available via hover and click.

Indicator execution hinges on OnInit and OnCalculate. MQL5 provides overloaded OnCalculate signatures; the chosen signature affects whether specific configuration tabs are shown. A minimal indicator can be defined statically with #property, one plot buffer, and SetIndexBuffer, relying on platform-managed styling options such as color, line style, thickness, and calculation mode.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #Indicator
❀63πŸ‘7⚑6πŸ‘Œ3😁2πŸŽ‰2πŸ‘€1
Moving Average Cloud renders four moving averages on the same chart using a histogram-style band. It combines slow SMA(200) and EMA(200) with fast SMA(50) and EMA(50).

The space between the paired slow lines and the paired fast lines is plotted as boundary histograms, forming a cloud that highlights MA separation and compression. This makes it easier to track trend structure and potential support/resistance zones derived from MA alignment.

Histogram color changes are used to flag momentum shifts, helping detect transitions where fast/slow relationships start to rotate or converge.

πŸ‘‰ Read | Quotes | @mql5dev

#MQL4 #MT4 #Indicator
❀47✍2πŸ‘Œ2
A lightweight EMA in MQL5 can be implemented with a single change in the calculation line, relying on MetaTrader 5 event handling and buffer management. The EMA formula only needs the current price, prior EMA value, and period, with an initialization workaround for the first value.

A key follow-up is parameterization. Using an input constant allows period changes without recompilation, and a string comment improves the settings UI by providing a clear label instead of the raw identifier.

The article also contrasts the two OnCalculate signatures. The extended version exposes more series data but typically fixes the applied price (for example, Close), which removes UI options and shifts responsibility to the implementation.

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 #Indicator
❀22πŸ‘Œ4
Manual Supertrend trading is deterministic on paper, but live execution often adds latency and decision noise. An MQL5 Expert Advisor can keep analysis separate from execution by acting only on confirmed trend flips.

Supertrend stays in two states. A buy triggers when a completed candle closes above the upper band and the state turns bullish. A sell triggers when a completed candle closes below the lower band and the state turns bearish. Signals are evaluated only on closed bars to avoid unstable reads.

EA rules: close any opposite position first, then open in the new direction if enabled. Direction can be long-only, short-only, or both. Stop loss is optional, using last candle high/low or the Supertrend band. Lot sizing supports fixed volume or risk-percent auto sizing.

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #Indicator
❀37πŸ‘5✍2πŸ‘Œ2πŸ€”1
StrategyTester5 adds multi-symbol, multi-timeframe history handling to a MetaTrader 5–Python simulator via a HistoryManager that fetches bars, ticks, and synthetic ticks, then syncs timeframe data for later copy_rates/copy_ticks access.

A naive multi-timeframe loop is a major bottleneck. Real-ticks mode can drop to ~13 ticks/s when repeatedly calling copy_rates_from_pos across symbols and timeframes. Switching to direct MT5 terminal reads can lift throughput to ~600 ticks/s, but long ranges still remain costly.

Parallel per-symbol OnTick execution improves total wall time by isolating trade operations per instrument while sharing account state. Additional gains come from new-bar event gating to avoid repeated history reads, and choosing faster modelling (M1 OHLC/new-bar) when tick-level accuracy is not required.

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀29πŸ‘2πŸ€“2πŸ‘Œ1🀑1
MetaTrader 5 already supports alerts, push, email, logs, and simple sounds, but typical notifications lack context. A tone does not identify BUY vs SELL, symbol, timeframe, or signal conditions.

Semi-automated trading tools amplify this gap because they depend on human confirmation while communicating mainly through chart visuals. Accessibility limits come from UI assumptions, not from MQL5 capabilities.

A practical approach is an MQL5 MA crossover indicator that triggers structured text plus embedded WAV resources. On each confirmed crossover it reports symbol, timeframe, MA values, and price, plays buy/sell audio, logs events for later review, and avoids duplicate alerts via new-bar gating.

The design can be extended with richer voice feedback, voice commands, and future AI voice synthesis via external APIs, without changing the core signal logic.

πŸ‘‰ Read | Quotes | @mql5dev

#MQL5 #MT5 #Indicator
❀28✍5πŸ‘Œ4⚑3πŸ‘€3πŸ†1
Angular analysis is moving from subjective chart drawing to measurable features: compute the angle between consecutive price points after normalizing time and price axes.

The workflow builds a continuous angle stream, then derives rolling features such as last angle, 3-bar mean, positive/negative ratio, standard deviation, and max angle.

A practical pipeline pairs direction classification with magnitude regression using gradient boosting (CatBoost), trained on windows (for example 15 bars) and labeled by forward returns (for example +24 bars).

Backtests on EURUSD indicate angles carry predictive signal, with stronger performance in trending regimes and around reversal setups where a unidirectional angle run flips sharply.

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀49πŸ‘Œ6πŸ€”5
Average price tracking can be configured on higher periods such as H1 and D1. A D1 average helps assess whether an instrument is trading above or below its daily mean, while H1 reacts faster and can flag reversals earlier.

The indicator relies on three inputs: calculation symbol, averaging timeframe, and applied price. Lower chart timeframes from M1 to M30 are typically used for monitoring, with M1 providing the most granular view.

It also supports overlay comparisons of multiple instruments on a single chart, such as EURUSD versus USDCAD on M15, and can display daily average levels that often act as practical support and resistance zones.

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #Indicator
❀29πŸ†2πŸ‘Œ1
A unidirectional trend strategy for XAUUSD is built by combining K-Means clustering with CatBoost classification. K-Means segments history into market modes using compact meta-features (e.g., rolling volatility), then a meta-model learns to detect the active mode while the main model predicts trade direction for that mode.

The workflow is engineered for fast iteration: feature generation from close prices, per-cluster trade labeling for a single side (buy-only in the example), 70/30 validation with early stopping, and a custom tester that ranks candidates using balance-curve RΒ². Sparse clusters are filtered out to avoid unreliable fits.

Practical deployment is covered via ONNX export to MT5, with a key caveat: feature calculations must match exactly between Python and MQL5, or live signals will drift.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀37πŸ€”3😁2πŸ‘Œ1
This article shows how to build richer MT5 indicators without multiplying separate scripts. It starts by extending a basic High-based plot into a single indicator that draws multiple lines (High and Low) by adding extra indicator buffers, assigning unique buffer indexes, and correctly increasing the declared plot count.

It then switches from DRAW_LINE to DRAW_COLOR_LINE to support color-changing lines. The key detail is that each colored plot needs an additional color-index buffer, mapped in order with SetIndexBuffer, and populated with INDICATOR_COLOR_INDEX values that select entries from the plot’s color array.

Finally, it previews DRAW_FILLING: a two-buffer plot that fills the area between lines, useful for band-style visuals or crossover-style signals by swapping top/bottom values based on bar direction.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #Indicator
❀29⚑2πŸ†2πŸ‘Œ1
Part 8 extends an MT5 hybrid EA (MA crossover + on-chart CCanvas controls) with a persistent CSV trade journal that records not just what happened, but why it happened.

A CTradeJournal module built on Files/FileTxt.mqh uses CFileTxt to open/append CSV safely, write the header once via Size(), Seek() to the end, and Flush() after each entry for crash-resistant logging. FILE_SHARE_READ keeps the journal inspectable while running.

Each trade event is tagged by decision source: ALGO for strategy-driven entries and HUMAN for chart-click closures routed through OnChartEvent(). The result is portable, analysis-ready data (time, ticket, symbol, action, profit) that cleanly separates automated performance from discretionary intervention and plugs directly into spreadsheets or Python/R workflows.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #EA
❀27πŸ‘Œ3
Part 39 in the MQL5 series focuses on practical file handling for trading tools. Core topics include where terminal files are stored, and safe open/read/write/close workflows for persistent logs, indicator snapshots, and error reporting.

A project script is outlined for a CSV trading journal that records account identity plus deal history fields such as ticket, symbol, type, volume, timestamps, prices, SL/TP, profit, and result, along with last update time.

User-selected storage is implemented via FileSelectDialog instead of hardcoded paths, supporting default names, filters like CSV|*.csv, and write modes that allow creating new files. FileOpen then creates or opens the target with flags such as FILE_WRITE, FILE_CSV, FILE_SHARE_READ, FILE_ANSI, followed by handle validation, error checks, and FileClose for data integrity.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #script
❀19πŸ†3πŸ‘Œ2πŸ‘1
Static indicator implementations in MQL5 are simple but lock the rendering mode. A dynamic approach allows multiple indicator behaviors, including pattern marking and alternative inner-bar criteria.

For candle recoloring, buffer order is critical. MetaTrader 5 interprets OHLC buffers by position; a wrong sequence can change candle geometry, not just colors. Correct indexing as Open, High, Low, Close fixes rendering.

An inner bar can be detected against the previous candle, or against an older boundary using stored high/low limits. Static variables can preserve these limits until a breach occurs, preventing false positives and clearing state when invalidated.

Chart UI can also be controlled via code, including hiding price/time scales. Such changes should be reversible in Deinit, but forced removals may skip cleanup, so user options and cautious defa...

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #Indicator
❀17πŸ‘Œ4πŸ‘2
Multi-agent trading in an MQL5–Python stack extends feedback-driven adaptation into cross-symbol coordination. Independent agents score trend, momentum, and volatility per instrument, while a context layer aggregates macro inputs such as USD strength from major pairs to bias decisions on XAUUSD.

The runtime is a shared MT5 session managed in Python, with real-time data pulled into pandas and enriched with EMA, RSI, and ATR. Agent outputs are combined through a weighted consensus model, logged to JSON, and gated by confidence thresholds before execution.

A Flask API provides /start, /stop, and /status controls plus signal delivery. The MQL5 EA polls the API, parses JSON via a minimal in-terminal parser, enforces risk sizing and ATR-based stops, closes opposing positions, normalizes prices, and submits orders asynchronously.

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀28✍7⚑6
Part 16 extends the MQL5 canvas dashboard with anti-aliasing and high-resolution rendering. Supersampling renders panels at 4x size and downsamples by pixel averaging, reducing jagged borders on curves, text, and UI controls. Bicubic-style resampling is used during scaling to retain smooth gradients.

The implementation adds high-res canvases for stats and text panels, plus inputs for rounded triangle arrows, font sizing, and optional scroll buttons. Initialization creates both normal and high-res bitmaps; deinit and UI state changes destroy them when not needed.

Rendering changes include precise arc-based rounded rectangle borders and scanline-filled quadrilaterals. Scrollbar arrows are redrawn as rounded triangles using precomputed tangent geometry and angle checks for correct arc sweeps, aligned to a Windows 11-style scrollbar.

πŸ‘‰ Read | Freelance | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀45πŸ‘Œ6πŸ€”4πŸ‘3
This tool upgrades trendline analysis in MT5 by replacing ZigZag pivots with swing points extracted directly from raw price action. Swings are detected via local high/low dominance, then filtered by a minimum size threshold or ATR-adjusted volatility, keeping only meaningful structural turns.

Validated swings are ordered by time to preserve structural consistency and reduce repaint-like behavior. Trendlines are built only when swing relationships align with market direction: descending highs for resistance and ascending lows for support.

Candidate lines are scored by touch count, recency, and tolerance-based β€œrespect” checks, then only the most significant support and resistance rays are drawn. The result is a cleaner chart and a repeatable way to work with sloped structure, useful for discretionary structure reading and algorithmic context filters r...

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 #Strategy
❀27πŸ‘Œ2⚑1
Mixed copulas extend elliptical and Archimedean models by blending multiple families into a single dependence model, with weights that sum to one. This makes it practical to represent center dependence plus asymmetric or symmetric tail behavior in one fit, which is common in financial pairs.

The article implements two mixtures used in copula-based pairs trading research: Clayton-Frank-Gumbel (separates lower tail, middle, upper tail) and Clayton-Student-t-Gumbel (adds two-sided tail dependence for volatility clustering/regime shifts).

Parameter estimation is handled with an EM algorithm and a penalized likelihood using the SCAD penalty, which can shrink unhelpful mixture weights to zero while avoiding Lasso-style bias on strong components. Hyperparameters are tuned via cross-validated grid search.

In MQL5, mixed.mqh defines a modular CMixedCopula ...

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀27πŸ‘5😁2πŸ‘Œ2✍1
Smash-day reversals are high-signal events, but trading every instance without context tends to amplify noise and reduce consistency. Larry Williams frames these as emotional excess: a breakout that attracts late entries, then fails quickly and forces a reversal.

A custom MQL5 indicator can handle objective detection without auto-execution. It flags confirmed patterns only: bullish when the next bar breaks above the smash bar high, bearish when the next bar breaks below the smash bar low. Outside bars are filtered, and lookback depth is adjustable.

Implementation centers on buffer binding, history mapping, and lightweight real-time updates. OnInit validates sufficient bars and configures plots; OnCalculate converts arrays to forward indexing, scans once on load, then updates the most recent indices on new bars and ticks.

πŸ‘‰ Read | Calendar | @mql5dev

#MQL5 #MT5 #Indicator
❀35πŸ‘Œ3
Follow-up work on MQL5 scripting shows why β€œorganized” code is not the same as structured code.

A script that hides and restores chart scales can be written with free functions plus a plain struct, but SAVE/RESTORE quickly lose context as features grow. Reuse then pushes toward overloads and duplicated names.

Moving SAVE/RESTORE into the struct binds behavior to the stored state, removes redundant declarations, and makes intent local to the data. The next failure case appears when adding another chart property: public fields allow unintended writes, causing state restore to break via data leakage.

This is the practical motivation for stronger encapsulation and the move toward classes.

πŸ‘‰ Read | Freelance | @mql5dev

#MQL5 #MT5 #Indicator
❀32✍7πŸ‘3πŸ‘Œ3
This article explains why socket-based Python servers (threads or select) can degrade Excel responsiveness: the script and Excel compete for CPU, making a spreadsheet-driven trading workflow impractical.

The proposed fix is to switch inter-process communication to Microsoft COM. Using Python’s built-in COM support, Excel can be automated directly without extra packages, with code that mirrors VBA-style object access (create or attach to an Excel instance, add/activate/rename sheets, write values and formulas).

It then extends the approach to event-driven integration: Python can subscribe to Excel Application/Workbook events, but handler methods must use exact event names from the Excel COM documentation. This enables real-time Excel-to-MetaTrader 5 control flows where Excel acts as the UI and an MT5 EA interprets commands.

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #EA
❀43πŸ†5✍3πŸ‘3πŸ‘Œ3