# FXGapFade.mq5 — source and execution notes

Original Edge Quant implementation, MIT license. Complete single-file EA using only MetaTrader's standard `Trade/Trade.mqh`. Run **EURUSD and GBPUSD separately**, each with an independent **EUR 10,000** initial account. Set `InpTradeSymbol` to the selected broker symbol and use a unique magic number for each case. No other pair case or parameter search is supplied.

Source: [Quantified Strategies — 80% Win Rate and a 4.69 Profit Factor Fading FX Gaps](https://substack.com/@quantifiedstrategies/note/c-313266239). Its public note describes fading a new day's gap of **at least five pips** versus the preceding daily close and exiting one hour later. It does not specify the daily clock. Its reported performance is not transferred to this study.

Our rule is a disclosed **long observed-quote-absence subset**, not a replication of all daily gaps. A 24-hour absence can reflect a holiday, weekend, missing provider data or another interruption; it is not proof of a market closure. No weekday, London/New York clock, holiday classification or additional trend filter is inferred.

## Frozen signal and holding rule

1. Compare two consecutive **actual observed M5 bar opening timestamps**. Require a start-to-start separation of **at least 86,400 seconds**. This does not subtract five minutes from the interval.
2. Gap = current reopened bar's **known bid open** minus the preceding observed bar's **completed bid close**. Require an absolute gap of **at least 0.00050**, five pips for EURUSD/GBPUSD. A price tolerance of `1e−12 * max(1, |current_bid_open|, |previous_bid_close|)` preserves inclusive equality under floating-point arithmetic.
3. Fade the gap: positive gap → short, negative gap → long. Use executable bid/ask sides for the order. The current bar's high, low, close and volume are never used to decide entry.
4. Hold **3,600 seconds from the actual broker fill timestamp**, then close on the first available tick at/after the deadline. A delayed exit remains pending and retries until confirmed flat. There is **no server SL or TP** and no intrabar price exit.
5. Process a due exit before checking a newly observed reopening gap. A confirmed flat state may enter the new gap on that same quote. A failed/unconfirmed exit leaves existing exposure protected from a duplicate position and skips that new gap.

There is **one entry submission per observed gap**. Persist consumption before conversion/sizing/submission. Insufficient size/margin, unavailable or stale conversion, trade permission failure and rejected entry requests skip the whole gap. They do not wait for a later fresh quote or create another attempt. Exit requests retry; entry requests are not blindly repeated.

## Historical fill assumption versus live operation

The Python study assumes entry at the **same first reopening M5 open quote** that reveals the gap, plus adverse modeled slippage. This is an **idealized zero-latency quote-response assumption**, not a guaranteed executable live fill. An EA must observe a tick, read data, calculate size and send an order; network, spread changes and broker processing can move its actual fill away from the opening quote.

The following are operational safeguards, separate from the historical strategy rules:

- Start the EA before the reopening bar. Initialization after that bar's opening timestamp skips its remaining interval; the exact boundary second is permitted. Late attachment does not resurrect an opening-price signal for a later live fill.
- Latch the first observed chart M5 interval **before** requesting history. If its previous/current bar context is unavailable, unsynchronized or mismatched on that observation, skip the entire interval. Later loaded history or fresher FX cannot revive it.
- Signal prices remain the prior completed bid close and known current bid open, while actual entry uses the broker's available executable tick. Even an already running EA can experience latency; exact first-open fills are not claimed.

These safeguards can produce fewer trades than the idealized historical model. They are not optimized threshold/time filters. Keep the EA attached with synchronized history before the expected reopen to assess execution differences on demo.

## EUR account, conversion and sizing

The EA requires an **EUR-denominated account**, a direct EUR/USD or GBP/USD trading symbol with USD profit currency, and a direct EUR/USD conversion symbol. Broker suffixes can be entered. Attach to the selected trading symbol's chart; set tester deposit to EUR 10,000. GBPUSD uses the separate EURUSD conversion feed; the EURUSD case can use the same symbol for trading and conversion.

The conversion tick must be at most **900 seconds old**, with no future-dated quote. A stale/missing entry conversion skips the gap immediately, rather than waiting for fresher data. The Python model measures freshness from its observed source M5 timestamp and uses backward-only available quotes; the EA uses actual broker tick timestamps. Quote availability and timestamp granularity can therefore differ.

Target approximately **1× entry EUR notional**, reserving entry commission/slippage. Read broker contract size, minimum/maximum lot, step, directional volume limit and available margin. Research assumes 100,000 base-currency units per lot and 0.01-lot minimum/step:

```
budget_entry = current_trade_ask + 0.00001   # long
budget_entry = current_trade_bid - 0.00001   # short
raw_lots = equity_EUR /
    (contract_base_units * budget_entry / EURUSD_ask + 3.50 / EURUSD_bid)
```

Floor to lot step; never round upward to satisfy a minimum. Reserve inputs default to **0.00001 adverse price slippage (0.1 pip)** and **USD 3.50 per lot entry commission**. They reserve exposure budget only. They do not deduct artificial fees or force the actual fill price. Other positions change account equity/margin; use a dedicated test account.

The Python study uses actual supplied bid/ask, modeled adverse 0.1-pip slippage and USD 3.50/lot/side commission. Positive USD P&L converts at EURUSD ask; negative P&L/fees/funding at bid. It assumes **5% annual funding** on entry absolute USD notional for actual elapsed time; this is a research cost scenario, not historical broker swaps. This EA uses actual broker execution, conversion, commission and swaps and does **not** charge artificial 5% funding. `InpDeviationPoints` is an execution tolerance in symbol points, not a guaranteed slippage charge.

## Actual-fill timer and restart persistence

Short comments `FG_L:<gap_utc>` / `FG_S:<gap_utc>` persist the direction and observed-gap identity. The timer uses **actual `POSITION_TIME`**, not a pre-order request-time estimate. Once a newly filled position is visible, save its UTC due timestamp in a terminal Global Variable keyed to account/server/symbol/magic and stable position identifier. For a newly observed live fill, the current server/GMT difference translates the actual broker position timestamp. The due marker is then authoritative across restarts.

If the due marker is unavailable after restart, reconstruct from the actual broker fill metadata using `InpServerUTCOffsetMinutes`. Thus the timestamp survives in durable broker position metadata even if the local marker is lost. The fixed offset must match the fill's historical timestamp convention. A position with missing/unparseable ownership comments, impossible metadata or multiple owned positions is flattened rather than inventing state.

A separate terminal marker plus matching own deal/order history prevents a second attempt for the same gap after reattachment. Tester/live keys are separate; fresh tester initialization clears only this EA's tester gap/due state. Live markers persist. Do not delete state or change account/symbol/magic/time settings while comparing a live run; lost state/history removes evidence of rejected unfilled attempts. Keep existing positions' broker metadata and due markers intact.

## UTC history and broker clocks

`InpServerUTCOffsetMinutes` interprets historical M5 and restart fill timestamps with a **fixed server-to-UTC offset**. In tester current UTC is `TimeCurrent() - offset*60`; **0** is appropriate for imported UTC custom symbols. Live current UTC uses the terminal computer's `TimeGMT()`, so keep the computer clock correct. [MetaQuotes documents that TimeGMT equals simulated server time in Strategy Tester](https://www.mql5.com/en/docs/dateandtime/timegmt).

A fixed offset cannot infer historical broker daylight-saving changes. Normalize history to UTC or independently implement/audit the broker's historical timestamp schedule. Saved actual-fill due UTC does not infer the timezone of older missing M5 data. No automatic historical broker-DST parity is claimed. The EA requires bid-based historical chart bars and rejects last-price mode.

## Ownership and order handling

Manage only matching-magic positions. Hedging exits use the exact position ticket. Netting ownership additionally requires available nonempty position deal history containing exclusively matching-magic trades. Foreign/mixed positions are never closed and block entries; foreign symbol orders also block entries. Use unique magic and a dedicated netting symbol/account because another system can change a net position between checks.

Log trade retcodes, order/deal IDs and fills; successful CTrade structure validation is not treated as execution proof. Accepted requests and active orders block duplicates. Partial entry fills are accepted without top-up. Before a required exit, cancel visible own entry remainders and then retry the owned close. Known unresolved order-history state remains latched. An accepted exit with no order ID reconciles a confirmed flat state; otherwise a logged, cooldown-limited ticket-specific close retries remaining owned exposure when no own active order remains. Ambiguous entries with no order ID are not blindly resubmitted and can require operator investigation. Foreign orders are never cancelled.

## Verification status

**MetaEditor/MT5 are unavailable here: FXGapFade.mq5 has not been compiled or backtested in MT5.** Independent static review checked signal inputs, first-observation handling, one-attempt persistence, actual-fill timing, exit-first order, ownership and request recovery. Initialization self-checks cover positive/negative exact five-pip equality and the next smaller quote increments; those MQL checks execute only in MT5. Independent Python arithmetic checks were also performed during preparation.

Compile with F7, inspect all diagnostics, then run the two pair cases independently with 2015 prior-quote context and the 2016–2025 evaluation window. Provide corresponding EURUSD conversion data, correct symbol metadata and actual/imported tick history. Check each gap's prior close/open, start separation, stale FX skip, one-hour due time, delayed exit, lot sizing, restart state and rejected requests. M5 OHLC alone cannot establish full bid/ask tick execution or intrabar FTMO compliance. The research's final-window forced liquidation is a reporting convention; the EA maintains the one-hour rule unless the tester/broker ends the run.

Python historical results are not MT5 tester results or FTMO certification. Official execution references: [CTrade Buy/result checks](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradebuy) and [ticket-specific PositionClose](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradepositionclose).
