add this def _initialize_state(self):
    """Initialize bot state with proper trade limits"""
    self.active = True
    self.execution_lock = asyncio.Lock()
    self.last_trade_time = 0
    self.active_trades = 0
    self.MAX_ACTIVE_TRADES = 1
    self.MIN_TRADE_INTERVAL = 0.5  # 2 TPS max
    self.metrics = {
        'trades_found': 0,
        'trades_executed': 0,
        'successful_trades': 0,
        'total_profit': 0.0,
        'execution_times': []
    }

async def _execute_trade_sequence(self, trade_info: dict):
    """Execute trade with proper rate limiting"""
    try:
        current_time = time.time()
        if self.active_trades >= self.MAX_ACTIVE_TRADES:
            return
        
        if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL:
            return

        async with self.execution_lock:
            market_accounts = config.get_market_accounts()
            trade_accounts = [
                config.get("wallet"),                    # signer
                config.get("wallet"),                    # user
                config.get("wsol_token_account"),        # user_token
                config.get("wsol_token_account"),        # user_wsol
                market_accounts["amm_authority"],        # AMM Authority needs to be before market
                market_accounts["market"],               # market
                market_accounts["amm_open_orders"],      # amm_open_orders
                market_accounts["amm_target"],           # amm_target
                market_accounts["serum_market"],         # serum_market
                market_accounts["serum_bids"],           # serum_bids
                market_accounts["serum_asks"],           # serum_asks
                market_accounts["event_queue"],          # event_queue
                market_accounts["base_vault"],           # base_vault
                market_accounts["quote_vault"],          # quote_vault
                market_accounts["vault_signer"]          # vault_signer
            ]to this import asyncio
import json
import websockets
import time
import base64
import numpy as np
import torch
from pathlib import Path
import os
import platform
from solana_rust_bot import TradingCore, TradeParams
from config_loader import config
from solana_logger import logger

# Fix Windows event loop
if platform.system() == 'Windows':
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

