Files
trading_bot_v3/app/api/automation/trade/route.js
mindesbunister abc94c06e2 Fix position sizing and improve automation UI
Major fixes:
- Fixed position size calculation: converts USD amount to SOL tokens properly
- Fixed insufficient collateral error by using correct position sizing
- Added proper TP/SL parameter passing through automation chain
- Enhanced position sizing UI with balance percentage slider

Position Sizing Fixes:
- Convert 2 USD to SOL tokens using current price (2 ÷ 97.87 = ~0.162 SOL)
- Remove incorrect 32 SOL token calculation (was 32,000,000,000 base units)
- Use USD position value for perpetual futures trading correctly

Take Profit & Stop Loss Improvements:
- Pass TP/SL percentages from config through automation → trade → drift chain
- Use actual config percentages instead of hardcoded 2:1 ratio
- Enable proper risk management with user-defined TP/SL levels

UI/UX Enhancements:
- Remove redundant 'Risk Per Trade (%)' field that caused confusion
- Remove conflicting 'Auto-Size (%)' dropdown
- Keep clean balance percentage slider (10% - 100% of available balance)
- Simplify position sizing to: Balance % → Position Size → Leverage → TP/SL

Technical Changes:
- Update Drift API position calculation from SOL tokens to USD conversion
- Fix automation trade route parameter passing
- Clean up AutomationConfig interface
- Improve position size validation and safety margins

These changes enable proper leveraged perpetual futures trading with correct
position sizing, collateral usage, and automated TP/SL order placement.
2025-07-23 14:16:55 +02:00

146 lines
3.9 KiB
JavaScript

import { NextResponse } from 'next/server'
export async function POST(request) {
try {
console.log('🔄 Unified trading endpoint called...')
const {
dexProvider,
action,
symbol,
amount,
side,
leverage = 1,
stopLoss,
takeProfit,
stopLossPercent,
takeProfitPercent,
mode = 'SIMULATION'
} = await request.json()
// Validate required parameters
if (!dexProvider) {
return NextResponse.json({
success: false,
error: 'DEX provider not specified'
}, { status: 400 })
}
console.log(`📊 Trading request:`, {
dexProvider,
action,
symbol,
amount,
side,
leverage,
stopLoss,
takeProfit,
stopLossPercent,
takeProfitPercent,
mode
})
// For simulation mode, return mock data
if (mode === 'SIMULATION') {
console.log('🎭 Simulation mode - returning mock response')
return NextResponse.json({
success: true,
simulation: true,
dexProvider,
action,
result: {
transactionId: `sim_${Date.now()}`,
symbol,
side,
amount,
leverage,
mode: 'SIMULATION',
message: 'Simulated trade executed successfully'
}
})
}
// Route to appropriate DEX based on provider
let response
if (dexProvider === 'DRIFT') {
console.log('🌊 Routing to Drift Protocol...')
// Call Drift API with correct action for trading
const driftResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/drift/trade`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'place_order',
symbol: symbol.replace('USD', ''), // Convert SOLUSD to SOL
amount,
side,
leverage,
// Pass through stop loss and take profit parameters
stopLoss: stopLoss !== undefined ? stopLoss : true,
takeProfit: takeProfit !== undefined ? takeProfit : true,
riskPercent: stopLossPercent || 2, // Use actual stop loss percentage from config
takeProfitPercent: takeProfitPercent || 4 // Use actual take profit percentage from config
})
})
response = await driftResponse.json()
if (response.success) {
response.dexProvider = 'DRIFT'
response.leverageUsed = leverage
}
} else if (dexProvider === 'JUPITER') {
console.log('🪐 Routing to Jupiter DEX...')
// Call Jupiter API (you may need to implement this endpoint)
const jupiterResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/jupiter/trade`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action,
symbol,
amount,
side
})
})
if (jupiterResponse.ok) {
response = await jupiterResponse.json()
response.dexProvider = 'JUPITER'
response.leverageUsed = 1 // Jupiter is spot only
} else {
response = {
success: false,
error: 'Jupiter DEX integration not yet implemented',
dexProvider: 'JUPITER'
}
}
} else {
return NextResponse.json({
success: false,
error: `Unsupported DEX provider: ${dexProvider}`
}, { status: 400 })
}
console.log('✅ DEX response received:', response.success ? 'SUCCESS' : 'FAILED')
return NextResponse.json(response)
} catch (error) {
console.error('❌ Unified trading error:', error)
return NextResponse.json({
success: false,
error: 'Trading execution failed',
details: error.message
}, { status: 500 })
}
}