without changing my script please add printing in terminal so i can see whats happening to fix the any problems ? import asyncio
import logging
import os
import sys
import json
import time
import torch
from pathlib import Path
from typing import Optional, Dict
import inspect
import signal
from decimal import Decimal

# Import optimized components
from solana_rust_bot import TradeParams, TradingCore
from solana_cli import SolanaCLI, WSOLState, TokenBalances
from advanced_trading import AdvancedTrading, TradingMetrics
from price_monitor import RaydiumMonitor
from price_impact import EnhancedImpactCalculator
from mev_protection import EnhancedMevProtection, MevConfig
from system_manager import SystemManager
from helius_client import HeliusWebSocketClient
from vector_store import EnhancedVectorStore, VectorConfig
from trading_config import TradingConfig
from mempool_analyzer import EnhancedMempoolAnalyzer
from gpu_accelerator import GPUAccelerator, AcceleratorConfig

# Configure logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger(__name__)

class RaydiumTrader:
    def __init__(self, config_path: str):
        self.start_time = time.time()
        try:
            with open(config_path, 'r') as f:
                self.config = json.load(f)
            logger.info("Configuration loaded successfully")
        except Exception as e:
            logger.error(f"Error loading configuration: {e}")
            raise

        # Initialize state variables
        self.active = False
        self.trading_active = False
        self.last_trade_time = 0
        self.trade_count = 0
        
        # Add metrics tracking
        self.metrics = TradingMetrics()

        # Add vector store initialization
        vector_config = VectorConfig(
            batch_size=self.config["vector_store"]["batch_size"],
            vector_dim=self.config["vector_store"]["dimension"],
            similarity_threshold=self.config["vector_store"]["similarity_threshold"]
        )
        self.vector_store = EnhancedVectorStore(self.config)
        
        # Initialize GPU accelerator
        self._init_gpu()
            
        # Initialize components that don't require async
        self.trading_core = None
        self.system = None
        self.price_monitor = None
        self.advanced_trading = None
        self.impact_calculator = None
        self.mev_protection = None
        self.mempool_analyzer = None
        self.solana_cli = None
        
        # Add signal handlers
        signal.signal(signal.SIGINT, self._handle_shutdown)
        signal.signal(signal.SIGTERM, self._handle_shutdown)
        
        logger.info("RaydiumTrader initialized")

    def _init_gpu(self):
        """Initialize GPU with optimal settings"""
        if torch.cuda.is_available():
            accelerator_config = AcceleratorConfig(
                memory_fraction=self.config["system"]["cuda"]["memory_fraction"],
                enable_tensor_cores=True,
                optimization_level="O3"
            )
            self.gpu_accelerator = GPUAccelerator(accelerator_config)
            self.gpu_accelerator.initialize()
            
            gpu_info = torch.cuda.get_device_properties(0)
            logger.info(f"GPU Initialized: {gpu_info.name} ({gpu_info.total_memory / 1024**3:.2f}GB)")
        else:
            logger.warning("No GPU available, using CPU")

    async def initialize(self) -> bool:
        """Initialize all trading components with proper error handling"""
        try:
            logger.info("Starting system initialization...")
            
            self.ws_client = HeliusWebSocketClient(self.config)
            await self.ws_client.start()
            logger.info("Helius WebSocket Client initialized")
            
            # Initialize system manager first
            self.system = SystemManager()
            await self.system.start()

            # Create standardized trading config
            trading_config = TradingConfig(
                min_profit=self.config["trading"]["min_profit"],
                max_position=self.config["trading"]["max_position"],
                risk_level=self.config["trading"]["risk_level"]
            )

            # Initialize TradingCore (Rust)
            self.trading_core = TradingCore(
                rpc_url=self.config["rpc"]["helius"]["endpoint"],
                config_json=json.dumps(trading_config)
            )
            logger.info("TradingCore (Rust) initialized successfully")

            # Initialize MEV protection
            mev_config = MevConfig(
                max_fee_multiplier=self.config["execution"]["fee_multiplier"],
                min_priority_fee=self.config["execution"]["min_priority_fee"],
                max_priority_fee=self.config["execution"]["max_priority_fee"],
                compute_budget=self.config["execution"]["compute_limit"],
                slippage=self.config["execution"]["slippage"]
            )
            self.mev_protection = EnhancedMevProtection(mev_config)
            logger.info("MEV protection initialized")

            # Initialize price impact calculator
            self.impact_calculator = EnhancedImpactCalculator(self.trading_core, self.config)
            logger.info("Impact calculator initialized")

            # Initialize advanced trading
            self.advanced_trading = AdvancedTrading(self, self.config)
            await self.advanced_trading.start()
            logger.info("Advanced trading initialized")

            # Initialize price monitor
            self.price_monitor = RaydiumMonitor(self.config)
            logger.info("Price monitor initialized")

            # Initialize mempool analyzer
            self.mempool_analyzer = EnhancedMempoolAnalyzer(
                self.trading_core,
                self.config["mempool"]["max_transactions"],
                self.config["mempool"]["update_interval"]
            )
            logger.info("Mempool analyzer initialized")

            # Initialize SolanaCLI for WSOL management
            self.solana_cli = SolanaCLI(self.trading_core)
            await self.solana_cli.start_monitoring()
            logger.info("SolanaCLI for WSOL management initialized")

            # Get initial balance
            try:
                raw_balance = await self.trading_core.get_balance()
                if raw_balance is not None:
                    sol_balance = int(raw_balance) / 1_000_000_000
                    logger.info(f"Initial SOL Balance: {sol_balance:.6f} SOL")
            except Exception as e:
                logger.warning(f"Could not get initial balance: {e}")

            self.active = True
            self.trading_active = True
            logger.info("All components initialized successfully")
            return True

        except Exception as e:
            logger.error(f"Initialization error: {e}")
            raise

    async def start_trading(self):
        """Start all trading processes"""
        logger.info("Starting trading processes...")
        try:
            # Create monitoring tasks
            tasks = [
                asyncio.create_task(self.price_monitor.start_monitoring()),
                asyncio.create_task(self.monitor_opportunities()),
                asyncio.create_task(self.system.monitor_loop()),
                asyncio.create_task(self.process_ws_messages()),
                asyncio.create_task(self.update_token_balances()),
                asyncio.create_task(self.monitor_system_metrics()),
                asyncio.create_task(self.mempool_analyzer.start_monitoring()),
                asyncio.create_task(self.vector_store.start_pattern_monitoring())
            ]
            
            # Wait for any task to complete or fail
            done, pending = await asyncio.wait(
                tasks,
                return_when=asyncio.FIRST_EXCEPTION
            )
            
            # Check for exceptions
            for task in done:
                if task.exception():
                    raise task.exception()
                    
        except Exception as e:
            logger.error(f"Trading error: {e}")
            await self.cleanup()
            raise

    async def process_ws_messages(self):
        """Process WebSocket messages"""
        while self.trading_active:
            try:
                if self.ws_client.process_queue.qsize() > 0:
                    message = await self.ws_client.process_queue.get()
                    await self.advanced_trading.process_market_update(message)
                await asyncio.sleep(0.001)
            except Exception as e:
                logger.error(f"WS message processing error: {e}")

    async def monitor_opportunities(self):
        """Monitor for trading opportunities"""
        logger.info("Starting opportunity monitoring...")
        
        while self.trading_active:
            try:
                # Check health status
                if not self.system.is_healthy():
                    logger.warning("System health check failed, pausing trading")
                    await asyncio.sleep(5)
                    continue
                    
                # Process opportunities
                opportunity = await self.advanced_trading.get_next_opportunity()
                if opportunity:
                    await self.process_opportunity(opportunity)
                
                await asyncio.sleep(0.001)  # 1ms delay
                
            except Exception as e:
                logger.error(f"Opportunity monitoring error: {e}")
                await asyncio.sleep(1)

    async def process_opportunity(self, opportunity: Dict):
        """Process trading opportunity"""
        try:
            if not self.trading_active:
                return
            
            # Update metrics for opportunity processing
            self.metrics.opportunities_found += 1

            # Validate opportunity
            valid, metrics = await self.impact_calculator.validate_trade(
                opportunity['pool'],
                opportunity['amount_in'],
                opportunity['min_amount_out'],
                opportunity['type']
            )

            if valid:
                # Update metrics for successful trades
                self.metrics.successful_trades += 1
                self.metrics.total_profit += Decimal(str(opportunity['profit']))
                
                if opportunity['type'] == 'sandwich':
                    self.metrics.sandwich_profits += Decimal(str(opportunity['profit']))
                else:
                    self.metrics.impact_profits += Decimal(str(opportunity['profit']))

                # Execute trade with trade parameters
                trade_params = TradeParams(
                    amount=opportunity["amount"],
                    slippage=self.config["trading"]["slippage"],
                    deadline=int(time.time() + 60)
                )
                
                # Trade execution with MEV protection
                protected_tx = await self.mev_protection.protect_transaction(opportunity)
                if protected_tx:
                    result = await self.advanced_trading.execute_opportunity(protected_tx)
                    if result:
                        self.trade_count += 1
                        self.last_trade_time = time.time()
                
        except Exception as e:
            logger.error(f"Opportunity processing error: {e}")

    async def update_token_balances(self):
        """Update token balances"""
        try:
            balances = await self.solana_cli.get_token_balances()
            self.token_balances = TokenBalances(
                wsol=WSOLState(
                    balance=balances['wsol'],
                    last_update=time.time()
                ),
                tokens=balances['tokens']
            )
        except Exception as e:
            logger.error(f"Balance update error: {e}")

    async def monitor_system_metrics(self):
        """Monitor system performance metrics"""
        while self.trading_active:
            try:
                metrics = {
                    'gpu_utilization': self.gpu_accelerator.get_utilization(),
                    'memory_usage': self.system.get_memory_usage(),
                    'trade_count': self.metrics.successful_trades,
                    'total_profit': float(self.metrics.total_profit),
                    'uptime_hours': self.get_runtime_hours()
                }
                await self.system.update_metrics(metrics)
                await asyncio.sleep(1)
            except Exception as e:
                logger.error(f"Metrics monitoring error: {e}")

    def _handle_shutdown(self, signum, frame):
        """Handle shutdown signals"""
        logger.info("Shutdown signal received")
        asyncio.create_task(self.cleanup())

    async def cleanup(self):
        """Clean up all resources properly"""
        logger.info("Cleaning up trading system...")
        try:
            self.active = False
            self.trading_active = False
            
            # Add WebSocket cleanup
            if hasattr(self, 'ws_client'):
                await self.ws_client.cleanup()
            
            cleanup_tasks = []
            
            # Cleanup components
            components = [
                self.advanced_trading,
                self.impact_calculator,
                self.price_monitor,
                self.system,
                self.mev_protection,
                self.mempool_analyzer,
                self.vector_store,
                self.solana_cli,
                self.gpu_accelerator
            ]
            
            for component in components:
                if component and hasattr(component, "cleanup"):
                    try:
                        cleanup_method = component.cleanup()
                        if inspect.iscoroutine(cleanup_method):
                            cleanup_tasks.append(asyncio.create_task(cleanup_method))
                    except Exception as e:
                        logger.error(f"Error cleaning up component: {e}")
            
            if cleanup_tasks:
                await asyncio.wait(cleanup_tasks)
                
            # Clear GPU memory
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
                
            runtime_hours = self.get_runtime_hours()
            logger.info(f"Trading session complete. Runtime: {runtime_hours:.2f} hours")
            
        except Exception as e:
            logger.error(f"Cleanup error: {e}")

    def get_runtime_hours(self) -> float:
        """Calculate runtime in hours"""
        return (time.time() - self.start_time) / 3600

async def main():
    """Main entry point with enhanced error handling"""
    bot = None
    
    try:
        logger.info("Starting Raydium Trading Bot...")
        
        # Initialize bot
        config_path = "config.json"
        bot = RaydiumTrader(config_path)
        
        # Initialize components
        await bot.initialize()
        
        # Start trading
        await bot.start_trading()
        
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt received")
    except Exception as e:
        logger.error(f"Critical system error: {e}")
    finally:
        if bot:
            await bot.cleanup()

if __name__ == "__main__":
    if sys.platform == 'win32':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    
    try:
        loop.run_until_complete(main())
    except KeyboardInterrupt:
        logger.info("Shutdown signal received")
    finally:
        loop.close()