i have a huge contest here i need you to do me a favor and take this script im going to share and make sure the bottom script gets integraded into it and provide me the final iteration with the proper code all of it please dont leave anything out fully coded eveyr line polease import os
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'  # Suppress TensorFlow messages

import sys
import json
import asyncio
import time
import numpy as np
from datetime import datetime
from typing import Dict, Set, List
from pathlib import Path

# PyQt6 imports
from PyQt6.QtCore import (
    Qt, 
    QTimer, 
    pyqtSignal, 
    QThread, 
    QPropertyAnimation, 
    QEasingCurve,
    QPointF
)
from PyQt6.QtGui import (
    QPainter, 
    QColor, 
    QPen, 
    QLinearGradient,
    QRadialGradient,
    QBrush,
    QGradient
)
from PyQt6.QtWidgets import (
    QApplication,
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QDoubleSpinBox,
    QSpinBox,
    QFrame,
    QTextEdit,
    QGraphicsDropShadowEffect,
    QGraphicsOpacityEffect,
    QTabWidget,
    QGridLayout,
    QScrollArea,
    QTableWidget,
    QTableWidgetItem,
    QStyleOptionTab,
    QStyle,
    QSlider,
    QComboBox
)
from PyQt6.QtCharts import (
    QChart,
    QChartView,
    QLineSeries,
    QSplineSeries,
    QScatterSeries,
    QValueAxis
)

# Trading system imports
import torch
import torch.nn as nn
from torch.cuda.amp import autocast
import pandas as pd
import websockets
import aiohttp

# Your quantum system imports
from quantum_core import QuantumCore
from quantum_strategy import QuantumStrategy
from quantum_analytics import QuantumAnalytics

# Ensure CUDA is properly initialized
if torch.cuda.is_available():
    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.benchmark = True
    device = torch.device('cuda')
    print(f"🎮 Using CUDA Device: {torch.cuda.get_device_name(0)}")
else:
    device = torch.device('cpu')
    print("⚠️ CUDA not available, using CPU")

# Configure asyncio for Windows if needed
if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

# Initialize logging directory
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)

class ElectricFrame(QFrame):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_electric_effect()
        
    def setup_electric_effect(self):
        glow = QGraphicsDropShadowEffect()
        glow.setColor(QColor("#00E4FF"))
        glow.setBlurRadius(20)
        glow.setOffset(0)
        self.setGraphicsEffect(glow)
        
        # Pulsing animation
        self.anim = QPropertyAnimation(self.graphicsEffect(), b"blurRadius")
        self.anim.setDuration(2000)
        self.anim.setStartValue(15)
        self.anim.setEndValue(25)
        self.anim.setEasingCurve(QEasingCurve.Type.InOutSine)
        self.anim.finished.connect(lambda: self.anim.start())
        self.anim.start()

class QuantumButton(QPushButton):
    def __init__(self, text, parent=None, color="#00E4FF"):
        super().__init__(text, parent)
        self.setup_quantum_effect(color)
        
    def setup_quantum_effect(self, color):
        glow = QGraphicsDropShadowEffect()
        glow.setColor(QColor(color))
        glow.setBlurRadius(20)
        glow.setOffset(0)
        self.setGraphicsEffect(glow)
        
        self.setStyleSheet(f"""
            QPushButton {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(0, 228, 255, 40),
                    stop:0.5 rgba(0, 228, 255, 60),
                    stop:1 rgba(0, 228, 255, 40));
                border: 2px solid {color};
                border-radius: 12px;
                color: {color};
                padding: 15px;
                font-size: 16px;
                font-weight: bold;
            }}
            QPushButton:hover {{
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 rgba(0, 228, 255, 60),
                    stop:0.5 rgba(0, 228, 255, 80),
                    stop:1 rgba(0, 228, 255, 60));
            }}
        """)

