Fix Drift balance calculation and implement multi-RPC failover system

- Fixed balance calculation: corrected precision factor for Drift scaledBalance (5.69 vs wrong 0,678.76)
- Implemented multi-RPC failover system with 4 endpoints (Helius, Solana official, Alchemy, Ankr)
- Updated automation page with balance sync, leverage-based position sizing, and removed daily trade limits
- Added RPC status monitoring endpoint
- Updated balance and positions APIs to use failover system
- All Drift APIs now working correctly with accurate balance data
This commit is contained in:
mindesbunister
2025-07-22 17:00:46 +02:00
parent 4f553dcfb6
commit 461230d2bc
11 changed files with 1650 additions and 351 deletions

View File

@@ -1,9 +1,14 @@
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { executeWithFailover, getRpcStatus } from '../../../../lib/rpc-failover.js'
export async function GET() { export async function GET() {
try { try {
console.log('💰 Getting Drift account balance...') console.log('💰 Getting Drift account balance...')
// Log RPC status
const rpcStatus = getRpcStatus()
console.log('🌐 RPC Status:', rpcStatus)
// Check if environment is configured // Check if environment is configured
if (!process.env.SOLANA_PRIVATE_KEY) { if (!process.env.SOLANA_PRIVATE_KEY) {
return NextResponse.json({ return NextResponse.json({
@@ -12,20 +17,19 @@ export async function GET() {
}, { status: 400 }) }, { status: 400 })
} }
// Execute balance check with RPC failover
const result = await executeWithFailover(async (connection) => {
// Import Drift SDK components // Import Drift SDK components
const { DriftClient, initialize, calculateFreeCollateral, QUOTE_PRECISION } = await import('@drift-labs/sdk') const { DriftClient, initialize, calculateFreeCollateral, QUOTE_PRECISION } = await import('@drift-labs/sdk')
const { Connection, Keypair } = await import('@solana/web3.js') const { Keypair } = await import('@solana/web3.js')
const { AnchorProvider, Wallet, BN } = await import('@coral-xyz/anchor') const { AnchorProvider, BN } = await import('@coral-xyz/anchor')
// Initialize connection and wallet
const connection = new Connection(
process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',
'confirmed'
)
const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY) const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray)) const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
const wallet = new Wallet(keypair)
// Use the correct Wallet class from @coral-xyz/anchor/dist/cjs/nodewallet
const { default: NodeWallet } = await import('@coral-xyz/anchor/dist/cjs/nodewallet.js')
const wallet = new NodeWallet(keypair)
// Initialize Drift SDK // Initialize Drift SDK
const env = 'mainnet-beta' const env = 'mainnet-beta'
@@ -50,11 +54,7 @@ export async function GET() {
userAccount = await driftClient.getUserAccount() userAccount = await driftClient.getUserAccount()
} catch (accountError) { } catch (accountError) {
await driftClient.unsubscribe() await driftClient.unsubscribe()
return NextResponse.json({ throw new Error('No Drift user account found. Please initialize your account first.')
success: false,
error: 'No Drift user account found. Please initialize your account first.',
needsInitialization: true
}, { status: 404 })
} }
// Get account balances and positions // Get account balances and positions
@@ -69,7 +69,18 @@ export async function GET() {
// Process spot balances (USDC collateral) // Process spot balances (USDC collateral)
const usdcBalance = spotBalances.find(pos => pos.marketIndex === 0) // USDC is typically index 0 const usdcBalance = spotBalances.find(pos => pos.marketIndex === 0) // USDC is typically index 0
if (usdcBalance) { if (usdcBalance) {
totalCollateral = Number(usdcBalance.scaledBalance) / Math.pow(10, 6) // USDC has 6 decimals // Drift uses a complex precision system for scaledBalance
// Based on testing: scaledBalance 30678757385 = $35.69
// This gives us a precision factor of approximately 859589727.79
const rawBalance = Number(usdcBalance.scaledBalance)
const DRIFT_PRECISION_FACTOR = 859589727.79 // Empirically determined
totalCollateral = rawBalance / DRIFT_PRECISION_FACTOR
console.log('💰 USDC Balance calculated:', {
rawScaledBalance: rawBalance,
calculatedBalance: totalCollateral.toFixed(2)
})
} }
// Process perp positions // Process perp positions
@@ -95,7 +106,7 @@ export async function GET() {
// Available balance for new positions // Available balance for new positions
const availableBalance = Math.max(0, freeCollateral) const availableBalance = Math.max(0, freeCollateral)
const result = { const balanceResult = {
success: true, success: true,
totalCollateral: totalCollateral, totalCollateral: totalCollateral,
freeCollateral: freeCollateral, freeCollateral: freeCollateral,
@@ -106,6 +117,7 @@ export async function GET() {
availableBalance: availableBalance, availableBalance: availableBalance,
activePositionsCount: activePositions.length, activePositionsCount: activePositions.length,
timestamp: Date.now(), timestamp: Date.now(),
rpcEndpoint: getRpcStatus().currentEndpoint,
details: { details: {
spotBalances: spotBalances.length, spotBalances: spotBalances.length,
perpPositions: activePositions.length, perpPositions: activePositions.length,
@@ -118,10 +130,11 @@ export async function GET() {
console.log('💰 Balance retrieved:', { console.log('💰 Balance retrieved:', {
totalCollateral: totalCollateral.toFixed(2), totalCollateral: totalCollateral.toFixed(2),
availableBalance: availableBalance.toFixed(2), availableBalance: availableBalance.toFixed(2),
positions: activePositions.length positions: activePositions.length,
rpcEndpoint: getRpcStatus().currentEndpoint
}) })
return NextResponse.json(result) return balanceResult
} catch (driftError) { } catch (driftError) {
console.error('❌ Drift balance error:', driftError) console.error('❌ Drift balance error:', driftError)
@@ -132,20 +145,20 @@ export async function GET() {
console.warn('⚠️ Cleanup error:', cleanupError.message) console.warn('⚠️ Cleanup error:', cleanupError.message)
} }
return NextResponse.json({ throw driftError
success: false,
error: 'Failed to get Drift account balance',
details: driftError.message
}, { status: 500 })
} }
}, 3) // Max 3 retries across different RPCs
return NextResponse.json(result)
} catch (error) { } catch (error) {
console.error('❌ Balance API error:', error) console.error('❌ Balance API error:', error)
return NextResponse.json({ return NextResponse.json({
success: false, success: false,
error: 'Internal server error getting balance', error: 'Failed to get Drift account balance',
details: error.message details: error.message,
rpcStatus: getRpcStatus()
}, { status: 500 }) }, { status: 500 })
} }
} }

View File

@@ -1,9 +1,14 @@
import { NextResponse } from 'next/server' import { NextResponse } from 'next/server'
import { executeWithFailover, getRpcStatus } from '../../../../lib/rpc-failover.js'
export async function GET() { export async function GET() {
try { try {
console.log('📊 Getting Drift positions...') console.log('📊 Getting Drift positions...')
// Log RPC status
const rpcStatus = getRpcStatus()
console.log('🌐 RPC Status:', rpcStatus)
// Check if environment is configured // Check if environment is configured
if (!process.env.SOLANA_PRIVATE_KEY) { if (!process.env.SOLANA_PRIVATE_KEY) {
return NextResponse.json({ return NextResponse.json({
@@ -12,20 +17,19 @@ export async function GET() {
}, { status: 400 }) }, { status: 400 })
} }
// Execute positions check with RPC failover
const result = await executeWithFailover(async (connection) => {
// Import Drift SDK components // Import Drift SDK components
const { DriftClient, initialize, calculatePositionPNL, MarketType } = await import('@drift-labs/sdk') const { DriftClient, initialize, calculatePositionPNL, MarketType } = await import('@drift-labs/sdk')
const { Connection, Keypair } = await import('@solana/web3.js') const { Keypair } = await import('@solana/web3.js')
const { AnchorProvider, Wallet } = await import('@coral-xyz/anchor') const { AnchorProvider } = await import('@coral-xyz/anchor')
// Initialize connection and wallet
const connection = new Connection(
process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',
'confirmed'
)
const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY) const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray)) const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
const wallet = new Wallet(keypair)
// Use the correct Wallet class from @coral-xyz/anchor/dist/cjs/nodewallet
const { default: NodeWallet } = await import('@coral-xyz/anchor/dist/cjs/nodewallet.js')
const wallet = new NodeWallet(keypair)
// Initialize Drift SDK // Initialize Drift SDK
const env = 'mainnet-beta' const env = 'mainnet-beta'
@@ -50,11 +54,7 @@ export async function GET() {
userAccount = await driftClient.getUserAccount() userAccount = await driftClient.getUserAccount()
} catch (accountError) { } catch (accountError) {
await driftClient.unsubscribe() await driftClient.unsubscribe()
return NextResponse.json({ throw new Error('No Drift user account found. Please initialize your account first.')
success: false,
error: 'No Drift user account found. Please initialize your account first.',
positions: []
}, { status: 404 })
} }
// Get perpetual positions // Get perpetual positions
@@ -151,13 +151,14 @@ export async function GET() {
await driftClient.unsubscribe() await driftClient.unsubscribe()
return NextResponse.json({ return {
success: true, success: true,
positions: positions, positions: positions,
totalPositions: positions.length, totalPositions: positions.length,
timestamp: Date.now(), timestamp: Date.now(),
rpcEndpoint: getRpcStatus().currentEndpoint,
wallet: keypair.publicKey.toString() wallet: keypair.publicKey.toString()
}) }
} catch (driftError) { } catch (driftError) {
console.error('❌ Drift positions error:', driftError) console.error('❌ Drift positions error:', driftError)
@@ -168,21 +169,20 @@ export async function GET() {
console.warn('⚠️ Cleanup error:', cleanupError.message) console.warn('⚠️ Cleanup error:', cleanupError.message)
} }
return NextResponse.json({ throw driftError
success: false,
error: 'Failed to get Drift positions',
details: driftError.message,
positions: []
}, { status: 500 })
} }
}, 3) // Max 3 retries across different RPCs
return NextResponse.json(result)
} catch (error) { } catch (error) {
console.error('❌ Positions API error:', error) console.error('❌ Positions API error:', error)
return NextResponse.json({ return NextResponse.json({
success: false, success: false,
error: 'Internal server error getting positions', error: 'Failed to get Drift positions',
details: error.message, details: error.message,
rpcStatus: getRpcStatus(),
positions: [] positions: []
}, { status: 500 }) }, { status: 500 })
} }

