# MondayCCI.mq5 — source and execution notes

Original Edge Quant implementation, MIT license. The EA is complete source and uses only the MetaTrader standard `Trade/Trade.mqh` include. No custom indicator or generated include is required.

Source: [QuantConnect forum — Forex Monday CCI Trend Strategy](https://www.quantconnect.com/forum/discussion/6245/forex-monday-cci-trend-strategy/). The posted algorithm uses **CCI levels**, not crossings: above +100 for long and below −100 for short, with Monday entries. Its fixed entry reference is the signal close, not the execution fill. Its posted LEAN implementation combines both directions and uses the algorithm's New York clock and midpoint quote bars.

This package instead tests two separate Dukascopy components, with **UTC hourly bid signals and UTC completed weekday bid daily bars**. It is an explicit adaptation, not an exact LEAN replication. Run `LONG_ONLY=0` and `SHORT_ONLY=1` separately with unique magic numbers. Do not combine them on one netting symbol/account.

## Exact rules

1. Aggregate actual EURUSD M5 bid bars into observed UTC weekdays. Exclude all Sunday and Saturday bars, omit missing days, and use only days completed before the signal hour's UTC calendar day. Form each daily typical price as `(high + low + close) / 3`.
2. On the latest 30 observed completed weekday bars, calculate the mean typical price and the **mean absolute deviation of those same 30 prices about that mean**. CCI is `(latest_typical_price - mean) / (0.015 * mean_absolute_deviation)`. A flat window has CCI zero. This is not a rolling mean of previously calculated deviations.
3. Each nonempty observed UTC hour produces one signal at its closing boundary, using its last observed M5 **bid close**. Empty hours do not create repeated-price signals. A Friday signal whose first available execution quote arrives after the weekend is retained for exit handling.
4. Evaluate an existing position first, using its original signal bid reference. Long exits require signal bid **strictly above** `reference * 1.01` or **strictly below** `reference * 0.95`. Short exits require signal bid **strictly below** `reference * 0.99` or **strictly above** `reference * 1.05`. Equality does not exit. The EA compares prices directly to these levels to avoid rounding cancellation in an intermediate percentage calculation.
5. Once an exit is confirmed flat, a UTC Monday signal may enter long if CCI > +100 or short if CCI < −100 for the selected component. One new entry is allowed per signal hour, including an exit followed by a same-hour re-entry. A newly entered position is first checked for another threshold exit on the next observed hourly signal. There is no trailing reference.

Entry orders use the first available tick at/after the hourly boundary with at most **15 minutes of delay, inclusive**. Failed entries can retry inside that window. Missed entries are skipped. Exits execute on the first available tick after their hourly signal and retry until closed; a delayed exit is never discarded because its signal is old. Signals use completed bid bars; actual long/short fills use the broker's executable ask/bid and can differ from the reference.

These are **hourly signal exits**, not intrabar price stops. The EA sends **no server SL or TP orders**. A large adverse move, spread expansion, gap or terminal outage can exceed the nominal 5% signal threshold before an exit executes. The strategy does not impose fixed 1% risk per trade or FTMO loss guard rails.

## History, startup and UTC

Provide the supplied 2015 history before testing January 2016 through December 2025. The EA reconstructs the last 30 observed weekday daily bars from up to 120 calendar days of M5 history. It never uses broker D1 bars or `iCCI`. At least 30 valid completed weekday bars are required; insufficient/unready indicator history blocks entries. Existing-position exits do not wait for CCI.

Start/restart **before the intended hourly entry boundary**. Initialization at the exact boundary second is accepted; initialization later than that boundary skips its remaining entry window. Matching existing positions continue to be managed. Offline operation cannot recreate historical executions that occurred while the terminal was stopped.

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

A fixed offset does not model a broker's historical summer/winter server offsets. Use normalized UTC custom-symbol data, or implement and audit the broker's historical offset schedule before relying on daily boundaries. No automatic broker-DST parity is claimed. Bars must be bid-based; initialization rejects a last-price chart series.

## EUR account and exposure

Attach to the selected broker EURUSD symbol, including any suffix. The EA requires an **EUR-denominated account**, symbol base currency EUR and profit currency USD. Set the Strategy Tester deposit to **EUR 10,000**. Broker contract size, lot minimum/maximum/step, directional limit and margin availability are read at runtime. The research assumes a 100,000-EUR contract, 0.01-lot step/minimum.

Sizing targets at most 1× equity in **base EUR notional** after an entry-cost reserve:

```
raw_lots = equity_EUR /
    (contract_EUR + (commission_USD_per_lot + contract_EUR * budget_slippage_price) / EURUSD_bid)
```

Defaults reserve USD 3.50 per lot entry commission and 0.00001 adverse price slippage. Floor to the broker's lot step and never round upward to meet a minimum. These are budget reserves only; the EA does not deduct artificial commission/slippage from cash. Actual fills, fees, conversion and swap remain broker controlled. Other account exposures change equity and margin; use a dedicated test account.

The Python research charges its modeled spread, 0.00001 adverse slippage per side, USD 3.50/lot/side commission and assumed 5% annual financing. The EA uses actual broker execution/fees/swaps and does not artificially charge 5% funding. `InpDeviationPoints` is an execution tolerance in broker points, not a guaranteed slippage charge. Matching the sizing budget does not guarantee identical fills or P&L.

## Ownership, restart and requests

The original signal reference is persisted in a short position/deal comment, `MCCI_L:<reference>` or `MCCI_S:<reference>`, within the broker's usual 31-character comment limit. It is never substituted with the fill price. An exclusively owned position with a missing/unparseable comment, wrong direction, or multiple owned positions is flattened instead of inventing a reference. Broker comment modification is therefore material.

Matching-magic hedging positions are closed by ticket. A netting position is modified only when nonempty available position deal history contains exclusively matching-magic trades. Foreign or mixed positions are never closed and block new entries. Foreign symbol orders also block entries. Unique magic and a dedicated netting symbol/account are required; external systems can modify a position between checks.

Before entering, deal history blocks a second new entry in the current signal hour. It still allows an older position to exit and one replacement to enter that hour. A failed history lookup blocks entry. Successful partial entries are accepted without top-up. Retcodes/deal/order IDs are logged; successful CTrade structure validation alone is not treated as execution proof. Accepted requests are latched while their order state is unresolved; active orders prevent duplicate submissions. Expired own entry orders/remainders are cancelled when visible, including before a required exit. Foreign orders are untouched.

If an accepted exit returns no order ID, a confirmed flat state clears the latch. Otherwise an explicit recovery message is logged and the EA retries a ticket-specific close of remaining visible owned exposure after cooldown if no own active order exists. An ambiguous entry with no order ID blocks further entries until exposure/history resolves or the operator investigates; it cannot safely be blindly resubmitted. Network/market-order latency can still produce late fills. Required exits remain based on the stored original reference and pending hourly exit signal.

## Verification status

**MetaEditor/MT5 are unavailable here: this EA has not been compiled or backtested in MT5.** Static source review checked API usage, signal windows, fixed-reference exits, same-hour re-entry, ownership and request handling. The EA includes an analytical CCI self-check at initialization: prices 1…30 have mean 15.5, mean absolute deviation 7.5 and CCI +128.8888888889; descending prices give the negative and constant prices give zero. The MQL self-check runs only when the EA is executed in MT5; independent Python arithmetic checks were also performed during preparation.

Compile with F7 in MetaEditor, review diagnostics, then test each case separately on imported UTC history with 2015 warmup and sufficient ending quotes to settle the final position. Verify Monday boundaries, Sunday exclusion, CCI values, exact-threshold equality, hourly exit-first re-entry, fixed bid references, spread, broker lot constraints, financing and rejected/partial requests. M5 bid OHLC alone cannot reproduce full intrabar bid/ask tick execution; exact MT5 validation needs corresponding tick quotes and broker configuration. Python historical results are not MT5 tester results or FTMO certification.

Official trade-result handling references: [CTrade Buy](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradebuy) and [ticket-specific PositionClose](https://www.mql5.com/en/docs/standardlibrary/tradeclasses/ctrade/ctradepositionclose).
