can you please # quantum_optimized.py
import asyncio
import websockets
import json
import base64
import logging
import time
from dataclasses import dataclass
from typing import Dict, Set, List, Optional
import torch
from solana_rust_bot import TradingCore
from position_scaler import PositionScaler

@dataclass
class TokenInfo:
    mint: str
    decimals: int
    volume_24h: float
    holders: int
    is_verified: bool
    last_validation: float

@dataclass
class PoolMetrics:
    liquidity: float
    volume_5min: float
    buy_pressure: int
    sell_pressure: int
    price: float
    holder_count: int
    mint_authority: bool
    liquidity_locked: float

class QuantumOptimized:
    def __init__(self, config):
        # Core initialization
        self.config = config
        self.core = TradingCore()
        self.scaler = PositionScaler()
        
        # CUDA setup
        self.device = torch.device('cuda')
        torch.backends.cudnn.benchmark = True
        self.gpu_streams = [torch.cuda.Stream() for _ in range(config.STREAMS)]
        
        # Program IDs
        self.TOKEN_PROGRAM = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
        self.RAYDIUM_PROGRAM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
        
        # Validation caches
        self.valid_tokens: Dict[str, TokenInfo] = {}
        self.valid_pools: Dict[str, PoolMetrics] = {}
        self.blacklisted_tokens: Set[str] = set()
        
        # Connection management
        self.endpoints = {
            "marga": {
                "ws": config.MARGA_WS,
                "rpc": config.MARGA_RPC,
                "tps": 5
            },
            "xyz": {
                "ws": "wss://rpc-ws-mainnet.helius.xyz",
                "rpc": "https://rpc-ws-mainnet.helius.xyz",
                "tps": 100
            }
        }
        
        # Initialize logging
        self._setup_logging()
        
        self.logger.info("🚀 Quantum Trading System Initialized")
        self.logger.info(f"💎 GPU: {torch.cuda.get_device_name(0)}")
        self.logger.info(f"💫 Streams: {config.STREAMS}")

    def _setup_logging(self):
        """Setup enhanced logging"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s | %(levelname)s | %(message)s',
            handlers=[
                logging.FileHandler("quantum.log"),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger(__name__)

    async def start(self):
        """Start the optimized trading system"""
        self.logger.info("Starting Quantum Trading System")
        
        # Initialize validation tasks
        validation_tasks = [
            self._monitor_token_program(endpoint["ws"]) 
            for endpoint in self.endpoints.values()
        ]
        
        # Initialize trading tasks
        trading_tasks = [
            self._monitor_trading_opportunities(endpoint["ws"])
            for endpoint in self.endpoints.values()
        ]
        
        # Start all tasks
        await asyncio.gather(
            *validation_tasks,
            *trading_tasks,
            self._cleanup_routine()
        )
    
    async def _monitor_token_program(self, ws_url: str):
        """Monitor Token program for validation"""
        while True:
            try:
                async with websockets.connect(ws_url) as ws:
                    self.logger.info(f"Connected to Token monitor: {ws_url}")
                    
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "programSubscribe",
                        "params": [
                            self.TOKEN_PROGRAM,
                            {"encoding": "jsonParsed"}
                        ]
                    }))
                    
                    async for msg in ws:
                        await self._validate_token_message(json.loads(msg))
                        
            except Exception as e:
                self.logger.error(f"Token monitoring error: {e}")
                await asyncio.sleep(1)

    async def _validate_token_message(self, msg: Dict):
        """Validate token messages with thorough checks"""
        try:
            if "params" not in msg or "result" not in msg["params"]:
                return
                
            result = msg["params"]["result"]
            token_mint = result.get("mint")
            
            if token_mint in self.blacklisted_tokens:
                return
                
            # Comprehensive token validation
            is_valid = await self._validate_token(token_mint)
            
            if is_valid:
                token_info = await self._get_token_info(token_mint)
                if self._meets_token_requirements(token_info):
                    self.valid_tokens[token_mint] = token_info
                    self.logger.debug(f"Validated token: {token_mint}")
            else:
                self.blacklisted_tokens.add(token_mint)
                
        except Exception as e:
            self.logger.error(f"Token validation error: {e}")

    async def _validate_token(self, token_mint: str) -> bool:
        """Thorough token validation"""
        try:
            if not self._is_valid_address(token_mint):
                return False
                
            # Check token program ownership
            account_info = await self._get_account_info(token_mint)
            if not account_info:
                return False
                
            return (
                account_info["owner"] == self.TOKEN_PROGRAM and
                "tokenAmount" in account_info["data"]["parsed"]["info"] and
                not self._is_suspicious_token(account_info)
            )
            
        except Exception:
            return False

    async def _monitor_trading_opportunities(self, ws_url: str):
        """Monitor for trading opportunities"""
        while True:
            try:
                async with websockets.connect(ws_url) as ws:
                    self.logger.info(f"Connected to trading monitor: {ws_url}")
                    
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "programSubscribe",
                        "params": [
                            self.RAYDIUM_PROGRAM,
                            {"encoding": "base64"}
                        ]
                    }))
                    
                    async for msg in ws:
                        await self._process_trading_message(json.loads(msg))
                        
            except Exception as e:
                self.logger.error(f"Trading monitor error: {e}")
                await asyncio.sleep(1)

    async def _process_trading_message(self, msg: Dict):
        """Process trading opportunities with validation"""
        try:
            if "params" not in msg or "result" not in msg["params"]:
                return
                
            pool_data = self._decode_pool_data(
                msg["params"]["result"]["value"]["account"]["data"][0]
            )
            
            if not pool_data:
                return
                
            # Validate pool metrics
            if self._is_valid_opportunity(pool_data):
                await self._execute_trading_strategy(pool_data)
                
        except Exception as e:
            self.logger.error(f"Trading process error: {e}")

    def _is_valid_opportunity(self, pool_data: Dict) -> bool:
        """Validate trading opportunity"""
        try:
            metrics = pool_data["metrics"]
            
            return (
                metrics["volume_5min"] >= self.config.MIN_VOL_5MIN and
                not metrics["mint_authority"] and
                metrics["liquidity_locked"] >= self.config.LIQUIDITY_LOCK_MIN and
                metrics["buy_pressure"] / max(metrics["sell_pressure"], 1) >= 
                self.config.MIN_BUY_SELL_RATIO and
                pool_data["token_mint"] in self.valid_tokens
            )
            
        except Exception:
            return False

    async def _cleanup_routine(self):
        """Periodic cleanup and maintenance"""
        while True:
            try:
                # Clean up old validations
                current_time = time.time()
                self.valid_tokens = {
                    mint: info for mint, info in self.valid_tokens.items()
                    if current_time - info.last_validation < 3600  # 1 hour
                }
                
                # Clean up blacklist periodically
                if len(self.blacklisted_tokens) > 10000:
                    self.blacklisted_tokens = set()
                    
                await asyncio.sleep(300)  # Every 5 minutes
                
            except Exception as e:
                self.logger.error(f"Cleanup error: {e}")
                await asyncio.sleep(60)

    async def _execute_trading_strategy(self, pool_data: Dict):
        """Execute trading strategy with position scaling"""
        try:
            # Get scaled position size
            current_size = self.scaler.get_current_size(
                "scalp" if self._is_scalp_opportunity(pool_data) else "arb"
            )
            
            # Execute trade with priority fee
            signature = await self._execute_trade(pool_data, current_size)
            
            if signature:
                # Calculate profit and update scaling
                profit = await self._calculate_profit(signature)
                self.scaler.add_trade_result(
                    signature=signature,
                    profit=profit,
                    size=current_size,
                    trade_type="scalp"  # or "arb"
                )
                
        except Exception as e:
            self.logger.error(f"Strategy execution error: {e}")

async def main():
    from config import Config
    
    config = Config.load()
    trader = QuantumOptimized(config)
    
    try:
        await trader.start()
    except KeyboardInterrupt:
        logging.info("Trading terminated by user")
    except Exception as e:
        logging.error(f"Fatal error: {e}")

if __name__ == "__main__":
    asyncio.run(main()) write this but also i need u to just add these into the script and write it all out and add some logging mayb ? # quantum_optimized.py
# Add this method inside the QuantumOptimized class

def _decode_pool_data(self, base64_data: str) -> Optional[Dict]:
    """Decode Raydium pool data"""
    try:
        raw = base64.b64decode(base64_data)
        return {
            "pool_address": raw[0:32].hex(),
            "metrics": {
                "liquidity": int.from_bytes(raw[48:56], "little") / 1e6,
                "volume_5min": int.from_bytes(raw[96:104], "little") / 1e6,
                "buy_pressure": int.from_bytes(raw[88:92], "little"),
                "sell_pressure": int.from_bytes(raw[92:96], "little"),
                "price": int.from_bytes(raw[104:112], "little") / 1e9,
                "mint_authority": bool(raw[72] & 1),
                "liquidity_locked": int.from_bytes(raw[80:88], "little") / 100
            },
            "token_mint": raw[32:64].hex()
        }
    except Exception as e:
        self.logger.error(f"Pool decode error: {e}")
        return None

async def _connect_websocket(self, ws_url: str) -> websockets.WebSocketClientProtocol:
    """Establish WebSocket connection with retry logic"""
    while True:
        try:
            ws = await websockets.connect(
                ws_url,
                ping_interval=20,
                ping_timeout=20,
                close_timeout=20
            )
            return ws
        except Exception as e:
            self.logger.error(f"WebSocket connection error: {e}")
            await asyncio.sleep(1)

async def _monitor_connection(self, ws: websockets.WebSocketClientProtocol):
    """Monitor WebSocket connection health"""
    try:
        while True:
            try:
                await ws.ping()
                await asyncio.sleep(15)
            except Exception:
                return False
    except asyncio.CancelledError:
        return False

async def _handle_connection(self, ws_url: str, handler):
    """Handle WebSocket connection with automatic reconnection"""
    while True:
        try:
            ws = await self._connect_websocket(ws_url)
            monitor_task = asyncio.create_task(self._monitor_connection(ws))
            
            try:
                async for msg in ws:
                    await handler(msg)
            except Exception as e:
                self.logger.error(f"Message handling error: {e}")
            finally:
                monitor_task.cancel()
                await ws.close()
        except Exception as e:
            self.logger.error(f"Connection error: {e}")
            await asyncio.sleep(1)