Files
mql-trading-bots/notes/Kimi_Code_CLI-Analysis_1-Recent_Changes_and_Vault_Synthesis.md
garfield 0894d18db4 WIP: 6+ weeks of uncommitted EA development and preset tuning
Confluence EA (v1.16 → v1.20):
- Per-EA realized P&L tracking via history deals
- Weekly drawdown protection
- Warmup bars, pivot cache, state persistence
- Point-scaled pivot thresholds, ranging ATR factor
- Market filling mode helper per symbol

Grid EA (v3.1 → v4.1):
- Adaptive filters, adaptive entry, spread filter
- Session filter, breakeven, correlation caps, range drift
- Profit protection (stop-after-profit, cycle reports)
- Edge cleanup v5.0 — close wrong-side positions outside grid
- Master one-shot shutdown, grid state persistence

Presets:
- Fix GetOut=Y shutdown bug on 4 grid presets
- Relax ADXMax 18→40, widen RSI 20/80 across grid presets
- Standardize daily drawdown 3%→5%, add weekly 10%
- Increase grid lots 0.01→0.03
- Normalize confluence ATR thresholds per pair
- Add XAGUSD, EURCHF, EURGBP, AUDNZD presets

Docs & DevOps:
- April 23 audit files (preset mismatch, code review, checklist)
- n8n workflow and validation infrastructure updates
- AI agent analyses in notes/

Known issues carried forward:
- Shared drawdown budget contamination (both EAs)
- Confluence ranging-market threshold inversion
- Older grid presets missing v4.1 safety controls
2026-05-12 09:02:25 -04:00

11 KiB
Raw Permalink Blame History

Kimi Code CLI — Analysis 1: Recent Changes & Vault Synthesis

Date: 2026-05-12 Scope: Uncommitted changes since last git commit (2026-03-30) + conversation history + audit files Confidence: 85% (will be refined in Analysis 2)


1. Executive Summary

The repository contains massive uncommitted evolution across both primary EAs and their preset files. The last git commit was 2026-03-30 (n8n/SSH workflow infrastructure). Since then, ~6+ weeks of trading system development exists only in the working tree. This represents significant risk: no version control, no rollback capability, and mixed fix states.

Key Evolution:

  • MultiSignal_Confluence_EA.mq5: v1.16 → v1.20 (per-EA realized P&L tracking, weekly drawdown, warmup, pivot cache, state persistence)
  • OrdersEA_Smart_Grid.mq5: v3.1 → v4.1 (massive architectural rewrite: adaptive filters, session filter, breakeven, correlation caps, range drift, state persistence, edge cleanup)
  • Presets: GetOut=Y emergency shutdown bug FIXED in working tree (was critical per Apr 23 audit). ADXMax relaxed from 18-25 → 40 on most grid presets. Lots standardized to 0.03.

2. MultiSignal_Confluence_EA.mq5 (v1.20) — Detailed Changes

2.1 New Inputs Added

Input Default Purpose
InpWarmupBars 20 Bars required before filters activate (prevents early-bar noise)
InpPivotThresholdPoints 100 Proximity threshold in POINTS for "near pivot" detection
InpRangingATRFactor 0.3 Ranging "near pivot" = ATR × factor
InpMaxWeeklyDrawdown 10.0 Weekly drawdown cap per-EA

2.2 Architecture Improvements

  • Per-EA realized P&L tracking: SumRealizedPnLSince() scans HistorySelect() filtered by DEAL_MAGIC + DEAL_SYMBOL. This is a genuine improvement over whole-account equity snapshots.
  • State persistence: GlobalVariableSet/Get for dailyStartEquity, lastEquityReset, weeklyStartEquity, lastWeeklyReset. Survives EA restart.
  • Warm-up guard: IsWarmedUp() requires InpWarmupBars bars + one full bar period since init. Prevents indicator-initialization gaps.
  • Pivot cache: Daily pivot values cached to avoid recalc every tick.
  • Market filling helper: GetMarketFilling() probes SYMBOL_FILLING_MODE per symbol, using IOC→FOK→RETURN fallback.
  • Structured logging: LogS() prefixes every message with [_Symbol:MagicNumber].

2.3 Drawdown Logic — PARTIALLY FIXED (Critical Finding)