class HolographicChart(QChartView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_chart()
        
    def setup_chart(self):
        self.chart = QChart()
        self.setChart(self.chart)
        self.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # Main price series with quantum glow
        self.price_series = QSplineSeries()
        pen = QPen(QColor("#00E4FF"))
        pen.setWidth(3)
        self.price_series.setPen(pen)
        self.chart.addSeries(self.price_series)
        
        # Neural prediction overlay
        self.prediction_series = QSplineSeries()
        pred_pen = QPen(QColor("#FF00FF"))
        pred_pen.setWidth(2)
        self.prediction_series.setPen(pred_pen)
        self.chart.addSeries(self.prediction_series)
        
        # Trade markers
        self.trade_markers = QScatterSeries()
        self.trade_markers.setMarkerSize(15)
        self.chart.addSeries(self.trade_markers)
        
        # Quantum field effect
        self.energy_series = QSplineSeries()
        energy_pen = QPen(QColor("#304FFE"))
        energy_pen.setWidth(1)
        self.energy_series.setPen(energy_pen)
        self.chart.addSeries(self.energy_series)
        
        # Chart styling
        self.chart.setBackgroundVisible(False)
        self.chart.setDropShadowEnabled(True)
        self.chart.legend().setVisible(False)
        
        # Add quantum glow
        glow = QGraphicsDropShadowEffect()
        glow.setColor(QColor("#00E4FF"))
        glow.setBlurRadius(30)
        glow.setOffset(0)
        self.setGraphicsEffect(glow)
        
        self.setStyleSheet("""
            QChartView {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #041429,
                    stop:0.5 #062147,
                    stop:1 #041429);
            }
        """)

class TokenHunterThread(QThread):
    token_found = pyqtSignal(dict)
    trade_signal = pyqtSignal(dict)
    error_signal = pyqtSignal(str)
    
    def __init__(self, core):
        super().__init__()
        self.core = core
        self.running = True
        self.seen_tokens = set()
        
    async def hunt_tokens(self):
        headers = {"Authorization": f"Bearer {self.core.HELIUS_API_KEY}"}
        
        while self.running:
            try:
                async with websockets.connect(
                    "wss://marga-e56m84-fast-mainnet.helius-rpc.com",
                    extra_headers=headers
                ) as ws:
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "programSubscribe",
                        "params": [
                            "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
                            {"encoding": "jsonParsed", "commitment": "confirmed"}
                        ]
                    }))
                    
                    while self.running:
                        msg = await ws.recv()
                        await self.process_message(json.loads(msg))
                        
            except Exception as e:
                self.error_signal.emit(f"WebSocket error: {str(e)}")
                await asyncio.sleep(5)
                
    async def process_message(self, msg):
        try:
            token_mint = self.extract_token_mint(msg)
            if token_mint and token_mint not in self.seen_tokens:
                self.seen_tokens.add(token_mint)
                
                # Validate token
                validation = await self.core.validate_token(token_mint)
                if validation["valid"]:
                    self.token_found.emit(validation)
                    await self.analyze_trade(token_mint, validation)
        except Exception as e:
            self.error_signal.emit(f"Process error: {str(e)}")
            
    async def analyze_trade(self, token_mint: str, validation: dict):
        try:
            # Get market data
            market_data = await self.core.get_market_data(token_mint)
            
            # Run CUDA analysis
            analysis = self.core.analyze_market(market_data)
            
            if analysis["market_score"] > 0.7 and analysis["risk_score"] < 0.3:
                self.trade_signal.emit({
                    "token": token_mint,
                    "type": "entry",
                    "confidence": analysis["confidence"],
                    "data": validation
                })
        except Exception as e:
            self.error_signal.emit(f"Analysis error: {str(e)}")
            
    def run(self):
        asyncio.run(self.hunt_tokens())
        
    def stop(self):
        self.running = False

