#!/usr/bin/env python3 """ Run Ultra-Fast Scalping Dashboard (500x Leverage) This script starts the custom scalping dashboard with: - Full-width 1s ETH/USDT candlestick chart - 3 small ETH charts: 1m, 1h, 1d - 1 small BTC 1s chart - Ultra-fast 100ms updates for scalping - Real-time PnL tracking and logging """ import logging import asyncio from threading import Thread import time import random from datetime import datetime, timedelta from dataclasses import dataclass from typing import Dict, List, Optional from core.config import get_config, setup_logging from core.data_provider import DataProvider from core.enhanced_orchestrator import EnhancedTradingOrchestrator, TradingAction, TimeframePrediction from web.scalping_dashboard_fixed import ScalpingDashboard # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @dataclass class Trade: """Individual trade tracking for PnL calculation""" trade_id: int symbol: str action: str # 'BUY', 'SELL' entry_price: float quantity: float entry_time: datetime confidence: float exit_price: Optional[float] = None exit_time: Optional[datetime] = None pnl: Optional[float] = None fees: Optional[float] = None leverage: int = 500 is_closed: bool = False class UltraFastScalpingRunner: """Ultra-fast scalping dashboard runner with 500x leverage simulation and PnL tracking""" def __init__(self): """Initialize the ultra-fast scalping system with PnL tracking""" self.config = get_config() self.data_provider = DataProvider(self.config) self.orchestrator = EnhancedTradingOrchestrator(self.data_provider) # Create the specialized scalping dashboard self.dashboard = ScalpingDashboard( data_provider=self.data_provider, orchestrator=self.orchestrator ) # Ultra-fast simulation state self.running = False self.simulation_thread = None self.exit_monitor_thread = None self.trade_count = 0 # PnL Tracking System self.open_positions: Dict[int, Trade] = {} # Track open positions by trade_id self.closed_trades: List[Trade] = [] # History of closed trades self.total_pnl = 0.0 self.total_fees = 0.0 self.win_count = 0 self.loss_count = 0 self.leverage = 500 # 500x leverage self.trading_fee = 0.0002 # 0.02% per trade self.balance = 10000.0 # Starting balance # Price tracking for PnL calculation self.current_prices = { 'ETH/USDT': 3050.0, 'BTC/USDT': 67000.0 } # Scalping parameters self.min_exit_time = 2 # Minimum 2 seconds before exit self.max_exit_time = 15 # Maximum 15 seconds before forced exit logger.info("🚀 Ultra-Fast Scalping Runner with PnL Tracking initialized") logger.info("⚡ 500x Leverage Mode Activated") logger.info(f"💰 Starting Balance: ${self.balance:.2f}") logger.info(f"📊 Leverage: {self.leverage}x") logger.info(f"💳 Trading Fee: {self.trading_fee*100:.3f}% per trade") logger.info(f"⏱️ Trade Duration: {self.min_exit_time}-{self.max_exit_time} seconds") logger.info("📊 Timeframes: 1s (primary), 1m, 1h, 1d") def start_ultra_fast_simulation(self): """Start ultra-fast trading simulation for 500x leverage scalping""" self.running = True self.simulation_thread = Thread(target=self._ultra_fast_loop, daemon=True) self.exit_monitor_thread = Thread(target=self._monitor_exits, daemon=True) self.simulation_thread.start() self.exit_monitor_thread.start() logger.info("🚀 Ultra-fast scalping simulation started") logger.info("⚡ Generating trades every 3-8 seconds") logger.info("📊 Monitoring trade exits for PnL calculation") def _ultra_fast_loop(self): """Ultra-fast scalping simulation loop with trade entry""" while self.running: try: # Update current prices with realistic movement self._update_prices() # Ultra-fast scalping - trades every 3-8 seconds for symbol in ['ETH/USDT', 'BTC/USDT']: # 40% chance of action (very active scalping) if random.random() > 0.6: self._execute_trade(symbol) # Ultra-fast interval (3-8 seconds between trades) sleep_time = random.uniform(3, 8) time.sleep(sleep_time) except Exception as e: logger.error(f"Error in ultra-fast scalping loop: {e}") time.sleep(2) def _execute_trade(self, symbol: str): """Execute a new scalping trade""" self.trade_count += 1 # Create ultra-fast timeframe predictions timeframe_predictions = [] # Focus on 1s predictions (primary for scalping) for tf, weight in [('1s', 0.6), ('1m', 0.2), ('1h', 0.15), ('1d', 0.05)]: # More aggressive probabilities for scalping if tf == '1s': # Primary scalping signal action_probs = [ random.uniform(0.05, 0.25), # SELL random.uniform(0.20, 0.40), # HOLD random.uniform(0.35, 0.75) # BUY (bias for bull market) ] else: action_probs = [ random.uniform(0.1, 0.4), # SELL random.uniform(0.3, 0.6), # HOLD random.uniform(0.1, 0.4) # BUY ] # Normalize probabilities total = sum(action_probs) action_probs = [p/total for p in action_probs] best_action_idx = action_probs.index(max(action_probs)) actions = ['SELL', 'HOLD', 'BUY'] best_action = actions[best_action_idx] tf_pred = TimeframePrediction( timeframe=tf, action=best_action, confidence=random.uniform(0.65, 0.95), # High confidence for scalping probabilities={ 'SELL': action_probs[0], 'HOLD': action_probs[1], 'BUY': action_probs[2] }, timestamp=datetime.now(), market_features={ 'volatility': random.uniform(0.005, 0.02), # Higher volatility for 1s 'volume': random.uniform(2000, 15000), # High volume for scalping 'trend_strength': random.uniform(0.4, 0.9), 'leverage': '500x', 'scalping_signal': tf == '1s' } ) timeframe_predictions.append(tf_pred) # Create scalping action (focus on non-HOLD actions) primary_action = timeframe_predictions[0].action # Use 1s timeframe if primary_action == 'HOLD': primary_action = random.choice(['BUY', 'SELL']) # Force action for demo # Get current price and calculate trade details entry_price = self.current_prices[symbol] quantity = random.uniform(0.01, 0.05) # Small quantities for scalping confidence = random.uniform(0.70, 0.95) # Create trade record trade = Trade( trade_id=self.trade_count, symbol=symbol, action=primary_action, entry_price=entry_price, quantity=quantity, entry_time=datetime.now(), confidence=confidence, leverage=self.leverage ) # Store open position self.open_positions[self.trade_count] = trade # Calculate position value and fees position_value = quantity * entry_price leveraged_value = position_value * self.leverage entry_fee = position_value * self.trading_fee # Create ultra-fast trading action for dashboard scalping_action = TradingAction( symbol=symbol, action=primary_action, quantity=quantity, confidence=confidence, price=entry_price, timestamp=datetime.now(), reasoning={ 'model': 'Ultra-Fast Scalping AI', 'leverage': f'{self.leverage}x', 'timeframe_primary': '1s', 'scalping_mode': True, 'trade_id': self.trade_count, 'expected_duration': f"{random.uniform(2, 8):.1f}s", 'market_regime': random.choice(['trending_up', 'momentum', 'breakout']), 'position_value': f"${leveraged_value:.2f}", 'entry_fee': f"${entry_fee:.2f}" }, timeframe_analysis=timeframe_predictions ) # Add to dashboard self.dashboard.add_trading_decision(scalping_action) # Log trade entry with detailed information logger.info(f"🔥 TRADE #{self.trade_count} OPENED:") logger.info(f" 📊 {primary_action} {symbol} @ ${entry_price:.2f}") logger.info(f" 📈 Quantity: {quantity:.4f} | Confidence: {confidence:.1%}") logger.info(f" 💰 Position Value: ${leveraged_value:.2f} ({self.leverage}x leverage)") logger.info(f" 💳 Entry Fee: ${entry_fee:.4f}") logger.info(f" ⏱️ Expected Exit: {self.min_exit_time}-{self.max_exit_time}s") def _monitor_exits(self): """Monitor open positions and execute exits for PnL calculation""" while self.running: try: current_time = datetime.now() positions_to_close = [] for trade_id, trade in self.open_positions.items(): time_elapsed = (current_time - trade.entry_time).total_seconds() # Check if trade should be closed should_close = False # Force close after max time if time_elapsed >= self.max_exit_time: should_close = True # Probabilistic close after min time (scalping style) elif time_elapsed >= self.min_exit_time: close_probability = (time_elapsed - self.min_exit_time) / (self.max_exit_time - self.min_exit_time) if random.random() < close_probability * 0.3: # 30% max probability per check should_close = True if should_close: positions_to_close.append(trade_id) # Close positions and calculate PnL for trade_id in positions_to_close: self._close_position(trade_id) time.sleep(0.5) # Check every 500ms for ultra-fast scalping except Exception as e: logger.error(f"Error in exit monitoring: {e}") time.sleep(1) def _close_position(self, trade_id: int): """Close a position and calculate PnL""" if trade_id not in self.open_positions: return trade = self.open_positions[trade_id] # Get current exit price exit_price = self.current_prices[trade.symbol] trade.exit_price = exit_price trade.exit_time = datetime.now() # Calculate PnL based on trade direction if trade.action == 'BUY': # Long position: profit when price goes up price_change = (exit_price - trade.entry_price) / trade.entry_price else: # SELL # Short position: profit when price goes down price_change = (trade.entry_price - exit_price) / trade.entry_price # Calculate leveraged PnL position_value = trade.quantity * trade.entry_price raw_pnl = position_value * price_change * self.leverage # Calculate fees (entry + exit) entry_fee = position_value * self.trading_fee exit_fee = trade.quantity * exit_price * self.trading_fee total_fees = entry_fee + exit_fee # Net PnL after fees net_pnl = raw_pnl - total_fees # Update trade record trade.pnl = net_pnl trade.fees = total_fees trade.is_closed = True # Update totals self.total_pnl += net_pnl self.total_fees += total_fees if net_pnl > 0: self.win_count += 1 else: self.loss_count += 1 # Update dashboard metrics self.dashboard.scalping_metrics['total_pnl'] = self.total_pnl self.dashboard.scalping_metrics['win_rate'] = self.win_count / (self.win_count + self.loss_count) if (self.win_count + self.loss_count) > 0 else 0 # Move to closed trades self.closed_trades.append(trade) del self.open_positions[trade_id] # Calculate trade duration duration = (trade.exit_time - trade.entry_time).total_seconds() # Log detailed PnL information pnl_color = "🟢" if net_pnl > 0 else "🔴" logger.info(f"{pnl_color} TRADE #{trade_id} CLOSED:") logger.info(f" 📊 {trade.action} {trade.symbol}: ${trade.entry_price:.2f} → ${exit_price:.2f}") logger.info(f" 📈 Price Change: {price_change*100:+.3f}%") logger.info(f" ⏱️ Duration: {duration:.1f}s") logger.info(f" 💰 Raw PnL: ${raw_pnl:+.2f} ({self.leverage}x leverage)") logger.info(f" 💳 Total Fees: ${total_fees:.4f}") logger.info(f" 🎯 Net PnL: ${net_pnl:+.2f}") logger.info(f" 📊 Total PnL: ${self.total_pnl:+.2f} | Win Rate: {self.dashboard.scalping_metrics['win_rate']*100:.1f}%") logger.info(" " + "="*50) def _update_prices(self): """Update current prices with realistic movement""" for symbol in self.current_prices: # Small random price movement (typical for 1s intervals) current_price = self.current_prices[symbol] # More volatile movement for realistic scalping if symbol == 'ETH/USDT': change_percent = random.normalvariate(0, 0.0008) # ~0.08% standard deviation else: # BTC/USDT change_percent = random.normalvariate(0, 0.0006) # ~0.06% standard deviation new_price = current_price * (1 + change_percent) # Keep prices within reasonable bounds if symbol == 'ETH/USDT': new_price = max(3000, min(3100, new_price)) else: # BTC/USDT new_price = max(66000, min(68000, new_price)) self.current_prices[symbol] = new_price def _get_realistic_price(self, symbol: str) -> float: """Get realistic price for symbol""" return self.current_prices[symbol] def run_scalping_dashboard(self, host='127.0.0.1', port=8051): """Run the ultra-fast scalping dashboard""" logger.info("🔥 ULTRA-FAST SCALPING DASHBOARD WITH PnL TRACKING 🔥") logger.info(f"🌐 Starting at http://{host}:{port}") logger.info("📊 Dashboard Features:") logger.info(" • Full-width 1s ETH/USDT candlestick chart") logger.info(" • 3 small ETH charts: 1m, 1h, 1d") logger.info(" • 1 small BTC 1s chart") logger.info(" • 100ms ultra-fast updates") logger.info(" • 500x leverage simulation") logger.info(" • Real-time PnL tracking and logging") logger.info("") logger.info("🎯 Optimized for ultra-fast scalping trades") logger.info("⚡ Generating trading signals every 3-8 seconds") logger.info("💰 Real-time PnL calculation with fees and leverage") # Start ultra-fast simulation self.start_ultra_fast_simulation() # Run dashboard try: self.dashboard.run(host=host, port=port, debug=False) except KeyboardInterrupt: logger.info("🛑 Scalping dashboard stopped by user") finally: self.running = False if self.simulation_thread: self.simulation_thread.join(timeout=2) if self.exit_monitor_thread: self.exit_monitor_thread.join(timeout=2) # Final session summary total_trades = len(self.closed_trades) logger.info("💼 FINAL SCALPING SESSION SUMMARY:") logger.info("="*60) logger.info(f" 📊 Total Trades: {total_trades}") logger.info(f" 🎯 Total PnL: ${self.total_pnl:+.2f}") logger.info(f" 💳 Total Fees: ${self.total_fees:.2f}") logger.info(f" 🟢 Wins: {self.win_count} | 🔴 Losses: {self.loss_count}") logger.info(f" 📈 Win Rate: {self.dashboard.scalping_metrics['win_rate']*100:.1f}%") logger.info(f" 💰 Starting Balance: ${self.balance:.2f}") logger.info(f" 💰 Final Balance: ${self.balance + self.total_pnl:.2f}") logger.info(f" 📊 Return: {((self.balance + self.total_pnl) / self.balance - 1) * 100:+.2f}%") logger.info("="*60) def main(): """Main function""" try: logger.info("=== ULTRA-FAST SCALPING SYSTEM WITH PnL TRACKING ===") logger.info("💰 500x Leverage Mode") logger.info("⚡ Optimized for 1s-8s trades") logger.info("📊 Real-time PnL calculation and logging") # Create and run scalping dashboard runner = UltraFastScalpingRunner() runner.run_scalping_dashboard() except Exception as e: logger.error(f"Fatal error: {e}") import traceback traceback.print_exc() if __name__ == "__main__": main()