class ProductionMEVBot:
    def __init__(self):
        logger.info("Initializing Production MEV Bot")
        
        # System Optimization
        self._setup_system()
        
        # Initialize trading core
        network_config = config.get_network_config()
        self.trading_core = TradingCore(
            rpc_url=network_config["rpc_url"],
            keypair_bytes=config.get_keypair_bytes()
        )

        # Constants
        self.WSOL_MINT = "So11111111111111111111111111111111111111112"
        self.SOL_DECIMALS = 9
        self.MAX_RETRIES = 3
        self.RETRY_DELAY = 0.1
        
        # Trading Parameters
        self._setup_trading_params()
        
        # Initialize state
        self._initialize_state()
        
        # Setup CUDA
        self._setup_cuda()
        logger.info("Bot initialization complete")

    def _setup_system(self):
        """Configure system settings"""
        os.environ["MKL_NUM_THREADS"] = str(os.cpu_count())
        os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count())
        os.environ["OMP_NUM_THREADS"] = str(os.cpu_count())
        np.set_printoptions(precision=4, suppress=True)

    def _setup_trading_params(self):
        """Initialize trading parameters"""
        self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0))
        self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0))
        self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002))
        self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4))
        self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05))
        self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000))
        self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100))

    def _setup_cuda(self):
        """Configure CUDA for optimal performance"""
        if not torch.cuda.is_available():
            raise RuntimeError("CUDA required for production!")

        torch.cuda.set_device(0)
        torch.cuda.empty_cache()
        torch.set_float32_matmul_precision('high')
        torch.backends.cudnn.benchmark = True
        torch.backends.cudnn.enabled = True
        self.stream = torch.cuda.Stream(priority=-1)

        cuda_info = torch.cuda.get_device_properties(0)
        logger.info(f"""
🚀 CUDA Configuration:
GPU: {torch.cuda.get_device_name()}
Memory: {cuda_info.total_memory/1e9:.1f}GB
Position Size: {self.POSITION_SIZE} WSOL
Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL
Min Profit: {self.MIN_PROFIT} SOL
""")

    def _initialize_state(self):
        """Initialize bot state"""
        self.active = True
        self.execution_lock = asyncio.Lock()
        self.last_trade_time = 0
        self.metrics = {
            'trades_found': 0,
            'trades_executed': 0,
            'successful_trades': 0,
            'total_profit': 0.0,
            'execution_times': []
        }
        self.ata_cache = {}

    def _calculate_profit(self, victim_size: float) -> float:
        """Calculate potential profit for trade size"""
        with torch.cuda.stream(self.stream):
            impact = self.POSITION_SIZE / victim_size
            
            if victim_size >= 35:
                rate = 0.012  # Premium rate
            elif victim_size >= 20:
                rate = 0.010  # Standard rate
            else:
                rate = 0.008  # Mini rate
            
            return float(victim_size * impact * rate - 0.001)

    def _decode_ray_log(self, raw_data: bytes) -> dict:
        """Decode and validate ray log data"""
        try:
            size = int.from_bytes(raw_data[1:9], "little") / 1e9
            
            if not (self.MIN_SIZE <= size <= self.MAX_SIZE):
                return None

            profit = self._calculate_profit(size)
            
            if profit > self.MIN_PROFIT:
                return {
                    'size': size,
                    'profit': profit,
                    'data': raw_data
                }

        except Exception as e:
            logger.error(f"Ray log decode error: {str(e)}")
        return None

    async def _execute_trade_sequence(self, trade_info: dict):
        """Execute complete trade sequence"""
        try:
            market_accounts = config.get_market_accounts()
            trade_accounts = [
                config.get("wallet"),                    # signer
                config.get("wallet"),                    # user
                config.get("wsol_token_account"),        # user_token
                config.get("wsol_token_account"),        # user_wsol
                config.get("raydium"),                   # raydium_program
                market_accounts["market"],               # market
                market_accounts["amm_authority"],        # amm_authority
                market_accounts["amm_open_orders"],      # amm_open_orders
                market_accounts["amm_target"],           # amm_target
                market_accounts["serum_market"],         # serum_market
                market_accounts["serum_bids"],           # serum_bids
                market_accounts["serum_asks"],           # serum_asks
                market_accounts["event_queue"],          # event_queue
                market_accounts["base_vault"],           # base_vault
                market_accounts["quote_vault"],          # quote_vault
                market_accounts["vault_signer"]          # vault_signer
            ]

            # Entry trade
            entry_params = TradeParams(
                accounts=trade_accounts,
                amount_in=self.POSITION_SIZE,
                is_buy=True,
                victim_data=base64.b64encode(trade_info['data']).decode(),
                reuse_blockhash=False,
                token_a_mint=self.WSOL_MINT,
                token_b_mint=self.WSOL_MINT
            )
            
            start_time = time.time()
            entry_sig = await self.trading_core.execute_trade_py(entry_params)
            
            if not entry_sig:
                logger.error("Entry trade failed")
                return

            # Quick exit trade
            exit_params = TradeParams(
                accounts=trade_accounts,
                amount_in=self.POSITION_SIZE,
                is_buy=False,
                victim_data=None,
                reuse_blockhash=True,
                token_a_mint=self.WSOL_MINT,
                token_b_mint=self.WSOL_MINT
            )
            
            exit_sig = await self.trading_core.execute_trade_py(exit_params)
            execution_time = (time.time() - start_time) * 1000  # convert to ms
            
            if exit_sig:
                self.metrics['successful_trades'] += 1
                self.metrics['total_profit'] += trade_info['profit']
                self.metrics['execution_times'].append(execution_time)
                self.last_trade_time = time.time()
                
                trade_type = (
                    "PREMIUM" if trade_info['size'] >= 35 else
                    "STANDARD" if trade_info['size'] >= 20 else
                    "MINI"
                )
                
                logger.info(f"""
💫 Trade #{self.metrics['successful_trades']} [{trade_type}]
Entry: {entry_sig}
Exit: {exit_sig}
Size: {trade_info['size']:.2f} SOL
Profit: {trade_info['profit']:.6f} SOL
Time: {execution_time:.3f}ms
Total Profit: {self.metrics['total_profit']:.6f} SOL
""")

        except Exception as e:
            logger.error(f"Trade sequence error: {str(e)}")

    async def _process_message(self, msg: str):
        """Process incoming WebSocket messages"""
        try:
            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())
                        trade_info = self._decode_ray_log(raw_data)
                        
                        if trade_info:
                            self.metrics['trades_found'] += 1
                            async with self.execution_lock:
                                await self._execute_trade_sequence(trade_info)
                        
        except Exception as e:
            logger.error(f"Message processing error: {str(e)}")

    async def start(self):
        """Start the MEV bot"""
        network = config.get_network_config()
        logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50)
        
        while self.active:
            try:
                async with websockets.connect(
                    network['ws_url'],
                    extra_headers={'api-key': network['api_key']},
                    ping_interval=None,
                    ping_timeout=None
                ) as ws:
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "logsSubscribe",
                        "params": [
                            {"mentions": [config.get('raydium')]},
                            {"commitment": "processed"}
                        ]
                    }))
                    
                    while True:
                        msg = await ws.recv()
                        await self._process_message(msg)
                        
            except Exception as e:
                logger.error(f"WebSocket error: {str(e)}")
                await asyncio.sleep(1)

    async def cleanup(self):
        """Cleanup resources"""
        logger.info("Starting cleanup...")
        self.active = False
        torch.cuda.empty_cache()
        
        if len(self.metrics['execution_times']) > 0:
            avg_execution = np.mean(self.metrics['execution_times'])
            success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100
            
            logger.info(f"""
🔚 Bot Statistics:
Trades Found: {self.metrics['trades_found']}
Trades Executed: {self.metrics['trades_executed']}
Successful Trades: {self.metrics['successful_trades']}
Success Rate: {success_rate:.1f}%
Average Execution: {avg_execution:.3f}ms
Total Profit: {self.metrics['total_profit']:.6f} SOL
""")

async def main():
    bot = ProductionMEVBot()
    try:
        await bot.start()
    except KeyboardInterrupt:
        await bot.cleanup()
        logger.info("Bot stopped by user")
    except Exception as e:
        logger.error(f"Fatal error: {str(e)}")
        await bot.cleanup()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass