diff --git a/app/api/automation/position-monitor/route.js b/app/api/automation/position-monitor/route.js index a91c2ed..dad09af 100644 --- a/app/api/automation/position-monitor/route.js +++ b/app/api/automation/position-monitor/route.js @@ -98,9 +98,13 @@ export async function GET() { if (activeOrders.length > 0) { console.log('📋 No active positions detected - checking for truly orphaned orders...'); - // Filter for truly orphaned orders (non-reduce-only orders without positions) - // Do NOT clean up reduce-only orders as these could be legitimate SL/TP from recently closed positions - const trulyOrphanedOrders = activeOrders.filter(order => !order.reduceOnly); + // Filter for truly orphaned orders (ONLY non-reduce-only orders without positions) + // 🛡️ CRITICAL: NEVER clean up reduce-only orders as these are SL/TP protecting positions + const trulyOrphanedOrders = activeOrders.filter(order => { + // Only consider non-reduce-only orders for cleanup + // Reduce-only orders (SL/TP) should NEVER be automatically canceled + return !order.reduceOnly + }); if (trulyOrphanedOrders.length > 0) { console.log(`🎯 Found ${trulyOrphanedOrders.length} truly orphaned orders (non-reduce-only) - triggering cleanup...`); diff --git a/app/api/drift/cleanup-orders/route.js b/app/api/drift/cleanup-orders/route.js index 524aa9c..8dbc736 100644 --- a/app/api/drift/cleanup-orders/route.js +++ b/app/api/drift/cleanup-orders/route.js @@ -99,9 +99,14 @@ export async function POST() { // Check if this order is for a market where we have no position const hasPosition = positionMarkets.has(order.marketIndex) - // CORRECTED LOGIC: Cancel ALL orders when no position exists - // If we have no position, then ALL orders (including SL/TP) are orphaned - return !hasPosition + // 🛡️ CRITICAL FIX: Only cancel non-reduce-only orders when no position exists + // NEVER cancel reduce-only orders (SL/TP) as they protect existing positions + if (!hasPosition) { + // Only cancel orders that are NOT reduce-only (market makers, limit orders) + return !order.reduceOnly + } + + return false // Don't cancel any orders when position exists }) // Additionally, find lingering SL/TP orders when position has changed significantly diff --git a/prisma/prisma/dev.db b/prisma/prisma/dev.db index 8eb2371..fbdd063 100644 Binary files a/prisma/prisma/dev.db and b/prisma/prisma/dev.db differ