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:
@@ -1,6 +1,5 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
import { aiAnalysisService, AnalysisResult } from './ai-analysis'
|
||||
import { jupiterDEXService } from './jupiter-dex-service'
|
||||
import { enhancedScreenshotService } from './enhanced-screenshot-simple'
|
||||
import { TradingViewCredentials } from './tradingview-automation'
|
||||
import { progressTracker, ProgressStatus } from './progress-tracker'
|
||||
@@ -21,6 +20,7 @@ export interface AutomationConfig {
|
||||
// stopLossPercent and takeProfitPercent removed - AI calculates these automatically
|
||||
maxDailyTrades: number
|
||||
riskPercentage: number
|
||||
dexProvider?: string // DEX provider (DRIFT or JUPITER)
|
||||
}
|
||||
|
||||
export interface AutomationStatus {
|
||||
@@ -850,7 +850,7 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
|
||||
// Execute simulation trade
|
||||
tradeResult = await this.executeSimulationTrade(decision)
|
||||
} else {
|
||||
// Execute live trade via Jupiter
|
||||
// Execute live trade via Drift Protocol
|
||||
console.log(`💰 LIVE TRADE: $${this.config!.tradingAmount} trading amount configured`)
|
||||
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')
|
||||
tradeResult = await this.executeSimulationTrade(decision)
|
||||
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> {
|
||||
// Execute real trade via Jupiter DEX
|
||||
const inputToken = decision.direction === 'BUY' ? 'USDC' : 'SOL'
|
||||
const outputToken = decision.direction === 'BUY' ? 'SOL' : 'USDC'
|
||||
// Execute real trade via Drift Protocol
|
||||
console.log(`🌊 Executing Drift trade: ${decision.direction} ${this.config!.symbol}`)
|
||||
|
||||
const tokens = {
|
||||
SOL: 'So11111111111111111111111111111111111111112',
|
||||
USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
|
||||
}
|
||||
// Calculate AI-generated stop loss and take profit from analysis
|
||||
const stopLossPercent = decision.stopLoss || this.calculateAIStopLoss(decision)
|
||||
const takeProfitPercent = decision.takeProfit || this.calculateAITakeProfit(decision)
|
||||
|
||||
console.log(`🎯 AI Risk Management: SL=${stopLossPercent}%, TP=${takeProfitPercent}%`)
|
||||
|
||||
// Calculate proper amount for Jupiter API
|
||||
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`)
|
||||
}
|
||||
// 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'
|
||||
})
|
||||
})
|
||||
|
||||
console.log(`🔄 Executing Jupiter swap with corrected amount: ${swapAmount}`)
|
||||
const tradeResult = await tradeResponse.json()
|
||||
|
||||
const swapResult = await jupiterDEXService.executeSwap(
|
||||
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
|
||||
if (swapResult.success) {
|
||||
// Convert Drift result to standard trade result format
|
||||
if (tradeResult.success) {
|
||||
return {
|
||||
transactionId: swapResult.txId,
|
||||
executionPrice: swapResult.executionPrice,
|
||||
amount: swapResult.outputAmount, // Amount of tokens received
|
||||
transactionId: tradeResult.result?.transactionId || tradeResult.result?.txId,
|
||||
executionPrice: tradeResult.result?.executionPrice,
|
||||
amount: tradeResult.result?.amount,
|
||||
direction: decision.direction,
|
||||
status: 'COMPLETED',
|
||||
timestamp: new Date(),
|
||||
fees: swapResult.fees || 0,
|
||||
slippage: swapResult.slippage || 0,
|
||||
inputAmount: swapResult.inputAmount, // Amount of tokens spent
|
||||
tradingAmount: this.config!.tradingAmount // Original USD amount
|
||||
leverage: tradeResult.leverageUsed || this.config!.maxLeverage,
|
||||
stopLoss: stopLossPercent,
|
||||
takeProfit: takeProfitPercent,
|
||||
tradingAmount: this.config!.tradingAmount,
|
||||
dexProvider: 'DRIFT'
|
||||
}
|
||||
} 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
|
||||
}
|
||||
|
||||
// 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 actualAmount = result.amount || decision.positionSize
|
||||
|
||||
@@ -1005,11 +1008,11 @@ ${validResults.map(r => `• ${r.timeframe}: ${r.analysis?.recommendation} (${r.
|
||||
confidence: decision.confidence,
|
||||
marketSentiment: decision.marketSentiment,
|
||||
createdAt: new Date(),
|
||||
// Add Jupiter-specific fields for live trades
|
||||
// Add Drift-specific fields for live trades
|
||||
...(this.config!.mode === 'LIVE' && result.tradingAmount && {
|
||||
realTradingAmount: this.config!.tradingAmount,
|
||||
inputAmount: result.inputAmount,
|
||||
slippage: result.slippage
|
||||
leverage: result.leverage,
|
||||
driftTxId: result.transactionId
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user