#!/usr/bin/env python3
"""
🏆 PERFECT FUSION ORCHESTRATOR - RUST LIBRARY FIXED VERSION
===========================================================
💎 Uses YOUR PyO3/maturin built Rust library for ALL trades
💎 Maintains dashboard.json compatibility for your bridge
💎 Fixes Jupiter "base64 encoded too large" error
💎 Uses YOUR EXACT .env parameters and proven systems
===========================================================
"""

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

# Essential imports for signal scripts
try:
    import websockets
    WEBSOCKETS_AVAILABLE = True
except ImportError:
    WEBSOCKETS_AVAILABLE = False
    print("⚠️ websockets not installed - WebSocket features may be limited")

try:
    import torch
    GPU_AVAILABLE = torch.cuda.is_available() if torch else False
except ImportError:
    torch = None
    GPU_AVAILABLE = False
    print("⚠️ PyTorch not installed - GPU acceleration disabled")

try:
    import requests
    REQUESTS_AVAILABLE = True
except ImportError:
    REQUESTS_AVAILABLE = False
    print("⚠️ requests not installed - some features may be limited")

# Rich for legendary terminal output
try:
    from rich.console import Console
    from rich.logging import RichHandler
    console = Console()
    RICH_AVAILABLE = True
except ImportError:
    RICH_AVAILABLE = False
    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__)))

# 🔥 CRITICAL: Import YOUR Rust library first before any Jupiter Python code
RUST_TRADER_AVAILABLE = False
try:
    from solana_rust_bot import SolanaTrader
    RUST_TRADER_AVAILABLE = True
    console.print("[green]✅ RUST LIBRARY LOADED - Using optimized PyO3 implementation[/green]")
except ImportError as e:
    RUST_TRADER_AVAILABLE = False
    console.print(f"[red]❌ RUST LIBRARY FAILED: {e}[/red]")
    console.print("[red]Make sure you've built the Rust library with: maturin develop --release[/red]")
    sys.exit(1)  # Exit if Rust library not available

# Import signal components with error handling
try:
    from quantum_signal_finder_complete import QuantumSignalFinder
    QUANTUM_FINDER_AVAILABLE = True
except ImportError as e:
    QUANTUM_FINDER_AVAILABLE = False
    console.print(f"[yellow]⚠️ quantum_signal_finder_complete import failed: {e}[/yellow]")

try:
    from gpu_accelerator_improved import GPUAcceleratorULTIMATE
    GPU_ACCELERATOR_AVAILABLE = True
except ImportError as e:
    GPU_ACCELERATOR_AVAILABLE = False
    console.print(f"[yellow]⚠️ gpu_accelerator_improved import failed: {e}[/yellow]")

try:
    from helius_safety_validator import HeliusEnhancedSafetyValidator
    SAFETY_VALIDATOR_AVAILABLE = True
except ImportError as e:
    SAFETY_VALIDATOR_AVAILABLE = False
    console.print(f"[yellow]⚠️ helius_safety_validator import failed: {e}[/yellow]")

try:
    from token_discover import UltimateTokenDiscovery
    TOKEN_DISCOVERY_AVAILABLE = True
except ImportError as e:
    TOKEN_DISCOVERY_AVAILABLE = False
    console.print(f"[yellow]⚠️ token_discover import failed: {e}[/yellow]")

# Force load environment from your exact path
from dotenv import load_dotenv

# Try your exact paths
env_paths = [
    r"C:\solana_rust_bot\.env",
    ".env",
    os.path.join(os.path.dirname(__file__), ".env"),
    os.path.join(os.path.dirname(__file__), "..", "..", ".env")
]

env_loaded = False
for path in env_paths:
    if os.path.exists(path):
        load_dotenv(path, override=True)
        console.print(f"[green]✅ Loaded .env from: {path}[/green]")
        env_loaded = True
        break

if not env_loaded:
    console.print("[red]❌ No .env file found![/red]")
    console.print(f"Searched paths: {env_paths}")

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


class PerfectConfig:
    """🏆 YOUR EXACT CONFIG - UNCHANGED"""
    
    def __init__(self):
        # Network & API (YOUR exact .env values)
        self.API_KEY = os.getenv("HELIUS_API_KEY", "86ab5634-df30-4a5b-bcfb-3f53d7095ca2")
        self.KEYPAIR_PATH = os.getenv("KEYPAIR_PATH", r"C:\solana_rust_bot\keypair.bin")
        self.WALLET_ADDRESS = os.getenv("SOLANA_PUBLIC_KEY", "77ssrQ7LmPso1d1wYp4jAQdz4NqKSbKK8t6mFLcx6Xwr")
        
        # RPC/WebSocket endpoints (YOUR exact .env values)
        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}")
        self.FALLBACK_RPC_URL = os.getenv("FALLBACK_RPC_URL", "https://api.mainnet-beta.solana.com")
        self.FALLBACK_WS_URL = os.getenv("FALLBACK_WS_URL", "wss://api.mainnet-beta.solana.com")
        
        # 🔥 YOUR EXACT .ENV TRADING PARAMETERS 🔥
        self.TRADE_AMOUNT_SOL = float(os.getenv("TRADE_AMOUNT", "0.03"))        # YOUR .env: 0.03 SOL
        self.COMPUTE_LIMIT = int(os.getenv("COMPUTE_LIMIT", "120000"))          # YOUR .env: 120000
        self.PRIORITY_FEE = int(os.getenv("PRIORITY_FEE", "60000"))             # YOUR .env: 60000
        self.SLIPPAGE_PERCENT = float(os.getenv("SLIPPAGE", "3.0"))             # YOUR .env: 3.0%
        self.SELL_PERCENTAGE = float(os.getenv("SELL_PERCENTAGE", "0.997"))     # YOUR .env: 99.7%
        
        # Position management (YOUR exact .env values)
        self.PROFIT_TARGET_PCT = float(os.getenv("PROFIT_TARGET_PCT", "1.2"))   # YOUR .env: 1.2%
        self.STOP_LOSS_PCT = float(os.getenv("STOP_LOSS_PCT", "2.0"))           # YOUR .env: 2.0%
        self.MAX_HOLD_TIME = int(os.getenv("MAX_HOLD_TIME_SECONDS", "45"))      # YOUR .env: 45s
        self.MAX_POSITIONS = int(os.getenv("MAX_POSITIONS", "1"))               # YOUR .env: 1
        
        # Signal & filtering thresholds (YOUR exact .env values)
        self.MIN_SIGNAL_STRENGTH = float(os.getenv("MIN_SIGNAL_STRENGTH", "0.50"))     # YOUR .env: 0.50
        self.MIN_LIQUIDITY_USD = float(os.getenv("MIN_LIQUIDITY_USD", "150000"))       # YOUR .env: 150000
        self.MIN_VOLUME_5M = float(os.getenv("MIN_VOLUME_5M", "10000"))               # YOUR .env: 10000
        self.MIN_SAFETY_SCORE = int(os.getenv("MIN_SAFETY_SCORE", "55"))               # YOUR .env: 55
        
        # WebSocket configuration (YOUR exact .env values)
        self.WS_CONFIRMATION_TIMEOUT = float(os.getenv("WS_CONFIRMATION_TIMEOUT", "3.0"))  # YOUR .env: 3.0s
        self.BALANCE_CHANGE_THRESHOLD = 0.005  # Proven working threshold
        
        # Intervals (YOUR exact .env values)
        self.CHECK_INTERVAL = int(os.getenv("CHECK_INTERVAL", "30"))                        # YOUR .env: 30s
        self.POSITION_CHECK_INTERVAL = float(os.getenv("POSITION_CHECK_INTERVAL", "0.5"))  # YOUR .env: 0.5s
        self.DASHBOARD_UPDATE_INTERVAL = float(os.getenv("DASHBOARD_UPDATE_INTERVAL", "2.0"))  # YOUR .env: 2.0s
        self.PRICE_UPDATE_INTERVAL = float(os.getenv("PRICE_UPDATE_INTERVAL", "0.5"))      # YOUR .env: 0.5s
        
        # Blacklist (YOUR exact .env values)
        blacklist_str = os.getenv("BLACKLISTED_TOKENS", 
            "MONKEPHONE,SOL,SOLAMI,GIGA,USDC,USDT,WSOL,COPE,RAY,ORCA,JUP,$WIF,BONK,WIF,BOME,FIDA,SRM,MNGO,SAMO,STEP,TRUMP,BIDEN,KAMALA,MAGA,PUMP,DUMP,SCAM,TEST,PEPE,DOGE,SHIB,MEME,MOON,INU,FLOKI,BABY,SAFE,ELON,WOJAK,APU,CHAD,GIGACHAD,BASED,FARTCOIN,JLP,CBBTC,WBTC,USELESS,BAOBAO,JITOSOL,WETH,LAUNCHCOIN,AURA,LABUBU,GOR,SPX,NEXUS,OIL,KMNO,BAYC,JUPSOL,BUNKER,VERNUS,PYTH,GMT,GST,APT,SUI,FTT,BNB,ETH,BTC,OMNI,TRY")
        self.EXCLUDED_TOKENS = [token.strip().upper() for token in blacklist_str.split(",") if token.strip()]
        
        # 🔥 NEW: Dynamic blacklist management
        self.DYNAMIC_BLACKLIST_FILE = "dynamic_blacklist.json"
        self.DYNAMIC_BLACKLIST_DURATION = 24 * 3600  # 24 hours in seconds
        self.load_dynamic_blacklist()
        
        # Advanced settings (YOUR exact .env values)
        self.MIN_AGE_HOURS = float(os.getenv("MIN_AGE_HOURS", "24"))
        self.MAX_AGE_HOURS = float(os.getenv("MAX_AGE_HOURS", "2500"))
        self.MIN_PRICE_CHANGE_5M = float(os.getenv("MIN_PRICE_CHANGE_5M", "0.5"))
        self.MAX_PRICE_CHANGE_5M = float(os.getenv("MAX_PRICE_CHANGE_5M", "8.0"))
        self.MIN_TRANSACTIONS_5M = int(os.getenv("MIN_TRANSACTIONS_5M", "25"))
        self.MIN_UNIQUE_TRADERS_5M = int(os.getenv("MIN_UNIQUE_TRADERS_5M", "40"))
        
        console.print("[green]✅ YOUR EXACT CONFIG LOADED![/green]")
    
    def load_dynamic_blacklist(self):
        """Load dynamic blacklist from file"""
        self.dynamic_blacklist = {}  # {symbol: {reason: str, timestamp: float, mint: str}}
        
        try:
            if os.path.exists(self.DYNAMIC_BLACKLIST_FILE):
                with open(self.DYNAMIC_BLACKLIST_FILE, 'r') as f:
                    data = json.load(f)
                    current_time = time.time()
                    
                    # Remove expired entries
                    for symbol, entry in data.items():
                        if current_time - entry.get('timestamp', 0) < self.DYNAMIC_BLACKLIST_DURATION:
                            self.dynamic_blacklist[symbol] = entry
                    
                    console.print(f"[yellow]🚫 Loaded {len(self.dynamic_blacklist)} dynamic blacklist entries[/yellow]")
        except Exception as e:
            console.print(f"[yellow]⚠️ Could not load dynamic blacklist: {e}[/yellow]")
    
    def save_dynamic_blacklist(self):
        """Save dynamic blacklist to file"""
        try:
            with open(self.DYNAMIC_BLACKLIST_FILE, 'w') as f:
                json.dump(self.dynamic_blacklist, f, indent=2)
        except Exception as e:
            console.print(f"[yellow]⚠️ Could not save dynamic blacklist: {e}[/yellow]")
    
    def add_to_dynamic_blacklist(self, symbol: str, mint: str, reason: str):
        """Add token to dynamic blacklist"""
        self.dynamic_blacklist[symbol.upper()] = {
            "reason": reason,
            "timestamp": time.time(),
            "mint": mint
        }
        self.save_dynamic_blacklist()
        console.print(f"[red]🚫 BLACKLISTED {symbol}: {reason}[/red]")
    
    def is_dynamically_blacklisted(self, symbol: str) -> bool:
        """Check if token is in dynamic blacklist"""
        symbol_upper = symbol.upper()
        if symbol_upper in self.dynamic_blacklist:
            entry = self.dynamic_blacklist[symbol_upper]
            # Check if entry is still valid
            if time.time() - entry.get('timestamp', 0) < self.DYNAMIC_BLACKLIST_DURATION:
                return True
            else:
                # Remove expired entry
                del self.dynamic_blacklist[symbol_upper]
                self.save_dynamic_blacklist()
        return False
    
    def get_all_excluded_tokens(self) -> set:
        """Get all excluded tokens (static + dynamic)"""
        all_excluded = set(self.EXCLUDED_TOKENS)
        all_excluded.update(self.dynamic_blacklist.keys())
        return all_excluded


