diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 891cb73..0d47d97 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1906,6 +1906,42 @@ trade.realizedPnL += actualRealizedPnL // NOT: result.realizedPnL from SDK - **Git commit:** 528a0f4 "fix: Use Drift's actual entry price for breakeven SL" - **Lesson:** For critical price calculations (breakeven, TP, SL), always prefer on-chain data over cached database values +45. **100% position sizing causes InsufficientCollateral (Fixed Nov 16, 2025):** + - **Symptom:** Bot configured for 100% position size gets InsufficientCollateral errors, but Drift UI can open same size position + - **Root Cause:** Drift's margin calculation includes fees, slippage buffers, and rounding - exact 100% leaves no room + - **Error details:** + ``` + Program log: total_collateral=85547535 ($85.55) + Program log: margin_requirement=85583087 ($85.58) + Error: InsufficientCollateral (shortage: $0.03) + ``` + - **Real incident (Nov 16, 01:50 CET):** + * Collateral: $85.55 + * Bot tries: $1,283.21 notional (100% × 15x leverage) + * Drift UI works: $1,282.57 notional (has internal safety buffer) + * Difference: $0.64 causes rejection + - **Impact:** Bot cannot trade at full capacity despite account leverage correctly set to 15x + - **Fix:** Apply 99% safety buffer automatically when user configures 100% position size + ```typescript + // In config/trading.ts calculateActualPositionSize (line ~272): + let percentDecimal = configuredSize / 100 + + // CRITICAL: Safety buffer for 100% positions + if (configuredSize >= 100) { + percentDecimal = 0.99 + console.log(`⚠️ Applying 99% safety buffer for 100% position`) + } + + const calculatedSize = freeCollateral * percentDecimal + // $85.55 × 99% = $84.69 (leaves $0.86 for fees/slippage) + ``` + - **Result:** $84.69 × 15x = $1,270.35 notional (well within margin requirements) + - **User experience:** Transparent - bot logs "Applying 99% safety buffer" when triggered + - **Why Drift UI works:** Has internal safety calculations that bot must replicate externally + - **Math proof:** 1% buffer on $85 = $0.85 safety margin (covers typical fees of $0.03-0.10) + - **Git commit:** 7129cbf "fix: Add 99% safety buffer for 100% position sizing" + - **Lesson:** When integrating with DEX protocols, never use 100% of resources - always leave safety margin for protocol-level calculations + ## File Conventions - **API routes:** `app/api/[feature]/[action]/route.ts` (Next.js 15 App Router)