#!/usr/bin/env python3
"""
🏆 QUANTUM BEAST TRADING SYSTEM - ABSOLUTE PERFECTION 🏆
=========================================================
💎 BULLETPROOF WEBSOCKETS + FAILOVER + FALLBACK VERIFICATION 💎
🚀 UNIFIED .ENV CONFIG + PERFECT P&L + LEGENDARY DASHBOARD 🚀
⚡ lib.rs RUST ENGINE + GPU ACCELERATION + SMART BLACKLIST ⚡
=========================================================

ABSOLUTE PERFECTION FEATURES:
✅ DUAL WEBSOCKET FAILOVER (1 always active, auto-reconnect)
✅ FALLBACK VERIFICATION (dashboard corrections via Helius APIs)
✅ UNIFIED .ENV configuration (NO MORE MISMATCHES!)
✅ PERFECT P&L calculation (blockchain-verified accuracy)
✅ BULLETPROOF error handling (retries + emergency protection)
✅ REAL-TIME price tracking (instant alerts + momentum detection)
✅ lib.rs microsecond performance (0.19μs balance access)
✅ GPU early wave detection (catches setups before they happen)
✅ SMART blacklist system (1h cooldown + permanent ban)
✅ LEGENDARY dashboard (live metrics + unified config display)
✅ GRACEFUL shutdown (emergency position closure + cleanup)
✅ HELIUS VERIFICATION (blockchain-accurate trade confirmation)

THIS IS YOUR LEGENDARY TRADING WEAPON!
"""

import asyncio
import json
import time
import os
import sys
import logging
import aiohttp
import websockets
import threading
import traceback
import signal
import requests
import numpy as np
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from collections import deque, defaultdict
from dataclasses import dataclass
import statistics

# Rich for legendary terminal output
try:
    from rich.console import Console
    from rich.logging import RichHandler
    console = Console()
except ImportError:
    class Console:
        def print(self, *args, **kwargs): print(*args)
    console = Console()

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Import YOUR legendary components (NO src.python needed!)
from solana_rust_bot import SolanaTrader
from quantum_signal_finder_complete import QuantumSignalFinder
from gpu_accelerator_improved import GPUAcceleratorULTIMATE

# Load environment FIRST - single source of truth
from dotenv import load_dotenv
load_dotenv()

# Windows compatibility
if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


class UnifiedConfig:
    """🏆 UNIFIED CONFIGURATION - SINGLE SOURCE OF TRUTH FROM .ENV"""
    
    def __init__(self):
        """Load ALL configuration from .env file with intelligent defaults"""
        
        # ============= NETWORK & API CONFIGURATION =============
        self.API_KEY = os.getenv("HELIUS_API_KEY", "86ab5634-df30-4a5b-bcfb-3f53d7095ca2")
        self.KEYPAIR_PATH = os.getenv("SOLANA_KEYPAIR", r"C:\solana_rust_bot\keypair.bin")
        self.WALLET_ADDRESS = os.getenv("SOLANA_PUBLIC_KEY", "77ssrQ7LmPso1d1wYp4jAQdz4NqKSbKK8t6mFLcx6Xwr")
        
        # RPC/WebSocket endpoints with PERFECT failover
        self.PRIMARY_RPC_URL = os.getenv("PRIMARY_RPC_URL", "https://winny-rychu7-fast-mainnet.helius-rpc.com")
        self.PRIMARY_WS_URL = os.getenv("PRIMARY_WS_URL", "wss://winny-rychu7-fast-mainnet.helius-rpc.com/")
        self.SECONDARY_RPC_URL = os.getenv("SECONDARY_RPC_URL", f"https://mainnet.helius-rpc.com/?api-key={self.API_KEY}")
        self.SECONDARY_WS_URL = os.getenv("SECONDARY_WS_URL", f"wss://mainnet.helius-rpc.com/?api-key={self.API_KEY}")
        
        # Helius Enhanced APIs for verification
        self.HELIUS_ENHANCED_API = f"https://api.helius.xyz/v0"
        
        # ============= TRADING PARAMETERS =============
        self.TRADE_AMOUNT_SOL = float(os.getenv("TRADE_AMOUNT", "0.08"))
        self.COMPUTE_LIMIT = int(os.getenv("COMPUTE_LIMIT", "120000"))
        self.PRIORITY_FEE = int(os.getenv("PRIORITY_FEE", "60000"))
        self.SLIPPAGE_PERCENT = float(os.getenv("SLIPPAGE", "3.0"))
        self.SELL_PERCENTAGE = float(os.getenv("SELL_PERCENTAGE", "0.997"))
        
        # Position management
        self.MAX_CONCURRENT_POSITIONS = int(os.getenv("MAX_POSITIONS", "1"))
        self.PROFIT_TARGET_PCT = float(os.getenv("PROFIT_TARGET_PCT", "2.0"))
        self.STOP_LOSS_PCT = float(os.getenv("STOP_LOSS_PCT", "2.0"))
        self.MAX_HOLD_TIME = int(os.getenv("MAX_HOLD_TIME_SECONDS", "240"))
        
        # ============= UNIFIED SIGNAL & FILTERING THRESHOLDS =============
        self.MIN_SIGNAL_STRENGTH = float(os.getenv("MIN_SIGNAL_STRENGTH", "0.30"))
        self.MIN_LIQUIDITY_USD = float(os.getenv("MIN_LIQUIDITY_USD", "5000"))
        self.MIN_VOLUME_5M = float(os.getenv("MIN_VOLUME_5M", "500"))
        self.MIN_24H_VOLUME = float(os.getenv("MIN_24H_VOLUME", "1000"))
        self.MIN_SAFETY_SCORE = int(os.getenv("MIN_SAFETY_SCORE", "45"))
        self.MIN_EARLY_WAVE_SCORE = float(os.getenv("MIN_EARLY_WAVE_SCORE", "0.30"))
        
        # Price change thresholds
        self.MIN_PRICE_CHANGE_5M = float(os.getenv("MIN_PRICE_CHANGE_5M", "1.0"))
        self.MAX_PRICE_CHANGE_5M = float(os.getenv("MAX_PRICE_CHANGE_5M", "9.0"))
        
        # ============= INTERVALS & TIMING =============
        self.CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL", "20"))
        self.POSITION_CHECK_INTERVAL = float(os.getenv("POSITION_CHECK_INTERVAL", "0.5"))
        self.DASHBOARD_UPDATE_INTERVAL = float(os.getenv("DASHBOARD_UPDATE_INTERVAL", "1.0"))
        self.PRICE_UPDATE_INTERVAL = float(os.getenv("PRICE_UPDATE_INTERVAL", "0.5"))
        
        # ============= WEBSOCKET CONFIGURATION =============
        self.WS_CONFIRMATION_TIMEOUT = float(os.getenv("WS_CONFIRMATION_TIMEOUT", "5.0"))
        self.WS_RETRY_ATTEMPTS = int(os.getenv("WS_RETRY_ATTEMPTS", "3"))
        self.CONNECTION_TIMEOUT = int(os.getenv("CONNECTION_TIMEOUT", "10"))
        self.BALANCE_CHANGE_THRESHOLD = float(os.getenv("BALANCE_CHANGE_THRESHOLD", "0.01"))  # Your 0.01 SOL threshold!
        
        # ============= BLACKLIST & EXCLUSIONS =============
        blacklist_str = os.getenv("BLACKLISTED_TOKENS", "SOL,USDC,USDT,WSOL,RAY,JUP,BONK,WIF,BOME")
        self.EXCLUDED_TOKENS = [token.strip().upper() for token in blacklist_str.split(",") if token.strip()]
        
        # ============= RISK MANAGEMENT =============
        self.MIN_SOL_BALANCE = float(os.getenv("MIN_SOL_BALANCE", "0.005"))
        self.MAX_WALLET_USAGE_PERCENT = float(os.getenv("MAX_WALLET_USAGE_PERCENT", "80.0"))
        
        # ============= LOGGING =============
        self.LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
        self.DETAILED_LOGGING = os.getenv("DETAILED_LOGGING", "false").lower() == "true"
        
        # ============= VERIFICATION SETTINGS =============
        self.ENABLE_FALLBACK_VERIFICATION = os.getenv("ENABLE_FALLBACK_VERIFICATION", "true").lower() == "true"
        self.VERIFICATION_INTERVAL = int(os.getenv("VERIFICATION_INTERVAL", "300"))  # 5 minutes
        
        console.print("[green]✅ PERFECT UNIFIED CONFIG LOADED - SINGLE SOURCE OF TRUTH![/green]")
        self.print_key_settings()
    
    def print_key_settings(self):
        """Print key configuration settings for verification"""
        console.print(f"[cyan]📊 PERFECT UNIFIED SETTINGS:[/cyan]")
        console.print(f"   💰 Trade Amount: {self.TRADE_AMOUNT_SOL} SOL")
        console.print(f"   🎯 Targets: +{self.PROFIT_TARGET_PCT}% / -{self.STOP_LOSS_PCT}%")
        console.print(f"   📈 Min Signal: {self.MIN_SIGNAL_STRENGTH}")
        console.print(f"   💧 Min Liquidity: ${self.MIN_LIQUIDITY_USD:,.0f}")
        console.print(f"   📊 Min Volume 5m: ${self.MIN_VOLUME_5M:,.0f}")
        console.print(f"   ⏱️ Check Interval: {self.CHECK_INTERVAL}s")
        console.print(f"   🚫 Blacklisted: {len(self.EXCLUDED_TOKENS)} tokens")
        console.print(f"   🌐 Balance Threshold: {self.BALANCE_CHANGE_THRESHOLD} SOL (YOUR 0.01 GENIUS!)")
        console.print(f"   🔄 Fallback Verification: {'ENABLED' if self.ENABLE_FALLBACK_VERIFICATION else 'DISABLED'}")


# Initialize global config
CONFIG = UnifiedConfig()


class PerfectWebSocketMonitor:
    """🔥 PERFECT WebSocket system with bulletproof failover and auto-reconnect"""
    
    def __init__(self, wallet_address: str, api_key: str):
        self.wallet_address = wallet_address
        self.api_key = api_key
        
        # WebSocket URLs from config
        self.primary_url = CONFIG.PRIMARY_WS_URL
        self.secondary_url = CONFIG.SECONDARY_WS_URL
        
        # Connection objects
        self.primary_ws = None
        self.secondary_ws = None
        self.primary_healthy = False
        self.secondary_healthy = False
        
        # PERFECT failover tracking
        self.primary_last_seen = 0
        self.secondary_last_seen = 0
        self.reconnect_delays = {"primary": 1, "secondary": 1}
        self.max_reconnect_delay = 30
        
        # Balance tracking with PERFECT precision
        self.balance_updates = deque(maxlen=200)
        self.current_balance = 0.0
        self.last_balance = None
        self.balance_precision = 6
        
        # Racing logic for confirmations
        self.balance_event = asyncio.Event()
        self.confirmation_responder = None
        
        # PERFECT stats tracking
        self.primary_wins = 0
        self.secondary_wins = 0
        self.total_updates = 0
        self.connection_attempts = {"primary": 0, "secondary": 0}
        self.reconnect_count = {"primary": 0, "secondary": 0}
        
        # Health monitoring
        self.health_check_interval = 30  # seconds
        self.last_health_check = 0
        
        # Headers with authentication
        self.headers = {
            "User-Agent": "solana-cli 1.18.23 (src:aeb3a2e1; feat:4215500110, client:SolanaLabs)",
            "Authorization": f"Bearer {self.api_key}"
        }
    
    async def connect(self):
        """PERFECT connection with bulletproof failover"""
        console.print("[WS] 🚀 Initializing PERFECT WebSocket system with failover...")
        
        # Start both connections concurrently
        primary_task = asyncio.create_task(self._maintain_primary_connection())
        secondary_task = asyncio.create_task(self._maintain_secondary_connection())
        health_task = asyncio.create_task(self._health_monitor())
        
        # Wait for at least one connection
        try:
            await asyncio.wait_for(self._wait_for_any_connection(), timeout=CONFIG.CONNECTION_TIMEOUT)
            console.print("[green]✅ PERFECT WebSocket system ready with failover![/green]")
            return True
        except asyncio.TimeoutError:
            console.print("[yellow]⏰ WebSocket timeout - lib.rs RPC fallback ready[/yellow]")
            return False
    
    async def _wait_for_any_connection(self):
        """Wait for at least one healthy connection"""
        while not (self.primary_healthy or self.secondary_healthy):
            await asyncio.sleep(0.1)
    
    async def _health_monitor(self):
        """PERFECT health monitoring with auto-healing"""
        while True:
            try:
                await asyncio.sleep(self.health_check_interval)
                current_time = time.time()
                
                # Check if connections are stale
                primary_stale = (current_time - self.primary_last_seen) > 60 if self.primary_last_seen > 0 else False
                secondary_stale = (current_time - self.secondary_last_seen) > 60 if self.secondary_last_seen > 0 else False
                
                if primary_stale and self.primary_healthy:
                    console.print("[yellow][HEALTH] Primary connection stale - triggering reconnect[/yellow]")
                    self.primary_healthy = False
                    if self.primary_ws:
                        await self.primary_ws.close()
                
                if secondary_stale and self.secondary_healthy:
                    console.print("[yellow][HEALTH] Secondary connection stale - triggering reconnect[/yellow]")
                    self.secondary_healthy = False
                    if self.secondary_ws:
                        await self.secondary_ws.close()
                
                # Ensure at least one connection is always healthy
                if not self.primary_healthy and not self.secondary_healthy:
                    console.print("[red][HEALTH] 🚨 ALL CONNECTIONS DOWN - CRITICAL HEALING[/red]")
                    # Reset delays for emergency reconnect
                    self.reconnect_delays = {"primary": 1, "secondary": 1}
                
                self.last_health_check = current_time
                
            except Exception as e:
                console.print(f"[red][HEALTH] Health monitor error: {e}[/red]")
                await asyncio.sleep(5)
    
    async def _maintain_primary_connection(self):
        """Maintain primary connection with PERFECT exponential backoff"""
        while True:
            try:
                self.connection_attempts["primary"] += 1
                console.print(f"[PRIMARY] 🔌 Connecting... (attempt {self.connection_attempts['primary']})")
                
                # Adaptive headers based on endpoint
                headers = self.headers if "helius" not in self.primary_url else {}
                
                self.primary_ws = await websockets.connect(
                    self.primary_url,
                    extra_headers=headers,
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=5
                )
                
                await self._subscribe_to_account(self.primary_ws, "PRIMARY")
                self.primary_healthy = True
                self.primary_last_seen = time.time()
                self.reconnect_delays["primary"] = 1  # Reset delay on success
                self.reconnect_count["primary"] += 1
                console.print("[green][PRIMARY] ✅ WebSocket Connected and Subscribed[/green]")
                
                # Listen for messages
                await self._listen_primary()
                
            except Exception as e:
                console.print(f"[PRIMARY] ❌ Connection failed: {e}")
                self.primary_healthy = False
                
                # PERFECT exponential backoff with jitter
                delay = min(self.reconnect_delays["primary"] * 2, self.max_reconnect_delay)
                self.reconnect_delays["primary"] = delay
                jitter = delay * 0.1 * (0.5 - time.time() % 1)
                
                console.print(f"[PRIMARY] 🔄 Reconnecting in {delay + jitter:.1f}s...")
                await asyncio.sleep(delay + jitter)
    
    async def _maintain_secondary_connection(self):
        """Maintain secondary connection with PERFECT exponential backoff"""
        # Stagger connections to avoid thundering herd
        await asyncio.sleep(2)
        
        while True:
            try:
                self.connection_attempts["secondary"] += 1
                console.print(f"[SECONDARY] 🔌 Connecting... (attempt {self.connection_attempts['secondary']})")
                
                self.secondary_ws = await websockets.connect(
                    self.secondary_url,
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=5
                )
                
                await self._subscribe_to_account(self.secondary_ws, "SECONDARY")
                self.secondary_healthy = True
                self.secondary_last_seen = time.time()
                self.reconnect_delays["secondary"] = 1  # Reset delay on success
                self.reconnect_count["secondary"] += 1
                console.print("[green][SECONDARY] ✅ WebSocket Connected and Subscribed[/green]")
                
                # Listen for messages
                await self._listen_secondary()
                
            except Exception as e:
                console.print(f"[SECONDARY] ❌ Connection failed: {e}")
                self.secondary_healthy = False
                
                # PERFECT exponential backoff with jitter
                delay = min(self.reconnect_delays["secondary"] * 2, self.max_reconnect_delay)
                self.reconnect_delays["secondary"] = delay
                jitter = delay * 0.1 * (0.5 - time.time() % 1)
                
                console.print(f"[SECONDARY] 🔄 Reconnecting in {delay + jitter:.1f}s...")
                await asyncio.sleep(delay + jitter)
    
    async def _subscribe_to_account(self, ws, label: str):
        """Subscribe to account updates with PERFECT error handling"""
        subscribe_msg = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "accountSubscribe",
            "params": [
                self.wallet_address,
                {
                    "encoding": "base64",
                    "commitment": "processed"
                }
            ]
        }
        
        await asyncio.wait_for(ws.send(json.dumps(subscribe_msg)), timeout=10)
        response = await asyncio.wait_for(ws.recv(), timeout=10)
        result = json.loads(response)
        
        if "result" in result:
            console.print(f"[{label}] 🎯 Account Subscription Active (ID: {result['result']})")
        else:
            console.print(f"[{label}] ⚠️ Subscription Error: {result}")
            raise Exception(f"Subscription failed: {result}")
    
    async def _listen_primary(self):
        """Listen for primary WebSocket updates with PERFECT error handling"""
        try:
            async for message in self.primary_ws:
                self.primary_last_seen = time.time()
                await self._process_balance_update(message, "PRIMARY")
        except websockets.exceptions.ConnectionClosed:
            console.print("[PRIMARY] 🔌 Connection closed - auto-reconnecting...")
        except Exception as e:
            console.print(f"[PRIMARY] 👂 Listen error: {e}")
        finally:
            self.primary_healthy = False
    
    async def _listen_secondary(self):
        """Listen for secondary WebSocket updates with PERFECT error handling"""
        try:
            async for message in self.secondary_ws:
                self.secondary_last_seen = time.time()
                await self._process_balance_update(message, "SECONDARY")
        except websockets.exceptions.ConnectionClosed:
            console.print("[SECONDARY] 🔌 Connection closed - auto-reconnecting...")
        except Exception as e:
            console.print(f"[SECONDARY] 👂 Listen error: {e}")
        finally:
            self.secondary_healthy = False
    
    async def _process_balance_update(self, message: str, source: str):
        """🔥 PERFECT balance detection with YOUR 0.01 SOL threshold"""
        try:
            data = json.loads(message)
            
            if "method" in data and data["method"] == "accountNotification":
                result = data["params"]["result"]
                value = result.get("value", {})
                
                if "lamports" in value:
                    new_balance = round(value["lamports"] / 1_000_000_000, self.balance_precision)
                    old_balance = self.current_balance
                    
                    self.current_balance = new_balance
                    self.total_updates += 1
                    
                    if old_balance > 0:
                        balance_change = round(new_balance - old_balance, self.balance_precision)
                        
                        # YOUR GENIUS 0.01 SOL THRESHOLD SYSTEM!
                        if abs(balance_change) >= CONFIG.BALANCE_CHANGE_THRESHOLD:
                            change_style = "green" if balance_change > 0 else "red"
                            
                            # Determine trade type
                            if balance_change <= -CONFIG.BALANCE_CHANGE_THRESHOLD:
                                trade_type = "🚀 BUY CONFIRMED"
                            elif balance_change >= CONFIG.BALANCE_CHANGE_THRESHOLD:
                                trade_type = "💰 SELL CONFIRMED"
                            else:
                                trade_type = "💰 BALANCE CHANGE"
                            
                            console.print(f"[{source}] [{change_style}]{trade_type}: {new_balance:.6f} SOL ({balance_change:+.6f})[/{change_style}]")
                            
                            # RACING LOGIC - First to detect wins!
                            if not self.balance_event.is_set():
                                self.confirmation_responder = source
                                self.balance_event.set()
                                
                                if source == "PRIMARY":
                                    self.primary_wins += 1
                                else:
                                    self.secondary_wins += 1
                    
                    # Store update with timestamp
                    update = {
                        "source": source,
                        "balance": new_balance,
                        "change": new_balance - old_balance if old_balance > 0 else 0,
                        "timestamp": time.time(),
                        "is_trade": abs(new_balance - old_balance) >= CONFIG.BALANCE_CHANGE_THRESHOLD if old_balance > 0 else False
                    }
                    self.balance_updates.append(update)
                    
        except Exception as e:
            if CONFIG.DETAILED_LOGGING:
                console.print(f"[{source}] 🔍 Parse error: {e}")
    
    async def wait_for_balance_change(self, timeout=None):
        """🏆 PERFECT racing confirmation system"""
        if timeout is None:
            timeout = CONFIG.WS_CONFIRMATION_TIMEOUT
            
        self.balance_event.clear()
        self.confirmation_responder = None
        
        start_time = time.perf_counter()
        
        try:
            await asyncio.wait_for(self.balance_event.wait(), timeout)
            elapsed_time = (time.perf_counter() - start_time) * 1000
            return True, elapsed_time, self.confirmation_responder
        except asyncio.TimeoutError:
            elapsed_time = timeout * 1000
            return False, elapsed_time, None
    
    def get_balance(self) -> float:
        """Get current balance (MICROSECOND ACCESS)"""
        return self.current_balance
    
    def is_connected(self) -> bool:
        """Check if at least one WebSocket is connected"""
        return self.primary_healthy or self.secondary_healthy
    
    def get_connection_status(self) -> str:
        """Get detailed connection status"""
        if self.primary_healthy and self.secondary_healthy:
            return "🔥 DUAL_POWER"
        elif self.primary_healthy:
            return "⚡ PRIMARY_ACTIVE"  
        elif self.secondary_healthy:
            return "🔄 SECONDARY_ACTIVE"
        else:
            return "❌ DISCONNECTED"
    
    def get_connection_stats(self) -> Dict:
        """Get detailed connection statistics"""
        return {
            "primary_healthy": self.primary_healthy,
            "secondary_healthy": self.secondary_healthy,
            "primary_wins": self.primary_wins,
            "secondary_wins": self.secondary_wins,
            "total_updates": self.total_updates,
            "primary_attempts": self.connection_attempts["primary"],
            "secondary_attempts": self.connection_attempts["secondary"],
            "primary_reconnects": self.reconnect_count["primary"],
            "secondary_reconnects": self.reconnect_count["secondary"],
            "primary_last_seen": time.time() - self.primary_last_seen if self.primary_last_seen > 0 else -1,
            "secondary_last_seen": time.time() - self.secondary_last_seen if self.secondary_last_seen > 0 else -1,
            "status": self.get_connection_status(),
            "balance_threshold": CONFIG.BALANCE_CHANGE_THRESHOLD,
            "health_monitoring": True
        }
    
    async def close(self):
        """Gracefully close all connections"""
        console.print("[WS] 🛑 Closing PERFECT WebSocket connections...")
        try:
            if self.primary_ws and not self.primary_ws.closed:
                await self.primary_ws.close()
            if self.secondary_ws and not self.secondary_ws.closed:
                await self.secondary_ws.close()
        except Exception as e:
            console.print(f"[WS] ⚠️ Close error: {e}")


