Join our fan page
- Views:
- 324
- Rating:
- Published:
-
Need a robot or indicator based on this code? Order it on Freelance Go to Freelance
Overview
Gold Fractal Breakout EA is a MetaTrader 5 Expert Advisor that searches for confirmed swing highs and lows, then attempts to place Buy Stop and Sell Stop orders near those levels. Its structure detection uses configurable neighboring bars rather than the built-in iFractals indicator. Orders and positions are identified by the current symbol and the configured magic number.
The strategy combines price structure, pending entries and percentage-based exit management. It does not draw entry arrows, fractal markers or trading panels on the chart. The illustration below explains the order placement concept; it is synthetic and does not represent historical trades, a terminal screenshot or measured performance.

Conceptual buy setup. Illustrative prices; no historical performance data.
Symbol and timeframe
The product name suggests gold, so a broker-specific gold symbol such as XAUUSD is the intended starting point for evaluation. However, the source trades the symbol of the chart to which it is attached and contains no gold-only restriction. No supplied backtest or forward-test evidence establishes an optimal symbol, timeframe or profitable parameter set.
The structure timeframe is fixed to H1 by the internal constant InpFractalTF. It is not an editable input. Even when the chart or Strategy Tester period is D1, CopyRates reads H1 bars. Scans run on the first available tick after the configured interval, which defaults to 15 minutes; position management runs on every tick. H1 therefore describes the default signal data, not a verified best trading timeframe.
How entry conditions are interpreted
IsSwingHigh requires the candidate high to be strictly higher than all selected older and newer neighboring highs; IsSwingLow requires the corresponding strictly lower low. With the default settings, five bars are checked on each side. FindSwing starts beyond the newest five closed bars, excluding the current bar from the confirmation window, and returns the most recent qualifying level. If the required history is unavailable, no level is returned.
For a buy setup, Ask must be below the swing high by more than the configured minimum clearance. For a sell setup, Bid must be above the swing low by more than that clearance. The EA then applies its entry offset, checks for an existing same-direction pending order within the duplicate distance, and verifies that the pending entry is beyond the broker minimum stop distance from the current quote.
Buy entry = swing high + swing high × buy offset / 100. Sell entry = swing low − swing low × sell offset / 100. Both default offsets are −0.10%, so the buy entry is below the high and the sell entry is above the low. These defaults anticipate the swing boundary rather than require a completed break beyond it. The order is still submitted only if its price is valid for a stop order relative to the current market.
Sizing and position management
Fixed-lot mode returns InpFixedLots directly. Risk-percent mode estimates order volume from current account equity, the configured risk percentage, entry-to-stop distance, and the symbol tick size and tick value cached at initialization. It clamps volume to the symbol minimum and maximum, rounds down to the volume step, and normalizes to two decimal places. Invalid distance or cached tick properties cause a fallback to fixed lots.
Initial stop loss and take profit are calculated as percentages of the pending entry price. On each tick, favorable movement is measured from the position opening price using Bid for buys and Ask for sells. At the break-even trigger, the stop is moved toward a small price-based profit lock. Trailing updates apply only while favorable movement is between the trailing trigger and the maximum trailing percentage.
At the salvage loss threshold, the EA moves take profit to a smaller loss relative to the opening price. This seeks an exit if price subsequently recovers toward that target; it does not close the position immediately or guarantee recovery. For example, the default buy salvage target is 0.15% below entry after an adverse move of at least 1.00%. The updated target is not automatically restored to the original take profit when the loss condition ends.
Input parameters
All 25 configurable inputs are listed below with their source defaults. Except for InpRiskPercent, percentage settings describe price distances or price movement, not account returns. InpDuplicatePoints uses symbol points rather than a universal pip size. The trailing distance is based on the current quote; the other exit percentages described here are based on the entry or opening price.
| Parameter | Default | Meaning and interpretation |
|---|---|---|
| InpMagic | 900009 | Identifier used together with the chart symbol to select this EA orders and positions. |
| InpComment | "GoldX9 strategy 9" | Text attached to submitted orders; ownership filtering uses symbol and magic number. |
| InpLotMode | LOT_FIXED | LOT_FIXED uses fixed volume; LOT_RISK_PERCENT uses equity-risk sizing. |
| InpFixedLots | 0.01 | Direct fixed-mode volume; also the fallback for invalid risk-sizing properties. |
| InpRiskPercent | 0.50 | Estimated equity risk per order; not a guaranteed realized loss limit. |
| InpMaxPending | 3 | Same-symbol and magic-number pending orders, counted separately for each direction. |
| InpMaxPositions | 10 | Stops new scans at this count; existing pending orders can still fill. |
| InpPendingExpiryHours | 15 | Timestamp calculated from this value; submissions still use GTC, so timed expiry is not implemented. |
| InpDuplicatePoints | 100 | A same-type pending entry at or within this distance prevents submission. |
| InpRescanMinutes | 15 | Minimum time between entry scans; scans require an arriving tick. |
| InpFractalLeft | 5 | Number of older neighboring bars in the strict swing comparison. |
| InpFractalRight | 5 | Number of newer closed neighboring bars required to confirm a swing. |
| InpMaxSearchBars | 200 | Maximum candidate series index examined; extra bars are loaded for comparisons. |
| InpMinFractalClearancePct | 0.02 | Ask clearance below a high or Bid clearance above a low, as a percentage of the swing. |
| InpBuyEntryOffsetPct | -0.10 | Added to the swing high; a negative default places entry below the high. |
| InpSellEntryOffsetPct | -0.10 | Subtracted from the swing low; a negative default places entry above the low. |
| InpStopLossPct | 2.00 | Initial stop distance from pending entry price. |
| InpTakeProfitPct | 1.00 | Initial target distance from pending entry price. |
| InpTrailTriggerPct | 0.20 | Minimum favorable move from opening price for trailing updates. |
| InpTrailDistancePct | 0.20 | Stop distance calculated as a percentage of current Bid or Ask. |
| InpMaxTrailPct | 1.00 | Upper favorable-move threshold for trailing updates; not a cap on profit. |
| InpSalvageTriggerPct | 1.00 | Adverse move from opening price that activates the salvage target. |
| InpSalvageExitPct | 0.15 | Loss-side target distance from opening price; does not close immediately. |
| InpBreakEvenTriggerPct | 0.10 | Favorable move from opening price that activates the profit lock. |
| InpBreakEvenLockPct | 0.025 | Price profit locked relative to opening price, before costs. |
Code organization and dependencies
The only include is <Trade/Trade.mqh>, the MetaTrader 5 Standard Library trading interface. Its CTrade object, trade, submits pending orders, assigns the expert magic number, requests position modifications and supplies trade-result descriptions. It is not used for swing detection or lot-size calculation. No custom indicator, external DLL, web service or additional custom include is referenced.
OnInit caches symbol point size, digits, tick size and tick value and checks four positive-count inputs. OnTick manages positions, checks the current position count and throttles entry scans. Pct and N handle percentage distances and decimal normalization; OurOrder and OurPosition filter ownership; CountPositions and CountPending enforce scan-time limits; FindSwing and the swing helpers identify structure; SimilarPending, LotsForRisk, PlaceBreakout and ManagePositions implement duplicate checks, sizing, submission and exits.
The internal global variables are trade (the trading interface), g_last_scan (the last scan time), g_point (symbol point size), g_digits (price decimal places), g_tick_size (tick-size increment) and g_tick_value (reported tick value). InpFractalTF is an internal constant fixed to PERIOD_H1. These internal variables and the timeframe constant are not user inputs. The EA uses built-in terminal APIs for prices, history, account equity, orders and positions.
Implementation boundaries to understand before testing
InpPendingExpiryHours is used to calculate an expiry timestamp, but the order calls explicitly use ORDER_TIME_GTC. The present code therefore does not implement the advertised hour-based expiration mode, and there is no OrderDelete cleanup routine. Existing pending orders are also not canceled when the open-position limit is reached or when a new swing is found.
InpMaxPositions blocks new scans when the current count reaches its threshold; it is not a hard cap on later fills of pending orders. Risk percentage is per proposed order rather than an aggregate portfolio limit. Broker minimum-volume requirements, the fixed-volume fallback, execution prices and trading costs can make actual exposure differ from the estimate. The source contains no spread, trading-session or total-risk filter.
Prices are normalized to decimal digits rather than explicitly aligned to the symbol tick-size grid. Fixed-lot volume bypasses the symbol volume clamp, and risk-mode volume is normalized to two decimal places. Exit modification requests have no explicit stop-distance or freeze-level validation and their results are not checked. A true return from a CTrade submission alone is insufficient evidence that the server accepted the trade; the code logs a failure description only when the submission call returns false.
The source checks only fractal neighbor counts and the pending and position limits at initialization. Several other ranges remain unchecked. Independent opposing positions are easiest to interpret on a hedging account; on a netting account, orders on the same symbol affect a shared position. Compilation, broker-specific order behavior and real-tick demo testing remain unverified in this documentation task. No performance results are claimed.
Opening Range Breakout with NR4 / NR7 Contraction Filters
An opening range breakout Expert Advisor that places stop orders a set distance from the session open, with optional NR4, NR7, inside-day and 3-bar narrow-range filters and a no-filter control mode for testing.
APEX VELOCITY
ApexVelocity is a professional-grade Expert Advisor designed to capture explosive momentum in high-volatility instruments like XAUUSD (Gold). Moving away from rigid, hard-coded parameters, v1.0 introduces a robust, fully dynamic architecture that adapts to market conditions and broker specifications in real-time.
CLiveTradeInfo - CHistoryTradeInfo
The library reconstructs a complete MQL4-style order model on top of the native MQL5 Position, Order, Deal, and History APIs. This design allows legacy MQL4 Expert Advisors to operate with minimal code changes while preserving MQL5.
GDS Renko Trade Manager — MetaTrader 5
A manual-trade manager for MetaTrader 5: completed Renko bricks, configurable break-even and trailing Stop Loss, plus an on-chart Renko dashboard. No automatic entries.