async def _update_displays(self):
    """Update all GUI displays asynchronously"""
    try:
        # Update charts
        self._update_price_chart()
        self._update_indicators_chart()
        
        # Update tables if data available
        if hasattr(self, 'trades'):
            self.update_trades_display(self.trades)
            
        # Update signals
        await self._update_signals({
            "direction": "NEUTRAL",
            "strength": 50,
            "confidence": 50
        })
        
        # Small delay to prevent GUI freezing
        await asyncio.sleep(0.1)
        
    except Exception as e:
        logging.error(f"Display update error: {e}")
  from PyQt6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QPushButton, QLineEdit, QTabWidget, QGridLayout, QFrame,
    QTableWidget, QTableWidgetItem, QProgressBar, QStatusBar,
    QHeaderView, QSplitter
)
from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QObject, QSize
from PyQt6.QtGui import QPalette, QColor, QFont, QPainter, QBrush
import pyqtgraph as pg
import numpy as np
from datetime import datetime
from typing import Dict, Optional, List, Any
import logging
from queue import Queue
import threading

class DarkTheme:
    """Professional dark theme color scheme"""
    BACKGROUND = "#1C1C1C"
    DARKER_BACKGROUND = "#141414"
    LIGHTER_BACKGROUND = "#2A2A2A"
    TEXT_PRIMARY = "#E0E0E0"
    TEXT_SECONDARY = "#A0A0A0"
    ACCENT_BLUE = "#2196F3"
    ACCENT_GREEN = "#4CAF50"
    ACCENT_RED = "#F44336"
    ACCENT_YELLOW = "#FFD700"
    CHART_BACKGROUND = "#1C1C1C"
    GRID_COLOR = "#323232"
    PRICE_LINE = "#00BCD4"
    VOLUME_BAR = "#2196F3"
    SUCCESS = "#43A047"
    WARNING = "#FFA000"
    ERROR = "#D32F2F"
    TABLE_HEADER = "#252525"
    TABLE_ALTERNATE = "#202020"
    
    @staticmethod
    def get_stylesheet():
        return f"""
            QMainWindow {{
                background-color: {DarkTheme.BACKGROUND};
                color: {DarkTheme.TEXT_PRIMARY};
            }}
            QLabel {{
                color: {DarkTheme.TEXT_PRIMARY};
                font-size: 12px;
            }}
            QLineEdit {{
                background-color: {DarkTheme.DARKER_BACKGROUND};
                border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
                border-radius: 3px;
                padding: 5px;
                color: {DarkTheme.TEXT_PRIMARY};
                font-size: 12px;
            }}
            QPushButton {{
                background-color: {DarkTheme.ACCENT_BLUE};
                color: {DarkTheme.TEXT_PRIMARY};
                border: none;
                border-radius: 3px;
                padding: 8px;
                font-size: 12px;
                font-weight: bold;
            }}
            QPushButton:hover {{
                background-color: #1E88E5;
            }}
            QPushButton:pressed {{
                background-color: #1976D2;
            }}
            QTableWidget {{
                background-color: {DarkTheme.BACKGROUND};
                alternate-background-color: {DarkTheme.TABLE_ALTERNATE};
                color: {DarkTheme.TEXT_PRIMARY};
                gridline-color: {DarkTheme.GRID_COLOR};
                font-size: 12px;
            }}
            QHeaderView::section {{
                background-color: {DarkTheme.TABLE_HEADER};
                color: {DarkTheme.TEXT_PRIMARY};
                padding: 5px;
                border: none;
                font-weight: bold;
            }}
            QTabWidget::pane {{
                border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
                background: {DarkTheme.BACKGROUND};
            }}
            QTabBar::tab {{
                background: {DarkTheme.DARKER_BACKGROUND};
                color: {DarkTheme.TEXT_PRIMARY};
                padding: 8px 12px;
                margin-right: 2px;
            }}
            QTabBar::tab:selected {{
                background: {DarkTheme.ACCENT_BLUE};
            }}
            QProgressBar {{
                border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
                border-radius: 2px;
                text-align: center;
                background-color: {DarkTheme.DARKER_BACKGROUND};
            }}
            QProgressBar::chunk {{
                background-color: {DarkTheme.ACCENT_BLUE};
            }}
            QStatusBar {{
                background-color: {DarkTheme.DARKER_BACKGROUND};
                color: {DarkTheme.TEXT_PRIMARY};
            }}
            QFrame {{
                background-color: {DarkTheme.BACKGROUND};
                border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
                border-radius: 3px;
            }}
        """

