feat: Add on-chain TP/SL order placement

- Add placeExitOrders() to create reduce-only LIMIT orders for TP1, TP2, and SL
- Orders now visible in Drift UI
- Tested with real tiny position (0 base x 5x = 0)
- All 3 exit orders placed successfully on-chain
- Position manager continues monitoring as backup
- Added test script and results documentation
This commit is contained in:
mindesbunister
2025-10-26 13:30:07 +01:00
parent 993ae64c64
commit 4cc294baef
6 changed files with 365 additions and 17 deletions

View File

@@ -7,7 +7,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { initializeDriftService } from '@/lib/drift/client'
import { openPosition } from '@/lib/drift/orders'
import { openPosition, placeExitOrders } from '@/lib/drift/orders'
import { normalizeTradingViewSymbol } from '@/config/trading'
import { getMergedConfig } from '@/config/trading'
import { getPositionManager, ActiveTrade } from '@/lib/trading/position-manager'
@@ -192,9 +192,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
console.log('✅ Trade added to position manager for monitoring')
// TODO: Save trade to database (add Prisma integration later)
// Create response object
const response: ExecuteTradeResponse = {
success: true,
positionId: openResult.transactionSignature,
@@ -212,6 +210,35 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
timestamp: new Date().toISOString(),
}
// Place on-chain TP/SL orders so they appear in Drift UI (reduce-only LIMIT orders)
try {
const exitRes = await placeExitOrders({
symbol: driftSymbol,
positionSizeUSD: positionSizeUSD,
tp1Price,
tp2Price,
stopLossPrice,
tp1SizePercent: config.takeProfit1SizePercent || 50,
tp2SizePercent: config.takeProfit2SizePercent || 100,
direction: body.direction,
})
if (!exitRes.success) {
console.error('❌ Failed to place on-chain exit orders:', exitRes.error)
} else {
console.log('📨 Exit orders placed on-chain:', exitRes.signatures)
}
// Attach signatures to response when available
if (exitRes.signatures && exitRes.signatures.length > 0) {
;(response as any).exitOrderSignatures = exitRes.signatures
}
} catch (err) {
console.error('❌ Unexpected error placing exit orders:', err)
}
// TODO: Save trade to database (add Prisma integration later)
console.log('✅ Trade executed successfully!')
return NextResponse.json(response)