# LastHourLow.mq5

Original Edge Quant implementation, MIT license. **One EURUSD long-only case**, with an EUR 10,000 research account. The complete package requires **LastHourLow.mq5 plus the supplied sessions.csv**. It uses MetaTrader's standard `Trade/Trade.mqh` and built-in file/hash functions, without custom indicators or binary libraries.

Source read directly: [Quantified Strategies — SPY Sets Low or High in the Last Hour](https://quantifiedstrategies.substack.com/p/spy-sets-low-or-high-in-the-last), July 5, 2024. It explicitly describes next-open entry and an 11:30 same-day exit; its illustration combines long last-hour lows with short last-hour highs. This study transfers **only the long component to EURUSD**, using NYSE core-session boundaries and M5 bid lows. It does not reproduce SPY execution, exchange-traded lows or the combined source curve.

## Install the required calendar

1. Put `LastHourLow.mq5` in your terminal's `MQL5/Experts/` folder and compile it with MetaEditor.
2. Copy **sessions.csv unchanged** into the terminal's **MQL5/Files/** folder. `#property tester_file "sessions.csv"` instructs MT5 to send this required file to its testing agent.
3. Keep the calendar with the EA download/package. The `.mq5` alone is not the complete deliverable.

The calendar has **4,021 XNYS sessions, 2015–2030**, including daylight saving, actual early closes and supplied special closures. Its exact SHA-256 is:

```
3cbbac4e5d20f5f2471fb476521a6106b6a6b3959e808dc380d86e3c4f10558d
```

The EA hashes the raw file bytes at initialization and validates the six-column schema and ordered session epochs. Missing/modified CSV fails initialization. Text-editor newline changes also change the hash, so preserve the distributed bytes. The package includes the calendar generator, manifest and pinned requirements. Future unannounced closures require a reviewed calendar update and matching Python/EA hash; calendar coverage is not extended by guessing. New entries stop outside its coverage, while existing positions retain exit management.

## Frozen rules

- Prior session means the **immediately preceding actual XNYS calendar row**, including holiday gaps. Use every M5 interval fully inside its core `[open, close)` window.
- Require **complete, aligned coverage**: each expected timestamp must exist, with no missing interval. Regular sessions have **78** five-minute bars; early closes have **42**. Incomplete sessions cannot produce an entry.
- Determine the minimum prior-session **bid low** on the frozen five-decimal EURUSD integer grid. On equal minima, keep the **first occurrence**. Its bar-start timestamp must be at/after **actual close minus 60 minutes**, inclusive. A low repeated in the final hour does not qualify if it first occurred earlier.
- Enter long at the next actual XNYS session's **exact 09:30 New York M5 opening interval**. Missing opening quote, unready context, stale conversion or rejected/undersized entry consumes the candidate. No later opening, fresh-FX retry or nearest-quote substitution is allowed.
- Exit at the first available quote at/after **11:30 New York on the entry session's date**. Its UTC deadline is `calendar_open + 7200`; it is not two hours after a delayed fill. Retain delayed/rejected exits across gaps.
- Exit before checking a new opening candidate. One position, no SL/TP or additional historical signal filter.

An early 13:00 close makes the prior session's last hour **12:00–13:00**, not 15:00–16:00. Calendar UTC epochs implement winter/summer entry and exit times directly. Five-minute bar starts identify the minimum's interval; they do not reveal the exact intrabar tick time of the low. This is a disclosed resolution/tie convention. Finer broker quote precision can change minima/ties when converted to the research grid.

## Initial context and operational fills

Start the historical test **flat in 2016**, with 2015 prior-session quote history available. The first 2016 session can use December 31, 2015 as its prior session; no 2015 position is carried or warmup trades replayed.

Python assumes the exact opening M5 quote plus modeled costs. Live observation, computation, network and broker latency can change the actual fill. Operational safeguards are separate from that idealized historical fill: latch the first observed M5 interval and consume its session before history/FX reads; reject a later interval or live attachment after the opening interval began. Exact-boundary-second initialization is allowed. Unready context cannot be revived by a later tick. These safeguards can reduce actual entries; they are not optimized signal filters.

The position comment `LHL:<session_open_utc>:<exit_due_utc>` persists the calendar deadline for restart. Missing/invalid comments, wrong direction or multiple exclusively owned positions cause operational flattening rather than an invented exit time. Late accepted fills visible after the deadline are exited. Market/network failures can still delay execution.

## EUR sizing, data clocks and costs

Use an **EUR-denominated account**, attach to the selected direct EURUSD symbol and select the direct EURUSD conversion symbol, including broker suffixes. Set tester deposit to **EUR 10,000**. Broker contract/minimum/maximum/step/directional limit and free margin are read at runtime; research assumes **100,000 EUR/lot** and **0.01-lot minimum/step**.

```
raw_lots = equity_EUR /
    (contract_EUR * (trade_ask + 0.00001) / conversion_ask
     + 3.50 / conversion_bid)
```

Floor to lot step and never round upward to a minimum. The budget targets approximately **1× current EUR equity notional** after reserving 0.1-pip adverse entry slippage and USD 3.50/lot entry commission. Conversion must be no more than **900 seconds old**, without future quotes; otherwise skip the opening. Exits have no conversion-freshness filter. Use a dedicated account so unrelated exposure does not change the budget.

Python models supplied bid/ask, 0.1-pip adverse slippage per side, USD 3.50/lot/side commission and **5% assumed annual financing**. This EA uses actual broker fills, fees, conversion and swaps; it does not impose the model's slippage or artificial funding charge. `InpDeviationPoints` is an execution tolerance, not guaranteed slippage. Tick/source timestamp granularity and broker costs can produce different results.

`InpServerUTCOffsetMinutes` applies a **fixed** offset to historical M5/order timestamps. Tester UTC is `TimeCurrent() - offset*60`; use **0** with imported UTC data. 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). The CSV handles New York DST, but a fixed quote-history offset does **not** infer a broker's historical server DST. Normalize quote data to UTC or separately audit that offset schedule. Bid-based chart bars are required.

## Persistence, ownership and verification

A terminal marker keyed to account/server/symbol/magic plus matching own order/deal comments prevents duplicate submissions for a session. Fresh tester state is separate from persistent live state. Keep identity and markers intact. Only matching-magic owned tickets are closed. Netting ownership additionally requires available nonempty position deal history containing exclusively matching-magic trades. Foreign/mixed positions and foreign orders are untouched and block entry; temporary ownership-history failure is not treated as verified flat.

Retcodes, orders and deals are checked/logged. Active or unresolved accepted requests block duplicates; partial entries are accepted without top-up. Expired own entry remainders are cancelled before required exits. Known unresolved order history stays latched. Missing exit-order IDs permit logged, cooldown-limited ticket-specific recovery of remaining owned exposure; ambiguous entries are never blindly resubmitted.

**MetaEditor/MT5 are unavailable: LastHourLow.mq5 has not been compiled or backtested in MT5.** Independent static review found no material defect or obvious API blocker. The calendar hash/all session lengths were verified. Independent raw-quote checks matched all **2,766** prior-session completeness, earliest-minimum and last-hour flags; **2,760** were complete. Synthetic checks cover first-tie rejection, inclusive last-hour boundaries and early closes. These are input/signal checks, not MT5 execution results.

Compile with F7 and inspect diagnostics, then test this single case on matching UTC EURUSD history and the bundled CSV. Verify DST/early-close anchors, missing bars/opening quotes, first ties, 11:30 delayed exits, stale FX and restart recovery. M5 OHLC cannot establish full tick execution or intrabar FTMO compliance. Python results are not MT5 results or FTMO certification.
