do me a favor and make the proper edits and include this async def monitor_market_data(self):
    """Monitor market data continuously"""
    self.logger.info("Starting market data monitoring")
    while True:
        try:
            # Get updates from the websocket instead of direct pool query
            updates = await self._get_market_updates()
            
            if updates:
                for update in updates:
                    decoded_data = self.decode_pool_data(update)
                    if decoded_data:
                        self.update_metrics(decoded_data)
                        market_data = self.get_latest_market_data()
                        
                        if self._validate_trading_conditions(market_data):
                            trade_result = await self.execute_trade(market_data)
                            if trade_result:
                                self.logger.info(f"Trade executed: {trade_result}")
            
            await asyncio.sleep(0.1)
            
        except Exception as e:
            self.logger.error(f"Market monitoring error: {str(e)}")
            await asyncio.sleep(1)

async def _get_market_updates(self) -> List[Dict]:
    """Get market updates from websocket data"""
    # This will be populated by the market poller
    return list(self.active_tokens.values())

def _validate_trading_conditions(self, market_data: Optional[Dict]) -> bool:
    """Validate if we should trade based on market conditions"""
    if not market_data:
        return False
        
    try:
        token = self.active_tokens.get(market_data['token_mint'])
        if not token:
            return False
            
        return all([
            token.volume_5min >= self.min_volume,
            token.bs_ratio >= self.min_bs_ratio,
            token.liquidity >= self.min_liquidity,
            token.liquidity_locked >= self.min_lp_locked,
            not token.mint_authority
        ])
    except Exception as e:
        self.logger.error(f"Trading validation error: {e}")
        return False

async def execute_trade(self, market_data: Dict) -> Optional[str]:
    """Execute trade with proper async handling"""
    try:
        trade_data = {
            "token_mint": market_data["token_mint"],
            "size": self.position_size,
            "slippage_bps": self.config["jupiter"]["default_slippage_bps"],
            "priority_fee": self.config["trading"]["priority_fee"],
            "compute_limit": self.config["trading"]["compute_limit"]
        }
        
        signature = self.core.execute_trade(json.dumps(trade_data))
        if signature:
            await self.record_trade(signature, market_data)
            return signature
            
        return None
        
    except Exception as e:
        self.logger.error(f"Trade execution error: {e}")
        return None   this code here needs to be inside of this script here   import os
import base64
import struct
import json
from typing import Optional, Dict, List
import logging
import time
from dataclasses import dataclass
from pathlib import Path
from solana_rust_bot import TradingCore
import asyncio

@dataclass
class TokenMetrics:
    """Data class for token metrics"""
    mint: str
    liquidity: float
    volume_5min: float
    buy_pressure: int
    sell_pressure: int
    price: float
    bs_ratio: float
    mint_authority: bool
    liquidity_locked: float
    holder_count: Optional[int] = None
    market_cap: float = 0.0

