feat: Enhanced Jupiter DEX with full bidirectional trading support

MAJOR ENHANCEMENTS:

- Added SELL signal processing in automation service
- Smart position management with SOL holdings verification
- Risk-adjusted sell amounts based on current portfolio
- Proper swap direction logic (SOL → USDC for shorts)
- Enhanced stop loss/take profit for both BUY and SELL orders

- Fixed investment amount calculations (corrected from 00 to actual 4)
- Implemented proportional P&L adjustment for historical trades
- Synchronized price data between analysis-details and price-monitor APIs
- Enhanced active trades display with priority sorting and visual indicators

- checkCurrentPosition(): Verifies SOL holdings before SELL orders
- calculateSellAmount(): Risk-based position sizing for shorts
- Enhanced TP/SL calculations for bidirectional trading
- Real-time price synchronization across all endpoints
- Active trades monitoring with visual enhancements

- BUY: USDC → SOL (profit from price increases)
- SELL: SOL → USDC (profit from price decreases)
- Position-aware risk management
- Confidence-based position sizing
- Proper decimal handling (SOL=9, USDC=6)

- Comprehensive Jupiter shorting test suite
- P&L calculation verification
- Position management validation
- API endpoint testing

- P&L corrected from .15 to /bin/bash.78 for 4 investment
- Active trades display enhanced with blue borders and pulsing indicators
- Full bidirectional trading now available
- Risk-managed shorting based on actual holdings

This enables making money in both bull and bear markets! 🎯
This commit is contained in:
mindesbunister
2025-07-21 17:08:48 +02:00
parent d7a1b96a80
commit 491ff51ba9
7 changed files with 859 additions and 53 deletions

View File

