🚀 Fix position sizing and add real wallet balance integration

Fixed Position Size Calculation:
- Changed input from SOL to USD for clarity
- Fixed calculation: positionSizeSOL = positionValueUSD / coinPrice
- Resolved issue where entering 0.4 SOL showed incorrect 0.0025 underneath

 Added Real Wallet Balance Integration:
- TradeModal now fetches actual wallet balance from /api/wallet/balance
- Percentage buttons now calculate from real available balance (3.40)
- No more impossible 1 SOL positions when only 3.40 available

 Enhanced Position Sizing UI:
- Added slider for smooth position adjustment ( to full balance)
- Percentage buttons (25%, 50%, 75%, 100%) now accurate
- Real-time display shows both USD and SOL amounts
- Live percentage display of balance usage

 Added Wallet Overview to Dashboard:
- Main dashboard shows real wallet balance prominently
- Trading page displays actual wallet holdings
- StatusOverview component enhanced with wallet info

- Accurate position sizing based on actual 3.40 balance
- Intuitive slider + percentage buttons
- Real-time balance updates every 30 seconds
- Clear USD/SOL conversion display
- No more calculation errors in trading modal
This commit is contained in:
mindesbunister
2025-07-15 13:41:02 +02:00
parent b0b63d5db0
commit 52454bbf98
8 changed files with 119 additions and 240 deletions

View File