class QuantumMasterDashboard(QMainWindow):
    def __init__(self):
        super().__init__()
        self.core = QuantumCore()
        self.strategy = QuantumStrategy()
        self.analytics = QuantumAnalytics()
        
        # Initialize threads
        self.token_hunter = TokenHunterThread(self.core)
        self.token_hunter.token_found.connect(self.on_token_found)
        self.token_hunter.trade_signal.connect(self.on_trade_signal)
        self.token_hunter.error_signal.connect(self.log_error)
        
        self.setWindowTitle("⚡ QUANTUM HFT MATRIX ⚡")
        self.setup_ui()
        self.token_hunter.start()
        
    def setup_ui(self):
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        
        # Header with pulsing effect
        header = ElectricFrame()
        header_layout = QHBoxLayout(header)
        
        title = QLabel("QUANTUM TRADING MATRIX")
        title.setStyleSheet("""
            QLabel {
                color: #00E4FF;
                font-size: 24px;
                font-weight: bold;
            }
        """)
        header_layout.addWidget(title)
        
        layout.addWidget(header)
        
        # Main content
        content = QTabWidget()
        content.setStyleSheet("""
            QTabWidget::pane {
                border: 2px solid #00E4FF;
                border-radius: 15px;
                background: rgba(4, 20, 41, 180);
            }
            QTabBar::tab {
                background: rgba(0, 228, 255, 20);
                color: #00E4FF;
                border: 2px solid #00E4FF;
                border-radius: 8px;
                padding: 10px;
                margin: 2px;
            }
            QTabBar::tab:selected {
                background: rgba(0, 228, 255, 40);
            }
        """)
        
        # Trading Matrix tab
        trading_tab = QWidget()
        trading_layout = QGridLayout(trading_tab)
        
        # Main chart
        self.chart = HolographicChart()
        trading_layout.addWidget(self.chart, 0, 0, 1, 2)
        
        # Control panel
        control_panel = ElectricFrame()
        control_layout = QVBoxLayout(control_panel)
        
        # Trading controls
        controls = QHBoxLayout()
        controls.addWidget(QuantumButton("START TRADING"))
        controls.addWidget(QuantumButton("EMERGENCY STOP", color="#FF0055"))
        control_layout.addLayout(controls)
        
        # Parameters
        params_layout = QGridLayout()
        params = {
            "Max Concurrent": QSpinBox(),
            "Priority Fee": QSpinBox(),
            "Risk Level": QDoubleSpinBox(),
            "Neural Power": QDoubleSpinBox()
        }
        
        for i, (name, widget) in enumerate(params.items()):
            label = QLabel(name)
            label.setStyleSheet("color: #00E4FF;")
            params_layout.addWidget(label, i, 0)
            widget.setStyleSheet("""
                QSpinBox, QDoubleSpinBox {
                    background: rgba(0, 228, 255, 20);
                    border: 2px solid #00E4FF;
                    color: #00E4FF;
                    padding: 5px;
                }
            """)
            params_layout.addWidget(widget, i, 1)
            
        control_layout.addLayout(params_layout)
        trading_layout.addWidget(control_panel, 1, 0)
        
        # Active trades panel
        trades_panel = ElectricFrame()
        trades_layout = QVBoxLayout(trades_panel)
        
        trades_title = QLabel("ACTIVE TRADES")
        trades_title.setStyleSheet("color: #00E4FF; font-weight: bold;")
        trades_layout.addWidget(trades_title)
        
        self.trades_log = QTextEdit()
        self.trades_log.setReadOnly(True)
        self.trades_log.setStyleSheet("""
            QTextEdit {
                background: rgba(4, 20, 41, 180);
                border: 2px solid #00E4FF;
                color: #00E4FF;
            }
        """)
        trades_layout.addWidget(self.trades_log)
        
        trading_layout.addWidget(trades_panel, 1, 1)
        
        content.addTab(trading_tab, "TRADING MATRIX")
        
        # Add more tabs here...
        layout.addWidget(content)
        
        # Status bar
        self.status_bar = self.statusBar()
        self.status_bar.setStyleSheet("""
            QStatusBar {
                color: #00E4FF;
                background: rgba(4, 20, 41, 180);
                border-top: 2px solid #00E4FF;
            }
        """)
        
        self.apply_quantum_style()
        
    def apply_quantum_style(self):
        self.setStyleSheet("""
            QMainWindow {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:1,
                    stop:0 #041429,
                    stop:0.5 #062147,
                    stop:1 #041429);
            }
        """)
        
    def on_token_found(self, validation: dict):
        self.log_trade(
            f"🎯 Found token: {validation['token_name']}\n"
            f"Risk Score: {validation['risk_score']:.2f}\n"
            f"Market Score: {validation['market_score']:.2f}"
        )
        
    def on_trade_signal(self, signal: dict):
        self.log_trade(
            f"⚡ Trade signal for {signal['data']['token_name']}\n"
            f"Type: {signal['type'].upper()}\n"
            f"Confidence: {signal['confidence']:.2f}"
        )
        
    def log_trade(self, message: str):
        timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
        self.trades_log.append(
            f'<div style="margin: 5px; padding: 8px; background: rgba(0, 228, 255, 0.1); '
            f'border: 1px solid #00E4FF; border-radius: 8px;">'
            f'<span style="color: #00E4FF; font-weight: bold;">[{timestamp}]</span> '
            f'<span style="color: #00FF9C;">{message}</span>'
            f'</div>'
        )
        # Auto-scroll to bottom
        self.trades_log.verticalScrollBar().setValue(
            self.trades_log.verticalScrollBar().maximum()
        )
    
    # Add to QuantumMasterDashboard class
        def setup_advanced_panels(self):
            # Neural Analysis Tab
            neural_tab = QWidget()
            neural_layout = QGridLayout(neural_tab)

            # Neural Network Visualization
            self.neural_view = NeuralNetworkVisualizer()
            neural_layout.addWidget(self.neural_view, 0, 0, 1, 2)

            # Market Analysis Panel
            analysis_panel = ElectricFrame()
            analysis_layout = QVBoxLayout(analysis_panel)

            # Real-time metrics
            self.metric_displays = {}
            metrics = [
                ("Neural Confidence", "0.00", "#00E4FF"),
                ("Market Depth", "0.00", "#FF00FF"),
                ("Risk Factor", "0.00", "#7B42FF"),
                ("Execution Speed", "0ms", "#00FF9C")
            ]

            metrics_grid = QGridLayout()
            for i, (name, value, color) in enumerate(metrics):
                label = QLabel(name)
                label.setStyleSheet(f"color: {color}; font-weight: bold;")
                value_label = QLabel(value)
                value_label.setStyleSheet(f"""
                    QLabel {{
                        color: {color};
                        font-size: 18px;
                        padding: 5px;
                        border: 2px solid {color};
                        border-radius: 8px;
                        background: rgba(0, 228, 255, 20);
                    }}
                """)
                self.metric_displays[name] = value_label
                metrics_grid.addWidget(label, i, 0)
                metrics_grid.addWidget(value_label, i, 1)

            analysis_layout.addLayout(metrics_grid)
            neural_layout.addWidget(analysis_panel, 1, 0)

            # Strategy Matrix Panel
            strategy_panel = ElectricFrame()
            strategy_layout = QVBoxLayout(strategy_panel)

            # Strategy controls
            strategy_controls = QHBoxLayout()
            strategies = ["Quantum Momentum", "Neural Breakout", "Matrix Scalp"]
            for strat in strategies:
                btn = QuantumButton(strat, color="#00FF9C")
                strategy_controls.addWidget(btn)

            strategy_layout.addLayout(strategy_controls)

            # Performance metrics
            performance_grid = QGridLayout()
            self.performance_labels = {}
            metrics = [
                "Win Rate", "Avg Return", "Sharpe", "Sortino"
            ]

            for i, metric in enumerate(metrics):
                label = QLabel(metric)
                label.setStyleSheet("color: #00E4FF;")
                value = QLabel("0.00")
                value.setStyleSheet("""
                    QLabel {
                        color: #00FF9C;
                        font-size: 16px;
                    }
                """)
                self.performance_labels[metric] = value
                performance_grid.addWidget(label, i, 0)
                performance_grid.addWidget(value, i, 1)

            strategy_layout.addLayout(performance_grid)
            neural_layout.addWidget(strategy_panel, 1, 1)

            # Add to tabs
            self.tabs.addTab(neural_tab, "NEURAL MATRIX")

            # Market Depth Visualization Tab
            depth_tab = QWidget()
            depth_layout = QVBoxLayout(depth_tab)

            self.depth_visualizer = MarketDepthVisualizer()
            depth_layout.addWidget(self.depth_visualizer)

            self.tabs.addTab(depth_tab, "MARKET DEPTH")

