Restore context metrics in execute endpoint and clean up test files

This commit is contained in:
mindesbunister
2025-10-31 09:09:26 +01:00
parent c88d94d14d
commit 37ce94d8f1
6 changed files with 20 additions and 208 deletions

View File

@@ -100,7 +100,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
{
success: false,
error: 'Insufficient collateral',
message: 'Free collateral: $' + health.freeCollateral.toFixed(2),
message: `Free collateral: $${health.freeCollateral.toFixed(2)}`,
},
{ status: 400 }
)
@@ -128,7 +128,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
console.error('❌ Failed to close opposite position:', closeResult.error)
// Continue anyway - we'll try to open the new position
} else {
console.log('✅ Closed ' + oppositePosition.direction + ' position at $' + closeResult.closePrice?.toFixed(4) + ' (P&L: $' + closeResult.realizedPnL?.toFixed(2) + ')')
console.log(`✅ Closed ${oppositePosition.direction} position at $${closeResult.closePrice?.toFixed(4)} (P&L: $${closeResult.realizedPnL?.toFixed(2)})`)
// Position Manager will handle cleanup (including order cancellation)
// The executeExit method already removes the trade and updates database
@@ -141,33 +141,11 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
// Calculate position size with leverage
const positionSizeUSD = config.positionSize * config.leverage
console.log('💰 Opening ' + body.direction + ' position:')
console.log(' Symbol: ' + driftSymbol)
console.log(' Base size: $' + config.positionSize)
console.log(' Leverage: ' + config.leverage + 'x')
console.log(' Total position: $' + positionSizeUSD)
// Capture market context BEFORE opening position
const { getMarketConfig } = await import('@/config/trading')
const marketConfig = getMarketConfig(driftSymbol)
let expectedEntryPrice: number | undefined
let fundingRateAtEntry: number | undefined
try {
// Get expected entry price from oracle
expectedEntryPrice = await driftService.getOraclePrice(marketConfig.driftMarketIndex)
console.log('📊 Expected entry price: $' + expectedEntryPrice.toFixed(4))
// Get funding rate
fundingRateAtEntry = await driftService.getFundingRate(marketConfig.driftMarketIndex) || undefined
if (fundingRateAtEntry) {
console.log('💸 Funding rate: ' + (fundingRateAtEntry * 100).toFixed(4) + '%')
}
} catch (error) {
console.warn('⚠️ Failed to capture market context:', error)
// Don't fail the trade if market context capture fails
}
console.log(`💰 Opening ${body.direction} position:`)
console.log(` Symbol: ${driftSymbol}`)
console.log(` Base size: $${config.positionSize}`)
console.log(` Leverage: ${config.leverage}x`)
console.log(` Total position: $${positionSizeUSD}`)
// Open position
const openResult = await openPosition({
@@ -212,9 +190,9 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
config.hardStopPercent,
body.direction
)
console.log('🛡️ Dual stop system enabled:')
console.log(' Soft stop: $' + softStopPrice.toFixed(4) + ' (' + config.softStopPercent + '%)')
console.log(' Hard stop: $' + hardStopPrice.toFixed(4) + ' (' + config.hardStopPercent + '%)')
console.log('🛡️🛡️ Dual stop system enabled:')
console.log(` Soft stop: $${softStopPrice.toFixed(4)} (${config.softStopPercent}%)`)
console.log(` Hard stop: $${hardStopPrice.toFixed(4)} (${config.hardStopPercent}%)`)
}
const tp1Price = calculatePrice(
@@ -230,10 +208,10 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
)
console.log('📊 Trade targets:')
console.log(' Entry: $' + entryPrice.toFixed(4))
console.log(' SL: $' + stopLossPrice.toFixed(4) + ' (' + config.stopLossPercent + '%)')
console.log(' TP1: $' + tp1Price.toFixed(4) + ' (' + config.takeProfit1Percent + '%)')
console.log(' TP2: $' + tp2Price.toFixed(4) + ' (' + config.takeProfit2Percent + '%)')
console.log(` Entry: $${entryPrice.toFixed(4)}`)
console.log(` SL: $${stopLossPrice.toFixed(4)} (${config.stopLossPercent}%)`)
console.log(` TP1: $${tp1Price.toFixed(4)} (${config.takeProfit1Percent}%)`)
console.log(` TP2: $${tp2Price.toFixed(4)} (${config.takeProfit2Percent}%)`)
// Calculate emergency stop
const emergencyStopPrice = calculatePrice(
@@ -269,11 +247,6 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
priceCheckCount: 0,
lastPrice: entryPrice,
lastUpdateTime: Date.now(),
maxFavorableExcursion: 0,
maxAdverseExcursion: 0,
maxFavorablePrice: entryPrice,
maxAdversePrice: entryPrice,
lastDbMetricsUpdate: Date.now(),
}
// CRITICAL FIX: Place on-chain TP/SL orders BEFORE adding to Position Manager
@@ -344,7 +317,6 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
symbol: driftSymbol,
direction: body.direction,
entryPrice,
entrySlippage: openResult.slippage,
positionSizeUSD: positionSizeUSD,
leverage: config.leverage,
stopLossPrice,
@@ -363,9 +335,6 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
hardStopPrice,
signalStrength: body.signalStrength,
timeframe: body.timeframe,
// Market context
expectedEntryPrice,
fundingRateAtEntry,
// Context metrics from TradingView
atrAtEntry: body.atr,
adxAtEntry: body.adx,
@@ -377,7 +346,7 @@ export async function POST(request: NextRequest): Promise<NextResponse<ExecuteTr
console.log('💾 Trade saved to database')
} catch (dbError) {
console.error('❌ Failed to save trade to database:', dbError)
// Don't fail the database save fails
// Don't fail the trade if database save fails
}
console.log('✅ Trade executed successfully!')