- Real-time positions tracking with live P&L updates - PositionsPanel component with auto-refresh every 10s - Position creation on trade execution (DEX, Perp, Standard) - One-click position closing functionality - Stop Loss and Take Profit display with monitoring - /api/trading/positions API for CRUD operations - Real-time price updates via CoinGecko integration - Automatic position creation on successful trades - In-memory positions storage with P&L calculations - Enhanced trading page layout with positions panel - Entry price, current price, and unrealized P&L - Percentage-based P&L calculations - Portfolio summary with total value and total P&L - Transaction ID tracking for audit trail - Support for leverage positions and TP/SL orders Confirmed Working: - Position created: SOL/USDC BUY 0.02 @ 68.10 - Real-time P&L: -/bin/bash.0052 (-0.15%) - TP/SL monitoring: SL 60, TP 80 - Transaction: 5qYx7nmpgE3fHEZpjJCMtJNb1jSQVGfKhKNzJNgJ5VGV4xG2cSSpr1wtfPfbmx8zSjwHnzSgZiWsMnAWmCFQ2RVx - Clear positions display on trading page - Real-time updates without manual refresh - Intuitive close buttons for quick position management - Separate wallet holdings vs active trading positions - Professional trading interface with P&L visualization
164 lines
5.1 KiB
JavaScript
164 lines
5.1 KiB
JavaScript
import { NextResponse } from 'next/server'
|
|
|
|
// In-memory positions storage (in production, this would be a database)
|
|
let activePositions = []
|
|
|
|
export async function GET() {
|
|
try {
|
|
// Calculate current P&L for each position using real-time prices
|
|
const updatedPositions = await Promise.all(
|
|
activePositions.map(async (position) => {
|
|
try {
|
|
// Get current price from CoinGecko
|
|
const priceResponse = await fetch(
|
|
`https://api.coingecko.com/api/v3/simple/price?ids=${getCoinGeckoId(position.symbol)}&vs_currencies=usd`
|
|
)
|
|
const priceData = await priceResponse.json()
|
|
const currentPrice = priceData[getCoinGeckoId(position.symbol)]?.usd || position.entryPrice
|
|
|
|
// Calculate unrealized P&L
|
|
const priceDiff = currentPrice - position.entryPrice
|
|
const unrealizedPnl = position.side === 'BUY'
|
|
? priceDiff * position.amount
|
|
: -priceDiff * position.amount
|
|
|
|
const pnlPercentage = ((currentPrice - position.entryPrice) / position.entryPrice) * 100
|
|
const adjustedPnlPercentage = position.side === 'BUY' ? pnlPercentage : -pnlPercentage
|
|
|
|
return {
|
|
...position,
|
|
currentPrice,
|
|
unrealizedPnl,
|
|
pnlPercentage: adjustedPnlPercentage,
|
|
totalValue: position.amount * currentPrice
|
|
}
|
|
} catch (error) {
|
|
console.error(`Error updating position ${position.id}:`, error)
|
|
return position
|
|
}
|
|
})
|
|
)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
positions: updatedPositions,
|
|
totalPositions: updatedPositions.length,
|
|
totalValue: updatedPositions.reduce((sum, pos) => sum + (pos.totalValue || 0), 0),
|
|
totalPnl: updatedPositions.reduce((sum, pos) => sum + (pos.unrealizedPnl || 0), 0)
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('Error fetching positions:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to fetch positions',
|
|
positions: []
|
|
}, { status: 500 })
|
|
}
|
|
}
|
|
|
|
export async function POST(request) {
|
|
try {
|
|
const body = await request.json()
|
|
const { action, positionId, ...positionData } = body
|
|
|
|
if (action === 'add') {
|
|
// Add new position
|
|
const newPosition = {
|
|
id: `pos_${Date.now()}_${Math.random().toString(36).substr(2, 8)}`,
|
|
symbol: positionData.symbol,
|
|
side: positionData.side,
|
|
amount: parseFloat(positionData.amount),
|
|
entryPrice: parseFloat(positionData.entryPrice),
|
|
leverage: positionData.leverage || 1,
|
|
timestamp: Date.now(),
|
|
status: 'OPEN',
|
|
stopLoss: positionData.stopLoss ? parseFloat(positionData.stopLoss) : null,
|
|
takeProfit: positionData.takeProfit ? parseFloat(positionData.takeProfit) : null,
|
|
txId: positionData.txId || null
|
|
}
|
|
|
|
activePositions.push(newPosition)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
position: newPosition,
|
|
message: `Position opened: ${newPosition.side} ${newPosition.amount} ${newPosition.symbol}`
|
|
})
|
|
|
|
} else if (action === 'close') {
|
|
// Close position
|
|
const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
|
|
|
|
if (positionIndex === -1) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Position not found'
|
|
}, { status: 404 })
|
|
}
|
|
|
|
const closedPosition = activePositions[positionIndex]
|
|
closedPosition.status = 'CLOSED'
|
|
closedPosition.closedAt = Date.now()
|
|
closedPosition.exitPrice = positionData.exitPrice
|
|
|
|
// Remove from active positions
|
|
activePositions.splice(positionIndex, 1)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
position: closedPosition,
|
|
message: `Position closed: ${closedPosition.symbol}`
|
|
})
|
|
|
|
} else if (action === 'update') {
|
|
// Update position (for SL/TP changes)
|
|
const positionIndex = activePositions.findIndex(pos => pos.id === positionId)
|
|
|
|
if (positionIndex === -1) {
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Position not found'
|
|
}, { status: 404 })
|
|
}
|
|
|
|
const position = activePositions[positionIndex]
|
|
if (positionData.stopLoss !== undefined) position.stopLoss = positionData.stopLoss
|
|
if (positionData.takeProfit !== undefined) position.takeProfit = positionData.takeProfit
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
position,
|
|
message: 'Position updated successfully'
|
|
})
|
|
}
|
|
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Invalid action'
|
|
}, { status: 400 })
|
|
|
|
} catch (error) {
|
|
console.error('Error managing position:', error)
|
|
return NextResponse.json({
|
|
success: false,
|
|
error: 'Failed to manage position'
|
|
}, { status: 500 })
|
|
}
|
|
}
|
|
|
|
// Helper function to map symbols to CoinGecko IDs
|
|
function getCoinGeckoId(symbol) {
|
|
const mapping = {
|
|
'SOL': 'solana',
|
|
'SOLUSD': 'solana',
|
|
'BTC': 'bitcoin',
|
|
'ETH': 'ethereum',
|
|
'USDC': 'usd-coin',
|
|
'USDT': 'tether',
|
|
'RAY': 'raydium',
|
|
'ORCA': 'orca'
|
|
}
|
|
return mapping[symbol.replace('USD', '')] || 'solana'
|
|
}
|