# ThreeDownCloses.mq5

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

Source read directly: [Quantified Strategies — 65 SPY Trading Strategies, section 34](https://quantifiedstrategies.substack.com/p/spy-trading-strategies). Its public profile describes three down closes followed by a one-session hold in SPY. This EA transfers that idea to **EURUSD observed UTC weekday bid closes and next-quote execution**. It does not reproduce SPY's exchange sessions, close fills, dividends or published results; paid settings are not reconstructed. The cited guide was published after the 2016–2025 evaluation, so retrospective splits are not prospective out-of-sample evidence.

## Frozen rules and event order

- Manually aggregate actual observed M5 **bid closes** into UTC Monday–Friday dates. Exclude Sunday/Saturday daily signals. Do not invent holidays/missing dates or use broker D1 bars. The four-bar sequence uses successive **observations**, not four consecutive calendar dates.
- Let `C0…C3` run from oldest to newest among four completed observed weekday closes. Enter long if `C0 > C1 > C2 > C3`, with each adjacent decline required to exceed `1e−12 * max(1, |previous|, |next|)`. Equality breaks the streak. The tolerance only protects numerical strictness and is far below a quote tick.
- A day becomes actionable at the following **00:00 UTC**. Enter at the first available quote thereafter. A Friday signal can fill at Sunday's reopen. Current incomplete-day prices never determine the pattern.
- Store the **entry signal day**, not the fill date, in `TDC:<day_utc>`. Exit at the first available quote after the **next observed weekday after that signal day completes**. Discover that event as completed data arrives; do not select a future calendar date or hold for a fixed 24 hours.
- **Exit first**, then evaluate the current four-close pattern. If flat and it qualifies, re-enter at that same quote, paying new trading costs. A new position's signal date equals the current event, so it is not immediately exited by that same event.
- One position, no SL/TP, price target, additional signal filter or calendar/time fallback. Missing weekday data delay the next observed-session event rather than being padded.

Example: a Friday entry signal can enter Sunday and exit after Monday completes, at the first Tuesday quote. If Monday has no observations, it waits for the next actual weekday to complete. Conversely, a Thursday signal enters Friday and can exit Sunday after the observed Friday completes. “One session” is therefore not always 24 wall-clock hours.

## Initial context, execution and skips

Provide **2015 context** before testing 2016–2025. Fresh tester initialization starts flat and retains only the latest completed prior weekday event, with its four-observation context; it does not replay 2015 trades or carry a position. The supplied December 31, 2015 context is **not** a three-down pattern, so it leaves the initial January 3 reopen flat. A neutral/unready initial event is consumed without searching backward for a different trigger.

Every later observed weekday event is processed once, chronologically. Multiple events mapped to one quote preserve their order, including exits/re-entries. Exits do not require a ready four-close entry window. Failed/stale-FX/below-minimum entry events are consumed and never wait for fresher quotes; a later daily event can provide another signal. Exit intent remains pending across rejected requests and gaps.

The Python model assumes the first observed M5 opening quote after availability plus modeled costs. Actual terminal/network/broker latency can change live fills. Operational entry safeguards are separate from the historical rule: latch the first observed M5 interval before requesting history, verify it is the first actual interval after availability, and in live mode reject attachment after that interval began. Exact-boundary initialization is permitted. Later loaded context cannot revive an old entry interval. These safeguards can reduce entries relative to idealized historical fills; pending exits remain active. Offline operation cannot recreate historical fills.

The EA requests 120 calendar days before its checkpoint for recent context. All four-close windows in the supplied history fit inside that context; insufficient/unready history blocks entry instead of inventing prices. New completed events after a saved checkpoint are still processed in order.

## EUR sizing, clocks and broker costs

Use an **EUR-denominated account**, attach to the selected direct EURUSD symbol, and select its 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**.

The entry budget targets approximately 1× current EUR equity notional:

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

Floor to lot step, never round upward to a minimum. Conversion must be no more than **900 seconds old**, without future quotes; otherwise skip that daily entry. Exits have no conversion-freshness filter. Budget inputs reserve 0.00001 adverse slippage (0.1 pip) and USD 3.50/lot entry commission, without imposing a fill or deducting artificial fees.

Python models supplied bid/ask, 0.1-pip adverse slippage per side, USD 3.50/lot/side commission and **5% assumed annual funding** for elapsed time. Positive USD P&L converts at ask; losses/fees/funding at bid. The EA uses actual broker execution, conversion, commission and swaps, not artificial 5% financing. `InpDeviationPoints` is an execution tolerance, not guaranteed slippage. Quote timing, broker specifications and costs can change outcomes. Use a dedicated account so unrelated exposure does not alter the budget.

`InpServerUTCOffsetMinutes` is a **fixed** offset for historical M5/order timestamps. Tester UTC is `TimeCurrent() - offset*60`; use **0** with imported UTC data. Live 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 historical broker DST: normalize data or separately audit that schedule. Bid-based chart bars are required; no automatic historical timezone parity is claimed.

## Persistence, ownership and verification

Terminal markers keyed to account/server/symbol/magic store consumed events and pending exits. Persist exit intent before advancing checkpoints; later neutral events cannot checkpoint past an unpersisted exit. A saved processed observed day later than the position's entry signal also reconstructs a missed exit on restart. Active own entry orders' signal dates are recovered before a position appears, allowing stale accepted entries to be cancelled at the later observed event.

Only matching-magic owned tickets are closed. Netting ownership additionally requires nonempty available position deal history containing exclusively matching-magic trades. Foreign/mixed exposure is never closed and blocks entry. Known entry dates preserve exit intent during temporary ownership-history failure, without authorizing a foreign close. Saved exit intent clears only after verified flat state. Keep unique magic and saved state intact. Missing entry-signal comments, wrong direction or multiple exclusively owned positions cause operational flattening instead of an invented holding deadline.

Retcodes, order/deal IDs and results are checked/logged. Active/unresolved accepted requests block duplicates; partial entries are accepted without top-up. Required exits cancel own entry remainders and retry by ticket. Known unresolved history stays latched; a missing exit ID permits logged, cooldown-limited recovery of remaining owned exposure. Confirmed flat resets the old position's retry clock so another queued position can exit at the same quote. Ambiguous entries are not blindly resubmitted. Foreign orders are untouched.

**MetaEditor/MT5 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 equal-price streak breaks, tiny floating differences, observed-session timing and all **2,865** ready four-close windows against independent integer-tick comparisons, including 2015 context.

Compile with F7 and inspect diagnostics, then test this one case on UTC history with matching account/cost configuration. Verify holiday/Sunday handling, the initial neutral event, next-observed-session exits, same-quote re-entry, stale-FX skips, checkpoints and restart recovery. M5 OHLC cannot establish full tick execution or intrabar FTMO compliance. Python historical results are not MT5 results or FTMO certification; final-window liquidation is a reporting convention rather than this EA's session-exit rule.
