async def unwrap_wsol(self, amount: float) -> Optional[str]:
        """Unwrap WSOL to SOL without closing account"""
        try:
            # Create unwrap instruction
            wsol_mint = self.config['accounts']['sol_wsol']['base_mint']
            payer = self.trading_core.get_balance()  # Gets signer's public key
            wsol_account = await self.cli.get_token_accounts(payer)
            
            if not wsol_account:
                logger.error("WSOL account not found")
                return None

            # Add compute budget instruction for priority fee
            priority_fee = self.config['execution']['priority_fee']
            compute_limit = self.config['execution']['compute_limit']
            
            instruction_params = {
                'amount': amount,
                'wsol_account': wsol_account[0],  # Use first WSOL account
                'priority_fee': priority_fee,
                'compute_limit': compute_limit
            }
            
            # Execute unwrap via trading core
            signature = self.trading_core.unwrap_sol(instruction_params)
            
            if signature:
                logger.info(f"Successfully unwrapped {amount:.6f} WSOL to SOL: {signature}")
                return signature
            
            return None
            
        except Exception as e:
            logger.error(f"WSOL unwrap error: {e}")
            return None

    async def manage_balances(self) -> bool:
        """Manage and rebalance SOL/WSOL ratios"""
        try:
            # Get current balances
            sol_balance = self.trading_core.get_balance()
            wsol_balance = self.trading_core.get_wsol_balance()
            total_balance = sol_balance + wsol_balance
            
            # Calculate current ratios
            current_wsol_ratio = wsol_balance / total_balance
            current_sol_ratio = sol_balance / total_balance
            
            # Get target ratios from config
            target_wsol = self.config['trading']['balance_management']['wsol_target_ratio']
            target_sol = self.config['trading']['balance_management']['sol_target_ratio']
            threshold = self.config['trading']['balance_management']['rebalance_threshold']
            min_amount = self.config['trading']['balance_management']['min_rebalance_amount']
            
            logger.info(f"""
Balance Status:
SOL Balance: {sol_balance:.6f} ({current_sol_ratio*100:.1f}%)
WSOL Balance: {wsol_balance:.6f} ({current_wsol_ratio*100:.1f}%)
Target SOL: {target_sol*100}%
Target WSOL: {target_wsol*100}%
            """)
            
            # Check if rebalance needed
            if abs(current_wsol_ratio - target_wsol) > threshold:
                if current_wsol_ratio < target_wsol:
                    # Need to wrap more SOL to WSOL
                    wrap_amount = total_balance * (target_wsol - current_wsol_ratio)
                    if wrap_amount > min_amount:
                        logger.info(f"Wrapping {wrap_amount:.6f} SOL to WSOL")
                        result = await self.trading_core.transfer_to_wsol(float(wrap_amount))
                        if result:
                            logger.info(f"Successfully wrapped SOL to WSOL: {result}")
                            return True
                else:
                    # Need to unwrap WSOL to SOL
                    unwrap_amount = total_balance * (current_wsol_ratio - target_wsol)
                    if unwrap_amount > min_amount:
                        logger.info(f"Unwrapping {unwrap_amount:.6f} WSOL to SOL")
                        result = await self.unwrap_wsol(float(unwrap_amount))
                        if result:
                            logger.info(f"Successfully unwrapped WSOL to SOL: {result}")
                            return True
            
            return True
            
        except Exception as e:
            logger.error(f"Balance management error: {e}")
            return False    async def manage_balances(self) -> bool:
        """Manage and rebalance SOL/WSOL ratios"""
        try:
            # Get current balances
            sol_balance = self.trading_core.get_balance()
            wsol_balance = self.trading_core.get_wsol_balance()
            total_balance = sol_balance + wsol_balance
            
            # Calculate current ratios
            current_wsol_ratio = wsol_balance / total_balance
            current_sol_ratio = sol_balance / total_balance
            
            # Get target ratios from config
            target_wsol = self.config['trading']['balance_management']['wsol_target_ratio']
            target_sol = self.config['trading']['balance_management']['sol_target_ratio']
            threshold = self.config['trading']['balance_management']['rebalance_threshold']
            min_amount = self.config['trading']['balance_management']['min_rebalance_amount']
            
            logger.info(f"""
Balance Check:
SOL Balance: {sol_balance:.6f} ({current_sol_ratio*100:.1f}%)
WSOL Balance: {wsol_balance:.6f} ({current_wsol_ratio*100:.1f}%)
Target SOL: {target_sol*100}%
Target WSOL: {target_wsol*100}%
            """)
            
            # Check if rebalance needed
            if abs(current_wsol_ratio - target_wsol) > threshold:
                if current_wsol_ratio < target_wsol:
                    # Need to wrap more SOL to WSOL
                    wrap_amount = total_balance * (target_wsol - current_wsol_ratio)
                    if wrap_amount > min_amount:
                        logger.info(f"Wrapping {wrap_amount:.6f} SOL to WSOL")
                        result = await self.trading_core.transfer_to_wsol(float(wrap_amount))
                        if result:
                            logger.info("Rebalance successful")
                            return True
                else:
                    # Need to unwrap WSOL to SOL
                    unwrap_amount = total_balance * (current_wsol_ratio - target_wsol)
                    if unwrap_amount > min_amount:
                        logger.info(f"Need to unwrap {unwrap_amount:.6f} WSOL to SOL")
                        # Note: Implement unwrap functionality if needed
            
            return True
            
        except Exception as e:
            logger.error(f"Balance management error: {e}")
            return False

    async def _balance_management_loop(self):
        """Continuous balance management loop"""
        logger.info("Starting balance management loop")
        while self.active:
            try:
                await self.manage_balances()
            except Exception as e:
                logger.error(f"Balance loop error: {e}")
            await asyncio.sleep(60)  # Check every minuteimport asyncio
