Watch how to download trading robots for free
Find us on Facebook!
Join our fan page
Interesting script?
So post a link to it -
let others appraise it
You liked the script? Try it in the MetaTrader 5 terminal
Experts

Structural Swing Migration BUY - expert for MetaTrader 5

Duy Van Nguy
Duy Van Nguy
QUANTITATIVE RESEARCHER | ALGORITHMIC TRADING DEVELOPER | XAUUSD SPECIALIST
I specialize in quantitative trading research, systematic strategy discovery, and Expert Advisor development for MetaTrader 5.
Views:
65
Rating:
(1)
Published:
MQL5 Freelance Need a robot or indicator based on this code? Order it on Freelance Go to Freelance

What ideas is the code based on?

The EA compares the two most recent confirmed swing highs and the two most recent confirmed swing lows. A swing high must be strictly higher than every other high in its confirmation window; a swing low must be strictly lower than every other low. Equal highs or equal lows do not qualify.

With the default pivot radius of 5, each pivot requires five completed candles on both sides. The pivot therefore becomes available five bars after its own candle. A signal is considered only when the latest closed candle confirms a new swing high, a new swing low, or both.

Both the high-to-high increase and the low-to-low increase must reach at least 35% of the average True Range over the latest 24 closed candles. This volatility measure is a simple moving average of True Range, rather than Wilder smoothing. The latest swing high and low must each be no more than 16 bars old, while their preceding counterparts must each be no more than 32 bars old.

The signal candle must also be bullish and close at or above 70% of its own high-to-low range, measured upward from its low. The EA calculates these conditions directly from price data converted to the symbol's tick grid.

How can the indications be interpreted?

Entry. At the first available tick of a new M15 bar, the EA checks the previous closed M15 candle. If all conditions agree and execution checks pass, it sends a market BUY request at the current Ask. It does not open SELL positions or create pending orders.

Only one entry opportunity is evaluated per new M15 bar. Attaching the EA does not trigger an immediate entry from an older signal. Any existing position or pending order on the same symbol blocks a new entry, including trades belonging to another EA or opened manually. An exit recorded with this EA's symbol and magic number from the signal candle's opening time through the entry check also blocks re-entry.

Stop Loss. The requested stop is the signal candle's close minus InpStopOffset , rounded to the symbol's tick grid. The default offset is 22.0 in quoted price units. For example, a signal close of 2700.00 produces an SL of 2678.00 before any grid adjustment. This is a price difference of 22.00, not 22 points or pips. The stop is not trailed or widened.

Take Profit. The initial target is calculated from the current Ask and the stop. After entry, the EA attempts to align the target with the actual position opening price using the formula: TP = opening price + InpRewardRisk × (opening price - SL). The default multiplier is 2.0. Broker stop and freeze restrictions can delay or prevent a target modification.

Time exit. With InpHoldingBars set to 8, the EA attempts to close the position after eight completed M15 bars, counting the entry bar. This is normally around two hours when bars are continuous. Closure depends on an available tick, trading permissions, the broker's session and order acceptance. Position management runs on ticks, with attempts to close or adjust protection spaced at least five seconds apart.

Position size and execution. Volume is fixed at the configured lot size. Unsupported volumes are rejected rather than increased automatically. The EA checks trading permissions, broker sessions, margin, filling policies and stop distances before submitting entry requests. It manages BUY positions identified by the current symbol and its magic number. Use a distinct magic number and avoid sharing the symbol with other strategies.

There is no grid, martingale, percentage-based risk sizing, trailing stop, news filter or maximum-spread filter. Fixed lots and a fixed offset from the signal close do not produce a fixed monetary loss per trade: the actual entry-to-stop distance depends on the entry price, spread and execution. Test in Strategy Tester and on a demo account before considering live use.


Strategy Tester results and balance curve for January–November 2026: 73 trades, a profit factor of 1.77, and a maximum equity drawdown of 1.00%. These historical test results do not represent live trading performance or predict future results.

Suitable Symbols and Timeframes

The intended instrument is XAUUSD, with a fixed M15 signal timeframe. The EA uses the current chart symbol, so a broker's gold symbol with a suffix can be selected directly. It has no hardcoded XAUUSD symbol lock, but suitability for other instruments has not been established.

The signal timeframe stays M15 even when the EA is attached to a chart with another timeframe. New entries require a symbol whose chart candles are based on Bid prices; Last-price chart symbols are skipped. Use an XAUUSD M15 chart for a setup that matches the intended use.

Compile the source in MetaEditor, attach the EA to the selected chart, enable algorithmic trading and verify that the lot size meets the broker's volume requirements. For testing, select the broker's gold symbol and M15, and use real ticks where available to examine spread, stop execution and the time exit. Review the Experts and Journal logs for skipped requests. Performance and broker compatibility require separate testing.

Description of #include Files Used

This code does not use external #include files. Signal calculations, order requests and position management are implemented in the single MQ5 file using built-in MQL5 functions. No custom indicators, DLLs or additional data files are referenced.

Description of Main External Variables

The following inputs are exposed in the EA settings. The 24-bar True Range averaging period and the M15 signal timeframe are constants, not adjustable inputs.

Variable Default Description
Signal: M15, closed bars only
InpPivotRadius 5 Number of candles required on each side of a strict swing pivot.
InpMaxPivotAge 16 Maximum age of the latest high and low pivots, measured in M15 bars from the signal candle. Previous pivots may be up to twice this age.
InpMigrationPct 35 Minimum upward movement of both swing highs and swing lows, as a percentage of the 24-bar average True Range.
InpCloseLocationPct 70 Minimum signal-candle close location within its range, as a percentage measured from the low. The candle must also close above its open.
Trade execution
InpLots 0.01 Fixed lot size. Entries are skipped if this volume does not meet the broker's requirements.
InpStopOffset 22.0 Distance below the signal candle's close used to set SL, in quoted price units.
InpRewardRisk 2.0 Target distance divided by the distance from the opening price to SL.
InpHoldingBars 8 Completed M15 bars before the EA attempts a time exit, including the entry bar.
Broker execution
InpMagic 163401112 Nonzero magic number used to identify this EA's trades on the current symbol.
InpDeviationPoints 10 Requested order-price deviation in broker points, where supported by the execution mode.
InpLogSkips true Enables diagnostic messages for selected skip conditions. Some conditions return without a message.
AesHmac: AES-256 encryption with tamper check and password keys for MQL5 AesHmac: AES-256 encryption with tamper check and password keys for MQL5

One include file that encrypts texts and bytes so only a program with the same key can read them. A wrong key or a changed message is refused instead of read as garbage, keys can come from a password, and the code is checked against the official NIST and RFC test vectors.

History Gaps: find missing bars before you backtest History Gaps: find missing bars before you backtest

Checks the chart's history against the symbol's trading sessions and separates real holes from holiday short sessions and days without bars. Marks the holes on the chart, shows coverage and the largest hole, warns when the history stops short of now, and can write a CSV report.

Demetra Symbol Spec Sheet Demetra Symbol Spec Sheet

Puts the contract specification of the chart symbol on one sheet, including the money value of one point and the margin for one lot.

MACD Signals MACD Signals

Indicator edition for new platform.