class HeliusFallbackVerifier:
    """🔍 PERFECT fallback verification using Helius Enhanced APIs"""
    
    def __init__(self, api_key: str, wallet_address: str):
        self.api_key = api_key
        self.wallet_address = wallet_address
        self.base_url = CONFIG.HELIUS_ENHANCED_API
        
        # Session for HTTP requests
        self.session = requests.Session()
        self.session.headers.update({
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        })
        
        # Verification tracking
        self.verified_trades = {}
        self.verification_errors = 0
        self.last_verification = 0
    
    def parse_transaction(self, signature: str) -> Dict:
        """Parse a single transaction using Helius Enhanced API"""
        try:
            url = f"{self.base_url}/transactions/?api-key={self.api_key}"
            payload = {"transactions": [signature]}
            
            response = self.session.post(url, json=payload, timeout=10)
            
            if response.status_code != 200:
                return {"error": f"HTTP {response.status_code}"}
            
            data = response.json()
            if not data or len(data) == 0:
                return {"error": "No data"}
            
            tx_data = data[0]
            return self._extract_trade_data(tx_data, signature)
            
        except Exception as e:
            return {"error": str(e)}
    
    def _extract_trade_data(self, tx_data: Dict, signature: str) -> Dict:
        """Extract trading data from transaction"""
        timestamp = tx_data.get("timestamp", 0)
        fee = tx_data.get("fee", 0)
        success = tx_data.get("success", False)
        
        # Native transfers (SOL movements)
        native_transfers = tx_data.get("nativeTransfers", [])
        sol_in = 0.0
        sol_out = 0.0
        
        for transfer in native_transfers:
            from_account = transfer.get("fromUserAccount", "")
            to_account = transfer.get("toUserAccount", "")
            amount_sol = transfer.get("amount", 0) / 1_000_000_000
            
            if from_account == self.wallet_address:
                sol_out += amount_sol
            elif to_account == self.wallet_address:
                sol_in += amount_sol
        
        # Token transfers
        token_transfers = tx_data.get("tokenTransfers", [])
        tokens_in = {}
        tokens_out = {}
        
        for transfer in token_transfers:
            from_account = transfer.get("fromUserAccount", "")
            to_account = transfer.get("toUserAccount", "")
            mint = transfer.get("mint", "")
            amount = transfer.get("tokenAmount", 0)
            
            if from_account == self.wallet_address:
                tokens_out[mint] = tokens_out.get(mint, 0) + amount
            elif to_account == self.wallet_address:
                tokens_in[mint] = tokens_in.get(mint, 0) + amount
        
        return {
            "signature": signature,
            "timestamp": timestamp,
            "success": success,
            "fee_lamports": fee,
            "fee_sol": fee / 1_000_000_000,
            "sol_in": sol_in,
            "sol_out": sol_out,
            "net_sol": sol_in - sol_out,
            "tokens_in": tokens_in,
            "tokens_out": tokens_out,
            "raw_data": tx_data
        }
    
    def verify_trade(self, buy_signature: str, sell_signature: str = None) -> Dict:
        """Verify a complete trade (buy + optional sell)"""
        try:
            # Parse buy transaction
            buy_data = self.parse_transaction(buy_signature)
            if "error" in buy_data:
                return {"error": f"Buy verification failed: {buy_data['error']}"}
            
            verification_result = {
                "buy_verified": True,
                "buy_data": buy_data,
                "sell_verified": False,
                "sell_data": None,
                "net_pnl_sol": 0,
                "net_pnl_pct": 0,
                "verification_timestamp": time.time()
            }
            
            if sell_signature:
                # Parse sell transaction
                sell_data = self.parse_transaction(sell_signature)
                if "error" not in sell_data:
                    verification_result["sell_verified"] = True
                    verification_result["sell_data"] = sell_data
                    
                    # Calculate verified P&L
                    total_cost = buy_data["sol_out"] + buy_data["fee_sol"]
                    total_received = sell_data["sol_in"] - sell_data["fee_sol"]
                    net_pnl = total_received - total_cost
                    net_pnl_pct = (net_pnl / total_cost) * 100 if total_cost > 0 else 0
                    
                    verification_result["net_pnl_sol"] = net_pnl
                    verification_result["net_pnl_pct"] = net_pnl_pct
            
            self.verified_trades[buy_signature] = verification_result
            return verification_result
            
        except Exception as e:
            self.verification_errors += 1
            return {"error": f"Verification failed: {e}"}


class PerfectRealTimePriceTracker:
    """🎯 PERFECT real-time price tracking with advanced alerts"""
    
    def __init__(self):
        self.tracking_tokens = {}
        self.current_prices = {}
        self.last_prices = {}
        self.running = False
        self.price_alerts = deque(maxlen=100)
        self.price_history = defaultdict(lambda: deque(maxlen=200))
        self.fetch_errors = defaultdict(int)
        self.last_successful_fetch = defaultdict(float)
        
        # Advanced tracking
        self.momentum_alerts = deque(maxlen=50)
        self.volatility_tracking = defaultdict(list)
        
    def add_token(self, symbol, mint_address, entry_price):
        """Add token to PERFECT tracking system"""
        self.tracking_tokens[symbol] = mint_address
        self.current_prices[symbol] = entry_price
        self.last_prices[symbol] = entry_price
        self.fetch_errors[symbol] = 0
        self.last_successful_fetch[symbol] = time.time()
        console.print(f"[TRACKER] 📊 Started {CONFIG.PRICE_UPDATE_INTERVAL}s tracking {symbol} @ ${entry_price:.8f}")
        
    def remove_token(self, symbol):
        """Remove token from tracking"""
        if symbol in self.tracking_tokens:
            del self.tracking_tokens[symbol]
            del self.current_prices[symbol]
            del self.last_prices[symbol]
            if symbol in self.fetch_errors:
                del self.fetch_errors[symbol]
            if symbol in self.last_successful_fetch:
                del self.last_successful_fetch[symbol]
            console.print(f"[TRACKER] 🛑 Stopped tracking {symbol}")
    
    def get_current_price(self, symbol):
        """Get current price with fallback"""
        return self.current_prices.get(symbol, 0)
    
    async def fetch_price(self, session, mint_address):
        """PERFECT price fetching with error handling"""
        try:
            url = f"https://api.dexscreener.com/latest/dex/tokens/{mint_address}"
            async with session.get(url, timeout=3) as response:
                if response.status != 200:
                    return None
                
                data = await response.json()
                if "pairs" in data and data["pairs"]:
                    # Get best pair by liquidity
                    best_pair = max(data["pairs"], 
                                  key=lambda p: float(p.get("liquidity", {}).get("usd", 0)))
                    price = best_pair.get("priceUsd")
                    return float(price) if price else None
                return None
        except Exception:
            return None
    
    async def update_prices(self):
        """Update all tracked prices with PERFECT error handling"""
        if not self.tracking_tokens:
            return
        
        try:
            connector = aiohttp.TCPConnector(ssl=False, limit=10, ttl_dns_cache=300)
            timeout = aiohttp.ClientTimeout(total=8)
            
            async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
                for symbol, mint_address in self.tracking_tokens.items():
                    try:
                        new_price = await self.fetch_price(session, mint_address)
                        
                        if new_price and new_price > 0:
                            old_price = self.last_prices.get(symbol, new_price)
                            self.current_prices[symbol] = new_price
                            self.fetch_errors[symbol] = 0
                            self.last_successful_fetch[symbol] = time.time()
                            
                            # Store price history
                            self.price_history[symbol].append({
                                "price": new_price,
                                "timestamp": time.time()
                            })
                            
                            # Calculate volatility
                            if len(self.price_history[symbol]) >= 10:
                                recent_prices = [p["price"] for p in list(self.price_history[symbol])[-10:]]
                                volatility = np.std(recent_prices) / np.mean(recent_prices) if np.mean(recent_prices) > 0 else 0
                                self.volatility_tracking[symbol].append(volatility)
                                if len(self.volatility_tracking[symbol]) > 20:
                                    self.volatility_tracking[symbol].pop(0)
                            
                            # Check for significant price movements
                            if old_price > 0:
                                price_change_pct = ((new_price - old_price) / old_price) * 100
                                
                                if abs(price_change_pct) >= CONFIG.PRICE_ALERT_THRESHOLD:
                                    direction = "📈" if price_change_pct > 0 else "📉"
                                    style = "green" if price_change_pct > 0 else "red"
                                    
                                    # Enhanced alerts
                                    if abs(price_change_pct) >= 5.0:
                                        alert_type = "🚀 MASSIVE" if price_change_pct > 0 else "💥 CRASH"
                                        console.print(f"[{style}]{alert_type}: {symbol} {direction} {abs(price_change_pct):.2f}% | ${new_price:.8f}[/{style}]")
                                    elif abs(price_change_pct) >= 3.0:
                                        alert_type = "🔥 MAJOR" if price_change_pct > 0 else "💀 MAJOR"
                                        console.print(f"[{style}]{alert_type}: {symbol} {direction} {abs(price_change_pct):.2f}% | ${new_price:.8f}[/{style}]")
                                    else:
                                        console.print(f"[{style}]💰 {symbol}: {direction} {abs(price_change_pct):.2f}% | ${new_price:.8f}[/{style}]")
                                    
                                    self.price_alerts.append({
                                        "symbol": symbol,
                                        "price": new_price,
                                        "change_pct": price_change_pct,
                                        "timestamp": time.time(),
                                        "alert_type": "MASSIVE" if abs(price_change_pct) >= 5.0 else "MAJOR" if abs(price_change_pct) >= 3.0 else "NORMAL"
                                    })
                                
                                # Momentum detection
                                if len(self.price_history[symbol]) >= 5:
                                    recent_prices = [p["price"] for p in list(self.price_history[symbol])[-5:]]
                                    if all(recent_prices[i] > recent_prices[i-1] for i in range(1, 5)):
                                        console.print(f"🔥 {symbol}: 5 GREEN CANDLES IN A ROW! 🚀")
                                        self.momentum_alerts.append({
                                            "symbol": symbol,
                                            "type": "5_GREEN_CANDLES",
                                            "timestamp": time.time()
                                        })
                                    elif all(recent_prices[i] < recent_prices[i-1] for i in range(1, 5)):
                                        console.print(f"⚠️ {symbol}: 5 RED CANDLES IN A ROW! 📉")
                                        self.momentum_alerts.append({
                                            "symbol": symbol,
                                            "type": "5_RED_CANDLES",
                                            "timestamp": time.time()
                                        })
                            
                            self.last_prices[symbol] = new_price
                        else:
                            self.fetch_errors[symbol] += 1
                            if self.fetch_errors[symbol] > 5:
                                console.print(f"[yellow]⚠️ {symbol}: Multiple price fetch errors[/yellow]")
                                
                    except Exception as e:
                        self.fetch_errors[symbol] += 1
                        if CONFIG.DETAILED_LOGGING:
                            console.print(f"[yellow]⚠️ Price fetch error for {symbol}: {e}[/yellow]")
                        continue
                        
        except Exception as e:
            if CONFIG.DETAILED_LOGGING:
                console.print(f"[yellow]⚠️ Price update session error: {e}[/yellow]")
    
    async def start_tracking(self):
        """Start the PERFECT price tracking loop"""
        self.running = True
        console.print(f"[TRACKER] 🚀 PERFECT {CONFIG.PRICE_UPDATE_INTERVAL}s TRACKING STARTED!")
        
        while self.running:
            try:
                if self.tracking_tokens:
                    await self.update_prices()
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)
            except Exception as e:
                if CONFIG.DETAILED_LOGGING:
                    console.print(f"[yellow]⚠️ Tracking loop error: {e}[/yellow]")
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)
    
    def stop_tracking(self):
        """Stop the price tracking"""
        self.running = False
        console.print("[TRACKER] 🛑 PERFECT TRACKING STOPPED")