import logging
import os
from typing import Optional
import time
from decimal import Decimal

# Import your components
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

logger = logging.getLogger(__name__)

class RaydiumTrader:
    def __init__(self, config_path: str):
        with open(config_path, 'r') as f:
            self.config = json.load(f)
            
        self.active = False
        self.last_trade_time = 0
        self.successful_trades = 0
        self.total_profit = Decimal('0')
        
        # Initialize core components
        self.trading_core = None
        self.gpu = None
        self.vector_store = None
        self.impact_calculator = None
        self.mev_protection = None
        self.system = None
        self.price_monitor = None
        
        # Trading parameters
        self.MIN_PROFIT = Decimal(str(self.config['trading']['limits']['min_profit_pct']))
        self.MAX_SIZE = Decimal(str(self.config['trading']['position']['max_size']))
        self.SLIPPAGE = Decimal(str(self.config['execution']['slippage']))

    async def initialize(self) -> bool:
        """Initialize all system components"""
        try:
            logger.info("Initializing trading system...")
            
            if not os.getenv('SOLANA_PRIVATE_KEY'):
                logger.error("SOLANA_PRIVATE_KEY not set")
                return False

            # Initialize system manager first
            self.system = SystemManager()
            await self.system.start()

            # Initialize GPU accelerator with specific config
            gpu_config = AcceleratorConfig(
                batch_size=1024,
                matrix_size=2048,
                use_amp=True,  # Use automatic mixed precision
                num_streams=3,
                memory_fraction=0.8,  # Use 80% of GPU memory
                cpu_workers=16,  # For your i9
                cpu_batch_size=256
            )
            self.gpu = GPUAccelerator(gpu_config)
            
            # Verify GPU setup
            if not torch.cuda.is_available():
                logger.error("CUDA is not available!")
                return False
                
            logger.info(f"""
GPU Configuration:
CUDA Device: {torch.cuda.get_device_name()}
Memory Allocated: {torch.cuda.memory_allocated(0)/1024**2:.1f}MB
Memory Reserved: {torch.cuda.memory_reserved(0)/1024**2:.1f}MB
Using TF32: {torch.backends.cuda.matmul.allow_tf32}
AMP Enabled: {gpu_config.use_amp}
            """)
            
            # Initialize vector store
            self.vector_store = EnhancedVectorStore(self.config)
            
            # 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": float(self.SLIPPAGE),
                "retry_count": self.config['execution']['retry_count'],
                "position_size": float(self.config['trading']['position']['size']),
                "max_position_size": float(self.MAX_SIZE),
                "gas_reserve": float(self.config['trading']['position']['gas_reserve'])
            }
            
            # Check for required environment variables
            if not os.getenv('SOLANA_PRIVATE_KEY') or not os.getenv('SOLANA_PUBLIC_KEY'):
                logger.error("Required environment variables SOLANA_PRIVATE_KEY and SOLANA_PUBLIC_KEY not set")
                return False

            # Initialize trading core with proper key config
            try:
                self.trading_core = TradingCore(
                    secret_key=os.environ['SOLANA_PRIVATE_KEY'],
                    rpc_url=self.config['rpc']['helius']['endpoint'],
                    config_json=json.dumps(trading_config)
                )
                
                # Verify keys match
                pub_key = self.trading_core.get_public_key()
                if pub_key != os.environ['SOLANA_PUBLIC_KEY']:
                    logger.error("Public key mismatch between environment and trading core")
                    return False
                    
                logger.info("Trading core initialized successfully with keys")
            except Exception as e:
                logger.error(f"Failed to initialize trading core: {e}")
                return False

            # Initialize impact calculator after trading core
            self.impact_calculator = EnhancedImpactCalculator(self.config, self.trading_core)
            
            # Initialize MEV protection
            self.mev_protection = MevProtection(MevConfig())
            
            # Initialize price monitor
            self.price_monitor = RaydiumMonitor(self.config['rpc']['helius']['websocket'])
            
            # Update pool configuration
            # Convert pool data to the format expected by Rust
            pool_data = {
                'amm_id': self.config['accounts']['sol_wsol']['amm_id'],
                'amm_authority': self.config['accounts']['sol_wsol']['amm_authority'],
                'amm_open_orders': self.config['accounts']['sol_wsol']['amm_open_orders'],
                'amm_target': self.config['accounts']['sol_wsol']['amm_target'],
                'pool_coin_token_account': self.config['accounts']['sol_wsol']['pool_coin_token_account'],
                'pool_pc_token_account': self.config['accounts']['sol_wsol']['pool_pc_token_account'],
                'serum_market': self.config['accounts']['sol_wsol']['serum_market'],
                'serum_bids': self.config['accounts']['sol_wsol']['serum_bids'],
                'serum_asks': self.config['accounts']['sol_wsol']['serum_asks'],
                'serum_events': self.config['accounts']['sol_wsol']['serum_events'],
                'vault_signer': self.config['accounts']['sol_wsol']['vault_signer'],
                'base_mint': self.config['accounts']['sol_wsol']['base_mint'],
                'quote_mint': self.config['accounts']['sol_wsol']['quote_mint']
            }
            
            # Set environment variable for Rust backtrace
            os.environ['RUST_BACKTRACE'] = '1'
            
            # Update pool info in trading core
            try:
                self.trading_core.update_pool(pool_data)
                logger.info("Pool configuration updated successfully")
            except Exception as e:
                logger.error(f"Failed to update pool configuration: {e}")
                return False

            # Log initial balances
            sol_balance = self.trading_core.get_balance()
            wsol_balance = self.trading_core.get_wsol_balance()
            
            logger.info(f"""
Trading System Initialized Successfully:
SOL Balance: {sol_balance}
WSOL Balance: {wsol_balance}
Min Profit: {float(self.MIN_PROFIT)} SOL
Max Size: {float(self.MAX_SIZE)} SOL
Slippage: {float(self.SLIPPAGE * 100)}%
            """)

            self.active = True
            return True

        except Exception as e:
            logger.error(f"Initialization error: {e}", exc_info=True)
            return False

    async def process_opportunity(self, log_data: bytes) -> Optional[bool]:
        """Process and execute trading opportunity"""
        try:
            # Quick validation with MEV protection
            if not self.mev_protection.decode_opportunity(log_data):
                return None
                
            # Analyze with GPU acceleration
            opportunity = await self.gpu.analyze_opportunity(log_data)
            if not opportunity:
                return None
                
            # Calculate price impact
            impact_data = {
                "amount": opportunity['amount_in'],
                "price_impact": opportunity['profit'] / 100  # Convert profit % to decimal
            }
            
            impact, metrics = await self.impact_calculator.calculate_impact(impact_data)
            if impact > self.config['trading']['limits']['max_price_impact']:
                return None

            # Execute trade if profitable
            if opportunity['profit'] >= float(self.MIN_PROFIT):
                params = TradeParams(
                    pool_address=self.config['accounts']['sol_wsol']['amm_id'],
                    amount_in=opportunity['amount_in'],
                    min_amount_out=opportunity['amount_out'] * (1 - float(self.SLIPPAGE))
                )
                
                signature = self.trading_core.execute_trade(params)
                if signature:
                    self.successful_trades += 1
                    self.total_profit += Decimal(str(opportunity['profit']))
                    
                    logger.info(f"""
Trade Executed Successfully:
Signature: {signature}
Amount In: {opportunity['amount_in']:.6f} SOL
Amount Out: {opportunity['amount_out']:.6f} SOL
Profit: {opportunity['profit']:.4f}%
Total Profit: {float(self.total_profit):.6f} SOL
Total Trades: {self.successful_trades}
                    """)
                    return True
                    
            return False

        except Exception as e:
            logger.error(f"Opportunity processing error: {e}", exc_info=True)
            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
                ) 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}")
                await asyncio.sleep(1)

    async def cleanup(self):
        """Cleanup all components"""
        logger.info("Cleaning up trading system...")
        try:
            self.active = False
            
            if self.gpu:
                await self.gpu.cleanup()
            if self.vector_store:
                await self.vector_store.cleanup()
            if self.impact_calculator:
                await self.impact_calculator.cleanup()
            if self.system:
                await self.system.stop()
                
            logger.info("Cleanup completed successfully")
            
        except Exception as e:
            logger.error(f"Cleanup error: {e}")

