Files
conversation-history/Trading/MT5/2026-04-19 OrdersEA Smart Grid - Opportunities Plan.md

282 lines
16 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 2026-04-19 — OrdersEA Smart Grid: Opportunities & Fix Plan
> **STATUS: IMPLEMENTED as v4.0 on 2026-04-19.** All tiers applied. `Opposite` input dropped, repo stubs deleted, 3.5 changed to `InpUseStopLoss` flag (default false = no SL). File grew from 981 → 1360 lines. See `~/mql-trading-bots/OrdersEA_Smart_Grid.mq5`.
>
> **UPDATE 2026-04-19 (same day):** Multi-horizon drawdown structure added per [[Option 2]]: daily default raised 3% → 5%, new `InpMaxWeeklyDrawdown` = 10% with Monday 00:00 broker reset. Either limit trips = block new trades. Both tracked per-EA via history scan. Grid presets (`grid-*.set`) still set `InpMaxDailyDrawdown=3.0` — update if desired.
**Source code reviewed:** `OrdersEA_Smart_Grid.mq5` (v3.4, 981 lines)
**Context:** Grid EA currently shut down (Apr 5) due to shared-drawdown with Confluence EA and ADX filter blocking trades in trending markets. User frustrated that EA "does not serve any purpose" on new $100K account (Apr 13).
Related notes:
- [[OrdersEA Smart Grid v3.4 Fix]]
- [[OrdersEA Smart Grid v3.4 Cheatsheet]]
- [[2026-04-05-grid-shutdown-analysis]]
- [[2026-04-13-new-account-grid-issue]]
- [[2026-04-01-mt5-analysis-and-fixes]]
---
## Repo hygiene (do first, costs nothing)
- **Delete or archive `OrdersEA.mq5` and `OrdersEA_MT5_Converted.mq5`.** Both are identical 240-line stubs with `OnTick()` placeholder comments and no trading logic. Someone could compile the wrong file and attach it thinking it's the real EA. The real file is `OrdersEA_Smart_Grid.mq5`.
---
## Tier 1 — Wrong code (fix before re-enabling)
### 1.1 `IsBreakout()` clobbers ATR-adjusted grid bounds
**Where:** `OrdersEA_Smart_Grid.mq5` lines 760-761
**What:** Every bar, `IsBreakout()` sets `GridHigh = PivotR1` and `GridLow = PivotS1`, overwriting the ATR-widened values set at midnight by `CalculatePivotPoints()`.
**Effect:** `UseAutoPivots + UseATRFilter` only affects the first bar after midnight; after that, grid uses raw pivot R1/S1. Users tuning `ATRMultiplier` see no effect past bar 1.
**Fix:** Remove the two assignments — `IsBreakout` only needs `PivotS2`/`PivotR2` for the actual breakout check.
**Effort:** 2 lines.
### 1.2 Pending orders use `ORDER_FILLING_IOC`
**Where:** Lines 191, 522, 618, 674 (`trade.SetTypeFilling(ORDER_FILLING_IOC)` and per-request `type_filling`)
**What:** IOC is meant for market orders. Strict brokers (including some Wine/Docker setups) reject pending orders with IOC.
**Fix:** In `OnInit()`, query `SYMBOL_FILLING_MODE` and pick per symbol. For pending orders, use `ORDER_FILLING_RETURN`. Keep IOC only for market-style operations.
**Effort:** ~10 lines, one helper function.
### 1.3 `longs`, `shorts`, `longAvgPrice`, `shortAvgPrice` never computed
**Where:** Declared lines 91, 107-108. Read lines 399-400 in `SendNotificationEx`. Never written.
**Effect:** Every Telegram notification shows `Longs: 0 @ 0.00000 | Shorts: 0 @ 0.00000`.
**Fix:** Port `CalcAvgPrice()` from MT4 original (lines 822-860) using MT5 position API. Call before notification.
**Effort:** ~30 lines.
### 1.4 `Master=true` runs `GlobalShutdown()` every tick forever
**Where:** Lines 802-806
**What:** Once set, iterates all positions/orders on every tick indefinitely. Wasteful; on a multi-chart setup every chart runs the full scan.
**Fix:** One-shot flag after first run. Subsequent ticks just `return`.
**Effort:** 3 lines.
---
## Tier 2 — Dead inputs (wire up or remove)
Three inputs declared but never referenced in logic. This is the same bug class fixed in v3.4 for `GetOut`/`OpenNewTrades`/`Master`.
### 2.1 `TakeProfitLevelPercent` (line 53)
Intent (from MT4): close entire cycle when equity gain % over start hits threshold.
**Recommended behavior:** cycle-close when `(AccountEquity() - cycleStartEquity) / cycleStartEquity * 100 >= TakeProfitLevelPercent`. Trigger `CloseAllPositions()` + `CancelAllOrders()` + `gridPlaced = false`.
**Effort:** ~15 lines.
### 2.2 `TakeProfitLevelDollarAmount` (line 54)
Same as above but absolute dollars: close cycle when `AccountEquity() - cycleStartEquity >= TakeProfitLevelDollarAmount`.
**Effort:** combine with 2.1, ~5 extra lines.
### 2.3 `Opposite` (line 52)
Intent (from MT4): when only one side of grid has fills, open an aggregated opposite position to hedge/recover.
**Decision needed:** port `HandleOpposite()` from MT4 original (lines 949-1035) OR remove the input. Current state is confusing — user sees the input and assumes it works.
**Recommendation:** remove for now. Classic "opposite hedging" on grid rarely helps; it doubles risk. Port only if user specifically wants it.
**Effort:** remove = 1 line. Port = ~60 lines.
---
## Tier 3 — Design improvements
### 3.1 Shared daily-drawdown between Grid EA and Confluence EA
**Where:** `CheckDailyDrawdown()` lines 146-189 (and mirror in Confluence EA)
**Problem:** Both EAs call `AccountInfoDouble(ACCOUNT_EQUITY)` and each enforces a 3% daily limit independently. If Grid loses 2%, Confluence only has 1% left. Identified in `2026-04-05-grid-shutdown-analysis.md` as the reason Grid was killed.
**Fix options:**
- **A.** Allocate budgets: Grid gets `InpMaxDailyDrawdown = 1.5%`, Confluence gets `1.5%`. Keeps independence, halves shared pressure.
- **B.** Track per-EA P&L (sum `PositionGetDouble(POSITION_PROFIT)` filtered by MagicNum) instead of account equity. Each EA then polices its own contribution.
- **C.** Shared via `GlobalVariable` with per-EA attribution.
**Recommendation:** Option B. Most truthful — each EA accountable for its own damage. ~20 lines.
### 3.2 Grid geometry overlaps at mid-range
**Where:** Lines 958-972
**What:** `buyLevel = actualLow + i*entry` and `sellLevel = actualHigh - i*entry` converge toward mid-range. With `MaxLevels=10, Entry=10pts` over a 200-pt range, half the levels get silently filtered by the `buyLevel < currentPrice - 2*Entry` guard. Not a bug, but wasteful.
**Fix:** Derive `MaxLevels` from `(actualHigh - actualLow) / (Entry * point)` so grid exactly fills the band, and enforce a "no-trade zone" around current price explicitly rather than via fallthrough.
**Effort:** ~10 lines.
### 3.3 ATR-scaled Entry spacing
**Where:** currently fixed `Entry=10` in inputs, tuned per pair via `.set` files
**Opportunity:** Auto-derive `Entry = k * ATR(Daily) / MaxLevels`. Grid scales with volatility regime and per-pair pip values. Kills the need for 11 per-pair `.set` files.
**Effort:** ~15 lines + testing.
### 3.4 No spread filter
**Where:** n/a
**Problem:** Grid pending orders fill during NFP/rollover spread spikes at terrible effective prices.
**Fix:** Add `InpMaxSpreadPoints` input. In `OnTick`, read `SymbolInfoInteger(_Symbol, SYMBOL_SPREAD)`; if over limit, skip grid placement and cancel un-filled pendings near price.
**Effort:** ~10 lines.
### 3.5 No `StopLoss` default (silent catastrophe)
**Where:** Line 46 `input int StopLoss=0;`
**Problem:** Default is 0 = no SL on grid trades. Grid + no SL + leverage = margin call mechanism. March's $60K loss is consistent with this pattern.
**Fix:** Enforce minimum SL (e.g., `StopLoss < Entry * 3` → warn and clamp to `Entry * 3`) OR change default to a safe value (e.g., `Entry * 5`).
**Effort:** 5 lines.
### 3.6 Multi-instance log noise
**Where:** All `Print()` calls
**Problem:** 8 pairs × same EA → Experts tab unreadable.
**Fix:** Prefix every `Print`/`Log` with `_Symbol + ": "`. Helper function `PrintS(msg)`.
**Effort:** 5 lines of helper + find/replace across ~40 Print calls.
### 3.7 Grid state lost on EA reinit
**Where:** `gridPlaced`, `cycleStartEquity`, `cycleProfitStop` are `static` locals (lines 139-141)
**Problem:** Settings change, broker reconnect, or recompile resets them. Grid re-places on already-occupied range.
**Fix:** Persist via `GlobalVariableSet/Get` keyed by MagicNum, following the MT4 pattern (`High_`+MagicNum, etc. in MT4 init() lines 341-382). Load in `OnInit`, save on changes.
**Effort:** ~25 lines.
### 3.8 Pivot recalc depends on tick arriving 00:00–00:05
**Where:** Lines 821-837
**Problem:** Low-liquidity pairs may not tick during the 5-min window; pivots stay stale for the day.
**Fix:** Add `bool pivotsCalcedToday = false`; reset at day-change; calc whenever flag is false and `dt.hour >= 0`. Alternative: `OnTimer()` at 1-minute resolution.
**Effort:** ~10 lines.
---
## Tier 4 — New features (real user value)
### 4.1 Session filter
**Why:** Grid works best in Asia range. Placing grids into London/NY trend = losing money. Would have saved much of March.
**How:** Input `InpActiveHourStart`/`InpActiveHourEnd` (broker time). Skip grid placement outside window. Optionally: close grids at window end.
**Effort:** ~15 lines.
### 4.2 Breakeven move on partial-fill
**Why:** When first grid TP hits, remaining open positions should move SL to breakeven. Protects cycle P&L against the classic "9 winners, one reversal erases all."
**How:** After any position closes in profit within a cycle, iterate open positions with same MagicNum/symbol and modify SL to entry price (+ spread cushion).
**Effort:** ~20 lines.
### 4.3 Correlation cap across MagicNum
**Why:** 8 correlated majors all open buy grids simultaneously = 8× effective exposure. A risk-bombshell the account can't absorb.
**How:** Maintain `GlobalVariable` counter of "active grid cycles per direction." Refuse new grid if over cap (e.g., max 3 concurrent long cycles).
**Effort:** ~25 lines.
### 4.4 Adaptive filters (address Apr 13 frustration)
**Why:** Current ADX=25 cap blocks strong-trend days indefinitely; in Q1 2026's trending market, EA never trades. User feedback: "does not serve any purpose."
**How:**
- Widen `ADXMax` to 30 as default.
- Add `InpRelaxAfterDays`: if no trade placed in N days, temporarily loosen to `ADXMax * 1.3` with smaller lot size.
- Or: detect "pullback in trend" (price between 38%-62% retracement) and allow grid inside it.
**Effort:** ~30 lines for basic adaptive, more for retracement detection.
### 4.5 Cycle-end performance report
**Why:** Currently no visibility into per-cycle outcomes. Hard to tune.
**How:** On cycle end (all orders closed), emit one notification: `"Cycle closed: +$X / -$Y, duration Nh, symbol, magic"`. Accumulate daily summary.
**Effort:** ~20 lines.
### 4.6 Dynamic range drift (port from MT4)
**Why:** MT4 original had `moveRangeTrigger` that shifted `LongLimit`/`ShortLimit` as price drifted, keeping grid centered on actual price. Smart Grid only recenters at midnight — so if price drifts outside S1/R1 mid-day, grid stops working until next day.
**How:** Port logic from MT4 original (lines 1136-1150).
**Effort:** ~15 lines.
---
## Proposed execution order
**Phase 1 — Safety net (same-day work):**
1.1 (IsBreakout clobber) → 1.2 (filling mode) → 1.3 (avg price compute) → 3.5 (SL default) → 3.4 (spread filter)
**Phase 2 — Wire up + polish (next session):**
2.1 + 2.2 (profit targets) → 2.3 (remove Opposite) → 3.6 (log prefix) → 3.8 (pivot recalc reliability)
**Phase 3 — Risk architecture:**
3.1 (per-EA drawdown) → 4.3 (correlation cap) → 3.7 (state persistence)
**Phase 4 — Make it actually trade:**
4.4 (adaptive filters) → 4.1 (session filter) → 3.3 (ATR-scaled entry) → 4.2 (breakeven move)
**Phase 5 — Observability:**
4.5 (cycle report) → 3.2 (grid geometry cleanup) → 4.6 (range drift)
---
## Open decisions for user
- [ ] Drop `Opposite` input, or port the MT4 hedging logic?
- [ ] Per-EA drawdown budget (option B) or split the 3% ceiling (option A)?
- [ ] Keep per-pair `.set` files, or move to ATR-scaled auto-tuning (3.3) and collapse them?
- [ ] Re-enable Grid EA on demo before/after Phase 1, or wait until Phase 2?
- [ ] Add breakeven-move (4.2) — does it match user's cycle philosophy, or is the current "let TP hit or SL hit" simpler model preferred?
---
*Plan author: Claude Opus 4.7 (1M context). Verify file:line citations against current source before implementing — code may have moved.*
---
## UPDATE 2026-04-22/23 — New Pairs Deployed + Breakeven Bug Fix
### New Pairs Added
Created and deployed `.set` files for 3 additional grid pairs:
| Pair | MagicNum | Entry | TP | ATR Mult | Spread Cap | Session Filter |
|------|----------|-------|-----|----------|------------|----------------|
| **EURGBP** | 333015 | 12 | 20 | 1.2 | 20 pts | Asia 01:00–10:00 |
| **EURCHF** | 333016 | 10 | 18 | 1.1 | 18 pts | Asia 01:00–10:00 |
| **AUDNZD** | 333017 | 18 | 28 | 1.5 | 35 pts | Asia 01:00–10:00 |
All three include v4.1 inputs: adaptive filters, spread filter, session filter, breakeven, correlation cap, per-EA drawdown (5%/10%), cycle reports. EURCHF gets lower 3%/6% DD caps due to SNB risk.
### Breakeven Bug Discovered & Fixed (CRITICAL)
**Discovered:** Apr 23 — AUDNZD log flooded with 17,822 `err=10016` (invalid stops) entries in ~7 hours. EURCHF also affected.
**Root cause:** `ApplyBreakeven()` line 791 had SL directions backwards:
```cpp
// BROKEN (v4.1 before fix):
double newSL = (ptype == POSITION_TYPE_BUY) ? (open + buffer) : (open - buffer);
// FIXED (v4.1 post-fix):
double newSL = (ptype == POSITION_TYPE_BUY) ? (open - buffer) : (open + buffer);
```
- BUY: SL must be **below** entry → `open - buffer` ✅
- SELL: SL must be **above** entry → `open + buffer` ✅
**Impact:** SELL positions were getting SL set in the TP zone (below entry), triggering `TRADE_RETCODE_INVALID_STOPS`. The EA retried every 5 seconds indefinitely.
**Fix applied:** Source code corrected, recompiled (`0 errors, 0 warnings`), `.ex5` updated Apr 23 07:27. All `.set` files updated to `InpUseBreakeven=false` pending chart reload.
### Trading Activity (Apr 22–23)
- **Grid EA running on 11 pairs** — active grids placed/cancelled across EURUSD, GBPUSD, USDJPY, USDCHF, USDCAD, NZDUSD, AUDUSD, EURJPY, EURGBP, EURCHF, AUDNZD
- **Range filters working** — grids cancelled within 1–3 hours when "No longer ranging" detected
- **One-sided grids observed** — e.g., AUDUSD placed 0 buy, 6 sell (price near bottom of range)
- **Confluence EA silent** — no log activity detected; may not be attached
### Action Items
- [ ] Reload `OrdersEA_Smart_Grid.ex5` on all charts to pick up breakeven fix
- [ ] Verify Confluence EA is attached to charts
- [ ] Monitor EURCHF SNB risk
- [ ] Monitor log file size — old 4.7MB log may need rotation
---
## CODE REVIEW — OrdersEA Smart Grid v4.1 (2026-04-23)
Full review written to: `~/mql-trading-bots/CODE_REVIEW_OrdersEA_Smart_Grid_v4.1.md`
### Summary Stats
| Category | Count | Severity |
|----------|-------|----------|
| Critical bugs | 2 | 🔴 High |
| Logic/design issues | 5 | 🟡 Medium |
| Performance concerns | 3 | 🟡 Medium |
| Missing safeguards | 4 | 🟡 Medium |
| Code quality / debt | 6 | 🟢 Low |
### Top 5 Issues
1. **Breakeven SL direction bug** — FIXED in v4.1 (was backwards for BUY/SELL)
2. **Drawdown rollover uses `ACCOUNT_EQUITY`** — includes other EAs' open P&L in baseline; should use `BALANCE`
3. **Breakout handler closes ALL positions** — should only close losing side, let winners run to TP
4. **`CalcLots()` uses `BaseEquity=10000` default** — dangerous if account is $100K and equity-based sizing enabled
5. **Adaptive filter tracks `lastTradePlacedTime`** — resets on every fill; should track `lastGridPlacedTime`
### What's Working Well
- Pivot calculation + ATR bands ✅
- Range filters (RSI/ADX/price) ✅
- Per-EA drawdown tracking ✅
- State persistence via GlobalVariables ✅
- Session/spread filters ✅
- Master one-shot shutdown ✅
- Grid geometry with no-trade zone ✅
### Immediate Actions Recommended
- ✅ ~~Fix breakeven~~ (done)
- Fix `BaseEquity` default or update all `.set` files
- Reload correct preset on USDJPY (currently using EURUSD's MagicNum 333011)
- Enable session filter by default
- Fix drawdown baseline to use `ACCOUNT_BALANCE`