🔧 CRITICAL FIX: Price Data Sync & Position Monitor Enhancement

Fixed major price data sync issues:
- Removed hardcoded price (77.63) from position monitor
- Added real-time oracle data instead of stale TWAP pricing
- Implemented cache-busting headers for fresh data
- Updated fallback prices to current market levels

- Real-time P&L tracking with trend indicators (📈📉➡️)
- Enhanced stop loss proximity alerts with color-coded risk levels
- Analysis progress indicators during automation cycles
- Performance metrics (runtime, cycles, trades, errors)
- Fresh data validation and improved error handling

- Price accuracy: 77.63 → 84.47 (matches Drift UI)
- P&L accuracy: -.91 → -.59 (correct calculation)
- Risk assessment: CRITICAL → MEDIUM (proper evaluation)
- Stop loss distance: 0.91% → 4.8% (safe distance)

- CLI monitor script with 8-second updates
- Web dashboard component (PositionMonitor.tsx)
- Real-time automation status tracking
- Database and error monitoring improvements

This fixes the automation showing false emergency alerts when
position was actually performing normally.
This commit is contained in:
mindesbunister
2025-07-25 23:33:06 +02:00
parent 08f9a9b541
commit 9b6a393e06
18 changed files with 6783 additions and 361 deletions

View File

@@ -3,7 +3,14 @@ import { executeWithFailover, getRpcStatus } from '../../../../lib/rpc-failover.
export async function GET() {
try {
console.log('📊 Getting Drift positions...')
console.log('📊 Getting fresh Drift positions...')
// Add cache headers to ensure fresh data
const headers = {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
// Log RPC status
const rpcStatus = getRpcStatus()
@@ -93,22 +100,29 @@ export async function GET() {
// Get quote asset amount (PnL)
const quoteAssetAmount = Number(position.quoteAssetAmount) / 1e6 // Convert from micro-USDC
// Get market data for current price (simplified - in production you'd get from oracle)
// Get market data for current price using fresh oracle data
let markPrice = 0
let entryPrice = 0
try {
// Try to get market data from Drift
// Get fresh oracle price instead of stale TWAP
const perpMarketAccount = driftClient.getPerpMarketAccount(marketIndex)
if (perpMarketAccount) {
markPrice = Number(perpMarketAccount.amm.lastMarkPriceTwap) / 1e6
// Use oracle price instead of TWAP for real-time data
const oracleData = perpMarketAccount.amm.historicalOracleData
if (oracleData && oracleData.lastOraclePrice) {
markPrice = Number(oracleData.lastOraclePrice) / 1e6
} else {
// Fallback to mark price if oracle not available
markPrice = Number(perpMarketAccount.amm.lastMarkPriceTwap) / 1e6
}
}
} catch (marketError) {
console.warn(`⚠️ Could not get market data for ${symbol}:`, marketError.message)
// Fallback prices
markPrice = symbol.includes('SOL') ? 166.75 :
symbol.includes('BTC') ? 121819 :
symbol.includes('ETH') ? 3041.66 : 100
// Fallback prices - use more recent estimates
markPrice = symbol.includes('SOL') ? 185.0 :
symbol.includes('BTC') ? 67000 :
symbol.includes('ETH') ? 3500 : 100
}
// Calculate entry price (simplified)
@@ -157,7 +171,8 @@ export async function GET() {
totalPositions: positions.length,
timestamp: Date.now(),
rpcEndpoint: getRpcStatus().currentEndpoint,
wallet: keypair.publicKey.toString()
wallet: keypair.publicKey.toString(),
freshData: true
}
} catch (driftError) {
@@ -173,7 +188,13 @@ export async function GET() {
}
}, 3) // Max 3 retries across different RPCs
return NextResponse.json(result)
return NextResponse.json(result, {
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0'
}
})
} catch (error) {
console.error('❌ Positions API error:', error)