if __name__ == "__main__":
    # Setup CUDA and PyTorch
    import torch
    import torch.amp as amp
    
    # Configure PyTorch/CUDA settings
    torch.backends.cuda.matmul.allow_tf32 = True  # Enable TF32 for better performance
    torch.cuda.set_device(0)  # Use first GPU
    
    # Print CUDA info
    logger.info(f"PyTorch version: {torch.__version__}")
    logger.info(f"CUDA version: {torch.version.cuda}")
    logger.info(f"GPU Device: {torch.cuda.get_device_name()}")
    logger.info(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.2f} GB")
    
    # Setup memory allocation
    if hasattr(torch.cuda, 'set_per_process_memory_fraction'):
        torch.cuda.set_per_process_memory_fraction(0.8)  # Use 80% of GPU memory
    
    # Clear any existing allocations
    torch.cuda.empty_cache()
    
    # Setup logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s.%(msecs)03d [%(levelname)s] %(message)s',
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler(f'trading_{time.strftime("%Y%m%d_%H%M%S")}.log')
        ]
    )

    async def main():
        try:
            # Initialize trader
            trader = RaydiumTrader('config.json')
            if not await trader.initialize():
                logger.error("Failed to initialize trading system")
                return

            # Start all monitoring tasks
            tasks = [
                trader.monitor_mempool(),
                trader._balance_management_loop(),
                trader._health_management_loop(),
                trader._price_monitoring_loop(),
                trader._continuous_cleanup_loop()
            ]
            
            await asyncio.gather(*tasks)
            
        except KeyboardInterrupt:
            logger.info("Shutting down by user request...")
        except Exception as e:
            logger.error(f"Fatal error: {e}", exc_info=True)
        finally:
            if trader:
                await trader.cleanup()

    # Run the system
    asyncio.run(main()) can you please write this in the proper order and add proffesional grade debug logging thanks