Files
trading_bot_v3/app/api/wallet/balance/route.js
mindesbunister b0b63d5db0 Fix critical balance validation and add comprehensive trading features
- Fixed CoinGecko API rate limiting with fallback SOL price (68.11)
- Corrected internal API calls to use proper Docker container ports
- Fixed balance validation to prevent trades exceeding wallet funds
- Blocked 0.5 SOL trades with only 0.073 SOL available (~2.24)

- Added persistent storage for positions, trades, and pending orders
- Implemented limit order system with auto-fill monitoring
- Created pending orders panel and management API
- Added trades history tracking and display panel
- Enhanced position tracking with P&L calculations
- Added wallet balance validation API endpoint

- Positions stored in data/positions.json
- Trade history stored in data/trades.json
- Pending orders with auto-fill logic
- Real-time balance validation before trades

- All trades now validate against actual wallet balance
- Insufficient balance trades are properly blocked
- Added comprehensive error handling and logging
- Fixed Docker networking for internal API calls

- SPOT and leveraged trading modes
- Limit orders with price monitoring
- Stop loss and take profit support
- DEX integration with Jupiter
- Real-time position updates and P&L tracking

 Tested and verified all balance validation works correctly
2025-07-14 17:19:58 +02:00

90 lines
2.8 KiB
JavaScript

import { NextResponse } from 'next/server'
import { Connection, Keypair } from '@solana/web3.js'
export async function GET() {
try {
console.log('💰 Fetching real Solana wallet balance...')
// Check if wallet is configured
if (!process.env.SOLANA_PRIVATE_KEY) {
return NextResponse.json({
success: false,
error: 'Wallet not configured',
message: 'SOLANA_PRIVATE_KEY not found in environment'
}, { status: 503 })
}
// Initialize connection and keypair
const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'
const connection = new Connection(rpcUrl, 'confirmed')
const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
const keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
// Get SOL balance
const balance = await connection.getBalance(keypair.publicKey)
const solBalance = balance / 1000000000 // Convert lamports to SOL
// Get current SOL price with fallback
let solPrice = 168.11 // Fallback price from our current market data
let change24h = 0
try {
const priceResponse = await fetch(
'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd&include_24hr_change=true'
)
if (priceResponse.ok) {
const priceData = await priceResponse.json()
if (priceData.solana?.usd) {
solPrice = priceData.solana.usd
change24h = priceData.solana.usd_24h_change || 0
console.log(`💰 Using live SOL price: $${solPrice}`)
} else {
console.log(`⚠️ Using fallback SOL price: $${solPrice} (CoinGecko data invalid)`)
}
} else {
console.log(`⚠️ Using fallback SOL price: $${solPrice} (CoinGecko rate limited)`)
}
} catch (priceError) {
console.log(`⚠️ Using fallback SOL price: $${solPrice} (CoinGecko error: ${priceError.message})`)
}
const usdValue = solBalance * solPrice
console.log(`💎 Real wallet: ${solBalance.toFixed(4)} SOL ($${usdValue.toFixed(2)})`)
return NextResponse.json({
success: true,
balance: {
totalValue: usdValue,
availableBalance: usdValue,
positions: [
{
symbol: 'SOL',
price: solPrice,
change24h: change24h,
volume24h: 0,
amount: solBalance,
usdValue: usdValue
}
]
},
wallet: {
publicKey: keypair.publicKey.toString(),
solBalance: solBalance,
usdValue: usdValue
},
timestamp: Date.now()
})
} catch (error) {
console.error('❌ Wallet balance API error:', error)
return NextResponse.json({
success: false,
error: 'Failed to fetch wallet balance',
message: error.message
}, { status: 500 })
}
}