import { NextResponse } from 'next/server'; export async function GET() { try { // Get current positions with real-time data const baseUrl = process.env.INTERNAL_API_URL || 'http://localhost:3000'; const positionsResponse = await fetch(`${baseUrl}/api/drift/positions`, { cache: 'no-store', // Force fresh data headers: { 'Cache-Control': 'no-cache' } }); const positionsData = await positionsResponse.json(); // Use real-time price from Drift positions data let currentPrice = 185.0; // Fallback price const result = { timestamp: new Date().toISOString(), hasPosition: false, position: null, stopLossProximity: null, riskLevel: 'NONE', nextAction: 'No position to monitor', recommendation: 'START_TRADING' }; if (positionsData.success && positionsData.positions.length > 0) { const position = positionsData.positions[0]; // Use real-time mark price from Drift currentPrice = position.markPrice || position.entryPrice || currentPrice; result.hasPosition = true; result.position = { symbol: position.symbol, side: position.side, size: position.size, entryPrice: position.entryPrice, currentPrice: currentPrice, unrealizedPnl: position.unrealizedPnl, notionalValue: position.notionalValue }; // Calculate stop loss proximity (mock - you'd need actual SL from order data) let stopLossPrice; if (position.side === 'long') { stopLossPrice = position.entryPrice * 0.95; // 5% below entry } else { stopLossPrice = position.entryPrice * 1.05; // 5% above entry } const distanceToSL = Math.abs(currentPrice - stopLossPrice) / currentPrice; const proximityPercent = distanceToSL * 100; result.stopLossProximity = { stopLossPrice: stopLossPrice, currentPrice: currentPrice, distancePercent: proximityPercent.toFixed(2), isNear: proximityPercent < 2.0 // Within 2% = NEAR }; // Risk assessment if (proximityPercent < 1.0) { result.riskLevel = 'CRITICAL'; result.nextAction = 'IMMEDIATE ANALYSIS REQUIRED - Price very close to SL'; result.recommendation = 'EMERGENCY_ANALYSIS'; } else if (proximityPercent < 2.0) { result.riskLevel = 'HIGH'; result.nextAction = 'Enhanced monitoring - Analyze within 5 minutes'; result.recommendation = 'URGENT_MONITORING'; } else if (proximityPercent < 5.0) { result.riskLevel = 'MEDIUM'; result.nextAction = 'Regular monitoring - Check every 10 minutes'; result.recommendation = 'NORMAL_MONITORING'; } else { result.riskLevel = 'LOW'; result.nextAction = 'Standard monitoring - Check every 30 minutes'; result.recommendation = 'RELAXED_MONITORING'; } } return NextResponse.json({ success: true, monitor: result }); } catch (error) { console.error('Position monitor error:', error); return NextResponse.json({ success: false, error: 'Failed to get position monitoring data', message: error.message }, { status: 500 }); } }