class GuiUpdateHandler(QObject):
    """Handles asynchronous GUI updates"""
    update_signal = pyqtSignal(dict)
    
    def __init__(self, gui: 'QuantumGUI'):
        super().__init__()
        self.gui = gui
        self.update_queue = Queue()
        self.update_signal.connect(self._process_update)
        self._setup_update_timer()
        
    def _setup_update_timer(self):
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self._check_queue)
        self.update_timer.start(50)  # 20 Hz update rate
        
    def _check_queue(self):
        """Process updates from queue"""
        try:
            while not self.update_queue.empty():
                update_data = self.update_queue.get_nowait()
                self._process_update(update_data)
                self.update_queue.task_done()
        except Exception as e:
            logging.error(f"Queue processing error: {e}")
            
    def _process_update(self, data: Dict[str, Any]):
        """Process updates synchronously"""
        try:
            if "market_data" in data:
                self.gui._update_market_data(data["market_data"])
            if "signals" in data:
                self.gui._update_signals(data["signals"])
            if "metrics" in data:
                self.gui._update_metrics(data["metrics"])
            if "wallet" in data:
                self.gui._update_wallet(data["wallet"])
            if "trades" in data:
                self.gui._update_trades(data["trades"])
            if "pools" in data:
                self.gui._handle_pool_update(data["pools"])
                
        except Exception as e:
            logging.error(f"Update processing error: {e}")
            self.gui.error_occurred.emit(str(e))

    def queue_update(self, data: Dict[str, Any]):
        """Queue an update to be processed"""
        try:
            # Deep copy the data to prevent any reference issues
            data_copy = {k: v.copy() if isinstance(v, dict) else v for k, v in data.items()}
            self.update_queue.put(data_copy)
            logging.info(f"Queued update: {data_copy}")
        except Exception as e:
            logging.error(f"Update queueing error: {e}")

