Files
trading_bot_v4/scripts/query-drift-pnl.mjs
mindesbunister 988fdb9ea4 Fix runner system + strengthen anti-chop filter
Three critical bugs fixed:
1. P&L calculation (65x inflation) - now uses collateralUSD not notional
2. handlePostTp1Adjustments() - checks tp2SizePercent===0 for runner mode
3. JavaScript || operator bug - changed to ?? for proper 0 handling

Signal quality improvements:
- Added anti-chop filter: price position <40% + ADX <25 = -25 points
- Prevents range-bound flip-flops (caught all 3 today)
- Backtest: 43.8% → 55.6% win rate, +86% profit per trade

Changes:
- lib/trading/signal-quality.ts: RANGE-BOUND CHOP penalty
- lib/drift/orders.ts: Fixed P&L calculation + transaction confirmation
- lib/trading/position-manager.ts: Runner system logic
- app/api/trading/execute/route.ts: || to ?? for tp2SizePercent
- app/api/trading/test/route.ts: || to ?? for tp1/tp2SizePercent
- prisma/schema.prisma: Added collateralUSD field
- scripts/fix_pnl_calculations.sql: Historical P&L correction
2025-11-10 15:36:51 +01:00

91 lines
3.0 KiB
JavaScript

#!/usr/bin/env node
/**
* Query Drift Protocol trade history and compare with database
*/
import { Connection, PublicKey } from '@solana/web3.js'
import { DriftClient, initialize } from '@drift-labs/sdk'
import bs58 from 'bs58'
const DRIFT_WALLET_KEY = process.env.DRIFT_WALLET_PRIVATE_KEY
const SOLANA_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'
async function queryDriftHistory() {
console.log('🔍 Querying Drift Protocol trade history...\n')
// Setup connection
const connection = new Connection(SOLANA_RPC_URL, 'confirmed')
// Parse wallet
let secretKey
if (DRIFT_WALLET_KEY.startsWith('[')) {
secretKey = new Uint8Array(JSON.parse(DRIFT_WALLET_KEY))
} else {
secretKey = bs58.decode(DRIFT_WALLET_KEY)
}
const walletKeypair = { publicKey: PublicKey.default, secretKey }
// Initialize Drift
const sdkConfig = initialize({ env: 'mainnet-beta' })
const driftClient = new DriftClient({
connection,
wallet: { publicKey: walletKeypair.publicKey },
programID: new PublicKey(sdkConfig.DRIFT_PROGRAM_ID),
opts: { commitment: 'confirmed' }
})
await driftClient.subscribe()
// Get account
const user = driftClient.getUser()
const userAccount = user.getUserAccount()
console.log('📊 Drift Account Summary:')
console.log('=' .repeat(60))
// Get total collateral
const totalCollateral = Number(user.getTotalCollateral()) / 1e6
const totalLiability = Number(user.getTotalLiabilityValue()) / 1e6
const freeCollateral = Number(user.getFreeCollateral()) / 1e6
const unrealizedPnL = Number(user.getUnrealizedPNL()) / 1e6
console.log(`Total Collateral: $${totalCollateral.toFixed(2)}`)
console.log(`Total Liability: $${totalLiability.toFixed(2)}`)
console.log(`Free Collateral: $${freeCollateral.toFixed(2)}`)
console.log(`Unrealized P&L: $${unrealizedPnL.toFixed(2)}`)
// Get settled P&L
const settledPnL = Number(userAccount.settledPerpPnl) / 1e6
console.log(`\n💰 Settled Perp P&L: $${settledPnL.toFixed(2)}`)
// Get cumulative P&L
const cumulativePnL = Number(userAccount.cumulativePerpFunding) / 1e6
console.log(`Cumulative Funding: $${cumulativePnL.toFixed(2)}`)
// Calculate deposits/withdrawals impact
const netDeposits = Number(userAccount.totalDeposits) / 1e6
const netWithdrawals = Number(userAccount.totalWithdraws) / 1e6
console.log(`\nTotal Deposits: $${netDeposits.toFixed(2)}`)
console.log(`Total Withdrawals: $${netWithdrawals.toFixed(2)}`)
console.log(`Net Deposits: $${(netDeposits - netWithdrawals).toFixed(2)}`)
// Calculate actual trading P&L
const actualTradingPnL = totalCollateral - (netDeposits - netWithdrawals)
console.log(`\n🎯 Actual Trading P&L: $${actualTradingPnL.toFixed(2)}`)
console.log(` (Total Collateral - Net Deposits)`)
await driftClient.unsubscribe()
return {
settledPnL,
unrealizedPnL,
totalCollateral,
netDeposits: netDeposits - netWithdrawals,
actualTradingPnL
}
}
queryDriftHistory().catch(console.error)