please write this with proper spacing and logging thank you import asyncio
import logging
import os
import sys
import json
import time
import websockets
import torch
from typing import Optional, Dict, Tuple
from decimal import Decimal
import base64
import subprocess
import psutil

# Import necessary components
from solana_cli import SolanaCLI
from solana_rust_bot import TradingCore, TradeParams
from gpu_accelerator import GPUAccelerator, AcceleratorConfig
from vector_store import EnhancedVectorStore
from price_impact import EnhancedImpactCalculator
from mev_protection import MevProtection, MevConfig
from system_manager import SystemManager
from price_monitor import RaydiumMonitor
from advanced_trading import AdvancedTrading
from mempool_analyzer import EnhancedMempoolAnalyzer

# Setup logging
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler(f'trading_{time.strftime("%Y%m%d_%H%M%S")}.log')
    ]
)
logger = logging.getLogger(__name__)

# BalanceManager
class BalanceManager:
    def __init__(self, config: Dict, trader: TradingCore):
        logger.debug("Initializing BalanceManager")
        self.config = config
        self.trader = trader
        self.wsol_target = config['trading']['balance_management']['wsol_target_ratio']
        self.sol_target = config['trading']['balance_management']['sol_target_ratio']
        self.rebalance_threshold = config['trading']['balance_management']['rebalance_threshold']
        self.min_rebalance_amount = config['trading']['balance_management']['min_rebalance_amount']
        self.last_rebalance = 0
        self.rebalance_cooldown = 60

    async def check_balances(self) -> Tuple[float, float]:
        try:
            sol_balance = float(self.trader.get_balance())
            wsol_balance = float(self.trader.get_wsol_balance())
            logger.debug(f"Checked balances - SOL: {sol_balance}, WSOL: {wsol_balance}")
            return sol_balance, wsol_balance
        except Exception as e:
            logger.error(f"Balance check error: {e}")
            return 0.0, 0.0

    async def rebalance_if_needed(self) -> bool:
        try:
            if time.time() - self.last_rebalance < self.rebalance_cooldown:
                logger.debug("Rebalance cooldown in effect")
                return False

            sol_balance, wsol_balance = await self.check_balances()
            total_balance = sol_balance + wsol_balance

            if total_balance == 0:
                logger.warning("No total balance to rebalance")
                return False

            current_wsol_ratio = wsol_balance / total_balance
            wsol_deviation = abs(current_wsol_ratio - self.wsol_target)

            if wsol_deviation > self.rebalance_threshold:
                target_wsol = total_balance * self.wsol_target
                
                if wsol_balance < target_wsol:
                    wrap_amount = target_wsol - wsol_balance
                    if wrap_amount >= self.min_rebalance_amount:
                        logger.info(f"Rebalancing: Wrapping {wrap_amount:.6f} SOL to WSOL")
                        result = self.trader.transfer_to_wsol(float(wrap_amount))
                        if result:
                            self.last_rebalance = time.time()
                            logger.info("Successfully rebalanced WSOL")
                            return True

            logger.debug("No rebalancing needed")
            return False

        except Exception as e:
            logger.error(f"Rebalance error: {e}")
            return False

# PositionManager
class PositionManager:
    def __init__(self, config: Dict):
        logger.debug("Initializing PositionManager")
        self.config = config
        self.current_size = config['trading']['position']['initial_size']
        self.max_size = config['trading']['position']['max_size']
        self.size_increment = config['trading']['position']['scale_increment']
        self.success_threshold = config['trading']['position']['success_threshold']
        self.successful_trades = 0
        self.total_profit = Decimal('0')

    def get_position_size(self) -> float:
        return float(self.current_size)

    def update_metrics(self, profit: Decimal, success: bool):
        logger.debug(f"Updating metrics - Profit: {profit}, Success: {success}")
        if success:
            self.successful_trades += 1
            self.total_profit += profit

            if self.successful_trades % self.success_threshold == 0:
                new_size = min(self.current_size + self.size_increment, self.max_size)
                if new_size != self.current_size:
                    logger.info(f"Scaling up position size: {self.current_size:.6f} -> {new_size:.6f}")
                    self.current_size = new_size
        else:
            self.successful_trades = 0

