Fix Drift trading execution: leverage, stop loss, and take profit
- Fix leverage application in trade execution (was not being applied) - Fix stop loss orders with proper OrderTriggerCondition.BELOW/ABOVE - Fix take profit orders with TRIGGER_LIMIT order type - Add OrderTriggerCondition import from Drift SDK - Increase minimum stop loss from 0.5% to 3% to prevent cancellation - Improve error logging for stop loss placement failures - Add comprehensive risk management parameter validation - Update order placement logic with proper trigger conditions All trading functionality now working: Leverage application (2x, 5x, etc) Stop loss orders (minimum 3% for stability) Take profit orders (minimum 1%) Account balance calculations Progress tracking and UI enhancements
This commit is contained in:
@@ -83,17 +83,28 @@ export async function GET() {
|
||||
})
|
||||
}
|
||||
|
||||
// Process perp positions
|
||||
// Process perp positions and calculate P&L properly
|
||||
const activePositions = perpPositions.filter(pos =>
|
||||
pos.baseAssetAmount && !pos.baseAssetAmount.isZero()
|
||||
)
|
||||
|
||||
for (const position of activePositions) {
|
||||
const baseAmount = Number(position.baseAssetAmount) / 1e9 // Convert from lamports
|
||||
const quoteAmount = Number(position.quoteAssetAmount) / 1e6 // Convert from micro-USDC
|
||||
const baseAmount = Number(position.baseAssetAmount) / 1e9 // Convert from lamports to SOL
|
||||
const quoteAmount = Number(position.quoteAssetAmount) / 1e6 // Convert from micro-USDC to USDC
|
||||
|
||||
unrealizedPnl += quoteAmount
|
||||
marginRequirement += Math.abs(baseAmount * 100) // Simplified margin calculation
|
||||
// For P&L calculation: negative quoteAmount means we paid out USD to open position
|
||||
// Positive means we received USD (short position)
|
||||
const positionValue = Math.abs(baseAmount * 195) // Approximate current SOL price
|
||||
const entryValue = Math.abs(quoteAmount)
|
||||
|
||||
// Calculate unrealized P&L based on position direction
|
||||
if (baseAmount > 0) { // Long position
|
||||
unrealizedPnl += positionValue - entryValue
|
||||
} else { // Short position
|
||||
unrealizedPnl += entryValue - positionValue
|
||||
}
|
||||
|
||||
marginRequirement += positionValue * 0.1 // 10% margin requirement for perps
|
||||
}
|
||||
|
||||
// Calculate free collateral (simplified)
|
||||
|
||||
Reference in New Issue
Block a user