can u fix my file please its supposed to store the logging in the proper places and with only 2 files at all times 1 previous and 1 current of the logging folders i have here and its to clean up the old ones so its easily managable so without removing my code can u add that to this file C:\solana_rust_bot\logs
C:\solana_rust_bot\logs\archived
C:\solana_rust_bot\logs\debug
C:\solana_rust_bot\logs\errors
C:\solana_rust_bot\logs\system
C:\solana_rust_bot\logs\trading these are the locations i have available and heres the script to add the debug logging without removing my coide i have 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
from pathlib import Path

# Import all 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
from optimized_parser import OptimizedParser

# Define the base logs directory
LOG_DIR = Path("C:/solana_rust_bot/logs/trading")

# Ensure log directory exists
LOG_DIR.mkdir(parents=True, exist_ok=True)

# Cleanup function for old logs
def cleanup_old_logs(log_dir: Path, max_logs: int = 2):
    """Keep only the most recent max_logs log files."""
    try:
        log_files = sorted(log_dir.glob('*.log'), key=os.path.getmtime)  # Sort by modified time
        if len(log_files) > max_logs:
            # Delete old log files
            for log_file in log_files[:-max_logs]:
                log_file.unlink()  # Delete the old log file
                logging.info(f"Deleted old log file: {log_file.name}")  # Log the deletion
    except Exception as e:
        logging.error(f"Log cleanup error: {e}")

# Call cleanup function at the start of the script
cleanup_old_logs(LOG_DIR)

# Configure logging
current_log_file = LOG_DIR / f'raydium_trader_{time.strftime("%Y%m%d_%H%M%S")}.log'
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(funcName)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=[
        logging.StreamHandler(),  # Log to console
        logging.FileHandler(current_log_file)  # Log to the current log file
    ]
)

logger = logging.getLogger(__name__)

class RaydiumTrader:
    def __init__(self, config_path: str):
        """Initialize RaydiumTrader with configuration"""
        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

        # Initialize state variables
        self.active = False
        self.last_trade_time = 0
        self.trade_count = 0

        # Initialize components to None
        self.parser = OptimizedParser(self.config)
        self.trading_core = None
        self.system = None
        self.gpu_accelerator = None
        self.vector_store = None
        self.impact_calculator = None
        self.price_monitor = None
        self.mev_protection = None
        self.mempool_analyzer = None
        self.advanced_trading = None
        self.solana_cli = None

    async def initialize(self) -> bool:
        """Initialize all trading components"""
        try:
            logger.info("Starting system initialization...")

            # Initialize system manager first
            self.system = SystemManager()
            await self.system.start()
            logger.info("System manager started successfully.")

            # 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,
                min_profit_pct=self.config['trading']['limits']['min_profit_pct'],
                max_profit_pct=self.config['trading']['limits']['max_profit_pct']
            )
            self.gpu_accelerator = GPUAccelerator(gpu_config)
            logger.info("GPU accelerator 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'],
                "skip_preflight": True
            }

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

            # Initialize remaining components
            self.solana_cli = SolanaCLI(self.trading_core)
            logger.info("Solana CLI initialized successfully.")

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

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

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

            self.advanced_trading = AdvancedTrading(self, self.config)
            logger.info("Advanced trading 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.")

            # Update pool data and get initial balance
            pool_data = self.config['accounts']['sol_wsol']
            self.trading_core.update_pool(pool_data)
            sol_balance = self.trading_core.get_balance()
            logger.info(f"Initial SOL Balance: {sol_balance}")

            self.active = True
            return True

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

    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()
                        
                        # Use optimized parser
                        opportunity = await self.parser.parse_log(msg)
                        if opportunity and await self.parser.validate_opportunity(opportunity):
                            # Run parallel analysis
                            results = await asyncio.gather(
                                self.mempool_analyzer.analyze_transaction(opportunity.raw_data),
                                self.advanced_trading._check_direct_swap(opportunity.raw_data),
                                self.advanced_trading._check_triangle_arbitrage(opportunity.raw_data)
                            )
                            
                            # Filter valid results
                            valid_results = [r for r in results if r and r.get('profit', 0) > 0]
                            if valid_results:
                                best_opp = max(valid_results, key=lambda x: x['profit'])
                                await self.advanced_trading._execute_opportunity(best_opp)
                            
            except websockets.exceptions.ConnectionClosed:
                logger.warning("WebSocket connection closed. Reconnecting...")
                await asyncio.sleep(1)
            except Exception as e:
                logger.error(f"Mempool monitoring error: {e}")
                await asyncio.sleep(1)

    async def monitor_system_health(self):
        """Monitor system health and performance"""
        logger.info("Starting system health monitoring...")
        while self.active:
            try:
                metrics = await self.system.collect_metrics()

                if metrics.gpu_usage > 0:
                    logger.info(f"""
                    System Health:
                    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}%
                    """)

                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)

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

    async def rebalance_loop(self):
        """Monitor and manage SOL/WSOL balances"""
        logger.info("Starting balance monitoring and rebalancing loop...")
        
        while self.active:
            try:
                # Get SOL balance
                sol_balance = self.trading_core.get_balance()
                
                # Check if we need to close WSOL account
                if sol_balance < self.config['trading']['position']['gas_reserve']:
                    logger.warning(f"SOL balance ({sol_balance}) below gas reserve. Closing WSOL account if exists...")
                    await asyncio.sleep(1)
                    continue

                # Check if we should create/fund WSOL account
                target_wsol = self.config['trading']['balance_management']['wsol_target_ratio']
                min_rebalance = self.config['trading']['balance_management']['min_rebalance_amount']
                
                if sol_balance > (self.config['trading']['position']['gas_reserve'] * 2):
                    amount_to_wrap = min(
                        sol_balance * target_wsol,
                        sol_balance - self.config['trading']['position']['gas_reserve']
                    )
                    
                    if amount_to_wrap >= min_rebalance:
                        logger.info(f"Converting {amount_to_wrap:.6f} SOL to WSOL")
                        self.trading_core.transfer_to_wsol(float(amount_to_wrap))
                        logger.info("WSOL account funded successfully")

                await asyncio.sleep(60)

            except Exception as e:
                logger.error(f"Rebalance loop error: {e}")
                await asyncio.sleep(5)

    async def cleanup(self):
        """Clean up all resources"""
        try:
            logger.info("Cleaning up trading system...")
            self.active = False

            cleanup_tasks = []

            if hasattr(self, 'gpu_accelerator'):
                cleanup_tasks.append(self.gpu_accelerator.cleanup())

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

            if hasattr(self, 'mempool_analyzer'):
                cleanup_tasks.append(self.mempool_analyzer.cleanup())

            if hasattr(self, 'system'):
                cleanup_tasks.append(self.system.cleanup())

            if cleanup_tasks:
                await asyncio.gather(*cleanup_tasks, return_exceptions=True)

            logger.info("Cleanup complete")

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