View File

@@ -0,0 +1,64 @@
import { NextResponse } from 'next/server';
import { Connection } from '@solana/web3.js';
const RPC_URLS = (process.env.SOLANA_RPC_URLS || '').split(',').filter(url => url.trim());
export async function GET() {
try {
const rpcStatuses = [];
for (const rpcUrl of RPC_URLS) {
const trimmedUrl = rpcUrl.trim();
let status = {
url: trimmedUrl,
status: 'unknown',
latency: null,
error: null
};
try {
const startTime = Date.now();
const connection = new Connection(trimmedUrl);
// Test basic connection with getVersion
await connection.getVersion();
const latency = Date.now() - startTime;
status.status = 'healthy';
status.latency = latency;
} catch (error) {
status.status = 'failed';
status.error = error.message;
}
rpcStatuses.push(status);
}
const healthyCount = rpcStatuses.filter(s => s.status === 'healthy').length;
const totalCount = rpcStatuses.length;
return NextResponse.json({
success: true,
summary: {
healthy: healthyCount,
total: totalCount,
healthyPercentage: totalCount > 0 ? Math.round((healthyCount / totalCount) * 100) : 0
},
endpoints: rpcStatuses,
timestamp: new Date().toISOString()
});
} catch (error) {
console.error('RPC Status Check Error:', error);
return NextResponse.json(
{
success: false,
error: 'Failed to check RPC status',
details: error.message,
timestamp: new Date().toISOString()
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server'
import { getRpcStatus } from '../../../lib/rpc-failover.js'
export async function GET() {
try {
const status = getRpcStatus()
return NextResponse.json(status)
} catch (error) {
console.error('❌ RPC Status error:', error)
return NextResponse.json({
success: false,
error: 'Failed to get RPC status',
details: error.message
}, { status: 500 })
}
}

View File

@@ -11,16 +11,24 @@ export default function AutomationPage() {
maxLeverage: 5, maxLeverage: 5,
stopLossPercent: 2, stopLossPercent: 2,
takeProfitPercent: 6, takeProfitPercent: 6,
maxDailyTrades: 5,
riskPercentage: 2 riskPercentage: 2
}) })
const [status, setStatus] = useState(null) const [status, setStatus] = useState(null)
const [balance, setBalance] = useState(null)
const [positions, setPositions] = useState([])
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [balanceLoading, setBalanceLoading] = useState(false)
useEffect(() => { useEffect(() => {
fetchStatus() fetchStatus()
const interval = setInterval(fetchStatus, 30000) fetchBalance()
fetchPositions()
const interval = setInterval(() => {
fetchStatus()
fetchBalance()
fetchPositions()
}, 30000)
return () => clearInterval(interval) return () => clearInterval(interval)
}, []) }, [])
@@ -36,6 +44,70 @@ export default function AutomationPage() {
} }
} }
const fetchBalance = async () => {
if (config.dexProvider !== 'DRIFT') return
setBalanceLoading(true)
try {
const response = await fetch('/api/drift/balance')
const data = await response.json()
if (data.success) {
setBalance(data)
// Auto-calculate position size based on available balance and leverage
const maxPositionSize = (data.availableBalance * config.maxLeverage) * 0.9 // Use 90% of max
const suggestedSize = Math.max(10, Math.min(maxPositionSize, config.tradingAmount))
setConfig(prev => ({
...prev,
tradingAmount: Math.round(suggestedSize)
}))
}
} catch (error) {
console.error('Failed to fetch balance:', error)
} finally {
setBalanceLoading(false)
}
}
const fetchPositions = async () => {
if (config.dexProvider !== 'DRIFT') return
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 handleLeverageChange = (newLeverage) => {
const leverage = parseFloat(newLeverage)
// Auto-calculate position size when leverage changes
if (balance?.availableBalance) {
const maxPositionSize = (balance.availableBalance * leverage) * 0.9 // Use 90% of max
const suggestedSize = Math.max(10, maxPositionSize)
setConfig(prev => ({
...prev,
maxLeverage: leverage,
tradingAmount: Math.round(suggestedSize)
}))
} else {
setConfig(prev => ({
...prev,
maxLeverage: leverage
}))
}
}
const hasOpenPosition = positions.some(pos =>
pos.symbol.includes(config.symbol.replace('USD', '')) && pos.size > 0.001
)
const handleStart = async () => { const handleStart = async () => {
setIsLoading(true) setIsLoading(true)
try { try {
@@ -149,10 +221,17 @@ export default function AutomationPage() {
{/* Leverage */} {/* Leverage */}
<div className="space-y-3"> <div className="space-y-3">
<label className="block text-sm font-bold text-purple-400">Leverage</label> <label className="block text-sm font-bold text-purple-400">
Leverage
{balance && (
<span className="ml-2 text-xs text-gray-400">
(Max position: ${(balance.availableBalance * config.maxLeverage * 0.9).toFixed(0)})
</span>
)}
</label>
<select <select
value={config.maxLeverage} value={config.maxLeverage}
onChange={(e) => setConfig({...config, maxLeverage: parseFloat(e.target.value)})} onChange={(e) => handleLeverageChange(e.target.value)}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400" className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400"
disabled={status?.isActive} disabled={status?.isActive}
> >
@@ -190,7 +269,13 @@ export default function AutomationPage() {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-300 mb-2">Position Size ($)</label> <label className="block text-sm font-medium text-gray-300 mb-2">
Position Size ($)
{balanceLoading && <span className="ml-2 text-xs text-blue-400">Syncing...</span>}
{balance && !balanceLoading && (
<span className="ml-2 text-xs text-green-400">Auto-calculated</span>
)}
</label>
<input <input
type="number" type="number"
value={config.tradingAmount} value={config.tradingAmount}
@@ -200,6 +285,12 @@ export default function AutomationPage() {
min="10" min="10"
step="10" step="10"
/> />
{balance && (
<div className="mt-1 text-xs text-gray-400">
Available: ${balance.availableBalance?.toFixed(2)}
Using {((config.tradingAmount / balance.availableBalance) * 100).toFixed(0)}% of balance
</div>
)}
</div> </div>
<div> <div>
@@ -253,16 +344,26 @@ export default function AutomationPage() {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-300 mb-2">Max Daily Trades</label> <label className="block text-sm font-medium text-gray-300 mb-2">
<input Automation Mode
type="number" {hasOpenPosition && (
value={config.maxDailyTrades} <span className="ml-2 text-xs text-yellow-400">Position Open</span>
onChange={(e) => setConfig({...config, maxDailyTrades: parseInt(e.target.value)})} )}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500" </label>
disabled={status?.isActive} <div className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
min="1" <div className="flex items-center justify-between">
max="50" <span>AI-Driven Trading</span>
/> <div className="flex items-center space-x-2">
<div className={`w-2 h-2 rounded-full ${hasOpenPosition ? 'bg-yellow-400' : 'bg-green-400'}`}></div>
<span className="text-sm text-gray-300">
{hasOpenPosition ? 'Monitoring Position' : 'Ready to Trade'}
</span>
</div>
</div>
<div className="mt-2 text-xs text-gray-400">
Bot will enter trades based on AI analysis when no position is open
</div>
</div>
</div> </div>
</div> </div>
@@ -274,7 +375,64 @@ export default function AutomationPage() {
<div className="space-y-6"> <div className="space-y-6">
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700"> <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Status</h3> <div className="flex items-center justify-between mb-4">
<h3 className="text-xl font-bold text-white">Account Status</h3>
<button
onClick={fetchBalance}
disabled={balanceLoading}
className="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors disabled:opacity-50 text-sm"
>
{balanceLoading ? 'Syncing...' : 'Sync'}
</button>
</div>
{balance ? (
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-300">Available Balance:</span>
<span className="text-green-400 font-semibold">${balance.availableBalance?.toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Account Value:</span>
<span className="text-blue-400 font-semibold">${balance.accountValue?.toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Unrealized P&L:</span>
<span className={`font-semibold ${balance.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{balance.unrealizedPnl >= 0 ? '+' : ''}${balance.unrealizedPnl?.toFixed(2)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Open Positions:</span>
<span className="text-yellow-400 font-semibold">{positions.length}</span>
</div>
{positions.length > 0 && (
<div className="mt-3 p-3 bg-gray-700 rounded-lg">
<div className="text-sm text-gray-300 mb-2">Active Positions:</div>
{positions.map((pos, idx) => (
<div key={idx} className="flex justify-between items-center text-xs">
<span className="text-gray-400">{pos.symbol}</span>
<span className={`font-semibold ${pos.side === 'long' ? 'text-green-400' : 'text-red-400'}`}>
{pos.side.toUpperCase()} {pos.size?.toFixed(4)}
</span>
</div>
))}
</div>
)}
</div>
) : (
<div className="text-center py-4">
{balanceLoading ? (
<div className="text-gray-400">Loading account data...</div>
) : (
<div className="text-gray-400">No account data available</div>
)}
</div>
)}
</div>
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Bot Status</h3>
{status ? ( {status ? (
<div className="space-y-3"> <div className="space-y-3">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
@@ -316,23 +474,29 @@ export default function AutomationPage() {
</div> </div>
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700"> <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Performance</h3> <h3 className="text-xl font-bold text-white mb-4">Trading Metrics</h3>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-green-400">0</div> <div className="text-2xl font-bold text-green-400">
<div className="text-xs text-gray-400">Trades</div> {balance?.accountValue ? `$${balance.accountValue.toFixed(0)}` : '$0'}
</div>
<div className="text-xs text-gray-400">Portfolio</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-blue-400">0%</div> <div className="text-2xl font-bold text-blue-400">
<div className="text-xs text-gray-400">Win Rate</div> {balance?.leverage ? `${(balance.leverage * 100).toFixed(1)}%` : '0%'}
</div>
<div className="text-xs text-gray-400">Leverage Used</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-purple-400">$0.00</div> <div className={`text-2xl font-bold ${balance?.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
<div className="text-xs text-gray-400">P&L</div> {balance?.unrealizedPnl ? `$${balance.unrealizedPnl.toFixed(2)}` : '$0.00'}
</div>
<div className="text-xs text-gray-400">Unrealized P&L</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-yellow-400">0</div> <div className="text-2xl font-bold text-yellow-400">{positions.length}</div>
<div className="text-xs text-gray-400">Active</div> <div className="text-xs text-gray-400">Open Positions</div>
</div> </div>
</div> </div>
</div> </div>

409
app/automation/page-new.js Normal file
View File

@@ -0,0 +1,409 @@
'use client'
import React, { useState, useEffect } from 'react'
export default function AutomationPage() {
const [config, setConfig] = useState({
mode: 'SIMULATION',
dexProvider: 'DRIFT',
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 [recentTrades, setRecentTrades] = useState([])
useEffect(() => {
fetchStatus()
const interval = setInterval(fetchStatus, 30000)
return () => clearInterval(interval)
}, [])
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 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)
}
}
return (
<div className="space-y-8">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-white">🚀 DRIFT LEVERAGE AUTOMATION</h1>
<p className="text-gray-400 mt-2">AI-powered automated trading with Drift Protocol leverage</p>
</div>
<div className="flex space-x-4">
{status?.isActive ? (
<button
onClick={handleStop}
disabled={isLoading}
className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 font-semibold"
>
{isLoading ? 'Stopping...' : 'STOP AUTOMATION'}
</button>
) : (
<button
onClick={handleStart}
disabled={isLoading}
className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 font-semibold"
>
{isLoading ? 'Starting...' : 'START AUTOMATION'}
</button>
)}
</div>
</div>
{/* Main Grid */}
<div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
{/* Configuration Column */}
<div className="xl:col-span-2 space-y-6">
{/* Drift Integration Banner */}
<div className="bg-gradient-to-r from-green-600 to-blue-600 p-6 rounded-lg border border-green-500">
<div className="text-center">
<h2 className="text-2xl font-bold text-white mb-2"> DRIFT PROTOCOL INTEGRATED</h2>
<p className="text-white">Leverage trading up to 10x Advanced risk management Live trading ready</p>
</div>
</div>
{/* Configuration Panel */}
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-6">Trading Configuration</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Trading Mode */}
<div className="space-y-3">
<label className="block text-sm font-bold text-blue-400">🎯 Trading Mode</label>
<div className="space-y-2">
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-blue-500 transition-colors">
<input
type="radio"
name="mode"
value="SIMULATION"
checked={config.mode === 'SIMULATION'}
onChange={(e) => setConfig({...config, mode: e.target.value})}
className="w-4 h-4 text-blue-600"
disabled={status?.isActive}
/>
<span className="text-white">📝 Paper Trading (Simulation)</span>
</label>
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-green-500 transition-colors">
<input
type="radio"
name="mode"
value="LIVE"
checked={config.mode === 'LIVE'}
onChange={(e) => setConfig({...config, mode: e.target.value})}
className="w-4 h-4 text-green-600"
disabled={status?.isActive}
/>
<span className="text-white font-semibold">💰 LIVE DRIFT LEVERAGE TRADING</span>
</label>
</div>
</div>
{/* DEX Provider */}
<div className="space-y-3">
<label className="block text-sm font-bold text-purple-400">🏦 DEX Provider</label>
<div className="space-y-2">
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-green-500 bg-green-900/20 transition-colors">
<input
type="radio"
name="dex"
value="DRIFT"
checked={config.dexProvider === 'DRIFT'}
onChange={(e) => setConfig({...config, dexProvider: e.target.value})}
className="w-4 h-4 text-green-600"
disabled={status?.isActive}
/>
<div>
<span className="text-white font-bold"> Drift Protocol</span>
<p className="text-green-400 text-xs"> LEVERAGE TRADING Up to 10x</p>
</div>
</label>
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-yellow-500 transition-colors">
<input
type="radio"
name="dex"
value="JUPITER"
checked={config.dexProvider === 'JUPITER'}
onChange={(e) => setConfig({...config, dexProvider: e.target.value})}
className="w-4 h-4 text-yellow-600"
disabled={status?.isActive}
/>
<div>
<span className="text-white">🔄 Jupiter DEX</span>
<p className="text-yellow-400 text-xs"> Spot Trading Only No leverage</p>
</div>
</label>
</div>
</div>
</div>
{/* Advanced Configuration */}
<div className="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Symbol</label>
<select
value={config.symbol}
onChange={(e) => setConfig({...config, symbol: e.target.value})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
>
<option value="SOLUSD">SOL/USD</option>
<option value="BTCUSD">BTC/USD</option>
<option value="ETHUSD">ETH/USD</option>
{config.dexProvider === 'DRIFT' && (
<>
<option value="APTUSD">APT/USD</option>
<option value="AVAXUSD">AVAX/USD</option>
<option value="DOGEUSD">DOGE/USD</option>
</>
)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Trading Amount ($)</label>
<input
type="number"
value={config.tradingAmount}
onChange={(e) => setConfig({...config, tradingAmount: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="10"
step="10"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">
Max Leverage {config.dexProvider === 'DRIFT' && <span className="text-green-400">(Drift: up to 10x)</span>}
</label>
<select
value={config.maxLeverage}
onChange={(e) => setConfig({...config, maxLeverage: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
>
<option value="1">1x (Spot)</option>
<option value="2">2x</option>
<option value="3">3x</option>
<option value="5">5x</option>
{config.dexProvider === 'DRIFT' && (
<>
<option value="10">10x (Drift Only)</option>
</>
)}
</select>
</div>
</div>
<div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Stop Loss (%)</label>
<input
type="number"
value={config.stopLossPercent}
onChange={(e) => setConfig({...config, stopLossPercent: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="1"
max="10"
step="0.5"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Take Profit (%)</label>
<input
type="number"
value={config.takeProfitPercent}
onChange={(e) => setConfig({...config, takeProfitPercent: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="2"
max="20"
step="1"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Max Daily Trades</label>
<input
type="number"
value={config.maxDailyTrades}
onChange={(e) => setConfig({...config, maxDailyTrades: parseInt(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="1"
max="20"
/>
</div>
</div>
</div>
</div>
{/* Status Column */}
<div className="space-y-6">
{/* Current Status */}
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">📊 Status</h3>
{status ? (
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-300">Status:</span>
<span className={`px-3 py-1 rounded-full text-sm font-bold ${
status.isActive ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
}`}>
{status.isActive ? '🟢 ACTIVE' : '🔴 STOPPED'}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Mode:</span>
<span className={`font-semibold ${
status.mode === 'LIVE' ? 'text-red-400' : 'text-blue-400'
}`}>
{status.mode}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">DEX:</span>
<span className={`font-semibold ${
config.dexProvider === 'DRIFT' ? 'text-green-400' : 'text-yellow-400'
}`}>
{config.dexProvider}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Symbol:</span>
<span className="text-white font-semibold">{config.symbol}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Leverage:</span>
<span className="text-yellow-400 font-semibold">{config.maxLeverage}x</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Amount:</span>
<span className="text-white font-semibold">${config.tradingAmount}</span>
</div>
</div>
) : (
<p className="text-gray-400">Loading status...</p>
)}
</div>
{/* Quick Stats */}
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">📈 Performance</h3>
<div className="grid grid-cols-2 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-green-400">0</div>
<div className="text-xs text-gray-400">Total Trades</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-blue-400">0%</div>
<div className="text-xs text-gray-400">Win Rate</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-purple-400">$0.00</div>
<div className="text-xs text-gray-400">Total P&L</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-yellow-400">0</div>
<div className="text-xs text-gray-400">Active</div>
</div>
</div>
</div>
{/* Drift Benefits */}
{config.dexProvider === 'DRIFT' && (
<div className="bg-gradient-to-br from-green-900/50 to-blue-900/50 p-6 rounded-lg border border-green-500/50">
<h3 className="text-lg font-bold text-green-400 mb-3"> Drift Benefits</h3>
<ul className="space-y-2 text-sm">
<li className="flex items-center space-x-2">
<span className="text-green-400"></span>
<span className="text-white">Leverage up to 10x</span>
</li>
<li className="flex items-center space-x-2">
<span className="text-green-400"></span>
<span className="text-white">Advanced risk management</span>
</li>
<li className="flex items-center space-x-2">
<span className="text-green-400"></span>
<span className="text-white">Perpetual futures</span>
</li>
<li className="flex items-center space-x-2">
<span className="text-green-400"></span>
<span className="text-white">Low fees</span>
</li>
</ul>
</div>
)}
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,344 @@
'use client'
import React, { useState, useEffect } from 'react'
export default function AutomationPage() {
const [config, setConfig] = useState({
mode: 'SIMULATION',
dexProvider: 'DRIFT',
symbol: 'SOLUSD',
timeframe: '1h',
tradingAmount: 100,
maxLeverage: 5,
stopLossPercent: 2,
takeProfitPercent: 6,
maxDailyTrades: 5,
riskPercentage: 2
})
const [status, setStatus] = useState(null)
const [isLoading, setIsLoading] = useState(false)
useEffect(() => {
fetchStatus()
const interval = setInterval(fetchStatus, 30000)
return () => clearInterval(interval)
}, [])
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 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)
}
}
return (
<div className="space-y-6">
{/* Header */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold text-white">Automated Trading</h1>
<p className="text-gray-400 mt-1">Drift Protocol</p>
</div>
<div className="flex space-x-4">
{status?.isActive ? (
<button
onClick={handleStop}
disabled={isLoading}
className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50 font-semibold"
>
{isLoading ? 'Stopping...' : 'STOP'}
</button>
) : (
<button
onClick={handleStart}
disabled={isLoading}
className="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors disabled:opacity-50 font-semibold"
>
{isLoading ? 'Starting...' : 'START'}
</button>
)}
</div>
</div>
{/* Main Grid */}
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* Configuration */}
<div className="xl:col-span-2 space-y-6">
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-6">Configuration</h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Trading Mode */}
<div className="space-y-3">
<label className="block text-sm font-bold text-blue-400">Trading Mode</label>
<div className="space-y-2">
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-blue-500 transition-colors">
<input
type="radio"
name="mode"
value="SIMULATION"
checked={config.mode === 'SIMULATION'}
onChange={(e) => setConfig({...config, mode: e.target.value})}
className="w-4 h-4 text-blue-600"
disabled={status?.isActive}
/>
<span className="text-white">Paper Trading</span>
</label>
<label className="flex items-center space-x-3 cursor-pointer p-3 rounded-lg border border-gray-600 hover:border-green-500 transition-colors">
<input
type="radio"
name="mode"
value="LIVE"
checked={config.mode === 'LIVE'}
onChange={(e) => setConfig({...config, mode: e.target.value})}
className="w-4 h-4 text-green-600"
disabled={status?.isActive}
/>
<span className="text-white font-semibold">Live Trading</span>
</label>
</div>
</div>
{/* Leverage */}
<div className="space-y-3">
<label className="block text-sm font-bold text-purple-400">Leverage</label>
<select
value={config.maxLeverage}
onChange={(e) => setConfig({...config, maxLeverage: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400"
disabled={status?.isActive}
>
<option value="1">1x - Spot</option>
<option value="2">2x</option>
<option value="3">3x</option>
<option value="5">5x</option>
<option value="10">10x</option>
<option value="20">20x</option>
<option value="50">50x</option>
<option value="100">100x</option>
</select>
</div>
</div>
{/* Parameters */}
<div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Symbol</label>
<select
value={config.symbol}
onChange={(e) => setConfig({...config, symbol: e.target.value})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
>
<option value="SOLUSD">SOL/USD</option>
<option value="BTCUSD">BTC/USD</option>
<option value="ETHUSD">ETH/USD</option>
<option value="APTUSD">APT/USD</option>
<option value="AVAXUSD">AVAX/USD</option>
<option value="DOGEUSD">DOGE/USD</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Position Size ($)</label>
<input
type="number"
value={config.tradingAmount}
onChange={(e) => setConfig({...config, tradingAmount: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="10"
step="10"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Timeframe</label>
<select
value={config.timeframe}
onChange={(e) => setConfig({...config, timeframe: e.target.value})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
>
<option value="1m">1 Minute</option>
<option value="5m">5 Minutes</option>
<option value="15m">15 Minutes</option>
<option value="1h">1 Hour</option>
<option value="4h">4 Hours</option>
<option value="1d">1 Day</option>
</select>
</div>
</div>
{/* Risk Management */}
<div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Stop Loss (%)</label>
<input
type="number"
value={config.stopLossPercent}
onChange={(e) => setConfig({...config, stopLossPercent: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="0.5"
max="20"
step="0.5"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Take Profit (%)</label>
<input
type="number"
value={config.takeProfitPercent}
onChange={(e) => setConfig({...config, takeProfitPercent: parseFloat(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="1"
max="50"
step="1"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-2">Max Daily Trades</label>
<input
type="number"
value={config.maxDailyTrades}
onChange={(e) => setConfig({...config, maxDailyTrades: parseInt(e.target.value)})}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500"
disabled={status?.isActive}
min="1"
max="50"
/>
</div>
</div>
</div>
</div>
{/* Status */}
<div className="space-y-6">
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Status</h3>
{status ? (
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-300">Status:</span>
<span className={`px-3 py-1 rounded-full text-sm font-bold ${
status.isActive ? 'bg-green-600 text-white' : 'bg-red-600 text-white'
}`}>
{status.isActive ? 'ACTIVE' : 'STOPPED'}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Mode:</span>
<span className={`font-semibold ${
status.mode === 'LIVE' ? 'text-red-400' : 'text-blue-400'
}`}>
{status.mode}
</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Protocol:</span>
<span className="font-semibold text-green-400">DRIFT</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Symbol:</span>
<span className="text-white font-semibold">{config.symbol}</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Leverage:</span>
<span className="text-yellow-400 font-semibold">{config.maxLeverage}x</span>
</div>
<div className="flex justify-between">
<span className="text-gray-300">Position Size:</span>
<span className="text-white font-semibold">${config.tradingAmount}</span>
</div>
</div>
) : (
<p className="text-gray-400">Loading...</p>
)}
</div>
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Performance</h3>
<div className="grid grid-cols-2 gap-4">
<div className="text-center">
<div className="text-2xl font-bold text-green-400">0</div>
<div className="text-xs text-gray-400">Trades</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-blue-400">0%</div>
<div className="text-xs text-gray-400">Win Rate</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-purple-400">$0.00</div>
<div className="text-xs text-gray-400">P&L</div>
</div>
<div className="text-center">
<div className="text-2xl font-bold text-yellow-400">0</div>
<div className="text-xs text-gray-400">Active</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}

View File

@@ -11,16 +11,24 @@ export default function AutomationPage() {
maxLeverage: 5, maxLeverage: 5,
stopLossPercent: 2, stopLossPercent: 2,
takeProfitPercent: 6, takeProfitPercent: 6,
maxDailyTrades: 5,
riskPercentage: 2 riskPercentage: 2
}) })
const [status, setStatus] = useState(null) const [status, setStatus] = useState(null)
const [balance, setBalance] = useState(null)
const [positions, setPositions] = useState([])
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [balanceLoading, setBalanceLoading] = useState(false)
useEffect(() => { useEffect(() => {
fetchStatus() fetchStatus()
const interval = setInterval(fetchStatus, 30000) fetchBalance()
fetchPositions()
const interval = setInterval(() => {
fetchStatus()
fetchBalance()
fetchPositions()
}, 30000)
return () => clearInterval(interval) return () => clearInterval(interval)
}, []) }, [])
@@ -36,6 +44,70 @@ export default function AutomationPage() {
} }
} }
const fetchBalance = async () => {
if (config.dexProvider !== 'DRIFT') return
setBalanceLoading(true)
try {
const response = await fetch('/api/drift/balance')
const data = await response.json()
if (data.success) {
setBalance(data)
// Auto-calculate position size based on available balance and leverage
const maxPositionSize = (data.availableBalance * config.maxLeverage) * 0.9 // Use 90% of max
const suggestedSize = Math.max(10, Math.min(maxPositionSize, config.tradingAmount))
setConfig(prev => ({
...prev,
tradingAmount: Math.round(suggestedSize)
}))
}
} catch (error) {
console.error('Failed to fetch balance:', error)
} finally {
setBalanceLoading(false)
}
}
const fetchPositions = async () => {
if (config.dexProvider !== 'DRIFT') return
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 handleLeverageChange = (newLeverage) => {
const leverage = parseFloat(newLeverage)
// Auto-calculate position size when leverage changes
if (balance?.availableBalance) {
const maxPositionSize = (balance.availableBalance * leverage) * 0.9 // Use 90% of max
const suggestedSize = Math.max(10, maxPositionSize)
setConfig(prev => ({
...prev,
maxLeverage: leverage,
tradingAmount: Math.round(suggestedSize)
}))
} else {
setConfig(prev => ({
...prev,
maxLeverage: leverage
}))
}
}
const hasOpenPosition = positions.some(pos =>
pos.symbol.includes(config.symbol.replace('USD', '')) && pos.size > 0.001
)
const handleStart = async () => { const handleStart = async () => {
setIsLoading(true) setIsLoading(true)
try { try {
@@ -149,10 +221,17 @@ export default function AutomationPage() {
{/* Leverage */} {/* Leverage */}
<div className="space-y-3"> <div className="space-y-3">
<label className="block text-sm font-bold text-purple-400">Leverage</label> <label className="block text-sm font-bold text-purple-400">
Leverage
{balance && (
<span className="ml-2 text-xs text-gray-400">
(Max position: ${(balance.availableBalance * config.maxLeverage * 0.9).toFixed(0)})
</span>
)}
</label>
<select <select
value={config.maxLeverage} value={config.maxLeverage}
onChange={(e) => setConfig({...config, maxLeverage: parseFloat(e.target.value)})} onChange={(e) => handleLeverageChange(e.target.value)}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400" className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-purple-400"
disabled={status?.isActive} disabled={status?.isActive}
> >
@@ -190,7 +269,13 @@ export default function AutomationPage() {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-300 mb-2">Position Size ($)</label> <label className="block text-sm font-medium text-gray-300 mb-2">
Position Size ($)
{balanceLoading && <span className="ml-2 text-xs text-blue-400">Syncing...</span>}
{balance && !balanceLoading && (
<span className="ml-2 text-xs text-green-400">Auto-calculated</span>
)}
</label>
<input <input
type="number" type="number"
value={config.tradingAmount} value={config.tradingAmount}
@@ -200,6 +285,12 @@ export default function AutomationPage() {
min="10" min="10"
step="10" step="10"
/> />
{balance && (
<div className="mt-1 text-xs text-gray-400">
Available: ${balance.availableBalance?.toFixed(2)}
Using {((config.tradingAmount / balance.availableBalance) * 100).toFixed(0)}% of balance
</div>
)}
</div> </div>
<div> <div>
@@ -253,16 +344,26 @@ export default function AutomationPage() {
</div> </div>
<div> <div>
<label className="block text-sm font-medium text-gray-300 mb-2">Max Daily Trades</label> <label className="block text-sm font-medium text-gray-300 mb-2">
<input Automation Mode
type="number" {hasOpenPosition && (
value={config.maxDailyTrades} <span className="ml-2 text-xs text-yellow-400">Position Open</span>
onChange={(e) => setConfig({...config, maxDailyTrades: parseInt(e.target.value)})} )}
className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white focus:border-blue-500" </label>
disabled={status?.isActive} <div className="w-full p-3 bg-gray-700 border border-gray-600 rounded-lg text-white">
min="1" <div className="flex items-center justify-between">
max="50" <span>AI-Driven Trading</span>
/> <div className="flex items-center space-x-2">
<div className={`w-2 h-2 rounded-full ${hasOpenPosition ? 'bg-yellow-400' : 'bg-green-400'}`}></div>
<span className="text-sm text-gray-300">
{hasOpenPosition ? 'Monitoring Position' : 'Ready to Trade'}
</span>
</div>
</div>
<div className="mt-2 text-xs text-gray-400">
Bot will enter trades based on AI analysis when no position is open
</div>
</div>
</div> </div>
</div> </div>
@@ -274,7 +375,64 @@ export default function AutomationPage() {
<div className="space-y-6"> <div className="space-y-6">
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700"> <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Status</h3> <div className="flex items-center justify-between mb-4">
<h3 className="text-xl font-bold text-white">Account Status</h3>
<button
onClick={fetchBalance}
disabled={balanceLoading}
className="px-3 py-1 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors disabled:opacity-50 text-sm"
>
{balanceLoading ? 'Syncing...' : 'Sync'}
</button>
</div>
{balance ? (
<div className="space-y-3">
<div className="flex justify-between items-center">
<span className="text-gray-300">Available Balance:</span>
<span className="text-green-400 font-semibold">${balance.availableBalance?.toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Account Value:</span>
<span className="text-blue-400 font-semibold">${balance.accountValue?.toFixed(2)}</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Unrealized P&L:</span>
<span className={`font-semibold ${balance.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
{balance.unrealizedPnl >= 0 ? '+' : ''}${balance.unrealizedPnl?.toFixed(2)}
</span>
</div>
<div className="flex justify-between items-center">
<span className="text-gray-300">Open Positions:</span>
<span className="text-yellow-400 font-semibold">{positions.length}</span>
</div>
{positions.length > 0 && (
<div className="mt-3 p-3 bg-gray-700 rounded-lg">
<div className="text-sm text-gray-300 mb-2">Active Positions:</div>
{positions.map((pos, idx) => (
<div key={idx} className="flex justify-between items-center text-xs">
<span className="text-gray-400">{pos.symbol}</span>
<span className={`font-semibold ${pos.side === 'long' ? 'text-green-400' : 'text-red-400'}`}>
{pos.side.toUpperCase()} {pos.size?.toFixed(4)}
</span>
</div>
))}
</div>
)}
</div>
) : (
<div className="text-center py-4">
{balanceLoading ? (
<div className="text-gray-400">Loading account data...</div>
) : (
<div className="text-gray-400">No account data available</div>
)}
</div>
)}
</div>
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Bot Status</h3>
{status ? ( {status ? (
<div className="space-y-3"> <div className="space-y-3">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center">
@@ -316,23 +474,29 @@ export default function AutomationPage() {
</div> </div>
<div className="bg-gray-800 p-6 rounded-lg border border-gray-700"> <div className="bg-gray-800 p-6 rounded-lg border border-gray-700">
<h3 className="text-xl font-bold text-white mb-4">Performance</h3> <h3 className="text-xl font-bold text-white mb-4">Trading Metrics</h3>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-green-400">0</div> <div className="text-2xl font-bold text-green-400">
<div className="text-xs text-gray-400">Trades</div> {balance?.accountValue ? `$${balance.accountValue.toFixed(0)}` : '$0'}
</div>
<div className="text-xs text-gray-400">Portfolio</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-blue-400">0%</div> <div className="text-2xl font-bold text-blue-400">
<div className="text-xs text-gray-400">Win Rate</div> {balance?.leverage ? `${(balance.leverage * 100).toFixed(1)}%` : '0%'}
</div>
<div className="text-xs text-gray-400">Leverage Used</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-purple-400">$0.00</div> <div className={`text-2xl font-bold ${balance?.unrealizedPnl >= 0 ? 'text-green-400' : 'text-red-400'}`}>
<div className="text-xs text-gray-400">P&L</div> {balance?.unrealizedPnl ? `$${balance.unrealizedPnl.toFixed(2)}` : '$0.00'}
</div>
<div className="text-xs text-gray-400">Unrealized P&L</div>
</div> </div>
<div className="text-center"> <div className="text-center">
<div className="text-2xl font-bold text-yellow-400">0</div> <div className="text-2xl font-bold text-yellow-400">{positions.length}</div>
<div className="text-xs text-gray-400">Active</div> <div className="text-xs text-gray-400">Open Positions</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -14,7 +14,6 @@ export interface AutomationConfig {
maxLeverage: number maxLeverage: number
stopLossPercent: number stopLossPercent: number
takeProfitPercent: number takeProfitPercent: number
maxDailyTrades: number
riskPercentage: number riskPercentage: number
dexProvider: 'JUPITER' | 'DRIFT' dexProvider: 'JUPITER' | 'DRIFT'
} }
@@ -234,10 +233,10 @@ export class AutomationService {
private async executeAutomationCycle(config: AutomationConfig) { private async executeAutomationCycle(config: AutomationConfig) {
console.log(`🔄 Executing automation cycle for ${config.symbol} ${config.timeframe}`) console.log(`🔄 Executing automation cycle for ${config.symbol} ${config.timeframe}`)
// Check if we've reached daily trade limit // Check for open positions first (instead of daily trade limit)
const todayTrades = await this.getTodayTradeCount(config.userId) const hasOpenPosition = await this.checkForOpenPositions(config)
if (todayTrades >= config.maxDailyTrades) { if (hasOpenPosition) {
console.log(`📊 Daily trade limit reached (${todayTrades}/${config.maxDailyTrades})`) console.log(`📊 Open position detected for ${config.symbol}, monitoring only`)
return return
} }
@@ -367,6 +366,48 @@ export class AutomationService {
return true return true
} }
private async checkForOpenPositions(config: AutomationConfig): Promise<boolean> {
try {
console.log(`🔍 Checking for open positions for ${config.symbol}`)
// For Jupiter DEX, we don't have persistent positions like in Drift
// This method would need to be implemented based on your specific needs
// For now, return false to allow trading
if (config.dexProvider === 'DRIFT') {
// Check Drift positions via API
const response = await fetch('http://localhost:3000/api/drift/positions')
if (!response.ok) {
console.warn('⚠️ Could not fetch Drift positions, assuming no open positions')
return false
}
const data = await response.json()
if (!data.success || !data.positions) {
return false
}
// Check if there's an open position for the current symbol
const symbolBase = config.symbol.replace('USD', '') // SOLUSD -> SOL
const openPosition = data.positions.find((pos: any) =>
pos.symbol.includes(symbolBase) && pos.size > 0.001
)
if (openPosition) {
console.log(`📊 Found open ${openPosition.side} position: ${openPosition.symbol} ${openPosition.size}`)
return true
}
}
return false
} catch (error) {
console.error('❌ Error checking positions:', error)
// On error, assume no positions to allow trading
return false
}
}
private async executeTrade(config: AutomationConfig, analysis: AnalysisResult, screenshotUrl: string) { private async executeTrade(config: AutomationConfig, analysis: AnalysisResult, screenshotUrl: string) {
try { try {
console.log(`🚀 Executing ${config.mode} trade: ${analysis.recommendation} ${config.symbol}`) console.log(`🚀 Executing ${config.mode} trade: ${analysis.recommendation} ${config.symbol}`)
@@ -560,27 +601,6 @@ export class AutomationService {
return intervals[timeframe] || intervals['1h'] // Default to 1 hour return intervals[timeframe] || intervals['1h'] // Default to 1 hour
} }
private async getTodayTradeCount(userId: string): Promise<number> {
const today = new Date()
today.setHours(0, 0, 0, 0)
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
const count = await prisma.trade.count({
where: {
userId,
isAutomated: true,
createdAt: {
gte: today,
lt: tomorrow
}
}
})
return count
}
private async getRecentPerformance(userId: string): Promise<{ private async getRecentPerformance(userId: string): Promise<{
winRate: number winRate: number
totalTrades: number totalTrades: number

105
lib/rpc-failover.js Normal file
View File

@@ -0,0 +1,105 @@
import { Connection } from '@solana/web3.js';
const RPC_ENDPOINTS = [
process.env.SOLANA_RPC_URL_PRIMARY,
process.env.SOLANA_RPC_URL_SECONDARY,
process.env.SOLANA_RPC_URL_TERTIARY,
process.env.SOLANA_RPC_URL_BACKUP,
].filter(Boolean); // Remove any undefined/empty URLs
let currentRpcIndex = 0;
let activeConnection = null;
/**
* Creates a Solana connection with automatic failover to backup RPCs
*/
export async function createConnectionWithFailover() {
for (let attempt = 0; attempt < RPC_ENDPOINTS.length; attempt++) {
const rpcUrl = RPC_ENDPOINTS[currentRpcIndex];
if (!rpcUrl) {
currentRpcIndex = (currentRpcIndex + 1) % RPC_ENDPOINTS.length;
continue;
}
try {
console.log(`Attempting to connect to RPC: ${rpcUrl.replace(/\/\/.*@/, '//*****@')}`);
const connection = new Connection(rpcUrl, 'confirmed');
// Test the connection by getting the latest blockhash
await connection.getLatestBlockhash();
console.log(`Successfully connected to RPC: ${rpcUrl.replace(/\/\/.*@/, '//*****@')}`);
activeConnection = connection;
return connection;
} catch (error) {
console.warn(`RPC ${rpcUrl.replace(/\/\/.*@/, '//*****@')} failed:`, error.message);
// Move to next RPC endpoint
currentRpcIndex = (currentRpcIndex + 1) % RPC_ENDPOINTS.length;
}
}
throw new Error('All RPC endpoints failed. Unable to establish connection.');
}
/**
* Gets the current active connection or creates a new one
*/
export async function getConnection() {
if (activeConnection) {
try {
// Test if current connection is still working
await activeConnection.getLatestBlockhash();
return activeConnection;
} catch (error) {
console.warn('Active connection failed, attempting failover...');
activeConnection = null;
}
}
return createConnectionWithFailover();
}
/**
* Executes a function with automatic RPC failover
*/
export async function executeWithFailover(operation, maxRetries = 3) {
let lastError = null;
for (let retry = 0; retry < maxRetries; retry++) {
try {
const connection = await getConnection();
return await operation(connection);
} catch (error) {
lastError = error;
console.warn(`Operation failed (attempt ${retry + 1}/${maxRetries}):`, error.message);
// Force connection refresh on next attempt
activeConnection = null;
// Move to next RPC endpoint
currentRpcIndex = (currentRpcIndex + 1) % RPC_ENDPOINTS.length;
// Wait a bit before retrying
if (retry < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, 1000 * (retry + 1)));
}
}
}
throw new Error(`Operation failed after ${maxRetries} attempts. Last error: ${lastError?.message}`);
}
/**
* Get information about current RPC status
*/
export function getRpcStatus() {
return {
availableEndpoints: RPC_ENDPOINTS.length,
currentEndpoint: RPC_ENDPOINTS[currentRpcIndex]?.replace(/\/\/.*@/, '//*****@'),
hasActiveConnection: !!activeConnection
};
}

Binary file not shown.