class QuantumBeastPerfect:
    """🏆 QUANTUM BEAST - ABSOLUTE PERFECTION 🏆"""
    
    def __init__(self):
        self.running = False
        self.shutdown_event = asyncio.Event()
        
        # Components
        self.trader = None
        self.signal_finder = None
        self.gpu_accelerator = None
        self.ws_listener = None
        self.price_tracker = PerfectRealTimePriceTracker()
        self.fallback_verifier = None
        
        # Session tracking
        self.initial_balance = 0
        self.session_start_balance = 0
        self.session_start_time = time.time()
        self.positions = {}
        self.completed_trades = []
        self.recent_trades = []
        
        # Stats
        self.trades_executed = 0
        self.trades_won = 0
        self.trades_lost = 0
        self.best_trade = 0
        self.worst_trade = 0
        self.dashboard_update_count = 0
        
        # Performance tracking
        self.execution_times = deque(maxlen=200)
        self.confirmation_times = deque(maxlen=200)
        self.blockhash_times = deque(maxlen=200)
        
        # Enhanced error tracking
        self.failed_tokens = defaultdict(int)
        self.blacklisted_tokens = set()
        self.token_cooldowns = {}  # 1-hour cooldowns
        
        # Emergency protection
        self.emergency_shutdown = False
        self.max_consecutive_failures = 3
        self.consecutive_failures = 0
        
        # Verification tracking
        self.last_verification_time = 0
        self.verified_trades_count = 0
        self.verification_corrections = 0
    
    async def initialize(self):
        """🚀 Initialize QUANTUM BEAST with ABSOLUTE PERFECTION"""
        
        # Display PERFECT header
        console.print("\n" + "🔥" * 80)
        console.print("🏆 QUANTUM BEAST - ABSOLUTE PERFECTION 🏆".center(80))
        console.print("💎 BULLETPROOF FAILOVER + HELIUS VERIFICATION + LEGENDARY DASHBOARD 💎".center(80))
        console.print("🚀 YOUR 0.01 SOL GENIUS + RUST SPEED + GPU POWER = PERFECTION! 🚀".center(80))
        console.print("🔥" * 80)
        
        console.print("\n[bold]🔥 INITIALIZING ABSOLUTE PERFECTION 🔥[/bold]")
        console.print("-" * 50)
        
        # Initialize Rust trader
        console.print("⚡ Initializing lib.rs Rust Trading Engine...", end="")
        self.trader = SolanaTrader(
            rpc_url=CONFIG.PRIMARY_RPC_URL,
            ws_url=CONFIG.PRIMARY_WS_URL,
            keypair_path=CONFIG.KEYPAIR_PATH,
            compute_limit=CONFIG.COMPUTE_LIMIT,
            api_key=CONFIG.API_KEY
        )
        console.print(" [green]✅ LEGENDARY[/green]")
        
        # Test lib.rs performance
        console.print("🔬 Testing lib.rs LEGENDARY performance...", end="")
        start_time = time.perf_counter()
        address = self.trader.get_address()
        blockhash_time = (time.perf_counter() - start_time) * 1000000
        self.blockhash_times.append(blockhash_time)
        console.print(f" [green]✅ {blockhash_time:.1f}μs[/green]")
        
        # Get initial balance
        console.print("💰 Getting initial balance...", end="")
        initial_bal = self.trader.get_sol_balance()
        self.initial_balance = initial_bal
        self.session_start_balance = initial_bal
        console.print(f" [green]✅ {initial_bal:.6f} SOL[/green]")
        
        # Prime blockhash cache
        console.print("🔄 Priming lib.rs blockhash cache...", end="")
        start_time = time.perf_counter()
        self.trader.force_update_blockhash()
        cache_time = (time.perf_counter() - start_time) * 1000
        console.print(f" [green]✅ {cache_time:.1f}ms[/green]")
        
        # Test cached blockhash (YOUR 0.19μs magic!)
        console.print("⚡ Testing YOUR 0.19μs cached access...", end="")
        start_time = time.perf_counter()
        cached_hash = self.trader.get_cached_blockhash()
        cached_time = (time.perf_counter() - start_time) * 1000000
        console.print(f" [green]✅ {cached_time:.1f}μs - YOUR GENIUS![/green]")
        
        # Initialize signal finder
        console.print("🧠 Initializing PERFECT Signal Finder...", end="")
        self.signal_finder = QuantumSignalFinder()
        await self.signal_finder.initialize()
        console.print(" [green]✅ LOADED[/green]")
        
        # Initialize GPU accelerator
        console.print("🎮 Initializing LEGENDARY GPU Accelerator...", end="")
        self.gpu_accelerator = GPUAcceleratorULTIMATE()
        console.print(" [green]✅ LEGENDARY[/green]")
        
        # Initialize fallback verifier
        if CONFIG.ENABLE_FALLBACK_VERIFICATION:
            console.print("🔍 Initializing Helius Fallback Verifier...", end="")
            self.fallback_verifier = HeliusFallbackVerifier(CONFIG.API_KEY, CONFIG.WALLET_ADDRESS)
            console.print(" [green]✅ READY[/green]")
        
        # Start price tracker
        console.print(f"📊 Starting PERFECT {CONFIG.PRICE_UPDATE_INTERVAL}s Price Tracker...", end="")
        self.price_tracker_task = asyncio.create_task(self.price_tracker.start_tracking())
        console.print(" [green]✅ LEGENDARY[/green]")
        
        # Initialize PERFECT WebSocket system
        console.print("🌐 Initializing PERFECT WebSocket Failover System...", end="")
        self.ws_listener = PerfectWebSocketMonitor(CONFIG.WALLET_ADDRESS, CONFIG.API_KEY)
        console.print(" [green]✅ BULLETPROOF[/green]")
        
        # Start PERFECT WebSocket connections
        console.print("\n🚀 Starting PERFECT WebSocket Failover System...")
        ws_success = await self.ws_listener.connect()
        
        # Handle balance initialization
        if ws_success and self.ws_listener.is_connected():
            await asyncio.sleep(3)
            ws_balance = self.ws_listener.get_balance()
            if ws_balance > 0:
                self.initial_balance = ws_balance
                console.print(f"[green]💰 WebSocket Balance Confirmed: {ws_balance:.6f} SOL[/green]")
            else:
                rpc_balance = self.trader.get_sol_balance()
                self.ws_listener.current_balance = rpc_balance
                self.initial_balance = rpc_balance
                console.print(f"[yellow]💰 lib.rs Fallback Balance: {rpc_balance:.6f} SOL[/yellow]")
        else:
            console.print("[yellow]⚠️ WebSocket Failed - lib.rs RPC Mode Active[/yellow]")
            self.initial_balance = self.trader.get_sol_balance()
        
        # Final validation
        if self.initial_balance < CONFIG.MIN_SOL_BALANCE:
            console.print(f"[red]❌ INSUFFICIENT BALANCE: {self.initial_balance:.6f} SOL (need {CONFIG.MIN_SOL_BALANCE:.6f})[/red]")
            raise Exception("Insufficient balance for trading")
        
        # Display PERFECT ready state
        console.print(f"\n[green]🏆 ABSOLUTE PERFECTION ACHIEVED! 🏆[/green]")
        console.print(f"🎯 Perfect Targets: +{CONFIG.PROFIT_TARGET_PCT}% / -{CONFIG.STOP_LOSS_PCT}%")
        console.print(f"💰 Balance: {self.initial_balance:.6f} SOL")
        console.print(f"🌐 WebSocket: {self.ws_listener.get_connection_status()}")
        console.print(f"📊 Price Tracking: {CONFIG.PRICE_UPDATE_INTERVAL}s intervals")
        console.print(f"⚡ lib.rs Performance: {cached_time:.1f}μs (YOUR GENIUS!)")
        console.print(f"🔧 Perfect Compute: {CONFIG.COMPUTE_LIMIT} | Priority: {CONFIG.PRIORITY_FEE}")
        console.print(f"📈 Perfect Signal Threshold: {CONFIG.MIN_SIGNAL_STRENGTH}")
        console.print(f"💧 Perfect Liquidity: ${CONFIG.MIN_LIQUIDITY_USD:,.0f}")
        console.print(f"🌐 YOUR 0.01 SOL Threshold: {CONFIG.BALANCE_CHANGE_THRESHOLD} SOL")
        console.print(f"🔍 Fallback Verification: {'ENABLED' if CONFIG.ENABLE_FALLBACK_VERIFICATION else 'DISABLED'}")
        console.print("-" * 50 + "\n")
    
    async def find_opportunities(self) -> List[Dict]:
        """🔍 Find opportunities with PERFECT unified thresholds"""
        try:
            opportunities = await self.signal_finder.find_opportunities(limit=5)
            
            if not opportunities:
                console.print("[INFO] No opportunities found during discovery phase")
                return []
            
            console.print(f"🔍 Found {len(opportunities)} initial opportunities")
            
            # GPU analysis
            console.print(f"🎮 GPU analyzing {len(opportunities)} tokens...")
            gpu_signals = self.gpu_accelerator.scan_market(opportunities, CONFIG.EXCLUDED_TOKENS)
            
            # PERFECT filtering
            verified_signals = []
            for signal in gpu_signals:
                try:
                    symbol = signal.get('symbol', '')
                    
                    # Check blacklist and cooldowns
                    if symbol in self.blacklisted_tokens:
                        continue
                    
                    if symbol in self.token_cooldowns:
                        if time.time() - self.token_cooldowns[symbol] < 3600:  # 1 hour cooldown
                            continue
                        else:
                            del self.token_cooldowns[symbol]  # Cooldown expired
                    
                    # PERFECT threshold checks
                    signal_strength = signal.get('signal_strength', 0)
                    liquidity = signal.get('liquidity', 0)
                    volume_24h = signal.get('volume_24h', 0)
                    volume_5m = signal.get('volume_5m', 0)
                    
                    if (signal_strength >= CONFIG.MIN_SIGNAL_STRENGTH and 
                        liquidity >= CONFIG.MIN_LIQUIDITY_USD and 
                        volume_24h >= CONFIG.MIN_24H_VOLUME and
                        volume_5m >= CONFIG.MIN_VOLUME_5M):
                        
                        verified_signals.append(signal)
                        console.print(f"  ✅ {symbol}: Signal {signal_strength:.3f}, Liq ${liquidity:,.0f}, Vol5m ${volume_5m:,.0f}")
                    else:
                        if CONFIG.DETAILED_LOGGING:
                            console.print(f"  ❌ {symbol}: Filtered (Signal:{signal_strength:.3f}, Liq:${liquidity:,.0f}, Vol5m:${volume_5m:,.0f})")
                        
                except Exception as e:
                    console.print(f"[yellow]⚠️ Signal verification failed for {signal.get('symbol', 'unknown')}: {e}[/yellow]")
                    continue
            
            if verified_signals:
                console.print(f"[green]🌊 PERFECT FILTER: {len(verified_signals)} verified signals passed[/green]")
                for wave in verified_signals[:3]:
                    console.print(f"  🏆 {wave['symbol']}: {wave['signal_type']} (score: {wave['signal_strength']:.3f})")
            else:
                console.print("[yellow]🔍 PERFECT FILTER: No signals met unified thresholds[/yellow]")
            
            return verified_signals
            
        except Exception as e:
            console.print(f"[red]💥 Opportunity finding error: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
            return []
    
    async def execute_trade(self, signal: Dict) -> bool:
        """🚀 Execute trade with ABSOLUTE PERFECTION"""
        symbol = signal['symbol']
        token_mint = signal['token_mint']
        entry_price = signal['price']
        
        console.print(f"\n[bold]🎯 PERFECT QUANTUM TRADE: {symbol}[/bold] ({signal['signal_type']}) @ ${entry_price:.8f}")
        
        trade_start_time = time.time()
        execution_start = time.perf_counter()
        
        try:
            # Check balance with PERFECT logic
            current_balance = self.ws_listener.get_balance()
            if current_balance == 0:
                current_balance = self.trader.get_sol_balance()
            
            min_required = CONFIG.TRADE_AMOUNT_SOL + CONFIG.MIN_SOL_BALANCE
            if current_balance < min_required:
                console.print(f"[red]❌ Insufficient balance: {current_balance:.6f} SOL (need {min_required:.6f})[/red]")
                return False
            
            # Get pre-trade balance (YOUR 0.19μs access!)
            pre_balance = self.ws_listener.get_balance()
            if pre_balance == 0:
                pre_balance = self.trader.get_sol_balance()
                console.print(f"[yellow]🔄 lib.rs Balance Fallback: {pre_balance:.6f} SOL[/yellow]")
            
            # Execute buy with YOUR 99.7% caching genius
            buy_start = time.perf_counter()
            buy_sig = self.trader.execute_jupiter_swap(
                "So11111111111111111111111111111111111111112",  # SOL
                token_mint,
                CONFIG.TRADE_AMOUNT_SOL,
                CONFIG.SLIPPAGE_PERCENT,
                1  # Priority multiplier
            )
            
            buy_exec_time = (time.perf_counter() - buy_start) * 1000
            self.execution_times.append(buy_exec_time)
            console.print(f"🚀 lib.rs Buy executed: {buy_exec_time:.0f}ms")
            
            # YOUR GENIUS CONFIRMATION SYSTEM!
            confirmation_start = time.perf_counter()
            confirmed, confirm_time, source = await self.ws_listener.wait_for_balance_change(CONFIG.WS_CONFIRMATION_TIMEOUT)
            
            if confirmed:
                self.confirmation_times.append(confirm_time)
                console.print(f"[green]✅ YOUR 0.01 SOL THRESHOLD TRIGGERED by {source} in {confirm_time:.0f}ms![/green]")
                post_balance = self.ws_listener.get_balance()
                sol_spent = round(pre_balance - post_balance, 6)
            else:
                console.print("[yellow]⏰ WebSocket timeout - using lib.rs verification[/yellow]")
                await asyncio.sleep(2)
                post_balance = self.trader.get_sol_balance()
                sol_spent = round(pre_balance - post_balance, 6)
                
                if sol_spent > 0.001:
                    console.print(f"[green]✅ Trade verified via lib.rs - {sol_spent:.6f} SOL spent[/green]")
                    self.ws_listener.current_balance = post_balance
                else:
                    console.print("[red]❌ Trade verification failed - no SOL spent[/red]")
                    self.consecutive_failures += 1
                    self.failed_tokens[symbol] += 1
                    return False
            
            # Get token balance
            await asyncio.sleep(1)
            token_balance = self.trader.get_token_balance(token_mint)
            console.print(f"💎 Received: {token_balance:.6f} {symbol} (will sell {token_balance * CONFIG.SELL_PERCENTAGE:.6f})")
            
            if token_balance <= 0:
                console.print("[red]❌ ERROR: No tokens received![/red]")
                self.consecutive_failures += 1
                self.failed_tokens[symbol] += 1
                return False
            
            # Reset failure counter on success
            self.consecutive_failures = 0
            
            # Create PERFECT position
            position = {
                "symbol": symbol,
                "mint": token_mint,
                "entry_price": entry_price,
                "current_price": entry_price,
                "amount_sol": sol_spent,
                "amount_tokens": token_balance,
                "cached_sell_amount": token_balance * CONFIG.SELL_PERCENTAGE,  # YOUR 99.7% GENIUS!
                "entry_time": trade_start_time,
                "entry_signature": buy_sig,
                "unrealized_pnl_pct": 0,
                "unrealized_pnl_sol": 0,
                "hold_time": 0,
                "signal_type": signal['signal_type'],
                "signal_strength": signal['signal_strength'],
                "feature_vector": signal.get('feature_vector', []),
                "last_logged_pnl": 0,
                "execution_time_ms": buy_exec_time,
                "confirmation_time_ms": confirm_time if confirmed else 0,
                "confirming_websocket": source if confirmed else "lib.rs"
            }
            
            self.positions[symbol] = position
            self.trades_executed += 1
            
            # Start tracking
            self.price_tracker.add_token(symbol, token_mint, entry_price)
            await self.signal_finder.track_position(symbol, token_mint, entry_price)
            
            # Update dashboard
            await self.update_dashboard()
            
            # Prime for next trade (YOUR lib.rs cache magic!)
            self.trader.force_update_blockhash()
            
            total_time = (time.perf_counter() - execution_start) * 1000
            console.print(f"[green]✅ PERFECT execution time: {total_time:.0f}ms[/green]")
            
            return True
            
        except Exception as e:
            console.print(f"[red]💥 Trade failed: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
            
            self.consecutive_failures += 1
            self.failed_tokens[symbol] += 1
            
            # Add to cooldown
            self.token_cooldowns[symbol] = time.time()
            
            # Emergency protection
            if self.consecutive_failures >= self.max_consecutive_failures:
                console.print(f"[red]🚨 EMERGENCY: {self.consecutive_failures} consecutive failures - safety shutdown[/red]")
                self.emergency_shutdown = True
                self.shutdown_event.set()
            
            return False
    
    async def check_exit_conditions(self):
        """🎯 Check exit conditions with YOUR PERFECT 0.01 SOL system"""
        if not self.positions:
            return
        
        positions_to_close = []
        
        for symbol, position in self.positions.items():
            try:
                current_time = time.time()
                entry_time = position.get('entry_time', current_time)
                hold_time = current_time - entry_time
                
                # MANDATORY timeout check
                if hold_time >= CONFIG.MAX_HOLD_TIME:
                    console.print(f"[red]🚨 MANDATORY TIMEOUT: {symbol} held for {hold_time:.0f}s - FORCE CLOSING[/red]")
                    positions_to_close.append((symbol, position, "MANDATORY_TIMEOUT"))
                    continue
                
                # Get current price from multiple sources
                stats = self.signal_finder.get_position_stats(symbol)
                current_price_rt = self.price_tracker.get_current_price(symbol)
                
                entry_price = position.get('entry_   #!/usr/bin/env python3
"""
🏆 QUANTUM BEAST TRADING SYSTEM - PERFECTED MAIN.PY 🏆
====================================================
💎 UNIFIED .ENV CONFIGURATION + BULLETPROOF WEBSOCKETS 💎
🚀 FIXED P&L + ENHANCED ERROR HANDLING + REAL-TIME TRACKING 🚀
⚡ lib.rs INTEGRATION + GPU ACCELERATION + SMART BLACKLIST ⚡
====================================================

PERFECTED FEATURES:
✅ UNIFIED .ENV configuration (NO MORE THRESHOLD MISMATCHES!)
✅ ENHANCED WebSocket system (dual racing + auto-reconnect)
✅ PERFECT P&L calculation (actual SOL amounts vs price changes)
✅ BULLETPROOF error handling (retries + fallbacks + force close)
✅ REAL-TIME price tracking (0.5s updates + alerts)
✅ lib.rs microsecond performance (2μs blockhash cache)
✅ GPU early wave detection (catches waves before they start)
✅ SMART blacklist system (1h cooldown + permanent ban)
✅ COMPREHENSIVE dashboard (live metrics + unified config display)
✅ GRACEFUL shutdown (emergency position closure)

THIS IS YOUR LEGENDARY TRADING INFRASTRUCTURE!
"""

import asyncio
import json
import time
import os
import sys
import logging
import aiohttp
import websockets
import threading
import traceback
import signal
import requests
import numpy as np
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from collections import deque, defaultdict
from dataclasses import dataclass
import statistics

# Rich for legendary terminal output
try:
    from rich.console import Console
    from rich.logging import RichHandler
    console = Console()
except ImportError:
    class Console:
        def print(self, *args, **kwargs): print(*args)
    console = Console()

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Import YOUR legendary components
from solana_rust_bot import SolanaTrader
from quantum_signal_finder_complete import QuantumSignalFinder
from gpu_accelerator_improved import GPUAcceleratorULTIMATE

# Load environment FIRST - this is our single source of truth
from dotenv import load_dotenv
load_dotenv()

# Windows compatibility
if sys.platform == 'win32':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())


class UnifiedConfig:
    """🏆 UNIFIED CONFIGURATION - SINGLE SOURCE OF TRUTH FROM .ENV"""
    
    def __init__(self):
        """Load ALL configuration from .env file with intelligent defaults"""
        
        # ============= NETWORK & API CONFIGURATION =============
        self.API_KEY = os.getenv("HELIUS_API_KEY", "86ab5634-df30-4a5b-bcfb-3f53d7095ca2")
        self.KEYPAIR_PATH = os.getenv("SOLANA_KEYPAIR", r"C:\solana_rust_bot\keypair.bin")
        self.WALLET_ADDRESS = os.getenv("SOLANA_PUBLIC_KEY", "77ssrQ7LmPso1d1wYp4jAQdz4NqKSbKK8t6mFLcx6Xwr")
        
        # RPC/WebSocket endpoints
        self.PRIMARY_RPC_URL = os.getenv("PRIMARY_RPC_URL", "https://winny-rychu7-fast-mainnet.helius-rpc.com")
        self.PRIMARY_WS_URL = os.getenv("PRIMARY_WS_URL", "wss://winny-rychu7-fast-mainnet.helius-rpc.com/")
        self.SECONDARY_RPC_URL = os.getenv("SECONDARY_RPC_URL", f"https://mainnet.helius-rpc.com/?api-key={self.API_KEY}")
        self.SECONDARY_WS_URL = os.getenv("SECONDARY_WS_URL", f"wss://mainnet.helius-rpc.com/?api-key={self.API_KEY}")
        
        # ============= TRADING PARAMETERS =============
        self.TRADE_AMOUNT_SOL = float(os.getenv("TRADE_AMOUNT", "0.08"))
        self.COMPUTE_LIMIT = int(os.getenv("COMPUTE_LIMIT", "120000"))
        self.PRIORITY_FEE = int(os.getenv("PRIORITY_FEE", "60000"))
        self.SLIPPAGE_PERCENT = float(os.getenv("SLIPPAGE", "3.0"))
        self.SELL_PERCENTAGE = float(os.getenv("SELL_PERCENTAGE", "0.997"))
        
        # Position management
        self.MAX_CONCURRENT_POSITIONS = int(os.getenv("MAX_POSITIONS", "1"))
        self.PROFIT_TARGET_PCT = float(os.getenv("PROFIT_TARGET_PCT", "2.0"))
        self.STOP_LOSS_PCT = float(os.getenv("STOP_LOSS_PCT", "2.0"))
        self.MAX_HOLD_TIME = int(os.getenv("MAX_HOLD_TIME_SECONDS", "240"))
        
        # ============= UNIFIED SIGNAL & FILTERING THRESHOLDS =============
        # These are now the SINGLE source of truth for both discovery AND execution
        self.MIN_SIGNAL_STRENGTH = float(os.getenv("MIN_SIGNAL_STRENGTH", "0.30"))
        self.MIN_LIQUIDITY_USD = float(os.getenv("MIN_LIQUIDITY_USD", "5000"))
        self.MIN_VOLUME_5M = float(os.getenv("MIN_VOLUME_5M", "500"))
        self.MIN_24H_VOLUME = float(os.getenv("MIN_24H_VOLUME", "1000"))
        self.MIN_SAFETY_SCORE = int(os.getenv("MIN_SAFETY_SCORE", "45"))
        self.MIN_EARLY_WAVE_SCORE = float(os.getenv("MIN_EARLY_WAVE_SCORE", "0.30"))
        
        # Price change thresholds
        self.MIN_PRICE_CHANGE_5M = float(os.getenv("MIN_PRICE_CHANGE_5M", "1.0"))
        self.MAX_PRICE_CHANGE_5M = float(os.getenv("MAX_PRICE_CHANGE_5M", "9.0"))
        
        # ============= INTERVALS & TIMING =============
        self.CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL", "20"))
        self.POSITION_CHECK_INTERVAL = float(os.getenv("POSITION_CHECK_INTERVAL", "0.5"))
        self.DASHBOARD_UPDATE_INTERVAL = float(os.getenv("DASHBOARD_UPDATE_INTERVAL", "1.0"))
        self.PRICE_UPDATE_INTERVAL = float(os.getenv("PRICE_UPDATE_INTERVAL", "0.5"))
        
        # ============= WEBSOCKET CONFIGURATION =============
        self.WS_CONFIRMATION_TIMEOUT = float(os.getenv("WS_CONFIRMATION_TIMEOUT", "5.0"))
        self.WS_RETRY_ATTEMPTS = int(os.getenv("WS_RETRY_ATTEMPTS", "3"))
        self.CONNECTION_TIMEOUT = int(os.getenv("CONNECTION_TIMEOUT", "10"))
        self.BALANCE_CHANGE_THRESHOLD = float(os.getenv("BALANCE_CHANGE_THRESHOLD", "0.005"))
        
        # ============= BLACKLIST & EXCLUSIONS =============
        # Parse blacklisted tokens from .env
        blacklist_str = os.getenv("BLACKLISTED_TOKENS", "SOL,USDC,USDT,WSOL,RAY,JUP,BONK,WIF,BOME")
        self.EXCLUDED_TOKENS = [token.strip().upper() for token in blacklist_str.split(",") if token.strip()]
        
        # Allowed DEXes
        allowed_dexes_str = os.getenv("ALLOWED_DEXES", "raydium,orca,jupiter,openbook,meteora")
        self.ALLOWED_DEXES = [dex.strip() for dex in allowed_dexes_str.split(",") if dex.strip()]
        
        # ============= PRICE TRACKING CONFIGURATION =============
        self.PRICE_ALERT_THRESHOLD = float(os.getenv("PRICE_ALERT_THRESHOLD", "1.0"))
        self.DEXSCREENER_TOKENS_URL = "https://api.dexscreener.com/latest/dex/tokens"
        
        # ============= PERFORMANCE & GPU SETTINGS =============
        self.GPU_BATCH_SIZE = int(os.getenv("BATCH_SIZE", "512"))
        self.GPU_MEMORY_FRACTION = float(os.getenv("GPU_MEMORY_FRACTION", "0.85"))
        self.THREADS = int(os.getenv("THREADS", "64"))
        
        # ============= RISK MANAGEMENT =============
        self.MIN_SOL_BALANCE = float(os.getenv("MIN_SOL_BALANCE", "0.005"))
        self.MAX_WALLET_USAGE_PERCENT = float(os.getenv("MAX_WALLET_USAGE_PERCENT", "80.0"))
        
        # ============= LOGGING =============
        self.LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
        self.DETAILED_LOGGING = os.getenv("DETAILED_LOGGING", "false").lower() == "true"
        
        console.print("[green]✅ UNIFIED CONFIG LOADED - ALL SETTINGS FROM .ENV[/green]")
        self.print_key_settings()
    
    def print_key_settings(self):
        """Print key configuration settings for verification"""
        console.print(f"[cyan]📊 UNIFIED QUANTUM SETTINGS:[/cyan]")
        console.print(f"   💰 Trade Amount: {self.TRADE_AMOUNT_SOL} SOL")
        console.print(f"   🎯 Targets: +{self.PROFIT_TARGET_PCT}% / -{self.STOP_LOSS_PCT}%")
        console.print(f"   📈 Min Signal: {self.MIN_SIGNAL_STRENGTH}")
        console.print(f"   💧 Min Liquidity: ${self.MIN_LIQUIDITY_USD:,.0f}")
        console.print(f"   📊 Min Volume 5m: ${self.MIN_VOLUME_5M:,.0f}")
        console.print(f"   ⏱️ Check Interval: {self.CHECK_INTERVAL}s")
        console.print(f"   🚫 Blacklisted: {len(self.EXCLUDED_TOKENS)} tokens")
        console.print(f"   🌐 Balance Threshold: {self.BALANCE_CHANGE_THRESHOLD} SOL")


# Initialize global config
CONFIG = UnifiedConfig()


class QuantumWebSocketMonitor:
    """🔥 ENHANCED QUANTUM WebSocket system with bulletproof stability"""
    
    def __init__(self, wallet_address: str, api_key: str):
        self.wallet_address = wallet_address
        self.api_key = api_key
        
        # WebSocket URLs from config
        self.primary_url = CONFIG.PRIMARY_WS_URL
        self.secondary_url = CONFIG.SECONDARY_WS_URL
        
        # Connection objects
        self.primary_ws = None
        self.secondary_ws = None
        self.primary_healthy = False
        self.secondary_healthy = False
        
        # Enhanced connection tracking
        self.primary_last_seen = 0
        self.secondary_last_seen = 0
        self.reconnect_delays = {"primary": 1, "secondary": 1}
        
        # Balance tracking with enhanced precision
        self.balance_updates = deque(maxlen=100)
        self.current_balance = 0.0
        self.last_balance = None
        self.balance_precision = 6
        
        # Racing logic for confirmations
        self.balance_event = asyncio.Event()
        self.confirmation_responder = None
        
        # Stats
        self.primary_wins = 0
        self.secondary_wins = 0
        self.total_updates = 0
        self.connection_attempts = {"primary": 0, "secondary": 0}
        
        # Headers with authentication
        self.headers = {
            "User-Agent": "solana-cli 1.18.23 (src:aeb3a2e1; feat:4215500110, client:SolanaLabs)",
            "Authorization": f"Bearer {self.api_key}"
        }
    
    async def connect(self):
        """Enhanced connection with bulletproof error handling"""
        console.print("[WS] 🚀 Initializing ENHANCED QUANTUM WebSocket listeners...")
        
        # Start both connections concurrently
        primary_task = asyncio.create_task(self._maintain_primary_connection())
        secondary_task = asyncio.create_task(self._maintain_secondary_connection())
        
        # Wait for at least one connection
        try:
            await asyncio.wait_for(self._wait_for_any_connection(), timeout=CONFIG.CONNECTION_TIMEOUT)
            console.print("[green]✅ QUANTUM WebSockets confirmed ready![/green]")
            return True
        except asyncio.TimeoutError:
            console.print("[yellow]⏰ WebSocket timeout - lib.rs RPC fallback ready[/yellow]")
            return False
    
    async def _wait_for_any_connection(self):
        """Wait for at least one healthy connection"""
        while not (self.primary_healthy or self.secondary_healthy):
            await asyncio.sleep(0.1)
    
    async def _maintain_primary_connection(self):
        """Maintain primary connection with exponential backoff"""
        while True:
            try:
                self.connection_attempts["primary"] += 1
                console.print(f"[PRIMARY] 🔌 Connecting... (attempt {self.connection_attempts['primary']})")
                
                # Use different headers based on endpoint
                headers = self.headers if "helius" not in self.primary_url else {}
                
                self.primary_ws = await websockets.connect(
                    self.primary_url,
                    extra_headers=headers,
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=5
                )
                
                await self._subscribe_to_account(self.primary_ws, "PRIMARY")
                self.primary_healthy = True
                self.primary_last_seen = time.time()
                self.reconnect_delays["primary"] = 1  # Reset delay on success
                console.print("[green][PRIMARY] ✅ WebSocket Connected and Subscribed[/green]")
                
                # Listen for messages
                await self._listen_primary()
                
            except Exception as e:
                console.print(f"[PRIMARY] ❌ Connection failed: {e}")
                self.primary_healthy = False
                
                # Exponential backoff with jitter
                delay = min(self.reconnect_delays["primary"] * 2, 30)
                self.reconnect_delays["primary"] = delay
                jitter = delay * 0.1 * (0.5 - time.time() % 1)
                
                await asyncio.sleep(delay + jitter)
    
    async def _maintain_secondary_connection(self):
        """Maintain secondary connection with exponential backoff"""
        # Small delay to stagger connections
        await asyncio.sleep(1)
        
        while True:
            try:
                self.connection_attempts["secondary"] += 1
                console.print(f"[SECONDARY] 🔌 Connecting... (attempt {self.connection_attempts['secondary']})")
                
                self.secondary_ws = await websockets.connect(
                    self.secondary_url,
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=5
                )
                
                await self._subscribe_to_account(self.secondary_ws, "SECONDARY")
                self.secondary_healthy = True
                self.secondary_last_seen = time.time()
                self.reconnect_delays["secondary"] = 1  # Reset delay on success
                console.print("[green][SECONDARY] ✅ WebSocket Connected and Subscribed[/green]")
                
                # Listen for messages
                await self._listen_secondary()
                
            except Exception as e:
                console.print(f"[SECONDARY] ❌ Connection failed: {e}")
                self.secondary_healthy = False
                
                # Exponential backoff with jitter
                delay = min(self.reconnect_delays["secondary"] * 2, 30)
                self.reconnect_delays["secondary"] = delay
                jitter = delay * 0.1 * (0.5 - time.time() % 1)
                
                await asyncio.sleep(delay + jitter)
    
    async def _subscribe_to_account(self, ws, label: str):
        """Subscribe to account updates with enhanced error handling"""
        subscribe_msg = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "accountSubscribe",
            "params": [
                self.wallet_address,
                {
                    "encoding": "base64",
                    "commitment": "processed"
                }
            ]
        }
        
        await asyncio.wait_for(ws.send(json.dumps(subscribe_msg)), timeout=10)
        response = await asyncio.wait_for(ws.recv(), timeout=10)
        result = json.loads(response)
        
        if "result" in result:
            console.print(f"[{label}] 🎯 Account Subscription Active")
        else:
            console.print(f"[{label}] ⚠️ Subscription Error: {result}")
            raise Exception(f"Subscription failed: {result}")
    
    async def _listen_primary(self):
        """Listen for primary WebSocket updates"""
        try:
            async for message in self.primary_ws:
                self.primary_last_seen = time.time()
                await self._process_balance_update(message, "PRIMARY")
        except websockets.exceptions.ConnectionClosed:
            console.print("[PRIMARY] 🔌 Connection closed - reconnecting...")
        except Exception as e:
            console.print(f"[PRIMARY] 👂 Listen error: {e}")
        finally:
            self.primary_healthy = False
    
    async def _listen_secondary(self):
        """Listen for secondary WebSocket updates"""
        try:
            async for message in self.secondary_ws:
                self.secondary_last_seen = time.time()
                await self._process_balance_update(message, "SECONDARY")
        except websockets.exceptions.ConnectionClosed:
            console.print("[SECONDARY] 🔌 Connection closed - reconnecting...")
        except Exception as e:
            console.print(f"[SECONDARY] 👂 Listen error: {e}")
        finally:
            self.secondary_healthy = False
    
    async def _process_balance_update(self, message: str, source: str):
        """🔥 ENHANCED BALANCE DETECTION with configurable threshold"""
        try:
            data = json.loads(message)
            
            if "method" in data and data["method"] == "accountNotification":
                result = data["params"]["result"]
                value = result.get("value", {})
                
                if "lamports" in value:
                    new_balance = round(value["lamports"] / 1_000_000_000, self.balance_precision)
                    old_balance = self.current_balance
                    
                    self.current_balance = new_balance
                    self.total_updates += 1
                    
                    if old_balance > 0:
                        balance_change = round(new_balance - old_balance, self.balance_precision)
                        
                        # Use configurable threshold from CONFIG
                        if abs(balance_change) >= CONFIG.BALANCE_CHANGE_THRESHOLD:
                            change_style = "green" if balance_change > 0 else "red"
                            console.print(f"[{source}] [{change_style}]💰 Balance: {new_balance:.6f} ({balance_change:+.6f})[/{change_style}]")
                            
                            # RACING LOGIC - First to detect wins!
                            if not self.balance_event.is_set():
                                self.confirmation_responder = source
                                self.balance_event.set()
                                
                                if source == "PRIMARY":
                                    self.primary_wins += 1
                                else:
                                    self.secondary_wins += 1
                    
                    # Store update with timestamp
                    update = {
                        "source": source,
                        "balance": new_balance,
                        "change": new_balance - old_balance if old_balance > 0 else 0,
                        "timestamp": time.time()
                    }
                    self.balance_updates.append(update)
                    
        except Exception as e:
            if CONFIG.DETAILED_LOGGING:
                console.print(f"[{source}] 🔍 Parse error: {e}")
    
    async def wait_for_balance_change(self, timeout=None):
        """🏆 Enhanced racing confirmation system"""
        if timeout is None:
            timeout = CONFIG.WS_CONFIRMATION_TIMEOUT
            
        self.balance_event.clear()
        self.confirmation_responder = None
        
        start_time = time.perf_counter()
        
        try:
            await asyncio.wait_for(self.balance_event.wait(), timeout)
            elapsed_time = (time.perf_counter() - start_time) * 1000
            return True, elapsed_time, self.confirmation_responder
        except asyncio.TimeoutError:
            elapsed_time = timeout * 1000
            return False, elapsed_time, None
    
    def get_balance(self) -> float:
        """Get current balance (MICROSECOND ACCESS)"""
        return self.current_balance
    
    def is_connected(self) -> bool:
        """Check if at least one WebSocket is connected"""
        return self.primary_healthy or self.secondary_healthy
    
    def get_connection_status(self) -> str:
        """Get detailed connection status"""
        if self.primary_healthy and self.secondary_healthy:
            return "🔥 DUAL_POWER"
        elif self.primary_healthy:
            return "⚡ PRIMARY_ACTIVE"  
        elif self.secondary_healthy:
            return "🔄 SECONDARY_ACTIVE"
        else:
            return "❌ DISCONNECTED"
    
    def get_connection_stats(self) -> Dict:
        """Get detailed connection statistics"""
        return {
            "primary_healthy": self.primary_healthy,
            "secondary_healthy": self.secondary_healthy,
            "primary_wins": self.primary_wins,
            "secondary_wins": self.secondary_wins,
            "total_updates": self.total_updates,
            "primary_attempts": self.connection_attempts["primary"],
            "secondary_attempts": self.connection_attempts["secondary"],
            "primary_last_seen": time.time() - self.primary_last_seen if self.primary_last_seen > 0 else -1,
            "secondary_last_seen": time.time() - self.secondary_last_seen if self.secondary_last_seen > 0 else -1,
            "status": self.get_connection_status(),
            "balance_threshold": CONFIG.BALANCE_CHANGE_THRESHOLD
        }
    
    async def close(self):
        """Gracefully close all connections"""
        console.print("[WS] 🛑 Closing WebSocket connections...")
        try:
            if self.primary_ws and not self.primary_ws.closed:
                await self.primary_ws.close()
            if self.secondary_ws and not self.secondary_ws.closed:
                await self.secondary_ws.close()
        except Exception as e:
            console.print(f"[WS] ⚠️ Close error: {e}")


class QuantumRealTimePriceTracker:
    """🎯 ENHANCED real-time price tracking with bulletproof reliability"""
    
    def __init__(self):
        self.tracking_tokens = {}
        self.current_prices = {}
        self.last_prices = {}
        self.running = False
        self.price_alerts = deque(maxlen=50)
        self.price_history = defaultdict(lambda: deque(maxlen=100))
        self.fetch_errors = defaultdict(int)
        self.last_successful_fetch = defaultdict(float)
        
    def add_token(self, symbol, mint_address, entry_price):
        """Add token to tracking system"""
        self.tracking_tokens[symbol] = mint_address
        self.current_prices[symbol] = entry_price
        self.last_prices[symbol] = entry_price
        self.fetch_errors[symbol] = 0
        self.last_successful_fetch[symbol] = time.time()
        console.print(f"[TRACKER] 📊 Started {CONFIG.PRICE_UPDATE_INTERVAL}s tracking {symbol} @ ${entry_price:.8f}")
        
    def remove_token(self, symbol):
        """Remove token from tracking"""
        if symbol in self.tracking_tokens:
            del self.tracking_tokens[symbol]
            del self.current_prices[symbol]
            del self.last_prices[symbol]
            if symbol in self.fetch_errors:
                del self.fetch_errors[symbol]
            if symbol in self.last_successful_fetch:
                del self.last_successful_fetch[symbol]
            console.print(f"[TRACKER] 🛑 Stopped tracking {symbol}")
    
    def get_current_price(self, symbol):
        """Get current price with fallback"""
        return self.current_prices.get(symbol, 0)
    
    async def fetch_price(self, session, mint_address):
        """Enhanced price fetching with better error handling"""
        try:
            url = f"{CONFIG.DEXSCREENER_TOKENS_URL}/{mint_address}"
            async with session.get(url, timeout=3) as response:
                if response.status != 200:
                    return None
                
                data = await response.json()
                if "pairs" in data and data["pairs"]:
                    # Get best pair by liquidity
                    best_pair = max(data["pairs"], 
                                  key=lambda p: float(p.get("liquidity", {}).get("usd", 0)))
                    price = best_pair.get("priceUsd")
                    return float(price) if price else None
                return None
        except Exception:
            return None
    
    async def update_prices(self):
        """Update all tracked prices with enhanced error handling"""
        if not self.tracking_tokens:
            return
        
        try:
            connector = aiohttp.TCPConnector(ssl=False, limit=5, ttl_dns_cache=300)
            timeout = aiohttp.ClientTimeout(total=8)
            
            async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:
                for symbol, mint_address in self.tracking_tokens.items():
                    try:
                        new_price = await self.fetch_price(session, mint_address)
                        
                        if new_price and new_price > 0:
                            old_price = self.last_prices.get(symbol, new_price)
                            self.current_prices[symbol] = new_price
                            self.fetch_errors[symbol] = 0  # Reset error count
                            self.last_successful_fetch[symbol] = time.time()
                            
                            # Store price history
                            self.price_history[symbol].append({
                                "price": new_price,
                                "timestamp": time.time()
                            })
                            
                            # Check for significant price movements
                            if old_price > 0:
                                price_change_pct = ((new_price - old_price) / old_price) * 100
                                
                                if abs(price_change_pct) >= CONFIG.PRICE_ALERT_THRESHOLD:
                                    direction = "📈" if price_change_pct > 0 else "📉"
                                    style = "green" if price_change_pct > 0 else "red"
                                    
                                    # Major alert for >3% moves
                                    if abs(price_change_pct) >= 3.0:
                                        alert_type = "🔥 MAJOR" if price_change_pct > 0 else "💥 MAJOR"
                                        console.print(f"[{style}]{alert_type}: {symbol} {direction} {abs(price_change_pct):.2f}% | ${new_price:.8f}[/{style}]")
                                    else:
                                        console.print(f"[{style}]💰 {symbol}: {direction} {abs(price_change_pct):.2f}% | ${new_price:.8f}[/{style}]")
                                    
                                    self.price_alerts.append({
                                        "symbol": symbol,
                                        "price": new_price,
                                        "change_pct": price_change_pct,
                                        "timestamp": time.time()
                                    })
                            
                            self.last_prices[symbol] = new_price
                        else:
                            # Track failed fetches
                            self.fetch_errors[symbol] += 1
                            if self.fetch_errors[symbol] > 5:  # Too many errors
                                console.print(f"[yellow]⚠️ {symbol}: Too many price fetch errors, using last known price[/yellow]")
                                
                    except Exception as e:
                        self.fetch_errors[symbol] += 1
                        if CONFIG.DETAILED_LOGGING:
                            console.print(f"[yellow]⚠️ Price fetch error for {symbol}: {e}[/yellow]")
                        continue
                        
        except Exception as e:
            if CONFIG.DETAILED_LOGGING:
                console.print(f"[yellow]⚠️ Price update session error: {e}[/yellow]")
    
    async def start_tracking(self):
        """Start the price tracking loop"""
        self.running = True
        console.print(f"[TRACKER] 🚀 {CONFIG.PRICE_UPDATE_INTERVAL}s REAL-TIME TRACKING STARTED!")
        
        while self.running:
            try:
                if self.tracking_tokens:
                    await self.update_prices()
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)
            except Exception as e:
                if CONFIG.DETAILED_LOGGING:
                    console.print(f"[yellow]⚠️ Tracking loop error: {e}[/yellow]")
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)
    
    def stop_tracking(self):
        """Stop the price tracking"""
        self.running = False
        console.print("[TRACKER] 🛑 TRACKING STOPPED")


