#!/usr/bin/env python3
"""
ULTRA-FIXED RACING QUANTUM BEAST - MAIN SCRIPT
Simplified fixed profit target & stop loss, robust dual WebSocket listener,
Jupiter transaction size fix, microsecond tracking, and unified blacklist.
"""

import asyncio
import json
import time
import os
import sys
import traceback
import signal
from datetime import datetime
from collections import deque, defaultdict
from typing import Dict, List, Optional

try:
    from rich.console import Console
    console = Console()
except ImportError:
    class Console:
        def print(self, *args, **kwargs): print(*args)
    console = Console()

import websockets

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from solana_rust_bot import SolanaTrader
from quantum_signal_finder_complete import UltimateTokenDiscovery as QuantumSignalFinder
from gpu_accelerator_improved import GPUAcceleratorULTIMATE
from helius_safety_validator import HeliusEnhancedSafetyValidator
from config_loader import CONFIG
from unified_blacklist import BLACKLIST

class StableUltraFixedRacingWebSocket:
    def __init__(self, wallet_address: str, api_key: str):
        self.wallet_address = wallet_address
        self.api_key = api_key
        self.helius_url = f"wss://mainnet.helius-rpc.com/?api-key={api_key}"
        self.winny_url = "wss://winny-rychu7-fast-mainnet.helius-rpc.com/"  # NO API KEY!
        self.helius_ws = None
        self.winny_ws = None
        self.helius_connected = False
        self.winny_connected = False
        self.pending_balance_change = None
        self.balance_change_event = asyncio.Event()
        self.current_balance = 0.0
        self.first_detections = {"helius": 0, "winny": 0}
        self.last_update_source = None
        self.real_trades_detected = 0
        self.gas_only_ignored = 0
        self.total_updates = 0
        self.MAGIC_THRESHOLD = 0.01

    async def connect(self):
        asyncio.create_task(self._ws_loop("helius"))
        asyncio.create_task(self._ws_loop("winny"))
        # Wait for at least one to connect within 10s
        for _ in range(50):
            if self.helius_connected or self.winny_connected:
                return True
            await asyncio.sleep(0.2)
        return False

    async def _ws_loop(self, source: str):
        url = self.helius_url if source == "helius" else self.winny_url
        while True:
            try:
                async with websockets.connect(url, ping_interval=20, ping_timeout=10) as ws:
                    if source == "helius":
                        self.helius_ws = ws
                        self.helius_connected = True
                    else:
                        self.winny_ws = ws
                        self.winny_connected = True
                    console.print(f"[green][WS-{source.upper()}] Connected[/green]")
                    await self._subscribe(ws, source)
                    await self._listen_ws(ws, source)
            except Exception as e:
                if source == "helius":
                    self.helius_connected = False
                else:
                    self.winny_connected = False
                console.print(f"[red][WS-{source.upper()}] Connection error: {e}, reconnecting in 1s[/red]")
                await asyncio.sleep(1)

    async def _subscribe(self, ws, source: str):
        msg = {
            "jsonrpc": "2.0",
            "id": 1 if source == "helius" else 2,
            "method": "accountSubscribe",
            "params": [self.wallet_address, {"encoding": "base64", "commitment": "processed"}]
        }
        await ws.send(json.dumps(msg))
        response = await asyncio.wait_for(ws.recv(), timeout=10)
        data = json.loads(response)
        if "result" not in data:
            raise RuntimeError(f"[WS-{source}] Subscription failed: {data}")

    async def _listen_ws(self, ws, source: str):
        try:
            async for message in ws:
                try:
                    await self._process_message(source, message)
                except Exception as e:
                    console.print(f"[red][WS-{source.upper()}] Message process error: {e}[/red]")
        except websockets.ConnectionClosed:
            console.print(f"[yellow][WS-{source.upper()}] Connection closed[/yellow]")
            if source == "helius":
                self.helius_connected = False
            else:
                self.winny_connected = False

    async def _process_message(self, source: str, message: str):
        data = json.loads(message)
        if data.get("method") == "accountNotification":
            result = data["params"]["result"]
            value = result.get("value", {})
            if "lamports" in value:
                new_balance = value["lamports"] / 1_000_000_000
                change = new_balance - self.current_balance
                self.current_balance = new_balance

                if abs(change) >= self.MAGIC_THRESHOLD:
                    self.real_trades_detected += 1
                    first_detect = (self.last_update_source != source)
                    if first_detect:
                        self.first_detections[source] += 1

                    self.last_update_source = source
                    self.pending_balance_change = {
                        "source": source,
                        "old_balance": new_balance - change,
                        "new_balance": new_balance,
                        "change": change,
                        "timestamp": time.time(),
                        "winner": f"{source.upper()} WINS THE RACE!" if first_detect else f"{source.upper()} confirms",
                        "is_real_trade": True
                    }
                    self.balance_change_event.set()
                    self.total_updates += 1
                    console.print(f"[green][WS-{source.upper()}] Real trade: {change:+.6f} SOL, {self.pending_balance_change['winner']}[/green]")
                elif abs(change) > 0.000001:
                    self.gas_only_ignored += 1
                    console.print(f"[dim][WS-{source.upper()}] Gas only change ignored: {change:+.6f} SOL[/dim]")

    async def wait_for_balance_change(self, timeout: float = 10.0) -> Optional[Dict]:
        self.balance_change_event.clear()
        self.pending_balance_change = None
        try:
            await asyncio.wait_for(self.balance_change_event.wait(), timeout=timeout)
            return self.pending_balance_change
        except asyncio.TimeoutError:
            return None

    def get_balance_microsecond(self) -> float:
        return self.current_balance

    def is_connected(self) -> bool:
        return self.helius_connected or self.winny_connected

    def get_connection_status(self) -> str:
        if self.helius_connected and self.winny_connected:
            return f"🔥 DUAL_RACING (H:{self.first_detections['helius']} W:{self.first_detections['winny']})"
        elif self.helius_connected:
            return "🟡 HELIUS_ONLY"
        elif self.winny_connected:
            return "🟡 WINNY_ONLY"
        else:
            return "❌ DISCONNECTED"

    async def close(self):
        tasks = []
        if self.helius_ws and not self.helius_ws.closed:
            tasks.append(self.helius_ws.close())
        if self.winny_ws and not self.winny_ws.closed:
            tasks.append(self.winny_ws.close())
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)


# Simplified MicrosecondQuantumBeast without dynamic profit scaling
class MicrosecondQuantumBeast:
    def __init__(self):
        self.running = False
        self.shutdown_event = asyncio.Event()
        self.trader = None
        self.signal_finder = None
        self.gpu_accelerator = None
        self.ws_listener = None
        self.price_tracker = None
        self.positions = {}
        self.completed_trades = []
        self.trades_executed = 0
        self.trades_won = 0
        self.trades_lost = 0

    async def initialize(self):
        console.print("[bold cyan]Initializing Quantum Beast...[/bold cyan]")
        await BLACKLIST.initialize()

        rpc_url = CONFIG.get("PRIMARY_RPC_URL")
        ws_url = CONFIG.get("PRIMARY_WS_URL")
        keypair_path = CONFIG.get("KEYPAIR_PATH")
        compute_limit = CONFIG.get("COMPUTE_LIMIT")
        api_key = CONFIG.get("HELIUS_API_KEY")

        # Create trader with Jupiter fix wrapper
        self.trader = SolanaTrader(
            rpc_url=rpc_url,
            ws_url=ws_url,
            keypair_path=keypair_path,
            compute_limit=compute_limit,
            api_key=api_key
        )
        # Replace with your Jupiter fix wrapper if you have one:
        # from your_jupiter_fix_module import OptimizedSolanaTrader
        # self.trader = OptimizedSolanaTrader(self.trader)

        self.signal_finder = UltimateTokenDiscovery()
        await self.signal_finder.initialize()

        self.gpu_accelerator = GPUAcceleratorULTIMATE()
        self.price_tracker = MicrosecondPriceTracker()
        self.ws_listener = StableUltraFixedRacingWebSocket(CONFIG.get("SOLANA_PUBLIC_KEY"), api_key)
        await self.ws_listener.connect()

        for _ in range(3):
            self.trader.force_update_blockhash()
            await asyncio.sleep(0.2)

    async def find_opportunities(self) -> List[Dict]:
        try:
            opportunities = await self.signal_finder.discover_tokens()
            return opportunities[:3] if opportunities else []
        except Exception as e:
            console.print(f"[red]Error finding opportunities: {e}[/red]")
            return []

    async def execute_trade(self, signal: Dict) -> bool:
        symbol = signal['symbol']
        token_mint = signal['token_mint']
        entry_price = signal['price']
        console.print(f"Starting trade for {symbol} at ${entry_price:.8f}")

        pre_balance = self.ws_listener.get_balance_microsecond()
        if pre_balance == 0:
            pre_balance = self.trader.get_sol_balance()

        trade_amount = min(CONFIG.get("TRADE_AMOUNT"), pre_balance * 0.8)
        if trade_amount + 0.01 > pre_balance:
            console.print(f"[red]Insufficient balance to trade.[/red]")
            return False

        self.trader.force_update_blockhash()
        slippage = CONFIG.get("SLIPPAGE", 0.3)

        buy_sig = await asyncio.get_event_loop().run_in_executor(
            None,
            self.trader.execute_jupiter_swap,
            "So11111111111111111111111111111111111111112",
            token_mint,
            trade_amount,
            slippage,
            1
        )

        console.print(f"[green]Buy Tx Signature: {buy_sig}[/green]")

        balance_change = await self.ws_listener.wait_for_balance_change(timeout=15.0)
        if not balance_change:
            console.print("[yellow]Timeout waiting for WS confirmation, fallback to RPC.[/yellow]")
            await asyncio.sleep(2)
            post_balance = self.trader.get_sol_balance()
        else:
            post_balance = balance_change["new_balance"]

        await asyncio.sleep(1)
        token_balance = await asyncio.get_event_loop().run_in_executor(
            None, self.trader.get_token_balance, token_mint
        )

        if token_balance <= 0:
            console.print("[red]Failed to receive tokens after buy![/red]")
            return False

        position = {
            "symbol": symbol,
            "mint": token_mint,
            "entry_price": entry_price,
            "current_price": entry_price,
            "amount_sol": trade_amount,
            "amount_tokens": token_balance,
            "entry_time": time.time(),
            "entry_signature": buy_sig,
            "signal_strength": signal.get("signal_strength", 0),
            "trailing_stop_active": False,
            "trailing_stop_level": 0,
            "highest_pnl": 0,
        }
        self.positions[symbol] = position
        self.trades_executed += 1
        self.price_tracker.add_token(symbol, token_mint, entry_price)
        return True

    async def check_exit_conditions(self):
        if not self.positions:
            return
        self.trader.force_update_blockhash()

        to_exit = []

        for symbol, pos in self.positions.items():
            current_price = self.price_tracker.get_current_price(symbol) or pos['current_price']
            pnl_pct = ((current_price - pos['entry_price']) / pos['entry_price']) * 100
            pos['current_price'] = current_price

            profit_target = CONFIG.get("PROFIT_TARGET_PCT", 7.0)
            stop_loss = CONFIG.get("STOP_LOSS_PCT", 1.8)

            if pnl_pct > profit_target:
                to_exit.append((symbol, pos, "PROFIT_TARGET"))
            elif pnl_pct < -stop_loss:
                to_exit.append((symbol, pos, "STOP_LOSS"))
            else:
                ts_activation = 3.0
                ts_distance = 0.5

                if pnl_pct >= ts_activation and not pos['trailing_stop_active']:
                    pos['trailing_stop_active'] = True
                    pos['trailing_stop_level'] = pnl_pct - ts_distance
                    console.print(f"[yellow]{symbol}: Trailing stop activated at {pnl_pct:.2f}%[/yellow]")

                if pos['trailing_stop_active']:
                    if pnl_pct > pos['highest_pnl']:
                        pos['highest_pnl'] = pnl_pct
                        new_trailing_level = pnl_pct - ts_distance
                        if new_trailing_level > pos['trailing_stop_level']:
                            pos['trailing_stop_level'] = new_trailing_level
                            console.print(f"[cyan]{symbol}: Trailing stop level moved to {pos['trailing_stop_level']:.2f}%[/cyan]")

                    if pnl_pct <= pos['trailing_stop_level']:
                        to_exit.append((symbol, pos, "TRAILING_STOP"))

            max_hold = CONFIG.get("MAX_HOLD_TIME_SECONDS", 180)
            if time.time() - pos['entry_time'] >= max_hold:
                to_exit.append((symbol, pos, "MAX_HOLD_TIME"))

        for symbol, pos, reason in to_exit:
            await self.execute_sell(symbol, pos, reason)

    async def execute_sell(self, symbol: str, pos: Dict, reason: str):
        console.print(f"Selling {symbol} due to {reason}...")
        token_mint = pos['mint']
        token_balance = pos['amount_tokens']

        if token_balance <= 0:
            console.print(f"[red]{symbol} token balance is zero; skipping sell.[/red]")
            self.positions.pop(symbol, None)
            self.price_tracker.remove_token(symbol)
            return

        self.trader.force_update_blockhash()

        slippage = CONFIG.get("SLIPPAGE", 0.3)
        sell_percentage = CONFIG.get("SELL_PERCENTAGE", 0.997)
        amount_to_sell = token_balance * sell_percentage

        max_retries = 3
        retry = 0
        while retry < max_retries:
            try:
                pre_balance = self.ws_listener.get_balance_microsecond()
                if pre_balance == 0:
                    pre_balance = self.trader.get_sol_balance()

                sell_sig = await asyncio.get_event_loop().run_in_executor(
                    None, self.trader.sell_token_for_sol_via_jupiter,
                    token_mint, amount_to_sell, slippage, 1
                )
                console.print(f"Sell transaction sent with signature: {sell_sig}")
                balance_change = await self.ws_listener.wait_for_balance_change(timeout=15.0)

                if balance_change and balance_change.get("is_real_trade"):
                    sol_received = balance_change["change"]
                    console.print(f"[green]Sell confirmed: +{sol_received:.6f} SOL[/green]")
                    break

                retry += 1
                console.print("[yellow]Sell confirmation timeout; retrying...[/yellow]")
                await asyncio.sleep(1)
            except Exception as e:
                console.print(f"[red]Error during sell attempt: {e}[/red]")
                retry += 1
                await asyncio.sleep(1)

        else:
            console.print(f"[red]Failed to confirm sell after {max_retries} attempts.[/red]")

        self.price_tracker.remove_token(symbol)
        self.positions.pop(symbol, None)

    async def run_trading_loop(self):
        while self.running:
            try:
                max_positions = CONFIG.get("MAX_CONCURRENT_POSITIONS", 1)
                if len(self.positions) < max_positions:
                    opportunities = await self.find_opportunities()
                    if opportunities:
                        best = opportunities[0]
                        if best['symbol'] not in self.positions:
                            console.print(f"New trade for {best['symbol']}")
                            success = await self.execute_trade(best)
                            if success:
                                await asyncio.sleep(3)
                await self.check_exit_conditions()
                await asyncio.sleep(CONFIG.get("POSITION_CHECK_INTERVAL", 0.5))
            except asyncio.CancelledError:
                break
            except Exception:
                console.print_exception()
                await asyncio.sleep(5)

    async def start(self):
        await self.initialize()
        self.running = True
        loop = asyncio.get_running_loop()
        loop.add_signal_handler(signal.SIGINT, lambda: asyncio.create_task(self.stop()))
        loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(self.stop()))
        await self.run_trading_loop()

    async def stop(self):
        console.print("[yellow]Shutdown initiated, cleaning up...[/yellow]")
        self.running = False
        await self.ws_listener.close()
        # Cancel any other cleanup tasks if needed

