From e068c5f2e64154a7609a25cb7263857f06b9d176 Mon Sep 17 00:00:00 2001 From: mindesbunister Date: Wed, 29 Oct 2025 20:51:46 +0100 Subject: [PATCH] Phase 2: Market context capture at entry - Added getFundingRate() method to DriftService - Capture expectedEntryPrice from oracle before order execution - Capture fundingRateAtEntry from Drift Protocol - Save market context fields to database (expectedEntryPrice, fundingRateAtEntry) - Calculate entry slippage percentage in createTrade() - Fixed template literal syntax errors in execute endpoint Database fields populated: - expectedEntryPrice: Oracle price before order - entrySlippagePct: Calculated from entrySlippage - fundingRateAtEntry: Current funding rate from Drift Next: Phase 3 (analytics API) or test market context on next trade --- app/api/trading/execute/route.ts | 56 +++++++++++++++++++++++--------- lib/database/trades.ts | 22 +++++++++++-- lib/drift/client.ts | 25 ++++++++++++++ 3 files changed, 85 insertions(+), 18 deletions(-) diff --git a/app/api/trading/execute/route.ts b/app/api/trading/execute/route.ts index c8de56e..9426852 100644 --- a/app/api/trading/execute/route.ts +++ b/app/api/trading/execute/route.ts @@ -94,7 +94,7 @@ export async function POST(request: NextRequest): Promise { + this.ensureInitialized() + + try { + const perpMarketAccount = this.driftClient!.getPerpMarketAccount(marketIndex) + if (!perpMarketAccount) { + console.warn(`⚠️ No perp market account found for index ${marketIndex}`) + return null + } + + // Funding rate is stored as a number with 9 decimals (1e9) + // Convert to percentage + const fundingRate = Number(perpMarketAccount.amm.lastFundingRate) / 1e9 + + return fundingRate + } catch (error) { + console.error(`❌ Failed to get funding rate for market ${marketIndex}:`, error) + return null + } + } + /** * Get account health (margin ratio) */