From 37ce94d8f1908c841dfdb4df296b1a36c16845e8 Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Fri, 31 Oct 2025 09:09:26 +0100 Subject: [PATCH] Restore context metrics in execute endpoint and clean up test files --- app/api/trading/execute/route.ts | 61 ++++--------- app/api/trading/test-db/route.ts | 5 -- app/api/trading/test/route.ts | 5 -- lib/trading/position-manager.ts | 89 ++----------------- .../trading/check_risk_with_quality.json | 33 ------- .../trading/execute_trade_with_metrics.json | 35 -------- 6 files changed, 20 insertions(+), 208 deletions(-) delete mode 100644 workflows/trading/check_risk_with_quality.json delete mode 100644 workflows/trading/execute_trade_with_metrics.json diff --git a/app/api/trading/execute/route.ts b/app/api/trading/execute/route.ts index 4966f83..762f9b2 100644 --- a/app/api/trading/execute/route.ts +++ b/app/api/trading/execute/route.ts @@ -100,7 +100,7 @@ export async function POST(request: NextRequest): Promise trade.maxFavorableExcursion) { - trade.maxFavorableExcursion = profitPercent - trade.maxFavorablePrice = currentPrice - } - - if (profitPercent < trade.maxAdverseExcursion) { - trade.maxAdverseExcursion = profitPercent - trade.maxAdversePrice = currentPrice - } - - // Update MAE/MFE in database (throttled to every 5 seconds to avoid spam) - if (Date.now() - trade.lastDbMetricsUpdate > 5000) { - await this.updateTradeMetrics(trade) - trade.lastDbMetricsUpdate = Date.now() - } - // Track peak P&L if (trade.unrealizedPnL > trade.peakPnL) { trade.peakPnL = trade.unrealizedPnL @@ -515,7 +468,7 @@ export class PositionManager { } // 5. Take profit 2 (remaining position) - if (trade.tp1Hit && !trade.tp2Hit && this.shouldTakeProfit2(currentPrice, trade)) { + if (trade.tp1Hit && this.shouldTakeProfit2(currentPrice, trade)) { console.log(`🎊 TP2 HIT: ${trade.symbol} at ${profitPercent.toFixed(2)}%`) // Calculate how much to close based on TP2 size percent @@ -621,13 +574,8 @@ export class PositionManager { holdTimeSeconds, maxDrawdown: 0, // TODO: Track this maxGain: trade.peakPnL, - // Save final MAE/MFE values - maxFavorableExcursion: trade.maxFavorableExcursion, - maxAdverseExcursion: trade.maxAdverseExcursion, - maxFavorablePrice: trade.maxFavorablePrice, - maxAdversePrice: trade.maxAdversePrice, }) - console.log('💾 Trade saved to database with MAE: ' + trade.maxAdverseExcursion.toFixed(2) + '% | MFE: ' + trade.maxFavorableExcursion.toFixed(2) + '%') + console.log('💾 Trade saved to database') } catch (dbError) { console.error('❌ Failed to save trade exit to database:', dbError) // Don't fail the close if database fails @@ -747,10 +695,6 @@ export class PositionManager { unrealizedPnL: trade.unrealizedPnL, peakPnL: trade.peakPnL, lastPrice: trade.lastPrice, - maxFavorableExcursion: trade.maxFavorableExcursion, - maxAdverseExcursion: trade.maxAdverseExcursion, - maxFavorablePrice: trade.maxFavorablePrice, - maxAdversePrice: trade.maxAdversePrice, }) } catch (error) { console.error('❌ Failed to save trade state:', error) @@ -776,29 +720,6 @@ export class PositionManager { symbols, } } - - /** - * Update MAE/MFE metrics in database (throttled) - */ - private async updateTradeMetrics(trade: ActiveTrade): Promise { - try { - const { getPrismaClient } = await import('../database/trades') - const prisma = getPrismaClient() - - await prisma.trade.update({ - where: { id: trade.id }, - data: { - maxFavorableExcursion: trade.maxFavorableExcursion, - maxAdverseExcursion: trade.maxAdverseExcursion, - maxFavorablePrice: trade.maxFavorablePrice, - maxAdversePrice: trade.maxAdversePrice, - }, - }) - } catch (error) { - // Silent failure to avoid disrupting monitoring loop - console.error('Failed to update trade metrics:', error) - } - } } // Singleton instance diff --git a/workflows/trading/check_risk_with_quality.json b/workflows/trading/check_risk_with_quality.json deleted file mode 100644 index 7ddb68b..0000000 --- a/workflows/trading/check_risk_with_quality.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "parameters": { - "method": "POST", - "url": "http://10.0.0.48:3001/api/trading/check-risk", - "authentication": "genericCredentialType", - "genericAuthType": "httpHeaderAuth", - "sendHeaders": true, - "headerParameters": { - "parameters": [ - { - "name": "Authorization", - "value": "Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb" - }, - { - "name": "Content-Type", - "value": "application/json" - } - ] - }, - "sendBody": true, - "specifyBody": "json", - "jsonBody": "={\n \"symbol\": \"{{ $json.symbol }}\",\n \"direction\": \"{{ $json.direction }}\",\n \"atr\": {{ $json.atr || 0 }},\n \"adx\": {{ $json.adx || 0 }},\n \"rsi\": {{ $json.rsi || 0 }},\n \"volumeRatio\": {{ $json.volumeRatio || 0 }},\n \"pricePosition\": {{ $json.pricePosition || 0 }}\n}", - "options": {} - }, - "name": "Check Risk (with Quality Scoring)", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - -340, - 560 - ], - "notes": "Updated to send 5 context metrics for signal quality scoring:\n- ATR% (volatility)\n- ADX (trend strength)\n- RSI (momentum)\n- Volume Ratio (participation)\n- Price Position (range position)\n\nMinimum quality score: 60/100" -} diff --git a/workflows/trading/execute_trade_with_metrics.json b/workflows/trading/execute_trade_with_metrics.json deleted file mode 100644 index fd04046..0000000 --- a/workflows/trading/execute_trade_with_metrics.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "parameters": { - "method": "POST", - "url": "http://10.0.0.48:3001/api/trading/execute", - "authentication": "genericCredentialType", - "genericAuthType": "httpHeaderAuth", - "sendHeaders": true, - "headerParameters": { - "parameters": [ - { - "name": "Authorization", - "value": "Bearer 2a344f0149442c857fb56c038c0c7d1b113883b830bec792c76f1e0efa15d6bb" - }, - { - "name": "Content-Type", - "value": "application/json" - } - ] - }, - "sendBody": true, - "specifyBody": "json", - "jsonBody": "={\n \"symbol\": \"{{ $('Parse Signal Enhanced').item.json.symbol }}\",\n \"direction\": \"{{ $('Parse Signal Enhanced').item.json.direction }}\",\n \"timeframe\": \"{{ $('Parse Signal Enhanced').item.json.timeframe }}\",\n \"signalStrength\": \"strong\",\n \"atr\": {{ $('Parse Signal Enhanced').item.json.atr || 0 }},\n \"adx\": {{ $('Parse Signal Enhanced').item.json.adx || 0 }},\n \"rsi\": {{ $('Parse Signal Enhanced').item.json.rsi || 0 }},\n \"volumeRatio\": {{ $('Parse Signal Enhanced').item.json.volumeRatio || 0 }},\n \"pricePosition\": {{ $('Parse Signal Enhanced').item.json.pricePosition || 0 }}\n}", - "options": { - "timeout": 120000 - } - }, - "name": "Execute Trade (with Context Metrics)", - "type": "n8n-nodes-base.httpRequest", - "typeVersion": 4.2, - "position": [ - 60, - 560 - ], - "notes": "Updated to send 5 context metrics for database storage:\n- ATR% at entry\n- ADX at entry\n- RSI at entry\n- Volume Ratio at entry\n- Price Position at entry\n\nThese metrics are stored with each trade for post-trade analysis." -}