# RaydiumTrader
class RaydiumTrader:
    def __init__(self, config_path: str):
        logger.debug("Initializing RaydiumTrader")
        
        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}", exc_info=True)
            raise

        self.active = False
        self.last_trade_time = 0
        self.trade_count = 0
        self.balance_manager = None
        self.position_manager = None
        self.vector_store = None
        self.impact_calculator = None
        self.mempool_analyzer = None
        self.system = None
        self.price_monitor = None
        self.trading_core = None
        self.gpu_accelerator = None
        logger.info("Raydium trader initialized")

    async def initialize(self) -> bool:
        logger.info("Starting system initialization...")
        try:
            await self._initialize_components()
            await self._log_initial_balances()
            self.active = True
            logger.info("RaydiumTrader is now active.")
            return True
        except Exception as e:
            logger.error(f"Initialization error: {e}", exc_info=True)
            return False

    async def _initialize_components(self):
    """Initialize all system components"""
    logger.debug("Initializing system components...")
    
    # Initialize system manager first
    self.system = SystemManager()
    await self.system.start()
    logger.info("System manager started successfully.")

    # Initialize GPU accelerator
    gpu_config = AcceleratorConfig()
    self.gpu_accelerator = GPUAccelerator(gpu_config)
    logger.info("GPU accelerator initialized successfully.")

    # Initialize vector store
    self.vector_store = EnhancedVectorStore(self.config)
    logger.info("Vector store initialized successfully.")

    # Initialize trading core
    trading_config = {
        "compute_limit": self.config['execution']['compute_limit'],
        "priority_fee": self.config['execution']['priority_fee'],
        "max_priority_fee": self.config['execution']['max_priority_fee'],
        "slippage": self.config['execution']['slippage'],
        "retry_count": self.config['execution']['retry_count'],
        "position_size": self.config['trading']['position']['initial_size'],
        "max_position_size": self.config['trading']['position']['max_size'],
        "gas_reserve": self.config['trading']['position']['gas_reserve']
    }
    
    self.trading_core = TradingCore(
        secret_key=os.environ['SOLANA_PRIVATE_KEY'],
        rpc_url=self.config['rpc']['helius']['endpoint'],
        config_json=json.dumps(trading_config)
    )
    logger.info("Trading core initialized successfully.")

    # Initialize Solana CLI
    self.solana_cli = SolanaCLI(self.trading_core)
    logger.info("Solana CLI 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 = MevProtection(mev_config)
    logger.info("MEV protection initialized successfully.")

    # Initialize price monitor
    self.price_monitor = RaydiumMonitor(self.config['rpc']['helius']['websocket'])
    logger.info("Price monitor initialized successfully.")

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

    # Initialize mempool analyzer
    self.mempool_analyzer = EnhancedMempoolAnalyzer(self.config)
    logger.info("Mempool analyzer initialized successfully.")

    # Initialize balance and position managers
    self.balance_manager = BalanceManager(self.config, self.trading_core)
    self.position_manager = PositionManager(self.config)
    logger.info("Balance and position managers initialized successfully.")

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

    # Update pool data
    pool_data = self.config['accounts']['sol_wsol']
    self.trading_core.update_pool(pool_data)
    logger.info("Pool data updated successfully.")

    async def _log_initial_balances(self):
        logger.debug("Logging initial SOL and WSOL balances")
        sol_balance = self.trading_core.get_balance()
        wsol_balance = self.trading_core.get_wsol_balance()
        logger.info(f"Initial Balances: SOL={sol_balance}, WSOL={wsol_balance}")

    async def monitor_mempool(self):
        """Monitor mempool for opportunities"""
        logger.info("Starting mempool monitoring...")
        
        while self.active:
            try:
                async with websockets.connect(
                    self.config['rpc']['helius']['websocket'],
                    ping_interval=30,
                    ping_timeout=10
                ) as ws:
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "logsSubscribe",
                        "params": [
                            {"mentions": [self.config['programs']['raydium']]},
                            {"commitment": "processed"}
                        ]
                    }))
                    
                    while self.active:
                        msg = await ws.recv()
                        data = json.loads(msg)
                        
                        if 'params' in data:
                            logs = data['params'].get('result', {}).get('value', {}).get('logs', [])
                            
                            for log in logs:
                                if "ray_log:" in log:
                                    raw_data = base64.b64decode(log.split('ray_log: ')[1].strip())
                                    await self.process_opportunity(raw_data)

            except Exception as e:
                logger.error(f"Mempool monitoring error: {e}", exc_info=True)
                await asyncio.sleep(1)

    async def process_opportunity(self, log_data: str) -> Optional[Dict]:
        """Process trading opportunity using both GPU Accelerator and Vector Store"""
        logger.debug("Processing trading opportunity")
        try:
            # First pass through GPU Accelerator for initial analysis
            opportunity = await self.gpu_accelerator.analyze_opportunity(log_data)
            if not opportunity:
                logger.debug("No initial opportunity found")
                return None

            # Extract pool data for vector analysis
            pool_data = {
                "address": self.config['accounts']['sol_wsol']['amm_id'],
                "price": opportunity['amount_out'] / opportunity['amount_in'],
                "volume": opportunity['amount_in'],
                "timestamp": opportunity['timestamp']
            }

            # Check for similar patterns using Vector Store
            similar_pools = await self.vector_store.search_similar_pools(pool_data)
            if not similar_pools:
                logger.debug("No similar patterns found")
                return None

            # Track momentum
            momentum = await self.vector_store.track_pool_momentum(
                pool_data["address"],
                {"price": pool_data["price"], "volume": pool_data["volume"]}
            )

            if momentum and abs(momentum["momentum_signal"]) > 0.02:
                # Combine GPU and Vector analysis
                enhanced_opportunity = {
                    **opportunity,
                    "similar_patterns": similar_pools,
                    "momentum": momentum,
                    "confidence": opportunity.get('confidence', 0) * max(s["similarity"] for s in similar_pools)
                }

                # Execute trade if profitable
                if enhanced_opportunity['profit'] >= self.config['trading']['limits']['min_profit_pct']:
                    params = TradeParams(
                        pool_address=self.config['accounts']['sol_wsol']['amm_id'],
                        amount_in=enhanced_opportunity['amount_in'],
                        min_amount_out=enhanced_opportunity['amount_out'] * (1 - self.config['execution']['slippage'])
                    )

                    # Execute trade
                    result = self.trading_core.execute_trade(params)
                    if result:
                        logger.info(f"""
                        Trade executed:
                        Profit: {enhanced_opportunity['profit']:.2f}%
                        Confidence: {enhanced_opportunity['confidence']:.2f}
                        Momentum: {enhanced_opportunity['momentum']['momentum_signal']:.2f}
                        Similar Patterns: {len(enhanced_opportunity['similar_patterns'])}
                        Signature: {result}
                        """)

                        # Update vectors after successful trade
                        await self.vector_store.update_pool_vectors(pool_data)

                    return enhanced_opportunity

            return None

        except Exception as e:
            logger.error(f"Opportunity processing error: {e}")
            return None

    async def monitor_mempool(self):
        """Monitor mempool for opportunities"""
        logger.info("Starting mempool monitoring...")

        while self.active:
            try:
                async with websockets.connect(
                    self.config['rpc']['helius']['websocket'],
                    ping_interval=30,
                    ping_timeout=10,
                    close_timeout=60,
                    max_size=16_777_216
                ) as ws:
                    # Subscribe to Raydium logs
                    subscription_msg = {
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "logsSubscribe",
                        "params": [
                            {"mentions": [self.config['programs']['raydium']]},
                            {"commitment": "processed"}
                        ]
                    }

                    await ws.send(json.dumps(subscription_msg))
                    logger.info("Subscribed to Raydium logs")

                    while self.active:
                        try:
                            msg = await ws.recv()
                            await self.process_opportunity(msg)

                        except websockets.exceptions.ConnectionClosed:
                            logger.warning("WebSocket connection closed. Reconnecting...")
                            break
                        except Exception as e:
                            logger.error(f"Message processing error: {e}")
                            continue

            except Exception as e:
                logger.error(f"WebSocket connection error: {e}")
                await asyncio.sleep(1)
    async def monitor_system_health(self):
        """Monitor system health and performance"""
        while self.active:
              # Check GPU and system metrics
            metrics = await self.system.collect_metrics()
            
            # Log performance stats
            if metrics.gpu_usage > 0:  # Only log when GPU is active
                logger.info(f"""
                Performance Stats:
                GPU Usage: {metrics.gpu_usage:.1f}%
                GPU Memory: {metrics.gpu_memory:.1f}MB
                CPU Usage: {metrics.cpu_usage:.1f}%
                Memory Used: {metrics.memory_used:.1f}%
                Active Trades: {metrics.active_trades}
                """)

            # Check balances and rebalance if needed
            await self.balance_manager.rebalance_if_needed()
            
            # Emergency cleanup if needed
            if (metrics.gpu_memory > self.config['system']['max_memory_usage'] or
                metrics.cpu_usage > 90):
                logger.warning("High resource usage detected, performing cleanup")
                await self.system.emergency_cleanup()

            await asyncio.sleep(5)  # Check every 5 seconds
        except Exception as e:
            logger.error(f"Health monitoring error: {e}")
            await asyncio.sleep(1)

    async def start(self):
        """Start the trading system"""
        try:
            logger.info("Starting trading system...")

            # Initialize GPU accelerator
            gpu_config = AcceleratorConfig(
                batch_size=32,
                matrix_size=2048,
                use_tensor_cores=True,
                use_cuda_graphs=True,
                pipeline_parallel=True,
                memory_fraction=0.8
            )
            self.gpu_accelerator = GPUAccelerator(gpu_config)

            # Initialize Vector Store
            self.vector_store = EnhancedVectorStore(self.config)

            # Initialize other components
            await self.initialize()

            # Start monitoring tasks
            self.active = True
            tasks = [
                self.monitor_mempool(),
                self.system.monitor_loop(),
                self.balance_manager.monitor_loop()
            ]

            await asyncio.gather(*tasks)

        except Exception as e:
            logger.error(f"Trading system error: {e}")
            await self.cleanup()
    async def cleanup(self):
        """Clean up all resources"""
        try:
            logger.info("Cleaning up trading system...")
            self.active = False

            if hasattr(self, 'gpu_accelerator'):
                await self.gpu_accelerator.cleanup()

            if hasattr(self, 'vector_store'):
                self.vector_store.cleanup()

            if hasattr(self, 'system'):
                await self.system.cleanup()

            logger.info("Cleanup complete")

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

    async def cleanup(self):
        logger.info("Cleaning up trading system...")
        try:
            self.active = False
            if self.gpu_accelerator:
                self.gpu_accelerator.cleanup()
            logger.info("Cleanup completed successfully.")
        except Exception as e:
            logger.error(f"Cleanup error: {e}", exc_info=True)

