critical: Fix Bug 1 (revenge external closures) & Bug 5 (validated entry bypass)

Bug 1 Fix - Revenge System External Closures:
- External closure handler now checks if SL stop-out with quality 85+
- Calls stopHuntTracker.recordStopHunt() after database save
- Enables revenge trading for on-chain order fills (not just Position Manager closes)
- Added null safety for trade.signalQualityScore (defaults to 0)
- Location: lib/trading/position-manager.ts line ~999

Bug 5 Fix - Execute Endpoint Validated Entry Bypass:
- Added isValidatedEntry check before quality threshold rejection
- Smart Validation Queue signals (quality 50-89) now execute successfully
- Logs show bypass reason and validation details (delay, original quality)
- Only affects signals with validatedEntry=true flag from queue
- Location: app/api/trading/execute/route.ts line ~228

User Clarification:
- TradingView price issue (4.47) was temporary glitch, not a bug
- Only Bug 1 (revenge) and Bug 5 (execute rejection) needed fixing
- Both fixes implemented and TypeScript errors resolved
This commit is contained in:
mindesbunister
2025-12-03 20:08:46 +01:00
parent 0f88d88dd3
commit 785b09eeed
2 changed files with 44 additions and 5 deletions

View File

@@ -225,9 +225,20 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
console.log(`✅ 5min signal confirmed - proceeding with trade execution`) console.log(`✅ 5min signal confirmed - proceeding with trade execution`)
// CRITICAL FIX (Dec 3, 2025): Check for validated entry bypass BEFORE quality threshold
// Bug Fix: Smart Validation Queue validates quality 50-89 signals, but execute endpoint was rejecting them
// Solution: If validatedEntry=true flag present, bypass quality check (signal already validated by queue)
const isValidatedEntry = body.validatedEntry === true
if (isValidatedEntry) {
console.log(`✅ VALIDATED ENTRY BYPASS: Quality ${qualityResult.score} accepted (validated by Smart Entry Queue)`)
console.log(` Original quality: ${body.originalQualityScore}, Validation delay: ${body.validationDelayMinutes}min`)
}
// CRITICAL FIX (Nov 27, 2025): Verify quality score meets minimum threshold // CRITICAL FIX (Nov 27, 2025): Verify quality score meets minimum threshold
// Bug: Quality 30 trade executed because no quality check after timeframe validation // Bug: Quality 30 trade executed because no quality check after timeframe validation
if (qualityResult.score < minQualityScore) { // ENHANCED (Dec 3, 2025): Skip this check if validatedEntry=true (already validated by queue)
if (!isValidatedEntry && qualityResult.score < minQualityScore) {
console.log(`❌ QUALITY TOO LOW: ${qualityResult.score} < ${minQualityScore} threshold for ${body.direction.toUpperCase()}`) console.log(`❌ QUALITY TOO LOW: ${qualityResult.score} < ${minQualityScore} threshold for ${body.direction.toUpperCase()}`)
console.log(` Reasons: ${qualityResult.reasons.join(', ')}`) console.log(` Reasons: ${qualityResult.reasons.join(', ')}`)
return NextResponse.json({ return NextResponse.json({
@@ -564,6 +575,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
console.log(` Possible reversal - executing at current price with caution`) console.log(` Possible reversal - executing at current price with caution`)
} }
} }
}
// Helper function for rate limit spacing // Helper function for rate limit spacing
const rpcDelay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)) const rpcDelay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

View File

@@ -995,6 +995,33 @@ export class PositionManager {
maxAdversePrice: trade.maxAdversePrice, maxAdversePrice: trade.maxAdversePrice,
}) })
console.log(`💾 External closure recorded: ${exitReason} at $${currentPrice} | P&L: $${totalRealizedPnL.toFixed(2)}`) console.log(`💾 External closure recorded: ${exitReason} at $${currentPrice} | P&L: $${totalRealizedPnL.toFixed(2)}`)
// CRITICAL FIX (Dec 3, 2025): Check revenge eligibility for external closures
// Bug Fix: External closures (on-chain SL orders) weren't checking if quality 85+ for revenge
// Solution: After DB save, check if this was a quality 85+ SL stop-out and record for revenge
const qualityScore = trade.signalQualityScore || 0
if (exitReason === 'SL' && qualityScore >= 85) {
console.log(`🔍 Quality ${qualityScore} SL stop-out (external) - checking revenge eligibility...`)
try {
const { getStopHuntTracker } = await import('./stop-hunt-tracker')
const stopHuntTracker = getStopHuntTracker()
await stopHuntTracker.recordStopHunt({
originalTradeId: trade.id,
symbol: trade.symbol,
direction: trade.direction,
stopHuntPrice: currentPrice,
originalEntryPrice: trade.entryPrice,
originalQualityScore: qualityScore,
originalADX: trade.adxAtEntry || 0,
originalATR: trade.atrAtEntry || 0,
stopLossAmount: Math.abs(totalRealizedPnL)
})
console.log(`🎯 Stop hunt recorded (external closure) - revenge window active for 4 hours`)
} catch (revengeError) {
console.error('⚠️ Failed to record stop hunt for revenge:', revengeError)
// Don't fail external closure if revenge recording fails
}
}
} catch (dbError) { } catch (dbError) {
console.error('❌ Failed to save external closure:', dbError) console.error('❌ Failed to save external closure:', dbError)
} }