'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: 'SIMULATION',
dexProvider: 'DRIFT',
symbol: 'SOLUSD',
timeframe: '1h', // Primary timeframe for backwards compatibility
selectedTimeframes: ['60'], // Multi-timeframe support
tradingAmount: 100,
balancePercentage: 50, // Default to 50% of available balance
maxLeverage: 5,
stopLossPercent: 2,
takeProfitPercent: 6
})
const [status, setStatus] = useState(null)
const [balance, setBalance] = useState(null)
const [positions, setPositions] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
fetchStatus()
fetchBalance()
fetchPositions()
const interval = setInterval(() => {
fetchStatus()
fetchBalance()
fetchPositions()
}, 30000)
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 fetched:', data) // Debug log
if (data.success) {
setStatus(data.status)
}
} 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 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 handleStart = async () => {
console.log('Start button clicked') // Debug log
setLoading(true)
try {
// Ensure we have selectedTimeframes before starting
if (config.selectedTimeframes.length === 0) {
alert('Please select at least one timeframe for analysis')
setLoading(false)
return
}
console.log('Starting automation with config:', {
...config,
selectedTimeframes: config.selectedTimeframes
})
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 {
setLoading(false)
}
}
const handleStop = async () => {
console.log('Stop button clicked') // Debug log
setLoading(true)
try {
const response = await fetch('/api/automation/stop', {
method: 'POST'
})
const data = await response.json()
console.log('Stop response:', data) // Debug log
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 {
setLoading(false)
}
}
return (
🚀 NEW AUTOMATION V2 - MULTI-TIMEFRAME READY 🚀
Automated Trading V2
Drift Protocol - Multi-Timeframe Analysis
{status?.isActive ? (
) : (
)}
{/* Configuration Panel */}
Configuration
{/* Trading Mode */}
{/* Symbol and Position Size */}
{
const percentage = parseFloat(e.target.value);
const newAmount = balance ? (parseFloat(balance.availableBalance) * percentage / 100) : 100;
setConfig({
...config,
balancePercentage: percentage,
tradingAmount: Math.round(newAmount)
});
}}
disabled={status?.isActive}
/>
10%
50%
100%
{balance && config.maxLeverage > 1 && (
With {config.maxLeverage}x leverage: ${(config.tradingAmount * config.maxLeverage).toFixed(2)} position exposure
)}
{/* MULTI-TIMEFRAME SELECTION */}
{/* Timeframe Checkboxes */}
{timeframes.map(tf => (
))}
{/* Selected Timeframes Display */}
{config.selectedTimeframes.length > 0 && (
Selected:
{config.selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label).filter(Boolean).join(', ')}
💡 Multiple timeframes provide more robust analysis
)}
{/* Quick Selection Buttons */}
{/* Risk Management */}
{/* Status Panels */}
{/* Account Status */}
Account Status
{balance ? (
Available Balance:
${parseFloat(balance.availableBalance).toFixed(2)}
Account Value:
${parseFloat(balance.accountValue || balance.availableBalance).toFixed(2)}
Unrealized P&L:
0 ? 'text-green-400' : balance.unrealizedPnl < 0 ? 'text-red-400' : 'text-gray-400'}`}>
${parseFloat(balance.unrealizedPnl || 0).toFixed(2)}
Open Positions:
{positions.length}
) : (
)}
{/* Bot Status */}
Bot Status
{status ? (
Status:
{status.isActive ? 'ACTIVE' : 'STOPPED'}
Mode:
{status.mode}
Protocol:
DRIFT
Symbol:
{status.symbol}
Timeframes:
{config.selectedTimeframes.map(tf => timeframes.find(t => t.value === tf)?.label).filter(Boolean).join(', ')}
Leverage:
{config.maxLeverage}x
) : (
Loading bot status...
)}
{/* Trading Metrics */}
Trading Metrics
${balance ? parseFloat(balance.accountValue || balance.availableBalance).toFixed(2) : '0.00'}
Portfolio
{balance ? parseFloat(balance.leverage || 0).toFixed(1) : '0.0'}%
Leverage Used
${balance ? parseFloat(balance.unrealizedPnl || 0).toFixed(2) : '0.00'}
Unrealized P&L
{positions.length}
Open Positions
)
}