please fix the console import and also please ensure you write back to me the same code just make sure the debugging log or logging that i have is good to find the solution to what ever the issues are cuasing them   # helius_client.py
import asyncio
import base64
import json
import logging
import os
import time
from typing import Dict, Optional, List
from decimal import Decimal
from pathlib import Path

import websockets
import yaml
from rich.console import Console
from rich.logging import RichHandler

# Import specific components
from solana_rust_bot import TradingCore, TradeParams
from price_impact import EnhancedImpactCalculator
from mempool_analyzer import EnhancedMempoolAnalyzer

# Configure logging with Rich
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=[
        RichHandler(
            show_time=True,
            show_path=False,
            rich_tracebacks=True,
            tracebacks_show_locals=True,
            console=Console()
        )
    ]
)
logger = logging.getLogger("helius_client")

class HeliusWebSocketClient:
    def __init__(
        self,
        trading_core: TradingCore, 
        impact_calculator: EnhancedImpactCalculator, 
        mempool_analyzer: EnhancedMempoolAnalyzer
    ):
        # Load Solana CLI config
        solana_config_path = Path.home() / '.config' / 'solana' / 'cli' / 'config.yml'
        try:
            with open(solana_config_path) as f:
                cli_config = yaml.safe_load(f)
                logger.info("Loaded Solana CLI config successfully.")
        except Exception as e:
            logger.warning(f"Failed to load Solana config: {e}")
            cli_config = {}

        # Configuration with CLI fallback
        self.config = {
            'ws_url': os.getenv('WS_URL') or cli_config.get('websocket_url'),
            'rpc_url': os.getenv('RPC_URL') or cli_config.get('json_rpc_url'),
            'api_key': os.getenv('HELIUS_API_KEY'),
            'raydium_program_id': os.getenv('RAYDIUM_PROGRAM_ID'),
            'wsol_account': os.getenv('WSOL_TOKEN_ACCOUNT'),
            'commitment': os.getenv('COMMITMENT') or cli_config.get('commitment', 'confirmed')
        }

        # Validate critical config
        missing = [k for k, v in self.config.items() if not v]
        if missing:
            raise ValueError(f"Missing required configuration: {', '.join(missing)}")

        # Components
        self.trading_core = trading_core
        self.impact_calculator = impact_calculator
        self.mempool_analyzer = mempool_analyzer
        
        # Connection state
        self.connection_state = {
            'active': False,
            'reconnect_attempts': 0,
            'max_reconnect_attempts': 10,
            'last_connection_time': 0,
            'backoff_time': 1.0
        }

        # Performance metrics
        self.metrics = {
            'messages_processed': 0,
            'opportunities_found': 0,
            'successful_trades': 0,
            'failed_trades': 0,
            'total_profit': Decimal('0'),
            'error_count': 0,
            'latency_stats': [],
            'last_trade_time': 0
        }

        # Transaction tracking
        self.recent_txs = set()
        self.tx_cache_size = 1000

        # Rate limits
        self.rate_limits = {
            'parse_tx': int(os.getenv('HELIUS_PARSE_TX_LIMIT')),
            'history': int(os.getenv('HELIUS_HISTORY_LIMIT')),
            'get_asset': int(os.getenv('HELIUS_ASSET_LIMIT'))
        }
        self.retry_delay = float(os.getenv('HELIUS_RETRY_DELAY'))
        
        logger.info(
            f"Helius client initialized - RPC: {self.config['rpc_url']}, "
            f"WS: {self.config['ws_url']}"
        )  
    async def start(self):
        """Start WebSocket client operations"""
        try:
            logger.info("Starting Helius WebSocket client...")
            
            # Use synchronous method directly
            initial_balance = self.trading_core.get_wsol_balance(self.config['wsol_account'])
            logger.info(f"Initial WSOL balance: {initial_balance} WSOL")

            if initial_balance < float(os.getenv('MIN_SOL_BALANCE', '0.04')):
                logger.warning(f"Low WSOL balance: {initial_balance} WSOL")

            await self.connect()
            
        except Exception as e:
            logger.error(f"Startup error: {e}")
            await self.cleanup()

    async def connect(self):
        """Establish and maintain WebSocket connection"""
        while (self.connection_state['reconnect_attempts'] < 
               self.connection_state['max_reconnect_attempts']):
            try:
                async with websockets.connect(
                    self.config['ws_url'],
                    ping_interval=30,
                    ping_timeout=10,
                    close_timeout=60,
                    extra_headers={
                        "Authorization": f"Bearer {self.config['api_key']}",
                        "Content-Type": "application/json"
                    },
                    max_size=16 * 1024 * 1024,
                    compression=None
                ) as websocket:
                    # Reset connection state
                    self.connection_state.update({
                        'active': True,
                        'reconnect_attempts': 0,
                        'last_connection_time': time.time(),
                        'backoff_time': 1.0
                    })

                    logger.info("WebSocket connection established.")

                    # Subscribe to program and accounts
                    await self._subscribe(websocket)

                    # Start processing messages
                    await self._process_messages(websocket)

            except websockets.exceptions.ConnectionClosed:
                logger.warning("WebSocket connection closed")
                await self._handle_disconnection()
            except Exception as e:
                logger.error(f"Connection error: {e}")
                await self._handle_disconnection()

        logger.error("Max reconnection attempts reached")
        self.connection_state['active'] = False

    async def _subscribe(self, websocket):
        """Set up program subscriptions"""
        try:
            # Program subscription
            program_sub = {
                "jsonrpc": "2.0",
                "id": 1,
                "method": "programSubscribe",
                "params": [
                    self.config['raydium_program_id'],
                    {
                        "encoding": "base64",
                        "commitment": "processed",
                        "filters": [
                            {
                                "memcmp": {
                                    "offset": 0,
                                    "bytes": "9"
                                }
                            }
                        ]
                    }
                ]
            }
            
            await websocket.send(json.dumps(program_sub))
            response = await websocket.recv()
            logger.info(f"Program subscription response: {response}")

            # Subscribe to specific pools
            await self._subscribe_to_pools(websocket)

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

    async def _subscribe_to_pools(self, websocket):
        """Subscribe to specific pools"""
        try:
            # Key pools to monitor
            pools = [
                os.getenv('SOL_WSOL_AMM_ID'),
                # Add other pools you want to monitor
            ]
            
            for pool in pools:
                pool_sub = {
                    "jsonrpc": "2.0",
                    "id": f"pool_{pool}",
                    "method": "accountSubscribe",
                    "params": [
                        pool,
                        {
                            "commitment": "processed",
                            "encoding": "base64"
                        }
                    ]
                }
                await websocket.send(json.dumps(pool_sub))
                response = await websocket.recv()
                logger.info(f"Pool subscription response: {response}")

        except Exception as e:
            logger.error(f"Error subscribing to pools: {e}")

    async def _process_messages(self, websocket):
        """Process incoming WebSocket messages with detailed logging"""
        console.print("[bold blue]Starting message processing...[/bold blue]")
        message_count = 0
        
        while self.connection_state['active']:
            try:
                message = await websocket.recv()
                message_count += 1
                
                # Log raw message for debugging
                console.print(f"[dim]Raw message received ({message_count}):[/dim]")
                console.print(message[:200] + "..." if len(message) > 200 else message)
                
                # Try to parse JSON
                data = json.loads(message)
                
                if "params" in data:
                    if "result" in data["params"]:
                        console.print("[green]✓ Valid transaction data received[/green]")
                    elif "subscription" in data:
                        console.print("[yellow]• Subscription message received[/yellow]")
                
                await self._handle_message(message)
                
            except websockets.exceptions.ConnectionClosed:
                console.print("[red]WebSocket connection closed[/red]")
                break
            except json.JSONDecodeError:
                console.print("[red]Failed to parse message as JSON[/red]")
            except Exception as e:
                console.print(f"[red]Error processing message: {e}[/red]")    
    async def _predict_block_time(self, tx_data):
        current_slot = self.get_slot()
        predicted_slot = current_slot + 2
        target_time = time.time() + 0.4  # Target 400ms ahead
        return target_time, predicted_slot
    
    def _calculate_multi_block_opportunity(self, mempool_data, blocks_ahead=2):
        profits = []
        for i in range(blocks_ahead):
            block_profit = self._simulate_position(mempool_data, i)
            profits.append((block_profit, i))
        return max(profits, key=lambda x: x[0])
    async def _handle_message(self, message):
        """Process incoming WebSocket message"""
        try:
            data = json.loads(message)
        
            # Ensure we have params and result
            if "params" not in data:
                return
            
            result = data["params"].get("result", {})
            if not result:
                return

            # Get raw transaction data
            tx_data = result.get("data")
            if not tx_data:
                return

            # Decode base64 data
            try:
                decoded_data = base64.b64decode(tx_data)
            except Exception as e:
                logger.error(f"Base64 decode error: {e}")
                return

            # Skip if we've seen this transaction
            tx_hash = base64.b64encode(decoded_data[:32]).decode()
            if tx_hash in self.recent_txs:
                return
            
            self.recent_txs.add(tx_hash)
            if len(self.recent_txs) > self.tx_cache_size:
                self.recent_txs.pop()

            # Process transaction
            start_time = time.perf_counter()

            # Calculate price impact
            impact = await self.impact_calculator.calculate_impact(decoded_data)
            if not impact or impact.price_impact > float(os.getenv('MAX_PRICE_IMPACT', '0.004')):
                return

            # Analyze mempool data
            analysis = await self.mempool_analyzer.analyze(
                decoded_data,
                impact.price_impact,
                impact.volume
            )

            if analysis.is_opportunity:
                logger.info(f"Found opportunity: {analysis.opportunity_type}")
                logger.info(f"Expected profit: {analysis.expected_profit:.6f} SOL")
            
                # Execute trade if profitable
                if analysis.expected_profit > float(os.getenv('MIN_PROFIT_PCT', '0.015')):
                    trade_params = TradeParams(
                        pool_address=impact.pool_address,
                        amount_in=max(0.0035, analysis.recommended_size),
                        min_amount_out=analysis.min_output_amount,
                        wsol_account=self.config['wsol_account']
                    )

                    result = self.trading_core.execute_trade(trade_params)
                    if result:
                        self.metrics['successful_trades'] += 1
                        self.metrics['total_profit'] += Decimal(str(analysis.expected_profit))
                        logger.info(f"Trade executed successfully: {result}")
                    else:
                        self.metrics['failed_trades'] += 1

            # Update metrics
            process_time = (time.perf_counter() - start_time) * 1000
            self.metrics['latency_stats'].append(process_time)

        except Exception as e:
            logger.error(f"Message handling error: {e}")
            self.metrics['error_count'] += 1

    async def cleanup(self):
        """Cleanup resources"""
        try:
            logger.info("Starting cleanup...")
            self.connection_state['active'] = False
            
            # Log final metrics
            await self._log_metrics()
            
            # Get final balance
            final_balance = self.trading_core.get_wsol_balance(self.config['wsol_account'])
            logger.info(f"Final WSOL balance: {final_balance} WSOL")
            
            logger.info("Cleanup completed")
            
        except Exception as e:
            logger.error(f"Cleanup error: {e}")

# Standalone testing entry point
if __name__ == "__main__":
    async def main():
        trading_core = TradingCore()
        client = HeliusWebSocketClient(
            trading_core, 
            EnhancedImpactCalculator(), 
            EnhancedMempoolAnalyzer(trading_core)
        )
        await client.start()

    asyncio.run(main())