MQL5 Algo Trading
489K subscribers
3.11K photos
3.11K 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
MetaTrader 5 can use sockets from MQL5, but socket calls are blocked inside indicators to protect chart calculation performance. The solution splits responsibilities: an indicator provides the isolated chat UI, while an Expert Advisor handles network I/O and embeds the indicator binary.

A small connection class wraps socket lifecycle, validates the handle, and implements simple text send/receive. Reads are non-blocking with a short timeout and only return complete messages when a newline delimiter is detected, making message framing explicit and pushing protocol responsibility to the server.

The EA bridges everything with timer-driven polling (OnTimer) and custom chart events (OnChartEvent), passing incoming socket data to the indicator and forwarding user messages back to the socket. The article also notes event spoofing risks and why real deployme...

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀31
This part connects an MT5 chart control panel to backend logic using event-driven code. Instead of polling in OnTick, user actions are handled in OnChartEvent, filtering for object-click events and checking sparam to confirm the Send button was pressed.

Once validated, the handler reads the prompt from the input control and performs an HTTP call via WebRequest. The request is built with a model URL, API key, JSON content-type header, and a JSON body, then encoded to a UTF-8 char array (with the trailing null removed) to match WebRequest requirements.

It also establishes basic response handling: capturing headers/body, enforcing timeouts, reporting errors, and converting the returned byte array back into a string for later JSON parsing and panel display.

πŸ‘‰ Read | Freelance | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀32
CPI Mini-Candles for MT5 adds a pressure layer to candlesticks using Closing Location Value: where the close sits inside the bar’s high–low range. This yields a normalized CPI in [-1, +1], exposing cases like β€œred-but-bullish” or β€œgreen-but-weak” that candle color can’t explain.

The indicator overlays mid-anchored mini-candles on closed bars only. Marker direction shows buy/sell pressure, height scales with |CPI| (clamped for readability), and five zones (strong/mild/neutral) drive color mapping. Optional arrows mark strong-pressure bars with a configurable offset.

Alerts are state-based to avoid noise: events fire on transitions (not persistence), mainly when entering strong zones, with optional strong exits and sign flips. The MQL5 design uses DRAW_COLOR_CANDLES with synthetic OHLC buffers plus separate arrow plots, includes range gating, and keeps...

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #Indicator
❀55✍9⚑5
FFC Data Feeder is a utility Expert Advisor used to download economic calendar data for the FFC Calendar indicator. It is not a trading system and does not place or manage orders. The EA exists because MQL4 indicators cannot call the secure WebRequest API directly.

The feeder runs in the background on a single chart, retrieves data via native WebRequest, and stores it locally for the indicator to render across charts. This avoids enabling DLL imports while keeping the data path consistent.

One-time configuration requires enabling WebRequest in Tools -> Options -> Expert Advisors, then adding https://nfs.faireconomy.media/ to the allowed URL list. Run one instance on an empty chart, verify connection status on the dashboard, then attach the FFC 2.0 Calendar indicator to any chart. Free and open source as part of the MQL Trading Tools suite.

πŸ‘‰ Read | Forum | @mql5dev

#MQL4 #MT4 #EA
❀28πŸ‘6✍3πŸ‘Œ3
Part 5 extends a dual WaveTrend crossover indicator into a full chart UI: a fast oscillator generates entry candidates, while a slower one optionally filters trades to reduce noise.

Signals now form β€œboxes” around crossover bars and wait for a price breakout before confirming direction. Boxes can auto-extend using average candle size, making the breakout logic adapt to volatility instead of fixed ranges.

Rendering moves beyond standard plots by using the MQL5 Canvas library. Gradient β€œfog” overlays visualize trend strength with smooth interpolation, while signals can be shown as triangles or labeled bubbles.