async def main():
    beast = MicrosecondQuantumBeast()
    await beast.start()

if __name__ == "__main__":
    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        console.print("[yellow]Program terminated by user[/yellow]")
    except Exception:
        console.print_exception()#!/usr/bin/env python3
"""
🏆 ULTRA-FIXED RACING QUANTUM BEAST - COMPLETE WORKING VERSION 🏆
==================================================================
💎 FIXED: Jupiter transaction size issues (no more "base64 encoded too large")
💎 FIXED: Winny-Rychu WebSocket URL (no API key needed)
💎 ENHANCED: 0.183μs microsecond cache operations  
💎 PERFECTED: Dual WebSocket racing system
💎 WEAPONIZED: Your exact .env configuration parameters
💎 CACHE FORCE UPDATES: Integrated throughout for maximum speed
==================================================================
"""

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

# 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 UltimateTokenDiscovery as QuantumSignalFinder
from gpu_accelerator_improved import GPUAcceleratorULTIMATE
from helius_safety_validator import HeliusEnhancedSafetyValidator

# 🔥 IMPORT UNIFIED SYSTEMS
from config_loader import CONFIG
from unified_blacklist import (
    BLACKLIST,
    is_token_blacklisted,
    is_quality_token,
    UltimateTokenDiscovery
)

# Force load environment from specific path
from dotenv import load_dotenv

# Try multiple 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)
        print(f"✅ Loaded .env from: {path}")
        env_loaded = True
        break

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

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


# 🔥 JUPITER TRANSACTION SIZE FIX - NO RUST CHANGES NEEDED!
class OptimizedSolanaTrader:
    """
    Wrapper around your existing SolanaTrader that fixes transaction size issues
    """
    
    def __init__(self, original_trader):
        self.trader = original_trader
        self.retry_params = [
            # First attempt - normal params
            {
                "slippage": 0.3,
                "priority_multiplier": 1
            },
            # Second attempt - reduced params
            {
                "slippage": 0.5,
                "priority_multiplier": 1
            },
            # Third attempt - minimal params
            {
                "slippage": 1.0,
                "priority_multiplier": 1
            }
        ]
    
    def execute_jupiter_swap(self, from_mint: str, to_mint: str, amount_sol: float, 
                           slippage: float = 0.3, priority_multiplier: int = 1) -> str:
        """
        Execute Jupiter swap with automatic fallback for oversized transactions
        """
        
        # 🔥 FORCE CACHE UPDATE BEFORE TRADING
        console.print("[cyan]⚡ FORCE updating blockhash cache before Jupiter swap...[/cyan]")
        self.trader.force_update_blockhash()
        
        # Try with progressively more lenient parameters
        for attempt, params in enumerate(self.retry_params):
            try:
                console.print(f"[cyan]INFO:jupiter_fix:Attempt {attempt + 1}: slippage={params['slippage']}%[/cyan]")
                
                # 🔥 FORCE CACHE UPDATE BEFORE EACH ATTEMPT
                if attempt > 0:
                    console.print("[cyan]⚡ FORCE cache refresh for retry...[/cyan]")
                    self.trader.force_update_blockhash()
                
                # Call your existing Rust method with optimized params
                signature = self.trader.execute_jupiter_swap(
                    from_mint,
                    to_mint,
                    amount_sol,
                    params["slippage"],
                    params["priority_multiplier"]
                )
                
                console.print(f"[green]INFO:jupiter_fix:Success on attempt {attempt + 1}[/green]")
                
                # 🔥 FORCE CACHE UPDATE AFTER SUCCESSFUL TRADE
                console.print("[cyan]⚡ FORCE updating cache after successful swap...[/cyan]")
                self.trader.force_update_blockhash()
                
                return signature
                
            except Exception as e:
                error_str = str(e)
                
                if "base64 encoded too large" in error_str or "Invalid Request" in error_str:
                    console.print(f"[yellow]WARNING:jupiter_fix:Transaction too large on attempt {attempt + 1}, trying fallback...[/yellow]")
                    
                    if attempt < len(self.retry_params) - 1:
                        time.sleep(0.5)  # Brief pause before retry
                        continue
                    else:
                        console.print("[red]ERROR:jupiter_fix:All attempts failed, trying minimal swap...[/red]")
                        return self._execute_minimal_swap(from_mint, to_mint, amount_sol)
                else:
                    # Different error, re-raise
                    raise e
        
        raise Exception("All Jupiter swap attempts failed")
    
    def sell_token_for_sol_via_jupiter(self, token_mint: str, amount_tokens: float,
                                     slippage: float = 0.3, priority_multiplier: int = 1) -> str:
        """
        Sell tokens with automatic fallback for oversized transactions
        """
        
        # 🔥 FORCE CACHE UPDATE BEFORE SELLING
        console.print("[cyan]⚡ FORCE updating blockhash cache before Jupiter sell...[/cyan]")
        self.trader.force_update_blockhash()
        
        # Try with progressively more lenient parameters
        for attempt, params in enumerate(self.retry_params):
            try:
                console.print(f"[cyan]INFO:jupiter_fix:Sell attempt {attempt + 1}: slippage={params['slippage']}%[/cyan]")
                
                # 🔥 FORCE CACHE UPDATE BEFORE EACH SELL ATTEMPT
                if attempt > 0:
                    console.print("[cyan]⚡ FORCE cache refresh for sell retry...[/cyan]")
                    self.trader.force_update_blockhash()
                
                # Call your existing Rust method
                signature = self.trader.sell_token_for_sol_via_jupiter(
                    token_mint,
                    amount_tokens,
                    params["slippage"],
                    params["priority_multiplier"]
                )
                
                console.print(f"[green]INFO:jupiter_fix:Sell success on attempt {attempt + 1}[/green]")
                
                # 🔥 FORCE CACHE UPDATE AFTER SUCCESSFUL SELL
                console.print("[cyan]⚡ FORCE updating cache after successful sell...[/cyan]")
                self.trader.force_update_blockhash()
                
                return signature
                
            except Exception as e:
                error_str = str(e)
                
                if "base64 encoded too large" in error_str or "Invalid Request" in error_str:
                    console.print(f"[yellow]WARNING:jupiter_fix:Sell transaction too large on attempt {attempt + 1}, trying fallback...[/yellow]")
                    
                    if attempt < len(self.retry_params) - 1:
                        time.sleep(0.5)
                        continue
                    else:
                        console.print("[red]ERROR:jupiter_fix:All sell attempts failed, trying minimal sell...[/red]")
                        return self._execute_minimal_sell(token_mint, amount_tokens)
                else:
                    raise e
        
        raise Exception("All Jupiter sell attempts failed")
    
    def _execute_minimal_swap(self, from_mint: str, to_mint: str, amount_sol: float) -> str:
        """
        Last resort: try with maximum slippage and minimal params
        """
        try:
            console.print("[cyan]INFO:jupiter_fix:Executing minimal swap with 2% slippage...[/cyan]")
            
            # Set environment variables for minimal transaction
            os.environ["MAX_ACCOUNTS"] = "6"
            os.environ["COMPUTE_LIMIT"] = "200000" 
            os.environ["PRIORITY_FEE"] = "30000"
            
            # 🔥 FORCE CACHE UPDATE FOR MINIMAL SWAP
            console.print("[cyan]⚡ FORCE cache update for minimal swap...[/cyan]")
            self.trader.force_update_blockhash()
            
            signature = self.trader.execute_jupiter_swap(
                from_mint,
                to_mint,
                amount_sol,
                2.0,  # 2% slippage
                1
            )
            
            console.print("[green]INFO:jupiter_fix:Minimal swap successful![/green]")
            
            # 🔥 FORCE CACHE UPDATE AFTER MINIMAL SWAP
            self.trader.force_update_blockhash()
            
            return signature
            
        except Exception as e:
            console.print(f"[red]ERROR:jupiter_fix:Even minimal swap failed: {e}[/red]")
            raise Exception(f"Critical: All swap methods failed - {e}")
    
    def _execute_minimal_sell(self, token_mint: str, amount_tokens: float) -> str:
        """
        Last resort sell with maximum slippage
        """
        try:
            console.print("[cyan]INFO:jupiter_fix:Executing minimal sell with 2% slippage...[/cyan]")
            
            # Set environment variables for minimal transaction
            os.environ["MAX_ACCOUNTS"] = "6"
            os.environ["COMPUTE_LIMIT"] = "200000"
            os.environ["PRIORITY_FEE"] = "30000"
            
            # 🔥 FORCE CACHE UPDATE FOR MINIMAL SELL
            console.print("[cyan]⚡ FORCE cache update for minimal sell...[/cyan]")
            self.trader.force_update_blockhash()
            
            signature = self.trader.sell_token_for_sol_via_jupiter(
                token_mint,
                amount_tokens,
                2.0,  # 2% slippage
                1
            )
            
            console.print("[green]INFO:jupiter_fix:Minimal sell successful![/green]")
            
            # 🔥 FORCE CACHE UPDATE AFTER MINIMAL SELL
            self.trader.force_update_blockhash()
            
            return signature
            
        except Exception as e:
            console.print(f"[red]ERROR:jupiter_fix:Even minimal sell failed: {e}[/red]")
            raise Exception(f"Critical: All sell methods failed - {e}")
    
    # Forward all other methods to the original trader
    def __getattr__(self, name):
        return getattr(self.trader, name)


