please correct this script and add professional debug logging for me and try to make sure all my scripts work together as i send them okay ell fix one at a time . import asyncio
import base64
import json
import logging
import time
import websockets
from typing import Dict, List, Optional
from decimal import Decimal
import torch

from vector_store import EnhancedVectorStore
from price_impact import EnhancedImpactCalculator
from gpu_accelerator import GPUAccelerator
from solana_rust_bot import TradeParams

logger = logging.getLogger(__name__)

class AdvancedTrading:
    def __init__(self, trader, config):
        self.trader = trader
        self.config = config
        self.active = False
        self.metrics = {
            'messages_received': 0,
            'opportunities_found': 0,
            'successful_trades': 0,
            'total_profit': Decimal('0'),
            'start_time': time.time()
        }

    async def start_websocket_monitoring(self):
        """Start monitoring WebSocket for opportunities"""
        self.active = True
        logger.info("Starting advanced trading monitor...")
        
        while self.active:
            try:
                async with websockets.connect(
                    self.config['rpc']['helius']['websocket'],
                    ping_interval=30,
                    ping_timeout=10,
                    close_timeout=60,
                    max_size=16_777_216
                ) as ws:
                    # Subscribe to Raydium logs
                    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()
                        self.metrics['messages_received'] += 1
                        
                        await self._process_message(msg)
                        
                        # Log metrics every 100 messages
                        if self.metrics['messages_received'] % 100 == 0:
                            self._log_metrics()
                            
            except websockets.exceptions.ConnectionClosed:
                logger.warning("WebSocket connection closed. Reconnecting...")
                await asyncio.sleep(1)
            except Exception as e:
                logger.error(f"WebSocket error: {e}")
                await asyncio.sleep(1)

    async def _process_message(self, msg: str):
        """Process incoming WebSocket message"""
        try:
            data = json.loads(msg)
            if 'params' not in data:
                return

            logs = data['params'].get('result', {}).get('value', {}).get('logs', [])
            for log in logs:
                if "ray_log:" not in log:
                    continue

                raw_data = base64.b64decode(log.split('ray_log: ')[1].strip())
                self.metrics['opportunities_found'] += 1

                # Process with different strategies in parallel
                results = await asyncio.gather(
                    self._check_triangle_arbitrage(raw_data),
                    self._check_multi_hop_opportunity(raw_data),
                    self._check_direct_swap(raw_data),
                    return_exceptions=True
                )

                # Execute best opportunity if any
                valid_results = [r for r in results if isinstance(r, dict) and r.get('profit', 0) > 0]
                if valid_results:
                    best_opportunity = max(valid_results, key=lambda x: x['profit'])
                    await self._execute_opportunity(best_opportunity)

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

    async def _check_triangle_arbitrage(self, raw_data: bytes) -> Optional[Dict]:
        """Check for triangle arbitrage opportunities"""
        try:
            # Use vector store to find triangle paths
            paths = await self.trader.vector_store._find_triangle_paths(
                token_in=self.config['accounts']['sol_wsol']['base_mint'],
                token_out=self.config['accounts']['sol_wsol']['quote_mint'],
                intermediates=await self.trader.trading_core.get_token_pools(
                    self.config['accounts']['sol_wsol']['base_mint'],
                    self.config['accounts']['sol_wsol']['quote_mint']
                ).intermediate_tokens
            )

            best_profit = 0
            best_path = None
            
            for path in paths:
                # Calculate total impact and profit
                total_impact, amounts = await self.trader.impact_calculator.calculate_multi_hop_impact(
                    0.1,  # Start with 0.1 SOL
                    path
                )
                
                if total_impact < self.config['trading']['limits']['max_price_impact']:
                    profit = (amounts[-1] - amounts[0]) / amounts[0] * 100
                    if profit > best_profit:
                        best_profit = profit
                        best_path = path

            if best_path and best_profit >= self.config['trading']['limits']['min_profit_pct']:
                return {
                    'type': 'triangle',
                    'profit': best_profit,
                    'path': best_path,
                    'amount_in': 0.1  # Can be adjusted based on liquidity
                }

            return None

        except Exception as e:
            logger.error(f"Triangle arbitrage error: {e}")
            return None

    async def _check_multi_hop_opportunity(self, raw_data: bytes) -> Optional[Dict]:
        """Check for multi-hop trading opportunities"""
        try:
            # Find viable paths between tokens
            token_pools = await self.trader.trading_core.get_token_pools(
                self.config['accounts']['sol_wsol']['base_mint'],
                self.config['accounts']['sol_wsol']['quote_mint']
            )

            # Find optimal route
            route = await self.trader.impact_calculator.optimize_route(
                0.1,  # Initial amount
                self.config['accounts']['sol_wsol']['base_mint'],
                self.config['accounts']['sol_wsol']['quote_mint']
            )

            if route and route['impact'] <= self.config['trading']['limits']['max_price_impact']:
                return {
                    'type': 'multi_hop',
                    'profit': route['profit'],
                    'path': route['path'],
                    'amount_in': 0.1
                }

            return None

        except Exception as e:
            logger.error(f"Multi-hop check error: {e}")
            return None

    async def _check_direct_swap(self, raw_data: bytes) -> Optional[Dict]:
        """Check for direct swap opportunities"""
        try:
            opportunity = await self.trader.gpu_accelerator.analyze_opportunity(raw_data)
            if opportunity and opportunity['profit'] >= self.config['trading']['limits']['min_profit_pct']:
                return {
                    'type': 'direct',
                    'profit': opportunity['profit'],
                    'amount_in': opportunity['amount_in'],
                    'amount_out': opportunity['amount_out']
                }
            return None
        except Exception as e:
            logger.error(f"Direct swap check error: {e}")
            return None

    async def _execute_opportunity(self, opportunity: Dict):
        """Execute trading opportunity"""
        try:
            if opportunity['type'] == 'triangle':
                result = await self._execute_triangle_trade(opportunity)
            elif opportunity['type'] == 'multi_hop':
                result = await self._execute_multi_hop_trade(opportunity)
            else:  # direct swap
                result = await self._execute_direct_trade(opportunity)

            if result:
                self.metrics['successful_trades'] += 1
                self.metrics['total_profit'] += Decimal(str(opportunity['profit']))
                logger.info(f"""
Trade executed successfully:
Type: {opportunity['type']}
Profit: {opportunity['profit']:.4f}%
Total Profit: {float(self.metrics['total_profit']):.6f} SOL
Total Trades: {self.metrics['successful_trades']}
                """)

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

    async def _execute_triangle_trade(self, opportunity: Dict) -> bool:
        """Execute triangle arbitrage trade"""
        try:
            # Create trade parameters for each hop
            trades = []
            for i in range(len(opportunity['path'])):
                trades.append(TradeParams(
                    pool_address=opportunity['path'][i],
                    amount_in=opportunity['amount_in'] if i == 0 else None,  # Only set for first hop
                    min_amount_out=0  # Will be calculated based on simulation
                ))

            # Execute trades
            for trade in trades:
                result = await self.trader.trading_core.execute_trade(trade)
                if not result:
                    return False
                await asyncio.sleep(0.1)  # Small delay between hops

            return True

        except Exception as e:
            logger.error(f"Triangle trade execution error: {e}")
            return False

    async def _execute_multi_hop_trade(self, opportunity: Dict) -> bool:
        """Execute multi-hop trade"""
        try:
            for i, pool in enumerate(opportunity['path']):
                params = TradeParams(
                    pool_address=pool,
                    amount_in=opportunity['amount_in'] if i == 0 else None,
                    min_amount_out=0  # Will be calculated
                )
                result = await self.trader.trading_core.execute_trade(params)
                if not result:
                    return False
                await asyncio.sleep(0.1)

            return True

        except Exception as e:
            logger.error(f"Multi-hop execution error: {e}")
            return False

    async def _execute_direct_trade(self, opportunity: Dict) -> bool:
        """Execute direct swap"""
        try:
            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.config['execution']['slippage']))
            )
            return await self.trader.trading_core.execute_trade(params)

        except Exception as e:
            logger.error(f"Direct trade execution error: {e}")
            return False

    def _log_metrics(self):
        """Log performance metrics"""
        elapsed_time = time.time() - self.metrics['start_time']
        messages_per_second = self.metrics['messages_received'] / elapsed_time
        opportunities_per_minute = (self.metrics['opportunities_found'] / elapsed_time) * 60
        trades_per_minute = (self.metrics['successful_trades'] / elapsed_time) * 60

        logger.info(f"""
Performance Metrics:
Messages/sec: {messages_per_second:.2f}
Opportunities/min: {opportunities_per_minute:.2f}
Trades/min: {trades_per_minute:.2f}
Total Messages: {self.metrics['messages_received']}
Total Opportunities: {self.metrics['opportunities_found']}
Successful Trades: {self.metrics['successful_trades']}
Total Profit: {float(self.metrics['total_profit']):.6f} SOL
        """)

    async def stop(self):
        """Stop advanced trading"""
        self.active = False
        logger.info("Advanced trading stopped.") 
        
        
        
        
        
        
        object builtins.TokenPools can't be used in 'await' expression:
        # In advanced_trading.py, modify get_token_pools call:
token_pools = await self.trader.trading_core.get_token_pools(
    self.config['accounts']['sol_wsol']['base_mint'],
    self.config['accounts']['sol_wsol']['quote_mint']
)
intermediate_tokens = token_pools.intermediate_tokens  # Access directly, no await