# Trading Bot v4 - Critical Issues Found & Fixes ## Issue Summary Three critical issues discovered: 1. **5-minute chart triggered instead of 15-minute** - TradingView alert format issue 2. **SL orders not cancelled after winning trade** - Race condition + order calculation bug 3. **No runner position (20% should remain)** - TP2 size calculation bug --- ## Issue 1: Wrong Timeframe Triggered ### Problem - Trade executed on 5-minute chart signal - n8n workflow has correct filter for "15" timeframe - Filter checks: `timeframe === "15"` ### Root Cause - n8n extracts timeframe with regex: `/\.P\s+(\d+)/` - Looks for ".P 5" or ".P 15" in TradingView message - Defaults to '15' if no match found ### Solution **Check your TradingView alert message format:** Your alert should include the timeframe like this: ``` SOL buy .P 15 ``` The ".P 15" tells n8n it's a 15-minute chart. If you're sending: ``` SOL buy .P 5 ``` Then n8n will reject it (correctly filtering out 5-minute signals). **Verify n8n is receiving correct format by checking n8n execution logs.** --- ## Issue 2: SL Orders Not Cancelled ### Problem - After winning trade, 2 SL orders remain on Drift ($198.39 and $195.77) - Bot detected "position closed externally" but found "no orders to cancel" ### Root Cause **Race Condition in `/api/trading/execute`:** Current order of operations: 1. Open position ✅ 2. Add to Position Manager (starts monitoring immediately) ⚠️ 3. Place exit orders (TP1, TP2, SL) ⏰ If TP hits very fast (< 2-3 seconds): - Position Manager detects "external closure" while orders are still being placed - Tries to cancel orders that don't exist yet - Orders finish placing AFTER position is gone → orphaned orders ### Solution **Reorder operations: Place exit orders BEFORE starting monitoring** --- ## Issue 3: No Runner Position ### Problem - Config: `TAKE_PROFIT_2_SIZE_PERCENT=80` (should leave 20% runner) - Expected: TP1 closes 75% → TP2 closes 80% of remaining → 5% runner remains - Actual: Position 100% closed, no runner ### Root Cause **BUG in `/home/icke/traderv4/lib/drift/orders.ts` lines 232-233:** ```typescript const tp1USD = (options.positionSizeUSD * options.tp1SizePercent) / 100 const tp2USD = (options.positionSizeUSD * options.tp2SizePercent) / 100 ``` Both TP1 and TP2 are calculated as **percentages of ORIGINAL position**, not remaining! **With your settings (TP1=75%, TP2=80%, position=$80):** - TP1: 75% × $80 = $60 ✅ - TP2: 80% × $80 = $64 ❌ (should be 80% × $20 remaining = $16) - Total: $60 + $64 = $124 (exceeds position size!) Drift caps at 100%, so entire position closes. ### Solution **Fix TP2 calculation to use remaining size after TP1** --- ## Recommended Fixes ### Fix 1: TradingView Alert Format Update your TradingView alert to include ".P 15": ``` {{ticker}} {{strategy.order.action}} .P 15 ``` ### Fix 2 & 3: Code Changes See next files for implementation...