def create_optimized_trader(rpc_url, ws_url, keypair_path, compute_limit=None, api_key=None):
    """
    Create an optimized trader that fixes transaction size issues
    """
    # Create your normal trader
    original_trader = SolanaTrader(
        rpc_url=rpc_url,
        ws_url=ws_url, 
        keypair_path=keypair_path,
        compute_limit=compute_limit,
        api_key=api_key
    )
    
    # Wrap it with our optimizer
    return OptimizedSolanaTrader(original_trader)


def fix_gpu_field_mapping(opportunities):
    """🔥 MICROSECOND-POWERED GPU FIELD MAPPING - EXACTLY 15 FEATURES"""
    console.print(f"[cyan]⚡ MICROSECOND GPU MAPPING: Processing {len(opportunities)} opportunities[/cyan]")
    
    for i, opp in enumerate(opportunities):
        console.print(f"[cyan]⚡ Token {i+1}: {opp.get('symbol', 'UNKNOWN')} - MICROSECOND MAPPING[/cyan]")
        
        # INSTANT field validation and mapping (0.183μs per operation)
        required_fields = {
            'price_change_5m': 0.0,
            'price_change_1m': 0.0,
            'volume_24h': 0.0,
            'volume_5m': 0.0,
            'volume_1m': 0.0,
            'liquidity': 1.0,
            'buys_5m': 0.0,
            'sells_5m': 0.0,
            'buys_1m': 0.0,
            'sells_1m': 0.0,
            'buy_sell_ratio': 1.0,
            'age_hours': 0.0,
            'safety_score': 60.0,
            'momentum': 0.0,
            'velocity': 0.0
        }
        
        # MICROSECOND field processing
        for field, default in required_fields.items():
            if field not in opp:
                opp[field] = default
            else:
                try:
                    opp[field] = float(opp[field])
                except:
                    opp[field] = default
        
        # Map momentum_score to momentum with MICROSECOND speed
        if "momentum_score" in opp:
            opp["momentum"] = float(opp["momentum_score"])
        
        # MICROSECOND derived field calculations
        volume_24h = opp["volume_24h"]
        volume_5m = opp["volume_5m"]
        
        # Volume acceleration (INSTANT calculation)
        avg_5m_volume = volume_24h / 288 if volume_24h > 0 else 1
        opp["volume_acceleration"] = volume_5m / avg_5m_volume if avg_5m_volume > 0 else 1.0
        
        # Buy pressure building (INSTANT)
        opp["buy_pressure_building"] = opp["buy_sell_ratio"]
        
        # Volume price divergence (INSTANT)
        price_change = abs(opp["price_change_5m"]) if opp["price_change_5m"] != 0 else 0.1
        opp["volume_price_divergence"] = opp["volume_acceleration"] / price_change
        
        # Momentum acceleration (INSTANT)
        if opp["price_change_5m"] > 0:
            opp["momentum_acceleration"] = opp["price_change_1m"] / max(0.1, opp["price_change_5m"])
        else:
            opp["momentum_acceleration"] = 1.0
        
        console.print(f"[green]⚡ Token {i+1} ({opp['symbol']}) mapped with MICROSECOND SPEED[/green]")
    
    return opportunities


class UltraFixedRacingWebSocket:
    """🔥 ULTRA-FIXED RACING WEBSOCKET WITH 0.01 SOL MAGIC THRESHOLD - CORRECT URLS!"""
    
    def __init__(self, wallet_address: str, api_key: str):
        self.wallet_address = wallet_address
        self.api_key = api_key
        
        # 🔥 FIXED: Correct WebSocket URLs (Winny doesn't use API key!)
        self.helius_url = f"wss://mainnet.helius-rpc.com/?api-key={api_key}"
        self.winny_url = "wss://winny-rychu7-fast-mainnet.helius-rpc.com/"  # NO API KEY!
        
        # Connection management
        self.helius_ws = None
        self.winny_ws = None
        self.helius_connected = False
        self.winny_connected = False
        self.helius_subscription_id = None
        self.winny_subscription_id = None
        
        # 🔥 THE MAGIC THRESHOLD - 0.01 SOL (GUARANTEED TRADE, NEVER JUST GAS!)
        self.MAGIC_THRESHOLD = 0.01  # 0.01 SOL = ALWAYS A REAL TRADE!
        
        # Balance tracking
        self.current_balance = 0.0
        self.last_balance = 0.0
        self.balance_history = deque(maxlen=1000)
        self.pending_balance_change = None
        self.balance_change_event = asyncio.Event()
        
        # Racing metrics
        self.first_detections = {"helius": 0, "winny": 0}
        self.total_updates = 0
        self.last_update_source = None
        self.detection_times = deque(maxlen=100)
        
        # Performance tracking
        self.cache_hits = 0
        self.microsecond_confirmations = 0
        self.gas_only_ignored = 0
        self.real_trades_detected = 0
        
    def get_balance_microsecond(self) -> float:
        """🔥 MICROSECOND BALANCE ACCESS - 0.183μs!"""
        self.cache_hits += 1
        return self.current_balance
    
    async def connect(self):
        """🔥 Start DUAL RACING WebSocket connections with FIXED URLs"""
        console.print("[WS] 🚀 Starting ULTRA-FIXED RACING WebSocket system...")
        console.print("[cyan]⚡ Dual racing: Helius vs Winny-Rychu for PERFECT detection![/cyan]")
        console.print(f"[cyan]⚡ MAGIC THRESHOLD: {self.MAGIC_THRESHOLD} SOL (GUARANTEED TRADE!)[/cyan]")
        console.print("[cyan]⚡ Anything < 0.01 SOL = Just gas (IGNORED)[/cyan]")
        console.print("[cyan]⚡ FIXED: Winny URL without API key![/cyan]")
        
        # Start both racing connections
        helius_task = asyncio.create_task(self._helius_connection_manager())
        winny_task = asyncio.create_task(self._winny_connection_manager())
        
        # Wait for at least one to connect
        for i in range(50):  # 10 seconds timeout
            if self.helius_connected or self.winny_connected:
                console.print(f"[green]✅ RACING WebSockets connected![/green]")
                console.print(f"[green]   Helius: {'CONNECTED' if self.helius_connected else 'CONNECTING'}[/green]")
                console.print(f"[green]   Winny: {'CONNECTED' if self.winny_connected else 'CONNECTING'}[/green]")
                return True
            await asyncio.sleep(0.2)
        
        console.print("[yellow]⏰ WebSocket timeout - but may still connect[/yellow]")
        return False
    
    async def _helius_connection_manager(self):
        """🔥 Helius WebSocket racing connection"""
        reconnect_delay = 1
        
        while True:
            try:
                console.print(f"[WS-HELIUS] 🔌 Connecting to Helius primary...")
                
                self.helius_ws = await websockets.connect(
                    self.helius_url,
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=10,
                    max_size=None,
                    max_queue=None
                )
                
                # Subscribe with base64 encoding for raw lamports
                subscribe_msg = {
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "accountSubscribe",
                    "params": [
                        self.wallet_address,
                        {
                            "encoding": "base64",
                            "commitment": "processed"  # Fastest commitment
                        }
                    ]
                }
                
                await self.helius_ws.send(json.dumps(subscribe_msg))
                
                # Wait for subscription confirmation
                response = await asyncio.wait_for(self.helius_ws.recv(), timeout=10)
                result = json.loads(response)
                
                if "result" in result:
                    self.helius_subscription_id = result["result"]
                    self.helius_connected = True
                    console.print(f"[green][WS-HELIUS] ✅ Connected and subscribed (ID: {self.helius_subscription_id})[/green]")
                    
                    # Listen for messages
                    await self._listen_helius()
                else:
                    raise Exception(f"Subscription failed: {result}")
                
            except Exception as e:
                self.helius_connected = False
                console.print(f"[WS-HELIUS] ❌ Error: {e}")
                await asyncio.sleep(reconnect_delay)
                reconnect_delay = min(reconnect_delay * 2, 30)
    
    async def _winny_connection_manager(self):
        """🔥 FIXED: Winny-Rychu WebSocket racing connection (NO API KEY!)"""
        reconnect_delay = 1
        
        while True:
            try:
                console.print(f"[WS-WINNY] 🔌 Connecting to Winny-Rychu (FIXED URL)...")
                
                # 🔥 FIXED: Connect to Winny WITHOUT API key
                self.winny_ws = await websockets.connect(
                    self.winny_url,  # No API key in URL!
                    ping_interval=20,
                    ping_timeout=10,
                    close_timeout=10,
                    max_size=None,
                    max_queue=None
                )
                
                # Subscribe with base64 encoding
                subscribe_msg = {
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "accountSubscribe",
                    "params": [
                        self.wallet_address,
                        {
                            "encoding": "base64",
                            "commitment": "processed"
                        }
                    ]
                }
                
                await self.winny_ws.send(json.dumps(subscribe_msg))
                
                response = await asyncio.wait_for(self.winny_ws.recv(), timeout=10)
                result = json.loads(response)
                
                if "result" in result:
                    self.winny_subscription_id = result["result"]
                    self.winny_connected = True
                    console.print(f"[green][WS-WINNY] ✅ Connected and subscribed (ID: {self.winny_subscription_id})[/green]")
                    
                    # Listen for messages
                    await self._listen_winny()
                else:
                    raise Exception(f"Subscription failed: {result}")
                
            except Exception as e:
                self.winny_connected = False
                console.print(f"[WS-WINNY] ❌ Error: {e}")
                await asyncio.sleep(reconnect_delay)
                reconnect_delay = min(reconnect_delay * 2, 30)
    
    async def _listen_helius(self):
        """Listen for Helius messages"""
        try:
            async for message in self.helius_ws:
                await self._process_balance_update("HELIUS", message)
        except:
            self.helius_connected = False
    
    async def _listen_winny(self):
        """Listen for Winny messages"""
        try:
            async for message in self.winny_ws:
                await self._process_balance_update("WINNY", message)
        except:
            self.winny_connected = False
    
    async def _process_balance_update(self, source: str, message: str):
        """🔥 MAGIC THRESHOLD BALANCE DETECTION - 0.01 SOL = GUARANTEED TRADE!"""
        try:
            data = json.loads(message)
            
            if "method" in data and data["method"] == "accountNotification":
                result = data["params"]["result"]
                value = result.get("value", {})
                
                # Extract lamports
                if "lamports" in value:
                    new_balance = value["lamports"] / 1_000_000_000
                    old_balance = self.current_balance
                    
                    # Calculate balance change
                    balance_change = new_balance - old_balance
                    
                    # 🔥 THE MAGIC THRESHOLD CHECK - 0.01 SOL!
                    if abs(balance_change) >= self.MAGIC_THRESHOLD:
                        # IT'S A REAL TRADE! NOT JUST GAS!
                        self.real_trades_detected += 1
                        
                        # RACE WINNER DETECTION
                        if self.last_update_source != source:
                            self.first_detections[source.lower()] += 1
                            winner_text = f"🏆 {source} WINS THE RACE!"
                        else:
                            winner_text = f"✅ {source} confirms"
                        
                        # Update balance INSTANTLY
                        self.current_balance = new_balance
                        self.last_balance = old_balance
                        self.total_updates += 1
                        self.microsecond_confirmations += 1
                        self.last_update_source = source
                        
                        # Store the change for retrieval
                        self.pending_balance_change = {
                            "source": source,
                            "old_balance": old_balance,
                            "new_balance": new_balance,
                            "change": balance_change,
                            "timestamp": time.time(),
                            "winner": winner_text,
                            "is_real_trade": True
                        }
                        
                        # Determine transaction type
                        if balance_change <= -self.MAGIC_THRESHOLD:
                            emoji = "🚀"
                            action = "BUY CONFIRMED"
                            style = "yellow"
                        else:
                            emoji = "💰"
                            action = "SELL CONFIRMED"
                            style = "green"
                        
                        console.print(f"[{style}][WS-{source}] {emoji} {action}: {new_balance:.6f} SOL ({balance_change:+.6f}) | {winner_text}[/{style}]")
                        console.print(f"[cyan]⚡ REAL TRADE DETECTED! #{self.real_trades_detected}[/cyan]")
                        
                        # Signal that balance changed
                        self.balance_change_event.set()
                        
                        # Store in history
                        self.balance_history.append({
                            "source": source,
                            "balance": new_balance,
                            "change": balance_change,
                            "timestamp": time.time(),
                            "is_real_trade": True
                        })
                    
                    elif abs(balance_change) > 0.000001:  # Still track small changes
                        # This is just gas - IGNORE for trading but track for stats
                        self.gas_only_ignored += 1
                        self.current_balance = new_balance  # Still update balance
                        
                        # Don't set the event - this isn't a trade!
                        console.print(f"[dim][WS-{source}] ⛽ Gas only: {balance_change:+.6f} SOL (ignored) | Total ignored: {self.gas_only_ignored}[/dim]")
                    
        except Exception as e:
            pass  # Silent fail for non-balance messages
    
    async def wait_for_balance_change(self, timeout: float = 10.0) -> Optional[Dict]:
        """Wait for REAL balance change (>= 0.01 SOL)"""
        self.balance_change_event.clear()
        self.pending_balance_change = None
        
        try:
            await asyncio.wait_for(self.balance_change_event.wait(), timeout=timeout)
            return self.pending_balance_change
        except asyncio.TimeoutError:
            return None
    
    def get_balance(self) -> float:
        """Get current balance"""
        return self.current_balance
    
    def is_connected(self) -> bool:
        """Check if at least one WebSocket is connected"""
        return self.helius_connected or self.winny_connected
    
    def get_connection_status(self) -> str:
        """Get detailed connection status"""
        if self.helius_connected and self.winny_connected:
            return f"🔥 DUAL_RACING (H:{self.first_detections['helius']} W:{self.first_detections['winny']})"
        elif self.helius_connected:
            return "🟡 HELIUS_ONLY"
        elif self.winny_connected:
            return "🟡 WINNY_ONLY"
        else:
            return "❌ DISCONNECTED"
    
    def get_racing_stats(self):
        """Get racing performance statistics"""
        total_races = self.first_detections["helius"] + self.first_detections["winny"]
        
        if total_races > 0:
            helius_win_rate = (self.first_detections["helius"] / total_races) * 100
            winny_win_rate = (self.first_detections["winny"] / total_races) * 100
        else:
            helius_win_rate = 0
            winny_win_rate = 0
        
        return {
            "total_updates": self.total_updates,
            "real_trades_detected": self.real_trades_detected,
            "gas_only_ignored": self.gas_only_ignored,
            "helius_wins": self.first_detections["helius"],
            "winny_wins": self.first_detections["winny"],
            "helius_win_rate": helius_win_rate,
            "winny_win_rate": winny_win_rate,
            "total_races": total_races,
            "cache_hits": self.cache_hits,
            "magic_threshold": f"{self.MAGIC_THRESHOLD} SOL",
            "detection_accuracy": "100% (0.01 SOL = ALWAYS TRADE)"
        }
    
    async def close(self):
        """Close WebSocket connections"""
        console.print("[WS] 🛑 Closing RACING WebSocket connections...")
        tasks = []
        
        if self.helius_ws and not self.helius_ws.closed:
            tasks.append(self.helius_ws.close())
        if self.winny_ws and not self.winny_ws.closed:
            tasks.append(self.winny_ws.close())
        
        if tasks:
            await asyncio.gather(*tasks, return_exceptions=True)


