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
This commit is contained in:
122
app/api/drift/trading-info/route.ts
Normal file
122
app/api/drift/trading-info/route.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
44
app/api/test-captcha/route.ts
Normal file
44
app/api/test-captcha/route.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { tradingViewAutomation } from '../../../lib/tradingview-automation'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
console.log('🧪 Testing manual CAPTCHA interaction...')
|
||||
|
||||
// Initialize browser with manual CAPTCHA support
|
||||
await tradingViewAutomation.init()
|
||||
|
||||
// Try a login that will likely trigger CAPTCHA
|
||||
const loginResult = await tradingViewAutomation.smartLogin()
|
||||
|
||||
return NextResponse.json({
|
||||
success: loginResult,
|
||||
message: loginResult ? 'Login successful!' : 'Login failed or CAPTCHA interaction required',
|
||||
timestamp: new Date().toISOString()
|
||||
})
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Manual CAPTCHA test failed:', error)
|
||||
return NextResponse.json({
|
||||
error: error.message,
|
||||
timestamp: new Date().toISOString()
|
||||
}, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
return NextResponse.json({
|
||||
message: 'Manual CAPTCHA test endpoint',
|
||||
instructions: [
|
||||
'1. Send a POST request to this endpoint to trigger login with manual CAPTCHA support',
|
||||
'2. If CAPTCHA is detected, a browser window will appear (non-headless mode)',
|
||||
'3. Manually click the "I am not a robot" checkbox',
|
||||
'4. Complete any additional challenges',
|
||||
'5. The automation will continue once CAPTCHA is solved'
|
||||
],
|
||||
environment: {
|
||||
allowManualCaptcha: process.env.ALLOW_MANUAL_CAPTCHA === 'true',
|
||||
display: process.env.DISPLAY
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user