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
β€œHeads or Tails” is a high-risk short-term trading approach used in equities and FX. Direction is selected randomly, commonly via a coin flip equivalent, while fundamental factors and objective signals are ignored.

Typical flow includes instrument selection, random buy/sell decision, and forced exit by time, take-profit, or stop-loss. The method is simple to implement but offers no basis for statistical edge and weakens risk control and capital allocation.

In automation, logic often checks that no positions are open (b + s = 0), then calls a pseudo-random generator (0–32767). Parity via modulo 2 selects direction: even opens a long position, odd opens a short position, each followed by an immediate return.

Use is mainly educational for platform mechanics or experimental testing, not for repeatable performance over long horizons.

πŸ‘‰ Read | Quotes | @mql5dev

#MQL4 #MT4 #AlgoTrading
❀36🀣6πŸ‘Œ2πŸ”₯1
Locking is a trade state where long and short positions of equal volume are held on the same instrument. Price movement impact is neutralized because gains on one side are offset by losses on the other, effectively freezing the net result until positions are modified or closed.

The VR Locker Lite approach begins by opening BUY and SELL immediately, then increases exposure on both sides through averaging, expanding the lock structure.

Common lock management paths include closing both legs and restarting the cycle, partially unlocking by holding one leg longer, applying trailing stops to one or both legs, shifting a leg to breakeven while keeping upside exposure, or creating additional locks on other symbols or via separate MagicNumber instances.

Key considerations include doubled commissions and potential swap costs, margin being tied up while the ...

πŸ‘‰ Read | Calendar | @mql5dev

#MQL4 #MT4 #AlgoTrading
❀37πŸŽ‰4
A practical control for MT4/MT5 Expert Advisors is the ability to detect duplicate instances on the same chart and react based on defined conditions. This can prevent double order placement, duplicated timers, and repeated event handling when templates are applied or charts are restored.

Using Expert.mqh from the referenced library, the EA can implement an instance check during initialization by scanning chart context and comparing identifiers such as symbol, timeframe, magic number, input signature, or a custom instance key. If a match is found, the EA can block startup, switch to read-only mode, or disable trading while continuing to monitor state changes.

πŸ‘‰ Read | AlgoBook | @mql5dev

#MQL5 #MT5 #EA
❀22✍4πŸ‘3πŸ”₯2
Locking is the simultaneous holding of a LONG and a SHORT position of equal volume on the same instrument. Price exposure is neutralized because gains on one leg are offset by losses on the other, keeping the net result largely unchanged while both legs remain open.

A typical implementation opens BUY and SELL immediately, then widens each side via averaging. Subsequent handling options include closing both legs and restarting, closing one leg and keeping the other running, applying trailing stops to one or both sides, or moving one leg to breakeven while keeping the other active. Parallel locks can be run on other instruments or isolated via separate MagicNumber values.

Key constraints remain: doubled commissions and potential negative swaps, margin still tied up, and higher decision complexity when selecting which leg to close and timing the exit.

πŸ‘‰ Read | AppStore | @mql5dev

#MQL5 #MT5 #EA
❀22⚑7✍1πŸ‘Œ1
MetaTrader 5 optimization can be made visual by attaching tester handlers to an EA and using frame mode. Agents run passes, OnTester() collects pass metrics and deal-by-deal balance, then FrameAdd() sends a frame to the terminal-side EA where OnTesterPass() renders and stores results.

The UI design uses a separate chart with a five-tab control: live pass chart plus post-run tabs for top-3 by Sharpe, Net Profit, Profit Factor, and Recovery Factor. Each tab pairs balance charts with two tables: pass results and EA inputs, plus a replay control.

Implementation is organized into MQL5 control classes (canvas, panels, labels, buttons, tab control), a refined table control, and three core components: progress bar, special chart renderer, and frame viewer, backed by sortable frame objects for ranking and selection.

πŸ‘‰ Read | Forum | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀26⚑6πŸ‘Œ2πŸ‘€1
Larry Williams’ approach reduces chart interpretation and focuses on short-term price events that can be defined and tested. Patterns are expressed as rules built from OHLC relationships, designed for automation and statistical validation.

