Files
trading_bot_v3/app/api/drift/trading-info/route.ts
mindesbunister b91d35ad60 Fix timeframe selection bug and syntax errors
- Fixed critical timeframe mapping bug where '4h' was interpreted as '4 minutes'
- Now prioritizes minute values: '4h' -> ['240', '240m', '4h', '4H']
- Added fallback mechanism to enter exact minutes (240) in custom interval input
- Fixed multiple syntax errors in tradingview-automation.ts:
  * Missing closing parentheses in console.log statements
  * Missing parentheses in writeFile and JSON.parse calls
  * Fixed import statements for fs and path modules
  * Added missing utility methods (fileExists, markCaptchaDetected, etc.)
- Enhanced timeframe selection with comprehensive hour mappings (1h, 2h, 4h, 6h, 12h)
- Added detailed logging for debugging timeframe selection
- Application now builds successfully without syntax errors
- Interval selection should work correctly for all common timeframes

Key improvements:
 4h chart selection now works correctly (240 minutes, not 4 minutes)
 All TypeScript compilation errors resolved
 Enhanced debugging output for timeframe mapping
 Robust fallback mechanisms for interval selection
 Docker integration and manual CAPTCHA handling maintained
2025-07-13 13:57:35 +02:00

123 lines
3.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { driftTradingService } from '../../../../lib/drift-trading'
export async function POST(request: NextRequest) {
try {
const { symbol, side, leverage } = await request.json()
console.log(`📊 Calculating trade requirements for ${symbol} ${side} with ${leverage}x leverage`)
// Get current account balance
const balance = await driftTradingService.getAccountBalance()
// Get current market price for the symbol
let marketPrice = 160 // Default SOL price
try {
// You could get real market price here from Drift or other price feeds
if (symbol === 'SOLUSD') {
marketPrice = 160 // Could be fetched from oracle
} else if (symbol === 'BTCUSD') {
marketPrice = 65000
} else if (symbol === 'ETHUSD') {
marketPrice = 3500
}
} catch (priceError) {
console.log('⚠️ Could not get market price, using default')
}
// Calculate position limits based on available collateral
const availableCollateral = balance.freeCollateral || balance.availableBalance || 0
const maxLeveragedValue = availableCollateral * (leverage || 1)
// Calculate max position size in tokens
const maxPositionSize = marketPrice > 0 ? maxLeveragedValue / marketPrice : 0
// Calculate margin requirement for this position size
const marginRequirement = maxLeveragedValue / (leverage || 1)
// Calculate estimated liquidation price (simplified)
const maintenanceMarginRatio = 0.05 // 5% maintenance margin
let estimatedLiquidationPrice = 0
if (side.toUpperCase() === 'LONG') {
estimatedLiquidationPrice = marketPrice * (1 - (1 / leverage) + maintenanceMarginRatio)
} else {
estimatedLiquidationPrice = marketPrice * (1 + (1 / leverage) - maintenanceMarginRatio)
}
const tradingCalculations = {
marketPrice,
availableCollateral,
maxPositionSize,
maxLeveragedValue,
marginRequirement,
estimatedLiquidationPrice,
leverage: leverage || 1,
symbol,
side: side.toUpperCase()
}
console.log(`📊 Trading calculations:`, tradingCalculations)
return NextResponse.json({
success: true,
calculations: tradingCalculations,
balance: {
totalCollateral: balance.totalCollateral,
freeCollateral: balance.freeCollateral,
availableBalance: balance.availableBalance,
marginRequirement: balance.marginRequirement,
netUsdValue: balance.netUsdValue
}
})
} catch (error: any) {
console.error('❌ Error calculating trade requirements:', error)
return NextResponse.json({
success: false,
error: error.message,
calculations: {
marketPrice: 0,
availableCollateral: 0,
maxPositionSize: 0,
maxLeveragedValue: 0,
marginRequirement: 0,
estimatedLiquidationPrice: 0,
leverage: 1,
symbol: 'UNKNOWN',
side: 'BUY'
}
}, { status: 500 })
}
}
export async function GET(request: NextRequest) {
try {
// Return basic trading info without specific calculations
const balance = await driftTradingService.getAccountBalance()
return NextResponse.json({
success: true,
balance: {
totalCollateral: balance.totalCollateral,
freeCollateral: balance.freeCollateral,
availableBalance: balance.availableBalance,
marginRequirement: balance.marginRequirement,
netUsdValue: balance.netUsdValue,
leverage: balance.leverage,
unrealizedPnl: balance.unrealizedPnl
},
message: 'Account balance retrieved successfully'
})
} catch (error: any) {
console.error('❌ Error getting trading info:', error)
return NextResponse.json({
success: false,
error: error.message
}, { status: 500 })
}
}