🔧 Add settlement lag detection and handling
- Detect when balance is low (.53) but no positions active - This commonly occurs after position closure before profit settlement - Add _meta field to API response indicating settlement pending status - Provide explanatory note for debugging and user understanding - Backend now correctly shows 0 positions and flags settlement delay Note: Drift UI shows 16.71 but account data shows .53, likely due to settlement lag between position closure and balance update on blockchain.
This commit is contained in:
@@ -78,15 +78,26 @@ class DriftTradingService {
|
||||
const usdcBalance = data.readBigInt64LE(106);
|
||||
const usdcValue = Number(usdcBalance) / 1_000_000; // USDC has 6 decimals
|
||||
|
||||
// Extract SOL position at offset 1208 (most reliable location)
|
||||
const solPosition = data.readBigInt64LE(1208);
|
||||
// Extract SOL position at offset 432 (most current/accurate location)
|
||||
const solPosition = data.readBigInt64LE(432);
|
||||
const solAmount = Number(solPosition) / 1_000_000_000; // SOL has 9 decimals
|
||||
|
||||
// Estimate SOL price (you could fetch this from an oracle)
|
||||
const solPrice = 17.11; // Current approximate price
|
||||
const solValue = solAmount * solPrice;
|
||||
|
||||
const totalValue = usdcValue + solValue;
|
||||
// Calculate basic total from current positions
|
||||
let totalValue = usdcValue + solValue;
|
||||
|
||||
// If we have a very low total but no active positions, this might indicate
|
||||
// settlement lag where profits from closed positions aren't yet reflected
|
||||
if (totalValue < 10 && solAmount === 0) {
|
||||
console.log(`⚠️ Low balance detected with no positions - possible settlement lag`);
|
||||
console.log(` This often happens after position closure before profit settlement`);
|
||||
|
||||
// In this case, we might want to use the last known total or a fallback
|
||||
// For now, we'll note this condition but keep the calculated value
|
||||
}
|
||||
|
||||
console.log(`💰 Parsed account data:`);
|
||||
console.log(` USDC Balance: $${usdcValue.toFixed(2)}`);
|
||||
@@ -99,7 +110,8 @@ class DriftTradingService {
|
||||
solPosition: solAmount,
|
||||
solPrice,
|
||||
solValue,
|
||||
totalValue
|
||||
totalValue,
|
||||
settlementPending: totalValue < 10 && solAmount === 0
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to parse account data:', error);
|
||||
@@ -126,7 +138,14 @@ class DriftTradingService {
|
||||
notionalValue: parsed.solValue,
|
||||
unrealizedPnl,
|
||||
side: 'long' as const
|
||||
}] : []
|
||||
}] : [],
|
||||
// Add settlement status info
|
||||
...(parsed.settlementPending && {
|
||||
_meta: {
|
||||
settlementPending: true,
|
||||
note: 'Low balance with no positions may indicate settlement lag after position closure'
|
||||
}
|
||||
})
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('❌ Failed to get trading balance:', error);
|
||||
|
||||
Reference in New Issue
Block a user