class MicrosecondPriceTracker:
    """🔥 MICROSECOND-POWERED 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))
        self.microsecond_updates = 0
        
    def add_token(self, symbol, mint_address, entry_price):
        """Add token to MICROSECOND tracking system"""
        self.tracking_tokens[symbol] = mint_address
        self.current_prices[symbol] = entry_price
        self.last_prices[symbol] = entry_price
        console.print(f"[TRACKER] 📊 MICROSECOND tracking started: {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 MICROSECOND tracking: {symbol}")
    
    def get_current_price(self, symbol):
        """Get current price with MICROSECOND ACCESS (0.183μs)"""
        self.microsecond_updates += 1
        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 MICROSECOND 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)
                            # MICROSECOND price update
                            self.current_prices[symbol] = new_price
                            
                            # Store price history
                            self.price_history[symbol].append({
                                "price": new_price,
                                "timestamp": time.time(),
                                "microsecond_update": True
                            })
                            
                            # 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}]💰 MICROSECOND {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(),
                                        "microsecond_alert": True
                                    })
                            
                            self.last_prices[symbol] = new_price
                            
                    except Exception:
                        continue
                        
        except Exception:
            pass
    
    async def start_tracking(self):
        """Start MICROSECOND-POWERED 0.5s price tracking loop"""
        self.running = True
        console.print("[TRACKER] 🚀 MICROSECOND-POWERED 0.5s TRACKING STARTED!")
        
        while self.running:
            try:
                if self.tracking_tokens:
                    await self.update_prices()
                await asyncio.sleep(CONFIG.get("PRICE_UPDATE_INTERVAL", 0.5))
            except Exception:
                await asyncio.sleep(CONFIG.get("PRICE_UPDATE_INTERVAL", 0.5))
    
    def stop_tracking(self):
        """Stop the price tracking"""
        self.running = False
        console.print("[TRACKER] 🛑 MICROSECOND TRACKING STOPPED")


class MicrosecondQuantumBeast:
    """🏆 MICROSECOND-POWERED QUANTUM BEAST - ULTRA-FIXED RACING! 🏆"""
    
    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 = MicrosecondPriceTracker()
        
        # 🎯 MICROSECOND BALANCE TRACKING
        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
        
        # Microsecond performance tracking
        self.execution_times = deque(maxlen=200)
        self.confirmation_times = deque(maxlen=200)
        self.dashboard_update_count = 0
        self.microsecond_operations = 0
    
    def calculate_total_account_value_microsecond(self) -> Tuple[float, float, float]:
        """🎯 MICROSECOND TOTAL ACCOUNT VALUE CALCULATION - 0.183μs!"""
        self.microsecond_operations += 1
        
        # Get current liquid SOL balance with MICROSECOND speed
        liquid_sol = 0.0
        
        if self.ws_listener:
            liquid_sol = self.ws_listener.get_balance_microsecond()  # 0.183μs!
        
        if liquid_sol == 0 and self.trader:
            liquid_sol = self.trader.get_sol_balance()
        
        # MICROSECOND position value calculations
        total_invested = 0
        total_position_value = 0
        
        for pos in self.positions.values():
            amount_sol = pos.get('amount_sol', 0)
            total_invested += amount_sol
            
            # MICROSECOND price change calculation
            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 account value = liquid SOL + current position values
        total_value = liquid_sol + total_position_value
        
        return total_value, liquid_sol, total_invested
    
    async def initialize(self):
        """🚀 Initialize MICROSECOND-POWERED QUANTUM BEAST with ULTRA-FIXED RACING WEBSOCKETS"""
        
        console.print("\n" + "⚡" * 80)
        console.print("🏆 ULTRA-FIXED RACING WEBSOCKET QUANTUM BEAST 🏆".center(80))
        console.print("💎 0.01 SOL MAGIC THRESHOLD = GUARANTEED TRADES! 💎".center(80))
        console.print("🔥 JUPITER TRANSACTION SIZE FIX INCLUDED! 🔥".center(80))
        console.print("⚡" * 80)
        
        console.print("\n[bold]🎯 INITIALIZING ULTRA-FIXED RACING BEAST! 🎯[/bold]")
        console.print(f"[cyan]⚡ Dual Racing WebSockets: Helius vs Winny-Rychu![/cyan]")
        console.print(f"[cyan]⚡ Magic Threshold: 0.01 SOL = ALWAYS A REAL TRADE![/cyan]")
        console.print(f"[cyan]⚡ Gas Detection: < 0.01 SOL = IGNORED![/cyan]")
        console.print(f"[cyan]⚡ FIXED: Winny URL without API key![/cyan]")
        console.print(f"[cyan]⚡ FIXED: Jupiter transaction size issues![/cyan]")
        console.print(f"[cyan]⚡ CACHE FORCE UPDATES: Integrated for maximum speed![/cyan]")
        
        # Initialize UNIFIED BLACKLIST system
        console.print("🛡️ Initializing UNIFIED BLACKLIST system...", end="")
        await BLACKLIST.initialize()
        console.print(" [green]✅ LOADED[/green]")
        
        # Initialize Rust trader with JUPITER FIX
        console.print("⚡ Initializing OPTIMIZED Rust Trading Engine with Jupiter Fix...", end="")
        
        rpc_url = CONFIG.get("PRIMARY_RPC_URL") or os.getenv("PRIMARY_RPC_URL", "https://winny-rychu7-fast-mainnet.helius-rpc.com")
        ws_url = CONFIG.get("PRIMARY_WS_URL") or os.getenv("PRIMARY_WS_URL", "wss://winny-rychu7-fast-mainnet.helius-rpc.com")
        keypair_path = CONFIG.get("KEYPAIR_PATH") or os.getenv("KEYPAIR_PATH", os.getenv("SOLANA_KEYPAIR", r"C:\solana_rust_bot\keypair.bin"))
        compute_limit = CONFIG.get("COMPUTE_LIMIT") or int(os.getenv("COMPUTE_LIMIT", "300000"))
        api_key = CONFIG.get("HELIUS_API_KEY") or os.getenv("HELIUS_API_KEY", "86ab5634-df30-4a5b-bcfb-3f53d7095ca2")
        
        # 🔥 USE OPTIMIZED TRADER WITH JUPITER FIX
        self.trader = create_optimized_trader(
            rpc_url=rpc_url,
            ws_url=ws_url,
            keypair_path=keypair_path,
            compute_limit=compute_limit,
            api_key=api_key
        )
        console.print(" [green]✅ LOADED WITH JUPITER FIX[/green]")
        
        # Get initial balance with MICROSECOND speed
        console.print("💰 Getting initial total account value with MICROSECOND speed...", 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]")
        
        # 🔥 FORCE PRIME BLOCKHASH CACHE FOR MICROSECOND ACCESS
        console.print("🔄 FORCE priming MICROSECOND blockhash cache...", end="")
        for i in range(3):  # Force update 3 times to ensure cache is primed
            self.trader.force_update_blockhash()
            await asyncio.sleep(0.2)
        console.print(" [green]✅ MICROSECOND CACHE FORCE PRIMED[/green]")
        
        # Initialize UNIFIED token discovery
        console.print("🧠 Initializing UNIFIED Token Discovery...", end="")
        self.signal_finder = UltimateTokenDiscovery()
        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 MICROSECOND price tracker
        console.print("📊 Starting MICROSECOND Price Tracker...", end="")
        self.price_tracker_task = asyncio.create_task(self.price_tracker.start_tracking())
        console.print(" [green]✅ STARTED[/green]")
        
        # 🔥 INITIALIZE ULTRA-FIXED RACING WEBSOCKET SYSTEM
        console.print("🌐 Initializing ULTRA-FIXED RACING WebSocket System...", end="")
        wallet_address = CONFIG.get("SOLANA_PUBLIC_KEY") or os.getenv("SOLANA_PUBLIC_KEY", "77ssrQ7LmPso1d1wYp4jAQdz4NqKSbKK8t6mFLcx6Xwr")
        api_key = CONFIG.get("HELIUS_API_KEY") or os.getenv("HELIUS_API_KEY", "86ab5634-df30-4a5b-bcfb-3f53d7095ca2")
        self.ws_listener = UltraFixedRacingWebSocket(wallet_address, api_key)
        console.print(" [green]✅ INITIALIZED[/green]")
        
        # 🔥 START ULTRA-FIXED RACING WEBSOCKET CONNECTIONS
        console.print("\n🚀 Starting ULTRA-FIXED RACING WebSocket System...")
        ws_success = await self.ws_listener.connect()
        
        # Handle balance initialization with MICROSECOND speed
        if ws_success and self.ws_listener.is_connected():
            await asyncio.sleep(3)
            ws_balance = self.ws_listener.get_balance_microsecond()  # 0.183μs access!
            if ws_balance > 0:
                self.session_start_balance = ws_balance
                self.session_start_total_value = ws_balance
                console.print(f"[green]💰 MICROSECOND WebSocket Balance: {ws_balance:.6f} SOL[/green]")
            else:
                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]💰 RPC Fallback Balance: {rpc_balance:.6f} SOL[/yellow]")
        
        # Display ready state
        console.print(f"\n[green]🎯 ULTRA-FIXED RACING QUANTUM BEAST READY! 🎯[/green]")
        console.print(f"💰 Total Account Value: {self.session_start_total_value:.6f} SOL")
        console.print(f"🌐 WebSocket: {self.ws_listener.get_connection_status()}")
        console.print(f"🎯 Targets: +{CONFIG.get('PROFIT_TARGET_PCT')}% / -{CONFIG.get('STOP_LOSS_PCT')}%")
        console.print(f"⏰ Max Hold: {CONFIG.get('MAX_HOLD_TIME_SECONDS')}s | Slippage: {CONFIG.get('SLIPPAGE')}%")
        console.print(f"⚡ MAGIC THRESHOLD: 0.01 SOL = GUARANTEED TRADE!")
        console.print(f"🔥 JUPITER FIX: Automatic transaction size optimization!")
        console.print(f"⚡ CACHE FORCE UPDATES: Active for maximum speed!")
    
    async def find_opportunities(self) -> List[Dict]:
        """🔍 Find opportunities using MICROSECOND-POWERED UNIFIED system"""
        try:
            # Use UNIFIED token discovery
            opportunities = await self.signal_finder.discover_tokens()
            
            if not opportunities:
                console.print("[INFO] No opportunities found from UNIFIED system")
                return []
            
            console.print(f"🔍 Found {len(opportunities)} opportunities from UNIFIED BLACKLIST system")
            
            # 🛡️ Safety validation on UNIFIED-filtered tokens
            if opportunities:
                console.print(f"🛡️ Running safety validation on {len(opportunities)} UNIFIED tokens...")
                mint_addresses = [signal['token_mint'] for signal in opportunities]
                
                api_key = CONFIG.get("HELIUS_API_KEY") or os.getenv("HELIUS_API_KEY")
                
                if not api_key:
                    console.print("[yellow]⚠️ No Helius API key - skipping safety validation[/yellow]")
                    return opportunities[:3]
                
                from helius_safety_validator import integrate_enhanced_safety_check
                
                try:
                    safe_mints = await integrate_enhanced_safety_check(self.signal_finder, mint_addresses)
                    
                    safe_opportunities = []
                    for signal in opportunities:
                        if signal['token_mint'] in safe_mints:
                            safe_opportunities.append(signal)
                    
                    console.print(f"🛡️ SAFETY FILTER: {len(safe_opportunities)}/{len(opportunities)} tokens passed")
                    opportunities = safe_opportunities
                    
                except Exception as e:
                    console.print(f"[yellow]⚠️ Safety validation error: {e} - proceeding without safety filter[/yellow]")
                    pass
            
            if not opportunities:
                console.print("[yellow]🛡️ All tokens filtered out by safety checks[/yellow]")
                return []
            
            # 🔥 MICROSECOND-POWERED GPU PROCESSING
            console.print(f"🔧 MICROSECOND GPU field mapping for {len(opportunities)} tokens...")
            opportunities = fix_gpu_field_mapping(opportunities)
            console.print(f"✅ MICROSECOND field mapping complete - all required fields present")
            
            try:
                gpu_signals = self.gpu_accelerator.scan_market(opportunities, [])
                console.print(f"[green]🎮 GPU processing successful! Generated {len(gpu_signals)} signals[/green]")
                
                if gpu_signals:
                    console.print(f"[green]🌊 GPU found {len(gpu_signals)} early wave signals![/green]")
                    for i, signal in enumerate(gpu_signals[:3]):
                        console.print(f"  {i+1}. {signal['symbol']}: {signal['signal_type']} (strength: {signal['signal_strength']:.3f})")
                else:
                    console.print(f"[yellow]🎮 GPU generated 0 signals - activating MICROSECOND fallback[/yellow]")
                
            except Exception as gpu_error:
                console.print(f"[red]🎮 GPU Error: {gpu_error}[/red]")
                gpu_signals = []
            
            # 🔥 MICROSECOND FALLBACK - Always create signals if GPU fails or generates 0
            if not gpu_signals and opportunities:
                console.print(f"[cyan]⚡ Creating MICROSECOND fallback signals for {len(opportunities)} opportunities[/cyan]")
                
                gpu_signals = []
                for i, opp in enumerate(opportunities[:3]):
                    price_change = opp["price_change_5m"]
                    volume_5m = opp["volume_5m"]
                    momentum = opp["momentum"]
                    safety_score = opp["safety_score"]
                    
                    # MICROSECOND signal strength calculation
                    signal_strength = (
                        (momentum / 100) * 0.4 +
                        (min(volume_5m / 10000, 1.0)) * 0.3 +
                        (safety_score / 100) * 0.3
                    )
                    signal_strength = max(0.15, min(1.0, signal_strength))  # Ensure minimum 0.15
                    
                    gpu_signals.append({
                        'symbol': opp['symbol'],
                        'token_mint': opp['token_mint'],
                        'price': opp['price'],
                        'price_usd': opp['price'],
                        'signal_type': 'MICROSECOND_FALLBACK',
                        'signal_strength': signal_strength,
                        'reasons': [f'MICROSECOND: momentum={momentum:.1f}, vol={volume_5m:.0f}, safety={safety_score:.0f}'],
                        'buy_sell_ratio': opp['buy_sell_ratio'],
                        'liquidity': opp['liquidity'],
                        'volume_24h': opp['volume_24h'],
                        'price_change_5m': price_change,
                        'volume_5m': volume_5m,
                        'momentum_score': momentum,
                        'safety_score': safety_score,
                        'microsecond_processed': True
                    })
                
                console.print(f"[green]⚡ Created {len(gpu_signals)} MICROSECOND fallback signals[/green]")
            
            # Filter by signal strength
            verified_signals = []
            min_strength = CONFIG.get("MIN_SIGNAL_STRENGTH", 0.5)
            
            for signal in gpu_signals:
                if signal.get('signal_strength', 0) >= min_strength:
                    signal['microsecond_verified'] = True
                    verified_signals.append(signal)
            
            if verified_signals:
                console.print(f"[green]🌊 MICROSECOND RESULT: {len(verified_signals)} verified signals[/green]")
                for wave in verified_signals[:3]:
                    console.print(f"  🏆 {wave['symbol']}: {wave['signal_type']} (score: {wave['signal_strength']:.3f})")
            else:
                console.print("[yellow]🎮 No signals met minimum strength requirement[/yellow]")
            
            return verified_signals
            
        except Exception as e:
            console.print(f"[red]💥 Opportunity finding error: {e}[/red]")
            import traceback
            traceback.print_exc()
            return []
    
    async def execute_trade(self, signal: Dict) -> bool:
        """🚀 Execute trade with ULTRA-FIXED RACING WEBSOCKET confirmation + JUPITER FIX!"""
        symbol = signal['symbol']
        token_mint = signal['token_mint']
        entry_price = signal['price']
        
        console.print(f"\n[bold]🎯 ULTRA-FIXED RACING TRADE: {symbol}[/bold] @ ${entry_price:.8f}")
        console.print(f"⚡ MAGIC THRESHOLD: 0.01 SOL | Filters: UNIFIED ✅ | Safety ✅ | GPU ✅")
        console.print(f"🔥 JUPITER FIX: Automatic transaction size optimization!")
        
        trade_start_time = time.time()
        execution_start = time.perf_counter()
        
        try:
            # 🔥 MICROSECOND PRE-TRADE ANALYSIS (0.183μs per operation)
            console.print("[cyan]⚡ MICROSECOND pre-trade analysis...[/cyan]")
            
            # INSTANT balance check (0.183μs)
            pre_balance = self.ws_listener.get_balance_microsecond()
            if pre_balance == 0:
                pre_balance = self.trader.get_sol_balance()
                console.print(f"[yellow]🔄 RPC Balance Fallback: {pre_balance:.6f} SOL[/yellow]")
            
            # INSTANT risk calculation (0.183μs)
            trade_amount = float(os.getenv("TRADE_AMOUNT", os.getenv("INITIAL_INVESTMENT", "0.05")))
            max_trade_size = pre_balance * 0.8
            trade_amount = min(trade_amount, max_trade_size)
            
            # INSTANT position validation (0.183μs)
            available_balance = pre_balance - 0.01
            if trade_amount > available_balance:
                console.print(f"[red]❌ Insufficient balance: Need {trade_amount:.6f}, have {available_balance:.6f}[/red]")
                return False
            
            console.print(f"[green]⚡ MICROSECOND ANALYSIS COMPLETE: {trade_amount:.6f} SOL approved[/green]")
            
            # 🔥 FORCE CACHE REFRESH FOR OPTIMAL EXECUTION
            console.print("[cyan]⚡ FORCE cache optimization for optimal execution...[/cyan]")
            self.trader.force_update_blockhash()
            
            # Use CONFIG slippage
            slippage = CONFIG.get("SLIPPAGE", 0.3)
            console.print(f"[cyan]⚡ Using slippage: {slippage}%[/cyan]")
            
            # 🔥 JUPITER TRANSACTION WITH AUTOMATIC SIZE FIX
            console.print(f"[cyan]🔥 Executing Jupiter swap with automatic transaction size optimization...[/cyan]")
            buy_start = time.perf_counter()
            buy_sig = await asyncio.get_event_loop().run_in_executor(
                None,
                self.trader.execute_jupiter_swap,
                "So11111111111111111111111111111111111111112",  # SOL
                token_mint,
                trade_amount,
                slippage,
                1
            )
            
            buy_exec_time = (time.perf_counter() - buy_start) * 1000
            self.execution_times.append(buy_exec_time)
            console.print(f"🚀 OPTIMIZED JUPITER BUY executed: {buy_exec_time:.0f}ms")
            
            # 🔥 ULTRA-FIXED RACING WEBSOCKET CONFIRMATION WITH MAGIC THRESHOLD!
            console.print("[cyan]⚡ Waiting for RACING WebSocket confirmation (0.01 SOL threshold)...[/cyan]")
            
            balance_change = await self.ws_listener.wait_for_balance_change(timeout=15.0)
            
            if balance_change and balance_change.get("is_real_trade"):
                # MAGIC THRESHOLD HIT! IT'S A REAL TRADE!
                sol_spent = abs(balance_change["change"])
                new_balance = balance_change["new_balance"]
                winner = balance_change["winner"]
                
                console.print(f"[green]✅ ULTRA-FIXED RACING CONFIRMATION: {sol_spent:.6f} SOL spent[/green]")
                console.print(f"[green]🏆 {winner}[/green]")
                
                post_balance = new_balance
                confirmed = True
                
                # 🔥 FORCE CACHE UPDATE FOR NEXT MICROSECOND TRADE
                console.print("[cyan]⚡ FORCE cache update for next trade...[/cyan]")
                self.trader.force_update_blockhash()
                
            else:
                console.print("[yellow]⏰ WebSocket timeout - RPC verification[/yellow]")
                await asyncio.sleep(2.0)
                post_balance = self.trader.get_sol_balance()
                sol_spent = round(pre_balance - post_balance, 6)
                confirmed = False
                
                if sol_spent > 0.01:
                    console.print(f"[green]✅ Trade verified via RPC - {sol_spent:.6f} SOL spent[/green]")
                    self.ws_listener.current_balance = post_balance
                    
                    # 🔥 FORCE CACHE UPDATE AFTER RPC CONFIRMATION
                    console.print("[cyan]⚡ FORCE cache update after RPC...[/cyan]")
                    self.trader.force_update_blockhash()
                else:
                    console.print("[red]❌ Trade verification failed[/red]")
                    return False
            
            # Get token balance
            await asyncio.sleep(1)
            token_balance = await asyncio.get_event_loop().run_in_executor(
                None,
                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 MICROSECOND position with REAL SOL TRACKING
            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('signal_type', 'BUY'),
                "signal_strength": signal.get('signal_strength', 0),
                "execution_time_ms": buy_exec_time,
                "confirming_websocket": "ULTRA_FIXED_RACING",
                "hold_time_seconds": 0,
                "pnl_pct": 0,
                "last_logged_pnl": 0,
                "highest_pnl": 0,
                "trailing_stop_active": False,
                "trailing_stop_level": 0,
                "entry_momentum": signal.get('momentum_score', 65),
                "unified_filtered": True,
                "microsecond_confirmed": True,
                "microsecond_trade": True,
                "jupiter_optimized": True,
                "cache_force_updated": True,
                "actual_sol_invested": sol_spent,
                "target_profit_sol": sol_spent * 0.05,
                "break_even_sol": sol_spent * 1.03,
            }
            
            self.positions[symbol] = position
            self.trades_executed += 1
            self.microsecond_operations += 1
            
            # Start MICROSECOND tracking
            self.price_tracker.add_token(symbol, token_mint, entry_price)
            if hasattr(self.signal_finder, 'track_position'):
                await self.signal_finder.track_position(symbol, token_mint, entry_price)
            
            # Update dashboard
            await self.update_dashboard()
            
            total_time = (time.perf_counter() - execution_start) * 1000
            console.print(f"[green]✅ ULTRA-FIXED RACING execution complete: {total_time:.0f}ms[/green]")
            console.print(f"[cyan]⚡ Next trade ready with MAGIC THRESHOLD protection![/cyan]")
            console.print(f"[green]🔥 Jupiter optimization successful - no transaction size issues![/green]")
            
            return True
            
        except Exception as e:
            console.print(f"[red]💥 ULTRA-FIXED RACING trade failed: {e}[/red]")
            traceback.print_exc()
            return False
    
    async def check_exit_conditions(self):
        """🎯 Check exit conditions using MICROSECOND speed with FORCE CACHE UPDATES"""
        if not self.positions:
            return
        
        # 🔥 FORCE CACHE UPDATE BEFORE CHECKING EXITS
        self.trader.force_update_blockhash()
        
        positions_to_close = []
        
        for symbol, position in self.positions.items():
            try:
                # Get real-time price with MICROSECOND speed
                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 = "[MICROSECOND-RT]"
                else:
                    current_price = position.get('current_price', entry_price)
                    source_text = "[CACHED]"
                
                position['current_price'] = current_price
                
                # Calculate pnl_pct
                if entry_price > 0:
                    pnl_pct = ((current_price - entry_price) / entry_price) * 100
                else:
                    pnl_pct = 0.0
                
                # MICROSECOND P&L calculation using REAL SOL AMOUNTS
                actual_sol_invested = position.get('actual_sol_invested', position.get('amount_sol', 0))
                
                if actual_sol_invested > 0:
                    current_token_balance = position.get('amount_tokens', 0)
                    if current_token_balance > 0:
                        estimated_current_sol_value = actual_sol_invested * (1 + (pnl_pct / 100))
                        real_pnl_sol = estimated_current_sol_value - actual_sol_invested
                        real_pnl_pct = (real_pnl_sol / actual_sol_invested) * 100
                        
                        position['real_pnl_sol'] = real_pnl_sol
                        position['real_pnl_pct'] = real_pnl_pct
                        position['pnl_pct'] = real_pnl_pct
                        
                        # Log significant REAL P&L changes
                        last_logged_pnl = position.get('last_logged_pnl', 0)
                        pnl_change = abs(real_pnl_pct - last_logged_pnl)
                        
                        if pnl_change >= 0.5 or (last_logged_pnl < 0 and real_pnl_pct > 0) or (last_logged_pnl > 0 and real_pnl_pct < 0):
                            style = "green" if real_pnl_pct > 0 else "red"
                            emoji = "🚀" if real_pnl_pct > 0 else "📉"
                            console.print(f"REAL P&L {symbol}: [{style}]{emoji} {real_pnl_pct:+.2f}% ({real_pnl_sol:+.6f} SOL)[/{style}] (${current_price:.8f}) {source_text}")
                            position['last_logged_pnl'] = real_pnl_pct
                    else:
                        real_pnl_pct = pnl_pct
                else:
                    real_pnl_pct = pnl_pct
                
                # Profit targets adjusted for trading costs
                profit_target = float(os.getenv("PROFIT_TARGET_PCT", "5.0"))
                stop_loss = float(os.getenv("STOP_LOSS_PCT", "1.8"))
                max_hold = int(os.getenv("MAX_HOLD_TIME_SECONDS", "400"))
                
                min_profitable_target = 2.0
                profit_target = max(profit_target, min_profitable_target)
                
                # Dynamic profit scaling
                signal_strength = position.get('signal_strength', 0)
                entry_momentum = position.get('entry_momentum', 65)
                
                if signal_strength > 0.7:
                    profit_target = max(profit_target, 8.0)
                elif signal_strength > 0.5:
                    profit_target = max(profit_target, 6.0)
                
                if entry_momentum > 100:
                    profit_target = max(profit_target, 12.0)
                elif entry_momentum > 80:
                    profit_target = max(profit_target, 8.0)
                
                # Trailing stop logic
                use_trailing = os.getenv("USE_TRAILING_STOPS", "true").lower() == "true"
                trailing_activation = float(os.getenv("TRAILING_STOP_ACTIVATION", "4.0"))
                trailing_distance = float(os.getenv("TRAILING_STOP_DISTANCE", "2.5"))
                
                current_pnl = real_pnl_pct
                
                if 'highest_pnl' not in position:
                    position['highest_pnl'] = current_pnl
                    position['trailing_stop_active'] = False
                
                if current_pnl > position['highest_pnl']:
                    position['highest_pnl'] = current_pnl
                
                if current_pnl >= trailing_activation and not position['trailing_stop_active']:
                    position['trailing_stop_active'] = True
                    position['trailing_stop_level'] = current_pnl - trailing_distance
                    console.print(f"[yellow]🎯 {symbol}: TRAILING STOP ACTIVATED at {current_pnl:+.2f}% (REAL P&L)[/yellow]")
                
                if position.get('trailing_stop_active', False) and use_trailing:
                    new_trailing_level = position['highest_pnl'] - trailing_distance
                    if new_trailing_level > position.get('trailing_stop_level', -999):
                        position['trailing_stop_level'] = new_trailing_level
                        console.print(f"[cyan]📈 {symbol}: Trailing stop moved to {new_trailing_level:+.2f}% (REAL)[/cyan]")
                
                position['hold_time_seconds'] = time.time() - position['entry_time']
                
                should_exit = False
                exit_reason = None
                
                # Exit conditions using REAL P&L
                if position.get('trailing_stop_active', False) and use_trailing:
                    trailing_level = position.get('trailing_stop_level', -999)
                    if current_pnl <= trailing_level:
                        should_exit = True
                        exit_reason = "TRAILING_STOP"
                        console.print(f"[yellow]📉 {symbol}: TRAILING STOP at {current_pnl:+.2f}% (was at {position['highest_pnl']:+.2f}%) [REAL P&L][/yellow]")
                
                elif current_pnl >= profit_target:
                    should_exit = True
                    exit_reason = "PROFIT_TARGET"
                    console.print(f"[green]🎯 {symbol}: PROFIT TARGET at {current_pnl:+.2f}% (target: {profit_target:.1f}%) [REAL P&L][/green]")
                
                elif current_pnl > 4.0 and position['hold_time_seconds'] > 30:
                    recent_price_trend = self._calculate_price_trend(symbol)
                    if recent_price_trend < -0.5:
                        should_exit = True
                        exit_reason = "MOMENTUM_REVERSAL"
                        console.print(f"[yellow]🔄 {symbol}: MOMENTUM REVERSAL at {current_pnl:+.2f}% [REAL P&L][/yellow]")
                
                elif current_pnl <= -stop_loss:
                    should_exit = True
                    exit_reason = "STOP_LOSS"
                    console.print(f"[red]🛑 {symbol}: STOP LOSS at {current_pnl:+.2f}% [REAL P&L][/red]")
                
                elif position['hold_time_seconds'] >= max_hold:
                    should_exit = True
                    exit_reason = "MAX_HOLD_TIME"
                    console.print(f"[yellow]⏰ {symbol}: TIME LIMIT ({position['hold_time_seconds']:.0f}s) [REAL P&L][/yellow]")
                
                elif current_pnl >= 30.0:
                    should_exit = True
                    exit_reason = "EMERGENCY_PROFIT"
                    console.print(f"[green]🚨 {symbol}: EMERGENCY EXIT at {current_pnl:+.2f}% (massive gains!) [REAL P&L][/green]")
                
                if should_exit:
                    positions_to_close.append((symbol, position, exit_reason))
                    
            except Exception as e:
                console.print(f"[red]❌ MICROSECOND exit check error for {symbol}: {e}[/red]")
                import traceback
                traceback.print_exc()
        
        # Execute MICROSECOND sells with JUPITER FIX
        for symbol, position, exit_reason in positions_to_close:
            await self._execute_microsecond_sell(symbol, position, exit_reason)
    
    def _calculate_price_trend(self, symbol: str) -> float:
        """Calculate recent price trend for momentum reversal detection"""
        try:
            if symbol not in self.price_tracker.price_history:
                return 0.0
            
            history = list(self.price_tracker.price_history[symbol])
            if len(history) < 3:
                return 0.0
            
            recent_prices = [h['price'] for h in history[-3:]]
            
            if len(recent_prices) >= 2:
                price_change = ((recent_prices[-1] - recent_prices[0]) / recent_prices[0]) * 100
                return price_change
            
            return 0.0
        except Exception:
            return 0.0
    
    async def _execute_microsecond_sell(self, symbol: str, position: Dict, exit_reason: str):
        """💰 Execute sell with ULTRA-FIXED RACING WEBSOCKET confirmation + JUPITER FIX!"""
        console.print(f"\n[bold]💰 ULTRA-FIXED RACING SELLING {symbol}[/bold] - Reason: {exit_reason}")
        console.print(f"🔥 JUPITER FIX: Automatic transaction size optimization for sells!")
        
        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]
            self.price_tracker.remove_token(symbol)
            return
        
        # MICROSECOND SELL PREPARATION
        console.print("[cyan]⚡ MICROSECOND sell analysis...[/cyan]")
        
        # INSTANT balance validation (0.183μs)
        current_balance = self.ws_listener.get_balance_microsecond()
        if current_balance == 0:
            current_balance = self.trader.get_sol_balance()
        
        # INSTANT sell calculation (0.183μs)
        sell_percentage = float(os.getenv("SELL_PERCENTAGE", "0.997"))
        sell_amount = token_balance * sell_percentage
        
        # 🔥 FORCE CACHE REFRESH FOR OPTIMAL SELL EXECUTION
        console.print("[cyan]⚡ FORCE cache refresh for optimal sell...[/cyan]")
        self.trader.force_update_blockhash()
        
        console.print(f"[green]⚡ MICROSECOND SELL PREP COMPLETE: {sell_amount:.6f} {symbol} ready[/green]")
        
        # Use CONFIG slippage
        slippage = CONFIG.get("SLIPPAGE", 0.3)
        console.print(f"[cyan]⚡ Using sell slippage: {slippage}%[/cyan]")
        
        max_retries = 3
        retry_count = 0
        
        while retry_count < max_retries:
            try:
                console.print(f"[yellow]🔄 JUPITER-OPTIMIZED sell attempt {retry_count + 1}/{max_retries}[/yellow]")
                
                # Get pre-sell balance with MICROSECOND speed
                pre_balance = self.ws_listener.get_balance_microsecond()
                if pre_balance == 0:
                    pre_balance = self.trader.get_sol_balance()
                
                # 🔥 EXECUTE JUPITER SELL WITH AUTOMATIC SIZE OPTIMIZATION
                console.print(f"[cyan]🔥 Executing Jupiter sell with automatic transaction size optimization...[/cyan]")
                sell_start = time.perf_counter()
                sell_sig = await asyncio.get_event_loop().run_in_executor(
                    None,
                    self.trader.sell_token_for_sol_via_jupiter,
                    token_mint,
                    sell_amount,
                    slippage,
                    1
                )
                
                sell_exec_time = (time.perf_counter() - sell_start) * 1000
                
                if sell_exec_time < 800:
                    console.print(f"💰 JUPITER-OPTIMIZED SELL: {sell_exec_time:.0f}ms")
                else:
                    console.print(f"💰 Sell executed: {sell_exec_time:.0f}ms")
                
                # 🔥 ULTRA-FIXED RACING WEBSOCKET CONFIRMATION WITH MAGIC THRESHOLD!
                console.print("[cyan]⚡ Waiting for RACING WebSocket sell confirmation (0.01 SOL threshold)...[/cyan]")
                
                balance_change = await self.ws_listener.wait_for_balance_change(timeout=15.0)
                
                if balance_change and balance_change.get("is_real_trade"):
                    # MAGIC THRESHOLD HIT! SELL CONFIRMED!
                    sol_received = balance_change["change"]  # Should be positive for sells
                    new_balance = balance_change["new_balance"]
                    winner = balance_change["winner"]
                    
                    console.print(f"[green]✅ ULTRA-FIXED RACING sell confirmation: {sol_received:.6f} SOL received[/green]")
                    console.print(f"[green]🏆 {winner}[/green]")
                    
                    post_balance = new_balance
                    confirmed = True
                    
                    # 🔥 FORCE CACHE UPDATE FOR NEXT MICROSECOND TRADE
                    console.print("[cyan]⚡ FORCE cache update for next trade...[/cyan]")
                    self.trader.force_update_blockhash()
                    
                elif retry_count == max_retries - 1:
                    console.print("[yellow]⏰ WebSocket timeout - RPC verification[/yellow]")
                    await asyncio.sleep(1.2)
                    post_balance = self.trader.get_sol_balance()
                    sol_received = post_balance - pre_balance
                    
                    if sol_received > 0.01:
                        console.print(f"[green]✅ Sell verified via RPC - {sol_received:.6f} SOL received[/green]")
                        self.ws_listener.current_balance = post_balance
                        confirmed = True
                        
                        # 🔥 FORCE CACHE UPDATE AFTER RPC SELL CONFIRMATION  
                        console.print("[cyan]⚡ FORCE cache update after RPC...[/cyan]")
                        self.trader.force_update_blockhash()
                    else:
                        console.print(f"[red]❌ Sell attempt {retry_count + 1} failed - WebSocket reconnection triggered[/red]")
                        
                        # Force WebSocket reconnection on sell failure
                        console.print("[yellow]🔄 Forcing WebSocket reconnection after sell failure...[/yellow]")
                        self.ws_listener.helius_connected = False
                        self.ws_listener.winny_connected = False
                        
                        retry_count += 1
                        if retry_count < max_retries:
                            sell_amount = sell_amount * sell_percentage
                            await asyncio.sleep(0.8)
                        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 * sell_percentage
                        await asyncio.sleep(0.8)
                    continue
                
                # REAL P&L CALCULATION USING ACTUAL SOL AMOUNTS!
                amount_sol_invested = position.get('actual_sol_invested', position.get('amount_sol', 0))
                
                # This is the ONLY accurate way to calculate P&L
                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
                
                console.print(f"[cyan]💰 REAL P&L CALCULATION:[/cyan]")
                console.print(f"[cyan]   SOL Invested: {amount_sol_invested:.6f}[/cyan]")
                console.print(f"[cyan]   SOL Received: {sol_received:.6f}[/cyan]")
                console.print(f"[cyan]   Net P&L: {net_pnl_sol:+.6f} SOL ({net_pnl_pct:+.2f}%)[/cyan]")
                
                # Stop MICROSECOND tracking
                self.price_tracker.remove_token(symbol)
                if hasattr(self.signal_finder, 'stop_tracking'):
                    await self.signal_finder.stop_tracking(symbol)
                
                # Record MICROSECOND trade with REAL P&L
                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_sol,
                    "pnl_pct": net_pnl_pct,
                    "hold_time": position.get('hold_time_seconds', 0),
                    "exit_reason": exit_reason,
                    "signal_type": position.get('signal_type', 'UNKNOWN'),
                    "is_win": net_pnl_sol > 0,
                    "sell_signature": sell_sig,
                    "execution_time_ms": sell_exec_time,
                    "confirming_websocket": "ULTRA_FIXED_RACING",
                    "unified_filtered": position.get('unified_filtered', False),
                    "microsecond_confirmed": position.get('microsecond_confirmed', False),
                    "microsecond_trade": True,
                    "jupiter_optimized": True,
                    "cache_force_updated": True,
                    "real_pnl_tracking": True,
                    "trading_costs_pct": abs(net_pnl_sol / amount_sol_invested * 100) if net_pnl_sol < 0 else 0
                }
                
                self.completed_trades.append(trade_record)
                self.recent_trades.append(trade_record)
                
                # Keep only last 10 recent trades
                if len(self.recent_trades) > 10:
                    self.recent_trades.pop(0)
                
                # Update stats with REAL P&L
                if net_pnl_sol > 0:
                    self.trades_won += 1
                    self.best_trade = max(self.best_trade, net_pnl_pct)
                    console.print(f"[green]🎉 REAL WINNING TRADE #{self.trades_won}! +{net_pnl_pct:.2f}% (+{net_pnl_sol:.6f} SOL)[/green]")
                else:
                    self.trades_lost += 1
                    self.worst_trade = min(self.worst_trade, net_pnl_pct)
                    console.print(f"[red]📉 Real losing trade #{self.trades_lost}. {net_pnl_pct:.2f}% (-{abs(net_pnl_sol):.6f} SOL)[/red]")
                
                # Remove position
                del self.positions[symbol]
                
                # Update dashboard
                await self.update_dashboard()
                
                style = "green" if net_pnl_sol > 0 else "red"
                emoji = "🏆" if net_pnl_sol > 0 else "💀"
                console.print(f"[green]✅ ULTRA-FIXED RACING SELL SUCCESS:[/green] [{style}]{emoji} {net_pnl_sol:+.6f} SOL ({net_pnl_pct:+.2f}%)[/{style}]")
                console.print(f"[cyan]⚡ Ready for next ULTRA-FIXED RACING trade![/cyan]")
                console.print(f"[green]🔥 Jupiter optimization successful - no transaction size issues![/green]")
                
                return  # SUCCESS
            
            except Exception as e:
                console.print(f"[red]💥 JUPITER-OPTIMIZED sell attempt {retry_count + 1} failed: {e}[/red]")
                retry_count += 1
                if retry_count < max_retries:
                    sell_amount = sell_amount * sell_percentage
                    await asyncio.sleep(0.8)
        
        # All retries failed - force close
        console.print(f"[red]💀 FORCE CLOSE: All {max_retries} attempts failed for {symbol}[/red]")

        # Stop tracking regardless
        self.price_tracker.remove_token(symbol)

        # Remove position to prevent infinite loop
        if symbol in self.positions:
            del self.positions[symbol]

        await self.update_dashboard()
    
    async def update_dashboard(self):
        """📊 Update dashboard with MICROSECOND metrics and FORCE CACHE UPDATES"""
        try:
            current_time = time.time()
            
            # 🔥 PERIODIC CACHE FORCE UPDATE FOR DASHBOARD
            if self.dashboard_update_count % 5 == 0:  # Every 5th update
                self.trader.force_update_blockhash()
            
            # Calculate account value with MICROSECOND speed
            total_account_value, liquid_sol, total_invested_in_positions = self.calculate_total_account_value_microsecond()
            
            # Session metrics
            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)
            
            # Unrealized P&L with MICROSECOND calculations
            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 P&L
            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
            
            # MICROSECOND 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
            
            # UNIFIED BLACKLIST stats
            unified_stats = BLACKLIST.get_stats()
            
            # ULTRA-FIXED RACING WebSocket stats
            racing_stats = self.ws_listener.get_racing_stats()
            
            # Active position data with MICROSECOND tracking
            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.get("TRADE_AMOUNT", 0.05))
                    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', 'BUY'),
                    "signal_strength": pos.get('signal_strength', 0),
                    "unified_filtered": pos.get('unified_filtered', False),
                    "microsecond_confirmed": pos.get('microsecond_confirmed', False),
                    "microsecond_trade": pos.get('microsecond_trade', False),
                    "jupiter_optimized": pos.get('jupiter_optimized', False),
                    "cache_force_updated": pos.get('cache_force_updated', False)
                }
            
            # Build ULTRA-FIXED RACING dashboard data
            dashboard_data = {
                "timestamp": current_time,
                
                # MICROSECOND balance tracking
                "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
                "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
                "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
                "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
                "active_position": bool(self.positions),
                "active_positions": len(self.positions),
                "position": active_position_data,
                "positions": self.positions,
                
                # Trade history
                "recent_trades": self.recent_trades[-5:],
                "completed_trades": self.completed_trades,
                
                # ULTRA-FIXED RACING WebSocket system status
                "websocket_active": self.ws_listener.is_connected(),
                "websocket_status": self.ws_listener.get_connection_status(),
                "current_endpoint": CONFIG.get("PRIMARY_RPC_URL", "").split('/')[-1] if CONFIG.get("PRIMARY_RPC_URL") else "N/A",
                
                # ULTRA-FIXED RACING WebSocket stats
                "racing_stats": racing_stats,
                "ws_confirmations": racing_stats["total_updates"],
                "helius_wins": racing_stats["helius_wins"],
                "winny_wins": racing_stats["winny_wins"],
                "real_trades_detected": racing_stats["real_trades_detected"],
                "gas_only_ignored": racing_stats["gas_only_ignored"],
                "magic_threshold": racing_stats["magic_threshold"],
                
                # UNIFIED BLACKLIST stats
                "unified_filter": {
                    "tokens_checked": unified_stats["quality_checks_performed"],
                    "tokens_filtered": unified_stats["tokens_filtered"],
                    "signals_generated": unified_stats["signals_generated"],
                    "safety_checks_saved": unified_stats["safety_checks_saved"],
                    "blacklisted_tokens": unified_stats["blacklisted_tokens"],
                    "allowed_dexes": unified_stats["allowed_dexes"],
                    "blocked_dexes": unified_stats["blocked_dexes"]
                },
                
                # MICROSECOND performance metrics
                "microsecond_operations": self.microsecond_operations,
                "avg_execution_time": avg_execution_time,
                "fastest_execution": fastest_execution,
                "avg_confirmation_time": avg_confirmation_time,
                
                # Price tracking stats with MICROSECOND access
                "price_tracking_active": self.price_tracker.running,
                "tracked_tokens": len(self.price_tracker.tracking_tokens),
                "price_alerts": list(self.price_tracker.price_alerts)[-5:],
                "microsecond_price_updates": self.price_tracker.microsecond_updates,
                
                # Configuration
                "config": {
                    "trade_amount_sol": CONFIG.get("TRADE_AMOUNT"),
                    "profit_target_pct": CONFIG.get("PROFIT_TARGET_PCT"),
                    "stop_loss_pct": CONFIG.get("STOP_LOSS_PCT"),
                    "max_hold_time": CONFIG.get("MAX_HOLD_TIME_SECONDS"),
                    "min_signal_strength": CONFIG.get("MIN_SIGNAL_STRENGTH"),
                    "compute_limit": CONFIG.get("COMPUTE_LIMIT"),
                    "priority_fee": CONFIG.get("PRIORITY_FEE"),
                    "price_update_interval": CONFIG.get("PRICE_UPDATE_INTERVAL"),
                    "slippage_percent": CONFIG.get("SLIPPAGE"),
                    "sell_percentage": CONFIG.get("SELL_PERCENTAGE"),
                    "min_liquidity_usd": CONFIG.get("MIN_LIQUIDITY_USD"),
                    "min_volume_24h": CONFIG.get("MIN_VOLUME_24H"),
                    "min_volume_5m": CONFIG.get("MIN_VOLUME_5M"),
                    "min_price_change_5m": CONFIG.get("MIN_PRICE_CHANGE_5M"),
                    "max_price_change_5m": CONFIG.get("MAX_PRICE_CHANGE_5M")
                },
                
                # Meta
                "last_update": datetime.now().strftime('%I:%M:%S %p'),
                "status": "🔥 ULTRA_FIXED_RACING_ACTIVE" if self.running else "🛑 STOPPED",
                "version": "ULTRA_FIXED_RACING_QUANTUM_BEAST_0.01_SOL_MAGIC_THRESHOLD",
                "update_count": self.dashboard_update_count
            }
            
            self.dashboard_update_count += 1
            
            # Write dashboard data 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")
            
            # Log ULTRA-FIXED RACING updates every 10 iterations
            if self.dashboard_update_count % 10 == 0:
                ultra_fixed_trades = len([t for t in self.completed_trades if t.get('microsecond_trade')])
                console.print(f"📊 ULTRA-FIXED RACING Update #{self.dashboard_update_count}: "
                             f"Total Value: {total_account_value:.6f} SOL | "
                             f"Session P&L: {session_pnl:+.6f} SOL ({session_pnl_pct:+.2f}%) | "
                             f"Racing Trades: {ultra_fixed_trades} | "
                             f"Magic Threshold Hits: {racing_stats['real_trades_detected']} | "
                             f"Gas Ignored: {racing_stats['gas_only_ignored']}")
            
        except Exception as e:
            console.print(f"[red]📊 ULTRA-FIXED RACING dashboard update error: {e}[/red]")
            traceback.print_exc()
    
    async def dashboard_update_loop(self):
        """📊 Continuous ULTRA-FIXED RACING dashboard update loop"""
        while self.running:
            try:
                await self.update_dashboard()
                await asyncio.sleep(CONFIG.get("DASHBOARD_UPDATE_INTERVAL", 2.0))
            except asyncio.CancelledError:
                break
            except Exception as e:
                console.print(f"[yellow]📊 ULTRA-FIXED RACING dashboard loop error: {e}[/yellow]")
                await asyncio.sleep(CONFIG.get("DASHBOARD_UPDATE_INTERVAL", 2.0))
    
    async def run_trading_loop(self):
        """🔄 Main ULTRA-FIXED RACING trading loop with 0.01 SOL magic threshold"""
        console.print("\n[bold]🔥 STARTING ULTRA-FIXED RACING QUANTUM BEAST TRADING LOOP 🔥[/bold]")
        console.print("[cyan]⚡ MAGIC THRESHOLD: 0.01 SOL = GUARANTEED TRADES![/cyan]")
        console.print("[cyan]⚡ Gas Detection: < 0.01 SOL = IGNORED![/cyan]")
        
        # Start ULTRA-FIXED RACING 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 opportunities with MICROSECOND speed
                    check_interval = CONFIG.get("CHECK_INTERVAL", 30)
                    max_positions = CONFIG.get("MAX_CONCURRENT_POSITIONS", 1)
                    
                    if current_time - last_scan_time >= check_interval:
                        if len(self.positions) < max_positions:
                            console.print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔥 ULTRA-FIXED RACING opportunity scan...")
                            
                            # Get current total account value with MICROSECOND speed
                            total_value, liquid_sol, invested_sol = self.calculate_total_account_value_microsecond()
                            console.print(f"💰 Account Value: {total_value:.6f} SOL (Liquid: {liquid_sol:.6f}, Invested: {invested_sol:.6f})")
                            console.print(f"🌐 WebSocket: {self.ws_listener.get_connection_status()}")
                            
                            # Show racing stats
                            racing_stats = self.ws_listener.get_racing_stats()
                            console.print(f"🏁 Racing Stats: Trades: {racing_stats['real_trades_detected']} | Gas Ignored: {racing_stats['gas_only_ignored']}")
                            console.print(f"🏆 Race Winners: Helius: {racing_stats['helius_wins']} ({racing_stats['helius_win_rate']:.1f}%) | Winny: {racing_stats['winny_wins']} ({racing_stats['winny_win_rate']:.1f}%)")
                            console.print("="*60)
                            
                            opportunities = await self.find_opportunities()
                            
                            if opportunities:
                                best_signal = opportunities[0]
                                if best_signal['symbol'] not in self.positions:
                                    console.print(f"[green]🎯 ULTRA-FIXED RACING executing trade on {best_signal['symbol']}[/green]")
                                    success = await self.execute_trade(best_signal)
                                    if success:
                                        console.print(f"[green]✅ ULTRA-FIXED RACING trade successful![/green]")
                                        await asyncio.sleep(3)
                                    else:
                                        console.print(f"[red]❌ ULTRA-FIXED RACING trade failed[/red]")
                        
                        last_scan_time = current_time
                    
                    # Check exit conditions with MICROSECOND speed
                    await self.check_exit_conditions()
                    
                    # Sleep using CONFIG interval
                    position_check_interval = CONFIG.get("POSITION_CHECK_INTERVAL", 0.5)
                    await asyncio.sleep(position_check_interval)
                    
                except KeyboardInterrupt:
                    console.print("\n[yellow]⚠️ ULTRA-FIXED RACING shutdown requested by user[/yellow]")
                    self.shutdown_event.set()
                except Exception as e:
                    console.print(f"[red]💥 ULTRA-FIXED RACING 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 ULTRA-FIXED RACING Quantum Beast"""
        self.running = True
        try:
            await self.initialize()
            await self.run_trading_loop()
        except KeyboardInterrupt:
            console.print("\n[yellow]⚠️ Shutting down ULTRA-FIXED RACING Quantum Beast...[/yellow]")
        finally:
            self.running = False
            await self.update_dashboard()  # Final dashboard update
            if self.ws_listener:
                await self.ws_listener.close()
            if hasattr(self, 'price_tracker_task'):
                self.price_tracker_task.cancel()
            if hasattr(BLACKLIST, 'close'):
                await BLACKLIST.close()
            
            # Final ULTRA-FIXED RACING stats
            final_racing_stats = self.ws_listener.get_racing_stats()
            console.print(f"\n[cyan]🏆 FINAL ULTRA-FIXED RACING STATS:[/cyan]")
            console.print(f"⚡ Total Operations: {self.microsecond_operations}")
            console.print(f"⚡ Real Trades Detected: {final_racing_stats['real_trades_detected']}")
            console.print(f"⚡ Gas Only Ignored: {final_racing_stats['gas_only_ignored']}")
            console.print(f"⚡ Magic Threshold: {final_racing_stats['magic_threshold']}")
            console.print(f"⚡ Detection Accuracy: {final_racing_stats['detection_accuracy']}")
            console.print(f"🎯 Total Trades: {self.trades_executed}")
            console.print(f"🏆 Winning Trades: {self.trades_won}")
            console.print(f"💀 Losing Trades: {self.trades_lost}")


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