Risk tools are integrated directly into the indicator: dynamic TP/SL levels are computed from candle-size multipliers or percentage moves, then drawn as lines and summarized in an on-chart table, updated only on new signals for efficient redraws.

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 #Indicator
❀26πŸ‘4πŸ‘Œ2
A Python trading simulator is being aligned with MetaTrader 5 semantics by implementing order_send as a single entry point for all trade operations. The request payload mirrors MqlTradeRequest fields and routes actions to either MT5 or a local tester mode.

In tester mode, pending orders, positions, and deals are stored in containers, with explicit handling for open, close, modify, delete, and history logging. Close requests validate bid/ask pricing rules and require opposing order types.

Request validation is centralized in a TradeValidators class: lot constraints, margin checks, entry price validity, stops level, SL/TP direction, max volume, max orders, and freeze level rules. A CTrade wrapper calls the simulator’s overridden order_send, enabling MT5-like trade APIs for strategy testing workflows.

πŸ‘‰ Read | Forum | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀22πŸ‘Œ3⚑2✍1
In the MetaTrader 5 beta build 5540, we have improved ONNX integration in MQL5:

β€’ ONNX models now run significantly faster on graphics cards with CUDA support.
β€’ New flags have been added for GPU management and logging.
β€’ The library installation workflow has been changed: it is now installed only on the first launch of an ONNX-based program, rather than together with the platform.

In addition, we refined the rendering of text and analytical objects on charts using the Blend2D engine introduced in the previous update. Trading reports have also been improved, and the strategy tester has been made more robust.

The web version of the platform has received several improvements as well. When adjusting stop levels on the chart, you can now see an approximate profit or loss in monetary terms. The display of certain trading data has also been corrected.

Read more…
❀27πŸ”₯8πŸ†3πŸ‘1πŸ‘Œ1
The article refactors an MT5 auto-optimization workflow to swap strategies cleanly, moving from SimpleVolumes to SimpleCandles while keeping library code independent from project code. The key change is separating β€œwhat varies per strategy” from the reusable project-creation and database plumbing.

A reliability bug is fixed in the optimization results database: concurrent tester agents can trigger β€œdatabase locked” insert failures. The solution adds retry logic with an attempt counter and short random backoff to SQL execution paths, plus a shared flag to detect errors and decide whether to commit or roll back transactions.

Developer ergonomics improve via redesigned loop macros that preserve debuggability and by documenting how to extend strategy inputs (example: max spread gate) end-to-end: tester inputs, init-string serialization, constructor parsing, ...

πŸ‘‰ Read | Quotes | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀45πŸ‘6✍4πŸ†4πŸ‘€3πŸ‘Œ2πŸ”₯1
Adaptive VWAP Institutional v1.0.0 is a VWAP indicator for MetaTrader 5 built with HFT and professional asset management constraints in mind, emphasizing consistent session logic and data-quality controls.

Asset class detection uses a multi-step verification flow (crypto, forex, metals, stocks, indices) to apply appropriate reset policies. Session handling includes DST-aware timezone calculations using Zeller’s Congruence, plus 17:00 New York rollover support for forex, gold, and energy.

Data conditioning adds median-volume sampling to reduce the impact of bad ticks and volume spikes. Session state persistence is handled via disk caching across restarts and timeframe changes. Core execution is optimized for O(n) behavior suitable for VPS deployments.

An on-chart diagnostic panel reports distance to VWAP (%), accumulated volume, bar count, and active tim...

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 #Indicator
❀23✍11πŸ‘6⚑4
A script is available for pulling cryptocurrency quotes from Binance and showing them in a custom symbol group inside MT5.

Enable WebRequest in Terminal Settings under Advisors and add https://api.binance.com to the allowed URLs. Copy BinanceQuotesDownloader into the terminal’s Scripts directory and run it from the Navigator.

Open View -> Symbols, then Custom -> Binance to select required instruments. Create charts via File -> New Chart -> Custom -> Binance.