class QuantumBeastUnified:
    """🏆 QUANTUM BEAST WITH PERFECTED UNIFIED CONFIGURATION 🏆"""
    
    def __init__(self):
        self.running = False
        self.shutdown_event = asyncio.Event()
        
        # Components
        self.trader = None
        self.signal_finder = None
        self.gpu_accelerator = None
        self.ws_listener = None
        self.price_tracker = QuantumRealTimePriceTracker()
        
        # Session tracking
        self.initial_balance = 0
        self.session_start_balance = 0
        self.session_start_time = time.time()
        self.positions = {}
        self.completed_trades = []
        self.recent_trades = []
        
        # Stats
        self.trades_executed = 0
        self.trades_won = 0
        self.trades_lost = 0
        self.best_trade = 0
        self.worst_trade = 0
        self.dashboard_update_count = 0
        
        # Performance tracking
        self.execution_times = deque(maxlen=100)
        self.confirmation_times = deque(maxlen=100)
        self.blockhash_times = deque(maxlen=100)
        
        # Enhanced error tracking
        self.failed_tokens = defaultdict(int)
        self.blacklisted_tokens = set()
        
        # Emergency protection
        self.emergency_shutdown = False
        self.max_consecutive_failures = 3
        self.consecutive_failures = 0
    
    async def initialize(self):
        """🚀 Initialize QUANTUM BEAST with perfected unified configuration"""
        
        # Display unified header
        console.print("\n" + "🔥" * 80)
        console.print("🏆 QUANTUM BEAST - PERFECTED UNIFIED CONFIGURATION 🏆".center(80))
        console.print("💎 BULLETPROOF WEBSOCKETS + FIXED P&L + REAL-TIME 💎".center(80))
        console.print("🚀 SINGLE SOURCE OF TRUTH - NO MORE MISMATCHES! 🚀".center(80))
        console.print("🔥" * 80)
        
        console.print("\n[bold]🔥 INITIALIZING PERFECTED QUANTUM BEAST 🔥[/bold]")
        console.print("-" * 50)
        
        # Initialize Rust trader with unified config
        console.print("⚡ Initializing lib.rs Rust Trader (PERFECTED)...", end="")
        self.trader = SolanaTrader(
            rpc_url=CONFIG.PRIMARY_RPC_URL,
            ws_url=CONFIG.PRIMARY_WS_URL,
            keypair_path=CONFIG.KEYPAIR_PATH,
            compute_limit=CONFIG.COMPUTE_LIMIT,
            api_key=CONFIG.API_KEY
        )
        console.print(" [green]✅ LOADED[/green]")
        
        # Test lib.rs performance
        console.print("🔬 Testing lib.rs performance...", end="")
        start_time = time.perf_counter()
        address = self.trader.get_address()
        blockhash_time = (time.perf_counter() - start_time) * 1000000
        self.blockhash_times.append(blockhash_time)
        console.print(f" [green]✅ {blockhash_time:.1f}μs[/green]")
        
        # Get initial balance
        console.print("💰 Getting initial balance...", end="")
        initial_bal = self.trader.get_sol_balance()
        self.initial_balance = initial_bal
        self.session_start_balance = initial_bal
        console.print(f" [green]✅ {initial_bal:.6f} SOL[/green]")
        
        # Prime blockhash cache
        console.print("🔄 Priming lib.rs blockhash cache...", end="")
        start_time = time.perf_counter()
        self.trader.force_update_blockhash()
        cache_time = (time.perf_counter() - start_time) * 1000
        console.print(f" [green]✅ {cache_time:.1f}ms[/green]")
        
        # Test cached blockhash retrieval
        console.print("⚡ Testing cached blockhash speed...", end="")
        start_time = time.perf_counter()
        cached_hash = self.trader.get_cached_blockhash()
        cached_time = (time.perf_counter() - start_time) * 1000000
        console.print(f" [green]✅ {cached_time:.1f}μs[/green]")
        
        # Initialize signal finder with unified config
        console.print("🧠 Initializing Signal Finder (UNIFIED THRESHOLDS)...", end="")
        self.signal_finder = QuantumSignalFinder()
        await self.signal_finder.initialize()
        console.print(" [green]✅ LOADED[/green]")
        
        # Initialize GPU accelerator
        console.print("🎮 Initializing GPU Accelerator...", end="")
        self.gpu_accelerator = GPUAcceleratorULTIMATE()
        console.print(" [green]✅ LOADED[/green]")
        
        # Start price tracker
        console.print(f"📊 Starting {CONFIG.PRICE_UPDATE_INTERVAL}s Price Tracker...", end="")
        self.price_tracker_task = asyncio.create_task(self.price_tracker.start_tracking())
        console.print(" [green]✅ STARTED[/green]")
        
        # Initialize enhanced WebSocket system
        console.print("🌐 Initializing ENHANCED WebSocket System...", end="")
        self.ws_listener = QuantumWebSocketMonitor(CONFIG.WALLET_ADDRESS, CONFIG.API_KEY)
        console.print(" [green]✅ INITIALIZED[/green]")
        
        # Start WebSocket connections
        console.print("\n🚀 Starting ENHANCED WebSocket Connections...")
        ws_success = await self.ws_listener.connect()
        
        # Handle balance initialization
        if ws_success and self.ws_listener.is_connected():
            await asyncio.sleep(3)
            ws_balance = self.ws_listener.get_balance()
            if ws_balance > 0:
                self.initial_balance = ws_balance
                console.print(f"[green]💰 WebSocket Balance Confirmed: {ws_balance:.6f} SOL[/green]")
            else:
                rpc_balance = self.trader.get_sol_balance()
                self.ws_listener.current_balance = rpc_balance
                self.initial_balance = rpc_balance
                console.print(f"[yellow]💰 lib.rs Fallback Balance: {rpc_balance:.6f} SOL[/yellow]")
        else:
            console.print("[yellow]⚠️ WebSocket Failed - lib.rs RPC Mode Active[/yellow]")
            self.initial_balance = self.trader.get_sol_balance()
        
        # Final validation
        if self.initial_balance < CONFIG.MIN_SOL_BALANCE:
            console.print(f"[red]❌ INSUFFICIENT BALANCE: {self.initial_balance:.6f} SOL (need {CONFIG.MIN_SOL_BALANCE:.6f})[/red]")
            raise Exception("Insufficient balance for trading")
        
        # Display ready state
        console.print(f"\n[green]🏆 PERFECTED QUANTUM BEAST READY! 🏆[/green]")
        console.print(f"🎯 Unified Targets: +{CONFIG.PROFIT_TARGET_PCT}% / -{CONFIG.STOP_LOSS_PCT}%")
        console.print(f"💰 Balance: {self.initial_balance:.6f} SOL")
        console.print(f"🌐 WebSocket: {self.ws_listener.get_connection_status()}")
        console.print(f"📊 Price Tracking: {CONFIG.PRICE_UPDATE_INTERVAL}s intervals")
        console.print(f"⚡ lib.rs Performance: {cached_time:.1f}μs cached access")
        console.print(f"🔧 Unified Compute: {CONFIG.COMPUTE_LIMIT} | Priority: {CONFIG.PRIORITY_FEE}")
        console.print(f"📈 Unified Signal Threshold: {CONFIG.MIN_SIGNAL_STRENGTH}")
        console.print(f"💧 Unified Liquidity Threshold: ${CONFIG.MIN_LIQUIDITY_USD:,.0f}")
        console.print(f"🌐 Balance Change Threshold: {CONFIG.BALANCE_CHANGE_THRESHOLD} SOL")
        console.print("-" * 50 + "\n")
    
    async def find_opportunities(self) -> List[Dict]:
        """🔍 Find opportunities using UNIFIED configuration thresholds"""
        try:
            opportunities = await self.signal_finder.find_opportunities(limit=5)
            
            if not opportunities:
                console.print("[INFO] No opportunities found during discovery phase")
                return []
            
            console.print(f"🔍 Found {len(opportunities)} initial opportunities")
            
            # GPU analysis
            console.print(f"🎮 GPU analyzing {len(opportunities)} tokens...")
            gpu_signals = self.gpu_accelerator.scan_market(opportunities, CONFIG.EXCLUDED_TOKENS)
            
            # UNIFIED filtering - using the SAME thresholds as discovery
            verified_signals = []
            for signal in gpu_signals:
                try:
                    symbol = signal.get('symbol', '')
                    
                    # Check if already blacklisted
                    if symbol in self.blacklisted_tokens:
                        if CONFIG.DETAILED_LOGGING:
                            console.print(f"  ❌ {symbol}: Blacklisted")
                        continue
                    
                    # UNIFIED threshold checks - these now match discovery exactly
                    signal_strength = signal.get('signal_strength', 0)
                    liquidity = signal.get('liquidity', 0)
                    volume_24h = signal.get('volume_24h', 0)
                    volume_5m = signal.get('volume_5m', 0)
                    
                    # Apply UNIFIED thresholds from CONFIG
                    if (signal_strength >= CONFIG.MIN_SIGNAL_STRENGTH and 
                        liquidity >= CONFIG.MIN_LIQUIDITY_USD and 
                        volume_24h >= CONFIG.MIN_24H_VOLUME and
                        volume_5m >= CONFIG.MIN_VOLUME_5M):
                        
                        verified_signals.append(signal)
                        console.print(f"  ✅ {symbol}: Signal {signal_strength:.3f}, Liq ${liquidity:,.0f}, Vol5m ${volume_5m:,.0f}")
                    else:
                        if CONFIG.DETAILED_LOGGING:
                            console.print(f"  ❌ {symbol}: Filtered (Signal:{signal_strength:.3f}, Liq:${liquidity:,.0f}, Vol5m:${volume_5m:,.0f})")
                        
                except Exception as e:
                    console.print(f"[yellow]⚠️ Signal verification failed for {signal.get('symbol', 'unknown')}: {e}[/yellow]")
                    continue
            
            if verified_signals:
                console.print(f"[green]🌊 UNIFIED FILTER: {len(verified_signals)} verified signals passed[/green]")
                for wave in verified_signals[:3]:
                    console.print(f"  🏆 {wave['symbol']}: {wave['signal_type']} (score: {wave['signal_strength']:.3f})")
            else:
                console.print("[yellow]🔍 UNIFIED FILTER: No signals met unified thresholds[/yellow]")
            
            return verified_signals
            
        except Exception as e:
            console.print(f"[red]💥 Opportunity finding error: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
            return []
    
    async def execute_trade(self, signal: Dict) -> bool:
        """🚀 Execute trade with perfected unified configuration"""
        symbol = signal['symbol']
        token_mint = signal['token_mint']
        entry_price = signal['price']
        
        console.print(f"\n[bold]🎯 PERFECTED QUANTUM TRADE: {symbol}[/bold] ({signal['signal_type']}) @ ${entry_price:.8f}")
        
        trade_start_time = time.time()
        execution_start = time.perf_counter()
        
        try:
            # Check if we have enough balance
            current_balance = self.ws_listener.get_balance()
            if current_balance == 0:
                current_balance = self.trader.get_sol_balance()
            
            min_required = CONFIG.TRADE_AMOUNT_SOL + CONFIG.MIN_SOL_BALANCE
            if current_balance < min_required:
                console.print(f"[red]❌ Insufficient balance: {current_balance:.6f} SOL (need {min_required:.6f})[/red]")
                return False
            
            # Get pre-trade balance
            pre_balance = self.ws_listener.get_balance()
            if pre_balance == 0:
                pre_balance = self.trader.get_sol_balance()
                console.print(f"[yellow]🔄 lib.rs Balance Fallback: {pre_balance:.6f} SOL[/yellow]")
            
            # Execute buy using unified config
            buy_start = time.perf_counter()
            buy_sig = self.trader.execute_jupiter_swap(
                "So11111111111111111111111111111111111111112",  # SOL
                token_mint,
                CONFIG.TRADE_AMOUNT_SOL,
                CONFIG.SLIPPAGE_PERCENT,
                1  # Priority multiplier
            )
            
            buy_exec_time = (time.perf_counter() - buy_start) * 1000
            self.execution_times.append(buy_exec_time)
            console.print(f"🚀 lib.rs Buy executed: {buy_exec_time:.0f}ms")
            
            # Wait for WebSocket confirmation with unified timeout
            confirmation_start = time.perf_counter()
            confirmed, confirm_time, source = await self.ws_listener.wait_for_balance_change(CONFIG.WS_CONFIRMATION_TIMEOUT)
            
            if confirmed:
                self.confirmation_times.append(confirm_time)
                console.print(f"[green]✅ Confirmed by {source} in {confirm_time:.0f}ms[/green]")
                post_balance = self.ws_listener.get_balance()
                sol_spent = round(pre_balance - post_balance, 6)
            else:
                console.print("[yellow]⏰ WebSocket timeout - using lib.rs verification[/yellow]")
                await asyncio.sleep(2)
                post_balance = self.trader.get_sol_balance()
                sol_spent = round(pre_balance - post_balance, 6)
                
                if sol_spent > 0.001:
                    console.print(f"[green]✅ Trade verified via lib.rs - {sol_spent:.6f} SOL spent[/green]")
                    self.ws_listener.current_balance = post_balance
                else:
                    console.print("[red]❌ Trade verification failed - no SOL spent[/red]")
                    self.consecutive_failures += 1
                    self.failed_tokens[symbol] += 1
                    return False
            
            # Get token balance
            await asyncio.sleep(1)
            token_balance = self.trader.get_token_balance(token_mint)
            console.print(f"💎 Received: {token_balance:.6f} {symbol}")
            
            if token_balance <= 0:
                console.print("[red]❌ ERROR: No tokens received![/red]")
                self.consecutive_failures += 1
                self.failed_tokens[symbol] += 1
                return False
            
            # Reset failure counter on success
            self.consecutive_failures = 0
            
            # Create position with unified config
            position = {
                "symbol": symbol,
                "mint": token_mint,
                "entry_price": entry_price,
                "current_price": entry_price,
                "amount_sol": sol_spent,
                "amount_tokens": token_balance,
                "entry_time": trade_start_time,
                "entry_signature": buy_sig,
                "unrealized_pnl_pct": 0,
                "unrealized_pnl_sol": 0,
                "hold_time": 0,
                "signal_type": signal['signal_type'],
                "signal_strength": signal['signal_strength'],
                "feature_vector": signal.get('feature_vector', []),
                "last_logged_pnl": 0,
                "execution_time_ms": buy_exec_time,
                "confirmation_time_ms": confirm_time if confirmed else 0
            }
            
            self.positions[symbol] = position
            self.trades_executed += 1
            
            # Start tracking
            self.price_tracker.add_token(symbol, token_mint, entry_price)
            await self.signal_finder.track_position(symbol, token_mint, entry_price)
            
            # Update dashboard
            await self.update_dashboard()
            
            # Update blockhash cache for next trade
            self.trader.force_update_blockhash()
            
            total_time = (time.perf_counter() - execution_start) * 1000
            console.print(f"[green]✅ Total execution time: {total_time:.0f}ms[/green]")
            
            return True
            
        except Exception as e:
            console.print(f"[red]💥 Trade failed: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
            
            self.consecutive_failures += 1
            self.failed_tokens[symbol] += 1
            
            # Emergency protection
            if self.consecutive_failures >= self.max_consecutive_failures:
                console.print(f"[red]🚨 EMERGENCY: {self.consecutive_failures} consecutive failures - initiating safety shutdown[/red]")
                self.emergency_shutdown = True
                self.shutdown_event.set()
            
            return False
    
    async def check_exit_conditions(self):
        """🎯 Check exit conditions with perfected unified configuration"""
        if not self.positions:
            return
        
        positions_to_close = []
        
        for symbol, position in self.positions.items():
            try:
                # Get current price from multiple sources
                stats = self.signal_finder.get_position_stats(symbol)
                current_price_rt = self.price_tracker.get_current_price(symbol)
                
                # Use real-time price if available, otherwise signal finder
                entry_price = position.get('entry_price', 0)
                
                if current_price_rt > 0:
                    current_price = current_price_rt
                    source_text = "[RT]"
                elif stats:
                    current_price = stats.get('current_price', entry_price)
                    source_text = "[SF]"
                else:
                    current_price = entry_price
                    source_text = "[ENTRY]"
                
                if entry_price > 0 and current_price > 0:
                    unrealized_pnl_pct = ((current_price - entry_price) / entry_price) * 100
                    amount_sol_invested = position.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL)
                    unrealized_pnl_sol = amount_sol_invested * (unrealized_pnl_pct / 100)
                else:
                    unrealized_pnl_pct = 0
                    unrealized_pnl_sol = 0
                
                # Update position
                position['current_price'] = current_price
                position['unrealized_pnl_pct'] = unrealized_pnl_pct
                position['unrealized_pnl_sol'] = unrealized_pnl_sol
                position['hold_time'] = time.time() - position.get('entry_time', time.time())
                
                # Log significant P&L changes
                last_logged_pnl = position.get('last_logged_pnl', 0)
                pnl_change = abs(unrealized_pnl_pct - last_logged_pnl)
                
                if pnl_change >= 0.5:
                    style = "green" if unrealized_pnl_pct > 0 else "red"
                    emoji = "🚀" if unrealized_pnl_pct > 0 else "📉"
                    console.print(f"{symbol}: [{style}]{emoji} {unrealized_pnl_pct:+.2f}%[/{style}] (${current_price:.8f}) {source_text}")
                    position['last_logged_pnl'] = unrealized_pnl_pct
                
                # Check exit conditions using UNIFIED config
                should_exit = False
                exit_reason = None
                
                if unrealized_pnl_pct >= CONFIG.PROFIT_TARGET_PCT:
                    should_exit = True
                    exit_reason = "TAKE_PROFIT"
                    console.print(f"[green]🎯 {symbol}: UNIFIED PROFIT at {unrealized_pnl_pct:+.2f}%[/green]")
                elif unrealized_pnl_pct <= -CONFIG.STOP_LOSS_PCT:
                    should_exit = True
                    exit_reason = "STOP_LOSS"
                    console.print(f"[red]🛑 {symbol}: UNIFIED STOP LOSS at {unrealized_pnl_pct:+.2f}%[/red]")
                elif position['hold_time'] >= CONFIG.MAX_HOLD_TIME:
                    should_exit = True
                    exit_reason = "MAX_HOLD_TIME"
                    console.print(f"⏰ {symbol}: UNIFIED TIME LIMIT ({position['hold_time']:.0f}s)")
                
                if should_exit:
                    positions_to_close.append((symbol, position, exit_reason))
                    
            except Exception as e:
                console.print(f"[red]💥 Exit condition check failed for {symbol}: {e}[/red]")
                if CONFIG.DETAILED_LOGGING:
                    traceback.print_exc()
        
        # Execute closes
        for symbol, position, exit_reason in positions_to_close:
            await self.close_position(symbol, position, exit_reason)
    
    async def close_position(self, symbol: str, position: Dict, exit_reason: str):
        """🏆 Close position with perfected unified configuration"""
        console.print(f"\n🎯 PERFECTED CLOSE: {symbol} ({exit_reason})")
        
        token_mint = position.get('mint', '')
        token_balance = position.get('amount_tokens', 0)
        
        if token_balance <= 0:
            console.print(f"[red]❌ ERROR: No tokens to sell for {symbol} (balance: {token_balance})[/red]")
            if symbol in self.positions:
                del self.positions[symbol]
            await self.signal_finder.stop_tracking(symbol)
            self.price_tracker.remove_token(symbol)
            return
        
        sell_amount = token_balance * CONFIG.SELL_PERCENTAGE
        max_retries = CONFIG.WS_RETRY_ATTEMPTS
        retry_count = 0
        
        while retry_count < max_retries:
            try:
                console.print(f"[yellow]🔄 Sell attempt {retry_count + 1}/{max_retries}[/yellow]")
                
                # Get pre-sell balance
                pre_balance = self.ws_listener.get_balance()
                if pre_balance == 0:
                    pre_balance = self.trader.get_sol_balance()
                
                # Execute sell with unified config
                sell_start = time.perf_counter()
                sell_sig = self.trader.sell_token_for_sol_via_jupiter(
                    token_mint,
                    sell_amount,
                    CONFIG.SLIPPAGE_PERCENT,
                    1  # Priority multiplier
                )
                
                sell_exec_time = (time.perf_counter() - sell_start) * 1000
                console.print(f"🚀 lib.rs Sell executed: {sell_exec_time:.0f}ms")
                
                # Wait for confirmation with unified timeout
                confirmed, confirm_time, source = await self.ws_listener.wait_for_balance_change(CONFIG.WS_CONFIRMATION_TIMEOUT)
                
                if confirmed:
                    console.print(f"[green]✅ Sell confirmed by {source} in {confirm_time:.0f}ms[/green]")
                    post_balance = self.ws_listener.get_balance()
                    sol_received = round(post_balance - pre_balance, 6)
                elif retry_count == max_retries - 1:
                    console.print("[yellow]⏰ WebSocket timeout - lib.rs verification[/yellow]")
                    await asyncio.sleep(2)
                    post_balance = self.trader.get_sol_balance()
                    sol_received = round(post_balance - pre_balance, 6)
                    
                    if sol_received > 0.001:
                        console.print(f"[green]✅ Sell verified via lib.rs - {sol_received:.6f} SOL received[/green]")
                        self.ws_listener.current_balance = post_balance
                    else:
                        console.print(f"[red]❌ Sell attempt {retry_count + 1} failed - continuing to retry[/red]")
                        retry_count += 1
                        if retry_count < max_retries:
                            sell_amount = sell_amount * CONFIG.SELL_PERCENTAGE
                            await asyncio.sleep(1)
                        continue
                else:
                    console.print(f"[red]❌ Sell confirmation timeout (attempt {retry_count + 1})[/red]")
                    retry_count += 1
                    if retry_count < max_retries:
                        sell_amount = sell_amount * CONFIG.SELL_PERCENTAGE
                        await asyncio.sleep(1)
                    continue
                
                # Calculate P&L
                amount_sol_invested = position.get('amount_sol', 0)
                
                if amount_sol_invested > 0:
                    net_pnl_sol = sol_received - amount_sol_invested
                    net_pnl_pct = (net_pnl_sol / amount_sol_invested) * 100
                else:
                    console.print(f"[yellow]⚠️ WARNING: Missing amount_sol for {symbol}, using fallback[/yellow]")
                    net_pnl_sol = sol_received - CONFIG.TRADE_AMOUNT_SOL
                    net_pnl_pct = (net_pnl_sol / CONFIG.TRADE_AMOUNT_SOL) * 100 if CONFIG.TRADE_AMOUNT_SOL > 0 else 0
                    amount_sol_invested = CONFIG.TRADE_AMOUNT_SOL
                
                # Stop tracking
                await self.signal_finder.stop_tracking(symbol)
                self.price_tracker.remove_token(symbol)
                
                # Record trade
                trade_record = {
                    "timestamp": time.time(),
                    "symbol": symbol,
                    "token_mint": token_mint,
                    "entry_price": position.get('entry_price', 0),
                    "exit_price": position.get('current_price', 0),
                    "sol_invested": amount_sol_invested,
                    "sol_received": sol_received,
                    "actual_pnl_sol": net_pnl_sol,
                    "pnl_pct": net_pnl_pct,
                    "hold_time": position.get('hold_time', 0),
                    "exit_reason": exit_reason,
                    "signal_type": position.get('signal_type', 'UNKNOWN'),
                    "is_win": net_pnl_sol > 0,
                    "retry_count": retry_count + 1,
                    "execution_time_ms": position.get('execution_time_ms', 0),
                    "confirmation_time_ms": position.get('confirmation_time_ms', 0),
                    "sell_time_ms": sell_exec_time,
                    "confirming_websocket": source if confirmed else "lib.rs"
                }
                
                self.completed_trades.append(trade_record)
                self.recent_trades.append(trade_record)
                if len(self.recent_trades) > 10:
                    self.recent_trades.pop(0)
                
                # Update stats
                if net_pnl_sol > 0:
                    self.trades_won += 1
                    self.best_trade = max(self.best_trade, net_pnl_pct)
                    # Reset failure counter on profit
                    self.consecutive_failures = 0
                else:
                    self.trades_lost += 1
                    self.worst_trade = min(self.worst_trade, net_pnl_pct)
                    
                    # Handle losses
                    if net_pnl_sol < -0.01:  # Significant loss
                        self.failed_tokens[symbol] += 1
                        
                        # Blacklist after multiple failures
                        if self.failed_tokens[symbol] >= 3:
                            self.blacklisted_tokens.add(symbol)
                            console.print(f"[red]🚫 {symbol} added to blacklist after {self.failed_tokens[symbol]} failures[/red]")
                
                # GPU learning
                feature_vector = position.get('feature_vector')
                if feature_vector and len(feature_vector) > 0:
                    try:
                        self.gpu_accelerator.learn_from_trade(
                            symbol,
                            feature_vector,
                            net_pnl_pct,
                            position.get('hold_time', 0),
                            exit_reason
                        )
                    except Exception as e:
                        console.print(f"[yellow]🎮 GPU learning failed: {e}[/yellow]")
                
                # Remove position
                if symbol in self.positions:
                    del self.positions[symbol]
                
                # Log result
                style = "green" if net_pnl_sol > 0 else "red"
                emoji = "🏆" if net_pnl_sol > 0 else "💀"
                console.print(f"[green]✅ PERFECTED CLOSE SUCCESS:[/green] [{style}]{emoji} {net_pnl_sol:+.6f} SOL ({net_pnl_pct:+.2f}%)[/{style}] in {position.get('hold_time', 0):.0f}s")
                
                # Update dashboard
                await self.update_dashboard()
                
                return  # SUCCESS
                
            except Exception as e:
                console.print(f"[red]💥 Sell attempt {retry_count + 1} failed: {e}[/red]")
                retry_count += 1
                if retry_count < max_retries:
                    sell_amount = sell_amount * CONFIG.SELL_PERCENTAGE
                    console.print(f"[yellow]🔄 Retrying with {sell_amount:.6f} tokens[/yellow]")
                    await asyncio.sleep(1)
        
        # All retries failed - force close
        console.print(f"[red]💀 PERFECTED FORCE CLOSE: All {max_retries} attempts failed for {symbol}[/red]")
        
        # Stop tracking regardless
        await self.signal_finder.stop_tracking(symbol)
        self.price_tracker.remove_token(symbol)
        
        # Add to blacklist
        self.blacklisted_tokens.add(symbol)
        console.print(f"[red]🚫 {symbol} blacklisted after failed close[/red]")
        
        # Create failed trade record
        amount_sol_invested = position.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL)
        
        failed_trade = {
            "timestamp": time.time(),
            "symbol": symbol,
            "token_mint": token_mint,
            "entry_price": position.get('entry_price', 0),
            "exit_price": position.get('current_price', 0),
            "sol_invested": amount_sol_invested,
            "sol_received": 0,
            "actual_pnl_sol": -amount_sol_invested,
            "pnl_pct": -100,
            "hold_time": position.get('hold_time', 0),
            "exit_reason": "PERFECTED_FORCE_CLOSE",
            "signal_type": position.get('signal_type', 'UNKNOWN'),
            "is_win": False,
            "retry_count": max_retries
        }
        
        self.completed_trades.append(failed_trade)
        self.trades_lost += 1
        self.consecutive_failures += 1
        
        # Force remove position
        if symbol in self.positions:
            del self.positions[symbol]
        
        console.print(f"[red]💀 Position {symbol} PERFECTED force-closed[/red]")
        await self.update_dashboard()
    
    async def update_dashboard(self):
        """📊 Update dashboard with perfected unified configuration data"""
        try:
            current_time = time.time()
            current_balance = self.ws_listener.get_balance()
            
            if current_balance == 0:
                current_balance = self.trader.get_sol_balance()
            
            # Calculate session metrics
            session_duration = current_time - self.session_start_time
            realized_pnl_sol = sum(trade.get('actual_pnl_sol', 0) for trade in self.completed_trades)
            unrealized_pnl_sol = 0
            
            for position in self.positions.values():
                unrealized_pnl_sol += position.get('unrealized_pnl_sol', 0)
            
            total_session_pnl = realized_pnl_sol + unrealized_pnl_sol
            
            # Calculate percentages
            total_invested = sum(trade.get('sol_invested', 0) for trade in self.completed_trades)
            total_invested += sum(pos.get('amount_sol', 0) for pos in self.positions.values())
            
            session_pnl_pct = (total_session_pnl / total_invested * 100) if total_invested > 0 else 0
            
            # Win rate
            total_trades = self.trades_won + self.trades_lost
            win_rate = (self.trades_won / total_trades * 100) if total_trades > 0 else 0
            
            # Performance metrics
            avg_execution_time = statistics.mean(self.execution_times) if self.execution_times else 0
            avg_confirmation_time = statistics.mean(self.confirmation_times) if self.confirmation_times else 0
            avg_blockhash_time = statistics.mean(self.blockhash_times) if self.blockhash_times else 0
            
            # Active position data
            active_position_data = None
            if self.positions:
                symbol, pos = next(iter(self.positions.items()))
                current_price_rt = self.price_tracker.get_current_price(symbol)
                
                entry_price = pos['entry_price']
                current_price = current_price_rt if current_price_rt > 0 else pos.get('current_price', entry_price)
                
                if entry_price > 0:
                    unrealized_pnl_pct = ((current_price - entry_price) / entry_price) * 100
                    amount_sol_invested = pos.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL)
                    unrealized_pnl_sol_calc = amount_sol_invested * (unrealized_pnl_pct / 100)
                else:
                    unrealized_pnl_pct = 0
                    unrealized_pnl_sol_calc = 0
                
                active_position_data = {
                    "symbol": symbol,
                    "token_mint": pos.get('mint', ''),
                    "entry_price": entry_price,
                    "current_price": current_price,
                    "amount_sol": pos.get('amount_sol', 0),
                    "amount_tokens": pos.get('amount_tokens', 0),
                    "price_change_pct": unrealized_pnl_pct,
                    "unrealized_pnl": unrealized_pnl_sol_calc,
                    "unrealized_pnl_pct": unrealized_pnl_pct,
                    "hold_time": time.time() - pos['entry_time'],
                    "hold_time_seconds": time.time() - pos['entry_time'],
                    "entry_time": pos['entry_time'],
                    "signal_type": pos.get('signal_type', 'BUY'),
                    "signal_strength": pos.get('signal_strength', 0),
                    "source": "PERFECTED_REAL_TIME" if current_price_rt > 0 else "SIGNAL_FINDER"
                }
            
            # Build perfected dashboard data
            dashboard_data = {
                "timestamp": current_time,
                "balance": current_balance,
                "trading_active": self.running,
                "total_trades": self.trades_executed,
                "trades_executed": self.trades_executed,
                "trades_closed": total_trades,
                "winning_trades": self.trades_won,
                "trades_won": self.trades_won,
                "losing_trades": self.trades_lost,
                "trades_lost": self.trades_lost,
                "win_rate": win_rate,
                
                # P&L tracking (PERFECTED)
                "session_pnl": total_session_pnl,
                "session_pnl_pct": session_pnl_pct,
                "realized_pnl": realized_pnl_sol,
                "unrealized_pnl": unrealized_pnl_sol,
                "total_pnl": total_session_pnl,
                
                "session_hours": session_duration / 3600,
                "session_minutes": (session_duration % 3600) / 60,
                "trades_per_hour": (self.trades_executed / max(session_duration / 3600, 0.1)),
                
                # Position data
                "active_position": bool(self.positions),
                "active_positions": len(self.positions),
                "position": active_position_data,
                "positions": self.positions,
                
                # Trade data
                "recent_trades": self.recent_trades[-5:],
                "last_trade": self.recent_trades[-1] if self.recent_trades else None,
                "best_trade": self.best_trade,
                "worst_trade": self.worst_trade,
                "largest_win": max([t.get('actual_pnl_sol', 0) for t in self.completed_trades] + [0]),
                "largest_loss": abs(min([t.get('actual_pnl_sol', 0) for t in self.completed_trades] + [0])),
                
                # Session data
                "session_start_balance": self.session_start_balance,
                "session_start_time": self.session_start_time,
                "session_duration": session_duration,
                "last_update": datetime.now().strftime('%I:%M:%S %p'),
                
                # System status (ENHANCED)
                "websocket_active": self.ws_listener.is_connected(),
                "websocket_status": self.ws_listener.get_connection_status(),
                "websocket_stats": self.ws_listener.get_connection_stats(),
                "current_endpoint": CONFIG.PRIMARY_RPC_URL.split('/')[-1] if CONFIG.PRIMARY_RPC_URL else "N/A",
                "connection_quality": "PERFECTED_QUANTUM" if self.ws_listener.get_connection_status() == "🔥 DUAL_POWER" else "EXCELLENT",
                
                # Performance metrics (ENHANCED)
                "avg_execution_time_ms": avg_execution_time,
                "avg_confirmation_time_ms": avg_confirmation_time,
                "avg_blockhash_time_us": avg_blockhash_time,
                "lib_rs_performance": f"{avg_blockhash_time:.1f}μs" if avg_blockhash_time < 1000 else f"{avg_blockhash_time/1000:.1f}ms",
                "fastest_execution": min(self.execution_times) if self.execution_times else 0,
                "fastest_confirmation": min(self.confirmation_times) if self.confirmation_times else 0,
                
                # Tracking data
                "price_tracking_active": self.price_tracker.running,
                "tracked_tokens": len(self.price_tracker.tracking_tokens),
                "price_alerts": list(self.price_tracker.price_alerts)[-5:],
                "tracking_interval": f"{CONFIG.POSITION_CHECK_INTERVAL}s",
                
                # WebSocket enhanced stats
                "ws_confirmations": self.ws_listener.total_updates,
                "primary_wins": self.ws_listener.primary_wins,
                "secondary_wins": self.ws_listener.secondary_wins,
                
                # Risk management
                "consecutive_failures": self.consecutive_failures,
                "emergency_shutdown": self.emergency_shutdown,
                "blacklisted_tokens": len(self.blacklisted_tokens),
                "failed_tokens": dict(self.failed_tokens),
                
                # PERFECTED UNIFIED CONFIG stats
                "unified_config": {
                    "compute_limit": CONFIG.COMPUTE_LIMIT,
                    "priority_fee": CONFIG.PRIORITY_FEE,
                    "slippage_percent": CONFIG.SLIPPAGE_PERCENT,
                    "trade_amount_sol": CONFIG.TRADE_AMOUNT_SOL,
                    "profit_target_pct": CONFIG.PROFIT_TARGET_PCT,
                    "stop_loss_pct": CONFIG.STOP_LOSS_PCT,
                    "min_signal_strength": CONFIG.MIN_SIGNAL_STRENGTH,
                    "min_liquidity_usd": CONFIG.MIN_LIQUIDITY_USD,
                    "min_volume_5m": CONFIG.MIN_VOLUME_5M,
                    "check_interval": CONFIG.CHECK_INTERVAL,
                    "position_check_interval": CONFIG.POSITION_CHECK_INTERVAL,
                    "ws_confirmation_timeout": CONFIG.WS_CONFIRMATION_TIMEOUT,
                    "balance_change_threshold": CONFIG.BALANCE_CHANGE_THRESHOLD,
                    "excluded_tokens_count": len(CONFIG.EXCLUDED_TOKENS),
                    "max_hold_time": CONFIG.MAX_HOLD_TIME,
                    "ws_retry_attempts": CONFIG.WS_RETRY_ATTEMPTS
                },
                
                # lib.rs Performance stats (ENHANCED)
                "rust_engine_stats": {
                    "compute_limit": CONFIG.COMPUTE_LIMIT,
                    "priority_fee": CONFIG.PRIORITY_FEE,
                    "avg_execution_ms": avg_execution_time,
                    "avg_confirmation_ms": avg_confirmation_time,
                    "blockhash_cache_us": avg_blockhash_time,
                    "jupiter_cache_enabled": True,
                    "unified_config_active": True,
                    "performance_grade": "PERFECTED_QUANTUM"
                },
                
                # Meta
                "status": "🏆 PERFECTED_QUANTUM_ACTIVE" if self.running else "🛑 STOPPED",
                "version": "PERFECTED_QUANTUM_BEAST_UNIFIED_CONFIG",
                "config_source": "UNIFIED_.ENV_PERFECTED",
                "update_count": getattr(self, 'dashboard_update_count', 0) + 1
            }
            
            # Increment update counter
            self.dashboard_update_count = dashboard_data["update_count"]
            
            # Write perfected dashboard file atomically
            temp_file = "dashboard_data.json.tmp"
            with open(temp_file, "w") as f:
                json.dump(dashboard_data, f, indent=2)
            
            # Atomic move
            if os.path.exists("dashboard_data.json"):
                os.remove("dashboard_data.json")
            os.rename(temp_file, "dashboard_data.json")
                
        except Exception as e:
            console.print(f"[red]📊 Dashboard update error: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
    
    async def run(self):
        """🚀 PERFECTED UNIFIED QUANTUM TRADING LOOP"""
        self.running = True
        console.print("[green]🏆 PERFECTED QUANTUM BEAST TRADING ACTIVE! 🏆[/green]\n")
        console.print("[cyan]💎 UNIFIED .ENV CONFIG - BULLETPROOF WEBSOCKETS! 💎[/cyan]\n")
        
        # Dashboard updater
        dashboard_task = asyncio.create_task(self.dashboard_update_loop())
        
        try:
            last_scan_time = 0
            
            while self.running and not self.emergency_shutdown:
                current_time = time.time()
                
                # Check for emergency shutdown
                if self.emergency_shutdown:
                    console.print(f"[red]🚨 EMERGENCY SHUTDOWN TRIGGERED[/red]")
                    break
                
                # Scan for opportunities using UNIFIED timing
                if current_time - last_scan_time >= CONFIG.CHECK_INTERVAL:
                    if len(self.positions) < CONFIG.MAX_CONCURRENT_POSITIONS:
                        console.print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔍 Scanning for PERFECTED QUANTUM opportunities...")
                        console.print("=" * 60)
                        console.print("[PERFECTED] Finding top opportunities with unified thresholds...")
                        
                        # Get current balance
                        current_bal = self.ws_listener.get_balance()
                        if current_bal == 0:
                            current_bal = self.trader.get_sol_balance()
                        console.print(f"💰 Balance: {current_bal:.6f} SOL")
                        
                        # Check if we have enough balance
                        min_required = CONFIG.TRADE_AMOUNT_SOL + CONFIG.MIN_SOL_BALANCE
                        if current_bal >= min_required:
                            opportunities = await self.find_opportunities()
                            
                            if opportunities:
                                best_signal = opportunities[0]
                                if best_signal['symbol'] not in self.positions and best_signal['symbol'] not in self.blacklisted_tokens:
                                    console.print(f"🎯 PERFECTED OPPORTUNITY: {best_signal['symbol']} (Signal: {best_signal['signal_strength']:.3f})")
                                    success = await self.execute_trade(best_signal)
                                    if success:
                                        await asyncio.sleep(3)
                                else:
                                    if best_signal['symbol'] in self.positions:
                                        console.print(f"[yellow]⚠️ Already holding position in {best_signal['symbol']}[/yellow]")
                                    elif best_signal['symbol'] in self.blacklisted_tokens:
                                        console.print(f"[red]🚫 {best_signal['symbol']} is blacklisted[/red]")
                            else:
                                console.print("[INFO] No opportunities found with perfected unified thresholds")
                        else:
                            console.print(f"[yellow]⚠️ Insufficient balance for trading (need {min_required:.6f} SOL, have {current_bal:.6f})[/yellow]")
                    else:
                        console.print(f"[yellow]📊 Max positions reached ({len(self.positions)}/{CONFIG.MAX_CONCURRENT_POSITIONS})[/yellow]")
                    
                    last_scan_time = current_time
                
                # Check exit conditions using UNIFIED config
                await self.check_exit_conditions()
                
                # Sleep using UNIFIED interval
                await asyncio.sleep(CONFIG.POSITION_CHECK_INTERVAL)
                
                # Check shutdown
                if self.shutdown_event.is_set():
                    break
                    
        except KeyboardInterrupt:
            console.print("\n[yellow]🛑 Perfected shutdown requested...[/yellow]")
        except Exception as e:
            console.print(f"[red]💥 Perfected error: {e}[/red]")
            if CONFIG.DETAILED_LOGGING:
                traceback.print_exc()
        finally:
            dashboard_task.cancel()
            await self.shutdown()
    
    async def dashboard_update_loop(self):
        """📊 Dashboard update loop with unified timing"""
        while self.running:
            try:
                await self.update_dashboard()
                await asyncio.sleep(CONFIG.DASHBOARD_UPDATE_INTERVAL)
            except asyncio.CancelledError:
                break
            except Exception as e:
                if CONFIG.DETAILED_LOGGING:
                    console.print(f"[yellow]📊 Dashboard loop error: {e}[/yellow]")
                await asyncio.sleep(CONFIG.DASHBOARD_UPDATE_INTERVAL)
    
    async def emergency_close_all_positions(self):
        """🚨 Emergency close all positions with perfected config"""
        if not self.positions:
            console.print("[green]✅ No positions to close[/green]")
            return
        
        console.print(f"[red]🚨 PERFECTED EMERGENCY: Closing {len(self.positions)} positions immediately![/red]")
        
        positions_to_close = list(self.positions.items())
        
        for symbol, position in positions_to_close:
            try:
                console.print(f"[yellow]🚨 Emergency closing {symbol}...[/yellow]")
                
                token_mint = position.get('mint', '')
                token_balance = position.get('amount_tokens', 0)
                
                if token_balance <= 0:
                    console.print(f"[yellow]⚠️ No tokens to sell for {symbol}[/yellow]")
                    continue
                
                # Use unified sell percentage
                sell_amount = token_balance * CONFIG.SELL_PERCENTAGE
                
                # Get pre-sell balance
                pre_balance = self.ws_listener.get_balance()
                if pre_balance == 0:
                    pre_balance = self.trader.get_sol_balance()
                
                # Execute emergency sell with perfected config
                try:
                    sell_sig = self.trader.sell_token_for_sol_via_jupiter(
                        token_mint,
                        sell_amount,
                        CONFIG.SLIPPAGE_PERCENT * 2,  # Double slippage for emergency
                        2  # Higher priority for emergency
                    )
                    
                    console.print(f"[green]✅ Emergency sell executed for {symbol}: {sell_sig}[/green]")
                    
                    # Wait for confirmation
                    await asyncio.sleep(3)
                    
                    # Get post-sell balance
                    post_balance = self.ws_listener.get_balance()
                    if post_balance == 0:
                        post_balance = self.trader.get_sol_balance()
                    
                    sol_received = post_balance - pre_balance
                    amount_sol_invested = position.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL)
                    net_pnl_sol = sol_received - amount_sol_invested
                    net_pnl_pct = (net_pnl_sol / amount_sol_invested) * 100 if amount_sol_invested > 0 else 0
                    
                    # Record emergency trade
                    emergency_trade = {
                        "timestamp": time.time(),
                        "symbol": symbol,
                        "token_mint": token_mint,
                        "entry_price": position.get('entry_price', 0),
                        "exit_price": position.get('current_price', 0),
                        "sol_invested": amount_sol_invested,
                        "sol_received": sol_received,
                        "actual_pnl_sol": net_pnl_sol,
                        "pnl_pct": net_pnl_pct,
                        "hold_time": time.time() - position.get('entry_time', time.time()),
                        "exit_reason": "PERFECTED_EMERGENCY_SHUTDOWN",
                        "signal_type": position.get('signal_type', 'UNKNOWN'),
                        "is_win": net_pnl_sol > 0,
                        "retry_count": 1
                    }
                    
                    self.completed_trades.append(emergency_trade)
                    
                    # Update stats
                    if net_pnl_sol > 0:
                        self.trades_won += 1
                        self.best_trade = max(self.best_trade, net_pnl_pct)
                    else:
                        self.trades_lost += 1
                        self.worst_trade = min(self.worst_trade, net_pnl_pct)
                    
                    console.print(f"[green]✅ Emergency close complete: {symbol} {net_pnl_sol:+.6f} SOL ({net_pnl_pct:+.2f}%)[/green]")
                    
                except Exception as sell_error:
                    console.print(f"[red]❌ Emergency sell failed for {symbol}: {sell_error}[/red]")
                    
                    # Force close anyway
                    failed_trade = {
                        "timestamp": time.time(),
                        "symbol": symbol,
                        "token_mint": token_mint,
                        "entry_price": position.get('entry_price', 0),
                        "exit_price": position.get('current_price', 0),
                        "sol_invested": position.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL),
                        "sol_received": 0,
                        "actual_pnl_sol": -position.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL),
                        "pnl_pct": -100,
                        "hold_time": time.time() - position.get('entry_time', time.time()),
                        "exit_reason": "PERFECTED_EMERGENCY_FORCE_CLOSE",
                        "signal_type": position.get('signal_type', 'UNKNOWN'),
                        "is_win": False,
                        "retry_count": 1
                    }
                    
                    self.completed_trades.append(failed_trade)
                    self.trades_lost += 1
                
                # Stop tracking
                await self.signal_finder.stop_tracking(symbol)
                self.price_tracker.remove_token(symbol)
                
            except Exception as e:
                console.print(f"[red]💥 Emergency close error for {symbol}: {e}[/red]")
        
        # Clear all positions
        self.positions.clear()
        console.print("[green]✅ All positions emergency closed with perfected config[/green]")
    
    async def shutdown(self):
        """🏆 PERFECTED QUANTUM SHUTDOWN SEQUENCE"""
        self.running = False
        console.print("\n🛑 PERFECTED QUANTUM SHUTDOWN INITIATED...")
        
        # Stop tracking
        self.price_tracker.stop_tracking()
        if hasattr(self, 'price_tracker_task'):
            self.price_tracker_task.cancel()
        
        # Emergency close all positions
        if self.positions:
            await self.emergency_close_all_positions()
        
        # Final update
        await self.update_dashboard()
        
        # Print summary
        self.print_perfected_summary()
        
        # Cleanup
        if self.ws_listener:
            await self.ws_listener.close()
        if self.signal_finder:
            await self.signal_finder.close()
        if self.gpu_accelerator:
            self.gpu_accelerator.cleanup()
        
        console.print("[green]🏆 PERFECTED QUANTUM SHUTDOWN COMPLETE 🏆[/green]")
    
    def print_perfected_summary(self):
        """🏆 Print perfected trading summary"""
        final_balance = self.ws_listener.get_balance()
        if final_balance == 0:
            final_balance = self.trader.get_sol_balance()
            
        total_pnl = final_balance - self.session_start_balance
        total_pnl_pct = (total_pnl / self.session_start_balance * 100) if self.session_start_balance > 0 else 0
        
        console.print("\n" + "=" * 70)
        console.print("[bold]🏆 PERFECTED QUANTUM BEAST SESSION SUMMARY 🏆[/bold]")
        console.print("=" * 70)
        
        style = "green" if total_pnl >= 0 else "red"
        emoji = "🚀" if total_pnl >= 0 else "💀"
        console.print(f"💰 P&L: [{style}]{emoji} {total_pnl:+.6f} SOL ({total_pnl_pct:+.2f}%)[/{style}]")
        console.print(f"📊 Trades: {self.trades_executed} ({self.trades_won}W / {self.trades_lost}L)")
        
        if self.trades_executed > 0:
            console.print(f"🎯 Win Rate: {(self.trades_won/self.trades_executed*100):.1f}%")
            
        if self.completed_trades:
            console.print(f"🏆 Best: {self.best_trade:+.2f}% | 💀 Worst: {self.worst_trade:+.2f}%")
        
        # Performance metrics
        if self.execution_times:
            avg_exec = statistics.mean(self.execution_times)
            console.print(f"\n⚡ PERFECTED Performance:")
            console.print(f"   🚀 Avg Execution: {avg_exec:.0f}ms")
            console.print(f"   ⚡ Best Execution: {min(self.execution_times):.0f}ms")
            
        if self.confirmation_times:
            avg_confirm = statistics.mean(self.confirmation_times)
            console.print(f"   📡 Avg Confirmation: {avg_confirm:.0f}ms")
            console.print(f"   🔥 Best Confirmation: {min(self.confirmation_times):.0f}ms")
            
        if self.blockhash_times:
            avg_blockhash = statistics.mean(self.blockhash_times)
            console.print(f"   💎 Blockhash Cache: {avg_blockhash:.1f}μs")
        
        # Enhanced WebSocket stats
        ws_stats = self.ws_listener.get_connection_stats()
        console.print(f"\n🌐 ENHANCED WebSocket Performance:")
        console.print(f"   🏆 PRIMARY Wins: {ws_stats['primary_wins']}")
        console.print(f"   🏆 SECONDARY Wins: {ws_stats['secondary_wins']}")
        console.print(f"   📡 Final Status: {ws_stats['status']}")
        console.print(f"   🔄 Connection Attempts: P:{ws_stats['primary_attempts']} S:{ws_stats['secondary_attempts']}")
        console.print(f"   🌐 Balance Threshold: {ws_stats['balance_threshold']} SOL")
        
        # Risk management stats
        console.print(f"\n🛡️ Risk Management:")
        console.print(f"   🚫 Blacklisted Tokens: {len(self.blacklisted_tokens)}")
        console.print(f"   ⚠️ Failed Tokens: {len(self.failed_tokens)}")
        console.print(f"   🔄 Consecutive Failures: {self.consecutive_failures}")
        console.print(f"   🚨 Emergency Shutdown: {'YES' if self.emergency_shutdown else 'NO'}")
        
        # Perfected config summary
        console.print(f"\n🔧 PERFECTED Configuration Results:")
        console.print(f"   💰 Trade Amount: {CONFIG.TRADE_AMOUNT_SOL} SOL")
        console.print(f"   🎯 Targets: +{CONFIG.PROFIT_TARGET_PCT}% / -{CONFIG.STOP_LOSS_PCT}%")
        console.print(f"   📈 Signal Threshold: {CONFIG.MIN_SIGNAL_STRENGTH}")
        console.print(f"   💧 Liquidity Threshold: ${CONFIG.MIN_LIQUIDITY_USD:,.0f}")
        console.print(f"   📊 Volume 5m Threshold: ${CONFIG.MIN_VOLUME_5M:,.0f}")
        console.print(f"   ⏱️ Check Interval: {CONFIG.CHECK_INTERVAL}s")
        console.print(f"   🚫 Excluded Tokens: {len(CONFIG.EXCLUDED_TOKENS)}")
        console.print(f"   💎 Sell Percentage: {CONFIG.SELL_PERCENTAGE * 100:.1f}%")
        console.print(f"   🌐 Balance Threshold: {CONFIG.BALANCE_CHANGE_THRESHOLD} SOL")
        console.print(f"   🔄 WS Retry Attempts: {CONFIG.WS_RETRY_ATTEMPTS}")
        console.print(f"   ⏰ WS Timeout: {CONFIG.WS_CONFIRMATION_TIMEOUT}s")
        
        # The perfected conclusion
        console.print("\n" + "=" * 70)
        console.print("🏆 PERFECTED .ENV CONFIG - BULLETPROOF WEBSOCKETS! 🏆".center(70))
        console.print("💎 DISCOVERY = EXECUTION = PERFECTED SUCCESS! 💎".center(70))
        console.print("=" * 70)


