critical: Fix test endpoint violating database-first pattern (Common Pitfall #29)
- Moved positionManager.addTrade() to AFTER database save succeeds - Changed database error handling to return HTTP 500 (not silent fail) - Test endpoint now enforces same pattern as execute endpoint - Prevents untracked positions when database save fails - Root cause of trade manual-1763391075992 compounding to -19.43 Before: Test endpoint added to Position Manager first, saved to DB after After: Test endpoint saves to DB first, only adds to PM if DB succeeds Impact: No more untracked positions from test trades with failed DB saves
This commit is contained in:
@@ -243,13 +243,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<TestTrade
|
||||
lastUpdateTime: Date.now(),
|
||||
}
|
||||
|
||||
// Add to position manager for monitoring
|
||||
const positionManager = await getInitializedPositionManager()
|
||||
await positionManager.addTrade(activeTrade)
|
||||
|
||||
console.log('✅ Trade added to position manager for monitoring')
|
||||
|
||||
// Create response object
|
||||
// Create response object (prepare before database save)
|
||||
const response: TestTradeResponse = {
|
||||
success: true,
|
||||
positionId: openResult.transactionSignature,
|
||||
@@ -334,10 +328,27 @@ export async function POST(request: NextRequest): Promise<NextResponse<TestTrade
|
||||
|
||||
console.log('💾 Trade saved to database')
|
||||
} catch (dbError) {
|
||||
console.error('❌ Failed to save trade to database:', dbError)
|
||||
// Don't fail the trade if database save fails
|
||||
console.error('❌ CRITICAL: Failed to save trade to database:', dbError)
|
||||
console.error(' Position is OPEN on Drift but NOT tracked!')
|
||||
console.error(' Manual intervention required - close position immediately')
|
||||
|
||||
// CRITICAL: If database save fails, we MUST NOT add to Position Manager
|
||||
// Return error to user so they know to close manually
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: 'Database save failed - position unprotected',
|
||||
message: `Position opened on Drift but database save failed. CLOSE POSITION MANUALLY IMMEDIATELY. Transaction: ${openResult.transactionSignature}`,
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
// Add to position manager for monitoring ONLY AFTER database save succeeds
|
||||
const positionManager = await getInitializedPositionManager()
|
||||
await positionManager.addTrade(activeTrade)
|
||||
|
||||
console.log('✅ Trade added to position manager for monitoring')
|
||||
console.log('✅ Test trade executed successfully!')
|
||||
|
||||
return NextResponse.json(response)
|
||||
|
||||
Reference in New Issue
Block a user