# GoldSessionEffect.mq5 — execution notes

Original Edge Quant implementation, MIT license. Required files: **GoldSessionEffect.mq5 and XNYS_Sessions.mqh in the same folder**. The EA uses MetaTrader's standard `Trade/Trade.mqh`. The calendar is a supplied source dependency; the `.mq5` alone is not the complete package.

The source idea is [Quantified Strategies, A Quantitative Look at the Gold Overnight Strategy](https://quantifiedstrategies.substack.com/p/a-quantitative-look-at-the-gold-overnight). Its GLD ETF observation is adapted to a USD-quoted gold CFD. XAUUSD quotes, spreads, financing and trading sessions differ from GLD. This adaptation is not a reproduction of the article's ETF returns.

## Exactly two cases

- `OVERNIGHT=0`: buy at the actual XNYS regular-session close, then close at the next XNYS session's 09:30 New York open. Friday/holiday positions remain held until the next session. Early closes use their actual 13:00 New York boundary.
- `INTRADAY=1`: buy at the actual 09:30 New York session open, then close at that session's regular/early close.

Both cases use the same supplied XNYS UTC open/close table. It accounts for U.S. daylight saving, exchange holidays, early closes and the 2018-12-05/2025-01-09 special closures. NYSE Arca GLD core hours align with these boundaries for the evaluated 2016–2025 sessions. [NYSE trading information](https://www.nyse.com/trade/trading-information) and [official holiday/early-close announcement](https://ir.theice.com/press/news-details/2024/NYSE-Group-Announces-2025-2026-and-2027-Holiday-and-Early-Closings-Calendar/default.aspx).

The EA submits a market entry on the first gold tick at or after the planned entry, with a **15-minute maximum entry delay, inclusive**. Failed entries may retry every five seconds during that window. An entry missed beyond 15 minutes is skipped. An exit is submitted on the first gold tick at or after its planned time and retried until confirmed closed; missing the planned exit tick does not skip the exit. There are no future pending orders.

Start the tester/EA **before** an intended entry boundary. Initialization at the exact entry second is accepted; initialization after the boundary skips that window, even if less than 15 minutes late. This prevents a restart/late attach from opening mid-hold. Terminal clocks have one-second calendar resolution. A restart continues managing matching existing positions, using their short encoded window-start comments. If a broker alters a position comment so its calendar window cannot be recovered, the EA closes that exclusively owned position instead of guessing an exit.

## Calendar parity and coverage

`XNYS_Sessions.mqh` is generated from the exact supplied `sessions.csv`, using `exchange_calendars` **4.13.3**, XNYS. The CSV has **4,021 sessions**, January 2, 2015 through December 31, 2030. Its SHA-256 is:

```
3cbbac4e5d20f5f2471fb476521a6106b6a6b3959e808dc380d86e3c4f10558d
```

The same hash is embedded in the include and expected by the EA. Calendar monotonicity is checked at initialization. This is a package identity check, not runtime cryptographic rehashing of the arrays. The Python engine uses the matching CSV. Future unannounced special closures are unknown. Regeneration has two steps: first run the supplied `generate_calendar.py` to rebuild `sessions.csv`; then run `python generate_mql_calendar.py` to deterministically rebuild `XNYS_Sessions.mqh`. The second script embeds the new CSV hash but never edits the EA. Review the changed schedule and explicitly replace `EXPECTED_CALENDAR_SHA256` in `GoldSessionEffect.mq5` with the newly printed hash before extending/reusing future schedules. If the calendar library version changes, update its include provenance comment in the generator as well. Outside table coverage no new entries are allowed. Existing owned positions retain exit management. The last table session has no overnight successor, so it cannot start a new overnight hold.

## EUR account and sizing

Use an **EUR-denominated account**, attach to the selected USD-quoted gold symbol, and select the broker's direct EURUSD conversion symbol (suffixes can be entered). Position size is `equity_EUR / ((gold_ask + budget_slippage_USD_per_oz) * contract_size / EURUSD_ask + entry_commission_USD_per_lot / EURUSD_bid)`, rounded **down** to the broker's lot step, then bounded by minimum/maximum/directional volume limits and available margin. Defaults reserve USD 0.10/oz adverse entry slippage and USD 3.50/lot entry commission, matching the Python sizing budget when contract specifications and quotes match. These inputs reserve exposure budget only; they do not deduct artificial cash fees or change the broker's execution price. A below-minimum position is skipped, never rounded up. The EURUSD quote must be at most 900 seconds old. The account should be dedicated to this test; other account exposure changes equity and margin. If conversion quotes are initially stale/unavailable, the EA retries inside the entry grace window. The Python engine instead skips that window if the first eligible gold quote has stale conversion data. Its completed 2016–2025 runs recorded zero such skips, so this handling difference did not change the reported sample.

The notional target is approximately 1× equity. It is **not** 1% planned risk and has **no SL or TP**. Gaps and financing losses are not bounded by a stop. The EA implements no FTMO challenge guard rails or pass guarantee.

Run each case separately with a unique magic. Matching-magic hedging positions are managed by ticket. A netting position is modified only if its available deal history contains exclusively matching-magic trades; unavailable/empty or mixed history fails closed. Foreign positions are never closed and block new symbol entries. Foreign symbol orders also block new entries. A dedicated netting symbol/account is required because outside systems can modify a net position between checks.

Successful CTrade structure validation is not treated as proof of execution: retcodes, deal/order IDs and fills are logged. Accepted active orders block another entry; an in-memory accepted-request latch waits for terminal order history to resolve uncertain requests. Before each entry, recent matching-magic deal history prevents a second entry in the same window after restart; history selection failure blocks entry. Partial entry fills are accepted without top-up. Partial/rejected exits retry. Expired own entry orders are cancelled when visible; foreign orders are untouched. An accepted market request can fill late despite a cancellation attempt or network interruption, so broker execution can deviate from planned windows; once its position is visible, exit management still uses the original planned exit. Market-order latency is not a guaranteed fill-time control.

## Research cost model versus MT5

The Python study assumes adverse gold slippage of **USD 0.10/oz per side**, **USD 3.50 per lot per side** commission, and **5% annual funding** on entry USD notional for elapsed holding time. It reserves entry commission when sizing. It converts positive USD P&L at EURUSD ask and negative liabilities at bid, with explicit stale-conversion handling. Refer to the Python configuration for the authoritative research assumptions.

This EA uses actual broker quotes, execution, commission, currency conversion and swap. It does not deduct artificial 5% funding or a fixed USD 0.10 slippage charge. The EA's default sizing reserves the research entry commission and slippage budgets; broker contract/quote differences can still change lot counts near a rounding threshold. `InpDeviationPoints=20` is a broker execution tolerance in gold points, not a guaranteed slippage cost. Exact P&L parity requires identical quotes, conversion, costs, sessions, fills and lot constraints. The Python results are not MT5 tester results.

## Tester UTC setup and verification status

In live operation, `TimeGMT()` uses the terminal computer clock; keep it correct. [MetaQuotes documents that TimeGMT equals simulated server time in Strategy Tester](https://www.mql5.com/en/docs/dateandtime/timegmt). In tester this EA therefore uses `TimeCurrent() - InpTesterServerUTCOffsetMinutes*60`. Use **0** with imported UTC custom-symbol data. A fixed offset does **not** infer a broker's historical summer/winter server offsets. Normalize data timestamps to UTC, or independently implement/audit the broker's historical offset schedule before comparing event fills. No automatic broker-DST parity is claimed.

Put both source files in `MQL5/Experts/EdgeQuant/`, open the `.mq5` in MetaEditor and compile with F7. Configure EUR 10,000 initial deposit, actual/imported gold contract size (research: 100 oz/lot), minimum and step (research: 0.01 lot), matching conversion data, sessions, spreads, fees and swaps. Run each case separately from January 1, 2016 through the end of 2025 with enough ending data to settle the final selected position. Review planned/actual boundary fills, early closes, holiday/weekend gaps, rejected orders, lot sizing and financing. Prefer real ticks for execution validation.

**Source reviewed only. MetaEditor/MT5 are unavailable here, so the EA has not been compiled or backtested in MT5.** The provided calendar arrays were independently checked against the CSV values and hash. Official CTrade result-handling references: [Buy](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradebuy), [ticket-specific PositionClose](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradepositionclose).
