fix: resolve SL/TP order placement and orphaned cleanup issues

- Fixed Drift SDK initialization in place-order endpoint (NodeWallet vs Wallet)
- Added 2% minimum trigger distance validation in execute-drift endpoint
- Corrected orphaned order cleanup logic to cancel ALL orders when no position
- Resolved issue where SL/TP orders were immediately canceled due to insufficient distance
- Tested complete cycle: position entry → protective orders → orphaned cleanup

Orders now maintain proper 2% distance from market price and stay active.
Cleanup system correctly identifies and removes orphaned orders when positions close.
This commit is contained in:
mindesbunister
2025-07-28 17:51:21 +02:00
parent cf6fddc434
commit 16e0ed9e5f
4 changed files with 42 additions and 15 deletions

View File

@@ -216,11 +216,28 @@ export async function POST(request) {
console.log('✅ Drift order placed:', txSig)
// Validate trigger distances before placing SL/TP orders
const MIN_TRIGGER_DISTANCE_PERCENT = 2.0; // Minimum 2% distance from current price
// Set up stop loss and take profit if specified
let stopLossOrderId = null
let takeProfitOrderId = null
if (stopLoss) {
// Validate stop loss distance
const slDistance = Math.abs(stopLoss - currentPrice) / currentPrice * 100;
if (slDistance < MIN_TRIGGER_DISTANCE_PERCENT) {
console.warn(`⚠️ Stop loss too close: ${slDistance.toFixed(2)}% < ${MIN_TRIGGER_DISTANCE_PERCENT}% minimum`);
// Adjust stop loss to minimum distance
if (direction === PositionDirection.LONG) {
stopLoss = currentPrice * (1 - MIN_TRIGGER_DISTANCE_PERCENT / 100);
} else {
stopLoss = currentPrice * (1 + MIN_TRIGGER_DISTANCE_PERCENT / 100);
}
console.log(`🔧 Adjusted stop loss to: $${stopLoss.toFixed(4)} (${MIN_TRIGGER_DISTANCE_PERCENT}% distance)`);
}
try {
const stopLossParams = {
orderType: OrderType.TRIGGER_LIMIT,
@@ -243,6 +260,20 @@ export async function POST(request) {
}
if (takeProfit) {
// Validate take profit distance
const tpDistance = Math.abs(takeProfit - currentPrice) / currentPrice * 100;
if (tpDistance < MIN_TRIGGER_DISTANCE_PERCENT) {
console.warn(`⚠️ Take profit too close: ${tpDistance.toFixed(2)}% < ${MIN_TRIGGER_DISTANCE_PERCENT}% minimum`);
// Adjust take profit to minimum distance
if (direction === PositionDirection.LONG) {
takeProfit = currentPrice * (1 + MIN_TRIGGER_DISTANCE_PERCENT / 100);
} else {
takeProfit = currentPrice * (1 - MIN_TRIGGER_DISTANCE_PERCENT / 100);
}
console.log(`🔧 Adjusted take profit to: $${takeProfit.toFixed(4)} (${MIN_TRIGGER_DISTANCE_PERCENT}% distance)`);
}
try {
const takeProfitParams = {
orderType: OrderType.TRIGGER_LIMIT,