Files
trading_bot_v3/record-recent-trade.js
mindesbunister 4d5fef3308 fix: record recent -2.34 stop loss trade
- Added script to record recent manual stop loss from Drift position history
- Trade: 5.34 SOL LONG at 84.265, stopped at 82 for -2.34 loss
- Updated total P&L from -9.32 to -1.66 (22 trades total)
- Corrected win rate to 9% (2 wins, 20 losses)
- Fixed automation system timeframe validation (selectedTimeframes vs timeframes)
- Automation now starts successfully but may need restart after interruption
2025-07-29 16:47:58 +02:00

101 lines
3.4 KiB
JavaScript

const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
async function recordRecentTrade() {
try {
console.log('📝 Recording recent trade from Drift Position History...');
// Data from the screenshot: 14 minutes ago stop loss
const tradeData = {
id: `drift_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
userId: 'user_main',
symbol: 'SOL-PERP',
side: 'LONG',
amount: 5.34, // 5.34 SOL from screenshot
price: 184.265, // Entry price from screenshot
entryPrice: 184.265,
exitPrice: 182, // Exit price from screenshot
stopLoss: null,
takeProfit: null,
leverage: 1,
profit: -12.34, // P&L from screenshot
pnlPercent: (-12.34 / (5.34 * 184.265)) * 100, // Calculate percentage
outcome: 'LOSS',
status: 'COMPLETED',
confidence: null,
aiAnalysis: 'Manual stop loss execution - trade recorded from Drift position history',
isAutomated: false,
tradingMode: 'PERP',
driftTxId: `DRIFT_MANUAL_${Date.now()}`,
executedAt: new Date(Date.now() - 14 * 60 * 1000), // 14 minutes ago
closedAt: new Date(Date.now() - 14 * 60 * 1000), // Same time
createdAt: new Date(Date.now() - 14 * 60 * 1000),
updatedAt: new Date()
};
console.log('📊 Trade details:');
console.log(` Symbol: ${tradeData.symbol}`);
console.log(` Side: ${tradeData.side}`);
console.log(` Amount: ${tradeData.amount} SOL`);
console.log(` Entry: $${tradeData.entryPrice}`);
console.log(` Exit: $${tradeData.exitPrice}`);
console.log(` P&L: $${tradeData.profit}`);
console.log(` P&L %: ${tradeData.pnlPercent.toFixed(2)}%`);
// Check if this trade already exists
const existingTrade = await prisma.trades.findFirst({
where: {
amount: tradeData.amount,
entryPrice: tradeData.entryPrice,
profit: tradeData.profit,
createdAt: {
gte: new Date(Date.now() - 30 * 60 * 1000) // Within last 30 minutes
}
}
});
if (existingTrade) {
console.log('⚠️ Trade already exists:', existingTrade.id);
return existingTrade;
}
// Create the trade record
const newTrade = await prisma.trades.create({
data: tradeData
});
console.log('✅ Successfully recorded trade:', newTrade.id);
// Get updated statistics
const allTrades = await prisma.trades.findMany({
where: {
status: { in: ['COMPLETED', 'EXECUTED'] },
tradingMode: { not: 'SIMULATION' },
driftTxId: { not: { startsWith: 'SIM_' } }
}
});
const completedTrades = allTrades.filter(t => t.profit !== null);
const totalPnl = completedTrades.reduce((sum, t) => sum + (t.profit || 0), 0);
const wins = completedTrades.filter(t => t.profit > 0);
const losses = completedTrades.filter(t => t.profit < 0);
console.log('\n📈 Updated Statistics:');
console.log(`Total Trades: ${completedTrades.length}`);
console.log(`Wins: ${wins.length}, Losses: ${losses.length}`);
console.log(`Win Rate: ${((wins.length / completedTrades.length) * 100).toFixed(1)}%`);
console.log(`Total P&L: $${totalPnl.toFixed(2)}`);
return newTrade;
} catch (error) {
console.error('❌ Error recording trade:', error.message);
throw error;
} finally {
await prisma.$disconnect();
}
}
recordRecentTrade();