async def main():
    try:
        # Configure GPU settings
        torch.cuda.set_device(0)
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.benchmark = True

        # Load configuration
        config_path = 'config.json'
        with open(config_path) as f:
            config = json.load(f)

        # Initialize core components
        trader = RaydiumTrader(config_path)
        
        # Initialize system manager first
        trader.system = SystemManager()
        await trader.system.start()
        
        # Initialize GPU accelerator with optimal settings
        gpu_config = AcceleratorConfig(
            batch_size=32,  # Optimized for your benchmarks
            matrix_size=2048,
            use_tensor_cores=True,
            use_cuda_graphs=True,
            pipeline_parallel=True,
            memory_fraction=0.8,
            min_profit_pct=config['trading']['limits']['min_profit_pct'],
            max_profit_pct=config['trading']['limits']['max_profit_pct']
        )
        trader.gpu_accelerator = GPUAccelerator(gpu_config)
        
        # Initialize remaining components
        await trader.initialize()

        # Start monitoring and trading tasks
        tasks = [
            trader.monitor_mempool(),
            trader.monitor_system_health(),
            trader.rebalance_loop()
        ]

        # Run all tasks
        await asyncio.gather(*tasks)

    except KeyboardInterrupt:
        logger.info("Shutting down gracefully...")
        if trader:
            await trader.cleanup()
    except Exception as e:
        logger.error(f"Fatal error: {e}", exc_info=True)
        if trader:
            await trader.cleanup()
        raise

if __name__ == "__main__":
    # Set Windows event loop policy
    if sys.platform == 'win32':
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
    
    # Run main
    asyncio.run(main())