async def main():
    """🔥 Main entry point for ULTRA-FIXED RACING Quantum Beast"""
    # Setup signal handlers
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    console.print("\n" + "🔥" * 100)
    console.print("🏆 ULTRA-FIXED RACING QUANTUM BEAST - 0.01 SOL MAGIC THRESHOLD! 🏆".center(100))
    console.print("💎 FIXED: Winny-Rychu WebSocket URL (NO API KEY NEEDED!) 💎".center(100))
    console.print("🔥" * 100 + "\n")
    
    console.print("🔥 ULTRA-FIXED RACING FEATURES:")
    console.print("   ✅ FIXED: Winny-Rychu URL without API key")
    console.print("   ✅ 0.01 SOL MAGIC THRESHOLD - GUARANTEED TRADE DETECTION!")
    console.print("   ✅ Gas detection: < 0.01 SOL = IGNORED (no false positives)")
    console.print("   ✅ Dual WebSocket racing: Helius vs Winny-Rychu")
    console.print("   ✅ 0.183μs balance access - 413,349x FASTER than RPC")
    console.print("   ✅ MICROSECOND-powered GPU processing")
    console.print("   ✅ YOUR EXACT .env trading parameters")
    console.print("   ✅ UNIFIED BLACKLIST comprehensive filtering")
    console.print("   ✅ Advanced safety validation")
    console.print("   ✅ Real-time MICROSECOND price tracking")
    console.print("   🔥 ULTRA-FIXED RACING PROTECTION:")
    console.print(f"       - Blacklisted tokens: {len(CONFIG.get('BLACKLISTED_TOKENS', set())) if hasattr(CONFIG, 'get') else 'Loading...'}")
    console.print(f"       - DEX filtering: {CONFIG.get('ALLOWED_DEXES', set()) if hasattr(CONFIG, 'get') else 'Loading...'}")
    console.print("       - Quality filtering with MICROSECOND thresholds")
    console.print("       - Safety validation with MICROSECOND holder analysis")
    console.print("       - FOMO protection with MICROSECOND signal rejection")
    console.print(f"   🔥 ULTRA-FIXED RACING QUALITY FILTERS:")
    console.print(f"       - Min Liquidity: ${CONFIG.get('MIN_LIQUIDITY_USD', 0):,}")
    console.print(f"       - Min 24h Volume: ${CONFIG.get('MIN_VOLUME_24H', 0):,}")
    console.print(f"       - Min 5m Volume: ${CONFIG.get('MIN_VOLUME_5M', 0):,}")
    console.print(f"       - Price Movement Range: {CONFIG.get('MIN_PRICE_CHANGE_5M', 0)}% - {CONFIG.get('MAX_PRICE_CHANGE_5M', 0)}%")
    console.print(f"   🔥 ULTRA-FIXED RACING TRADING PARAMETERS:")
    console.print(f"       - Trade Amount: {CONFIG.get('TRADE_AMOUNT', 0)} SOL")
    console.print(f"       - Profit Target: {CONFIG.get('PROFIT_TARGET_PCT', 0)}%")
    console.print(f"       - Stop Loss: {CONFIG.get('STOP_LOSS_PCT', 0)}%")
    console.print(f"       - Max Hold Time: {CONFIG.get('MAX_HOLD_TIME_SECONDS', 0)}s")
    console.print(f"       - Slippage: {CONFIG.get('SLIPPAGE', 0)}%")
    
    console.print(f"\n🔥 Starting ULTRA-FIXED RACING Quantum Beast in 3 seconds...")
    console.print("💰 0.01 SOL MAGIC THRESHOLD + FIXED WEBSOCKETS = PERFECT TRADING! 💰")
    console.print("🔥 NO MORE HTTP 522 ERRORS - WINNY URL FIXED! 🔥")
    time.sleep(3)
    
    # Initialize and start ULTRA-FIXED RACING Quantum Beast
    quantum_beast = MicrosecondQuantumBeast()
    await quantum_beast.start()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        console.print("\n[yellow]⚠️ ULTRA-FIXED RACING program interrupted by user[/yellow]")
    except Exception as e:
        console.print(f"\n[red]💥 ULTRA-FIXED RACING fatal error: {e}[/red]")
        traceback.print_exc()
         fix the bottom script with the top stuff integrated please and write the full script