/** * Risk Check API Endpoint * * Called by n8n workflow before executing trade * POST /api/trading/check-risk */ import { NextRequest, NextResponse } from 'next/server' import { getMergedConfig } from '@/config/trading' import { getInitializedPositionManager } from '@/lib/trading/position-manager' export interface RiskCheckRequest { symbol: string direction: 'long' | 'short' } export interface RiskCheckResponse { allowed: boolean reason?: string details?: string } export async function POST(request: NextRequest): Promise> { try { // Verify authorization const authHeader = request.headers.get('authorization') const expectedAuth = `Bearer ${process.env.API_SECRET_KEY}` if (!authHeader || authHeader !== expectedAuth) { return NextResponse.json( { allowed: false, reason: 'Unauthorized', }, { status: 401 } ) } const body: RiskCheckRequest = await request.json() console.log('🔍 Risk check for:', body) const config = getMergedConfig() // Check for existing positions on the same symbol const positionManager = await getInitializedPositionManager() const existingTrades = Array.from(positionManager.getActiveTrades().values()) const duplicatePosition = existingTrades.find(trade => trade.symbol === body.symbol) if (duplicatePosition) { console.log('🚫 Risk check BLOCKED: Duplicate position exists', { symbol: body.symbol, existingDirection: duplicatePosition.direction, requestedDirection: body.direction, existingEntry: duplicatePosition.entryPrice, }) return NextResponse.json({ allowed: false, reason: 'Duplicate position', details: `Already have ${duplicatePosition.direction} position on ${body.symbol} (entry: $${duplicatePosition.entryPrice})`, }) } // TODO: Implement additional risk checks: // 1. Check daily drawdown // 2. Check trades per hour limit // 3. Check cooldown period // 4. Check account health console.log(`✅ Risk check PASSED: No duplicate positions`) return NextResponse.json({ allowed: true, details: 'All risk checks passed', }) } catch (error) { console.error('❌ Risk check error:', error) return NextResponse.json( { allowed: false, reason: 'Risk check failed', details: error instanceof Error ? error.message : 'Unknown error', }, { status: 500 } ) } }