Quote loading status is reported in the Experts tab. Once populated, the custom symbols can be used with indicators and standard chart analysis workflows.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #script
❀33πŸ‘9
A remote Python risk manager for MetaTrader 5 turns risk control into an always-on service, designed to protect accounts during volatility and human error. It focuses on the math behind drawdowns: deeper losses require disproportionately larger returns to recover, so limits must be enforced early.

The system connects via the MT5 Python API and checks account state every ~18 seconds. It tracks balance/equity drawdown, daily and weekly loss caps, and margin level, then can automatically close all positions and block further trading when thresholds are breached.

Implementation emphasizes reliability: a PyQt5 GUI for configuration and live metrics, multithreading to keep monitoring responsive, SQLite for state/history, autosave for restart safety, plus weekly HTML reports for post-trade analysis and iteration across multiple accounts.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #RiskMgmt
❀75πŸ‘Œ6🀯5πŸ‘3
A risk sizing indicator calculates position risk as a percentage of account equity and returns an acceptable lot size for the configured limits.

Configuration requires two inputs: target risk percentage and stop distance in pips. Based on these values, the tool determines the trade volume that keeps the maximum loss within the selected risk threshold for the instrument.

This supports consistent position sizing across varying stop sizes and helps standardize risk management when market conditions change.

πŸ‘‰ Read | Quotes | @mql5dev

#MQL5 #MT5 #Indicator
❀38πŸ‘€3πŸ‘Œ1
This article implements Larry Williams’ swing-based volatility in an MT5 Expert Advisor, replacing single-bar range metrics with two explicit three-day swing measurements. The EA takes the larger absolute swing distance as the active volatility proxy, capturing recent market expansion independent of direction.

At each new bar open, fixed breakout levels are projected from the session open using configurable swing percentages. Trades trigger only after price crosses these levels, using market orders (no pendings), with SL sized from the same swing and TP derived via a reward multiple of defined risk.

The code is structured for reuse: new-bar detection, a dedicated struct for stored levels, precise normalization, trade-direction controls, and manual or balance-risked position sizing, while enforcing one open position at a time.

πŸ‘‰ Read | AppStore | @mql5dev

#MQL5 #MT5 #EA
❀31πŸ€”7πŸ‘3⚑2
Part 12 upgrades an MQL5 correlation matrix dashboard from a static grid into an interactive tool driven by chart mouse events. The panel can be dragged, minimized to a header-only view, and provides hover feedback on buttons and timeframe selectors to reduce misclicks during live analysis.

The dashboard adds practical controls: cycle symbol ordering by average absolute correlation (original/ascending/descending), switch between correlation coefficients and p-values, and toggle light/dark themes with immediate recoloring of cells, headers, borders, and legend.

Implementation centers on new enums, inputs, and global state for hover/drag/minimize, plus functions that reorder matrices safely, rebuild UI blocks, and attach tooltips showing symbol pair, method, timeframe, bars, correlation, and p-value.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀38
Part 36 of the MQL5 series shifts from basic API connectivity to request security for exchange endpoints such as Binance.

Core focus is signing requests with HMAC-SHA256. The signature proves authenticity and integrity: the server recomputes the same value from request parameters plus a shared secret key and rejects mismatches.

SHA256 provides deterministic 256-bit hashing with strong change detection, but it does not identify the sender. HMAC adds the secret key so only authorized clients can generate valid signatures.

In MQL5, signing is performed locally before WebRequest. Inputs are typically a query string including a timestamp, plus the secret key. Both must be converted to byte arrays (commonly UTF-8). CryptEncode is used to produce the binary signature, which is then sent as a request parameter.

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #HMAC
❀24✍7⚑1
Central Force Optimization (CFO) applies deterministic kinematics to numerical optimization. Candidate solutions act as probes; fitness defines mass, and only better probes attract worse ones. Acceleration is aggregated from pairwise forces using mass difference and distance exponents, then positions are updated via a kinematic step with boundary reflection.

