# 2026-05-13 OrdersEA — Multi-Agent Synthesis Analysis **Method:** Three-agent adversarial synthesis. Each prior claim re-evaluated against code. **Agents:** Claude Sonnet 4.6 (this session), Kimi Code CLI (two passes), Opencode Agent (two passes) **Confidence target:** >90% on every retained claim. Findings below threshold are flagged or dropped. **Source docs:** - `notes/Kimi_Code_CLI-Analysis_1-Recent_Changes_and_Vault_Synthesis.md` - `notes/Kimi_Code_CLI-Analysis_2-First_Principles_Deep_Analysis.md` - `notes/opencode_analysis_recent_changes.md` - `notes/opencode_first_principles_analysis.md` - `2026-05-12 OrdersEA Smart Grid - Loss Diagnosis & First Principles Analysis.md` - `2026-05-12 OrdersEA Smart Grid - Deep First Principles Analysis.md` --- ## Part 1 — Cross-Agent Agreement Matrix | Finding | Claude | Kimi | Opencode | Confidence | |---------|--------|------|----------|-----------| | Drawdown baseline uses whole-account EQUITY | ✓ | ✓ | partial | 99% | | Edge cleanup v5.0 is causing current losses | ✓ | ✓ | — | 97% | | Session filter absent on older presets | ✓ | ✓ | — | 99% | | Fix checklist items mostly unimplemented | ✓ | ✓ | — | 95% | | GetOut=Y fixed in April 27 preset rewrite | ✓ | ✓ | — | 98% | | Lots tripled 0.01→0.03 in preset rewrite | ✓ | ✓ | — | 99% | | Confluence EA inverted ranging filter | — | ✓ | — | see §3.1 | | Breakeven SL is on loss side of entry | — | ✓ | — | see §3.2 | | ASK/BID asymmetry in edge cleanup | ✓ | — | — | 92% | | Bar-gate timing: cleanup runs at bar-open only | ✓ | — | — | 97% | | Session filter blocks cleanup in off-hours | ✓ | — | — | 97% | | Higher BUY levels fill first, not GridLow | ✓ | — | — | 95% | --- ## Part 2 — Verification of Kimi's Novel Findings ### 2.1 Confluence EA Inverted Ranging Filter — CONFIRMED CRITICAL Kimi found: `CheckVolatilityFilter()` raises thresholds in ranging markets. Verified against code: ```cpp // MultiSignal_Confluence_EA.mq5:511-513 double effectiveMinATR = ranging ? InpMinATRPercent * 1.5 : InpMinATRPercent; double effectiveMinADX = ranging ? InpMinADX + 5.0 : InpMinADX; ``` `isRangingMarket` is set true when `rangingBarsCounter >= 5 && ADX < 20`. **The trap:** - Ranging condition: ADX < 20 → `isRangingMarket = true` - Raised ADX threshold: `effectiveMinADX = InpMinADX + 5.0` (typically 23–27) - ADX filter check: `if(adxValue[0] < effectiveMinADX)` → blocks trade - Since ranging requires ADX < 20, and threshold is 23–27: the ADX check **always fails in ranging markets** This means the Confluence EA is **structurally incapable of trading in ranging markets.** It only fires in trending conditions (ADX ≥ 20), where a reversal-at-pivot strategy has lower success rates. **Why this was missed:** In April, the Confluence EA had zero trades due to ATR thresholds and zero signal sources. The inverted filter was a secondary block on top of those. It wasn't identifiable as the primary cause. But it IS a structural logic inversion in the code. **Impact on current losses:** - Confluence fires primarily in trending conditions - Reversal signals (buy at support, sell at resistance) in trending markets fail more often - Lowering InpMinConfluence to 1 on XAUUSD/EURJPY (April 30) amplifies this: single-source signals in trending markets are the weakest possible setup - Confluence losses contaminate Grid EA's drawdown baselines (see §4) **Confidence: 96%** --- ### 2.2 Breakeven SL Direction Bug — CONFIRMED, DORMANT Kimi found: breakeven sets SL on the LOSS side of entry, not at breakeven. Verified: ```cpp // OrdersEA_Smart_Grid.mq5:791 double newSL = (ptype == POSITION_TYPE_BUY) ? (open - buffer) : (open + buffer); ``` For a BUY at 1.08000 with buffer=5 points: - `newSL = 1.08000 - 0.00005 = 1.07995` — 5 pips BELOW entry - This is a 5-pip stop loss, not a breakeven Input comment says: `// Spread cushion above entry` — this is wrong. The code goes BELOW entry for BUY. True breakeven for BUY: `newSL = open + spread_points` (at least recover spread cost). Or if protecting profit: `newSL = open + buffer` (allow buffer pips of profit before stopping). **The `alreadyAtBE` check also fails:** ```cpp bool alreadyAtBE = (ptype == POSITION_TYPE_BUY) ? (curSL >= open - point) : ... ``` After setting SL to `open - 5 points`, this checks `curSL >= open - 1 point` → `open - 5 >= open - 1` → FALSE. The check never sees the position as "already at breakeven" and re-attempts the modification every 5 seconds. Each attempt sets the same SL value, which MT5 may succeed on silently or emit a redundant response. **Dormancy status:** `InpUseBreakeven = false` in all presets. This bug does not affect live trading. But if anyone enables breakeven, they get a 5-pip stop-loss + perpetual modification spam, not breakeven protection. **The correct fix:** ```cpp // For true breakeven (BUY): SL at entry + spread (above entry, protecting costs) double newSL = (ptype == POSITION_TYPE_BUY) ? (open + buffer) : (open - buffer); // alreadyAtBE check should match: bool alreadyAtBE = (ptype == POSITION_TYPE_BUY) ? (curSL >= open - point) // SL is above/near entry ← already OK : (curSL <= open + point && curSL > 0); ``` Wait — the v4.0 had `open + buffer` for BUY. That was called the "bug" because it caused immediate stop triggers (SL above entry on a position that may still be at entry price). The v4.1 "fix" went to `open - buffer`. The distinction: breakeven means "don't let this trade lose money." For a BUY: - SL at entry = perfect breakeven (no profit, no loss) - SL at `open - buffer` = allows buffer pips of loss (NOT breakeven, it's a stop-loss) - SL at `open + buffer` = locks in buffer pips of profit (profit lock, not breakeven) All three are different. The fix should be `open` (exactly at entry) for pure breakeven, or `open + spread` to recover the cost of entering. **Confidence: 95%** --- ### 2.3 Three-Times Lot Increase as Risk Escalation — CONFIRMED Kimi found: "Fixed the car, now drive faster." Verified: all presets show `Lots=0.03` (was 0.01 before April 27). Framing: - The $60K loss came from a clustering bug: positions accumulated without limit - The clustering was fixed via MaxLevels, edge cleanup, one-fill-per-side - Response: triple lot size (0.01 → 0.03), relax ADXMax (18 → 40), relax RSI (35/65 → 20/80), raise daily DD limit (3% → 5%) This is not a calculated rebalancing — it's frustration-driven risk escalation after a bug fix. The bug was mechanical. The mechanical fix (MaxLevels + edge cleanup) reduces catastrophic accumulation, but tripling lot size raises the per-event loss proportionally: | Parameter | Before April 27 | After April 27 | Change | |-----------|----------------|----------------|--------| | Lots | 0.01 | 0.03 | +200% | | ADXMax | 18–24 | 40 | +67–122% | | RSILower/Upper | 35/65 | 20/80 | much wider | | Daily DD | 3% | 5% | +67% | At 0.03 lots, each edge-cleanup loss is 3× larger. From May 11 data: forced closes averaged −$5.86 per trade. At 0.03 lots: −$17.58 per trade. The edge cleanup that was "marginal" at 0.01 lots becomes "meaningful" at 0.03 lots. **Confidence: 97%** --- ## Part 3 — Challenge to My Own Previous Findings ### 3.1 Challenge: "Edge cleanup is the primary cause of losses" **Kimi's counter:** The inverted ranging filter in Confluence EA means it fires reversal trades in trending markets. These trades lose. Those losses contaminate Grid EA's drawdown baselines. The losses may be multi-source, not single-source. **My response:** The May 11 data that forms the empirical basis of my analysis says explicitly: "32 forced Friday closes, −$187.46" — this is from **OrdersEA** trade history (forced at `InpWeekendCloseHour`). Confluence EA uses time-based trailing stops, not a specific weekend close hour. The data is Grid EA specific. However, Kimi is correct that Confluence losses contaminate Grid EA's cycle P&L and drawdown baselines. This is an additional loss source that I treated as a secondary issue but should be elevated. **Revised conclusion:** The edge cleanup is the primary cause of the small, frequent Grid EA losses. The Confluence EA's inverted filter and resulting trending-market trades are a secondary loss source that becomes primary when Confluence is actively trading. **Confidence in "edge cleanup is primary": 93%** (elevated to 97% for Grid EA specifically, lower for combined system) --- ### 3.2 Challenge: "Enable session filter" as the top fix **Kimi's counter:** The session filter check is at line 1279, which is inside the bar-gate block. If session filter is enabled (01:00–10:00), edge cleanup at line 1283 only runs during session hours. A position stranded at 10:05 bleeds for 15 hours until 01:00 next day. **My response:** I identified this in my second document. This means enabling session filter alone makes stranded positions WORSE, not better. You must ALSO move edge cleanup before the session filter gate. **So "enable session filter" is incomplete as stated.** The correct fix requires both: 1. Move edge cleanup block before `CheckSessionFilter()` call 2. Then enable session filter Without #1, session filter creates a 15-hour window where stranded positions have no cleanup. **Revised confidence in "enable session filter" alone fixing the problem: 40%** (it helps for new placements but harms existing position management) **Confidence in the compound fix (move cleanup + enable filter): 93%** --- ### 3.3 Challenge: "ASK/BID asymmetry fires immediately after fill" **Self-challenge:** I claimed the BUY at GridLow triggers edge cleanup immediately via spread. Is this actually true? **Re-verification:** - BUY_LIMIT at GridLow fills when ASK = GridLow → BID = GridLow − spread at fill time - Bar gate: edge cleanup runs at NEXT BAR OPEN (not at fill time within the same bar) - At next bar open: if price bounced, BID may be above GridLow → no cleanup. If price stayed flat, BID ≈ GridLow − spread → cleanup fires. The spread asymmetry is real but activates on the NEXT bar, not the fill tick. Whether it fires depends on what price does between fill and next bar open. On H1 charts: if price wicked to GridLow and then bounced within the same hour, BID at hour close is above GridLow → no cleanup. The spread issue only matters when price lingers at GridLow. **Refined claim:** The spread asymmetry creates false triggers when prices close AT GridLow (not merely touches it). This is a real but narrower problem than my initial framing. **Confidence in the asymmetry causing false triggers at GridLow: 90%** (narrower than previously stated) --- ### 3.4 Challenge: "EV analysis shows edge cleanup is marginally correct" **Self-challenge:** My EV calc showed edge cleanup is better if bounce rate < 37.5%. But the bounce rate estimate (40–55%) came from general S1 reasoning, not actual data. If the market regime has been trending (May 2026 tariff volatility?), the actual bounce rate could be much lower. **Additional factor I missed:** The 3× lot increase changes the EV calculation significantly: - At 0.01 lots: edge cleanup loss = −$0.30 (spread) to −$2.80 (28-pt move) - At 0.03 lots: edge cleanup loss = −$0.90 to −$8.40 - Weekend closure at 0.03 lots: −$17.58 per trade (vs −$5.86 at 0.01 lots) The 37.5% breakeven threshold still holds mathematically. But the MAGNITUDE of the losses on both sides is 3×. This doesn't change the direction of the EV calculation, but it makes the difference between "edge cleanup is right" and "edge cleanup is wrong" much more consequential. **Confidence in "edge cleanup is directionally correct for the Grid strategy": 85%** (sufficient to keep it, insufficient to declare it optimal) --- ## Part 4 — The Compound Contamination Problem (New Finding) Neither agent fully articulated this cascade. Tracing it precisely: ### Step 1: Confluence EA fires in trending market - Inverted ranging filter → Confluence only trades when ADX ≥ 20 (trending) - In trending conditions, reversal signals fail more often - Confluence opens a SELL at R1 in an uptrend - Price continues up → Confluence trade is at floating loss ### Step 2: Confluence loss enters Grid EA's equity view - Grid EA line 1445: `cycleStartEquity = AccountInfoDouble(ACCOUNT_EQUITY)` - This is set when the Grid places a new cycle - If Confluence has −$500 floating at Grid cycle start: cycleStartEquity = balance − $500 ### Step 3: Confluence closes trade (realized loss) - Confluence SELL hits its drawdown limit or trailing stop - Loss of −$500 realized → account equity recovers to balance (Confluence floating gone) - Grid EA's equity is now HIGHER than when cycleStartEquity was set - `CheckProfitTarget()`: `gain = equity − cycleStartEquity = +$500` (appears as profit!) - Grid EA incorrectly thinks the cycle was profitable → closes the cycle ### Step 4: Grid EA closes cycle early - Grid EA's BUY positions close at market - Some of those BUY positions may be in floating loss (negative) - Grid EA realizes a loss while "thinking" it hit a profit target - The profit target was a contamination artifact, not real Grid EA profit **This cascade is partially bi-directional:** - Grid EA losing → contaminated Confluence drawdown baseline - Confluence EA losing → contaminated Grid EA profit target check **Confidence in cascade logic: 91%** (each step individually confirmed in code; cascade requires both EAs active simultaneously) --- ## Part 5 — Opencode's Contribution Opencode's analyses were based on older git history (committed code, not working tree) and earlier Confluence performance data. Key usable insight: **Opencode: "Grid EA likely performs poorly in strong trends; Confluence excels in trends. Natural hedging."** This is partially correct but inverted for the current setup: - Grid EA WITH session filter (01:00–10:00) = Asia session = ranging = Grid works well - Confluence EA WITH inverted filter = only fires in trending conditions = London/NY = works poorly - Both EAs running together without session filter: **both perform in the wrong regime at the same time** — Grid places during trending hours and loses, Confluence fires during trending hours and loses, losses compound The "natural hedge" only works if Grid is truly restricted to ranging hours and Confluence to trending hours. Right now, neither is properly gated. --- ## Part 6 — Revised Priority List (synthesized from all agents) ### P0 — Code fixes required before any new preset changes **P0.1 — Move edge cleanup before session filter gate** (Claude finding) `OrdersEA_Smart_Grid.mq5:~1278` Current structure: ```cpp if(!CheckSessionFilter()) return; // Line 1279 — gates edge cleanup if(!CheckSpreadFilter()) return; // Line 1280 if(!IsRangingMarket()) { edge cleanup } // Line 1283 ``` Required structure: ```cpp // Edge cleanup: always active, gated only by bar-open { double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK); double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID); double aHigh = (InpManualHigh > 0) ? InpManualHigh : GridHigh; double aLow = (InpManualLow > 0) ? InpManualLow : GridLow; if(ask < aLow && aLow > 0) ClosePositionsBySide(POSITION_TYPE_BUY, "Edge cleanup — below GridLow"); else if(bid > aHigh && aHigh > 0) ClosePositionsBySide(POSITION_TYPE_SELL, "Edge cleanup — above GridHigh"); } if(!CheckSessionFilter()) return; // Now gates new grid placement only if(!CheckSpreadFilter()) return; if(!IsRangingMarket()) { cancel orders; return; } // No longer closes positions here ``` This separates position management from grid placement gating. **P0.2 — Fix drawdown baseline in BOTH EAs** (Kimi finding, code-verified) ```cpp // Both EAs, daily reset (Grid:340, Confluence:957): // FROM: dailyStartEquity = AccountInfoDouble(ACCOUNT_EQUITY); // TO: dailyStartEquity = AccountInfoDouble(ACCOUNT_BALANCE); // AND: capture this EA's own floating at reset double baselineFloating = GetFloatingPnL(); GlobalVariableSet(GvKey("baselineFloating"), baselineFloating); // Both EAs, daily check: // FROM: double dailyPnL = GetRealizedPnLToday() + floating; // TO: double baselineFloat = GlobalVariableGet(GvKey("baselineFloating")); double dailyPnL = GetRealizedPnLToday() + (floating - baselineFloat); ``` Same fix needed for weekly reset. Same fix needed for `cycleStartEquity` in Grid EA: ```cpp // Grid EA line 1445: // FROM: cycleStartEquity = AccountInfoDouble(ACCOUNT_EQUITY); // TO: cycleStartEquity = AccountInfoDouble(ACCOUNT_BALANCE) + GetFloatingPnL(); ``` **P0.3 — Fix Confluence EA inverted ranging filter** (Kimi finding, code-verified) ```cpp // MultiSignal_Confluence_EA.mq5:511-513 // FROM (inverted — harder to trade in ranging): double effectiveMinATR = ranging ? InpMinATRPercent * 1.5 : InpMinATRPercent; double effectiveMinADX = ranging ? InpMinADX + 5.0 : InpMinADX; // TO (correct — easier to trade in ranging, harder in trending): double effectiveMinATR = ranging ? InpMinATRPercent * 0.7 : InpMinATRPercent; double effectiveMinADX = ranging ? MathMax(0, InpMinADX - 5.0) : InpMinADX; ``` In ranging markets: lower ATR threshold (small moves are OK), lower ADX requirement (weak trend is expected and correct). This lets the reversal strategy fire in its optimal environment. **Confidence in inversion fix logic: 92%** — this is the correct direction; the exact multipliers may need tuning. --- ### P1 — Preset changes (after P0 code fixes) **P1.1 — Enable session filter on all older grid presets** Add to all 10 older grid presets: ```ini InpUseSessionFilter=true InpSessionStartHour=1 InpSessionEndHour=10 ``` **Only safe after P0.1 is deployed.** Without P0.1, enabling session filter causes 15-hour cleanup gaps. **P1.2 — Restore InpMinConfluence=2 on XAUUSD and EURJPY** The April 30 change to `InpMinConfluence=1` was made because Confluence was silent. The silence was caused by the ATR filter and inverted ranging filter (now fixed in P0.3). With P0.3 deployed, single-source signals are no longer needed to get trades. ```ini InpMinConfluence=2 ``` **P1.3 — Tighten RSI/ADX filters on grid presets** ```ini RSILower=30 RSIUpper=70 ADXMax=25 ``` These were loosened too far in April 27 rewrite. Tightening brings the filter closer to the original intent without reverting all the way to the over-strict 18/24 that caused the "no trades" complaint. **P1.4 — Add explicit v4.1 controls to all older presets** From the April 23 preset mismatch audit, still unresolved: older presets need explicit values for: ```ini InpUseBreakeven=false InpMaxSpreadPoints=30 InpMaxLongSymbols=0 InpMaxShortSymbols=0 InpRelaxFilterAfterDays=3 InpRangeDriftEnable=false InpAdaptiveEntry=false InpUseStopLoss=false ``` --- ### P2 — Risk posture review (deferred, requires data) **P2.1 — Lot size review** The 0.01→0.03 lot increase was not a calculated decision. After implementing P0 and P1 fixes, run one week at 0.03 lots and measure per-trade loss distribution from edge cleanup. If edge cleanup losses average > −$5 per trade, reduce to 0.02 lots. Keep 0.03 if losses stay < −$3 per trade. **P2.2 — Commit working tree** 6+ weeks of changes exist only in the working tree. This is a data-loss risk that is independent of all trading logic. Commit before the next live session. --- ## Part 7 — Confidence Summary (Final) | Claim | Confidence | Source | |-------|-----------|--------| | Edge cleanup v5.0 causes the frequent small losses | 97% | Claude, Kimi | | ASK/BID asymmetry: BUY at GridLow fires via spread on next bar | 90% | Claude only | | Session filter blocks edge cleanup in off-hours | 97% | Claude only | | Confluence EA inverted ranging filter | 96% | Kimi, code-verified | | Breakeven SL is on loss side (dormant) | 95% | Kimi, code-verified | | Drawdown baselines use whole-account equity (both EAs) | 99% | All agents | | Lot tripling is frustration-driven risk escalation | 97% | Kimi, data-verified | | Compound EA contamination cascade is active when both run | 91% | Claude synthesis | | Confluence fires only in trending conditions (inverted filter) | 96% | Code-verified | | "Enable session filter" incomplete without moving cleanup block | 97% | Claude | | InpMinConfluence=1 on XAUUSD/EURJPY amplifies trending-market risk | 90% | Claude+Kimi | | Fix checklist from Apr 23 is >90% unimplemented | 95% | Kimi | **Aggregate confidence in the full diagnosis: 94%** The 6% gap comes from: - Unknown actual bounce rate at S1 after bar-close (requires log data) - Unknown whether live MT5 charts reloaded presets after April 27 rewrite - Unknown live performance of Confluence EA after InpMinConfluence change --- ## Part 8 — The Three Deepest Structural Issues After synthesizing four analyses across three agents: **1. The EAs run in the wrong regimes for each other** Grid EA (mean reversion) needs Asia ranging. Confluence EA (pivot reversal) also needs ranging. Both are currently running 24/7 with no session gating. In trending London/NY sessions: Grid places grids that get edge-cleaned, Confluence fires reversals that fail. Both lose simultaneously. The fix is not just "enable session filter" — it's recognizing that both strategies need ranging conditions, and restricting both to those conditions. **2. The drawdown architecture creates phantom signals** Both EAs use whole-account equity as their baseline. When one EA has floating losses, the other EA's drawdown margin appears consumed. When one EA has floating profits that then close, the other EA's profit target appears hit. The EAs react to each other's P&L as if it were their own. True isolation requires `ACCOUNT_BALANCE + own_floating` as the baseline for both. **3. The strategy is structurally risk-escalated after a mechanical fix** The $60K loss from the clustering bug was a mechanical failure. The mechanical fix (MaxLevels + edge cleanup + one-fill-per-side) was correct. But the system responded by tripling lot size, relaxing filters, and raising DD limits — all simultaneously. The result is a system that is now more exposed to a different failure mode: correct mechanics, wrong market regime (trending), 3× the loss per event. --- *Analysis complete. Aggregate confidence: 94%.* *Three agents, four documents, one code base.* *Session recorded: 2026-05-13*