@@ -1,7 +1,6 @@
'use client' 'use client'
import React, { useState } from 'react' import React, { useState } from 'react'
import AIAnalysisPanel from '../../components/AIAnalysisPanel.tsx' import AIAnalysisPanel from '../../components/AIAnalysisPanel.tsx'
import TradeExecutionPanel from '../../components/TradeExecutionPanel.js'
export default function AnalysisPage() { export default function AnalysisPage() {
const [analysisResult, setAnalysisResult] = useState(null) const [analysisResult, setAnalysisResult] = useState(null)
@@ -16,22 +15,13 @@ export default function AnalysisPage() {
<div className="space-y-8"> <div className="space-y-8">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div> <div>
<h1 className="text-3xl font-bold text-white">AI Analysis & Trading</h1> <h1 className="text-3xl font-bold text-white">AI Analysis</h1>
<p className="text-gray-400 mt-2">Get market insights and execute trades based on AI recommendations</p> <p className="text-gray-400 mt-2">Get comprehensive market insights powered by AI analysis</p>
</div> </div>
</div> </div>
<div className="grid grid-cols-1 xl:grid-cols-3 gap-8"> <div className="max-w-6xl mx-auto">
<div className="xl:col-span-2"> <AIAnalysisPanel onAnalysisComplete={handleAnalysisComplete} />
<AIAnalysisPanel onAnalysisComplete={handleAnalysisComplete} />
</div>
<div className="xl:col-span-1">
<TradeExecutionPanel
analysis={analysisResult}
symbol={currentSymbol}
/>
</div>
</div> </div>
</div> </div>
) )

View File

@@ -52,3 +52,44 @@ body {
transform: translateY(-2px); transform: translateY(-2px);
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
} }
/* Custom range slider styling */
input[type="range"] {
-webkit-appearance: none;
appearance: none;
height: 8px;
background: linear-gradient(to right, #3B82F6 0%, #3B82F6 30%, #374151 30%, #374151 100%);
border-radius: 4px;
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
background: #3B82F6;
border-radius: 50%;
cursor: pointer;
border: 2px solid #1e40af;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}
input[type="range"]::-moz-range-thumb {
width: 20px;
height: 20px;
background: #3B82F6;
border-radius: 50%;
cursor: pointer;
border: 2px solid #1e40af;
box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}
input[type="range"]:focus::-webkit-slider-thumb {
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
}
input[type="range"]:focus::-moz-range-thumb {
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
}

View File

@@ -18,16 +18,22 @@ export default function TradingPage() {
useEffect(() => { useEffect(() => {
fetchBalance() fetchBalance()
// Refresh balance every 30 seconds to keep it current
const interval = setInterval(fetchBalance, 30000)
return () => clearInterval(interval)
}, []) }, [])
const fetchBalance = async () => { const fetchBalance = async () => {
setLoading(true) setLoading(true)
try { try {
const response = await fetch('/api/trading/balance') // Use the real wallet balance API
const response = await fetch('/api/wallet/balance')
const data = await response.json() const data = await response.json()
if (data.success) { if (data.success) {
setBalance(data.balance) setBalance(data.balance)
} else {
console.error('Failed to fetch balance:', data.error)
} }
} catch (error) { } catch (error) {
console.error('Failed to fetch balance:', error) console.error('Failed to fetch balance:', error)

View File

@@ -8,7 +8,9 @@ export default function StatusOverview() {
dailyPnL: 0, dailyPnL: 0,
systemStatus: 'offline', systemStatus: 'offline',
bitqueryStatus: 'unknown', bitqueryStatus: 'unknown',
marketPrices: [] marketPrices: [],
walletBalance: null, // Real wallet balance
availableCoins: [] // Available coins in wallet
}) })
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
@@ -17,8 +19,25 @@ export default function StatusOverview() {
try { try {
setLoading(true) setLoading(true)
// Get real wallet balance
let walletBalance = null
let availableCoins = []
try {
const walletRes = await fetch('/api/wallet/balance')
if (walletRes.ok) {
const walletData = await walletRes.json()
if (walletData.success) {
walletBalance = walletData.balance
availableCoins = walletData.balance.positions || []
}
}
} catch (e) {
console.warn('Could not fetch wallet balance:', e)
}
// Get market data from Bitquery // Get market data from Bitquery
let balance = 0 let balance = walletBalance?.totalValue || 0 // Use real wallet balance
let bitqueryStatus = 'error' let bitqueryStatus = 'error'
let marketPrices = [] let marketPrices = []
@@ -29,15 +48,6 @@ export default function StatusOverview() {
if (marketData.success) { if (marketData.success) {
marketPrices = marketData.data.prices || [] marketPrices = marketData.data.prices || []
bitqueryStatus = marketData.data.status?.connected ? 'online' : 'error' bitqueryStatus = marketData.data.status?.connected ? 'online' : 'error'
// Calculate portfolio value from Bitquery
const portfolioRes = await fetch('/api/trading/balance')
if (portfolioRes.ok) {
const portfolioData = await portfolioRes.json()
if (portfolioData.success) {
balance = portfolioData.balance.totalValue || 0
}
}
} }
} }
} catch (e) { } catch (e) {
@@ -61,7 +71,9 @@ export default function StatusOverview() {
dailyPnL: 0, // No fake P&L dailyPnL: 0, // No fake P&L
systemStatus: systemStatus, systemStatus: systemStatus,
bitqueryStatus: bitqueryStatus, bitqueryStatus: bitqueryStatus,
marketPrices: marketPrices marketPrices: marketPrices,
walletBalance: walletBalance,
availableCoins: availableCoins
}) })
} catch (error) { } catch (error) {
console.error('Error fetching status:', error) console.error('Error fetching status:', error)
@@ -119,6 +131,19 @@ export default function StatusOverview() {
<p className="text-gray-400 text-sm">Portfolio Value</p> <p className="text-gray-400 text-sm">Portfolio Value</p>
</div> </div>
{/* Wallet Balance */}
{status.walletBalance && (
<div className="text-center">
<div className="w-16 h-16 bg-emerald-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
<span className="text-emerald-400 text-2xl">🪙</span>
</div>
<p className="text-2xl font-bold text-emerald-400">
{status.walletBalance.positions?.[0]?.amount?.toFixed(4) || '0.0000'} SOL
</p>
<p className="text-gray-400 text-sm">Wallet Balance</p>
</div>
)}
<div className="text-center"> <div className="text-center">
<div className="w-16 h-16 bg-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-3"> <div className="w-16 h-16 bg-purple-500/20 rounded-full flex items-center justify-center mx-auto mb-3">
<span className="text-purple-400 text-2xl">🔄</span> <span className="text-purple-400 text-2xl">🔄</span>
@@ -194,6 +219,35 @@ export default function StatusOverview() {
</div> </div>
</div> </div>
)} )}
{/* Available Coins in Wallet */}
{status.availableCoins.length > 0 && (
<div className="border-t border-gray-700 pt-6">
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-white">Available Wallet Coins</h3>
<span className="text-xs text-gray-400">Ready for Trading</span>
</div>
<div className="grid grid-cols-1 gap-3">
{status.availableCoins.map((coin, index) => (
<div key={index} className="p-3 bg-gray-800 rounded-lg">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-3">
<span className="text-lg">🪙</span>
<div>
<span className="text-white font-medium">{coin.symbol}</span>
<div className="text-xs text-gray-400">${coin.price?.toFixed(2)}</div>
</div>
</div>
<div className="text-right">
<div className="text-white font-bold">{coin.amount?.toFixed(4)}</div>
<div className="text-sm text-gray-400">${coin.usdValue?.toFixed(2)}</div>
</div>
</div>
</div>
))}
</div>
</div>
)}
</div> </div>
)} )}
</div> </div>

View File

