Fix automated trading display calculations

Fixed position size calculation: 00 investment now shows 00 position (was 04.76)
 Fixed token amount display: Now shows correct tokens (~0.996) for 00 investment (was 2.04)
 Corrected API route: /api/automation/analysis-details now returns 200 instead of 405

Technical changes:
- Updated route calculation logic: tradingAmount / trade.price for correct token amounts
- Fixed displayPositionSize to show intended investment amount
- Used Docker Compose v2 for container management
- Resolved Next.js module export issues

The API now correctly displays trade details matching user investment intentions.
This commit is contained in:
mindesbunister
2025-07-20 22:32:16 +02:00
parent 6ce4f364a9
commit 55cea00e5e
22 changed files with 1180 additions and 189 deletions

View File

@@ -60,6 +60,12 @@ class AggressiveCleanup {
return
}
// Check if auto cleanup is disabled (for development)
if (process.env.DISABLE_AUTO_CLEANUP === 'true') {
console.log('🚫 Auto cleanup disabled via DISABLE_AUTO_CLEANUP environment variable')
return
}
this.isRunning = true
const isDevelopment = process.env.NODE_ENV === 'development'
const cleanupType = isDevelopment ? 'gentle' : 'aggressive'
@@ -95,8 +101,8 @@ class AggressiveCleanup {
// In case of import errors, be extra cautious - only clean very old processes
if (isDevelopment) {
console.log('🔧 Development mode with import issues - skipping cleanup for safety')
return
console.log('🔧 Development mode with import issues - using aggressive cleanup to clear stuck processes')
// In development, if we can't check sessions, assume they're stuck and clean aggressively
}
}
@@ -248,48 +254,95 @@ class AggressiveCleanup {
// New method for on-demand cleanup after complete automation cycle
async runPostAnalysisCleanup(): Promise<void> {
// Check if auto cleanup is disabled (for development)
if (process.env.DISABLE_AUTO_CLEANUP === 'true') {
console.log('🚫 Post-analysis cleanup disabled via DISABLE_AUTO_CLEANUP environment variable')
return
}
console.log('🧹 Post-cycle cleanup triggered (analysis + decision complete)...')
// Wait for all browser processes to fully close
console.log('⏳ Waiting 5 seconds for all processes to close gracefully...')
await new Promise(resolve => setTimeout(resolve, 5000))
console.log('⏳ Waiting 3 seconds for all processes to close gracefully...')
await new Promise(resolve => setTimeout(resolve, 3000))
// Check if there are still active sessions before cleaning
// Always run cleanup after complete automation cycle - don't check for active sessions
// since the analysis is complete and we need to ensure all processes are cleaned up
console.log('🧹 Running comprehensive post-cycle cleanup (ignoring session status)...')
try {
// Find all chromium processes
const chromiumProcesses = await this.findChromiumProcesses()
if (chromiumProcesses.length === 0) {
console.log('✅ No chromium processes found to clean up')
return
}
console.log(`🔍 Found ${chromiumProcesses.length} chromium processes for post-analysis cleanup`)
// In post-analysis cleanup, we're more aggressive since analysis is complete
// Try graceful shutdown first
for (const pid of chromiumProcesses) {
try {
console.log(`🔧 Attempting graceful shutdown of process ${pid}`)
await execAsync(`kill -TERM ${pid}`)
} catch (error) {
console.log(` Process ${pid} may already be terminated`)
}
}
// Wait for graceful shutdown
await new Promise(resolve => setTimeout(resolve, 5000))
// Check which processes are still running and force kill them
const stillRunning = await this.findStillRunningProcesses(chromiumProcesses)
if (stillRunning.length > 0) {
console.log(`🗡️ Force killing ${stillRunning.length} stubborn processes`)
for (const pid of stillRunning) {
try {
await execAsync(`kill -9 ${pid}`)
console.log(`💀 Force killed process ${pid}`)
} catch (error) {
console.log(` Process ${pid} already terminated`)
}
}
} else {
console.log('✅ All processes shut down gracefully')
}
// Clean up temp directories and shared memory
try {
await execAsync('rm -rf /tmp/puppeteer_dev_chrome_profile-* 2>/dev/null || true')
await execAsync('rm -rf /dev/shm/.org.chromium.* 2>/dev/null || true')
await execAsync('rm -rf /tmp/.org.chromium.* 2>/dev/null || true')
console.log('✅ Cleaned up temporary files and shared memory')
} catch (error) {
console.error('Warning: Could not clean up temporary files:', error)
}
console.log('✅ Post-analysis cleanup completed successfully')
} catch (error) {
console.error('Error in post-analysis cleanup:', error)
}
// Clear any stuck progress sessions
try {
const { progressTracker } = await import('./progress-tracker')
const activeSessions = progressTracker.getActiveSessions()
if (activeSessions.length > 0) {
console.log(`⚠️ Post-cycle cleanup: Still ${activeSessions.length} active sessions detected`)
console.log(`🧹 Force clearing ${activeSessions.length} potentially stuck sessions`)
activeSessions.forEach(session => {
const progress = progressTracker.getProgress(session)
if (progress) {
const activeStep = progress.steps.find(step => step.status === 'active')
const currentStep = activeStep ? activeStep.title : 'Unknown'
console.log(` - ${session}: ${currentStep} (Step ${progress.currentStep}/${progress.totalSteps})`)
}
})
// Force cleanup anyway since cycle is complete
console.log('<27> Forcing cleanup - analysis cycle is complete regardless of session status')
// Clean up the session tracker entries that might be stuck
activeSessions.forEach(session => {
console.log(`🧹 Force clearing stuck session: ${session}`)
console.log(`🧹 Force clearing session: ${session}`)
progressTracker.deleteSession(session)
})
} else {
console.log('✅ No active sessions detected - proceeding with post-cycle cleanup')
}
} catch (error) {
console.warn('⚠️ Could not check active sessions for post-cycle cleanup:', error)
console.warn('Could not clear progress sessions:', error)
}
// Always run cleanup after complete automation cycle
console.log('🧹 Running comprehensive post-cycle cleanup...')
await this.cleanupOrphanedProcesses()
console.log('✅ Post-cycle cleanup completed - all analysis processes should be cleaned up')
}
// Signal that an analysis cycle is complete and all processes should be cleaned up
@@ -397,6 +450,40 @@ class AggressiveCleanup {
return stillRunning
}
// Method to get detailed process information for debugging
async getProcessInfo(): Promise<void> {
try {
console.log('🔍 Current browser process information:')
// Get all chromium processes with detailed info
const { stdout } = await execAsync('ps aux | grep -E "(chromium|chrome)" | grep -v grep')
const processes = stdout.trim().split('\n').filter(line => line.length > 0)
if (processes.length === 0) {
console.log('✅ No browser processes currently running')
return
}
console.log(`📊 Found ${processes.length} browser processes:`)
processes.forEach((process, index) => {
const parts = process.split(/\s+/)
const pid = parts[1]
const cpu = parts[2]
const mem = parts[3]
const command = parts.slice(10).join(' ')
console.log(` ${index + 1}. PID: ${pid}, CPU: ${cpu}%, MEM: ${mem}%, CMD: ${command.substring(0, 100)}...`)
})
// Get memory usage
const { stdout: memInfo } = await execAsync('free -h')
console.log('💾 Memory usage:')
console.log(memInfo)
} catch (error) {
console.error('Error getting process info:', error)
}
}
stop(): void {
if (this.cleanupInterval) {
clearInterval(this.cleanupInterval)