def setup_signal_handlers(beast):
    """Setup graceful shutdown signal handlers"""
    def signal_handler(sig, frame):
        console.print(f"\n[yellow]🛑 Perfected Signal {sig} received - initiating graceful shutdown[/yellow]")
        beast.shutdown_event.set()
    
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    if hasattr(signal, 'SIGBREAK'):
        signal.signal(signal.SIGBREAK, signal_handler)


# Set up enhanced logging
LOG_DIR = Path("logs/perfected_quantum")
LOG_DIR.mkdir(exist_ok=True, parents=True)
log_file = LOG_DIR / f"perfected_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

logging.basicConfig(
    level=getattr(logging, CONFIG.LOG_LEVEL.upper()),
    format='%(message)s',
    datefmt='%H:%M:%S',
    handlers=[logging.FileHandler(log_file)]
)


async def main():
    """🏆 PERFECTED QUANTUM MAIN ENTRY POINT"""
    beast = QuantumBeastUnified()
    
    # Setup signal handlers
    setup_signal_handlers(beast)
    
    try:
        await beast.initialize()
        await beast.run()
    except KeyboardInterrupt:
        console.print(f"\n[yellow]🛑 Perfected Quantum Beast interrupted by user[/yellow]")
    except Exception as e:
        console.print(f"[red]💥 Perfected Fatal Error: {e}[/red]")
        if CONFIG.DETAILED_LOGGING:
            traceback.print_exc()
    finally:
        if not beast.shutdown_event.is_set():
            await beast.shutdown()