A single MQL5 Expert Advisor is structured to run one strategy at a time, hold one position at a time, and apply uniform risk and exit handling. Signals are confirmed via a volatility-based breakout level, with the baseline mode entering directly at the open.

The strategy set includes: buy on open, buy after a down close, buy after three down closes, buy after a measured pullback, buy after a bearish outside bar, and a short setup fading three bullish closes. A day-of-week filter is applied to measure time-based effects.

Stops are configurable (range-based or prior-bar extreme). Exits support profit-on-next-open, fixed h...

πŸ‘‰ Read | Docs | @mql5dev

#MQL5 #MT5 #EA
❀31πŸ‘Œ4⚑1
Part 15 extends an MQL5 canvas dashboard with header blur/shadow rendering and corrected mouse wheel scrolling behavior for text panels.

Blur is used for fog-like gradients via per-pixel opacity blending. Shadows are rendered with multi-pass rounded rectangles, offset and alpha-faded by distance and blur radius. Bicubic interpolation and antialiased primitives are applied for higher quality scaling and lines.

Implementation adds grouped inputs for shadow color, opacity percent, distance, and blur radius. Header drawing is reworked to allocate extra padding, prevent clipping, and keep borders/icons aligned. Hit testing expands to include the shadow area while excluding button regions.

Minimize/maximize and OnInit resize the header canvas using the same extra padding. OnChartEvent removes wheel logic that altered chart scale, so wheel scrolling affect...

πŸ‘‰ Read | Forum | @mql5dev

#MQL5 #MT5 #Indicator
❀26✍6πŸ‘Œ2😈2
A quantified liquidity model is turned into an MT5 tool: consolidation zones (A–B) are measured, then validated only when a breakout impulse (to C) reaches a configurable multiple of the zone depth, with 1:3 as the tested baseline.

The indicator encodes this as deterministic rules in MQL5. It separates logic from presentation via inputs (LookbackBars, RatioMultiplier, colors, projection length), manages its own OHLC/time arrays for consistent indexing, and combines chart rectangles with eight buffers so zones are both visible and EA-consumable.

Lifecycle handling is treated as a first-class concern: strict object naming, cleanup on deinit, buffer clearing by time validity, and forward projection for retest tracking.

Live testing on XAUUSD showed zones mapped cleanly to real consolidations and many breakouts meeting or exceeding the 1:3 threshold, su...

πŸ‘‰ Read | Quotes | @mql5dev

#MQL5 #MT5 #Indicator
❀40πŸ‘7πŸ†4⚑3πŸ‘Œ2
An MT5 indicator example demonstrates sending trade signals through terminal global variables, leaving execution logic to external code. It targets quick testing workflows rather than a complete trading system.

Recommended usage is a 5‑second chart on any liquid instrument. The signal is derived by counting candle colors over the lookback window: the majority color selects the direction, mapped to CALL or PUT. A configurable reverse mode flips the rule so the minority color drives the output.

Signal publication can be verified in the terminal by opening the Global Variables window (F3) and checking the values being written and updated in real time.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #Indicator
❀28πŸ‘2πŸ‘Œ2
A standalone MQL5 include library is available for adding balance/equity mini-charts and extra optimization criteria to existing Expert Advisors. After placing Advanced Optimization Report Saver.mqh into \MQL5\Include\, the file can be included and its exported functions called from standard EA handlers to save frames and custom metrics.

The library adds inputs such as toggling statistics collection and setting the chart width in pixels. Using the Moving Average example EA, the required changes are limited to small additions near the end of the code after existing trade checks.

For large parameter grids, readability and runtime can be improved by replacing linear steps with an enum scale (e.g., 1,2,3,5,7,10,15,20,30,50,70,100). This reduces optimization passes, speeds up processing, and shrinks saved output while making average lines clearer. Update 2026-02...

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #EA
❀26⚑3πŸ‘Œ3πŸ†2
A chart-side service extends the default terminal view of open positions by rendering clearer trade context directly on price charts. It marks entry time and price, and can also annotate related deals such as partial closes or volume adds in netting accounts.

The service polls account state on a configurable interval (default 5 seconds) and draws objects only on the active chart when its symbol matches an existing position. Supported objects include trend lines or vertical lines, optional deal arrows, and profit/loss coloring with configurable style and width.

