# GoldTurnaroundTuesday.mq5

Original Edge Quant implementation, MIT license. **One XAUUSD long-only case**, with an EUR 10,000 research account. Complete source uses only the standard MetaTrader `Trade/Trade.mqh`; no custom indicator or generated include is required.

Source, read directly: [Quantified Strategies — 15 SPY Trading Strategies With Backtested Rules and Equity Curves](https://quantifiedstrategies.substack.com/p/spy-trading-strategies-backtests). Its freely visible introductory example describes buying Monday's close after a decline of at least 1% versus Friday and selling Tuesday's close. The numbered paid rules were not accessed or reconstructed. This EA transfers that public **SPY example to gold**, using UTC daily bid closes and next-quote execution. It is not an equity replication and does not inherit the article's SPY results.

## Exact rules

- Manually aggregate actual observed M5 **bid closes** by completed UTC Monday–Friday dates. Do not use broker D1 bars, Sunday signals or invented dates. The study uses data from January 1, 2016 onward; no 2015 warmup or position carry is required.
- For each completed Monday, require an observed close on the **literal Friday date, Monday minus three calendar days**. If Friday or Monday is missing, that week has no eligible signal. Never substitute Thursday or another previous observed day.
- Enter when `MondayClose <= 0.99*FridayClose + epsilon`, with `epsilon = 1e−12*max(1, |MondayClose|, |FridayClose|)`. This implements an **inclusive 1% decline** without losing exact equality to binary rounding.
- Entry is the first available quote at/after **Tuesday 00:00 UTC**, only if that quote occurs **strictly before Wednesday 00:00 UTC**. If the first available entry is Wednesday or later, skip the entire week. Stale conversion, failed size/margin checks or a rejected submission also consume the week; do not wait for a later fresh quote or retry entry.
- Exit at the first available quote at/after **Wednesday 00:00 UTC**. This is a **calendar deadline, not 24 hours after fill**. A delayed Tuesday fill has a shorter planned hold. Keep a delayed/rejected exit pending until closed. Process exits before a new week's entry.
- One position, no server SL/TP, price target, trend filter or additional historical rule.

## Historical fills and operational safeguards

The Python study uses the first observed M5 opening quote after the boundary plus modeled costs. Actual terminal/network/broker latency can change the live fill; first-open execution is not guaranteed.

The EA latches the first observed M5 interval before requesting history. Entry requires that interval to be the first observed quote after Tuesday midnight. If context is unready and becomes available only later, the old opening interval cannot be revived. Live initialization after that interval began skips the entry; the exact boundary second is allowed. These are **operational safeguards separate from the historical rules**, and can reduce the trade count relative to an ideal next-quote backtest. Fresh tester state starts flat and clears only this EA's separate tester consumption marker.

A comment `GTT:<MondayUTC>:<WednesdayDueUTC>` persists the calendar deadline. Restarts reconstruct Wednesday directly from the validated comment; they never substitute fill time plus 24 hours. Missing/invalid comments, wrong direction or multiple exclusively owned positions trigger an operational flattening instead of an invented deadline. Expired visible entry orders/remainders are cancelled; a late accepted fill visible after Wednesday is then closed.

## EUR sizing and broker differences

Attach to the selected USD-quoted gold symbol; its broker metadata must identify base XAU and profit currency USD. Select a direct EURUSD conversion symbol, including broker suffixes. An **EUR-denominated account** is required; set tester deposit to EUR 10,000.

Read actual contract/minimum/maximum/step/directional limit and available margin from the broker. Research assumes **100 oz per lot**, 0.01-lot minimum/step and approximately **1× current EUR equity notional**. The budget is:

```
raw_lots = equity_EUR /
    (contract_oz * (gold_ask + 0.10) / EURUSD_ask + 3.50 / EURUSD_bid)
```

Round down to the lot step; never round up to meet a minimum. Entry conversion must be no more than **900 seconds old** and not future-dated, otherwise skip the week. Defaults reserve USD 0.10/oz adverse slippage and USD 3.50/lot entry commission. These are sizing reserves, not artificial cash charges or guaranteed fill prices.

Python models supplied bid/ask, USD 0.10/oz adverse slippage per side, USD 3.50/lot/side commission and **5% assumed annual funding** for elapsed holding time. The EA uses actual broker fills, commission, conversion and swaps; it does not charge artificial 5% funding. `InpDeviationPoints` is an execution tolerance in symbol points. Tick availability, conversion age granularity, broker specifications and costs can produce different outcomes. Use a dedicated account so unrelated positions do not change the sizing budget.

## UTC and persistence

`InpServerUTCOffsetMinutes` applies a **fixed** server-to-UTC offset to historical M5/order timestamps. Tester UTC is `TimeCurrent() - offset*60`; use **0** for imported UTC custom symbols. Live current UTC uses the computer's `TimeGMT()`. [MetaQuotes documents that tester TimeGMT equals simulated server time](https://www.mql5.com/en/docs/dateandtime/timegmt). A fixed offset cannot infer a broker's historical DST schedule: normalize data to UTC or separately audit that schedule. Bid-based chart bars are required.

A terminal marker keyed to account/server/symbol/magic plus own order/deal comments prevents duplicate weekly submissions after restart. Neutral, missing-Friday and skipped weeks remain consumed. Keep identity and saved state intact. Foreign/mixed positions are never closed and block entry. Netting ownership requires nonempty available position history containing exclusively matching-magic trades; hedging closes use exact tickets. A temporarily unverified position is not treated as a confirmed flat state.

Trade retcodes, orders and deals are checked/logged. Active or unresolved accepted requests block duplicates; partial entries are accepted without top-up. Known unresolved order history remains latched. Missing exit-order IDs reconcile verified flat state or permit logged, cooldown-limited ticket-specific recovery of remaining owned exposure. Ambiguous entries are never blindly resubmitted. Broker/network failures can still delay fills and require investigation.

## Verification

**MT5/MetaEditor are unavailable: this source has not been compiled or backtested in MT5.** Independent static review found no material defect or obvious API blocker. Arithmetic checks covered inclusive equality, literal Friday dates, Tuesday/Wednesday boundaries and entry-at-Wednesday rejection. All available Friday/Monday pairs among the supplied **522 Mondays** matched exact integer-tick arithmetic; 14 lacked the literal Friday and 49 met the decline condition. These are signal checks, not MT5 trade results.

Compile with F7 and inspect diagnostics, then test the one case on 2016–2025 UTC history with matching XAUUSD/EURUSD data and broker configuration. Verify missing-Friday weeks, first Tuesday quotes, Wednesday calendar exits, stale FX, lot rounding and restart recovery. M5 OHLC cannot establish full tick execution or FTMO compliance. Python results are not MT5 results or FTMO certification.
