Fix P&L calculation and signal flip detection

- Fix external closure P&L using tp1Hit flag instead of currentSize
- Add direction change detection to prevent false TP1 on signal flips
- Signal flips now recorded with accurate P&L as 'manual' exits
- Add retry logic with exponential backoff for Solana RPC rate limits
- Create /api/trading/cancel-orders endpoint for manual cleanup
- Improves data integrity for win/loss statistics
This commit is contained in:
mindesbunister
2025-11-09 17:59:50 +01:00
parent 4d533ccb53
commit 22195ed34c
15 changed files with 2166 additions and 17 deletions

View File

@@ -624,6 +624,33 @@ export async function closePosition(
/**
* Cancel all open orders for a specific market
*/
/**
* Retry a function with exponential backoff for rate limit errors
*/
async function retryWithBackoff<T>(
fn: () => Promise<T>,
maxRetries: number = 3,
baseDelay: number = 2000
): Promise<T> {
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn()
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
const isRateLimit = errorMessage.includes('429') || errorMessage.includes('rate limit')
if (!isRateLimit || attempt === maxRetries) {
throw error
}
const delay = baseDelay * Math.pow(2, attempt)
console.log(`⏳ Rate limited, retrying in ${delay / 1000}s... (attempt ${attempt + 1}/${maxRetries})`)
await new Promise(resolve => setTimeout(resolve, delay))
}
}
throw new Error('Max retries reached')
}
export async function cancelAllOrders(
symbol: string
): Promise<{ success: boolean; cancelledCount?: number; error?: string }> {
@@ -667,12 +694,14 @@ export async function cancelAllOrders(
console.log(`📋 Found ${ordersToCancel.length} open orders to cancel (including trigger orders)`)
// Cancel all orders for this market (cancels all types: LIMIT, TRIGGER_MARKET, TRIGGER_LIMIT)
const txSig = await driftClient.cancelOrders(
undefined, // Cancel by market type
marketConfig.driftMarketIndex,
undefined // No specific direction filter
)
// Cancel all orders with retry logic for rate limits
const txSig = await retryWithBackoff(async () => {
return await driftClient.cancelOrders(
undefined, // Cancel by market type
marketConfig.driftMarketIndex,
undefined // No specific direction filter
)
})
console.log(`✅ Orders cancelled! Transaction: ${txSig}`)