Files
trading_bot_v4/app/api/trading/check-risk/route.ts
mindesbunister 8f90339d8d Add duplicate position prevention to risk check
- Updated risk check API to verify no existing positions on same symbol
- Use getInitializedPositionManager() to wait for trade restoration
- Updated .dockerignore to exclude test files and archive/
- Moved test-*.ts files to archive directory
- Prevents multiple positions from being opened on same symbol even if signals are valid
2025-10-27 19:08:07 +01:00

91 lines
2.5 KiB
TypeScript

/**
* 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<NextResponse<RiskCheckResponse>> {
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 }
)
}
}