if __name__ == "__main__":
    # Display perfected header
    console.print("\n" + "🔥" * 80)
    console.print("🏆 QUANTUM BEAST - PERFECTED UNIFIED CONFIGURATION 🏆".center(80))
    console.print("💎 BULLETPROOF WEBSOCKETS + FIXED P&L + REAL-TIME 💎".center(80))
    console.print("🚀 SINGLE SOURCE OF TRUTH - NO MORE MISMATCHES! 🚀".center(80))
    console.print("🔥" * 80 + "\n")
    
    console.print("🏆 PERFECTED QUANTUM FEATURES:")
    console.print("   ✅ UNIFIED .env configuration (NO MORE MISMATCHES!)")
    console.print("   ✅ BULLETPROOF WebSocket system (dual racing + auto-reconnect)")
    console.print("   ✅ PERFECTED P&L calculation (actual SOL amounts)")
    console.print("   ✅ ENHANCED error handling (retries + fallbacks + blacklist)")
    console.print("   ✅ REAL-TIME price tracking (0.5s updates + alerts)")
    console.print("   ✅ lib.rs microsecond performance (2μs blockhash cache)")
    console.print("   ✅ GPU early wave detection (catches waves first)")
    console.print("   ✅ SMART risk management (emergency protection)")
    console.print("   ✅ COMPREHENSIVE dashboard (live perfected metrics)")
    console.print("   ✅ GRACEFUL shutdown (emergency position closure)")
    console.print("   ✅ CONFIGURABLE thresholds (balance, confirmations, retries)")
    
    console.print(f"\n🚀 Starting PERFECTED QUANTUM Beast in 3 seconds...")
    console.print("💰 .env + WebSocket + lib.rs + GPU = PERFECTED PROFIT MACHINE! 💰")
    console.print("🛑 Press Ctrl+C anytime for graceful shutdown")
    time.sleep(3)
    
    # Validate environment
    if not os.path.exists(CONFIG.KEYPAIR_PATH):
        console.print(f"[red]❌ Keypair file not found: {CONFIG.KEYPAIR_PATH}[/red]")
        console.print(f"[yellow]Please ensure your keypair.bin file exists at the specified path[/yellow]")
        sys.exit(1)
    
    if not CONFIG.API_KEY or CONFIG.API_KEY == "your_api_key_here":
        console.print(f"[red]❌ Please set your HELIUS_API_KEY in the .env file[/red]")
        sys.exit(1)
    
    # All systems go!
    console.print("[green]🚀 ALL SYSTEMS GO - PERFECTED QUANTUM BEAST LAUNCHING![/green]")
    
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        console.print("\n[green]✅ Perfected Quantum Beast shutdown completed successfully[/green]")
    except Exception as e:
        console.print(f"\n[red]💥 Perfected Quantum Beast crashed: {e}[/red]")
        sys.exit(1)   whats missing in the 1st script?