Chart objects are tracked via global variables to manage cleanup. When KeepLinesOnCharts is disabled, objects are removed on position close. When enabled, objects remain for manual control, while related global variables are still cleared. Tooltips and on-chart text expose key position and deal prope...

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #Indicator
❀27πŸ‘Œ4⚑3
Forex swap carry remains underused in systematic trading, despite being a direct function of rate differentials and broker rollover terms.

Backtests on 2015–2025 data indicate 5–8% annualized return contribution from swaps in optimized portfolios, with slower swap repricing versus FX spot moves supporting longer holding periods.

A swap-aware allocation model can combine expected market return, average swap, and volatility, then apply correlation and covariance constraints to reduce portfolio variance. Sharpe optimization with a positive cumulative swap constraint filters high-return portfolios with negative carry.

Implementation details typically include MT5 data ingestion (swap_long/swap_short, spreads), cost ratios such as swap-to-spread, business-day swap application, and SLSQP optimization for nonlinear constraints.

πŸ‘‰ Read | AlgoBook | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀26πŸ”₯8πŸ‘Œ3πŸŽ‰1
Part 38 finalizes the API workflow by building an MQL5 Expert Advisor that pulls Binance candlestick data and evaluates it inside MetaTrader 5, without relying on MT5’s symbol history or indicators.

The EA requests the last three closed 30-minute candles via WebRequest, then converts the raw byte response into text and extracts OHLC and candle open time by cleaning and splitting Binance’s JSON array structure into ordered fields and arrays.

To respect exchange rate limits and avoid incomplete bars, the EA triggers the API call only when a new 30-minute candle opens, using the current candle’s opening timestamp as a simple state check. This creates a reusable pattern for external-market data analysis and pattern detection (e.g., bullish engulfing) that can be extended to other timeframes and signals.

πŸ‘‰ Read | Signals | @mql5dev

#MQL5 #MT5 #EA
❀37πŸ‘Œ5
The article presents β€œcompression readiness,” a non-repainting MT5 indicator that turns discretionary price-action compression reading into closed-bar rules. It targets the key problem: separating meaningful absorption ranges from low-information sideways drift.

Detection compares a recent window to a prior one, scoring range contraction, candle overlap, boundary tests, and wick rejections. Robustness comes from optional wick-trimmed boxes, close-out invalidation when a bar closes outside the range, and a dead-drift filter to reject ultra-quiet markets.

Compression is graded (none/early/building/mature) via transparent thresholds. Directional bias is estimated without indicators, using CLV and rejection asymmetry, with optional smoothing and state-change visuals for practical chart context.

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #Indicator
❀33πŸ†6πŸ‘Œ3
An MQL5 Expert Advisor can model liquidity zones using a minimal two-candle structure: a β€œbase” candle representing compression and an β€œimpulse” candle representing expansion, with evaluation restricted to closed candles for non-repainting behavior.

Execution logic typically relies on candle high-low range comparisons (not indicators), a configurable impulse-to-base ratio, and directional alignment to bias continuation setups.

Automation details include CTrade-based order handling, spread checks, magic number tagging, and one-bar-one-execution timing. Entries can be split into multiple limit orders across the base candle range, with stop-loss buffered beyond the zone and targets anchored to the impulse extreme.

Testing in MT5 Strategy Tester should first validate mechanical correctness: order placement, fills, stop/target behavior, and pending expiry when ...

πŸ‘‰ Read | VPS | @mql5dev

#MQL5 #MT5 #EA
❀59πŸ‘Œ8πŸ€”1
A standard deviation variant based on price momentum rather than raw price. The calculation is optimized for minimal CPU load while keeping output values broadly comparable to conventional standard deviation.

Like standard deviation, it can be applied to measure deviation for different input series, not only price. This makes it suitable for custom data streams such as indicator buffers or derived signals.

In side-by-side comparison, the upper plot represents the momentum-based deviation, while the lower plot shows the classic standard deviation. Usage guidance remains the same as for standard deviation indicators across volatility filtering, normalization, and regime detection.

