+ {console.log('๐ฏ Rendering trades section, count:', recentTrades.length)}
{recentTrades.length > 0 ? (
{recentTrades.slice(0, 4).map((trade, idx) => (
diff --git a/app/automation/page.js.backup b/app/automation/page.js.backup
new file mode 100644
index 0000000..c11ab83
--- /dev/null
+++ b/app/automation/page.js.backup
@@ -0,0 +1,1200 @@
+'use client'
+import React, { useState, useEffect } from 'react'
+import RealTimePriceMonitor from '../../components/RealTimePriceMonitor'
+
+export default function AutomationPage() {
+ const [config, setConfig] = useState({
+ mode: 'SIMULATION',
+ symbol: 'SOLUSD',
+ timeframe: '1h',
+ tradingAmount: 100,
+ maxLeverage: 3,
+ stopLossPercent: 2,
+ takeProfitPercent: 6,
+ maxDailyTrades: 5,
+ riskPercentage: 2
+ })
+
+ const [status, setStatus] = useState(null)
+ const [isLoading, setIsLoading] = useState(false)
+ const [learningInsights, setLearningInsights] = useState(null)
+ const [aiLearningStatus, setAiLearningStatus] = useState(null)
+ const [recentTrades, setRecentTrades] = useState([])
+ const [analysisDetails, setAnalysisDetails] = useState(null)
+ const [selectedTrade, setSelectedTrade] = useState(null)
+ const [tradeModalOpen, setTradeModalOpen] = useState(false)
+
+ useEffect(() => {
+ fetchStatus()
+ fetchLearningInsights()
+ fetchAiLearningStatus()
+ fetchRecentTrades()
+ fetchAnalysisDetails()
+
+ // Auto-refresh every 30 seconds
+ const interval = setInterval(() => {
+ fetchStatus()
+ fetchAnalysisDetails()
+ fetchAiLearningStatus()
+ }, 30000)
+
+ return () => clearInterval(interval)
+ }, [])
+
+ const fetchAnalysisDetails = async () => {
+ try {
+ const response = await fetch('/api/automation/analysis-details')
+ const data = await response.json()
+ if (data.success) {
+ setAnalysisDetails(data.data)
+ // Also update recent trades from the same endpoint
+ if (data.data.recentTrades) {
+ setRecentTrades(data.data.recentTrades)
+ }
+ }
+ } catch (error) {
+ console.error('Failed to fetch analysis details:', error)
+ }
+ }
+
+ const fetchStatus = async () => {
+ try {
+ const response = await fetch('/api/automation/status')
+ const data = await response.json()
+ if (data.success) {
+ setStatus(data.status)
+ }
+ } catch (error) {
+ console.error('Failed to fetch status:', error)
+ }
+ }
+
+ const fetchLearningInsights = async () => {
+ try {
+ const response = await fetch('/api/automation/learning-insights')
+ const data = await response.json()
+ if (data.success) {
+ setLearningInsights(data.insights)
+ }
+ } catch (error) {
+ console.error('Failed to fetch learning insights:', error)
+ }
+ }
+
+ const fetchAiLearningStatus = async () => {
+ try {
+ const response = await fetch('/api/ai-learning-status')
+ const data = await response.json()
+ if (data.success) {
+ setAiLearningStatus(data.data)
+ }
+ } catch (error) {
+ console.error('Failed to fetch AI learning status:', error)
+ }
+ }
+
+ const fetchRecentTrades = async () => {
+ try {
+ console.log('๐ Fetching recent trades...')
+ // Get enhanced trade data from analysis-details instead of recent-trades
+ const response = await fetch('/api/automation/analysis-details')
+ const data = await response.json()
+ console.log('๐ API Response:', data)
+ console.log('๐ Recent trades in response:', data.data?.recentTrades?.length || 0)
+ if (data.success && data.data.recentTrades) {
+ console.log('โ
Setting recent trades:', data.data.recentTrades.length)
+ setRecentTrades(data.data.recentTrades)
+ } else {
+ console.log('โ No recent trades found in API response')
+ }
+ } catch (error) {
+ console.error('Failed to fetch recent trades:', error)
+ }
+ }
+
+ const handleStart = async () => {
+ setIsLoading(true)
+ try {
+ const response = await fetch('/api/automation/start', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(config)
+ })
+ const data = await response.json()
+ if (data.success) {
+ fetchStatus()
+ } else {
+ alert('Failed to start automation: ' + data.error)
+ }
+ } catch (error) {
+ console.error('Failed to start automation:', error)
+ alert('Failed to start automation')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handleStop = async () => {
+ setIsLoading(true)
+ try {
+ const response = await fetch('/api/automation/stop', {
+ method: 'POST'
+ })
+ const data = await response.json()
+ if (data.success) {
+ fetchStatus()
+ } else {
+ alert('Failed to stop automation: ' + data.error)
+ }
+ } catch (error) {
+ console.error('Failed to stop automation:', error)
+ alert('Failed to stop automation')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handlePause = async () => {
+ setIsLoading(true)
+ try {
+ const response = await fetch('/api/automation/pause', {
+ method: 'POST'
+ })
+ const data = await response.json()
+ if (data.success) {
+ fetchStatus()
+ } else {
+ alert('Failed to pause automation: ' + data.error)
+ }
+ } catch (error) {
+ console.error('Failed to pause automation:', error)
+ alert('Failed to pause automation')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const handleResume = async () => {
+ setIsLoading(true)
+ try {
+ const response = await fetch('/api/automation/resume', {
+ method: 'POST'
+ })
+ const data = await response.json()
+ if (data.success) {
+ fetchStatus()
+ } else {
+ alert('Failed to resume automation: ' + data.error)
+ }
+ } catch (error) {
+ console.error('Failed to resume automation:', error)
+ alert('Failed to resume automation')
+ } finally {
+ setIsLoading(false)
+ }
+ }
+
+ const openTradeModal = async (tradeId) => {
+ try {
+ const response = await fetch(`/api/automation/trade-details/${tradeId}`)
+ const data = await response.json()
+ if (data.success) {
+ setSelectedTrade(data.data)
+ setTradeModalOpen(true)
+ } else {
+ alert('Failed to load trade details')
+ }
+ } catch (error) {
+ console.error('Failed to load trade details:', error)
+ alert('Failed to load trade details')
+ }
+ }
+
+ const closeTradeModal = () => {
+ setTradeModalOpen(false)
+ setSelectedTrade(null)
+ }
+
+ // Calculate win rate from recent trades
+ const calculateWinRate = () => {
+ if (!recentTrades.length) return 0
+ const completedTrades = recentTrades.filter(t => t.status === 'COMPLETED')
+ if (!completedTrades.length) return 0
+ const winningTrades = completedTrades.filter(t => t.result === 'WIN')
+ return (winningTrades.length / completedTrades.length * 100).toFixed(1)
+ }
+
+ // Calculate total P&L from recent trades
+ const calculateTotalPnL = () => {
+ if (!recentTrades.length) return 0
+ return recentTrades
+ .filter(t => t.status === 'COMPLETED' && t.pnl)
+ .reduce((total, trade) => total + parseFloat(trade.pnl), 0)
+ .toFixed(2)
+ }
+
+ return (
+
+
+
+
Automation Mode
+
+ AI-powered automated trading on 1H timeframe with learning capabilities
+
+
+
+ {status?.isActive ? (
+ <>
+
+
+ >
+ ) : (
+ <>
+ {status?.status === 'PAUSED' && (
+
+ )}
+
+ >
+ )}
+
+
+
+ {/* Real-Time Price Monitor - Top Priority */}
+
+
+
+ {/* Left Column: Configuration & Controls */}
+
+ {/* Configuration Panel */}
+
+
โ๏ธ Configuration
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ setConfig({...config, tradingAmount: parseFloat(e.target.value)})}
+ className="w-full p-3 bg-gray-800 border border-gray-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
+ disabled={status?.isActive}
+ min="10"
+ step="10"
+ />
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {/* Right Column: Status & Performance */}
+
+ {/* Status Panel */}
+
+
๐ Automation Status
+ {status ? (
+
+
+ Status:
+
+ {status.isActive ? 'ACTIVE' : 'STOPPED'}
+
+
+
+ Mode:
+
+ {status.mode}
+
+
+
+ Symbol:
+ {status.symbol}
+
+
+ Timeframe:
+ {status.timeframe}
+
+
+ Total Trades:
+ {status.totalTrades}
+
+
+ Win Rate:
+ 60 ? 'text-green-400' :
+ calculateWinRate() > 40 ? 'text-yellow-400' : 'text-red-400'
+ }`}>
+ {calculateWinRate()}%
+
+
+
+ Total P&L:
+ 0 ? 'text-green-400' :
+ calculateTotalPnL() < 0 ? 'text-red-400' : 'text-gray-300'
+ }`}>
+ ${calculateTotalPnL()}
+
+
+ {status.lastAnalysis && (
+
+ Last Analysis:
+
+ {new Date(status.lastAnalysis).toLocaleTimeString()}
+
+
+ )}
+ {status.errorCount > 0 && (
+
+ Errors:
+ {status.errorCount}
+
+ )}
+
+ ) : (
+
No active automation session
+ )}
+
+
+ {/* Recent Trades */}
+
+
Latest 4 Automated Trades (Debug: {recentTrades.length})
+ {recentTrades.length > 0 ? (
+
+
โ
We have {recentTrades.length} trades to display
+ {recentTrades.slice(0, 4).map((trade, idx) => (
+
+
+ Trade #{idx + 1}: {trade?.side || 'UNKNOWN'} - ${trade?.amount?.toFixed(4) || 'N/A'} - {trade?.status || 'UNKNOWN'}
+
+
+ Entry: ${trade?.entryPrice?.toFixed(2) || trade?.price?.toFixed(2) || '0.00'} |
+ P&L: ${trade?.pnl || trade?.realizedPnl || '0.00'} |
+ Result: {trade?.result || 'UNKNOWN'}
+
+
+ ))}
+
+ ) : (
+
No recent trades
+ )}
+
+
+
{trade?.amount?.toFixed(4) || 'N/A'}
+
{trade?.leverage || 1}x
+
+ {trade?.isActive ? 'ACTIVE' : (trade?.result || 'UNKNOWN')}
+
+
+
+
${trade?.entryPrice?.toFixed(2) || trade?.price?.toFixed(2) || '0.00'}
+
{trade?.confidence || 0}% confidence
+
+
+
+ {/* Enhanced Timing Information */}
+
+
+
+ Entry Time:
+ {trade?.entryTime ? new Date(trade.entryTime).toLocaleTimeString() : 'N/A'}
+
+
+ Exit Time:
+
+ {trade?.exitTime ? new Date(trade.exitTime).toLocaleTimeString() : 'Active'}
+
+
+
+ Duration:
+ {trade?.durationText || 'N/A'}
+
+
+
+
+ {/* Trading Details */}
+
+
+
+ Trading Amount:
+ ${trade?.tradingAmount || 0}
+
+
+ Leverage:
+ {trade?.leverage || 1}x
+
+
+ Position Size:
+ ${trade?.positionSize || '0.00'}
+
+ {/* Entry Price - Always show for completed trades */}
+
+ Entry Price:
+ ${trade?.entryPrice?.toFixed(2) || trade?.price?.toFixed(2) || '0.00'}
+
+ {/* Exit Price or Current Price */}
+
+ {trade?.isActive ? 'Current' : 'Exit'} Price:
+
+ {trade?.isActive ?
+ `$${trade?.currentPrice?.toFixed(2) || '0.00'}` :
+ (trade?.exitPrice ?
+ `$${trade.exitPrice.toFixed(2)}` :
+ Not recorded
+ )
+ }
+
+
+ {/* Price difference for completed trades */}
+ {!trade?.isActive && trade?.exitPrice && trade?.entryPrice && (
+
+ Price Difference:
+ 0 ? 'text-green-400' :
+ (trade?.exitPrice - trade?.entryPrice) < 0 ? 'text-red-400' :
+ 'text-gray-400'
+ }`}>
+ ${((trade?.exitPrice - trade?.entryPrice) >= 0 ? '+' : '')}${(trade?.exitPrice - trade?.entryPrice)?.toFixed(2) || '0.00'}
+
+
+ )}
+
+
+
+ {/* P&L Display */}
+
+
+
P&L:
+
+ 0 ? 'text-green-400' : 'text-red-400') :
+ (trade?.realizedPnl && parseFloat(trade.realizedPnl) > 0 ? 'text-green-400' :
+ trade?.realizedPnl && parseFloat(trade.realizedPnl) < 0 ? 'text-red-400' : 'text-gray-400')
+ }`}>
+ ${trade?.isActive ?
+ (trade?.unrealizedPnl || '0.00') :
+ (trade?.realizedPnl || trade?.pnl || '0.00')
+ }
+
+ {trade?.pnlPercent && (
+ 0 ? 'text-green-400' : 'text-red-400') :
+ (trade?.realizedPnl && parseFloat(trade.realizedPnl) > 0 ? 'text-green-400' :
+ trade?.realizedPnl && parseFloat(trade.realizedPnl) < 0 ? 'text-red-400' : 'text-gray-400')
+ }`}>
+ ({trade?.pnlPercent || '0%'})
+
+ )}
+
+ {trade?.isActive ? '(Unrealized)' : '(Realized)'}
+
+
+
+ {/* Debug info for missing data */}
+ {trade?.result === 'UNKNOWN' && (
+
+ โ ๏ธ Missing exit data: {!trade?.exitPrice ? 'Exit Price ' : ''}{trade?.calculatedProfit === null ? 'Profit' : ''}
+
+ )}
+ {/* Warning for old incorrect trades */}
+ {trade?.isOldWrongTrade && (
+
+ ๐ง Old trade with incorrect price data (stored: ${trade?.originalStoredPrice?.toFixed(2)}, should be ~$189)
+
+ )}
+
+
+ {/* Click hint */}
+
+
+ SL: ${trade?.stopLoss || 'N/A'} | TP: ${trade?.takeProfit || 'N/A'}
+
+
+ ๐ Click to view analysis
+
+
+
+ {/* Learning Insights */}
+ {learningInsights && (
+
+
๐ก Learning Insights
+
+
+ Total Analyses:
+ {learningInsights.totalAnalyses}
+
+
+ Avg Accuracy:
+ {(learningInsights.avgAccuracy * 100).toFixed(1)}%
+
+
+ Best Timeframe:
+ {learningInsights.bestTimeframe}
+
+
+ Worst Timeframe:
+ {learningInsights.worstTimeframe}
+
+
+
+
Recommendations
+
+ {learningInsights.recommendations.map((rec, idx) => (
+ - โข {rec}
+ ))}
+
+
+
+
+ )}
+