CRITICAL FIX: Replace Jupiter with Drift Protocol in automation service

- Remove Jupiter DEX import and dependencies from automation-service-simple.ts
- Replace executeLiveTrade method to use Drift Protocol via /api/automation/trade
- Add dexProvider field to AutomationConfig interface
- Update AI risk management to use calculateAIStopLoss/calculateAITakeProfit methods
- Fix all Jupiter references to use Drift Protocol instead
- Ensure automation uses proper Drift leverage trading instead of Jupiter spot trading
- Route trades through unified API that defaults to DRIFT provider

This resolves the issue where automation was incorrectly using Jupiter DEX
instead of the configured Drift Protocol for leveraged trading.
This commit is contained in:
mindesbunister
2025-07-24 11:14:22 +02:00
parent 241c2bd436
commit 9e6de772f2
2 changed files with 46 additions and 43 deletions

View File

@@ -1,6 +1,5 @@
import { PrismaClient } from '@prisma/client' import { PrismaClient } from '@prisma/client'
import { aiAnalysisService, AnalysisResult } from './ai-analysis' import { aiAnalysisService, AnalysisResult } from './ai-analysis'
import { jupiterDEXService } from './jupiter-dex-service'
import { enhancedScreenshotService } from './enhanced-screenshot-simple' import { enhancedScreenshotService } from './enhanced-screenshot-simple'
import { TradingViewCredentials } from './tradingview-automation' import { TradingViewCredentials } from './tradingview-automation'
import { progressTracker, ProgressStatus } from './progress-tracker' import { progressTracker, ProgressStatus } from './progress-tracker'
@@ -21,6 +20,7 @@ export interface AutomationConfig {
// stopLossPercent and takeProfitPercent removed - AI calculates these automatically // stopLossPercent and takeProfitPercent removed - AI calculates these automatically
maxDailyTrades: number maxDailyTrades: number
riskPercentage: number riskPercentage: number
dexProvider?: string // DEX provider (DRIFT or JUPITER)
} }
export interface AutomationStatus { export interface AutomationStatus {
@@ -850,7 +850,7 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
// Execute simulation trade // Execute simulation trade
tradeResult = await this.executeSimulationTrade(decision) tradeResult = await this.executeSimulationTrade(decision)
} else { } else {
// Execute live trade via Jupiter // Execute live trade via Drift Protocol
console.log(`💰 LIVE TRADE: $${this.config!.tradingAmount} trading amount configured`) console.log(`💰 LIVE TRADE: $${this.config!.tradingAmount} trading amount configured`)
tradeResult = await this.executeLiveTrade(decision) tradeResult = await this.executeLiveTrade(decision)
@@ -859,7 +859,7 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
console.log('⚠️ Live trade failed, falling back to simulation for record keeping') console.log('⚠️ Live trade failed, falling back to simulation for record keeping')
tradeResult = await this.executeSimulationTrade(decision) tradeResult = await this.executeSimulationTrade(decision)
tradeResult.status = 'FAILED' tradeResult.status = 'FAILED'
tradeResult.error = 'Jupiter DEX execution failed' tradeResult.error = 'Drift Protocol execution failed'
} }
} }
@@ -922,52 +922,55 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
} }
private async executeLiveTrade(decision: any): Promise<any> { private async executeLiveTrade(decision: any): Promise<any> {
// Execute real trade via Jupiter DEX // Execute real trade via Drift Protocol
const inputToken = decision.direction === 'BUY' ? 'USDC' : 'SOL' console.log(`🌊 Executing Drift trade: ${decision.direction} ${this.config!.symbol}`)
const outputToken = decision.direction === 'BUY' ? 'SOL' : 'USDC'
const tokens = { // Calculate AI-generated stop loss and take profit from analysis
SOL: 'So11111111111111111111111111111111111111112', const stopLossPercent = decision.stopLoss || this.calculateAIStopLoss(decision)
USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', const takeProfitPercent = decision.takeProfit || this.calculateAITakeProfit(decision)
}
// Calculate proper amount for Jupiter API console.log(`🎯 AI Risk Management: SL=${stopLossPercent}%, TP=${takeProfitPercent}%`)
let swapAmount
if (decision.direction === 'BUY') {
// BUY: Use trading amount in USDC (convert to 6 decimals)
swapAmount = Math.floor(this.config!.tradingAmount * 1e6) // USDC has 6 decimals
console.log(`💱 BUY: Converting $${this.config!.tradingAmount} USDC to ${swapAmount} USDC tokens`)
} else {
// SELL: Use SOL amount (convert to 9 decimals)
swapAmount = Math.floor(decision.positionSize * 1e9) // SOL has 9 decimals
console.log(`💱 SELL: Converting ${decision.positionSize} SOL to ${swapAmount} SOL tokens`)
}
console.log(`🔄 Executing Jupiter swap with corrected amount: ${swapAmount}`) // Call the unified trading API endpoint that routes to Drift
const tradeResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/api/automation/trade`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
dexProvider: this.config!.dexProvider || 'DRIFT',
action: 'place_order',
symbol: this.config!.symbol,
amount: this.config!.tradingAmount,
side: decision.direction.toLowerCase(),
leverage: this.config!.maxLeverage || 2,
stopLoss: true,
takeProfit: true,
stopLossPercent: stopLossPercent,
takeProfitPercent: takeProfitPercent,
mode: this.config!.mode || 'SIMULATION'
})
})
const swapResult = await jupiterDEXService.executeSwap( const tradeResult = await tradeResponse.json()
tokens[inputToken as keyof typeof tokens],
tokens[outputToken as keyof typeof tokens],
swapAmount,
50 // 0.5% slippage
)
// Convert Jupiter result to standard trade result format // Convert Drift result to standard trade result format
if (swapResult.success) { if (tradeResult.success) {
return { return {
transactionId: swapResult.txId, transactionId: tradeResult.result?.transactionId || tradeResult.result?.txId,
executionPrice: swapResult.executionPrice, executionPrice: tradeResult.result?.executionPrice,
amount: swapResult.outputAmount, // Amount of tokens received amount: tradeResult.result?.amount,
direction: decision.direction, direction: decision.direction,
status: 'COMPLETED', status: 'COMPLETED',
timestamp: new Date(), timestamp: new Date(),
fees: swapResult.fees || 0, leverage: tradeResult.leverageUsed || this.config!.maxLeverage,
slippage: swapResult.slippage || 0, stopLoss: stopLossPercent,
inputAmount: swapResult.inputAmount, // Amount of tokens spent takeProfit: takeProfitPercent,
tradingAmount: this.config!.tradingAmount // Original USD amount tradingAmount: this.config!.tradingAmount,
dexProvider: 'DRIFT'
} }
} else { } else {
throw new Error(swapResult.error || 'Jupiter swap failed') throw new Error(tradeResult.error || 'Drift trade execution failed')
} }
} }
@@ -982,7 +985,7 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
return return
} }
// For live trades, use the actual amounts from Jupiter // For live trades, use the actual amounts from Drift
const tradeAmount = result.tradingAmount ? this.config!.tradingAmount : decision.positionSize const tradeAmount = result.tradingAmount ? this.config!.tradingAmount : decision.positionSize
const actualAmount = result.amount || decision.positionSize const actualAmount = result.amount || decision.positionSize
@@ -1005,11 +1008,11 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
confidence: decision.confidence, confidence: decision.confidence,
marketSentiment: decision.marketSentiment, marketSentiment: decision.marketSentiment,
createdAt: new Date(), createdAt: new Date(),
// Add Jupiter-specific fields for live trades // Add Drift-specific fields for live trades
...(this.config!.mode === 'LIVE' && result.tradingAmount && { ...(this.config!.mode === 'LIVE' && result.tradingAmount && {
realTradingAmount: this.config!.tradingAmount, realTradingAmount: this.config!.tradingAmount,
inputAmount: result.inputAmount, leverage: result.leverage,
slippage: result.slippage driftTxId: result.transactionId
}) })
} }
}) })

Binary file not shown.