# Initialize global config
CONFIG = PerfectConfig()


class PerfectSignalFusion:
    """🔥 FUSION ENGINE - Combines GPU + Quantum + Token Discovery"""
    
    def __init__(self):
        # Initialize all signal components
        self.gpu_accelerator = None
        self.quantum_finder = None
        self.token_discovery = None
        
        # Fusion weights for combining signals
        self.fusion_weights = {
            "gpu_early_wave": 0.4,        # 40% weight to GPU early detection
            "quantum_quality": 0.35,      # 35% weight to quality filtering  
            "token_discovery": 0.25       # 25% weight to discovery volume
        }
        
        # Performance tracking
        self.fusion_signals_found = 0
        self.fusion_trades_executed = 0
        
    async def initialize(self):
        """Initialize all signal components with error handling"""
        console.print("🧠 Initializing FUSION Signal Engine...")
        
        # Check prerequisites
        missing_components = []
        if not GPU_ACCELERATOR_AVAILABLE:
            missing_components.append("GPU Accelerator")
        if not QUANTUM_FINDER_AVAILABLE:
            missing_components.append("Quantum Signal Finder")
        if not TOKEN_DISCOVERY_AVAILABLE:
            missing_components.append("Token Discovery")
        
        if missing_components:
            console.print(f"[yellow]⚠️ Missing components: {', '.join(missing_components)}[/yellow]")
            console.print("[yellow]FUSION will work with available components only[/yellow]")
        
        # Initialize GPU accelerator
        if GPU_ACCELERATOR_AVAILABLE:
            console.print("🎮 Loading GPU Accelerator...", end="")
            try:
                self.gpu_accelerator = GPUAcceleratorULTIMATE()
                console.print(" [green]✅[/green]")
            except Exception as e:
                console.print(f" [red]❌ {e}[/red]")
                self.gpu_accelerator = None
        else:
            console.print("🎮 GPU Accelerator: [yellow]UNAVAILABLE[/yellow]")
            self.gpu_accelerator = None
        
        # Initialize quantum signal finder
        if QUANTUM_FINDER_AVAILABLE:
            console.print("💎 Loading Quantum Signal Finder...", end="")
            try:
                self.quantum_finder = QuantumSignalFinder()
                await self.quantum_finder.initialize()
                console.print(" [green]✅[/green]")
            except Exception as e:
                console.print(f" [red]❌ {e}[/red]")
                self.quantum_finder = None
        else:
            console.print("💎 Quantum Signal Finder: [yellow]UNAVAILABLE[/yellow]")
            self.quantum_finder = None
        
        # Initialize token discovery
        if TOKEN_DISCOVERY_AVAILABLE:
            console.print("🔍 Loading Token Discovery...", end="")
            try:
                self.token_discovery = UltimateTokenDiscovery()
                await self.token_discovery.initialize()
                console.print(" [green]✅[/green]")
            except Exception as e:
                console.print(f" [red]❌ {e}[/red]")
                self.token_discovery = None
        else:
            console.print("🔍 Token Discovery: [yellow]UNAVAILABLE[/yellow]")
            self.token_discovery = None
        
        # Check if we have at least one component
        available_components = sum([
            self.gpu_accelerator is not None,
            self.quantum_finder is not None,
            self.token_discovery is not None
        ])
        
        if available_components == 0:
            console.print("[red]❌ NO SIGNAL COMPONENTS AVAILABLE - FUSION DISABLED[/red]")
    
    async def check_exit_conditions(self):
        """🎯 Check exit conditions using YOUR WORKING P&L calculation"""
        if not self.positions:
            return
        
        positions_to_close = []
        
        for symbol, position in self.positions.items():
            try:
                current_price_rt = self.price_tracker.get_current_price(symbol)
                entry_price = position.get('entry_price', 0)
                
                if current_price_rt > 0:
                    current_price = current_price_rt
                    source_text = "[RT]"
                else:
                    current_price = entry_price
                    source_text = "[ENTRY]"
                
                position['current_price'] = current_price
                
                if entry_price > 0 and current_price > 0:
                    pnl_pct = ((current_price - entry_price) / entry_price) * 100
                else:
                    pnl_pct = 0
                
                position['pnl_pct'] = pnl_pct
                position['hold_time_seconds'] = time.time() - position['entry_time']
                
                # Log significant P&L changes
                last_logged_pnl = position.get('last_logged_pnl', 0)
                pnl_change = abs(pnl_pct - last_logged_pnl)
                
                if pnl_change >= 0.5 or (last_logged_pnl < 0 and pnl_pct > 0) or (last_logged_pnl > 0 and pnl_pct < 0):
                    style = "green" if pnl_pct > 0 else "red"
                    emoji = "🚀" if pnl_pct > 0 else "📉"
                    console.print(f"{symbol}: [{style}]{emoji} {pnl_pct:+.2f}%[/{style}] (${current_price:.8f}) {source_text}")
                    position['last_logged_pnl'] = pnl_pct
                
                # Check exit conditions using YOUR working thresholds
                should_exit = False
                exit_reason = None
                
                if pnl_pct >= CONFIG.PROFIT_TARGET_PCT:
                    should_exit = True
                    exit_reason = "TAKE_PROFIT"
                    console.print(f"[green]🎯 {symbol}: PROFIT TARGET at {pnl_pct:+.2f}%[/green]")
                elif pnl_pct <= -CONFIG.STOP_LOSS_PCT:
                    should_exit = True
                    exit_reason = "STOP_LOSS"
                    console.print(f"[red]🛑 {symbol}: STOP LOSS at {pnl_pct:+.2f}%[/red]")
                elif position['hold_time_seconds'] >= CONFIG.MAX_HOLD_TIME:
                    should_exit = True
                    exit_reason = "MAX_HOLD_TIME"
                    console.print(f"⏰ {symbol}: TIME LIMIT ({position['hold_time_seconds']:.0f}s)")
                
                if should_exit:
                    positions_to_close.append((symbol, position, exit_reason))
                    
            except Exception as e:
                console.print(f"[red]❌ Exit check error for {symbol}: {e}[/red]")
        
        # Execute sells
        for symbol, position, exit_reason in positions_to_close:
            await self._execute_sell(symbol, position, exit_reason)
    
    async def _execute_sell(self, symbol: str, position: Dict, exit_reason: str):
        """💰 Execute sell using YOUR RUST LIBRARY - NO MORE PYTHON JUPITER!"""
        console.print(f"\n[bold]💰 SELLING {symbol}[/bold] - Reason: {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}[/red]")
            if symbol in self.positions:
                del self.positions[symbol]
            self.price_tracker.remove_token(symbol)
            return
        
        sell_amount = token_balance * CONFIG.SELL_PERCENTAGE
        max_retries = 3
        retry_count = 0
        
        while retry_count < max_retries:
            try:
                console.print(f"[yellow]🔄 Sell attempt {retry_count + 1}/{max_retries} via RUST[/yellow]")
                
                pre_balance = self.ws_listener.get_balance()
                if pre_balance == 0:
                    pre_balance = self.trader.get_sol_balance()
                
                sell_start = time.perf_counter()
                
                # 🦀 USE YOUR RUST LIBRARY FOR SELLING (not Python!)
                sell_sig = self.trader.sell_token_for_sol_via_jupiter(
                    token_mint=token_mint,
                    amount_tokens=sell_amount,
                    slippage_percent=CONFIG.SLIPPAGE_PERCENT,
                    priority_multiplier=1
                )
                
                sell_exec_time = (time.perf_counter() - sell_start) * 1000
                console.print(f"🦀 RUST sell executed: {sell_exec_time:.0f}ms - {sell_sig}")
                
                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 = post_balance - pre_balance
                    
                elif retry_count == max_retries - 1:
                    console.print("[yellow]⏰ WebSocket timeout - RUST verification[/yellow]")
                    await asyncio.sleep(2)
                    post_balance = self.trader.get_sol_balance()
                    sol_received = post_balance - pre_balance
                    
                    if sol_received > 0.001:
                        console.print(f"[green]✅ Sell verified via RUST - {sol_received:.6f} SOL received[/green]")
                        self.ws_listener.current_balance = post_balance
                    else:
                        console.print(f"[red]❌ Sell attempt {retry_count + 1} failed - retrying[/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_received - amount_sol_invested
                    net_pnl_pct = (net_pnl / amount_sol_invested) * 100
                else:
                    console.print(f"[yellow]⚠️ WARNING: Missing amount_sol for {symbol}, using fallback[/yellow]")
                    net_pnl = sol_received - CONFIG.TRADE_AMOUNT_SOL
                    net_pnl_pct = (net_pnl / CONFIG.TRADE_AMOUNT_SOL) * 100 if CONFIG.TRADE_AMOUNT_SOL > 0 else 0
                    amount_sol_invested = CONFIG.TRADE_AMOUNT_SOL
                
                # Stop tracking
                self.price_tracker.remove_token(symbol)
                
                # Record trade with FUSION + RUST data
                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": net_pnl,
                    "pnl_pct": net_pnl_pct,
                    "hold_time": position.get('hold_time_seconds', 0),
                    "exit_reason": exit_reason,
                    "signal_type": position.get('signal_type', 'FUSION'),
                    "signal_source": "FUSION_RUST",
                    "gpu_verified": position.get('gpu_verified', False),
                    "quantum_verified": position.get('quantum_verified', False),
                    "discovery_verified": position.get('discovery_verified', False),
                    "is_win": net_pnl > 0,
                    "sell_signature": sell_sig,
                    "execution_time_ms": sell_exec_time,
                    "confirming_websocket": source if confirmed else "RUST_RPC",
                    "trading_engine": "RUST_LIBRARY"
                }
                
                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 > 0:
                    self.trades_won += 1
                    self.best_trade = max(self.best_trade, net_pnl_pct)
                    console.print(f"[green]🎉 RUST FUSION WIN #{self.trades_won}! Best: {self.best_trade:.2f}%[/green]")
                else:
                    self.trades_lost += 1
                    self.worst_trade = min(self.worst_trade, net_pnl_pct)
                    console.print(f"[red]📉 Loss #{self.trades_lost}. Worst: {self.worst_trade:.2f}%[/red]")
                
                del self.positions[symbol]
                await self.update_dashboard()
                
                style = "green" if net_pnl > 0 else "red"
                emoji = "🏆" if net_pnl > 0 else "💀"
                console.print(f"[green]✅ RUST FUSION SELL:[/green] [{style}]{emoji} {net_pnl:+.6f} SOL ({net_pnl_pct:+.2f}%)[/{style}]")
                
                return  # SUCCESS
                
            except Exception as e:
                console.print(f"[red]💥 RUST Sell attempt {retry_count + 1} failed: {e}[/red]")
                retry_count += 1
                if retry_count < max_retries:
                    sell_amount = sell_amount * CONFIG.SELL_PERCENTAGE
                    await asyncio.sleep(1)
        
        # Force close if all retries failed
        console.print(f"[red]💀 FORCE CLOSE: All {max_retries} RUST attempts failed for {symbol}[/red]")
        self.price_tracker.remove_token(symbol)
        if symbol in self.positions:
            del self.positions[symbol]
        await self.update_dashboard()
    
    async def update_dashboard(self):
        """📊 Update dashboard with FUSION + RUST data - MAINTAINS YOUR BRIDGE COMPATIBILITY"""
        try:
            current_time = time.time()
            
            # Calculate values
            total_account_value, liquid_sol, total_invested_in_positions = self.calculate_total_account_value()
            
            session_duration = current_time - self.session_start_time
            session_hours = session_duration / 3600
            session_minutes = (session_duration % 3600) / 60
            
            # P&L calculations
            realized_pnl = sum(trade.get('actual_pnl', 0) for trade in self.completed_trades)
            
            total_unrealized_pnl = 0
            for pos in self.positions.values():
                amount_sol = pos.get('amount_sol', 0)
                entry_price = pos.get('entry_price', 0)
                current_price = pos.get('current_price', entry_price)
                
                if entry_price > 0:
                    price_change_pct = ((current_price - entry_price) / entry_price) * 100
                    unrealized_pnl = amount_sol * (price_change_pct / 100)
                    total_unrealized_pnl += unrealized_pnl
            
            session_pnl = total_account_value - self.session_start_total_value
            session_pnl_pct = (session_pnl / self.session_start_total_value * 100) if self.session_start_total_value > 0 else 0
            
            # Win rate
            total_closed_trades = self.trades_won + self.trades_lost
            win_rate = (self.trades_won / total_closed_trades * 100) if total_closed_trades > 0 else 0
            
            # Performance metrics
            avg_execution_time = statistics.mean(self.execution_times) if self.execution_times else 0
            fastest_execution = min(self.execution_times) if self.execution_times else 0
            avg_confirmation_time = statistics.mean(self.confirmation_times) if self.confirmation_times else 0
            
            # Active position data with FUSION + RUST info
            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:
                    price_change_pct = ((current_price - entry_price) / entry_price) * 100
                    amount_sol = pos.get('amount_sol', CONFIG.TRADE_AMOUNT_SOL)
                    unrealized_pnl_position = amount_sol * (price_change_pct / 100)
                else:
                    price_change_pct = 0
                    unrealized_pnl_position = 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": price_change_pct,
                    "unrealized_pnl": unrealized_pnl_position,
                    "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', 'FUSION'),
                    "signal_source": pos.get('signal_source', 'FUSION_RUST'),
                    "signal_strength": pos.get('signal_strength', 0),
                    "gpu_verified": pos.get('gpu_verified', False),
                    "quantum_verified": pos.get('quantum_verified', False),
                    "discovery_verified": pos.get('discovery_verified', False),
                    "trading_engine": "RUST_LIBRARY"
                }
            
            # 🔥 CRITICAL: Build dashboard data with YOUR EXACT BRIDGE COMPATIBILITY
            dashboard_data = {
                "timestamp": current_time,
                
                # Balance tracking (YOUR bridge needs these exact keys)
                "balance": total_account_value,
                "liquid_sol": liquid_sol,
                "total_invested": total_invested_in_positions,
                "session_start_balance": self.session_start_total_value,
                "trading_active": self.running,
                
                # Trade statistics (YOUR bridge compatibility)
                "total_trades": self.trades_executed,
                "trades_executed": self.trades_executed,
                "trades_closed": total_closed_trades,
                "trades_won": self.trades_won,
                "trades_lost": self.trades_lost,
                "winning_trades": self.trades_won,
                "losing_trades": self.trades_lost,
                "win_rate": win_rate,
                
                # P&L tracking (YOUR bridge needs these)
                "session_pnl": session_pnl,
                "session_pnl_pct": session_pnl_pct,
                "realized_pnl": realized_pnl,
                "unrealized_pnl": total_unrealized_pnl,
                "total_pnl": session_pnl,
                "best_trade": self.best_trade,
                "worst_trade": self.worst_trade,
                "largest_win": max([t.get('actual_pnl', 0) for t in self.completed_trades] + [0]),
                "largest_loss": abs(min([t.get('actual_pnl', 0) for t in self.completed_trades] + [0])),
                
                # Session data (YOUR bridge compatibility)
                "session_hours": session_hours,
                "session_minutes": session_minutes,
                "session_start_time": self.session_start_time,
                "session_duration": session_duration,
                "trades_per_hour": (self.trades_executed / max(session_hours, 0.01)),
                
                # Position data (YOUR bridge needs these)
                "active_position": bool(self.positions),
                "active_positions": len(self.positions),
                "position": active_position_data,
                "positions": self.positions,
                
                # Trade history (YOUR bridge compatibility)
                "recent_trades": self.recent_trades[-5:],
                "completed_trades": self.completed_trades,
                
                # System status (YOUR bridge needs these)
                "websocket_active": self.ws_listener.is_connected(),
                "websocket_status": self.ws_listener.get_connection_status(),
                "current_endpoint": CONFIG.PRIMARY_RPC_URL.split('/')[-1] if CONFIG.PRIMARY_RPC_URL else "N/A",
                
                # WebSocket stats
                "ws_confirmations": self.ws_listener.total_updates,
                "primary_wins": self.ws_listener.primary_wins,
                "secondary_wins": self.ws_listener.secondary_wins,
                
                # Performance metrics
                "avg_execution_time": avg_execution_time,
                "fastest_execution": fastest_execution,
                "avg_confirmation_time": avg_confirmation_time,
                
                # Price tracking stats
                "price_tracking_active": self.price_tracker.running,
                "tracked_tokens": len(self.price_tracker.tracking_tokens),
                "price_alerts": list(self.price_tracker.price_alerts)[-5:],
                
                # 🔥 NEW: FUSION + RUST ENGINE STATS
                "fusion_signals_found": self.signal_fusion.fusion_signals_found if self.signal_fusion else 0,
                "fusion_trades_executed": self.signal_fusion.fusion_trades_executed if self.signal_fusion else 0,
                "signal_engine": "FUSION_RUST_OPTIMIZED",
                "trading_engine": "RUST_LIBRARY",
                "gpu_accelerator_active": GPU_ACCELERATOR_AVAILABLE,
                "quantum_finder_active": QUANTUM_FINDER_AVAILABLE,
                "token_discovery_active": TOKEN_DISCOVERY_AVAILABLE,
                "rust_library_active": RUST_TRADER_AVAILABLE,
                
                # Configuration (YOUR bridge needs these exact keys)
                "config": {
                    "trade_amount_sol": CONFIG.TRADE_AMOUNT_SOL,
                    "profit_target_pct": CONFIG.PROFIT_TARGET_PCT,
                    "stop_loss_pct": CONFIG.STOP_LOSS_PCT,
                    "max_hold_time": CONFIG.MAX_HOLD_TIME,
                    "min_signal_strength": CONFIG.MIN_SIGNAL_STRENGTH,
                    "balance_change_threshold": CONFIG.BALANCE_CHANGE_THRESHOLD,
                    "compute_limit": CONFIG.COMPUTE_LIMIT,
                    "priority_fee": CONFIG.PRIORITY_FEE,
                    "price_update_interval": CONFIG.PRICE_UPDATE_INTERVAL,
                    "slippage_percent": CONFIG.SLIPPAGE_PERCENT,
                    "sell_percentage": CONFIG.SELL_PERCENTAGE
                },
                
                # Meta (YOUR bridge compatibility)
                "last_update": datetime.now().strftime('%I:%M:%S %p'),
                "status": "🔥 FUSION_RUST_ACTIVE" if self.running else "🛑 STOPPED",
                "version": "PERFECT_FUSION_RUST_QUANTUM_BEAST",
                "update_count": self.dashboard_update_count
            }
            
            self.dashboard_update_count += 1
            
            # 🔥 CRITICAL: Write dashboard data atomically for YOUR bridge
            temp_file = "dashboard_data.json.tmp"
            with open(temp_file, "w") as f:
                json.dump(dashboard_data, f, indent=2)
            
            # Atomic move to ensure YOUR bridge never reads partial data
            if os.path.exists("dashboard_data.json"):
                os.remove("dashboard_data.json")
            os.rename(temp_file, "dashboard_data.json")
            
            # Log updates every 10 iterations
            if self.dashboard_update_count % 10 == 0:
                console.print(f"📊 RUST FUSION Update #{self.dashboard_update_count}: "
                             f"Total Value: {total_account_value:.6f} SOL | "
                             f"Liquid: {liquid_sol:.6f} SOL | "
                             f"Session P&L: {session_pnl:+.6f} SOL ({session_pnl_pct:+.2f}%)")
            
        except Exception as e:
            console.print(f"[red]📊 Dashboard update error: {e}[/red]")
            traceback.print_exc()
    
    async def dashboard_update_loop(self):
        """📊 Continuous dashboard update loop"""
        while self.running:
            try:
                await self.update_dashboard()
                await asyncio.sleep(CONFIG.DASHBOARD_UPDATE_INTERVAL)
            except asyncio.CancelledError:
                break
            except Exception as e:
                console.print(f"[yellow]📊 Dashboard loop error: {e}[/yellow]")
                await asyncio.sleep(CONFIG.DASHBOARD_UPDATE_INTERVAL)
    
    async def run_trading_loop(self):
        """🔄 Main trading loop with FUSION signals + RUST execution"""
        console.print("\n[bold]🚀 STARTING RUST FUSION QUANTUM BEAST TRADING LOOP 🚀[/bold]")
        
        # Start dashboard update loop
        dashboard_task = asyncio.create_task(self.dashboard_update_loop())
        
        try:
            last_scan_time = 0
            
            while not self.shutdown_event.is_set():
                try:
                    current_time = time.time()
                    
                    # Scan for FUSION opportunities using YOUR working timing
                    if current_time - last_scan_time >= CONFIG.CHECK_INTERVAL:
                        if len(self.positions) < CONFIG.MAX_POSITIONS:
                            console.print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔍 Scanning for RUST FUSION opportunities...")
                            
                            # Get current total account value
                            total_value, liquid_sol, invested_sol = self.calculate_total_account_value()
                            console.print(f"💰 Total Account Value: {total_value:.6f} SOL (Liquid: {liquid_sol:.6f}, Invested: {invested_sol:.6f})")
                            
                            # Find FUSION opportunities
                            opportunities = await self.find_opportunities()
                            
                            if opportunities:
                                best_signal = opportunities[0]
                                if best_signal['symbol'] not in self.positions:
                                    console.print(f"🦀 Executing RUST FUSION trade for {best_signal['symbol']}...")
                                    success = await self.execute_trade(best_signal)
                                    if success:
                                        await asyncio.sleep(3)
                        
                        last_scan_time = current_time
                    
                    # Check exit conditions
                    await self.check_exit_conditions()
                    
                    # Sleep using YOUR interval
                    await asyncio.sleep(CONFIG.POSITION_CHECK_INTERVAL)
                    
                except KeyboardInterrupt:
                    console.print("\n[yellow]⚠️ Shutdown requested by user[/yellow]")
                    self.shutdown_event.set()
                except Exception as e:
                    console.print(f"[red]💥 Trading loop error: {e}[/red]")
                    await asyncio.sleep(5)
        finally:
            dashboard_task.cancel()
            try:
                await dashboard_task
            except asyncio.CancelledError:
                pass
    
    async def start(self):
        """🚀 Start the RUST FUSION Quantum Beast"""
        self.running = True
        try:
            await self.initialize()
            await self.run_trading_loop()
        except KeyboardInterrupt:
            console.print("\n[yellow]⚠️ Shutting down RUST FUSION Quantum Beast...[/yellow]")
        finally:
            self.running = False
            await self.update_dashboard()  # Final dashboard update
            if self.ws_listener:
                await self.ws_listener.close()
            if self.signal_fusion:
                await self.signal_fusion.close()
            if hasattr(self, 'price_tracker_task'):
                self.price_tracker_task.cancel()