// DAILY RESET — still uses WHOLE-ACCOUNT EQUITY
dailyStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);

// CHECK — uses PER-EA P&L
double dailyPnL = GetRealizedPnLToday() + floating;

Problem: The baseline is whole-account, but the measured P&L is per-EA. This is the "shared drawdown budget" contamination identified in 2026-04-03 conversation history. If Grid EA drops account equity by $4,000 overnight, Confluence EAs 5% limit shrinks from $5,000 → $4,750. If both EAs run together, Confluence gets penalized for Grids losses.

Severity: HIGH. Not fully fixed despite explicit intent.

2.4 Preset Changes (confluence-*.set)

  • InpRiskPercent: 1.0% → 1.5% (aggression increased)
  • InpMaxDailyDrawdown: 3.0% → 5.0% (relaxed)
  • InpMaxWeeklyDrawdown: 10.0% added
  • InpMinATRPercent: normalized per pair (EURUSD 0.3%, GBPJPY 0.5%, XAUUSD 0.7%, etc.)
  • InpMinADX: 18.022.0 range (was 2028)
  • InpWeekendCloseHour: varies by pair (EURUSD 14:00, others mostly 17:00)
  • InpDebugMode: true across all presets

Context: The Apr 7 diagnosis found ATR thresholds at 0.8% blocked ALL trades silently. The presets were corrected in this working tree.


3. OrdersEA_Smart_Grid.mq5 (v4.1) — Detailed Changes

3.1 Major New Features

Feature Description Risk Level
Adaptive Filters Relax ADX/lot size after InpRelaxFilterAfterDays of no trade Medium
Adaptive Entry Auto-scale grid spacing from ATR (InpEntryATRFactor) Medium
Spread Filter InpMaxSpreadPoints — blocks grid placement if spread too wide Low
Stop Loss Toggle InpUseStopLoss — opt-in SL (default false = original behavior) High if enabled
Session Filter InpUseSessionFilter — restrict trading to Asia hours (default false) Low
Breakeven Move remaining SLs to entry + buffer after first TP hits Medium
Correlation Cap InpMaxLongSymbols / InpMaxShortSymbols — limit cross-symbol exposure Low
Range Drift InpRangeDriftEnable — re-center grid when mid drifts N points Medium
Profit Protection InpStopAfterProfit — stop new grids after profitable cycle Low
Cycle Report Notification on cycle end Low
Master One-Shot masterShutdownDone prevents repeated master shutdown Low
Edge Cleanup (v5.0) Close wrong-side positions when price exits grid bounds High if wrong
State Persistence GlobalVariables for grid state, drawdown baselines, cycle data Low

3.2 Drawdown Logic — SAME CONTAMINATION BUG AS CONFLUENCE

// Grid EA also resets from whole-account equity
dailyStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
// But measures P&L per-EA via realized + floating

Same shared-drawdown-budget problem. The April 23 audit explicitly called this out. It is NOT fixed in the working tree.

3.3 Preset Evolution

  • GetOut=YGetOut=N on: GBPJPY, GBPUSD, USDJPY, XAUUSD. This was a critical fix.
  • Lots: 0.01 → 0.03 on most presets (3× position size increase)
  • ADXMax: relaxed to 40 on most (was very strict 1824; this addresses Apr 13 "filters too strict" complaint)
  • RSILower/Upper: widened to 20/80 on most (was 2535 / 6575)
  • InpMaxDailyDrawdown: standardized to 5.0%
  • InpMaxWeeklyDrawdown: 10.0% added

3.4 Unresolved Issues from April 23 Audit

  1. Older presets still missing v4.1 safety controls: grid-eurusd, grid-audusd, grid-usdcad, grid-usdchf, grid-nzdusd, grid-eurjpy do not define InpUseSessionFilter, InpMaxSpreadPoints, InpUseBreakeven, correlation caps, adaptive settings, or range drift. They fall back to source defaults.
  2. Same-side pending cancellation: When a BUY fills, remaining BUY_LIMITs are deleted. This may be intentional "one-fill-per-side" risk reduction, but contradicts the "multi-level averaging grid" expectation. Comments and behavior remain misaligned.
  3. Breakeven implementation: Sets SL to open - buffer (BUY) or open + buffer (SELL). This parks the stop on the loss side of entry, NOT at true breakeven or profit-lock. The Apr 23 review noted this.
  4. Cycle P&L contamination: cycleStartEquity captured from whole-account equity. If Confluence EA has floating P&L, Grid EAs cycle profit/stop logic is contaminated.

