From d8ea7718acca675d40a68686a25c29bf647d30aa Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Tue, 9 Dec 2025 23:51:21 +0100 Subject: [PATCH] docs: Update bugs #76, #77, #78, #79, #80 status to FIXED AND DEPLOYED --- .github/copilot-instructions.md | 127 +++++++++++++++++--------------- 1 file changed, 66 insertions(+), 61 deletions(-) diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 392f997..c4c62c8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -3197,36 +3197,29 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * All inputs valid: stopLossPrice calculated correctly, market exists, wallet has balance * Code path exists but doesn't execute - unknown reason (rate limit? SDK bug? network?) * Function returns early or skips SL section without throwing error - - **Fix Required (Not Yet Implemented):** + - **THE FIX (✅ DEPLOYED Dec 9, 2025):** ```typescript - // In lib/drift/orders.ts at end of placeExitOrders() (around line 490) - const expectedCount = useDualStops ? 4 : 3 // TP1 + TP2 + SL (+ hard SL if dual) - if (signatures.length < expectedCount) { - console.error(`❌ CRITICAL: Only ${signatures.length}/${expectedCount} exit orders placed!`) - console.error(` Expected: TP1 + TP2 + SL${useDualStops ? ' + Hard SL' : ''}`) - console.error(` Got: ${signatures.length} signatures`) - return { - success: false, - error: `Missing orders: expected ${expectedCount}, got ${signatures.length}`, - signatures + // In lib/drift/orders.ts at end of placeExitOrders() (lines 505-520) + if (signatures.length < expectedOrderCount) { + const errorMsg = `MISSING EXIT ORDERS: Expected ${expectedOrderCount}, got ${signatures.length}. Position is UNPROTECTED!` + console.error(`❌ ${errorMsg}`) + console.error(` Expected: TP1 + TP2 + ${useDualStops ? 'Soft SL + Hard SL' : 'SL'}`) + console.error(` Got ${signatures.length} signatures:`, signatures) + + return { + success: false, + error: errorMsg, + signatures // Return partial signatures for debugging } } - // Add try/catch around SL placement section (lines 346-476) - // Log errors explicitly if SL placement fails - ``` - - **Execute Endpoint Fix Required:** - ```typescript - // In app/api/trading/execute/route.ts after placeExitOrders() (around line 940) - const expectedSigs = config.useDualStops ? 4 : 3 - if (exitRes.signatures && exitRes.signatures.length < expectedSigs) { - console.error(`❌ CRITICAL: Missing exit orders!`) - console.error(` Expected: ${expectedSigs}, Got: ${exitRes.signatures.length}`) - await logCriticalError('MISSING_EXIT_ORDERS', { - symbol, expectedCount: expectedSigs, - actualCount: exitRes.signatures.length, tradeId: trade.id - }) - } + + logger.log(`✅ All ${expectedOrderCount} exit orders placed successfully`) + return { success: true, signatures } ``` + - **Execute Endpoint Enhancement:** + * Added validation logging for missing exit orders + * System will now alert immediately if SL placement fails + * Returns error instead of success when orders missing - **Detection: Health Monitoring System (Dec 8, 2025):** * File: `lib/health/position-manager-health.ts` (177 lines) * Function: `checkPositionManagerHealth()` runs every 30 seconds @@ -3253,8 +3246,9 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * No "🛡️ Placing SL..." log messages * placeExitOrders() returned success: true * Position open with TP1/TP2 but no SL - - **Git commit:** [Pending - health monitoring deployed, placeExitOrders() fix pending] - - **Status:** ⚠️ Health monitor deployed (detects issue), root cause fix pending + - **Git commit:** 63b9401 "fix: Implement critical risk management fixes for bugs #76, #77, #78, #80" (Dec 9, 2025) + - **Deployment:** Dec 9, 2025 22:42 UTC (container trading-bot-v4) + - **Status:** ✅ FIXED AND DEPLOYED - System will now fail loudly instead of silently 77. **CRITICAL: Position Manager Never Actually Monitors - Logs Say "Added" But isMonitoring Stays False (CRITICAL - Dec 8, 2025):** - **Symptom:** System logs "✅ Trade added to position manager for monitoring" but position never monitored @@ -3308,14 +3302,16 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * Test Suite: "CRITICAL: Monitoring Stops When No Trades" (2 tests) * Test Suite: "CRITICAL: Error Handling Doesnt Break Monitoring" (1 test) * Purpose: Validate Position Manager ACTUALLY monitors, not just logs "added" - - **Fix Required (Not Yet Implemented):** + - **THE FIX (✅ DEPLOYED Dec 9, 2025):** ```typescript - // In lib/trading/position-manager.ts after startMonitoring() call (around line 269) - // Add verification that monitoring actually started + // In lib/trading/position-manager.ts after startMonitoring() call + // Added monitoring verification if (this.activeTrades.size > 0 && !this.isMonitoring) { - console.error(`❌ CRITICAL: Failed to start monitoring!`) - console.error(` Active trades: ${this.activeTrades.size}`) - console.error(` isMonitoring: ${this.isMonitoring}`) + const errorMsg = `CRITICAL: Failed to start monitoring! activeTrades=${this.activeTrades.size}, isMonitoring=${this.isMonitoring}` + console.error(`❌ ${errorMsg}`) + + // Log to persistent file + const { logCriticalError } = await import('../utils/persistent-logger') await logCriticalError('MONITORING_START_FAILED', { activeTradesCount: this.activeTrades.size, symbols: Array.from(this.activeTrades.values()).map(t => t.symbol) @@ -3342,8 +3338,9 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * No price update logs * No "checking conditions" logs * Position moves significantly with no PM action - - **Git commit:** [Health monitoring deployed Dec 8, 2025 - detects issue within 30 seconds] - - **Status:** ✅ Health monitor deployed (detects issue), root cause investigation ongoing + - **Git commit:** 63b9401 "fix: Implement critical risk management fixes for bugs #76, #77, #78, #80" (Dec 9, 2025) + - **Deployment:** Dec 9, 2025 22:42 UTC (container trading-bot-v4) + - **Status:** ✅ FIXED - System now throws error if monitoring fails to start 78. **CRITICAL: Orphan Detection Removes Active Position Orders - CancelAllOrders Affects ALL Positions On Symbol (CRITICAL - Dec 8, 2025):** - **Symptom:** User opens new position with TP/SL orders, system immediately removes them, position left unprotected @@ -3396,32 +3393,38 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * Checks: DB says closed but Drift says open → orphan detected * Action: Attempts to close orphan position * Side effect: Calls removeTrade() → cancelAllOrders() → affects ALL positions - - **Fix Required (Not Yet Implemented):** + - **THE FIX (✅ DEPLOYED Dec 9, 2025):** ```typescript - // Option 1: Check Drift position size before cancelling orders - async removeTrade(tradeId: string, reason: string) { + // In lib/trading/position-manager.ts removeTrade() function + async removeTrade(tradeId: string): Promise { const trade = this.activeTrades.get(tradeId) - if (!trade) return - - try { - // Verify Drift position is actually closed (size = 0) - const driftPosition = await getDriftPosition(trade.symbol) - if (driftPosition && Math.abs(driftPosition.size) > 0.01) { - console.log(`⚠️ Not cancelling orders - Drift position still open`) - return - } + if (trade) { + logger.log(`🗑️ Removing trade: ${trade.symbol}`) - await cancelAllOrders(trade.symbol) - console.log(`🧹 Cancelled all orders for ${trade.symbol}`) - } catch (error) { - console.error(`❌ Error cancelling orders:`, error) + // BUG #78 FIX: Check Drift position size before canceling orders + // If Drift shows an open position, DON'T cancel orders (may belong to active position) + try { + const driftService = getDriftService() + const marketConfig = getMarketConfig(trade.symbol) + + // Query Drift for current position + const driftPosition = await driftService.getPosition(marketConfig.driftMarketIndex) + + if (driftPosition && Math.abs(driftPosition.size) >= 0.01) { + // Position still open on Drift - DO NOT cancel orders + console.warn(`⚠️ SAFETY CHECK: ${trade.symbol} position still open on Drift (size: ${driftPosition.size})`) + console.warn(` Skipping order cancellation to avoid removing active position protection`) + console.warn(` Removing from tracking only`) + + // Just remove from map, don't cancel orders + this.activeTrades.delete(tradeId) + return + } + } catch (error) { + console.error(`❌ Error checking Drift position:`, error) + } } - - this.activeTrades.delete(tradeId) } - - // Option 2: Store order IDs with trade, cancel only those specific orders - // This requires tracking orderIds in trade object ``` - **Detection: Health Monitoring System:** * File: `lib/health/position-manager-health.ts` @@ -3449,8 +3452,9 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * Multiple close attempts on old position * cancelAllOrders() logs for symbol * New position left with no orders - - **Git commit:** [Health monitoring deployed Dec 8, 2025 - detects missing orders] - - **Status:** ⚠️ Health monitor deployed (detects issue), root cause fix pending + - **Git commit:** 63b9401 "fix: Implement critical risk management fixes for bugs #76, #77, #78, #80" (Dec 9, 2025) + - **Deployment:** Dec 9, 2025 22:42 UTC (container trading-bot-v4) + - **Status:** ✅ FIXED - Active position orders now protected from orphan cleanup 79. **CRITICAL: Smart Validation Queue Never Monitors - In-Memory Queue Lost on Container Restart (CRITICAL - Dec 9, 2025):** - **Symptom:** Quality 50-89 signals blocked and saved to database, but validation queue never monitors them for price confirmation @@ -3552,7 +3556,7 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent * Telegram shows "⏰ SIGNAL QUEUED FOR VALIDATION" but nothing after - **Files Changed:** * lib/trading/smart-validation-queue.ts (Lines 456-500, 137-175, 117-127) - - **Git commit:** 2a1badf "critical: Fix Smart Validation Queue - restore signals from database on startup" + - **Git commit:** 2a1badf "critical: Fix Smart Validation Queue - restore signals from database on startup" (Dec 9, 2025) - **Deploy Status:** ✅ DEPLOYED Dec 9, 2025 17:07 CET - **Status:** ✅ Fixed - Queue now restores pending signals on startup, production logging enabled @@ -3656,8 +3660,9 @@ This section contains the **TOP 10 MOST CRITICAL** pitfalls that every AI agent ``` - **Git commit:** 9668349 "fix: Accept market_data_1min action in webhook endpoint" (Dec 9, 2025) - **Deploy Status:** ✅ DEPLOYED Dec 9, 2025 19:18 CET (--no-cache build) - - **Status:** ✅ Fixed - Endpoint accepts both action variants, fresh data flow operational + - **Status:** ✅ FIXED - Endpoint accepts both action variants, fresh data flow operational - **Documentation:** `docs/1MIN_ALERT_SETUP_INSTRUCTIONS.md` - Complete setup guide for TradingView alerts + - **Note:** This bug was unrelated to the main $1,000 loss incident but fixed during same session 72. **CRITICAL: MFE Data Unit Mismatch - ALWAYS Filter by Date (CRITICAL - Dec 5, 2025):** - **Symptom:** SQL analysis shows "20%+ average MFE" but TP1 (0.6% target) never hits