class QuantumGUI(QMainWindow):
    """Professional Quantum Trading Interface"""
    # Signals
    balance_updated = pyqtSignal(float)
    price_updated = pyqtSignal(float)
    volume_updated = pyqtSignal(float)
    trade_executed = pyqtSignal(str)
    error_occurred = pyqtSignal(str)

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Quantum Trading Engine")
        self.setGeometry(100, 100, 1920, 1080)
        
        # Initialize state
        self.price_history = []
        self.volume_history = []
        self.signal_history = []
        self.trades = []
        
        # Setup UI
        self._init_ui()
        self._setup_update_handler()
        self._setup_timers()
        self._connect_signals()
        
        # Apply theme
        self.setStyleSheet(DarkTheme.get_stylesheet())
        
        self.statusBar().showMessage("System Ready")
        logging.info("Quantum GUI initialized")

    def _init_ui(self):
        """Initialize the main UI layout"""
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        
        # Create main layout
        main_layout = QHBoxLayout(self.central_widget)
        
        # Create splitters for resizable sections
        h_splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # Add panels to splitter
        h_splitter.addWidget(self._create_left_panel())
        h_splitter.addWidget(self._create_center_panel())
        h_splitter.addWidget(self._create_right_panel())
        
        # Set initial sizes (adjust as needed)
        h_splitter.setSizes([300, 1000, 300])
        
        main_layout.addWidget(h_splitter)
    
    def _setup_update_handler(self):
        """Initialize the update handler"""
        self.update_handler = GuiUpdateHandler(self)

    def _setup_timers(self):
        """Initialize update timers"""
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self._update_displays)
        self.update_timer.start(1000)  # 1 second updates

    def _create_section(self, title: str) -> tuple[QFrame, QVBoxLayout]:
        """Create a styled section with title"""
        section = QFrame()
        section.setFrameStyle(QFrame.Shape.StyledPanel)
        section.setStyleSheet(f"""
            QFrame {{
                background-color: {DarkTheme.DARKER_BACKGROUND};
                border: 1px solid {DarkTheme.LIGHTER_BACKGROUND};
                border-radius: 5px;
                margin: 5px;
            }}
        """)

        layout = QVBoxLayout()
        if title:
            header = QLabel(title)
            header.setStyleSheet(f"""
                font-weight: bold;
                color: {DarkTheme.TEXT_PRIMARY};
                font-size: 13px;
            """)
            layout.addWidget(header)

        section.setLayout(layout)
        return section, layout

    def _create_center_panel(self):
        """Create the center panel with charts"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.Shape.StyledPanel)
        layout = QVBoxLayout()
        panel.setLayout(layout)

        # Charts container
        charts_tabs = QTabWidget()
        
        # Price Chart
        self.price_chart = self._create_chart("Price")
        self.price_line = self.price_chart.plot(pen=pg.mkPen(DarkTheme.PRICE_LINE, width=2))
        charts_tabs.addTab(self.price_chart, "Price")

        # Volume Chart
        self.volume_chart = self._create_chart("Volume")
        self.volume_bar = pg.BarGraphItem(x=[], height=[], width=0.8, brush=DarkTheme.VOLUME_BAR)
        self.volume_chart.addItem(self.volume_bar)
        charts_tabs.addTab(self.volume_chart, "Volume")

        # Indicators Chart
        self.indicators_chart = self._create_chart("Technical Indicators")
        self.rsi_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_YELLOW, width=2))
        self.macd_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_BLUE, width=2))
        self.signal_line = self.indicators_chart.plot(pen=pg.mkPen(DarkTheme.ACCENT_RED, width=2))
        charts_tabs.addTab(self.indicators_chart, "Indicators")

        layout.addWidget(charts_tabs)

        # Trading Signals Panel
        signals_frame, signals_layout = self._create_section("Trading Signals")
        grid_layout = QGridLayout()
        
        self.signal_indicators = {
            "strength": self._create_progress_bar(),
            "direction": self._create_direction_label(),
            "confidence": self._create_progress_bar(),
        }
        
        grid_layout.addWidget(QLabel("Signal Strength:"), 0, 0)
        grid_layout.addWidget(self.signal_indicators["strength"], 0, 1)
        grid_layout.addWidget(QLabel("Direction:"), 1, 0)
        grid_layout.addWidget(self.signal_indicators["direction"], 1, 1)
        grid_layout.addWidget(QLabel("AI Confidence:"), 2, 0)
        grid_layout.addWidget(self.signal_indicators["confidence"], 2, 1)

        signals_layout.addLayout(grid_layout)
        layout.addWidget(signals_frame)
        
        return panel

    def _create_right_panel(self):
        """Create the right panel with positions and trades"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.Shape.StyledPanel)
        layout = QVBoxLayout()
        panel.setLayout(layout)

        # Active Positions
        positions_frame, positions_layout = self._create_section("Active Positions")
        
        self.positions_table = self._create_table(
            headers=["Token", "Size", "Entry", "PnL"],
            column_widths=[150, 100, 100, 100]
        )
        positions_layout.addWidget(self.positions_table)
        layout.addWidget(positions_frame)

        # Trade History
        trades_frame, trades_layout = self._create_section("Trade History")
        
        self.trades_table = self._create_table(
            headers=["Time", "Token", "Side", "Size", "PnL"],
            column_widths=[150, 150, 80, 100, 100]
        )
        trades_layout.addWidget(self.trades_table)
        layout.addWidget(trades_frame)

        return panel

    def _create_left_panel(self):
        """Create the left control panel"""
        panel = QFrame()
        panel.setFrameStyle(QFrame.Shape.StyledPanel)
        main_layout = QVBoxLayout()
        panel.setLayout(main_layout)
        main_layout.setSpacing(10)

        # Wallet Section
        wallet_frame, wallet_layout = self._create_section("Wallet Information")
        grid_layout = QGridLayout()
        self.wallet_address = QLineEdit()
        self.wallet_address.setReadOnly(True)
        self.balance_label = QLabel("Balance: 0.00 SOL")
        grid_layout.addWidget(QLabel("Address:"), 0, 0)
        grid_layout.addWidget(self.wallet_address, 0, 1)
        grid_layout.addWidget(self.balance_label, 1, 0, 1, 2)
        wallet_layout.addLayout(grid_layout)  # Add grid to the wallet layout
        main_layout.addWidget(wallet_frame)   # Add frame to main layout

        # Trading Controls
        controls_frame, controls_layout = self._create_section("Trading Controls")
        grid_layout = QGridLayout()

        self.token_input = QLineEdit()
        self.token_input.setPlaceholderText("Token Address")
        self.amount_input = QLineEdit()
        self.amount_input.setPlaceholderText("Amount (SOL)")

        self.buy_button = QPushButton("BUY")
        self.sell_button = QPushButton("SELL")
        
        self.status_labels = {
            "price": QLabel("Price: $0.00"),
            "volume": QLabel("Volume: $0"),
            "trades": QLabel("Trades: 0"),
            "win_rate": QLabel("Win Rate: 0%"),
            "pnl": QLabel("PnL: $0.00"),
            "liquidity": QLabel("Liquidity: $0"),
            "buyer_ratio": QLabel("Buy Ratio: 50%"),
            "lp_locked": QLabel("LP Locked: 0%"),
        }

        self.buy_button.setStyleSheet(f"""
            QPushButton {{
                background-color: {DarkTheme.ACCENT_GREEN};
                min-height: 30px;
            }}
            QPushButton:hover {{
                background-color: {DarkTheme.SUCCESS};
            }}
        """)
        self.sell_button.setStyleSheet(f"""
            QPushButton {{
                background-color: {DarkTheme.ACCENT_RED};
                min-height: 30px;
            }}
            QPushButton:hover {{
                background-color: {DarkTheme.ERROR};
            }}
        """)

        grid_layout.addWidget(QLabel("Token:"), 0, 0)
        grid_layout.addWidget(self.token_input, 0, 1)
        grid_layout.addWidget(QLabel("Amount:"), 1, 0)
        grid_layout.addWidget(self.amount_input, 1, 1)
        grid_layout.addWidget(self.buy_button, 2, 0)
        grid_layout.addWidget(self.sell_button, 2, 1)
        controls_layout.addLayout(grid_layout)
        main_layout.addWidget(controls_frame)

        # Status Indicators
        status_frame, status_layout = self._create_section("Market Status")
        grid_layout = QGridLayout()

        for i, (key, label) in enumerate(self.status_labels.items()):
            label.setStyleSheet(f"color: {DarkTheme.TEXT_PRIMARY}; font-size: 12px;")
            grid_layout.addWidget(label, i, 0)
        status_layout.addLayout(grid_layout)
        main_layout.addWidget(status_frame)

        # Auto-Trading Controls
        auto_frame, auto_layout = self._create_section("Automated Trading")

        self.auto_trade_button = QPushButton("Start Auto-Trading")
        self.auto_trade_button.setCheckable(True)
        self.stop_button = QPushButton("Emergency Stop")

        self.auto_trade_button.setStyleSheet(f"""
            QPushButton {{
                background-color: {DarkTheme.ACCENT_BLUE};
                min-height: 35px;
            }}
            QPushButton:checked {{
                background-color: {DarkTheme.SUCCESS};
            }}
        """)

        self.stop_button.setStyleSheet(f"""
            QPushButton {{
                background-color: {DarkTheme.ERROR};
                min-height: 35px;
            }}
            QPushButton:hover {{
                background-color: {DarkTheme.ACCENT_RED};
            }}
        """)

        auto_layout.addWidget(self.auto_trade_button)
        auto_layout.addWidget(self.stop_button)
        main_layout.addWidget(auto_frame)

        main_layout.addStretch()
        return panel

    def _create_chart(self, title: str) -> pg.PlotWidget:
        """Create a styled pyqtgraph plot widget"""
        logging.info(f"Creating chart: {title}")
        chart = pg.PlotWidget(title=title)
        chart.setBackground(DarkTheme.CHART_BACKGROUND)
        chart.showGrid(x=True, y=True, alpha=0.2)
        chart.getAxis('bottom').setPen(pg.mkPen(DarkTheme.TEXT_SECONDARY))
        chart.getAxis('left').setPen(pg.mkPen(DarkTheme.TEXT_SECONDARY))
        return chart

    def _create_table(self, headers: List[str], column_widths: List[int]) -> QTableWidget:
        """Create a styled table widget"""
        table = QTableWidget(0, len(headers))
        table.setHorizontalHeaderLabels(headers)
        
        # Set column widths
        for i, width in enumerate(column_widths):
            table.setColumnWidth(i, width)
            
        # Style header
        header = table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Fixed)
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignLeft)
        
        logging.info("Table created with headers: {}".format(headers))
        return table

    def _create_progress_bar(self) -> QProgressBar:
        """Create a styled progress bar"""
        bar = QProgressBar()
        bar.setMinimum(0)
        bar.setMaximum(100)
        bar.setTextVisible(True)
        bar.setFormat("%v%")
        logging.info("Progress bar created.")
        return bar

    def _create_direction_label(self) -> QLabel:
        """Create a styled direction label"""
        label = QLabel("NEUTRAL")
        label.setStyleSheet(f"""
            font-weight: bold;
            font-size: 13px;
            padding: 5px;
            color: {DarkTheme.TEXT_SECONDARY};
        """)
        return label

    def update_status_message(self, message: str, color: str = DarkTheme.TEXT_PRIMARY):
        """Update status bar message with color"""
        self.statusBar().setStyleSheet(f"color: {color};")
        self.statusBar().showMessage(message)

    def get_trade_params(self) -> Dict:
        """Get current trading parameters from inputs"""
        return {
            "token": self.token_input.text().strip(),
            "amount": float(self.amount_input.text() or 0),
        }

    def _update_market_data(self, data: Dict):
        """Update market data displays"""
        try:
            if "price" in data:
                self.update_price(data["price"], data.get("volume", 0))
                self._update_price_chart()
            if "indicators" in data:
                self._update_indicators(data["indicators"])
        except Exception as e:
            logging.error(f"Market data update error: {e}")

    def _connect_signals(self):
        """Connect internal GUI signals"""
        self.balance_updated.connect(lambda val: self.update_balance(val))
        self.price_updated.connect(lambda val: self.update_price(val))
        self.volume_updated.connect(lambda val: self.update_price(0, val))
        self.trade_executed.connect(self._handle_trade)
        self.error_occurred.connect(self._handle_error)

    def update_price(self, price: float, volume: float = 0):
        """Update price and volume displays with type safety"""
        try:
            # Convert and store current price
            current_price = float(price)
            self.price_history.append(current_price)
            
            # Initialize last_price if needed
            if not hasattr(self, 'last_price'):
                self.last_price = current_price
            
            # Update price color based on movement
            if current_price > self.last_price:
                self.status_labels["price"].setStyleSheet(f"color: {DarkTheme.ACCENT_GREEN};")
            else:
                self.status_labels["price"].setStyleSheet(f"color: {DarkTheme.ACCENT_RED};")
            
            # Store for next comparison
            self.last_price = current_price

            # Handle volume updates
            if volume > 0:
                self.volume_history.append(float(volume))
            
            # Maintain history length
            if len(self.price_history) > 1000:
                self.price_history = self.price_history[-1000:]
                self.volume_history = self.volume_history[-1000:]

            # Update display labels
            self.status_labels["price"].setText(f"Price: ${self._format_number(current_price, 4)}")
            if volume > 0:
                self.status_labels["volume"].setText(f"Volume: ${self._format_number(volume)}")

        except Exception as e:
            logging.error(f"Price update error: {e}")
            
    def get_token_address(self):
        return self.token_input.text()

    def update_wallet(self, address: str):
        """Update wallet address display"""
        logging.info(f"Updating wallet address to: {address}")
        self.wallet_address.setText(address)

    def update_balance(self, balance: float):
        """Update wallet balance display"""
        logging.info(f"Updating balance to: {balance} SOL")
        self.balance_label.setText(f"Balance: {self._format_number(balance, 4)} SOL")

    def _update_trades(self, trades: List[Dict]):
        """Process and display trade updates"""
        try:
            logging.info(f"Updating trades: {len(trades)} trades")
            self.trades = trades
            self.update_trades_display(trades)
        except Exception as e:
            logging.error(f"Trade update error: {e}")

    def _update_metrics(self, metrics: Dict):
        """Update trading metrics display"""
        try:
            if "pnl" in metrics:
                pnl = metrics["pnl"]
                self.status_labels["pnl"].setText(f"PnL: ${self._format_number(pnl, 2)}")
                # Color code PnL
                self.status_labels["pnl"].setStyleSheet(
                    f"color: {DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED};"
                )
            
            if "total_trades" in metrics:
                self.status_labels["trades"].setText(f"Trades: {metrics['total_trades']}")
            
            if "win_rate" in metrics:
                self.status_labels["win_rate"].setText(f"Win Rate: {self._format_number(metrics['win_rate'], 1)}%")
                
        except Exception as e:
            logging.error(f"Metrics update error: {e}")

    def update_price_display(self, stats: Dict):
        """Update price-related displays with current stats"""
        try:
            logging.debug("Updating price display with current stats.")
            # Update price label
            if "price" in stats:
                price = stats["price"]
                self.status_labels["price"].setText(f"Price: ${self._format_number(price, 4)}")

            # Update volume label
            if "volume" in stats:
                volume = stats["volume"]
                self.status_labels["volume"].setText(f"Volume: ${self._format_number(volume)}")

            # Update trades count
            if "trades" in stats:
                trades = stats["trades"]
                self.status_labels["trades"].setText(f"Trades: {trades}")

            # Update win rate
            if "win_rate" in stats:
                win_rate = stats["win_rate"]
                self.status_labels["win_rate"].setText(f"Win Rate: {self._format_number(win_rate, 1)}%")

            # Update PnL
            if "pnl" in stats:
                pnl = stats["pnl"]
                self.status_labels["pnl"].setText(f"PnL: ${self._format_number(pnl, 2)}")
                # Color code PnL
                self.status_labels["pnl"].setStyleSheet(
                    f"color: {DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED};"
                )

            # Queue chart update if price data available
            if "price" in stats:
                self.queue_update({
                    "market_data": {
                        "price": stats["price"],
                        "volume": stats.get("volume", 0)
                    }
                })

        except Exception as e:
            logging.error(f"Price display update error: {e}")
            self.error_occurred.emit(str(e))

    def _update_indicators_chart(self):
        """Update technical indicators chart"""
        try:
            if len(self.price_history) > 14:
                price_array = np.array(self.price_history)
                self._calculate_and_update_indicators(price_array)
        except Exception as e:
            logging.error(f"Indicators chart update error: {e}")

    def _calculate_and_update_indicators(self, price_array: np.ndarray):
        """Calculate and update technical indicators"""
        try:
            logging.debug("Calculating and updating indicators.")
            # Calculate RSI
            changes = np.diff(price_array)
            gains = np.where(changes > 0, changes, 0)
            losses = np.where(changes < 0, -changes, 0)
            avg_gain = np.mean(gains[-14:])
            avg_loss = np.mean(losses[-14:])
            rsi = 100 - (100 / (1 + (avg_gain / avg_loss if avg_loss else 1)))
            
            # Calculate MACD
            ema12 = self._calculate_ema(price_array, 12)
            ema26 = self._calculate_ema(price_array, 26)
            macd = ema12 - ema26
            signal = self._calculate_ema(macd, 9)
            
            # Update indicator lines
            timestamps = np.arange(len(price_array))
            self.rsi_line.setData(x=timestamps, y=np.array([rsi] * len(price_array)))
            self.macd_line.setData(x=timestamps, y=macd)
            self.signal_line.setData(x=timestamps, y=signal)
            
            logging.info("Indicators updated successfully.")
        except Exception as e:
            logging.error(f"Indicator calculation error: {e}")

    def update_trades_display(self, trades: List[Dict]):
        """Update trade history display"""
        try:
            logging.debug(f"Updating trades display with {len(trades)} trades.")
            self.trades_table.setRowCount(len(trades))
            for i, trade in enumerate(trades):
                # Time
                time_str = datetime.fromtimestamp(trade.get("timestamp", 0)).strftime("%Y-%m-%d %H:%M:%S")
                self.trades_table.setItem(i, 0, self._create_table_item(time_str))
                
                # Token
                self.trades_table.setItem(i, 1, self._create_table_item(trade.get("token", "")))
                
                # Side
                side = trade.get("side", "")
                side_color = DarkTheme.ACCENT_GREEN if side == "BUY" else DarkTheme.ACCENT_RED
                self.trades_table.setItem(i, 2, self._create_table_item(side, side_color))
                
                # Size
                self.trades_table.setItem(i, 3, self._create_table_item(
                    self._format_number(trade.get("size", 0), 4)
                ))
                
                # PnL
                pnl = trade.get("pnl", 0)
                pnl_color = DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED
                self.trades_table.setItem(i, 4, self._create_table_item(
                    f"${self._format_number(pnl, 2)}", pnl_color
                ))
                
            logging.info("Trades display updated successfully.")
        except Exception as e:
            logging.error(f"Trades display update error: {e}")

    def update_positions_display(self, positions: List[Dict]):
        """Update active positions display"""
        try:
            logging.debug(f"Updating positions display with {len(positions)} positions.")
            self.positions_table.setRowCount(len(positions))
            for i, position in enumerate(positions):
                # Token
                self.positions_table.setItem(i, 0, self._create_table_item(position.get("token", "")))
                
                # Size
                self.positions_table.setItem(i, 1, self._create_table_item(
                    self._format_number(position.get("size", 0), 4)
                ))
                
                # Entry
                self.positions_table.setItem(i, 2, self._create_table_item(
                    f"${self._format_number(position.get('entry', 0), 4)}"
                ))
                
                # PnL
                pnl = position.get("pnl", 0)
                pnl_color = DarkTheme.ACCENT_GREEN if pnl >= 0 else DarkTheme.ACCENT_RED
                self.positions_table.setItem(i, 3, self._create_table_item(
                    f"${self._format_number(pnl, 2)}", pnl_color
                ))
                
            logging.info("Positions display updated successfully.")
        except Exception as e:
            logging.error(f"Positions display update error: {e}")

    def _update_signals(self, signals: Dict):
        """Update trading signals display"""
        try:
            logging.debug("Updating trading signals display.")
            direction = signals.get("direction", "NEUTRAL")
            strength = int(signals.get("strength", 0))
            confidence = int(signals.get("confidence", 0))
            
            # Update direction indicator
            direction_color = {
                "LONG": DarkTheme.ACCENT_GREEN,
                "SHORT": DarkTheme.ACCENT_RED,
                "NEUTRAL": DarkTheme.TEXT_SECONDARY
            }.get(direction, DarkTheme.TEXT_SECONDARY)
            
            self.signal_indicators["direction"].setText(direction)
            self.signal_indicators["direction"].setStyleSheet(f"color: {direction_color};")
            
            # Update progress bars
            self.signal_indicators["strength"].setValue(strength)
            self.signal_indicators["confidence"].setValue(confidence)
            
            logging.info("Trading signals updated successfully.")
        except Exception as e:
            logging.error(f"Signal update error: {e}")

    def _update_price_chart(self):
        """Update price chart with latest data"""
        try:
            if len(self.price_history) > 1:
                # Create timestamp range
                timestamps = np.arange(len(self.price_history))
                
                # Update price line
                self.price_line.setData(x=timestamps, y=self.price_history)
                
                # Update volume bars if available
                if self.volume_history:
                    self.volume_bar.setOpts(
                        x=timestamps[-len(self.volume_history):],
                        height=self.volume_history,
                        width=0.8
                    )
            logging.info("Price chart updated successfully.")
        except Exception as e:
            logging.error(f"Chart update error: {e}")

    def _format_number(self, number: float, decimals: int = 2) -> str:
        """Format numbers with thousand separators and fixed decimals"""
        try:
            return f"{number:,.{decimals}f}"
        except Exception as e:
            logging.error(f"Number formatting error: {e}")
            return str(number)

    def _create_table_item(self, text: str, color: Optional[str] = None) -> QTableWidgetItem:
        """Create a styled table item"""
        item = QTableWidgetItem(text)
        if color:
            item.setForeground(QColor(color))
        item.setTextAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
        logging.debug(f"Table item created: {text}, color: {color}")
        return item

    def queue_update(self, data: Dict[str, Any]):
        """Queue an update to be processed"""
        logging.debug(f"Queuing update: {data}")
        self.update_handler.queue_update(data)

    def closeEvent(self, event):
        """Handle application closure"""
        try:
            self.update_handler.update_timer.stop()
            self.update_timer.stop()
            logging.info("GUI closed.")
        except Exception as e:
            logging.error(f"Error during GUI close event: {e}")
        event.accept()   PLEASE FIX MY EYES ARE BAD I CANT EDIT IT PROPERLY