class NeuralNetworkVisualizer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_visualization()

    def setup_visualization(self):
        layout = QVBoxLayout(self)
        self.canvas = ElectricFrame()
        layout.addWidget(self.canvas)

        # Neural network animation
        self.nodes = []
        self.edges = []
        self.setup_neural_network()

    def setup_neural_network(self):
        # Create nodes
        layers = [64, 128, 256, 128, 64]
        y_spacing = self.height() / max(layers)
        
        for i, layer_size in enumerate(layers):
            x = (i + 1) * self.width() / (len(layers) + 1)
            for j in range(layer_size):
                y = (j + 1) * self.height() / (layer_size + 1)
                self.nodes.append((x, y))

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)

        # Draw edges with gradient
        for start, end in self.edges:
            gradient = QLinearGradient(start[0], start[1], end[0], end[1])
            gradient.setColorAt(0, QColor("#00E4FF"))
            gradient.setColorAt(1, QColor("#FF00FF"))
            painter.setPen(QPen(gradient, 2))
            painter.drawLine(start[0], start[1], end[0], end[1])

        # Draw nodes with glow
        for x, y in self.nodes:
            # Node glow
            painter.setPen(Qt.PenStyle.NoPen)
            radial = QRadialGradient(x, y, 20)
            radial.setColorAt(0, QColor("#00E4FF"))
            radial.setColorAt(1, QColor(0, 228, 255, 0))
            painter.setBrush(radial)
            painter.drawEllipse(x-20, y-20, 40, 40)

            # Node center
            painter.setBrush(QColor("#00E4FF"))
            painter.drawEllipse(x-5, y-5, 10, 10)

class MarketDepthVisualizer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_visualization()

    def setup_visualization(self):
        layout = QVBoxLayout(self)
        
        # 3D surface chart for market depth
        self.surface = Q3DSurface()
        container = QWidget.createWindowContainer(self.surface)
        layout.addWidget(container)

        # Setup surface series
        self.series = QSurface3DSeries()
        self.surface.addSeries(self.series)

        # Customize appearance
        self.surface.setTheme(Q3DTheme.ThemeCyberpunk)
        self.surface.scene().activeCamera().setCameraPreset(
            Q3DCamera.CameraPresetFrontLow)

    async def update_depth(self, data):
        # Create depth surface
        array_data = []
        for price, size in data['bids']:
            array_data.append(QSurfaceDataRow([price, 0, size]))
        for price, size in data['asks']:
            array_data.append(QSurfaceDataRow([price, 1, size]))
            
        self.series.dataProxy().resetArray(array_data)

    def set_data(self, data):
        # Convert orderbook to surface data
        bids = np.array(data['bids'])
        asks = np.array(data['asks'])
        
        # Create surface
        x = np.linspace(bids[0,0], asks[-1,0], 100)
        y = np.linspace(0, 1, 2)
        z = np.zeros((len(y), len(x)))
        
        # Interpolate values
        for i in range(len(y)):
            if i == 0:  # Bids
                z[i] = np.interp(x, bids[:,0], bids[:,1])
            else:  # Asks
                z[i] = np.interp(x, asks[:,0], asks[:,1])
                
        self.update_surface(x, y, z)
    