# Signal handlers
def signal_handler(signum, frame):
    console.print(f"\n[yellow]⚠️ Received signal {signum} - initiating graceful shutdown[/yellow]")


async def main():
    """🏆 Main entry point for RUST FUSION Quantum Beast"""
    # Setup signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    console.print("\n" + "🔥" * 100)
    console.print("🏆 RUST FUSION QUANTUM BEAST - ULTIMATE OPTIMIZED TRADING! 🏆".center(100))
    console.print("💎 YOUR EXACT VALUES + RUST LIBRARY + FUSION SIGNALS ENGINE 💎".center(100))
    console.print("🔥" * 100 + "\n")
    
    # Check dependencies
    console.print("🔍 CHECKING DEPENDENCIES:")
    
    critical_missing = []
    optional_missing = []
    
    if not RUST_TRADER_AVAILABLE:
        critical_missing.append("🦀 Rust Trading Engine (solana_rust_bot)")
    else:
        console.print("   ✅ 🦀 Rust Trading Engine")
    
    if not WEBSOCKETS_AVAILABLE:
        optional_missing.append("websockets (pip install websockets)")
    else:
        console.print("   ✅ WebSockets")
    
    if not GPU_ACCELERATOR_AVAILABLE:
        optional_missing.append("GPU Accelerator")
    else:
        console.print("   ✅ GPU Accelerator")
    
    if not QUANTUM_FINDER_AVAILABLE:
        optional_missing.append("Quantum Signal Finder")
    else:
        console.print("   ✅ Quantum Signal Finder")
    
    if not TOKEN_DISCOVERY_AVAILABLE:
        optional_missing.append("Token Discovery")
    else:
        console.print("   ✅ Token Discovery")
    
    if not SAFETY_VALIDATOR_AVAILABLE:
        optional_missing.append("Safety Validator")
    else:
        console.print("   ✅ Safety Validator")
    
    if torch is None:
        optional_missing.append("PyTorch (pip install torch)")
    else:
        console.print(f"   ✅ PyTorch (GPU: {'Available' if GPU_AVAILABLE else 'Not Available'})")
    
    if not REQUESTS_AVAILABLE:
        optional_missing.append("requests (pip install requests)")
    else:
        console.print("   ✅ Requests")
    
    # Handle critical missing dependencies
    if critical_missing:
        console.print(f"\n[red]❌ CRITICAL DEPENDENCIES MISSING:[/red]")
        for dep in critical_missing:
            console.print(f"   ❌ {dep}")
        console.print("\n[red]Cannot continue without Rust library![/red]")
        console.print("[red]Run: maturin develop --release[/red]")
        return
    
    # Show optional missing dependencies
    if optional_missing:
        console.print(f"\n[yellow]⚠️ OPTIONAL DEPENDENCIES MISSING:[/yellow]")
        for dep in optional_missing:
            console.print(f"   ⚠️ {dep}")
        console.print("[yellow]FUSION will work with reduced functionality[/yellow]")
    
    console.print("\n🎯 RUST FUSION FEATURES:")
    console.print("   ✅ YOUR EXACT .env trading parameters (ALL VALUES UNCHANGED)")
    console.print("   ✅ YOUR EXACT WebSocket confirmation system (3.0s timeout, 0.005 SOL threshold)")
    console.print("   ✅ 🦀 RUST LIBRARY execution (NO MORE PYTHON JUPITER CALLS!)")
    console.print("   ✅ YOUR EXACT position management (1.2% profit, 2.0% stop, 45s max hold)")
    console.print("   ✅ YOUR EXACT intervals (30s check, 0.5s position check)")
    console.print("   ✅ YOUR EXACT blacklist (comprehensive token exclusions)")
    console.print("   ✅ YOUR EXACT safety requirements (min score 55)")
    console.print("   ✅ PERFECT balance tracking (Total Account Value = Liquid + Position Values)")
    console.print("   ✅ PERFECT P&L calculation (Real gains/losses only)")
    console.print("   ✅ PERFECT dashboard.json compatibility (YOUR bridge will work)")
    console.print("")
    console.print("🦀 RUST OPTIMIZATIONS:")
    console.print("   🚀 Optimized Jupiter transaction building (fixes 'base64 encoded too large')")
    console.print("   ⚡ Fast blockhash caching system")
    console.print("   🔄 Automatic retry logic with fresh blockhashes")
    console.print("   💎 Token account management")
    console.print("   🛡️ Advanced error handling and recovery")
    console.print("")
    console.print("🔥 FUSION ENGINE:")
    console.print("   🎮 GPU Accelerator: EARLY WAVE detection (PRE-WAVE + volume analysis)")
    console.print("   💎 Quantum Signal Finder: HIGH QUALITY filtering (production scoring)")
    console.print("   🔍 Token Discovery: ACTIVE TRADING detection (volume + momentum)")
    console.print("   🔥 FUSION LOGIC: Only trades when 2+ systems agree (MAXIMUM confidence)")
    console.print("   🛡️ Safety Validation: Enhanced Helius safety checks on ALL signals")
    console.print("")
    console.print("🎯 FUSION SCORING:")
    console.print("   • 40% GPU Early Wave Score (timing)")
    console.print("   • 35% Quantum Quality Score (safety)")
    console.print("   • 25% Discovery Volume Score (activity)")
    console.print("   • Only executes when fusion score >= YOUR min signal strength")
    
    console.print(f"\n🚀 Starting RUST FUSION Quantum Beast in 3 seconds...")
    console.print("💰 YOUR EXACT .ENV PARAMETERS + RUST OPTIMIZATIONS + FUSION SIGNALS = LEGENDARY SUCCESS! 💰")
    time.sleep(3)
    
    # Initialize and start RUST FUSION Quantum Beast
    fusion_beast = PerfectFusionQuantumBeast()
    await fusion_beast.start()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        console.print("\n[yellow]⚠️ Program interrupted by user[/yellow]")
    except Exception as e:
        console.print(f"\n[red]💥 Fatal error: {e}[/red]")
        traceback.print_exc()
        
        console.print(f"[green]🔥 FUSION ENGINE READY with {available_components}/3 components![/green]")
        return True
    
    async def find_fusion_opportunities(self) -> List[Dict]:
        """🌊 FUSION LOGIC: Combine available signal sources for ULTIMATE accuracy"""
        console.print("\n🔍 FUSION SCAN: Finding opportunities with available systems...")
        
        try:
            discovered_tokens = []
            
            # Step 1: Token Discovery (if available)
            if self.token_discovery:
                console.print("🔍 Step 1: Token Discovery...")
                try:
                    discovered_tokens = await self.token_discovery.discover_tokens()
                    if discovered_tokens:
                        console.print(f"🔍 Found {len(discovered_tokens)} actively traded tokens")
                    else:
                        console.print("[yellow]🔍 No actively traded tokens found[/yellow]")
                except Exception as e:
                    console.print(f"[yellow]🔍 Token Discovery error: {e}[/yellow]")
                    discovered_tokens = []
            else:
                console.print("🔍 Step 1: Token Discovery [yellow]SKIPPED (unavailable)[/yellow]")
            
            # Step 2: Quantum Quality Filter - Get high-quality tokens
            quantum_opportunities = []
            if self.quantum_finder:
                console.print("💎 Step 2: Quantum Quality Filtering...")
                try:
                    quantum_opportunities = await self.quantum_finder.find_opportunities(limit=10)
                    if quantum_opportunities:
                        console.print(f"💎 {len(quantum_opportunities)} tokens passed quality filters")
                    else:
                        console.print("[yellow]💎 No quality opportunities found[/yellow]")
                except Exception as e:
                    console.print(f"[yellow]💎 Quantum Finder error: {e}[/yellow]")
                    quantum_opportunities = []
            else:
                console.print("💎 Step 2: Quantum Quality Filtering [yellow]SKIPPED (unavailable)[/yellow]")
            
            # Step 3: If we have no tokens yet, use a fallback method
            if not discovered_tokens and not quantum_opportunities:
                console.print("🔄 Step 3: Fallback Token Collection...")
                # Create basic token data from quantum finder's discovered tokens
                if self.quantum_finder and hasattr(self.quantum_finder, 'discovered_tokens'):
                    quantum_opportunities = self.quantum_finder.discovered_tokens[:10]
                    console.print(f"🔄 Using {len(quantum_opportunities)} quantum discovered tokens")
                else:
                    console.print("[yellow]🔄 No fallback tokens available[/yellow]")
                    return []
            
            # Step 4: GPU Early Wave Detection - Find PRE-WAVE signals
            console.print("🎮 Step 4: GPU Early Wave Detection...")
            
            # Combine available tokens
            all_tokens = []
            token_mints = set()
            
            # Add discovered tokens (if any)
            for token in discovered_tokens:
                mint = token.get('mint', token.get('token_mint', ''))
                if mint and mint not in token_mints:
                    all_tokens.append(token)
                    token_mints.add(mint)
            
            # Add quantum opportunities (if any)
            for token in quantum_opportunities:
                mint = token.get('mint', token.get('token_mint', ''))
                if mint and mint not in token_mints:
                    all_tokens.append(token)
                    token_mints.add(mint)
            
            if not all_tokens:
                console.print("[yellow]🎮 No tokens available for GPU analysis[/yellow]")
                return []
            
            # GPU scan for early waves (if available)
            gpu_signals = []
            if self.gpu_accelerator:
                try:
                    # Use enhanced blacklist (static + dynamic)
                    all_excluded_tokens = CONFIG.get_all_excluded_tokens()
                    gpu_signals = self.gpu_accelerator.scan_market(all_tokens, list(all_excluded_tokens))
                    if gpu_signals:
                        console.print(f"🎮 GPU found {len(gpu_signals)} early wave signals")
                    else:
                        console.print("[yellow]🎮 No GPU signals found[/yellow]")
                except Exception as e:
                    console.print(f"[yellow]🎮 GPU Accelerator error: {e}[/yellow]")
                    gpu_signals = []
            else:
                console.print("🎮 Step 4: GPU Early Wave Detection [yellow]SKIPPED (unavailable)[/yellow]")
                # If no GPU, use quantum opportunities as signals
                gpu_signals = quantum_opportunities
            
            if not gpu_signals:
                console.print("[yellow]🔥 No signals available for fusion analysis[/yellow]")
                return []
            
            # Step 5: FUSION - Combine signals where they overlap
            console.print("🔥 Step 5: FUSION ANALYSIS...")
            fusion_signals = []
            
            for gpu_signal in gpu_signals:
                gpu_mint = gpu_signal.get('mint', gpu_signal.get('token_mint', ''))
                
                # Find matching quantum signal
                quantum_match = None
                if quantum_opportunities:
                    for q_opp in quantum_opportunities:
                        q_mint = q_opp.get('mint', q_opp.get('token_mint', ''))
                        if q_mint == gpu_mint:
                            quantum_match = q_opp
                            break
                
                # Find matching discovery signal  
                discovery_match = None
                if discovered_tokens:
                    for d_token in discovered_tokens:
                        d_mint = d_token.get('mint', d_token.get('token_mint', ''))
                        if d_mint == gpu_mint:
                            discovery_match = d_token
                            break
                
                # ADAPTIVE FUSION SCORING - Works with available components
                gpu_score = gpu_signal.get('early_wave_score', gpu_signal.get('signal_strength', 0.5))
                
                # Adjust weights based on available components
                available_components = sum([
                    self.gpu_accelerator is not None,
                    self.quantum_finder is not None,
                    self.token_discovery is not None
                ])
                
                if available_components == 3:
                    # Full fusion
                    gpu_weight = 0.4
                    quantum_weight = 0.35
                    discovery_weight = 0.25
                elif available_components == 2:
                    if self.token_discovery is None:
                        # No discovery
                        gpu_weight = 0.6
                        quantum_weight = 0.4
                        discovery_weight = 0.0
                    else:
                        # Fallback weights
                        gpu_weight = 0.5
                        quantum_weight = 0.3
                        discovery_weight = 0.2
                else:
                    # Single component
                    gpu_weight = 1.0
                    quantum_weight = 0.0
                    discovery_weight = 0.0
                
                # Calculate component scores
                gpu_component_score = gpu_score * gpu_weight
                
                quantum_component_score = 0
                if quantum_match and self.quantum_finder:
                    quantum_score = quantum_match.get('production_score', quantum_match.get('signal_strength', 0.5))
                    quantum_component_score = quantum_score * quantum_weight
                
                discovery_component_score = 0
                if discovery_match and self.token_discovery:
                    volume_5m = discovery_match.get('volume_5m', 0)
                    discovery_score = min(volume_5m / 50000, 1.0) if volume_5m > 0 else 0.3
                    discovery_component_score = discovery_score * discovery_weight
                
                fusion_score = gpu_component_score + quantum_component_score + discovery_component_score
                
                # Lower threshold for reduced components
                min_threshold = CONFIG.MIN_SIGNAL_STRENGTH * (available_components / 3.0)
                
                # Only proceed if fusion score is high enough
                if fusion_score >= min_threshold:
                    
                    # Create FUSION signal with best data from available sources
                    fusion_signal = {
                        **gpu_signal,  # Base signal data
                        "fusion_score": fusion_score,
                        "signal_source": "FUSION",
                        "gpu_type": gpu_signal.get("signal_type", "WAVE"),
                        "gpu_score": gpu_component_score,
                        "quantum_verified": quantum_match is not None,
                        "discovery_verified": discovery_match is not None,
                        "available_components": available_components,
                        "fusion_weights": {
                            "gpu": gpu_weight,
                            "quantum": quantum_weight,
                            "discovery": discovery_weight
                        }
                    }
                    
                    # Add quantum data if available
                    if quantum_match:
                        fusion_signal.update({
                            "production_score": quantum_match.get('production_score', 0),
                            "safety_score": quantum_match.get('safety_score', 0),
                            "quantum_signals": quantum_match.get('signals', [])
                        })
                    
                    # Add discovery data if available
                    if discovery_match:
                        fusion_signal.update({
                            "discovery_volume_5m": discovery_match.get('volume_5m', 0),
                            "discovery_momentum": discovery_match.get('momentum', 0),
                            "discovery_trend": discovery_match.get('trend', 'NEUTRAL')
                        })
                    
                    fusion_signals.append(fusion_signal)
                    self.fusion_signals_found += 1
            
            # Sort by fusion score
            fusion_signals.sort(key=lambda x: x["fusion_score"], reverse=True)
            
            if fusion_signals:
                console.print(f"[green]🔥 FUSION RESULT: {len(fusion_signals)} verified signals ({available_components}/3 components)![/green]")
                
                # Log top fusion signals
                for i, signal in enumerate(fusion_signals[:3], 1):
                    symbol = signal.get('symbol', 'UNKNOWN')
                    fusion_score = signal.get('fusion_score', 0)
                    gpu_type = signal.get('gpu_type', 'UNKNOWN')
                    quantum_verified = signal.get('quantum_verified', False)
                    discovery_verified = signal.get('discovery_verified', False)
                    
                    verification_badges = []
                    if quantum_verified:
                        verification_badges.append("💎QUALITY")
                    if discovery_verified:
                        verification_badges.append("🔍ACTIVE")
                    if not verification_badges:
                        verification_badges.append("🎮GPU_ONLY")
                    
                    badges_str = " ".join(verification_badges)
                    
                    console.print(f"  #{i} 🏆 {symbol}: {gpu_type} (fusion: {fusion_score:.3f}) {badges_str}")
            else:
                console.print(f"[yellow]🔥 No fusion signals found with {available_components}/3 components[/yellow]")
            
            return fusion_signals
            
        except Exception as e:
            console.print(f"[red]💥 Fusion error: {e}[/red]")
            traceback.print_exc()
            return []
    
    async def close(self):
        """Close all signal components"""
        if self.quantum_finder:
            await self.quantum_finder.close()
        if self.token_discovery:
            await self.token_discovery.close()