@@ -1,183 +0,0 @@
"use client"
import React, { useState } from 'react'
interface TradeModalProps {
isOpen: boolean
onClose: () => void
tradeData: {
symbol: string
timeframe: string
entry: string
tp: string
sl: string
} | null
onExecute: (data: any) => void
}
export default function TradeModal({ isOpen, onClose, tradeData, onExecute }: TradeModalProps) {
const [loading, setLoading] = useState(false)
const [formData, setFormData] = useState({
entry: tradeData?.entry || '',
tp: tradeData?.tp || '',
sl: tradeData?.sl || '',
size: '0.1',
leverage: '1'
})
React.useEffect(() => {
if (tradeData) {
setFormData(prev => ({
...prev,
entry: tradeData.entry || '',
tp: tradeData.tp || '',
sl: tradeData.sl || ''
}))
}
}, [tradeData])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLoading(true)
try {
await onExecute({
symbol: tradeData?.symbol,
timeframe: tradeData?.timeframe,
...formData
})
} catch (error) {
console.error('Trade execution failed:', error)
} finally {
setLoading(false)
}
}
if (!isOpen || !tradeData) return null
return (
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center p-4 z-50">
<div className="bg-gray-900 border border-gray-700 rounded-xl p-6 max-w-md w-full">
<div className="flex items-center justify-between mb-6">
<h3 className="text-xl font-bold text-white flex items-center">
<span className="w-8 h-8 bg-gradient-to-br from-green-400 to-green-600 rounded-lg flex items-center justify-center mr-3">
💰
</span>
Execute Trade
</h3>
<button
onClick={onClose}
className="text-gray-400 hover:text-white transition-colors"
>
</button>
</div>
<div className="mb-4 p-3 bg-blue-500/10 border border-blue-500/30 rounded-lg">
<div className="text-sm text-blue-300">
<div><strong>Symbol:</strong> {tradeData.symbol}</div>
<div><strong>Timeframe:</strong> {tradeData.timeframe}</div>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-xs font-medium text-gray-400 mb-2">Entry Price</label>
<input
type="number"
step="0.01"
value={formData.entry}
onChange={(e) => setFormData(prev => ({ ...prev, entry: e.target.value }))}
className="w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-green-500 focus:outline-none"
placeholder="0.00"
required
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-400 mb-2">Take Profit</label>
<input
type="number"
step="0.01"
value={formData.tp}
onChange={(e) => setFormData(prev => ({ ...prev, tp: e.target.value }))}
className="w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-green-500 focus:outline-none"
placeholder="0.00"
required
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-400 mb-2">Stop Loss</label>
<input
type="number"
step="0.01"
value={formData.sl}
onChange={(e) => setFormData(prev => ({ ...prev, sl: e.target.value }))}
className="w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-red-500 focus:outline-none"
placeholder="0.00"
required
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-xs font-medium text-gray-400 mb-2">Position Size</label>
<input
type="number"
step="0.01"
value={formData.size}
onChange={(e) => setFormData(prev => ({ ...prev, size: e.target.value }))}
className="w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:border-cyan-500 focus:outline-none"
placeholder="0.1"
required
/>
</div>
<div>
<label className="block text-xs font-medium text-gray-400 mb-2">Leverage</label>
<select
value={formData.leverage}
onChange={(e) => setFormData(prev => ({ ...prev, leverage: e.target.value }))}
className="w-full px-3 py-2 bg-gray-800/50 border border-gray-700 rounded-lg text-white focus:border-cyan-500 focus:outline-none"
>
<option value="1">1x</option>
<option value="2">2x</option>
<option value="3">3x</option>
<option value="5">5x</option>
<option value="10">10x</option>
</select>
</div>
</div>
<div className="flex space-x-3 mt-6">
<button
type="button"
onClick={onClose}
className="flex-1 py-2 px-4 bg-gray-700 text-gray-300 rounded-lg hover:bg-gray-600 transition-colors"
>
Cancel
</button>
<button
type="submit"
disabled={loading}
className={`flex-1 py-2 px-4 rounded-lg font-medium transition-all ${
loading
? 'bg-gray-700 text-gray-400 cursor-not-allowed'
: 'bg-gradient-to-r from-green-500 to-green-600 text-white hover:from-green-600 hover:to-green-700 transform hover:scale-[1.02]'
}`}
>
{loading ? (
<div className="flex items-center justify-center space-x-2">
<div className="w-4 h-4 border-2 border-gray-400 border-t-transparent rounded-full animate-spin"></div>
<span>Executing...</span>
</div>
) : (
'Execute Trade'
)}
</button>
</div>
</form>
</div>
</div>
)
}

View File

@@ -1,29 +0,0 @@
# Docker Compose override for development
# This file is automatically merged with docker-compose.yml in development
# Use: docker compose up (will automatically include this file)
services:
app:
# Development-specific settings
environment:
- NODE_ENV=development
- NEXT_TELEMETRY_DISABLED=1
# Enable hot reloading for development
volumes:
- ./:/app
- /app/node_modules
- ./screenshots:/app/screenshots
- ./videos:/app/videos
- ./.env:/app/.env # Mount .env file for development
# Override command for development
command: ["npm", "run", "dev:docker"]
# Note: Using host networking so no port bindings needed
# Ports are available directly on host via network_mode: host
# Add development labels
labels:
- "traefik.enable=false"
- "dev.local=true"

View File

@@ -8,7 +8,7 @@ services:
NODE_OPTIONS: "--max-old-space-size=4096" NODE_OPTIONS: "--max-old-space-size=4096"
restart: unless-stopped restart: unless-stopped
container_name: trader
# Base environment variables (common to all environments) # Base environment variables (common to all environments)
environment: environment:
- DOCKER_ENV=true - DOCKER_ENV=true