# IBSReversal.mq5 — source and execution notes

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

Primary source, read directly: [Quantified Strategies — The IBS Indicator: The Powerful Indicator You Have Never Heard of](https://quantifiedstrategies.substack.com/p/the-ibs-indicator-the-powerful-indicator), March 14, 2026. Its QQQ example buys IBS below 0.10 and sells above 0.90. The article focuses on stock/index mean reversion and emphasizes execution near the close; it also discusses lower results when execution waits until the following open.

This study applies those threshold ideas to **EURUSD**, using **UTC weekday bid bars and first available quotes after completion**. It is not an equity/QQQ replication, does not inherit the article's performance claims and does not establish that an equity-market effect transfers to FX. The 2016–2025 research period precedes the cited article, so its split diagnostics remain retrospective.

## Frozen rules

- Manually aggregate actual observed M5 **bid** bars into UTC calendar-day OHLC. Include only **Monday through Friday dates**. Exclude Sunday/Saturday daily signals; do not invent missing dates or substitute broker D1 bars.
- Use only completed days: a day `d` becomes actionable at **00:00 UTC on d+1**. The current incomplete day's high, low and close never enter the indicator.
- `IBS = (close − low) / (high − low)`. A zero-range observed day has **no signal**, and is still consumed as that day's event.
- If flat, enter long on **strict IBS < 0.10**. If holding, exit on **strict IBS > 0.90**. These are levels, not crossings. There is **no short side, stop, target, time exit, trend filter or other historical signal rule**.
- Execute at the first available quote after availability. A Friday signal becomes available Saturday 00:00 UTC and can execute at Sunday's reopen. There is no 15-minute age limit on a waiting daily signal. The entry conversion quote itself must be fresh.
- Process every new observed weekday event once, in chronological order. If several become executable at one quote, preserve their sequence; an entry followed by a later daily exit can occur at that same quote. Preserve a pending exit across later events, gaps and rejected close requests until flat is confirmed.

For numerical strictness, EA/Python compare price differences instead of dividing near a threshold. With `epsilon = 1e−12 * max(1, |high|, |low|, |close|)`:

```
entry: 10*(close-low) < (high-low) - epsilon
exit:  10*(close-low) > 9*(high-low) + epsilon
```

Exact IBS 0.10 and 0.90 remain neutral. The tolerance is far smaller than the source quote increment; it addresses floating-point equality rather than changing a trading threshold.

## Initial 2016 context and subsequent events

Fresh tester initialization clears only this EA's separate tester signal/exit markers. It starts with no 2015 position carried into the new test and retains **only the latest observed completed prior weekday event** on its first tick, including a neutral or zero-range event. It does not search backward for the latest actionable event or replay all 2015 trades.

For the supplied history, the initial event is **December 31, 2015**, IBS **35/843 ≈ 0.0415183867**, available January 1, 2016. The first 2016 quote is **January 3 at 22:00 UTC**, so the historical model can enter there once. The EA is capable of using that tester-only initial context when imported history is ready; this is not a claim that MT5 parity has been demonstrated.

After initialization, persistent state checkpoints each processed day. New completed weekday events after that checkpoint are processed chronologically. A day with no action is still processed once. A stale conversion, below-minimum size, insufficient margin, disabled trading or rejected entry consumes that daily entry event; it does not wait for a later fresh quote or resubmit it. A new later low-IBS day can provide a new entry signal if flat.

## Historical next-quote assumption and operational safeguards

The Python study assumes execution at the first observed M5 **open quote** after a completed daily signal, plus its modeled costs. This is a declared quote-response approximation, not a guarantee of a live first-open fill. Actual terminal processing, network latency and broker execution can change the available quote and fill.

The EA's operational entry safeguards are separate from the historical strategy rules:

- Latch the first observed M5 chart interval before requesting history. A later tick with newly loaded context cannot revive that same interval for entry.
- Verify that the current observed interval is the first actual M5 interval available after the signal's midnight availability. Do not attach late and execute an old signal at a later quote.
- In **live operation**, that interval must not predate initialization. An EA attached before a weekend reopen can act on the still-waiting Friday signal; one attached after the reopening interval began skips it. The exact boundary second is permitted.
- Tester initialization permits the latest prior completed context described above, while still checking the first available observed quote interval. No 2015 position is imported.

These safeguards may produce fewer entries than the idealized historical model if history is unready or the EA attaches late. They are not optimized signal filters. Required exits remain active even if indicator history or a fresh conversion is unavailable; the broker may still reject a close, in which case it is retried. Offline operation cannot recreate fills that should have occurred while the terminal was stopped.

## EUR sizing, conversion and costs

Attach to the selected EURUSD symbol, including its broker suffix. Both trading and conversion symbols must be direct EUR/USD with USD profit currency. The EA requires an **EUR-denominated account**; set tester deposit to **EUR 10,000**. The default conversion symbol is the same EURUSD symbol, but an explicit broker conversion symbol can be selected.

Read contract size, minimum/maximum lot, step, directional volume limit and free margin from the broker. Research assumes a 100,000-EUR contract and 0.01-lot minimum/step. Target at most approximately **1× entry EUR notional**, with an entry-cost reserve:

```
budget_entry = current_EURUSD_ask + 0.00001
raw_lots = equity_EUR /
    (contract_EUR * budget_entry / conversion_EURUSD_ask
     + 3.50 / conversion_EURUSD_bid)
```

Floor to lot step, never round upward to meet a minimum. Defaults reserve **0.00001 adverse slippage (0.1 pip)** and **USD 3.50 per lot entry commission**. Those inputs reserve budget only; they do not deduct artificial charges or impose a fill price. Other positions change equity and margin, so use a dedicated test account.

Entry conversion must be no more than **900 seconds old**, without using a future-dated quote. Stale entry conversion skips that daily event; exit submission has no freshness filter. The Python model uses backward-only source-quote availability and measures source age from its M5 timestamps; the EA reads actual broker tick timestamps. Quote ordering/granularity can differ.

The Python study models supplied bid/ask, 0.1-pip adverse slippage per side, USD 3.50/lot/side commission and assumed **5% annual funding** on entry absolute USD notional for elapsed holding time. Positive USD P&L converts at EURUSD ask; negative P&L/fees/funding at bid. This is a research scenario, not historical broker swaps. The EA uses actual broker execution, commissions, conversion and swap, and does **not** artificially charge 5% financing. `InpDeviationPoints` is an execution tolerance in broker points, not a guaranteed slippage charge.

## UTC history and calendar handling

Use the supplied 2015 prior context before the 2016–2025 evaluation. The EA constructs daily high/low/close from actual completed M5 bars, excluding weekend dates and missing dates. It never reads broker D1 OHLC or an `iCustom` indicator. The latest 120 calendar days are sufficient to establish fresh initial context; after a saved checkpoint, the requested history begins at the next calendar day.

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

A fixed offset cannot infer historical broker daylight-saving changes. Normalize the data to UTC or independently audit/implement the broker's historical schedule before comparing daily boundaries. No automatic historical broker-DST parity is claimed. Bid-based historical chart bars are required; initialization rejects last-price mode.

## Restart, ownership and requests

Terminal Global Variables keyed to account/server/symbol/magic store the last consumed signal day and pending exit intent. Broker comments `IBS_L:<signal_day_utc>` provide an additional recovery path for submitted/filled own signals. Neutral or skipped events without broker records rely on the local checkpoint. Tester/live keys are separate; live state persists through reattachment. Do not delete or change that identity while comparing a run.

Persist pending exit intent **before** checkpointing its day. No later daily checkpoint may advance past an exit whose intent is not durable. A crash therefore leaves either a saved exit or an unconsumed event for recovery. Restore and retry pending exits before processing newer events. Clear saved intent only when the symbol is verified flat; temporary unavailable/mixed netting ownership does not falsely count as a confirmed close.

Only matching-magic owned exposure is managed. Hedging exits use exact tickets. Netting ownership additionally requires available nonempty position deal history containing exclusively matching-magic trades. Foreign/mixed exposure is never closed and blocks entries. A high-IBS event retains intent if ownership is temporarily unverified, but closing requests still require exclusively owned tickets. Foreign symbol orders are untouched and block new entries. A dedicated netting account/symbol is required because outside systems can modify positions between checks.

IBS exits need neither an entry-price reference nor a holding timer. An owned long remains manageable if its broker comment is altered. An unexpected owned short or multiple owned positions triggers an operational flattening of exclusively owned exposure rather than being treated as the one-position long strategy.

Retcodes, order/deal IDs and fills are logged. Successful CTrade structure validation is not treated as proof of execution. Accepted requests/active orders block duplicate submissions; successful partial entries are accepted without top-up. Before an exit, cancel visible own entry remainders and retry the close. Known unresolved order history remains latched. A missing exit order ID reconciles verified flat state; otherwise a logged, cooldown-limited ticket-specific retry can close remaining owned exposure when no own order remains. An ambiguous entry is never blindly resubmitted and may require operator investigation.

## Verification status

**MetaEditor/MT5 are unavailable here: IBSReversal.mq5 has not been compiled or backtested in MT5.** Independent static review checked daily causality, initial context, event sequencing, checkpoint/exit crash consistency, ownership and request handling.

Independent arithmetic checks verified strict 0.10/0.90 equality, the next quote increments, zero-range neutrality and the initial 35/843 signal. All **2,868** supplied observed weekday classifications matched independent integer-tick arithmetic. The EA includes equivalent initialization checks, but those MQL checks run only when executed in MT5.

Compile with F7 in MetaEditor and inspect diagnostics. Test this single EURUSD long case on UTC history with the specified initial context, EUR 10,000 deposit and matching symbol/cost configuration. Verify the initial January 3 entry, Friday-to-Sunday availability, Sunday exclusion, missing/zero-range days, strict equality, stale FX skips, pending exits, restart persistence and chronological events. M5 OHLC alone cannot reproduce full tick execution or certify intrabar FTMO compliance. The research's final-window liquidation is a reporting convention; the EA otherwise waits for its high-IBS signal without a time exit.

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).