class QuantumHolographicMatrix(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_matrix()
        self.setup_animation_timer()

    def setup_matrix(self):
        layout = QVBoxLayout(self)
        
        # Main trading matrix display
        self.matrix_frame = ElectricFrame()
        matrix_layout = QGridLayout(self.matrix_frame)
        
        # Neural activity visualization
        self.neural_view = NeuralFlowVisualizer()
        matrix_layout.addWidget(self.neural_view, 0, 0, 1, 2)
        
        # Live trades matrix
        self.trades_matrix = QTableWidget(0, 6)
        self.trades_matrix.setHorizontalHeaderLabels([
            "Token", "Entry", "Current", "P&L", "Neural Score", "Time"
        ])
        self.trades_matrix.setStyleSheet("""
            QTableWidget {
                background: rgba(4, 20, 41, 180);
                color: #00E4FF;
                border: 2px solid #00E4FF;
                border-radius: 15px;
                gridline-color: #304FFE;
            }
            QHeaderView::section {
                background: rgba(0, 228, 255, 20);
                color: #00E4FF;
                border: 1px solid #00E4FF;
                padding: 5px;
            }
            QTableWidget::item {
                padding: 10px;
            }
        """)
        matrix_layout.addWidget(self.trades_matrix, 1, 0, 1, 2)
        
        # Performance metrics panel
        metrics_panel = ElectricFrame()
        metrics_layout = QHBoxLayout(metrics_panel)
        
        self.metric_widgets = {}
        metrics = [
            ("Execution Speed", "0ms", "#00FF9C"),
            ("Success Rate", "0%", "#FF00FF"),
            ("Neural Accuracy", "0%", "#7B42FF"),
            ("Active Trades", "0", "#00E4FF")
        ]
        
        for name, value, color in metrics:
            widget = QLabel(f"{name}\n{value}")
            widget.setStyleSheet(f"""
                QLabel {{
                    color: {color};
                    font-size: 16px;
                    padding: 10px;
                    border: 2px solid {color};
                    border-radius: 10px;
                    background: rgba(0, 228, 255, 20);
                }}
            """)
            widget.setAlignment(Qt.AlignmentFlag.AlignCenter)
            metrics_layout.addWidget(widget)
            self.metric_widgets[name] = widget
            
        matrix_layout.addWidget(metrics_panel, 2, 0, 1, 2)
        
        # Trading controls
        controls_panel = ElectricFrame()
        controls_layout = QHBoxLayout(controls_panel)
        
        # Priority fee control with quantum styling
        fee_container = QWidget()
        fee_layout = QVBoxLayout(fee_container)
        fee_label = QLabel("PRIORITY FEE")
        fee_label.setStyleSheet("color: #00E4FF; font-weight: bold;")
        self.fee_slider = QSlider(Qt.Orientation.Horizontal)
        self.fee_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                background: #304FFE;
                height: 6px;
                border-radius: 3px;
            }
            QSlider::handle:horizontal {
                background: #00E4FF;
                width: 18px;
                margin: -6px 0;
                border-radius: 9px;
            }
        """)
        fee_layout.addWidget(fee_label)
        fee_layout.addWidget(self.fee_slider)
        controls_layout.addWidget(fee_container)
        
        # Neural power control
        power_container = QWidget()
        power_layout = QVBoxLayout(power_container)
        power_label = QLabel("NEURAL POWER")
        power_label.setStyleSheet("color: #00E4FF; font-weight: bold;")
        self.power_slider = QSlider(Qt.Orientation.Horizontal)
        self.power_slider.setStyleSheet("""
            QSlider::groove:horizontal {
                background: #7B42FF;
                height: 6px;
                border-radius: 3px;
            }
            QSlider::handle:horizontal {
                background: #FF00FF;
                width: 18px;
                margin: -6px 0;
                border-radius: 9px;
            }
        """)
        power_layout.addWidget(power_label)
        power_layout.addWidget(self.power_slider)
        controls_layout.addWidget(power_container)
        
        matrix_layout.addWidget(controls_panel, 3, 0, 1, 2)
        
        layout.addWidget(self.matrix_frame)
        
        # Setup animations
        self.setup_glow_effects()
        
    def setup_glow_effects(self):
        glow = QGraphicsDropShadowEffect()
        glow.setColor(QColor("#00E4FF"))
        glow.setBlurRadius(20)
        glow.setOffset(0)
        self.matrix_frame.setGraphicsEffect(glow)
        
        # Pulsing animation
        self.glow_anim = QPropertyAnimation(glow, b"blurRadius")
        self.glow_anim.setStartValue(15)
        self.glow_anim.setEndValue(25)
        self.glow_anim.setDuration(2000)
        self.glow_anim.setEasingCurve(QEasingCurve.Type.InOutSine)
        
        # Loop animation
        self.glow_anim.finished.connect(self.reverse_animation)
        self.glow_anim.start()
        
    def setup_animation_timer(self):
        self.anim_timer = QTimer()
        self.anim_timer.timeout.connect(self.update_animations)
        self.anim_timer.start(50)  # 50ms updates for smooth animation
        
    def update_animations(self):
        # Update neural flow visualization
        self.neural_view.update_flow()
        
        # Update matrix cells with glowing effect
        for row in range(self.trades_matrix.rowCount()):
            for col in range(self.trades_matrix.columnCount()):
                item = self.trades_matrix.item(row, col)
                if item:
                    opacity = abs(np.sin(time.time() * 2 + row * 0.5))
                    color = QColor("#00E4FF")
                    color.setAlpha(int(opacity * 255))
                    item.setBackground(color)

    def reverse_animation(self):
        # Reverse glow animation direction
        new_start = self.glow_anim.endValue()
        new_end = self.glow_anim.startValue()
        self.glow_anim.setStartValue(new_start)
        self.glow_anim.setEndValue(new_end)
        self.glow_anim.start()

class NeuralFlowVisualizer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.particles = []
        self.flows = []
        self.setup_neural_flow()
        
    def setup_neural_flow(self):
        # Create particle system
        for _ in range(100):
            particle = {
                'pos': QPointF(random.randint(0, self.width()),
                             random.randint(0, self.height())),
                'vel': QPointF(random.uniform(-2, 2),
                             random.uniform(-2, 2)),
                'life': random.uniform(0.5, 1.0)
            }
            self.particles.append(particle)
            
        # Create flow fields
        self.flows = np.zeros((20, 20, 2))  # 20x20 grid of 2D vectors
        
    def update_flow(self):
        # Update particle positions
        for p in self.particles:
            # Update position
            p['pos'] += p['vel']
            
            # Update lifetime
            p['life'] -= 0.01
            if p['life'] <= 0:
                p['life'] = 1.0
                p['pos'] = QPointF(random.randint(0, self.width()),
                                 random.randint(0, self.height()))
                                 
            # Bounce off edges
            if p['pos'].x() < 0 or p['pos'].x() > self.width():
                p['vel'].setX(-p['vel'].x())
            if p['pos'].y() < 0 or p['pos'].y() > self.height():
                p['vel'].setY(-p['vel'].y())
                
        self.update()  # Trigger repaint
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # Draw flow field
        for y in range(20):
            for x in range(20):
                # Draw flow vectors with gradient
                start = QPointF(x * self.width() / 20,
                              y * self.height() / 20)
                end = start + QPointF(self.flows[y, x, 0] * 10,
                                    self.flows[y, x, 1] * 10)
                                    
                gradient = QLinearGradient(start, end)
                gradient.setColorAt(0, QColor("#00E4FF"))
                gradient.setColorAt(1, QColor("#FF00FF"))
                painter.setPen(QPen(gradient, 1))
                painter.drawLine(start, end)
                
        # Draw particles
        for p in self.particles:
            # Particle glow
            radial = QRadialGradient(p['pos'], 10)
            color = QColor("#00E4FF")
            color.setAlphaF(p['life'])
            radial.setColorAt(0, color)
            radial.setColorAt(1, QColor(0, 228, 255, 0))
            
            painter.setPen(Qt.PenStyle.NoPen)
            painter.setBrush(radial)
            painter.drawEllipse(p['pos'], 10, 10)

class MarketDepthVisualizer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_3d_visualization()
        self.setup_animation_timer()

    def setup_3d_visualization(self):
        layout = QVBoxLayout(self)
        
        # Neural depth surface
        self.depth_frame = ElectricFrame()
        depth_layout = QVBoxLayout(self.depth_frame)
        
        # 3D surface with quantum styling
        self.surface_view = QChartView()
        self.surface_view.setRenderHint(QPainter.RenderHint.Antialiasing)
        self.surface_view.chart().setBackgroundVisible(False)
        self.surface_view.setStyleSheet("""
            QChartView {
                background: transparent;
                border: none;
            }
        """)
        
        # Add quantum glow
        glow = QGraphicsDropShadowEffect()
        glow.setColor(QColor("#00E4FF"))
        glow.setBlurRadius(30)
        self.surface_view.setGraphicsEffect(glow)
        
        depth_layout.addWidget(self.surface_view)
        layout.addWidget(self.depth_frame)
        
    def update_depth_data(self, bids, asks):
        # Clear previous series
        self.surface_view.chart().removeAllSeries()
        
        # Create bid surface
        bid_series = QLineSeries()
        bid_series.setPen(QPen(QColor("#00FF9C"), 2))
        for price, size in bids:
            bid_series.append(price, size)
            
        # Create ask surface    
        ask_series = QLineSeries()
        ask_series.setPen(QPen(QColor("#FF00FF"), 2))
        for price, size in asks:
            ask_series.append(price, size)
            
        # Add neural prediction overlay
        prediction_series = QLineSeries()
        prediction_series.setPen(QPen(QColor("#7B42FF"), 2))
        
        self.surface_view.chart().addSeries(bid_series)
        self.surface_view.chart().addSeries(ask_series)
        self.surface_view.chart().addSeries(prediction_series)

class NeuralPredictionSystem:
    def __init__(self, device):
        self.device = device
        self.setup_neural_models()
        
    def setup_neural_models(self):
        # Price prediction model
        self.price_predictor = torch.nn.Sequential(
            torch.nn.LSTM(128, 256, num_layers=4),
            torch.nn.Dropout(0.2),
            torch.nn.Linear(256, 64),
            torch.nn.ReLU(),
            torch.nn.Linear(64, 1)
        ).to(self.device)
        
        # Market analysis model
        self.market_analyzer = torch.nn.Sequential(
            torch.nn.Linear(64, 128),
            torch.nn.ReLU(),
            torch.nn.Dropout(0.2),
            torch.nn.Linear(128, 32),
            torch.nn.ReLU(),
            torch.nn.Linear(32, 16)
        ).to(self.device)
        
    @torch.cuda.amp.autocast()
    def predict_price(self, market_data):
        with torch.no_grad():
            features = self.prepare_features(market_data)
            prediction = self.price_predictor(features)
            confidence = self.calculate_confidence(prediction)
            return prediction.item(), confidence
            
    @torch.cuda.amp.autocast()
    def analyze_market(self, market_data):
        with torch.no_grad():
            features = self.prepare_features(market_data)
            analysis = self.market_analyzer(features)
            return self.interpret_analysis(analysis)

class QuantumTradeExecutor:
    def __init__(self, core):
        self.core = core
        self.active_trades = {}
        self.setup_execution_engine()
        
    def setup_execution_engine(self):
        # Initialize GPU acceleration
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.benchmark = True
        
    async def execute_trade(self, trade_params):
        try:
            start_time = time.time()
            
            # Get Jupiter quote
            quote = await self.core.get_quote(
                trade_params['input_mint'],
                trade_params['output_mint'],
                trade_params['amount']
            )
            
            # Build transaction
            swap_data = await self.core.get_swap_data(quote)
            
            # Execute with priority fee
            signature = await self.core.send_priority_tx(swap_data)
            
            execution_time = (time.time() - start_time) * 1000  # ms
            
            return {
                "success": True,
                "signature": signature,
                "execution_time": execution_time,
                "price_impact": quote.get("priceImpact", 0)
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

class QuantumMasterInterface(QMainWindow):
    def __init__(self):
        super().__init__()
        # Initialize all components
        self.core = QuantumCore()
        self.neural_system = NeuralPredictionSystem(torch.device('cuda'))
        self.trade_executor = QuantumTradeExecutor(self.core)
        self.token_hunter = TokenHunterThread(self.core)
        
        # Setup UI
        self.setWindowTitle("⚡ QUANTUM NEURAL MATRIX v1.0 ⚡")
        self.setup_complete_interface()
        
        # Start systems
        self.token_hunter.start()
        self.start_market_updates()
        
    def setup_complete_interface(self):
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        
        # Trading Matrix
        self.matrix = QuantumHolographicMatrix()
        
        # Market Depth
        self.depth_view = MarketDepthVisualizer()
        
        # Setup tabs with quantum styling
        tabs = QTabWidget()
        tabs.setStyleSheet("""
            QTabWidget::pane {
                border: 2px solid #00E4FF;
                border-radius: 15px;
                background: rgba(4, 20, 41, 180);
            }
            QTabBar::tab {
                background: rgba(0, 228, 255, 20);
                color: #00E4FF;
                border: 2px solid #00E4FF;
                padding: 10px;
                margin: 2px;
            }
            QTabBar::tab:selected {
                background: rgba(0, 228, 255, 40);
            }
        """)
        
        tabs.addTab(self.matrix, "QUANTUM MATRIX")
        tabs.addTab(self.depth_view, "NEURAL DEPTH")
        
        layout.addWidget(tabs)
        
        # Setup status bar with live metrics
        self.status_bar = self.statusBar()
        self.status_bar.setStyleSheet("""
            QStatusBar {
                color: #00E4FF;
                background: rgba(4, 20, 41, 180);
                border-top: 2px solid #00E4FF;
            }
        """)
        
        # Apply quantum styling
        self.apply_quantum_style()
        
    def start_market_updates(self):
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update_market_data)
        self.update_timer.start(100)  # 100ms updates
        
    async def update_market_data(self):
        try:
            # Update neural predictions
            prediction, confidence = await self.get_neural_prediction()
            self.matrix.update_prediction(prediction, confidence)
            
            # Update market depth
            depth_data = await self.core.get_market_depth()
            self.depth_view.update_depth_data(
                depth_data['bids'],
                depth_data['asks']
            )
            
            # Update performance metrics
            metrics = self.calculate_performance_metrics()
            self.matrix.update_metrics(metrics)
            
        except Exception as e:
            self.log_error(f"Update error: {str(e)}")
            
    async def execute_quantum_trade(self, params):
        try:
            # Neural validation
            analysis = await self.neural_system.analyze_market(params)
            if analysis['confidence'] < 0.7:
                return
                
            # Execute trade
            result = await self.trade_executor.execute_trade(params)
            
            if result['success']:
                self.log_trade(result)
            else:
                self.log_error(result['error'])
                
        except Exception as e:
            self.log_error(f"Trade error: {str(e)}")

def main():
    app = QApplication(sys.argv)
    
    # Create and show window
    window = QuantumMasterInterface()
    window.resize(1800, 1000)
    window.show()
    
    # Setup event loop
    loop = asyncio.get_event_loop()
    
    # Create Qt event loop
    from qasync import QEventLoop
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    
    # Run the system
    with loop:
        loop.run_forever()

if __name__ == "__main__":
    main()     //// the stuff from this last file needs to go in the proper place inside the 1st script # In quantum_core.py, update the decorator:
@torch.amp.autocast(device_type='cuda')
def analyze_market(self, data: Dict) -> Dict:
    """CUDA market analysis"""
    features = self.prepare_features(data)
    
    with torch.no_grad():
        # Market analysis
        market_score = self.market_analyzer(features)
        
        # Risk assessment
        risk_score = self.risk_analyzer(features[:64])
        
        return {
            "market_score": market_score.item(),
            "risk_score": risk_score.item(),
            "confidence": self.calculate_confidence(features)
        }

# Then in your NeuralPredictionSystem class:
@torch.amp.autocast(device_type='cuda')
def predict_price(self, market_data):
    with torch.no_grad():
        features = self.prepare_features(market_data)
        prediction = self.price_predictor(features)
        confidence = self.calculate_confidence(prediction)
        return prediction.item(), confidence
        
@torch.amp.autocast(device_type='cuda')
def analyze_market(self, market_data):
    with torch.no_grad():
        features = self.prepare_features(market_data)
        analysis = self.market_analyzer(features)
        return self.interpret_analysis(analysis)

# For performance monitoring, add this at the top:
class MarketPerformance:
    def __init__(self):
        self.execution_times = []
        self.success_rate = 1.0
        self.last_execution = 0.0
        
    def log_execution(self, execution_time: float, success: bool):
        self.execution_times.append(execution_time)
        if len(self.execution_times) > 1000:  # Keep last 1000 executions
            self.execution_times.pop(0)
            
        self.last_execution = execution_time
        self.success_rate = (self.success_rate * 0.99) + (float(success) * 0.01)
        
    @property
    def avg_execution_time(self) -> float:
        return sum(self.execution_times) / max(len(self.execution_times), 1)
        
    @property
    def last_exec_time(self) -> float:
        return self.last_execution
        
performance_monitor = MarketPerformance()

# Update initialization in QuantumMasterInterface
def __init__(self):
    super().__init__()
    self.core = QuantumCore()
    print(f"Initializing Quantum HFT System on {torch.cuda.get_device_name(0)}")
    
    # Monitor CUDA memory
    if torch.cuda.is_available():
        print(f"CUDA Memory Allocated: {torch.cuda.memory_allocated()/1024**2:.1f}MB")
        print(f"CUDA Memory Reserved: {torch.cuda.memory_reserved()/1024**2:.1f}MB")
    
    # Initialize components
    self.neural_system = NeuralPredictionSystem(torch.device('cuda'))
    self.setup_complete_interface()
    self.start_market_updates()