**Feature: Position Scaling** Allows adding to existing profitable positions when high-quality signals confirm trend strength. **Configuration (config/trading.ts):** - enablePositionScaling: false (disabled by default - enable after testing) - minScaleQualityScore: 75 (higher bar than initial 60) - minProfitForScale: 0.4% (must be at/past TP1) - maxScaleMultiplier: 2.0 (max 200% of original size) - scaleSizePercent: 50% (add 50% of original position) - minAdxIncrease: 5 (ADX must strengthen) - maxPricePositionForScale: 70% (don't chase resistance) **Validation Logic (check-risk endpoint):** Same-direction signal triggers scaling check if enabled: 1. Quality score ≥75 (stronger than initial entry) 2. Position profitable ≥0.4% (at/past TP1) 3. ADX increased ≥5 points (trend strengthening) 4. Price position <70% (not near resistance) 5. Total size <2x original (risk management) 6. Returns 'allowed: true, reason: Position scaling' if all pass **Execution (execute endpoint):** - Opens additional position at scale size (50% of original) - Updates ActiveTrade: timesScaled, totalScaleAdded, currentSize - Tracks originalAdx from first entry for comparison - Returns 'action: scaled' with scale details **ActiveTrade Interface:** Added fields: - originalAdx?: number (for scaling validation) - timesScaled?: number (track scaling count) - totalScaleAdded?: number (total USD added) **Example Scenario:** 1. LONG SOL at $176 (quality: 45, ADX: 13.4) - weak but entered 2. Price hits $176.70 (+0.4%) - at TP1 3. New LONG signal (quality: 78, ADX: 19) - strong confirmation 4. Scaling validation: ✅ Quality 78 ✅ Profit +0.4% ✅ ADX +5.6 ✅ Price 68% 5. Adds 50% more position at $176.70 6. Total position: 150% of original size **Conservative Design:** - Disabled by default (requires manual enabling) - Only scales INTO profitable positions (never averaging down) - Requires significant quality improvement (75 vs 60) - Requires trend confirmation (ADX increase) - Hard cap at 2x original size - Won't chase near resistance levels **Next Steps:** 1. Enable in settings: ENABLE_POSITION_SCALING=true 2. Test with small positions first 3. Monitor data: do scaled positions outperform? 4. Adjust thresholds based on results **Safety:** - All existing duplicate prevention logic intact - Flip logic unchanged (still requires quality check) - Position Manager tracks scaling state - Can be toggled on/off without code changes
458 lines
16 KiB
TypeScript
458 lines
16 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, TradingConfig } from '@/config/trading'
|
|
import { getInitializedPositionManager, ActiveTrade } from '@/lib/trading/position-manager'
|
|
import { getLastTradeTime, getLastTradeTimeForSymbol, getTradesInLastHour, getTodayPnL } from '@/lib/database/trades'
|
|
import { getPythPriceMonitor } from '@/lib/pyth/price-monitor'
|
|
|
|
export interface RiskCheckRequest {
|
|
symbol: string
|
|
direction: 'long' | 'short'
|
|
// Optional context metrics from TradingView
|
|
atr?: number
|
|
adx?: number
|
|
rsi?: number
|
|
volumeRatio?: number
|
|
pricePosition?: number
|
|
}
|
|
|
|
export interface RiskCheckResponse {
|
|
allowed: boolean
|
|
reason?: string
|
|
details?: string
|
|
qualityScore?: number
|
|
qualityReasons?: string[]
|
|
}
|
|
|
|
/**
|
|
* Position Scaling Validation
|
|
* Determines if adding to an existing position is allowed
|
|
*/
|
|
function shouldAllowScaling(
|
|
existingTrade: ActiveTrade,
|
|
newSignal: RiskCheckRequest,
|
|
config: TradingConfig
|
|
): { allowed: boolean; reasons: string[]; qualityScore?: number; qualityReasons?: string[] } {
|
|
const reasons: string[] = []
|
|
|
|
// Check if we have context metrics
|
|
if (!newSignal.atr || !newSignal.adx || !newSignal.pricePosition) {
|
|
reasons.push('Missing signal metrics for scaling validation')
|
|
return { allowed: false, reasons }
|
|
}
|
|
|
|
// 1. Calculate new signal quality score
|
|
const qualityScore = scoreSignalQuality({
|
|
atr: newSignal.atr,
|
|
adx: newSignal.adx,
|
|
rsi: newSignal.rsi || 50,
|
|
volumeRatio: newSignal.volumeRatio || 1,
|
|
pricePosition: newSignal.pricePosition,
|
|
direction: newSignal.direction,
|
|
minScore: config.minScaleQualityScore,
|
|
})
|
|
|
|
// 2. Check quality score (higher bar than initial entry)
|
|
if (qualityScore.score < config.minScaleQualityScore) {
|
|
reasons.push(`Quality score too low: ${qualityScore.score} (need ${config.minScaleQualityScore}+)`)
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score, qualityReasons: qualityScore.reasons }
|
|
}
|
|
|
|
// 3. Check current position profitability
|
|
const priceMonitor = getPythPriceMonitor()
|
|
const latestPrice = priceMonitor.getCachedPrice(newSignal.symbol)
|
|
const currentPrice = latestPrice?.price
|
|
|
|
if (!currentPrice) {
|
|
reasons.push('Unable to fetch current price')
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score }
|
|
}
|
|
|
|
const pnlPercent = existingTrade.direction === 'long'
|
|
? ((currentPrice - existingTrade.entryPrice) / existingTrade.entryPrice) * 100
|
|
: ((existingTrade.entryPrice - currentPrice) / existingTrade.entryPrice) * 100
|
|
|
|
if (pnlPercent < config.minProfitForScale) {
|
|
reasons.push(`Position not profitable enough: ${pnlPercent.toFixed(2)}% (need ${config.minProfitForScale}%+)`)
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score }
|
|
}
|
|
|
|
// 4. Check ADX trend strengthening
|
|
const originalAdx = existingTrade.originalAdx || 0
|
|
const adxIncrease = newSignal.adx - originalAdx
|
|
|
|
if (adxIncrease < config.minAdxIncrease) {
|
|
reasons.push(`ADX not strengthening enough: +${adxIncrease.toFixed(1)} (need +${config.minAdxIncrease})`)
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score }
|
|
}
|
|
|
|
// 5. Check price position (don't chase near resistance)
|
|
if (newSignal.pricePosition > config.maxPricePositionForScale) {
|
|
reasons.push(`Price too high in range: ${newSignal.pricePosition.toFixed(0)}% (max ${config.maxPricePositionForScale}%)`)
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score }
|
|
}
|
|
|
|
// 6. Check max position size (if already scaled)
|
|
const totalScaled = existingTrade.timesScaled || 0
|
|
const currentMultiplier = 1 + (totalScaled * (config.scaleSizePercent / 100))
|
|
const newMultiplier = currentMultiplier + (config.scaleSizePercent / 100)
|
|
|
|
if (newMultiplier > config.maxScaleMultiplier) {
|
|
reasons.push(`Max position size reached: ${(currentMultiplier * 100).toFixed(0)}% (max ${(config.maxScaleMultiplier * 100).toFixed(0)}%)`)
|
|
return { allowed: false, reasons, qualityScore: qualityScore.score }
|
|
}
|
|
|
|
// All checks passed!
|
|
reasons.push(`Quality: ${qualityScore.score}/100`)
|
|
reasons.push(`P&L: +${pnlPercent.toFixed(2)}%`)
|
|
reasons.push(`ADX increased: +${adxIncrease.toFixed(1)}`)
|
|
reasons.push(`Price position: ${newSignal.pricePosition.toFixed(0)}%`)
|
|
|
|
return {
|
|
allowed: true,
|
|
reasons,
|
|
qualityScore: qualityScore.score,
|
|
qualityReasons: qualityScore.reasons
|
|
}
|
|
}
|
|
|
|
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 existingPosition = existingTrades.find(trade => trade.symbol === body.symbol)
|
|
|
|
if (existingPosition) {
|
|
// SAME direction - check if position scaling is allowed
|
|
if (existingPosition.direction === body.direction) {
|
|
// Position scaling feature
|
|
if (config.enablePositionScaling) {
|
|
const scalingCheck = shouldAllowScaling(existingPosition, body, config)
|
|
|
|
if (scalingCheck.allowed) {
|
|
console.log('✅ Position scaling ALLOWED:', scalingCheck.reasons)
|
|
return NextResponse.json({
|
|
allowed: true,
|
|
reason: 'Position scaling',
|
|
details: `Scaling into ${body.direction} position - ${scalingCheck.reasons.join(', ')}`,
|
|
qualityScore: scalingCheck.qualityScore,
|
|
qualityReasons: scalingCheck.qualityReasons,
|
|
})
|
|
} else {
|
|
console.log('🚫 Position scaling BLOCKED:', scalingCheck.reasons)
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Scaling not allowed',
|
|
details: scalingCheck.reasons.join(', '),
|
|
qualityScore: scalingCheck.qualityScore,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Scaling disabled - block duplicate position
|
|
console.log('🚫 Risk check BLOCKED: Duplicate position (same direction)', {
|
|
symbol: body.symbol,
|
|
existingDirection: existingPosition.direction,
|
|
requestedDirection: body.direction,
|
|
existingEntry: existingPosition.entryPrice,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Duplicate position',
|
|
details: `Already have ${existingPosition.direction} position on ${body.symbol} (entry: $${existingPosition.entryPrice}). Enable scaling in settings to add to position.`,
|
|
})
|
|
}
|
|
|
|
// OPPOSITE direction - potential signal flip
|
|
// Don't auto-allow! Let it go through normal quality checks below
|
|
console.log('🔄 Potential signal flip detected - checking quality score', {
|
|
symbol: body.symbol,
|
|
existingDirection: existingPosition.direction,
|
|
newDirection: body.direction,
|
|
note: 'Will flip IF signal quality passes',
|
|
})
|
|
|
|
// Continue to quality checks below instead of returning early
|
|
}
|
|
|
|
// 1. Check daily drawdown limit
|
|
const todayPnL = await getTodayPnL()
|
|
if (todayPnL < config.maxDailyDrawdown) {
|
|
console.log('🚫 Risk check BLOCKED: Daily drawdown limit reached', {
|
|
todayPnL: todayPnL.toFixed(2),
|
|
maxDrawdown: config.maxDailyDrawdown,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Daily drawdown limit',
|
|
details: `Today's P&L ($${todayPnL.toFixed(2)}) has reached max drawdown limit ($${config.maxDailyDrawdown})`,
|
|
})
|
|
}
|
|
|
|
// 2. Check trades per hour limit
|
|
const tradesInLastHour = await getTradesInLastHour()
|
|
if (tradesInLastHour >= config.maxTradesPerHour) {
|
|
console.log('🚫 Risk check BLOCKED: Hourly trade limit reached', {
|
|
tradesInLastHour,
|
|
maxTradesPerHour: config.maxTradesPerHour,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Hourly trade limit',
|
|
details: `Already placed ${tradesInLastHour} trades in the last hour (max: ${config.maxTradesPerHour})`,
|
|
})
|
|
}
|
|
|
|
// 3. Check cooldown period PER SYMBOL (not global)
|
|
const lastTradeTimeForSymbol = await getLastTradeTimeForSymbol(body.symbol)
|
|
if (lastTradeTimeForSymbol && config.minTimeBetweenTrades > 0) {
|
|
const timeSinceLastTrade = Date.now() - lastTradeTimeForSymbol.getTime()
|
|
const cooldownMs = config.minTimeBetweenTrades * 60 * 1000 // Convert minutes to milliseconds
|
|
|
|
if (timeSinceLastTrade < cooldownMs) {
|
|
const remainingMs = cooldownMs - timeSinceLastTrade
|
|
const remainingMinutes = Math.ceil(remainingMs / 60000)
|
|
|
|
console.log('🚫 Risk check BLOCKED: Cooldown period active for', body.symbol, {
|
|
lastTradeTime: lastTradeTimeForSymbol.toISOString(),
|
|
timeSinceLastTradeMs: timeSinceLastTrade,
|
|
cooldownMs,
|
|
remainingMinutes,
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Cooldown period',
|
|
details: `Must wait ${remainingMinutes} more minute(s) before next ${body.symbol} trade (cooldown: ${config.minTimeBetweenTrades} min)`,
|
|
})
|
|
}
|
|
}
|
|
|
|
// 4. Check signal quality (if context metrics provided)
|
|
const hasContextMetrics = body.atr !== undefined && body.atr > 0
|
|
|
|
if (hasContextMetrics) {
|
|
const qualityScore = scoreSignalQuality({
|
|
atr: body.atr || 0,
|
|
adx: body.adx || 0,
|
|
rsi: body.rsi || 0,
|
|
volumeRatio: body.volumeRatio || 0,
|
|
pricePosition: body.pricePosition || 0,
|
|
direction: body.direction,
|
|
minScore: 60 // Hardcoded threshold
|
|
})
|
|
|
|
if (!qualityScore.passed) {
|
|
console.log('🚫 Risk check BLOCKED: Signal quality too low', {
|
|
score: qualityScore.score,
|
|
reasons: qualityScore.reasons
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: false,
|
|
reason: 'Signal quality too low',
|
|
details: `Score: ${qualityScore.score}/100 - ${qualityScore.reasons.join(', ')}`,
|
|
qualityScore: qualityScore.score,
|
|
qualityReasons: qualityScore.reasons
|
|
})
|
|
}
|
|
|
|
console.log(`✅ Risk check PASSED: All checks passed`, {
|
|
todayPnL: todayPnL.toFixed(2),
|
|
tradesLastHour: tradesInLastHour,
|
|
cooldownPassed: lastTradeTimeForSymbol ? 'yes' : `no previous ${body.symbol} trades`,
|
|
qualityScore: qualityScore.score,
|
|
qualityReasons: qualityScore.reasons
|
|
})
|
|
|
|
return NextResponse.json({
|
|
allowed: true,
|
|
details: 'All risk checks passed',
|
|
qualityScore: qualityScore.score,
|
|
qualityReasons: qualityScore.reasons
|
|
})
|
|
}
|
|
|
|
console.log(`✅ Risk check PASSED: All checks passed`, {
|
|
todayPnL: todayPnL.toFixed(2),
|
|
tradesLastHour: tradesInLastHour,
|
|
cooldownPassed: lastTradeTimeForSymbol ? 'yes' : `no previous ${body.symbol} trades`,
|
|
})
|
|
|
|
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 }
|
|
)
|
|
}
|
|
}
|
|
|
|
interface SignalQualityResult {
|
|
passed: boolean
|
|
score: number
|
|
reasons: string[]
|
|
}
|
|
|
|
/**
|
|
* Score signal quality based on context metrics from TradingView
|
|
* Returns score 0-100 and array of reasons
|
|
*/
|
|
function scoreSignalQuality(params: {
|
|
atr: number
|
|
adx: number
|
|
rsi: number
|
|
volumeRatio: number
|
|
pricePosition: number
|
|
direction: 'long' | 'short'
|
|
minScore?: number // Configurable minimum score threshold
|
|
}): SignalQualityResult {
|
|
let score = 50 // Base score
|
|
const reasons: string[] = []
|
|
|
|
// ATR check (volatility gate: 0.15% - 2.5%)
|
|
if (params.atr > 0) {
|
|
if (params.atr < 0.15) {
|
|
score -= 15
|
|
reasons.push(`ATR too low (${params.atr.toFixed(2)}% - dead market)`)
|
|
} else if (params.atr > 2.5) {
|
|
score -= 20
|
|
reasons.push(`ATR too high (${params.atr.toFixed(2)}% - too volatile)`)
|
|
} else if (params.atr >= 0.15 && params.atr < 0.4) {
|
|
score += 5
|
|
reasons.push(`ATR moderate (${params.atr.toFixed(2)}%)`)
|
|
} else {
|
|
score += 10
|
|
reasons.push(`ATR healthy (${params.atr.toFixed(2)}%)`)
|
|
}
|
|
}
|
|
|
|
// ADX check (trend strength: want >18)
|
|
if (params.adx > 0) {
|
|
if (params.adx > 25) {
|
|
score += 15
|
|
reasons.push(`Strong trend (ADX ${params.adx.toFixed(1)})`)
|
|
} else if (params.adx < 18) {
|
|
score -= 15
|
|
reasons.push(`Weak trend (ADX ${params.adx.toFixed(1)})`)
|
|
} else {
|
|
score += 5
|
|
reasons.push(`Moderate trend (ADX ${params.adx.toFixed(1)})`)
|
|
}
|
|
}
|
|
|
|
// RSI check (momentum confirmation)
|
|
if (params.rsi > 0) {
|
|
if (params.direction === 'long') {
|
|
if (params.rsi > 50 && params.rsi < 70) {
|
|
score += 10
|
|
reasons.push(`RSI supports long (${params.rsi.toFixed(1)})`)
|
|
} else if (params.rsi > 70) {
|
|
score -= 10
|
|
reasons.push(`RSI overbought (${params.rsi.toFixed(1)})`)
|
|
}
|
|
} else { // short
|
|
if (params.rsi < 50 && params.rsi > 30) {
|
|
score += 10
|
|
reasons.push(`RSI supports short (${params.rsi.toFixed(1)})`)
|
|
} else if (params.rsi < 30) {
|
|
score -= 10
|
|
reasons.push(`RSI oversold (${params.rsi.toFixed(1)})`)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Volume check (want > 1.0 = above average)
|
|
if (params.volumeRatio > 0) {
|
|
if (params.volumeRatio > 1.5) {
|
|
score += 15
|
|
reasons.push(`Very strong volume (${params.volumeRatio.toFixed(2)}x avg)`)
|
|
} else if (params.volumeRatio > 1.2) {
|
|
score += 10
|
|
reasons.push(`Strong volume (${params.volumeRatio.toFixed(2)}x avg)`)
|
|
} else if (params.volumeRatio < 0.8) {
|
|
score -= 10
|
|
reasons.push(`Weak volume (${params.volumeRatio.toFixed(2)}x avg)`)
|
|
}
|
|
}
|
|
|
|
// Price position check (avoid chasing vs breakout detection)
|
|
if (params.pricePosition > 0) {
|
|
if (params.direction === 'long' && params.pricePosition > 95) {
|
|
// High volume breakout at range top can be good
|
|
if (params.volumeRatio > 1.4) {
|
|
score += 5
|
|
reasons.push(`Volume breakout at range top (${params.pricePosition.toFixed(0)}%, vol ${params.volumeRatio.toFixed(2)}x)`)
|
|
} else {
|
|
score -= 15
|
|
reasons.push(`Price near top of range (${params.pricePosition.toFixed(0)}%) - risky long`)
|
|
}
|
|
} else if (params.direction === 'short' && params.pricePosition < 5) {
|
|
// High volume breakdown at range bottom can be good
|
|
if (params.volumeRatio > 1.4) {
|
|
score += 5
|
|
reasons.push(`Volume breakdown at range bottom (${params.pricePosition.toFixed(0)}%, vol ${params.volumeRatio.toFixed(2)}x)`)
|
|
} else {
|
|
score -= 15
|
|
reasons.push(`Price near bottom of range (${params.pricePosition.toFixed(0)}%) - risky short`)
|
|
}
|
|
} else {
|
|
score += 5
|
|
reasons.push(`Price position OK (${params.pricePosition.toFixed(0)}%)`)
|
|
}
|
|
}
|
|
|
|
// Volume breakout bonus (high volume can override other weaknesses)
|
|
if (params.volumeRatio > 1.8 && params.atr < 0.6) {
|
|
score += 10
|
|
reasons.push(`Volume breakout compensates for low ATR`)
|
|
}
|
|
|
|
const minScore = params.minScore ?? 60 // Use config value or default to 60
|
|
return {
|
|
passed: score >= minScore,
|
|
score,
|
|
reasons
|
|
}
|
|
}
|