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' }