# LondonBollinger.mq5 — source and execution notes

Original Edge Quant implementation, MIT license. **One combined GBPUSD long/short case**. The complete `.mq5` source uses only MetaTrader's standard `Trade/Trade.mqh`; it needs no custom indicator or generated include.

Source: [QuantConnect forum — London Breakout Strategy](https://www.quantconnect.com/forum/discussion/1597/london-breakout-strategy/), public C# implementation. The source reads the **bar-start `Time.Hour`** on FXCM's **fixed EST clock, UTC−5 throughout the year**. QuantConnect staff explicitly explain the FXCM fixed-EST data convention in [Daylight savings / timezone confusion](https://www.quantconnect.com/forum/discussion/5365/daylight-savings-timezone-confusion/p1). This source-clock rule does not use `America/New_York` daylight saving. The name “London” does not override the actual code's clock.

The research adapts that posted code to observed Dukascopy UTC M5 **bid** bars, explicit next-available-quote execution, EUR accounting and modeled costs. It is not an exact reproduction of old LEAN/FXCM historical returns.

## Frozen rules and source event order

- Aggregate actual nonempty UTC H1 intervals from the M5 bid series. A signal at hour `t` uses the last observed bid close within `[t−1h,t)`. Empty hours produce no repeated-price signals; no bars are filled in. The ten-bar window contains the latest **10 observed completed hourly closes, including the current close**.
- Bollinger middle = arithmetic mean; standard deviation = **population** standard deviation over those same ten closes; lower/upper = mean ± **2.2** standard deviations.
- Convert **bar start `t−1h`** to fixed EST by subtracting five hours. Entries are allowed for bar-start hours **05 through 10 inclusive**, corresponding to decision times **11:00 through 16:00 UTC, all year**.
- Reset `hasTraded` only when an **actual observed** bar has fixed-EST start hour **01**, corresponding to decision **07:00 UTC**, after the indicator is ready. A missing reset bar does not trigger a substitute midnight/calendar-date reset.
- **Entry is checked before exit.** If flat, the cycle allowance is unused and the entry window is open: current close strictly above upper enters long; strictly below lower enters short. A qualifying attempted entry consumes that reset cycle's allowance even if sizing, conversion availability or execution fails. Failed requests can retry the **same reserved attempt** for up to 15 minutes; they cannot create a different attempt later in that cycle.
- Persist the **entry signal bid close** as the fixed reference, not the actual fill. New entry starts `holdEvents=0`, then the same entry event increments it to **1**. Each subsequent observed H1 event increments it once. Exit when the counter is **greater than 5**: the sixth observed event, five elapsed hours after entry when observations are contiguous.
- Held long: take profit when the signal bid close is strictly above reference + **0.00080**; stop when strictly below reference − **0.00180**. Held short: take profit strictly below reference − **0.00080**; stop strictly above reference + **0.00180**. These are **8 and 18 pips** for GBPUSD. Check profit, loss, then timed exit; the reference never trails.
- An existing position can exit after that event's entry check, so it **cannot exit and re-enter in the same event**. A newly entered position is included in that event's exit/count handling.

For numerical strictness, both EA and Python require a comparison difference greater than `1e−12 * max(1, |a|, |b|)`. This price-unit tolerance is far smaller than a quote tick. It is applied to band comparisons and additive TP/SL levels so binary floating-point addition cannot turn exact mathematical equality into a strict crossing. Equality at exactly 8 or 18 pips does not exit; the next 0.00001 quote increment does.

## Quotes, timing and risk

A new entry submits a market request on the first available GBPUSD tick at/after the signal boundary, with **15 minutes maximum entry delay, inclusive**. An older qualifying signal can consume the allowance while its entry execution is skipped for excessive delay. An exit submits on the first available tick after its signal and retries until confirmed closed. Missing the planned exit tick does not discard the exit. Pending exit state survives later signal changes. After a market gap the last **observed** hourly close is still available for exit handling; no empty weekend hours are counted.

These are **closed-hour signal exits**. The EA submits **no server stop-loss or take-profit orders**. Intrabar moves, spreads, gaps, outages and market-order latency can exceed 18 pips before a closing order executes. The source's hold counter counts observed events rather than wall-clock time. This implementation is not a fixed-percent-risk strategy and does not implement FTMO loss guard rails or certify challenge compliance.

Provide the supplied **2015 M5 warmup** before evaluating 2016–2025. The EA reconstructs recent observed H1 bars manually from M5; it does not use broker D1 bars or a custom indicator. Ten valid observed hourly closes are required. Missing/unready history blocks entries. Existing pending exits continue to be managed while indicator history loads.

## UTC history and fixed source clock

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

The broker's historical server timestamp convention is separate from the source's fixed-EST decision clock. A fixed offset cannot infer a broker's historical summer/winter server changes. Normalize historical timestamps to UTC, or implement/audit that broker's complete offset schedule before comparing hourly boundaries. No automatic broker-DST conversion is claimed. The EA requires bid-based GBPUSD historical bars and rejects last-price chart mode.

## EUR account and position budget

Attach the EA to the selected **GBPUSD** symbol, including its broker suffix. Select a separate direct **EURUSD** conversion symbol. The EA requires an **EUR-denominated account**, GBP/USD symbol currencies and EUR/USD conversion currencies. Set Strategy Tester initial deposit to **EUR 10,000**.

Read actual contract size, lot minimum/maximum/step, directional volume limit and available margin from the broker. The research assumes 100,000 GBP per lot and 0.01-lot minimum/step. Target at most approximately **1× EUR equity notional**, with an entry-cost reserve:

```
budget_entry = GBPUSD_ask + 0.00001     # long
budget_entry = GBPUSD_bid - 0.00001     # short
raw_lots = equity_EUR /
    (contract_GBP * budget_entry / EURUSD_ask + commission_USD_per_lot / EURUSD_bid)
```

Defaults reserve 0.00001 adverse price slippage and USD 3.50/lot entry commission. Floor to the broker's lot step; skip a below-minimum trade instead of rounding upward. The conversion quote must be no more than **900 seconds old**. Sizing failures/stale conversion can retry only the same consumed attempt inside its 15-minute window. Reserve inputs do not artificially charge account cash or dictate the broker's execution price.

The Python study models actual supplied bid/ask quotes, 0.00001 adverse slippage per side, USD 3.50/lot/side commission and assumed **5% annual funding**. This EA uses actual broker fees, currency conversion and swaps; it does not deduct artificial 5% financing. `InpDeviationPoints` is a broker execution tolerance in points, not a guaranteed slippage charge. Quote, conversion, lot constraints, broker costs and execution differences prevent a claim of exact P&L parity. Use a dedicated account: unrelated exposure changes equity and margin.

## Restart and trade ownership

Position comments persist direction, original signal reference and entry-event UTC hour as `LBB_L:<reference>:<epoch>` or `LBB_S:<reference>:<epoch>`, within the usual 31-character comment budget. Reconstruct the hold counter by counting actual observed H1 bins from that entry event **inclusive**, never by elapsed wall-clock hours. For deciding `>5`, the recovered count can stop at six. Older-history recovery is requested if recent data alone cannot establish the count. Missing/corrupt reference comments, impossible future entry hours, wrong direction or multiple owned positions cause exclusively owned exposure to be flattened rather than inventing state.

The consumed attempt is stored **before** sizing/order submission in a terminal Global Variable keyed to account/server/symbol/magic. History of own entries/orders since the latest **observed** reset provides a second reconstruction path. No observed reset means no assumed new allowance. Keep unique magic and that saved state intact; deleting it can remove proof of an unfilled attempt. Fresh tester initialization clears the separate tester marker, while live markers survive reattachment. Tester/live keys are separate.

Start/restart before the intended entry hour. Initialization at the exact boundary second is allowed; initialization after it skips that event's remaining entry window. A restart preserves the consumed allowance but does **not** resume a lost in-memory retry plan. Existing matching positions and their original references continue to be managed. Offline operation cannot recreate historical fills that should have occurred while the terminal was stopped.

Matching-magic hedging positions are closed by ticket. A netting position is changed only if its available nonempty position deal history contains exclusively matching-magic trades. Foreign/mixed GBPUSD positions are never closed and block new entries; foreign GBPUSD orders also block entries. A dedicated netting account/symbol is required because another system can change a net position between checks.

Retcodes, deal/order IDs and results are logged. Accepted requests and active own orders block duplicate submissions; known unresolved order-history state remains latched. Successful partial entries are accepted without top-up. Expired own entry orders/remainders are cancelled when visible, including before a required exit; foreign orders are untouched. For an accepted exit with no order ID, a confirmed flat state clears the latch; otherwise explicit recovery logging precedes a cooldown-limited ticket-specific close of still-visible owned exposure if no own order remains. An ambiguous entry with no order ID is not blindly resubmitted; it blocks until exposure/order state resolves or the operator investigates. Market/network latency can still produce late fills despite cancellation attempts.

## Verification status

**MetaEditor/MT5 are unavailable here: LondonBollinger.mq5 has not been compiled or backtested in MT5.** Independent static review checked the fixed source clock, reset/attempt persistence, observed-event counter, entry-before-exit order, reference comments, ownership and request handling.

The EA contains initialization self-checks for population bands (prices 1…10: mean 5.5 and variance 8.25), flat bands, winter/summer fixed-EST window/reset anchors, and exact decimal 8/18-pip equality versus the next quote increment. Those MQL checks execute only in MT5; independent Python arithmetic checks were also run during preparation.

Compile with F7 in MetaEditor and inspect diagnostics. Test the single combined case with 2015 warmup, UTC timestamps, EUR 10,000 deposit, matching GBPUSD/EURUSD history and broker symbol configuration. Verify observed 07:00 UTC resets, 11:00–16:00 UTC decisions in both winter and summer, rejected-attempt consumption, six-event exits, no same-event re-entry, exact threshold equality, bid references, lot sizing and financing. M5 bid OHLC alone cannot reproduce full bid/ask tick execution. 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).
