Files
trading_bot_v3/emergency-stop-loss.js
mindesbunister 416f72181e feat: enhance paper trading with comprehensive AI analysis and learning insights
New Features:
- 📊 Detailed Market Analysis Panel (similar to pro trading interface)
  * Market sentiment, recommendation, resistance/support levels
  * Detailed trading setup with entry/exit points
  * Risk management with R:R ratios and confirmation triggers
  * Technical indicators (RSI, OBV, VWAP) analysis

- 🧠 AI Learning Insights Panel
  * Real-time learning status and success rates
  * Winner/Loser trade outcome tracking
  * AI reflection messages explaining what was learned
  * Current thresholds and pattern recognition data

- 🔮 AI Database Integration
  * Shows what AI learned from previous trades
  * Current confidence thresholds and risk parameters
  * Pattern recognition for symbol/timeframe combinations
  * Next trade adjustments based on learning

- 🎓 Intelligent Learning from Outcomes
  * Automatic trade outcome analysis (winner/loser)
  * AI generates learning insights from each trade result
  * Confidence adjustment based on trade performance
  * Pattern reinforcement or correction based on results

- Beautiful gradient panels with color-coded sections
- Clear winner/loser indicators with visual feedback
- Expandable detailed analysis view
- Real-time learning progress tracking

- Completely isolated paper trading (no real money risk)
- Real market data integration for authentic learning
- Safe practice environment with professional analysis tools

This provides a complete AI learning trading simulation where users can:
1. Get real market analysis with detailed reasoning
2. Execute safe paper trades with zero risk
3. See immediate feedback on trade outcomes
4. Learn from AI reflections and insights
5. Understand how AI adapts and improves over time
2025-08-02 17:56:02 +02:00

122 lines
4.6 KiB
JavaScript

#!/usr/bin/env node
// EMERGENCY: Add stop loss to unprotected position
const axios = require('axios');
async function emergencyStopLoss() {
console.log('🚨 EMERGENCY STOP LOSS PROTECTION');
console.log('='.repeat(50));
const baseUrl = 'http://localhost:9001';
try {
// 1. Check current position
console.log('📊 Checking current position...');
const positionsResponse = await axios.get(`${baseUrl}/api/drift/positions`);
const positions = positionsResponse.data.positions;
if (positions && positions.length > 0) {
const position = positions[0];
console.log('⚠️ DANGEROUS POSITION FOUND:');
console.log(` Symbol: ${position.symbol}`);
console.log(` Side: ${position.side.toUpperCase()}`);
console.log(` Size: ${position.size}`);
console.log(` Entry: $${position.entryPrice}`);
console.log(` Current: $${position.markPrice}`);
console.log(` PnL: $${position.unrealizedPnl.toFixed(4)}`);
console.log(` Value: $${position.notionalValue.toFixed(2)}`);
// Calculate emergency stop loss (2% risk)
const entryPrice = position.entryPrice;
const isShort = position.side.toLowerCase() === 'short';
let stopLossPrice;
if (isShort) {
// SHORT position - stop loss ABOVE entry (if price goes up)
stopLossPrice = entryPrice * 1.02; // 2% above entry
} else {
// LONG position - stop loss BELOW entry (if price goes down)
stopLossPrice = entryPrice * 0.98; // 2% below entry
}
console.log(`\n🛡️ PLACING EMERGENCY STOP LOSS:`);
console.log(` Stop Loss Price: $${stopLossPrice.toFixed(3)}`);
console.log(` Risk: 2% of position value`);
// Place stop loss order
try {
const stopLossResponse = await axios.post(`${baseUrl}/api/drift/place-order`, {
symbol: position.symbol,
side: isShort ? 'BUY' : 'SELL', // Opposite side to close position
orderType: 'STOP_MARKET',
triggerPrice: stopLossPrice,
amount: Math.abs(position.size),
reduceOnly: true
});
if (stopLossResponse.data.success) {
console.log('✅ EMERGENCY STOP LOSS PLACED SUCCESSFULLY!');
console.log(` Order ID: ${stopLossResponse.data.orderId || 'N/A'}`);
} else {
console.log('❌ Failed to place stop loss:', stopLossResponse.data.error);
}
} catch (slError) {
console.log('❌ Stop loss placement failed:', slError.message);
console.log('⚠️ MANUAL ACTION REQUIRED: Place stop loss immediately in Drift app');
}
// Also try to place a take profit (4% gain)
let takeProfitPrice;
if (isShort) {
// SHORT position - take profit BELOW entry (if price goes down)
takeProfitPrice = entryPrice * 0.96; // 4% below entry
} else {
// LONG position - take profit ABOVE entry (if price goes up)
takeProfitPrice = entryPrice * 1.04; // 4% above entry
}
console.log(`\n📈 PLACING TAKE PROFIT:`);
console.log(` Take Profit Price: $${takeProfitPrice.toFixed(3)}`);
console.log(` Target: 4% profit`);
try {
const tpResponse = await axios.post(`${baseUrl}/api/drift/place-order`, {
symbol: position.symbol,
side: isShort ? 'BUY' : 'SELL',
orderType: 'LIMIT',
price: takeProfitPrice,
amount: Math.abs(position.size),
reduceOnly: true
});
if (tpResponse.data.success) {
console.log('✅ TAKE PROFIT PLACED SUCCESSFULLY!');
} else {
console.log('⚠️ Take profit placement failed:', tpResponse.data.error);
}
} catch (tpError) {
console.log('⚠️ Take profit placement failed:', tpError.message);
}
} else {
console.log('✅ No positions found - account is safe');
}
} catch (error) {
console.log('❌ Emergency protection failed:', error.message);
console.log('\n🆘 MANUAL ACTION REQUIRED:');
console.log(' 1. Open Drift app immediately');
console.log(' 2. Place stop loss order manually');
console.log(' 3. Set stop loss 2% from entry price');
console.log(' 4. Consider closing position entirely');
}
console.log('\n🔍 INVESTIGATING BUG:');
console.log(' • Paper trading page should NOT place real trades');
console.log(' • This is a critical system bug');
console.log(' • Need to identify why paper trading used live API');
console.log(' • Must fix immediately before any more damage');
}
emergencyStopLoss().catch(console.error);