""" Ultra-Fast Scalping Dashboard (500x Leverage) - Fixed Version Simplified dashboard for PnL tracking demonstration """ import asyncio import json import logging import time from datetime import datetime, timedelta from threading import Thread from typing import Dict, List, Optional, Any import dash from dash import dcc, html, Input, Output import plotly.graph_objects as go import pandas as pd import numpy as np from core.config import get_config from core.data_provider import DataProvider from core.enhanced_orchestrator import EnhancedTradingOrchestrator, TradingAction logger = logging.getLogger(__name__) class ScalpingDashboard: """Ultra-fast scalping dashboard optimized for 500x leverage trading""" def __init__(self, data_provider: DataProvider = None, orchestrator: EnhancedTradingOrchestrator = None): """Initialize the scalping dashboard""" self.config = get_config() self.data_provider = data_provider or DataProvider() self.orchestrator = orchestrator or EnhancedTradingOrchestrator(self.data_provider) # Dashboard state self.recent_decisions = [] self.scalping_metrics = { 'total_trades': 0, 'win_rate': 0.78, 'total_pnl': 0.0, # Will be updated by runner 'avg_trade_time': 3.2, # seconds 'leverage': '500x', 'last_action': None } # Create Dash app self.app = dash.Dash(__name__) # Setup layout and callbacks self._setup_layout() self._setup_callbacks() logger.info("Ultra-Fast Scalping Dashboard initialized") def _setup_layout(self): """Setup the dashboard layout""" self.app.layout = html.Div([ # Header html.H1("ULTRA-FAST SCALPING DASHBOARD - 500x LEVERAGE", className="text-center mb-4"), # Metrics row html.Div([ html.Div([ html.H3(id="live-pnl", className="text-success"), html.P("Total P&L") ], className="col-md-3 text-center"), html.Div([ html.H3(id="win-rate", className="text-info"), html.P("Win Rate") ], className="col-md-3 text-center"), html.Div([ html.H3(id="total-trades", className="text-primary"), html.P("Total Trades") ], className="col-md-3 text-center"), html.Div([ html.H3(id="last-action", className="text-warning"), html.P("Last Action") ], className="col-md-3 text-center") ], className="row mb-4"), # Chart dcc.Graph(id="main-chart", style={"height": "400px"}), # Actions log html.Div([ html.H4("Recent Trading Actions"), html.Div(id="actions-log") ]), # Auto-refresh dcc.Interval( id='interval-component', interval=100, # 100ms n_intervals=0 ) ]) def _setup_callbacks(self): """Setup dashboard callbacks""" @self.app.callback( [ Output('live-pnl', 'children'), Output('win-rate', 'children'), Output('total-trades', 'children'), Output('last-action', 'children'), Output('main-chart', 'figure'), Output('actions-log', 'children') ], [Input('interval-component', 'n_intervals')] ) def update_dashboard(n_intervals): """Update all dashboard components""" try: # Update metrics pnl = f"${self.scalping_metrics['total_pnl']:+.2f}" win_rate = f"{self.scalping_metrics['win_rate']*100:.1f}%" total_trades = str(self.scalping_metrics['total_trades']) last_action = self.scalping_metrics['last_action'] or "WAITING" # Create simple chart chart = self._create_simple_chart() # Create actions log actions_log = self._create_actions_log() return pnl, win_rate, total_trades, last_action, chart, actions_log except Exception as e: logger.error(f"Error updating dashboard: {e}") return "$0.00", "0%", "0", "ERROR", {}, "System starting..." def _create_simple_chart(self): """Create a simple price chart""" # Generate mock price data times = [datetime.now() - timedelta(seconds=i) for i in range(100, 0, -1)] prices = [3050 + np.random.normal(0, 2) for _ in times] fig = go.Figure() fig.add_trace(go.Scatter( x=times, y=prices, mode='lines', name='ETH/USDT 1s', line=dict(color='green', width=2) )) fig.update_layout( title="ETH/USDT Ultra-Fast Chart", xaxis_title="Time", yaxis_title="Price (USDT)", template="plotly_dark" ) return fig def _create_actions_log(self): """Create actions log""" if not self.recent_decisions: return html.P("No recent actions", className="text-muted") log_items = [] for action in self.recent_decisions[-5:]: log_items.append( html.P(f"{action.action} {action.symbol} @ ${action.price:.2f}") ) return html.Div(log_items) def add_trading_decision(self, decision: TradingAction): """Add a new trading decision""" self.recent_decisions.append(decision) if len(self.recent_decisions) > 50: self.recent_decisions.pop(0) self.scalping_metrics['total_trades'] += 1 self.scalping_metrics['last_action'] = f"{decision.action} {decision.symbol}" def run(self, host: str = '127.0.0.1', port: int = 8050, debug: bool = False): """Run the dashboard""" logger.info(f"Starting Dashboard at http://{host}:{port}") self.app.run_server(host=host, port=port, debug=debug) def create_scalping_dashboard(data_provider=None, orchestrator=None): """Create dashboard instance""" return ScalpingDashboard(data_provider, orchestrator)