class PerfectWebSocketMonitor:
    """🔥 YOUR WORKING WebSocket system - PROVEN TO WORK"""
    
    def __init__(self, wallet_address: str, api_key: str):
        self.wallet_address = wallet_address
        self.api_key = api_key
        
        # WebSocket URLs
        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
        
        # Balance tracking (YOUR WORKING METHOD)
        self.balance_updates = deque(maxlen=100)
        self.current_balance = 0.0
        self.last_balance = None
        
        # 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
        
        # Headers for compatibility
        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):
        """Connect to WebSocket endpoints - YOUR WORKING METHOD"""
        console.print("[WS] 🚀 Initializing YOUR working WebSocket system...")
        
        # Start both connections
        tasks = [
            asyncio.create_task(self._connect_primary()),
            asyncio.create_task(self._connect_secondary())
        ]
        
        # Wait for at least one to connect
        try:
            await asyncio.wait_for(self._wait_for_any_connection(), timeout=15)
            console.print("[green]✅ YOUR working WebSocket system ready![/green]")
            
            # Start keep-alive tasks
            asyncio.create_task(self._keep_primary_alive())
            asyncio.create_task(self._keep_secondary_alive())
            
            return True
            
        except asyncio.TimeoutError:
            console.print("[yellow]⏰ WebSocket timeout - RPC fallback ready[/yellow]")
            
            # Still start keep-alive tasks
            asyncio.create_task(self._keep_primary_alive())
            asyncio.create_task(self._keep_secondary_alive())
            
            return False
    
    async def _wait_for_any_connection(self):
        """Wait for at least one connection"""
        while not (self.primary_healthy or self.secondary_healthy):
            await asyncio.sleep(0.1)
    
    async def _connect_primary(self):
        """Connect to primary WebSocket"""
        if not WEBSOCKETS_AVAILABLE:
            console.print("[PRIMARY] ❌ websockets library not available")
            return
            
        retry_count = 0
        max_retries = 3
        
        while retry_count < max_retries:
            try:
                console.print(f"[PRIMARY] 🔌 Connecting... (attempt {retry_count + 1})")
                
                import websockets
                self.primary_ws = await websockets.connect(
                    self.primary_url,
                    extra_headers=self.headers if "helius" not in self.primary_url else {},
                    ping_interval=20,
                    ping_timeout=10
                )
                
                await self._subscribe_to_account(self.primary_ws, "PRIMARY")
                self.primary_healthy = True
                console.print("[green][PRIMARY] ✅ Connected and Subscribed[/green]")
                
                await self._listen_primary()
                
            except Exception as e:
                console.print(f"[PRIMARY] ❌ Connection failed: {e}")
                self.primary_healthy = False
                retry_count += 1
                
                if retry_count < max_retries:
                    await asyncio.sleep(2 ** retry_count)
    
    async def _connect_secondary(self):
        """Connect to secondary WebSocket"""
        if not WEBSOCKETS_AVAILABLE:
            console.print("[SECONDARY] ❌ websockets library not available")
            return
            
        await asyncio.sleep(2)  # Stagger connections
        retry_count = 0
        max_retries = 3
        
        while retry_count < max_retries:
            try:
                console.print(f"[SECONDARY] 🔌 Connecting... (attempt {retry_count + 1})")
                
                import websockets
                self.secondary_ws = await websockets.connect(
                    self.secondary_url,
                    ping_interval=20,
                    ping_timeout=10
                )
                
                await self._subscribe_to_account(self.secondary_ws, "SECONDARY")
                self.secondary_healthy = True
                console.print("[green][SECONDARY] ✅ Connected and Subscribed[/green]")
                
                await self._listen_secondary()
                
            except Exception as e:
                console.print(f"[SECONDARY] ❌ Connection failed: {e}")
                self.secondary_healthy = False
                retry_count += 1
                
                if retry_count < max_retries:
                    await asyncio.sleep(2 ** retry_count)
    
    async def _subscribe_to_account(self, ws, label: str):
        """Subscribe to account updates"""
        subscribe_msg = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "accountSubscribe",
            "params": [
                self.wallet_address,
                {"encoding": "base64", "commitment": "processed"}
            ]
        }
        
        await ws.send(json.dumps(subscribe_msg))
        response = await ws.recv()
        result = json.loads(response)
        
        if "result" in result:
            console.print(f"[{label}] 🎯 Account Subscription Active (ID: {result['result']})")
        else:
            raise Exception(f"Subscription failed: {result}")
    
    async def _listen_primary(self):
        """Listen for primary WebSocket updates"""
        try:
            async for message in self.primary_ws:
                await self._process_balance_update(message, "PRIMARY")
        except Exception:
            self.primary_healthy = False
    
    async def _listen_secondary(self):
        """Listen for secondary WebSocket updates"""
        try:
            async for message in self.secondary_ws:
                await self._process_balance_update(message, "SECONDARY")
        except Exception:
            self.secondary_healthy = False
    
    async def _process_balance_update(self, message: str, source: str):
        """🔥 YOUR WORKING BALANCE DETECTION - IMPROVED for sells"""
        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 = value["lamports"] / 1_000_000_000
                    old_balance = self.current_balance
                    
                    self.current_balance = new_balance
                    self.total_updates += 1
                    
                    if old_balance > 0:
                        balance_change = new_balance - old_balance
                        
                        # 🔥 IMPROVED: Lower threshold for sell confirmations
                        detection_threshold = CONFIG.BALANCE_CHANGE_THRESHOLD * 0.8  # 0.004 SOL for sells
                        
                        if abs(balance_change) >= detection_threshold:
                            change_style = "green" if balance_change > 0 else "red"
                            
                            # Determine trade type with better detection
                            if balance_change <= -detection_threshold:
                                trade_type = "🚀 BUY CONFIRMED"
                            elif balance_change >= detection_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
                    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:
            pass  # Silent fail for message parsing
    
    async def _keep_primary_alive(self):
        """Keep primary connection alive"""
        while True:
            try:
                if not self.primary_healthy:
                    await self._connect_primary()
                await asyncio.sleep(30)
            except Exception:
                await asyncio.sleep(30)
    
    async def _keep_secondary_alive(self):
        """Keep secondary connection alive"""
        while True:
            try:
                if not self.secondary_healthy:
                    await self._connect_secondary()
                await asyncio.sleep(30)
            except Exception:
                await asyncio.sleep(30)
    
    async def wait_for_balance_change(self, timeout=None):
        """🏆 YOUR WORKING 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 liquid SOL balance"""
        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"
    
    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 PerfectPriceTracker:
    """🔥 YOUR WORKING 0.5s price tracking system"""
    
    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))
        
    def add_token(self, symbol, mint_address, entry_price):
        """Add token to YOUR 0.5s tracking system"""
        self.tracking_tokens[symbol] = mint_address
        self.current_prices[symbol] = entry_price
        self.last_prices[symbol] = entry_price
        console.print(f"[TRACKER] 📊 Started 0.5s REAL-TIME 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]
            console.print(f"[TRACKER] 🛑 Stopped tracking {symbol}")
    
    def get_current_price(self, symbol):
        """Get current price (INSTANT ACCESS)"""
        return self.current_prices.get(symbol, 0)
    
    async def fetch_price(self, session, mint_address):
        """Fetch price from DexScreener"""
        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"]:
                    pair = data["pairs"][0]
                    price = 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 0.5s precision"""
        if not self.tracking_tokens:
            return
        
        try:
            connector = aiohttp.TCPConnector(ssl=False, limit=3)
            timeout = aiohttp.ClientTimeout(total=5)
            
            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
                            
                            # 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) >= 1.0:  # 1% threshold
                                    direction = "📈" if price_change_pct > 0 else "📉"
                                    style = "green" if price_change_pct > 0 else "red"
                                    
                                    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
                            
                    except Exception:
                        continue
                        
        except Exception:
            pass
    
    async def start_tracking(self):
        """Start YOUR 0.5s price tracking loop"""
        self.running = True
        console.print("[TRACKER] 🚀 0.5s REAL-TIME TRACKING STARTED!")
        
        while self.running:
            try:
                if self.tracking_tokens:
                    await self.update_prices()
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)  # 0.5s tracking!
            except Exception:
                await asyncio.sleep(CONFIG.PRICE_UPDATE_INTERVAL)
    
    def stop_tracking(self):
        """Stop the price tracking"""
        self.running = False
        console.print("[TRACKER] 🛑 TRACKING STOPPED")


class PerfectFusionQuantumBeast:
    """🏆 PERFECT FUSION QUANTUM BEAST - YOUR WORKING SETUP + RUST LIBRARY! 🏆"""
    
    def __init__(self):
        self.running = False
        self.shutdown_event = asyncio.Event()
        
        # Components
        self.trader = None  # YOUR RUST LIBRARY
        self.signal_fusion = None
        self.ws_listener = None
        self.price_tracker = PerfectPriceTracker()
        
        # 🎯 PERFECT BALANCE TRACKING (unchanged)
        self.session_start_balance = 0
        self.session_start_total_value = 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
        
        # Performance tracking
        self.execution_times = deque(maxlen=200)
        self.confirmation_times = deque(maxlen=200)
        self.dashboard_update_count = 0
    
    def calculate_total_account_value(self) -> Tuple[float, float, float]:
        """🎯 YOUR PERFECT CALCULATION - UNCHANGED"""
        liquid_sol = self.ws_listener.get_balance()
        if liquid_sol == 0:
            liquid_sol = self.trader.get_sol_balance()
        
        total_invested = 0
        total_position_value = 0
        
        for pos in self.positions.values():
            amount_sol = pos.get('amount_sol', 0)
            total_invested += amount_sol
            
            entry_price = pos.get('entry_price', 0)
            current_price = pos.get('current_price', entry_price)
            
            if entry_price > 0:
                price_change_pct = ((current_price - entry_price) / entry_price) * 100
                position_value = amount_sol * (1 + price_change_pct / 100)
                total_position_value += position_value
            else:
                total_position_value += amount_sol
        
        total_value = liquid_sol + total_position_value
        return total_value, liquid_sol, total_invested
    
    async def initialize(self):
        """🚀 Initialize PERFECT FUSION QUANTUM BEAST with RUST LIBRARY"""
        
        console.print("\n" + "🔥" * 80)
        console.print("🏆 PERFECT FUSION QUANTUM BEAST - RUST LIBRARY EDITION! 🏆".center(80))
        console.print("💎 YOUR EXACT VALUES + RUST OPTIMIZED + FUSION SIGNALS 💎".center(80))
        console.print("🔥" * 80)
        
        console.print("\n[bold]🔥 INITIALIZING FUSION BEAST WITH RUST LIBRARY 🔥[/bold]")
        
        # 🚀 Initialize YOUR RUST LIBRARY (no more Python Jupiter calls!)
        console.print("⚡ Initializing YOUR Rust Trading Engine...", end="")
        try:
            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]✅ RUST LIBRARY LOADED[/green]")
        except Exception as e:
            console.print(f" [red]❌ RUST LIBRARY FAILED: {e}[/red]")
            raise e
        
        # Get initial balance using RUST
        console.print("💰 Getting initial balance via RUST...", end="")
        initial_liquid_sol = self.trader.get_sol_balance()
        self.session_start_balance = initial_liquid_sol
        self.session_start_total_value = initial_liquid_sol
        console.print(f" [green]✅ {initial_liquid_sol:.6f} SOL[/green]")
        
        # Prime blockhash cache using RUST
        console.print("🔄 Priming RUST blockhash cache...", end="")
        self.trader.force_update_blockhash()
        await asyncio.sleep(0.5)
        console.print(" [green]✅[/green]")
        
        # Initialize FUSION signal engine
        console.print("🔥 Initializing FUSION Signal Engine...")
        self.signal_fusion = PerfectSignalFusion()
        await self.signal_fusion.initialize()
        
        # Start price tracker
        console.print("📊 Starting Price Tracker...", end="")
        self.price_tracker_task = asyncio.create_task(self.price_tracker.start_tracking())
        console.print(" [green]✅[/green]")
        
        # Initialize WebSocket system
        console.print("🌐 Initializing WebSocket System...", end="")
        self.ws_listener = PerfectWebSocketMonitor(CONFIG.WALLET_ADDRESS, CONFIG.API_KEY)
        console.print(" [green]✅[/green]")
        
        # Start WebSocket connections
        console.print("\n🚀 Starting WebSocket 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.session_start_balance = ws_balance
                self.session_start_total_value = ws_balance
                console.print(f"[green]💰 WebSocket Balance: {ws_balance:.6f} SOL[/green]")
            else:
                # Use RUST library for fallback
                rpc_balance = self.trader.get_sol_balance()
                self.ws_listener.current_balance = rpc_balance
                self.session_start_balance = rpc_balance
                self.session_start_total_value = rpc_balance
                console.print(f"[yellow]💰 RUST Library Fallback: {rpc_balance:.6f} SOL[/yellow]")
        
        # Display ready state
        console.print(f"\n[green]🏆 PERFECT FUSION QUANTUM BEAST READY! 🏆[/green]")
        console.print(f"💰 Account Value: {self.session_start_total_value:.6f} SOL")
        console.print(f"🌐 WebSocket: {self.ws_listener.get_connection_status()}")
        console.print(f"🦀 Rust Library: ACTIVE (optimized transactions)")
        console.print(f"🔥 FUSION Signals: GPU + Quantum + Discovery")
        console.print(f"🎯 YOUR Targets: +{CONFIG.PROFIT_TARGET_PCT}% / -{CONFIG.STOP_LOSS_PCT}%")
        console.print(f"🔧 YOUR Trade Amount: {CONFIG.TRADE_AMOUNT_SOL} SOL")
        console.print(f"⏰ YOUR Max Hold: {CONFIG.MAX_HOLD_TIME}s")
        console.print(f"📊 YOUR Intervals: {CONFIG.CHECK_INTERVAL}s check, {CONFIG.POSITION_CHECK_INTERVAL}s position")
    
    async def find_opportunities(self) -> List[Dict]:
        """🔍 Find FUSION opportunities using ALL signal systems"""
        try:
            # Use FUSION engine to get multi-source signals
            fusion_opportunities = await self.signal_fusion.find_fusion_opportunities()
            
            if not fusion_opportunities:
                console.print("[INFO] No fusion opportunities found")
                return []
            
            console.print(f"🔥 Found {len(fusion_opportunities)} FUSION opportunities")
            
            # 🛡️ Safety validation using YOUR working safety score
            console.print(f"🛡️ Running safety validation...")
            mint_addresses = [signal.get('token_mint', signal.get('mint', '')) for signal in fusion_opportunities]
            
            if not SAFETY_VALIDATOR_AVAILABLE:
                console.print("[yellow]⚠️ Safety validator unavailable - proceeding with caution[/yellow]")
                return fusion_opportunities[:1]  # Return only first opportunity
            
            safety_validator = HeliusEnhancedSafetyValidator(CONFIG.API_KEY)
            await safety_validator.initialize()
            
            try:
                safety_results = await safety_validator.batch_validate_tokens(mint_addresses)
                
                safe_opportunities = []
                unsafe_count = 0
                
                for signal in fusion_opportunities:
                    mint = signal.get('token_mint', signal.get('mint', ''))
                    symbol = signal.get('symbol', 'UNKNOWN')
                    
                    # Check dynamic blacklist first
                    if CONFIG.is_dynamically_blacklisted(symbol):
                        unsafe_count += 1
                        entry = CONFIG.dynamic_blacklist[symbol.upper()]
                        console.print(f"🚫 {symbol}: DYNAMIC BLACKLIST - {entry['reason']}")
                        continue
                    
                    if mint in safety_results:
                        result = safety_results[mint]
                        
                        if result.is_safe and result.safety_score >= CONFIG.MIN_SAFETY_SCORE:
                            safe_opportunities.append(signal)
                            console.print(f"✅ {symbol}: FUSION + SAFE (score: {result.safety_score})")
                        else:
                            unsafe_count += 1
                            issues_str = ', '.join(result.issues[:2])
                            console.print(f"🛡️ {symbol}: BLOCKED (score: {result.safety_score}) - {issues_str}")
                            
                            # 🔥 AUTO-BLACKLIST unsafe tokens
                            reason = f"Safety score {result.safety_score}, {issues_str}"
                            CONFIG.add_to_dynamic_blacklist(symbol, mint, reason)
                    else:
                        unsafe_count += 1
                        console.print(f"❌ {symbol}: BLOCKED - No safety data")
                        
                        # 🔥 AUTO-BLACKLIST tokens with no safety data
                        CONFIG.add_to_dynamic_blacklist(symbol, mint, "No safety data available")
                
                console.print(f"🛡️ FUSION + SAFETY: {len(safe_opportunities)}/{len(fusion_opportunities)} passed")
                return safe_opportunities
                
            finally:
                await safety_validator.close()
            
        except Exception as e:
            console.print(f"[red]💥 Opportunity finding error: {e}[/red]")
            return []
    
    async def execute_trade(self, signal: Dict) -> bool:
        """🚀 Execute trade using YOUR RUST LIBRARY - NO MORE PYTHON JUPITER CALLS!"""
        symbol = signal.get('symbol', 'UNKNOWN')
        token_mint = signal.get('token_mint', signal.get('mint', ''))
        entry_price = signal.get('price', 0)
        
        console.print(f"\n[bold]🎯 FUSION TRADE: {symbol}[/bold] @ ${entry_price:.8f}")
        console.print(f"    🔥 Source: {signal.get('signal_source', 'UNKNOWN')}")
        console.print(f"    🎮 GPU Type: {signal.get('gpu_type', 'UNKNOWN')}")
        console.print(f"    💎 Quantum: {'✅' if signal.get('quantum_verified', False) else '❌'}")
        console.print(f"    🔍 Discovery: {'✅' if signal.get('discovery_verified', False) else '❌'}")
        console.print(f"    🦀 Engine: RUST LIBRARY (optimized)")
        
        trade_start_time = time.time()
        execution_start = time.perf_counter()
        
        try:
            # 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]🔄 RUST Balance Fallback: {pre_balance:.6f} SOL[/yellow]")
            
            # 🦀 EXECUTE TRADE USING YOUR RUST LIBRARY (not Python!)
            buy_start = time.perf_counter()
            console.print(f"🦀 Executing buy via RUST library...")
            
            buy_sig = self.trader.execute_jupiter_swap(
                input_mint="So11111111111111111111111111111111111111112",  # SOL
                output_mint=token_mint,
                amount_sol=CONFIG.TRADE_AMOUNT_SOL,
                slippage_percent=CONFIG.SLIPPAGE_PERCENT,
                priority_multiplier=1
            )
            
            buy_exec_time = (time.perf_counter() - buy_start) * 1000
            self.execution_times.append(buy_exec_time)
            console.print(f"🦀 RUST buy executed: {buy_exec_time:.0f}ms - {buy_sig}")
            
            # YOUR WORKING confirmation system
            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]✅ RUST trade 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 RUST 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 RUST - {sol_spent:.6f} SOL spent[/green]")
                    self.ws_listener.current_balance = post_balance
                else:
                    console.print("[red]❌ Trade verification failed[/red]")
                    return False
            
            # Get token balance using RUST
            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]")
                return False
            
            # Create position with FUSION data
            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,
                "signal_type": signal.get('gpu_type', 'FUSION'),
                "signal_strength": signal.get('fusion_score', 0),
                "signal_source": "FUSION_RUST",
                "gpu_verified": True,
                "quantum_verified": signal.get('quantum_verified', False),
                "discovery_verified": signal.get('discovery_verified', False),
                "execution_time_ms": buy_exec_time,
                "confirmation_time_ms": confirm_time if confirmed else 0,
                "confirming_websocket": source if confirmed else "RUST_RPC",
                "hold_time_seconds": 0,
                "pnl_pct": 0,
                "last_logged_pnl": 0
            }
            
            self.positions[symbol] = position
            self.trades_executed += 1
            self.signal_fusion.fusion_trades_executed += 1
            
            # Start tracking
            self.price_tracker.add_token(symbol, token_mint, entry_price)
            
            # Update dashboard
            await self.update_dashboard()
            
            # Prime blockhash for next trade using RUST
            self.trader.force_update_blockhash()
            
            total_time = (time.perf_counter() - execution_start) * 1000
            console.print(f"[green]✅ RUST FUSION TRADE complete: {total_time:.0f}ms[/green]")
            
            return True
            
        except Exception as e:
            console.print(f"[red]💥 RUST FUSION Trade failed: {e}[/red]")
            traceback.print_exc()
            return False whats up with thsi