Add /close command and auto-flip logic with order cleanup
- Added /close Telegram command for full position closure - Updated /reduce to accept 10-100% (was 10-90%) - Implemented auto-flip logic: automatically closes opposite position when signal reverses - Fixed risk check to allow opposite direction trades (signal flips) - Enhanced Position Manager to cancel orders when removing trades - Added startup initialization for Position Manager (restores trades on restart) - Fixed analytics to show stopped-out trades (manual DB update for orphaned trade) - Updated reduce endpoint to route 100% closes through closePosition for proper cleanup - All position closures now guarantee TP/SL order cancellation on Drift
This commit is contained in:
@@ -60,16 +60,65 @@ export async function POST(request: NextRequest): Promise<NextResponse<ReducePos
|
||||
|
||||
const reducePercent = body.reducePercent || 50 // Default: close 50%
|
||||
|
||||
if (reducePercent < 10 || reducePercent > 90) {
|
||||
if (reducePercent < 10 || reducePercent > 100) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: 'Reduce percent must be between 10 and 90',
|
||||
message: 'Reduce percent must be between 10 and 100',
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// If reducing 100%, use the close endpoint logic instead
|
||||
if (reducePercent === 100) {
|
||||
// Get Position Manager
|
||||
const positionManager = await getInitializedPositionManager()
|
||||
const activeTrades = positionManager.getActiveTrades()
|
||||
const trade = activeTrades.find(t => t.id === body.tradeId)
|
||||
|
||||
if (!trade) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: `Position ${body.tradeId} not found`,
|
||||
},
|
||||
{ status: 404 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log(`🔴 Closing 100% of position: ${trade.symbol}`)
|
||||
|
||||
// Initialize Drift service
|
||||
await initializeDriftService()
|
||||
|
||||
// Close entire position (this will automatically cancel all orders)
|
||||
const closeResult = await closePosition({
|
||||
symbol: trade.symbol,
|
||||
percentToClose: 100,
|
||||
slippageTolerance: getMergedConfig().slippageTolerance,
|
||||
})
|
||||
|
||||
if (!closeResult.success) {
|
||||
throw new Error(`Failed to close position: ${closeResult.error}`)
|
||||
}
|
||||
|
||||
console.log(`✅ Position fully closed | P&L: $${closeResult.realizedPnL || 0}`)
|
||||
console.log(`✅ All TP/SL orders cancelled automatically`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Position closed 100%`,
|
||||
closedSize: trade.positionSize,
|
||||
remainingSize: 0,
|
||||
closePrice: closeResult.closePrice,
|
||||
realizedPnL: closeResult.realizedPnL,
|
||||
newTP1: 0,
|
||||
newTP2: 0,
|
||||
newSL: 0,
|
||||
})
|
||||
}
|
||||
|
||||
// Get current configuration
|
||||
const config = getMergedConfig()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user