@@ -46,14 +46,60 @@ export async function GET() {
const totalPnL = completedTrades.reduce((sum, trade) => sum + (trade.profit || 0), 0)
const winRate = completedTrades.length > 0 ? (successfulTrades.length / completedTrades.length * 100) : 0
const currentPrice = 189.50
// 🔥 GET REAL CURRENT PRICE - SYNCHRONIZED WITH PRICE MONITOR
let currentPrice = 193.54 // Fallback price
try {
// First try to get price from price-monitor endpoint (most recent and consistent)
const priceMonitorResponse = await fetch('http://localhost:3000/api/price-monitor')
if (priceMonitorResponse.ok) {
const priceMonitorData = await priceMonitorResponse.json()
if (priceMonitorData.success && priceMonitorData.data.prices.SOLUSD) {
currentPrice = priceMonitorData.data.prices.SOLUSD
console.log('📊 Using synchronized price from price monitor:', currentPrice)
} else {
throw new Error('Price monitor data not available')
}
} else {
throw new Error('Price monitor API not responding')
}
} catch (error) {
console.warn('⚠️ Price monitor unavailable, fetching directly from Binance:', error.message)
try {
// Fallback to direct Binance API call
const priceResponse = await fetch('https://api.binance.com/api/v3/ticker/price?symbol=SOLUSDT')
if (priceResponse.ok) {
const priceData = await priceResponse.json()
currentPrice = parseFloat(priceData.price)
console.log('📊 Using backup price from Binance:', currentPrice)
}
} catch (backupError) {
console.error('⚠️ Both price sources failed, using fallback:', backupError)
}
}
const formattedTrades = recentTrades.map(trade => {
const priceChange = trade.side === 'BUY' ?
(currentPrice - trade.price) :
(trade.price - currentPrice)
// 🔥 FIX: Calculate P&L based on ACTUAL investment amount, not position size
// Get the actual trading amount from the trade or session settings
const actualTradingAmount = trade.tradingAmount || latestSession.settings?.tradingAmount || 100
const storedPositionValue = trade.amount * trade.price // What was actually bought
// Calculate proportional P&L based on actual investment
const realizedPnL = trade.status === 'COMPLETED' ? (trade.profit || 0) : null
const unrealizedPnL = trade.status === 'OPEN' ? (priceChange * trade.amount) : null
const unrealizedPnL = trade.status === 'OPEN' ?
(priceChange * trade.amount * (actualTradingAmount / storedPositionValue)) : null
console.log(`💰 P&L Calculation for trade ${trade.id}:`, {
actualTradingAmount,
storedPositionValue: storedPositionValue.toFixed(2),
priceChange: priceChange.toFixed(2),
rawPnL: (priceChange * trade.amount).toFixed(2),
adjustedPnL: unrealizedPnL?.toFixed(2),
adjustment_ratio: (actualTradingAmount / storedPositionValue).toFixed(4)
})
const entryTime = new Date(trade.createdAt)
const exitTime = trade.closedAt ? new Date(trade.closedAt) : null
@@ -71,14 +117,9 @@ export async function GET() {
return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
}
// ✅ CORRECTED CALCULATION: Fix position size for $100 investment
const tradingAmount = 100
// ✅ CORRECTED CALCULATION: Show actual investment amounts
const leverage = trade.leverage || 1
// Use real current price for calculation instead of stored wrong price
const correctTokenAmount = tradingAmount / currentPrice
const displayAmount = correctTokenAmount // Show corrected amount
const displayPositionSize = (tradingAmount * leverage).toFixed(2)
const displayPositionSize = actualTradingAmount.toFixed(2)
// Mark old trades with wrong data
const isOldWrongTrade = trade.price < 150 && trade.amount > 1.5 // Detect old wrong trades
@@ -140,15 +181,16 @@ export async function GET() {
id: trade.id,
type: 'MARKET',
side: trade.side,
amount: displayAmount,
tradingAmount: tradingAmount,
amount: trade.amount, // Keep original SOL amount for reference
tradingAmount: actualTradingAmount, // Show actual investment amount
realTradingAmount: actualTradingAmount, // Show real trading amount
leverage: leverage,
positionSize: displayPositionSize,
price: trade.price,
status: trade.status,
pnl: realizedPnL ? realizedPnL.toFixed(2) : (unrealizedPnL ? unrealizedPnL.toFixed(2) : '0.00'),
pnlPercent: realizedPnL ? `${((realizedPnL / tradingAmount) * 100).toFixed(2)}%` :
(unrealizedPnL ? `${((unrealizedPnL / tradingAmount) * 100).toFixed(2)}%` : '0.00%'),
pnlPercent: realizedPnL ? `${((realizedPnL / actualTradingAmount) * 100).toFixed(2)}%` :
(unrealizedPnL ? `${((unrealizedPnL / actualTradingAmount) * 100).toFixed(2)}%` : '0.00%'),
createdAt: trade.createdAt,
entryTime: trade.createdAt,
exitTime: trade.closedAt,
@@ -170,8 +212,13 @@ export async function GET() {
`REAL: ${result === 'WIN' ? 'Profitable' : result === 'LOSS' ? 'Loss' : result} ${trade.side} trade - Completed` :
`REAL: ${trade.side} position active - ${formatDuration(durationMinutes)}`,
isOldWrongTrade: isOldWrongTrade,
correctedAmount: isOldWrongTrade ? correctTokenAmount.toFixed(4) : null,
originalStoredPrice: trade.price
correctedAmount: isOldWrongTrade ? (actualTradingAmount / currentPrice).toFixed(4) : null,
originalStoredPrice: trade.price,
tradingMode: trade.tradingMode || latestSession.mode, // 🔥 USE ACTUAL TRADING MODE FROM DATABASE
driftTxId: trade.driftTxId, // Jupiter DEX transaction ID
fees: trade.fees || 0, // Trading fees
actualInvestment: actualTradingAmount, // Show the real investment amount
positionAdjustment: `${actualTradingAmount}/${storedPositionValue.toFixed(2)}`
}
})