4. Vault Notes Integration

Conversation History Timeline

Date Key Finding Current Status
Mar 21 Stop-loss cross-symbol bug fixed (v1.11) Still in place
Mar 30 Weekend gap + short signal fixes (v1.14/v3.1) Evolved further
Apr 1 Grid clustering bug fixed, .set param names fixed Clustering fix still present
Apr 3 Grid EA caused ~$60K loss; equity at 47% ⚠️ Risk controls added but contamination persists
Apr 5 Grid EA shut down to free shared drawdown budget Grid later re-enabled with fixes
Apr 7 ATR thresholds 0.8% blocked ALL trades silently Fixed in presets (now 0.30.7%)
Apr 13 Grid filters too strict; user frustration ADXMax relaxed to 40, RSI widened
Apr 23 GetOut=Y preset bug, equity contamination, breakeven flaws ⚠️ GetOut fixed; contamination & breakeven NOT fixed

Audit Files Status

  • 2026-04-23 OrdersEA Smart Grid - Fix Checklist.md: 15 items. Most code-fix items remain unchecked in working tree.
  • 2026-04-23 OrdersEA Smart Grid - Preset Mismatch Audit.md: Preset values updated but structural mismatch (missing v4.1 controls) remains.
  • 2026-04-23 OrdersEA Smart Grid - Read-Only Code Review.md: 6 findings. Only 1 (GetOut=Y) clearly fixed.

5. Cross-Cutting Risks

5.1 Version Control Risk (CRITICAL)

~1,900 lines of diff across 57 files exist ONLY in the working tree. If the server crashes or files are overwritten, weeks of development vanish. This includes:

  • The GetOut=Y fix
  • The ATR threshold fix
  • The ADX relaxation
  • The per-EA realized P&L tracking
  • The v4.1 architecture rewrite

Recommendation: git add + git commit immediately after review.

5.2 Compounding Risk from 3× Lot Increase

Grid presets moved from 0.01 → 0.03 lots. With MaxLevels=5 and potential multi-chart deployment, total grid exposure could be significant. The daily drawdown was also relaxed (3% → 5%). This is a more aggressive risk posture.

5.3 Silent Failure Path Still Exists

Both EAs have InpDebugMode=true in presets currently. If a future session turns this off, filter blocks become silent again (the Apr 7 root cause). The code structure still gates filter-block prints behind if(InpDebugMode).

5.4 State Persistence Conflicts

Both EAs use GlobalVariableSet with keys like "Confluence_" + MagicNumber + "_" + Symbol + "_dailyStartEquity". If two EAs accidentally share a MagicNumber, state collides. The keys are sufficiently namespaced but rely on MagicNumber uniqueness per symbol.


6. Immediate Action Items (Ranked)

Priority Action Rationale
🔴 P0 git commit all working tree changes Prevent data loss
🔴 P0 Fix shared drawdown budget contamination in BOTH EAs Root cause of Apr 3 crisis
🟡 P1 Normalize all older grid presets with explicit v4.1 controls Prevent silent fallback to risky defaults
🟡 P1 Clarify grid strategy intent: true multi-level vs one-fill-per-side Align code, comments, and presets
🟡 P1 Fix breakeven to actually lock at breakeven or profit, not loss-side Current implementation misleading
🟢 P2 Add per-ticket retry backoff to PositionModify() Prevent log floods
🟢 P2 Fix adaptive relaxation for never-traded symbols lastTradePlacedTime == 0 blocks relaxation
🟢 P2 Add InpDebugMode safety check — ensure critical warnings bypass debug flag Prevent future silent failures

7. Confidence Assessment

Area Confidence Gap
Code change inventory 95% Large diff fully reviewed
Vault note synthesis 90% All conversation history + audit files read
Root cause identification 85% Shared drawdown confirmed; breakeven logic understood
Fix completeness assessment 80% Cannot guarantee all edge cases without compilation + backtest
Live MT5 state 60% No live log access in this session; assuming presets match repo

Overall Confidence: 85% — Analysis 2 will apply first-principles reasoning to push above 90%.