πŸ‘‰ Read | Freelance | @mql5dev

#MQL5 #MT5 #Indicator
❀27πŸ‘Œ3
AdaptiveQ Enhanced is an MQL5 Expert Advisor built around DQN reinforcement learning, game theory, and causal analysis for FX trading under uncertainty.

Market state is modeled as 531,441 discrete states across seven major currency pairs, with inter-symbol dependency handled via Nash-equilibrium action selection. Correlations are applied only when |corr| > 0.3 to reduce noise.

The action space expands to six actions: buy, sell, add-to-buy, add-to-sell, close-profitable-buys, close-profitable-sells. Inputs include multi-timeframe signals (M15/H1/H4), MA deltas/flags, RSI, Stochastic, and momentum, mapped into a single state index.

Implementation focuses on performance: cached prices, correlations, indicator values, persistent indicator handles, and periodic refresh. Learning adds an opportunity-cost term plus cross-learning between correlated pair...

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀24πŸ‘Œ3
This workshop rebuilds the Supertrend indicator in MQL5 with a focus on correctness and live-trading safety. It targets a common pain point: many retail Supertrend versions repaint, flip inconsistently, or hide the logic, making them unreliable for EAs.

Supertrend is treated as a volatility-driven state machine: ATR defines dynamic trailing bands, and a single bullish/bearish state is determined by closes relative to the band. The implementation leverages MT5’s built-in iATR via an indicator handle, then layers clear trend logic and plotting on top.

The design emphasizes practical usability: one line that flips sides, consistent candle recoloring for fast trend recognition, user inputs for ATR period/multiplier, documented buffers for automation, and proper handle lifecycle management to keep the indicator stable and extensible.

πŸ‘‰ Read | NeuroBook | @mql5dev

#MQL5 #MT5 #Indicator
❀46✍4πŸ‘Œ4🀣2πŸ†2πŸ‘€2⚑1
MQL5 Community OAuth can be configured from the Apps section and used as an identity provider for external software, including Android clients. OAuth 2.0 is implemented with standard authorization-code flow and endpoints for login, token exchange, and user_info.

Compared with generic social auth, the returned profile can include trading-focused signals such as rank, reputation, products, and forum activity. This is useful for apps that need domain-specific user context and basic trust signals.

Mobile clients should only initiate authorization and receive the code via a redirect URI or deep link. Token exchange requires a server component because the client secret must not ship in the APK. Some free PHP hosts block outbound POST, which breaks token exchange even when redirects work.

πŸ‘‰ Read | Calendar | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀70πŸ‘4⚑3πŸ‘Œ3✍1πŸ‘€1
An indicator is available to chart the spread between two instruments as either a difference or a ratio.

Configuration includes Instrument1 and Instrument2, which must match the broker’s symbol strings exactly. Multiplier1 and Multiplier2 apply scaling factors to each instrument to normalize contract sizes or pricing units.

The ChartDifernce boolean selects the output mode. When enabled, the indicator plots the difference between the two instruments. When disabled, it plots the ratio.

The spread series is rendered in a separate subwindow. Once plotted, standard technical indicators can be applied to the spread line for additional analysis.

πŸ‘‰ Read | Forum | @mql5dev

#MQL4 #MT4 #Indicator
❀37✍3πŸ‘Œ3⚑1πŸ‘€1
MetaTrader 5 indicators rely on event-driven flow: timeframe changes trigger OnDeinit, then OnInit after the chart rebuild. During this cycle, indicator memory is cleared, so runtime counters reset unless state is stored externally.

One approach is to handle OnDeinit(reason) and preserve the counter only when reason equals REASON_CHARTCHANGE; otherwise reset to zero. This keeps logic local, but file-based persistence can introduce race conditions when multiple charts or rapid period changes contend for the same state.

An alternative is terminal global variables. They persist across reinitializations while the terminal is running, store only double, and can be adapted via unions for packed data. GlobalVariableTemp enables session-scoped state without filesystem dependency, but shifts control to terminal-level storage semantics.

πŸ‘‰ Read | CodeBase | @mql5dev

#MQL5 #MT5 #AlgoTrading
❀25πŸ”₯8πŸ‘Œ2πŸ’―2