class MarketData:
    def __init__(self, config: Dict):
        self.logger = logging.getLogger(__name__)
        
        try:
            self.config = config
            self.root_dir = Path(__file__).parent.parent.parent
            
            # Validate paths and load config
            self._validate_paths()
            
            # Initialize TradingCore with config
            self.core = TradingCore(json.dumps(config))
            
            # Initialize state
            self.successful_trades: List[Dict] = []
            self.recent_prices: Dict[str, float] = {}
            self.total_volume: Dict[str, float] = {}
            self.active_tokens: Dict[str, TokenMetrics] = {}
            
            # Load parameters
            self._load_parameters()
            
            # Initialize tracking
            self.last_trade_time = 0
            self.trade_count = 0
            self.total_profit = 0.0
            
            self.logger.info("Market data initialized")

        except Exception as e:
            self.logger.error(f"Market data initialization failed: {e}")
            raise

    async def get_balance(self) -> float:
        """Get wallet SOL balance with proper async handling"""
        max_retries = 3
        last_error = None
        
        for attempt in range(max_retries):
            try:
                balance = await asyncio.to_thread(self.core.get_balance)
                balance_value = float(balance)
                
                if balance_value > 0:
                    self.logger.info(f"Current balance: {balance_value:.6f} SOL")
                    return balance_value
                    
                self.logger.warning(f"Received zero balance on attempt {attempt + 1}")
                await asyncio.sleep(0.1)
                
            except Exception as e:
                last_error = e
                self.logger.error(f"Balance check attempt {attempt + 1} failed: {e}")
                await asyncio.sleep(0.1)
        
        self.logger.error(f"All balance checks failed: {last_error}")
        return 0.0

    async def initialize(self):
        """Async initialization"""
        try:
            # Get initial balance
            initial_balance = await self.get_balance()
            self.logger.info(f"Initial wallet balance: {initial_balance:.6f} SOL")
            return initial_balance
        except Exception as e:
            self.logger.error(f"Async initialization failed: {e}")
            raise

    def _validate_paths(self):
        """Validate config and keypair files"""
        config_path = self.root_dir / "config.json"
        keypair_path = self.root_dir / "id.json"
        
        if not config_path.exists():
            raise FileNotFoundError(f"Config not found at: {config_path}")
            
        if not keypair_path.exists():
            raise FileNotFoundError(f"Keypair not found at: {keypair_path}")
            
        # Validate keypair format
        with open(keypair_path, 'r') as f:
            keypair_data = json.load(f)
            if not isinstance(keypair_data, list) or len(keypair_data) != 64:
                raise ValueError(f"Invalid keypair format or length: {len(keypair_data)}")
                
        self.logger.info(f"Using config at: {config_path}")
        self.logger.info(f"Using keypair at: {keypair_path}")

    def _load_parameters(self):
        """Load trading parameters from config"""
        trading_config = self.config["trading"]
        safety_config = self.config["safety"]
        
        # Trading parameters
        self.min_volume = float(trading_config["min_volume"])
        self.min_bs_ratio = float(trading_config["min_bs_ratio"])
        self.min_liquidity = float(trading_config["min_liquidity"])
        self.max_liquidity = float(trading_config["max_liquidity"])
        self.take_profit = float(trading_config["take_profit"])
        self.stop_loss = float(trading_config["stop_loss"])
        self.position_size = float(trading_config["position_size"])
        self.max_active_trades = int(trading_config["max_active_trades"])
        
        # Safety parameters
        self.market_cap_min = float(safety_config["market_cap_min"])
        self.min_lp_locked = float(trading_config["liquidity_lock_min"])
        self.emergency_stop_loss = float(safety_config["emergency_stop_loss"])

    def decode_pool_data(self, base64_data: str) -> Optional[Dict]:
        """Decode and validate Raydium pool data"""
        try:
            raw = base64.b64decode(base64_data)
            
            # Extract data with correct byte offsets
            pool_data = {
                "pool_address": raw[0:32].hex(),
                "token_mint": raw[32:64].hex(),
                "volume_24h": self.total_volume.get(raw[32:64].hex(), 0),
                "liquidity": int.from_bytes(raw[360:368], "little") / 1e9,
                "price": int.from_bytes(raw[344:352], "little") / 1e9,
                "buy_pressure": int.from_bytes(raw[336:344], "little"),
                "sell_pressure": max(int.from_bytes(raw[328:336], "little"), 1),
                "volume_5min": int.from_bytes(raw[352:360], "little") / 1e9,
                "mint_authority_revoked": bool(raw[248]),
                "liquidity_locked_pct": int.from_bytes(raw[240:248], "little") / 100,
            }
            
            # Calculate additional metrics
            pool_data["bs_ratio"] = pool_data["buy_pressure"] / pool_data["sell_pressure"]
            pool_data["timestamp"] = time.time()
            
            # Create metrics object
            metrics = TokenMetrics(
                mint=pool_data["token_mint"],
                liquidity=pool_data["liquidity"],
                volume_5min=pool_data["volume_5min"],
                buy_pressure=pool_data["buy_pressure"],
                sell_pressure=pool_data["sell_pressure"],
                price=pool_data["price"],
                bs_ratio=pool_data["bs_ratio"],
                mint_authority=not pool_data["mint_authority_revoked"],
                liquidity_locked=pool_data["liquidity_locked_pct"],
                market_cap=pool_data["liquidity"] * pool_data["price"] * 2
            )
            
            # Update state
            self.recent_prices[metrics.mint] = metrics.price
            if metrics.mint in self.total_volume:
                self.total_volume[metrics.mint] += metrics.volume_5min
            else:
                self.total_volume[metrics.mint] = metrics.volume_5min
            
            # Validate and store
            if self._validate_metrics(metrics):
                self.active_tokens[metrics.mint] = metrics
                return pool_data
                    
            return None
            
        except Exception as e:
            self.logger.error(f"Pool decode error: {e}")
            return None

    def _validate_metrics(self, metrics: TokenMetrics) -> bool:
        """Validate pool metrics against thresholds"""
        try:
            return all([
                metrics.market_cap >= self.market_cap_min,
                metrics.liquidity >= self.min_liquidity,
                metrics.liquidity <= self.max_liquidity,
                metrics.volume_5min >= self.min_volume,
                metrics.bs_ratio >= self.min_bs_ratio,
                metrics.liquidity_locked >= self.min_lp_locked,
                not metrics.mint_authority,
            ])
        except Exception as e:
            self.logger.error(f"Metrics validation error: {e}")
            return False

    def execute_trade(self, trade_data: Dict) -> Optional[str]:
        """Execute trade through Jupiter"""
        try:
            current_time = time.time()
            
            if current_time - self.last_trade_time < 1:
                return None
                
            if self.trade_count >= self.max_active_trades:
                return None
            
            self.logger.info(f"""
            Executing trade:
            Pool: {trade_data['pool_address']}
            Size: {self.position_size} SOL
            BS Ratio: {trade_data.get('bs_ratio', 0)}
            Volume: {trade_data.get('volume_5min', 0)}
            """)
            
            jupiter_data = {
                **trade_data,
                "slippage_bps": self.config["jupiter"]["default_slippage_bps"],
                "priority_fee": self.config["trading"]["priority_fee"],
                "compute_limit": self.config["trading"]["compute_limit"]
            }
            
            signature = self.core.execute_jupiter_swap(json.dumps(jupiter_data))
            
            if signature:
                self.last_trade_time = current_time
                self.trade_count += 1
                self.logger.info(f"Trade executed: {signature}")
                return signature
                
            return None
            
        except Exception as e:
            self.logger.error(f"Trade execution error: {e}")
            return None

    def record_trade(self, signature: str, token_mint: str, size: float, 
                    entry_price: float, exit_price: float, profit: float) -> None:
        """Record successful trade details"""
        try:
            trade = {
                "signature": signature,
                "token_mint": token_mint,
                "size": size,
                "entry_price": entry_price,
                "exit_price": exit_price,
                "profit": profit,
                "timestamp": time.time()
            }
            self.successful_trades.append(trade)
            self.total_profit += profit
            
            self.logger.info(f"""
            Trade recorded:
            Token: {token_mint}
            Profit: {profit:.2f}%
            Size: {size:.4f} SOL
            Total Profit: {self.total_profit:.2f}%
            Total Trades: {len(self.successful_trades)}
            """)
            
        except Exception as e:
            self.logger.error(f"Trade recording error: {e}")

    async def get_balance(self) -> float:
        """Get wallet SOL balance with proper async handling"""
        max_retries = 3
        last_error = None
    
        for attempt in range(max_retries):
            try:
                # Get balance synchronously and convert to float
                raw_balance = self.core.get_balance()
                if isinstance(raw_balance, (int, float)):
                    balance_value = float(raw_balance)
                else:
                    balance_value = 0.0
                
                if balance_value > 0:
                    self.logger.info(f"Current balance: {balance_value:.6f} SOL")
                    return balance_value
                
                self.logger.warning(f"Received zero balance on attempt {attempt + 1}")
                await asyncio.sleep(0.1)
            
            except Exception as e:
                last_error = e
                self.logger.error(f"Balance check attempt {attempt + 1} failed: {e}")
                await asyncio.sleep(0.1)
    
        self.logger.error(f"All balance checks failed: {last_error}")
        return 0.0
 
    def get_latest_market_data(self) -> Dict:
        """Get latest market data for analysis"""
        try:
            active_token = max(
                self.active_tokens.items(),
                key=lambda x: x[1].volume_5min
            )[0] if self.active_tokens else None
            
            if not active_token:
                return {}
                
            metrics = self.active_tokens[active_token]
            return {
                "token_mint": metrics.mint,
                "price": metrics.price,
                "volume_5min": metrics.volume_5min,
                "liquidity": metrics.liquidity,
                "buy_pressure": metrics.buy_pressure,
                "sell_pressure": metrics.sell_pressure,
                "bs_ratio": metrics.bs_ratio,
                "liquidity_locked_pct": metrics.liquidity_locked,
                "market_cap": metrics.market_cap,
                "timestamp": time.time()
            }
            
        except Exception as e:
            self.logger.error(f"Market data retrieval error: {e}")
            return {}

    def update_metrics(self, pool_data: Dict):
        """Update market metrics"""
        try:
            token_mint = pool_data["token_mint"]
            if token_mint in self.active_tokens:
                metrics = self.active_tokens[token_mint]
                metrics.price = pool_data["price"]
                metrics.volume_5min = pool_data["volume_5min"]
                metrics.liquidity = pool_data["liquidity"]
                metrics.buy_pressure = pool_data["buy_pressure"]
                metrics.sell_pressure = pool_data["sell_pressure"]
                metrics.bs_ratio = pool_data["bs_ratio"]
                metrics.liquidity_locked = pool_data["liquidity_locked_pct"]
                metrics.market_cap = pool_data["liquidity"] * pool_data["price"] * 2
                
        except Exception as e:
            self.logger.error(f"Metrics update error: {e}")

    def get_status(self) -> Dict:
        """Get current trading system status"""
        try:
            profitable_trades = [t for t in self.successful_trades if t["profit"] > 0]
            return {
                "total_trades": len(self.successful_trades),
                "active_tokens": len(self.active_tokens),
                "total_volume": sum(self.total_volume.values()),
                "successful_trades": len(profitable_trades),
                "total_profit": self.total_profit,
                "win_rate": len(profitable_trades) / max(len(self.successful_trades), 1) * 100
            }
        except Exception as e:
            self.logger.error(f"Status check error: {e}")
            return {}

    async def cleanup(self) -> None:
        """Cleanup resources and save final statistics"""
        try:
            stats = self.get_status()
            self.logger.info(f"""
            Final Trading Statistics:
            Total Trades: {stats['total_trades']}
            Total Profit: {stats['total_profit']:.2f}%
            Win Rate: {stats['win_rate']:.1f}%
            Total Volume: {stats['total_volume']:.2f}
            """)
            
            # Clear data structures
            self.active_tokens.clear()
            self.recent_prices.clear()
            self.total_volume.clear()
            self.successful_trades.clear()
            
        except Exception as e:
            self.logger.error(f"Cleanup error: {e}")

    async def monitor_market_data(self):
        """Monitor market data continuously"""
        self.logger.info("Starting market data monitoring")
        while True:
            try:
                # Get pool updates from market poller
                pool_updates = await self.core.get_pool_data()
                
                if pool_updates:
                    # Decode and process pool data
                    decoded_data = self.decode_pool_data(pool_updates)
                    if decoded_data:
                        # Update metrics
                        self.update_metrics(decoded_data)
                        
                        # Get latest market analysis
                        market_data = self.get_latest_market_data()
                        
                        # Check trading conditions
                        if market_data and self._validate_metrics(self.active_tokens.get(market_data['token_mint'])):
                            # Execute trade if conditions are met
                            trade_result = self.execute_trade(decoded_data)
                            if trade_result:
                                self.logger.info(f"Trade executed: {trade_result}")
                    
                    # Update balance periodically
                    balance = await self.get_balance()
                
                # Sleep to prevent CPU overuse
                await asyncio.sleep(0.1)
            
            except Exception as e:
                self.logger.error(f"Market monitoring error: {e}")
                await asyncio.sleep(1)
    async def process_market_updates(self):
        """Process market updates"""
        while True:
            try:
                # Get latest market data
                market_data = self.get_latest_market_data()
                
                if market_data:
                    # Process market data
                    token_mint = market_data["token_mint"]
                    metrics = self.active_tokens.get(token_mint)
                    
                    if metrics and self._validate_metrics(metrics):
                        # Check for trading signals
                        if metrics.bs_ratio > self.min_bs_ratio * 1.5:  # Strong buy pressure
                            trade_data = {
                                "token_mint": token_mint,
                                "size": self.position_size,
                                "price": metrics.price
                            }
                            
                            # Execute trade if conditions met
                            signature = await self.execute_trade(trade_data)
                            if signature:
                                self.logger.info(f"Trade executed based on strong signals: {signature}")
                
                await asyncio.sleep(0.1)
                
            except Exception as e:
                self.logger.error(f"Market update processing error: {e}")
                await asyncio.sleep(1)

    async def monitor_positions(self):
        """Monitor positions for take profit/stop loss"""
        while True:
            try:
                for trade in list(self.successful_trades):
                    token_mint = trade["token_mint"]
                    if token_mint in self.recent_prices:
                        current_price = self.recent_prices[token_mint]
                        entry_price = trade["entry_price"]
                        
                        # Calculate profit/loss
                        pnl = ((current_price - entry_price) / entry_price) * 100
                        
                        # Check take profit
                        if pnl >= self.take_profit:
                            self.logger.info(f"Take profit triggered for {token_mint}: {pnl:.2f}%")
                            await self.execute_trade({
                                "token_mint": token_mint,
                                "size": trade["size"],
                                "type": "sell"
                            })
                            
                        # Check stop loss
                        elif pnl <= -self.stop_loss:
                            self.logger.info(f"Stop loss triggered for {token_mint}: {pnl:.2f}%")
                            await self.execute_trade({
                                "token_mint": token_mint,
                                "size": trade["size"],
                                "type": "sell"
                            })
                            
                        # Emergency stop loss
                        elif pnl <= -self.emergency_stop_loss:
                            self.logger.warning(f"Emergency stop loss triggered for {token_mint}: {pnl:.2f}%")
                            await self.execute_trade({
                                "token_mint": token_mint,
                                "size": trade["size"],
                                "type": "sell",
                                "emergency": True
                            })
                
                await asyncio.sleep(0.1)
                
            except Exception as e:
                self.logger.error(f"Position monitoring error: {e}")
                await asyncio.sleep(1)

    def calculate_position_size(self, token_metrics: TokenMetrics) -> float:
        """Calculate optimal position size based on market metrics"""
        try:
            base_size = self.position_size
            
            # Adjust size based on liquidity
            liquidity_factor = min(token_metrics.liquidity / self.min_liquidity, 2.0)
            
            # Adjust size based on volume
            volume_factor = min(token_metrics.volume_5min / self.min_volume, 2.0)
            
            # Adjust size based on buy/sell ratio
            bs_factor = min(token_metrics.bs_ratio / self.min_bs_ratio, 1.5)
            
            # Calculate final position size
            adjusted_size = base_size * liquidity_factor * volume_factor * bs_factor
            
            # Apply safety caps
            max_size = base_size * 3
            return min(adjusted_size, max_size)
            
        except Exception as e:
            self.logger.error(f"Position size calculation error: {e}")
            return self.position_size