🧹 Integrate orphaned order cleanup into position monitoring
FEATURES: - Position monitor now automatically detects orphaned orders when no positions - Triggers cleanup only when hasPosition: false to eliminate redundant polling - Provides detailed cleanup results in monitoring response - Leverages existing frequent position checks vs separate timers - Modified /app/api/automation/position-monitor/route.js to check for orphaned orders - Calls existing /api/drift/cleanup-orders endpoint when no positions detected - Returns cleanup status, success/failure, and summary in monitoring response - Handles cleanup errors gracefully with detailed error reporting - Eliminates need for separate 60-second cleanup polling - Uses existing position monitoring infrastructure - Only runs cleanup when positions close (triggered by hasPosition: false) - Automatic handling of orphaned orders after SL/TP execution - Added test-orphaned-cleanup-integration.js for verification - Tests both position monitor integration and direct cleanup API - Provides detailed feedback on cleanup operations This completes the automation enhancement requested - no more manual cleanup needed!
This commit is contained in:
@@ -22,7 +22,8 @@ export async function GET() {
|
||||
stopLossProximity: null,
|
||||
riskLevel: 'NONE',
|
||||
nextAction: 'No position to monitor',
|
||||
recommendation: 'START_TRADING'
|
||||
recommendation: 'START_TRADING',
|
||||
orphanedOrderCleanup: null
|
||||
};
|
||||
|
||||
if (positionsData.success && positionsData.positions.length > 0) {
|
||||
@@ -78,6 +79,84 @@ export async function GET() {
|
||||
result.nextAction = 'Standard monitoring - Check every 30 minutes';
|
||||
result.recommendation = 'RELAXED_MONITORING';
|
||||
}
|
||||
} else {
|
||||
// NO POSITION DETECTED - Check for orphaned orders and cleanup
|
||||
console.log('📋 No active positions detected - checking for orphaned orders...');
|
||||
|
||||
try {
|
||||
// Check for any remaining orders when we have no positions
|
||||
const ordersResponse = await fetch(`${baseUrl}/api/drift/orders`, {
|
||||
cache: 'no-store',
|
||||
headers: {
|
||||
'Cache-Control': 'no-cache'
|
||||
}
|
||||
});
|
||||
|
||||
if (ordersResponse.ok) {
|
||||
const ordersData = await ordersResponse.json();
|
||||
const activeOrders = ordersData.orders || [];
|
||||
|
||||
if (activeOrders.length > 0) {
|
||||
console.log(`🎯 Found ${activeOrders.length} orphaned orders - triggering cleanup...`);
|
||||
|
||||
// Trigger automated cleanup of orphaned orders
|
||||
const cleanupResponse = await fetch(`${baseUrl}/api/drift/cleanup-orders`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
let cleanupResult = null;
|
||||
if (cleanupResponse.ok) {
|
||||
cleanupResult = await cleanupResponse.json();
|
||||
|
||||
if (cleanupResult.success) {
|
||||
console.log('✅ Orphaned order cleanup completed:', cleanupResult.summary);
|
||||
result.orphanedOrderCleanup = {
|
||||
triggered: true,
|
||||
success: true,
|
||||
summary: cleanupResult.summary,
|
||||
message: `Cleaned up ${cleanupResult.summary.totalCanceled} orphaned orders`
|
||||
};
|
||||
result.nextAction = `Cleaned up ${cleanupResult.summary.totalCanceled} orphaned orders - Ready for new trade`;
|
||||
} else {
|
||||
console.error('❌ Orphaned order cleanup failed:', cleanupResult.error);
|
||||
result.orphanedOrderCleanup = {
|
||||
triggered: true,
|
||||
success: false,
|
||||
error: cleanupResult.error,
|
||||
message: 'Cleanup failed - Manual intervention may be needed'
|
||||
};
|
||||
result.nextAction = 'Cleanup failed - Check orders manually';
|
||||
}
|
||||
} else {
|
||||
console.error('❌ Failed to trigger cleanup API');
|
||||
result.orphanedOrderCleanup = {
|
||||
triggered: false,
|
||||
success: false,
|
||||
error: 'Cleanup API unavailable',
|
||||
message: 'Could not trigger automatic cleanup'
|
||||
};
|
||||
}
|
||||
} else {
|
||||
console.log('✅ No orphaned orders found');
|
||||
result.orphanedOrderCleanup = {
|
||||
triggered: false,
|
||||
success: true,
|
||||
message: 'No orphaned orders detected'
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch (cleanupError) {
|
||||
console.error('❌ Error during orphaned order check:', cleanupError);
|
||||
result.orphanedOrderCleanup = {
|
||||
triggered: false,
|
||||
success: false,
|
||||
error: cleanupError.message,
|
||||
message: 'Error checking for orphaned orders'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
|
||||
Reference in New Issue
Block a user