'use client'
import React, { useState, useEffect } from 'react'
// Available timeframes for automation (matching analysis page format)
const timeframes = [
{ label: '5m', value: '5' },
{ label: '15m', value: '15' },
{ label: '30m', value: '30' },
{ label: '1h', value: '60' },
{ label: '2h', value: '120' },
{ label: '4h', value: '240' },
{ label: '1d', value: 'D' },
]
export default function AutomationPageV2() {
const [config, setConfig] = useState({
mode: 'LIVE',
dexProvider: 'DRIFT',
symbol: 'SOLUSD',
selectedTimeframes: ['5', '15', '30'], // Default to scalping preset
tradingAmount: 100,
balancePercentage: 100, // Default to 100% of available balance
})
const [status, setStatus] = useState(null)
const [balance, setBalance] = useState(null)
const [positions, setPositions] = useState([])
const [loading, setLoading] = useState(false)
const [monitorData, setMonitorData] = useState(null)
const [aiLearningData, setAiLearningData] = useState(null)
useEffect(() => {
fetchStatus()
fetchBalance()
fetchPositions()
fetchMonitorData()
fetchAiLearningData()
const interval = setInterval(() => {
fetchStatus()
fetchBalance()
fetchPositions()
fetchMonitorData()
fetchAiLearningData()
}, 300000) // 5 minutes instead of 30 seconds
return () => clearInterval(interval)
}, [])
const toggleTimeframe = (timeframe) => {
setConfig(prev => ({
...prev,
selectedTimeframes: prev.selectedTimeframes.includes(timeframe)
? prev.selectedTimeframes.filter(tf => tf !== timeframe)
: [...prev.selectedTimeframes, timeframe]
}))
}
const fetchStatus = async () => {
try {
const response = await fetch('/api/automation/status')
const data = await response.json()
console.log('Status response:', data) // Debug log
if (response.ok && !data.error) {
setStatus(data) // Status data is returned directly, not wrapped in 'success'
} else {
console.error('Status API error:', data.error || 'Unknown error')
}
} catch (error) {
console.error('Failed to fetch status:', error)
}
}
const fetchBalance = async () => {
try {
const response = await fetch('/api/drift/balance')
const data = await response.json()
if (data.success) {
setBalance(data)
}
} catch (error) {
console.error('Failed to fetch balance:', error)
}
}
const fetchMonitorData = async () => {
try {
const response = await fetch('/api/automation/position-monitor')
const data = await response.json()
if (data.success) {
setMonitorData(data.monitor)
}
} catch (error) {
console.error('Failed to fetch monitor data:', error)
}
}
const fetchPositions = async () => {
try {
const response = await fetch('/api/drift/positions')
const data = await response.json()
if (data.success) {
setPositions(data.positions || [])
}
} catch (error) {
console.error('Failed to fetch positions:', error)
}
}
const fetchAiLearningData = async () => {
try {
const response = await fetch('/api/ai-learning-status')
const data = await response.json()
if (data.success) {
setAiLearningData(data.data)
}
} catch (error) {
console.error('Failed to fetch AI learning data:', error)
}
}
const handleStart = async () => {
console.log('๐ Starting automation...')
setLoading(true)
try {
if (config.selectedTimeframes.length === 0) {
console.error('No timeframes selected')
setLoading(false)
return
}
const automationConfig = {
symbol: config.symbol,
selectedTimeframes: config.selectedTimeframes,
mode: config.mode,
tradingAmount: config.tradingAmount,
leverage: config.leverage,
stopLoss: config.stopLoss,
takeProfit: config.takeProfit
}
const response = await fetch('/api/automation/start', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(automationConfig)
})
const data = await response.json()
if (data.success) {
console.log('โ
Automation started successfully')
fetchStatus()
} else {
console.error('Failed to start automation:', data.error)
}
} catch (error) {
console.error('Failed to start automation:', error)
} finally {
setLoading(false)
}
}
const handleStop = async () => {
console.log('๐ Stopping automation...')
setLoading(true)
try {
const response = await fetch('/api/automation/stop', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
})
const data = await response.json()
if (data.success) {
console.log('โ
Automation stopped successfully')
fetchStatus()
} else {
console.error('Failed to stop automation:', data.error)
}
} catch (error) {
console.error('Failed to stop automation:', error)
} finally {
setLoading(false)
}
}
const handleEmergencyStop = async () => {
console.log('๐จ Emergency stop triggered!')
setLoading(true)
try {
const response = await fetch('/api/automation/emergency-stop', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
})
const data = await response.json()
if (data.success) {
console.log('โ
Emergency stop completed successfully')
fetchStatus()
fetchPositions()
fetchMonitorData()
fetchMonitorData()
} else {
console.error('Emergency stop failed:', data.error)
}
} catch (error) {
console.error('Emergency stop error:', error)
} finally {
setLoading(false)
}
}
const generateTestDecision = async () => {
console.log('๐งช Generating test AI decision...')
setLoading(true)
try {
const response = await fetch('/api/automation/test-decision', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'generate_test_decision',
analysis: {
recommendation: 'STRONG BUY',
confidence: 89,
reasoning: `๐ฏ BULLISH CONVERGENCE DETECTED:
๐ Technical Analysis:
โข RSI bounced from oversold (28โ54) showing strong recovery momentum
โข MACD histogram turning positive with bullish crossover confirmed
โข Price broke above key resistance at $185.40 with 3x normal volume
โข 20 EMA (184.92) providing strong support, price trending above all major EMAs
๐ Market Structure:
โข Higher lows pattern intact since yesterday's session
โข Volume profile shows accumulation at current levels
โข Order book depth favoring buyers (67% buy-side liquidity)
โก Entry Trigger:
โข Breakout candle closed above $186.00 resistance with conviction
โข Next resistance target: $189.75 (2.1% upside potential)
โข Risk/Reward ratio: 1:2.3 (excellent risk management setup)
๐ก๏ธ Risk Management:
โข Stop loss at $184.20 (1.0% below entry) protects against false breakout
โข Position sizing optimized for 2% account risk tolerance`,
stopLoss: 184.20,
takeProfit: 189.75,
currentPrice: 186.12,
stopLossPercent: '1.0% protective stop'
},
config: {
selectedTimeframes: config.selectedTimeframes,
symbol: config.symbol,
mode: config.mode,
enableTrading: config.enableTrading,
tradingAmount: 62
}
})
})
const data = await response.json()
if (data.success) {
console.log('โ
Test decision generated successfully')
fetchStatus() // Refresh to show the decision
} else {
console.error('Failed to generate test decision:', data.error)
}
} catch (error) {
console.error('Test decision error:', error)
} finally {
setLoading(false)
}
}
const analyzeExistingPosition = async () => {
console.log('๐ Analyzing existing position...')
setLoading(true)
try {
// First get the current position data
const positionResponse = await fetch('/api/automation/position-monitor')
const positionData = await positionResponse.json()
if (positionData.success && positionData.monitor.hasPosition) {
// Analyze the existing position
const response = await fetch('/api/automation/analyze-position', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
action: 'analyze_existing_position',
positionData: positionData.monitor.position
})
})
const data = await response.json()
if (data.success) {
console.log('โ
Position analysis generated successfully')
fetchStatus() // Refresh to show the analysis
} else {
console.error('Failed to analyze position:', data.error)
}
} else {
console.log('โน๏ธ No position found to analyze')
alert('No active position found to analyze')
}
} catch (error) {
console.error('Position analysis error:', error)
} finally {
setLoading(false)
}
}
return (
{/* Page Header */}
๐ค AI Trading Automation
Advanced AI-powered trading with real-time analysis and risk management
{/* Main Grid Layout */}
{/* Automation Control Panel - Main Column */}
{/* Control Header with Enhanced Buttons */}
๐ค
Automation Control
Configure and manage your AI trading bot
{status?.isActive ? (
<>
{loading ? (
) : (
๐
STOP
)}
๐จ
EMERGENCY
>
) : (
{loading ? (
) : (
{status?.rateLimitHit ? '๐' : '๐'}
{status?.rateLimitHit ? 'RESTART' : 'START'}
)}
)}
{/* Test & Analysis Buttons */}
๐งช
TEST AI
๐
ANALYZE
{/* Trading Mode Selection - Enhanced Cards */}
โ๏ธ
Trading Mode
setConfig({...config, mode: 'SIMULATION'})}
disabled={status?.isActive}
/>
๐
Paper Trading
Practice with virtual funds
Risk-free testing environment
{config.mode === 'SIMULATION' && (
)}
setConfig({...config, mode: 'LIVE'})}
disabled={status?.isActive}
/>
๐ฐ
Live Trading
Real money transactions
โ ๏ธ Use real funds carefully
{config.mode === 'LIVE' && (
)}
{/* Symbol and Balance Configuration */}
๐ฏ
Trading Symbol
setConfig({...config, symbol: e.target.value})}
disabled={status?.isActive}
>
SOL/USD - Solana
BTC/USD - Bitcoin
ETH/USD - Ethereum
APT/USD - Aptos
AVAX/USD - Avalanche
DOGE/USD - Dogecoin
๐ณ
Balance Usage: {config.balancePercentage}%
{balance && (
${(parseFloat(balance.availableBalance) * config.balancePercentage / 100).toFixed(2)}
)}
{/* Enhanced Multi-Timeframe Selection */}
โฐ
Analysis Timeframes
{config.selectedTimeframes.length} selected
{config.selectedTimeframes.length === 0 && (
โ ๏ธ Select at least one timeframe
)}
{/* Timeframe Selection Grid */}
{timeframes.map(tf => (
toggleTimeframe(tf.value)}
disabled={status?.isActive}
className="sr-only"
/>
{tf.label}
{config.selectedTimeframes.includes(tf.value) && (
)}
))}
{/* Selected Timeframes Display */}
{config.selectedTimeframes.length > 0 && (
Selected Timeframes:
{config.selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label || tf).filter(Boolean).join(', ')}
๐ก Multi-timeframe analysis
)}
{/* Trading Style Presets - Enhanced Cards */}
setConfig({...config, selectedTimeframes: ['5', '15', '30']})}
disabled={status?.isActive}
className="group p-6 rounded-xl bg-gradient-to-br from-green-600/20 to-emerald-600/10 border-2 border-green-600/30 hover:border-green-500/50 hover:from-green-600/30 hover:to-emerald-600/20 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-left hover:scale-105"
>
Scalping
Quick trades on short timeframes
5m โข 15m โข 30m
setConfig({...config, selectedTimeframes: ['60', '120']})}
disabled={status?.isActive}
className="group p-6 rounded-xl bg-gradient-to-br from-blue-600/20 to-indigo-600/10 border-2 border-blue-600/30 hover:border-blue-500/50 hover:from-blue-600/30 hover:to-indigo-600/20 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-left hover:scale-105"
>
Day Trading
Intraday momentum strategies
1h โข 2h
setConfig({...config, selectedTimeframes: ['240', 'D']})}
disabled={status?.isActive}
className="group p-6 rounded-xl bg-gradient-to-br from-purple-600/20 to-violet-600/10 border-2 border-purple-600/30 hover:border-purple-500/50 hover:from-purple-600/30 hover:to-violet-600/20 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed text-left hover:scale-105"
>
Swing Trading
Long-term trend following
4h โข 1d
{/* Enhanced Sidebar */}
{/* Unified Trading Dashboard Card */}
{status?.isActive ? '๐ข' : 'โช'}
Trading Dashboard
Status โข Positions โข Risk Monitor
{/* Bot Status Section */}
๐ค Bot Status
Status:
{status?.isActive ? 'RUNNING' : 'STOPPED'}
{status?.isActive && (
<>
Symbol:
{status.symbol}
Mode:
{status.mode}
Timeframes:
{status.timeframes?.map((tf, index) => (
{timeframes.find(t => t.value === tf)?.label || tf}
))}
>
)}
{/* Rate Limit Warning */}
{status?.rateLimitHit && (
โ ๏ธ
Rate Limit Reached
{status.rateLimitMessage && (
{status.rateLimitMessage}
)}
Automation stopped. Recharge OpenAI account to continue.
)}
{/* Position Monitor Section */}
{monitorData && (
๐ Position Monitor
Has Position:
{monitorData.hasPosition ? 'โ
YES' : 'โ NO'}
Risk Level:
{monitorData.riskLevel}
Next Action:
{monitorData.nextAction}
{monitorData.orphanedOrderCleanup && (
{monitorData.orphanedOrderCleanup.success ? 'โ
Cleanup Success' : 'โ Cleanup Failed'}
{monitorData.orphanedOrderCleanup.message}
)}
)}
{/* Open Positions Section */}
{positions.length > 0 && (
๐ Open Positions
{positions.length}
{positions.map((position, index) => (
{position.symbol}
{position.side}
Size:
{position.symbol?.includes('SOL') ?
`${parseFloat(position.size).toFixed(2)} SOL` :
`$${parseFloat(position.size).toFixed(2)}`
}
Value:
${((parseFloat(position.size) || 0) * (parseFloat(position.markPrice) || parseFloat(position.entryPrice) || 0)).toFixed(2)}
{position.entryPrice && (
Entry:
${parseFloat(position.entryPrice).toFixed(2)}
)}
{position.markPrice && (
Mark:
${parseFloat(position.markPrice).toFixed(2)}
)}
{position.pnl !== undefined && (
PnL:
= 0 ? 'text-green-400' : 'text-red-400'
}`}>
${position.pnl >= 0 ? '+' : ''}${parseFloat(position.pnl).toFixed(2)}
)}
))}
)}
{/* Account Balance Card */}
{balance && (
๐ฐ
Account Balance
Live Drift Protocol data
Available Balance
${parseFloat(balance.availableBalance).toFixed(2)}
Total Collateral
${parseFloat(balance.totalCollateral).toFixed(2)}
Total Positions
{balance.positions || 0}
)}
{/* Enhanced AI Learning Status Panel */}
{aiLearningData && (
๐ง
AI Learning Status
{aiLearningData.phase} โข Real-time learning progress
{/* Main Stats Grid */}
{aiLearningData.avgAccuracy}%
Avg Accuracy
{aiLearningData.winRate}%
Win Rate
{aiLearningData.confidenceLevel}%
Confidence Level
{aiLearningData.daysActive}
Days Active
{/* Trading Performance Section */}
{aiLearningData.statistics && aiLearningData.statistics.totalTrades > 0 && (
๐ Trading Performance
{aiLearningData.statistics.wins}
Wins
+${aiLearningData.statistics.winsPnl.toFixed(2)}
{aiLearningData.statistics.losses}
Losses
${aiLearningData.statistics.lossesPnl.toFixed(2)}
= 0 ? 'text-green-400' : 'text-red-400'}`}>
${aiLearningData.statistics.totalPnl >= 0 ? '+' : ''}${aiLearningData.statistics.totalPnl.toFixed(2)}
Total P&L
{/* Advanced Metrics */}
Avg Win
${aiLearningData.statistics.avgWin.toFixed(2)}
Avg Loss
${aiLearningData.statistics.avgLoss.toFixed(2)}
)}
{/* Learning Progress */}
Learning Progress
{aiLearningData.totalAnalyses} analyses
{/* Next Milestone */}
Next Milestone
{aiLearningData.nextMilestone}
{/* AI Recommendation */}
AI Recommendation
{aiLearningData.recommendation}
)}
{/* Enhanced AI Trading Analysis Panel */}
๐ง
AI Trading Analysis
Real-time market intelligence and decision reasoning
{status?.lastDecision ? '๐ข Analysis Active' : 'โช Waiting for Analysis'}
{status?.lastDecision ? (
{/* Quick Summary Cards */}
Recommendation
{status.lastDecision.recommendation || 'HOLD'}
{status.lastDecision.isRetrospective && (
๐ Retrospective Analysis
)}
Confidence
= 80 ? 'text-green-300' :
status.lastDecision.confidence >= 70 ? 'text-yellow-300' :
'text-red-300'
}`}>
{status.lastDecision.confidence}%
Min Required: {status.lastDecision.minConfidenceRequired}%
Execution
{status.lastDecision.executed ? 'โ
EXECUTED' : 'โ NOT EXECUTED'}
{new Date(status.lastDecision.timestamp).toLocaleTimeString()}
{status.lastDecision.executed && status.lastDecision.executionDetails && (
Leverage
{status.lastDecision.executionDetails.leverage}x
AI Calculated
)}
{/* Main Analysis Content */}
{/* AI Reasoning */}
๐ฏ
Market Analysis & Reasoning
{status.lastDecision.reasoning}
{/* Execution Error */}
{!status.lastDecision.executed && status.lastDecision.executionError && (
โ
Execution Failed
{status.lastDecision.executionError}
)}
{/* Trade Execution Details */}
{status.lastDecision.executed && status.lastDecision.executionDetails && (
๐
Trade Execution Details
Entry Price
${status.lastDecision.executionDetails.currentPrice?.toFixed(4)}
Position Size
${status.lastDecision.executionDetails.amount}
Direction
{status.lastDecision.executionDetails.side}
Leverage
{status.lastDecision.executionDetails.leverage}x
{/* Risk Management */}
๐ก๏ธ
Risk Management
Stop Loss:
${status.lastDecision.executionDetails.stopLoss?.toFixed(4)}
Take Profit:
${status.lastDecision.executionDetails.takeProfit?.toFixed(4)}
{status.lastDecision.executionDetails.txId && (
Transaction ID:
{status.lastDecision.executionDetails.txId.substring(0, 12)}...
)}
{/* AI Leverage Reasoning */}
โก
AI Leverage Analysis
{status.lastDecision.executionDetails.aiReasoning}
)}
) : (
๐ค
AI Analysis Standby
The AI will analyze market conditions using advanced technical indicators across multiple timeframes
and provide detailed reasoning for all trading decisions.
What you'll see when analysis starts:
๐ฏ
Entry Strategy
Why AI chose this entry point
๐ก๏ธ
Risk Management
Stop loss and take profit logic
๐
Technical Analysis
Multi-timeframe indicator consensus
โก
Leverage Calculation
AI's dynamic risk assessment
๐ฒ
Confidence Scoring
Probability-based decision making
โ
Execution Status
Real-time trade confirmation
)}
)
}