async def main():
    trader = None
    start_time = time.time()
    
    try:
        logger.info("Starting Raydium Trading Bot...")
        
        # Configure GPU settings
        torch.cuda.set_device(0)
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.benchmark = True
        
        if torch.cuda.is_available():
            gpu_name = torch.cuda.get_device_name()
            gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
            logger.info(f"Using GPU: {gpu_name} with {gpu_memory:.2f}GB memory")
        else:
            logger.warning("No GPU detected, running on CPU")

        # Initialize trader
        trader = RaydiumTrader('config.json')
        
        # Initialize core components with timeout
        try:
            async with asyncio.timeout(60):  # 60 second timeout for initialization
                initialized = await trader.initialize()
                if not initialized:
                    logger.error("Failed to initialize trader")
                    return
        except asyncio.TimeoutError:
            logger.error("Initialization timed out")
            return

        # Start monitoring and trading tasks with enhanced error handling
        tasks = [
            asyncio.create_task(trader.monitor_mempool(), name="mempool_monitor"),
            asyncio.create_task(trader.monitor_system_health(), name="health_monitor"),
            asyncio.create_task(trader.rebalance_loop(), name="balance_monitor")
        ]
        
        logger.info("All monitoring tasks started")
        
        try:
            # Run all tasks with enhanced error handling
            done, pending = await asyncio.wait(
                tasks,
                return_when=asyncio.FIRST_EXCEPTION
            )
            
            # Check for exceptions
            for task in done:
                if task.exception():
                    logger.error(f"Task {task.get_name()} failed: {task.exception()}")
                    raise task.exception()
                    
        finally:
            # Cancel any remaining tasks
            for task in tasks:
                if not task.done():
                    task.cancel()
            
            # Wait for tasks to complete
            await asyncio.gather(*tasks, return_exceptions=True)

    except KeyboardInterrupt:
        logger.info("Received shutdown signal. Cleaning up...")
    except Exception as e:
        logger.error(f"Fatal error: {e}", exc_info=True)
        if trader and trader.system:
            trader.system.log_error("Fatal error in main loop", exc_info=e)
    finally:
        try:
            if trader:
                logger.info("Cleaning up trading system...")
                await asyncio.wait_for(trader.cleanup(), timeout=30.0)
                
            runtime = time.time() - start_time
            logger.info(f"Trading bot shutdown complete. Total runtime: {runtime/3600:.2f} hours")
            
        except asyncio.TimeoutError:
            logger.error("Cleanup timed out")
        except Exception as e:
            logger.error(f"Error during cleanup: {e}", exc_info=True)

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