A reference implementation defines S_CFO_Agent with coordinate and acceleration arrays, plus fitness initialization. C_AO_CFO manages parameters (g, alpha, beta, population size, repositioning factor, optional noise), initialization, initial distribution, acceleration computation, and position updates across epochs.

Key operational points include one-way attraction, frep decay across epochs, distance-squared checks for numerical stability, and deterministic outcomes for a fixed initial probe la...

πŸ‘‰ Read | Calendar | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀47πŸ‘Œ6πŸ”₯2πŸ†2
Source text is missing.

Send the text to convert, and include any platform constraint (X/Twitter, LinkedIn, Mastodon) plus a target length if different from 800 characters.

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 Please paste the post text (or upload an image of it). I need the content to generate 2 relevant hashtags.
❀21πŸ‘Œ11🀣3😁2
An MQL5 panel for MetaTrader 5 was built to estimate β€œfair” FX rates from a currency matrix and to flag deviations versus live quotes.

The model derives cross-rates via multiple triangular paths, applies iterative convergence with weighted updates, and uses an arbitrage threshold to filter spread-driven noise. Output includes deviation signals, candidate triangles, and a live-updating matrix view.

Limits are noted upfront: broker quote coverage, latency, and execution constraints make it non-competitive with co-located hedge-fund infrastructure. Current status is demo-only, with a robot under development and validation pending on real trading conditions.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀21✍4
A Python-based Strategy Tester is extended toward MetaTrader 5 parity by adding sequential tick/bar playback, account and position monitoring, and reportable performance analytics.

Configuration is moved into JSON to mirror MT5 settings (symbols, timeframe, date range, modelling, deposit/leverage). The tester validates required keys and datatypes to prevent silent misconfiguration.

Four modelling modes are implemented: real broker ticks, synthetic ticks generated from M1 bars, new-bar execution (fast, least granular), and 1-minute OHLC (speed/accuracy compromise). A unified OnTick loop calls the EA callback per tick or per bar-open, while updating orders, positions, and account state.

The tester logs orders and deals, then produces an HTML report with core metrics (profit, win rates, drawdown, factors) and plots balance/equity curves, enabling practical st...

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #Strategy
❀39
Market Memory Zones standardizes price-level detection using objective zone types instead of subjective support/resistance markup.

Three core classifications are used: displacement zones from ATR-multiple impulsive candles with low overlap, structure transition zones from CHoCH-style swing breaks, and liquidity sweep origin zones from stop-run candles followed by reversal. Optional unfilled/inefficiency zones cover gap-like imbalances.

Implementation is object-driven: rectangles rendered in-chart, no indicator plots. Configuration includes detection timeframe, lookback, ATR multiplier, per-zone toggles, optional volume filter, max active zones, opacity, and forward extension.

Core design elements include a ZONE_TYPE enum, a MemoryZone struct (range, time, type, strength, mitigation checks), lifecycle hooks for init/deinit, new-bar processing, and zo...

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #Indicator
❀29πŸ”₯4πŸ‘Œ3πŸ‘€3πŸ‘2
Cointegration and correlation can persist long enough to trade, but relationships decay. Most failures are progressive and can be monitored with rolling tools such as RWEC and IS/OOS ADF.

Some breaks are abrupt. A single event can flip hedge ratios and correlations across FX, commodities, and equities. In econometrics this is a structural break: regression parameters change in a way the model does not anticipate.

Example: NVDA/INTC after the Sep 18, 2025 partnership announcement. Correlation moved from about -0.71 to +0.75, invalidating any portfolio assuming a stable beta. RWEC can flag instability ahead of the event, but it cannot confirm permanence.

Chow tests are designed for confirmation when a candidate breakpoint is known. They compare pre-break, post-break, and full-sample regressions; large F-stat and near-zero p-value indicate a regime c...

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀26✍6πŸ‘Œ2⚑1