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
This commit is contained in:
@@ -1,10 +1,63 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
// In-memory positions storage (in production, this would be a database)
|
||||
let activePositions = []
|
||||
// Persistent storage for positions using JSON file
|
||||
const POSITIONS_FILE = path.join(process.cwd(), 'data', 'positions.json')
|
||||
const TRADES_FILE = path.join(process.cwd(), 'data', 'trades.json')
|
||||
|
||||
// Ensure data directory exists
|
||||
const dataDir = path.join(process.cwd(), 'data')
|
||||
if (!fs.existsSync(dataDir)) {
|
||||
fs.mkdirSync(dataDir, { recursive: true })
|
||||
}
|
||||
|
||||
// Helper functions for persistent storage
|
||||
function loadPositions() {
|
||||
try {
|
||||
if (fs.existsSync(POSITIONS_FILE)) {
|
||||
const data = fs.readFileSync(POSITIONS_FILE, 'utf8')
|
||||
return JSON.parse(data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading positions:', error)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function savePositions(positions) {
|
||||
try {
|
||||
fs.writeFileSync(POSITIONS_FILE, JSON.stringify(positions, null, 2))
|
||||
} catch (error) {
|
||||
console.error('Error saving positions:', error)
|
||||
}
|
||||
}
|
||||
|
||||
function loadTrades() {
|
||||
try {
|
||||
if (fs.existsSync(TRADES_FILE)) {
|
||||
const data = fs.readFileSync(TRADES_FILE, 'utf8')
|
||||
return JSON.parse(data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading trades:', error)
|
||||
}
|
||||
return []
|
||||
}
|
||||
|
||||
function saveTrades(trades) {
|
||||
try {
|
||||
fs.writeFileSync(TRADES_FILE, JSON.stringify(trades, null, 2))
|
||||
} catch (error) {
|
||||
console.error('Error saving trades:', error)
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// Load positions from persistent storage
|
||||
const activePositions = loadPositions()
|
||||
|
||||
// Calculate current P&L for each position using real-time prices
|
||||
const updatedPositions = await Promise.all(
|
||||
activePositions.map(async (position) => {
|
||||
@@ -63,6 +116,9 @@ export async function POST(request) {
|
||||
const { action, positionId, ...positionData } = body
|
||||
|
||||
if (action === 'add') {
|
||||
// Load existing positions
|
||||
const activePositions = loadPositions()
|
||||
|
||||
// Add new position
|
||||
const newPosition = {
|
||||
id: `pos_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
|
||||
@@ -79,6 +135,9 @@ export async function POST(request) {
|
||||
}
|
||||
|
||||
activePositions.push(newPosition)
|
||||
savePositions(activePositions)
|
||||
|
||||
console.log(`✅ Position created: ${newPosition.side} ${newPosition.amount} ${newPosition.symbol}`)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
@@ -87,7 +146,10 @@ export async function POST(request) {
|
||||
})
|
||||
|
||||
} else if (action === 'close') {
|
||||
// Close position
|
||||
// Load existing positions
|
||||
const activePositions = loadPositions()
|
||||
|
||||
// Close position by executing reverse trade
|
||||
const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
|
||||
|
||||
if (positionIndex === -1) {
|
||||
@@ -97,21 +159,93 @@ export async function POST(request) {
|
||||
}, { status: 404 })
|
||||
}
|
||||
|
||||
const closedPosition = activePositions[positionIndex]
|
||||
closedPosition.status = 'CLOSED'
|
||||
closedPosition.closedAt = Date.now()
|
||||
closedPosition.exitPrice = positionData.exitPrice
|
||||
const position = activePositions[positionIndex]
|
||||
const exitPrice = positionData.exitPrice || position.currentPrice || position.entryPrice
|
||||
|
||||
// Remove from active positions
|
||||
activePositions.splice(positionIndex, 1)
|
||||
// Calculate P&L
|
||||
const priceDiff = exitPrice - position.entryPrice
|
||||
const realizedPnl = position.side === 'BUY'
|
||||
? priceDiff * position.amount
|
||||
: -priceDiff * position.amount
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
position: closedPosition,
|
||||
message: `Position closed: ${closedPosition.symbol}`
|
||||
})
|
||||
console.log(`🔄 Closing position ${positionId}: ${position.side} ${position.amount} ${position.symbol}`)
|
||||
console.log(`💰 Entry: $${position.entryPrice}, Exit: $${exitPrice}, P&L: $${realizedPnl.toFixed(4)}`)
|
||||
|
||||
try {
|
||||
// Add closing trade to history
|
||||
const existingTrades = loadTrades()
|
||||
const closingTrade = {
|
||||
id: `trade_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
|
||||
symbol: position.symbol,
|
||||
side: position.side === 'BUY' ? 'SELL' : 'BUY', // Reverse side for closing
|
||||
amount: position.amount,
|
||||
price: exitPrice,
|
||||
type: 'market',
|
||||
status: 'executed',
|
||||
timestamp: Date.now(),
|
||||
txId: `close_${position.id}`,
|
||||
fee: 0,
|
||||
pnl: realizedPnl,
|
||||
dex: 'SIMULATION',
|
||||
notes: `Closed position ${position.id} with P&L $${realizedPnl.toFixed(4)}`
|
||||
}
|
||||
|
||||
existingTrades.push(closingTrade)
|
||||
|
||||
// Keep only last 100 trades
|
||||
if (existingTrades.length > 100) {
|
||||
existingTrades.splice(0, existingTrades.length - 100)
|
||||
}
|
||||
|
||||
saveTrades(existingTrades)
|
||||
console.log('✅ Closing trade added to history')
|
||||
|
||||
console.log(`💰 Position closed with P&L: $${realizedPnl.toFixed(4)}`)
|
||||
|
||||
// Update position status and remove from active
|
||||
position.status = 'CLOSED'
|
||||
position.closedAt = Date.now()
|
||||
position.exitPrice = exitPrice
|
||||
position.realizedPnl = realizedPnl
|
||||
position.closeTxId = closingTrade.txId
|
||||
|
||||
// Remove from active positions
|
||||
activePositions.splice(positionIndex, 1)
|
||||
savePositions(activePositions)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
position: position,
|
||||
closingTrade: closingTrade,
|
||||
realizedPnl: realizedPnl,
|
||||
message: `Position closed: ${position.symbol} with P&L ${realizedPnl >= 0 ? '+' : ''}$${realizedPnl.toFixed(4)}`
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error closing position:', error)
|
||||
|
||||
// Fallback: just remove position
|
||||
position.status = 'CLOSED'
|
||||
position.closedAt = Date.now()
|
||||
position.exitPrice = exitPrice
|
||||
position.realizedPnl = realizedPnl
|
||||
|
||||
activePositions.splice(positionIndex, 1)
|
||||
savePositions(activePositions)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
position: position,
|
||||
realizedPnl: realizedPnl,
|
||||
message: `Position closed (fallback): ${position.symbol}`,
|
||||
warning: 'Failed to add to trade history'
|
||||
})
|
||||
}
|
||||
|
||||
} else if (action === 'update') {
|
||||
// Load existing positions
|
||||
const activePositions = loadPositions()
|
||||
|
||||
// Update position (for SL/TP changes)
|
||||
const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
|
||||
|
||||
@@ -126,6 +260,8 @@ export async function POST(request) {
|
||||
if (positionData.stopLoss !== undefined) position.stopLoss = positionData.stopLoss
|
||||
if (positionData.takeProfit !== undefined) position.takeProfit = positionData.takeProfit
|
||||
|
||||
savePositions(activePositions)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
position,
|
||||
|
||||
Reference in New Issue
Block a user