hello i need assistance please my eyes are going very bad i have health issue with my eyes i need u to please remove redundant code and fix spacing please for me thank you and just provide me the full script back with all the code its to hard for me to see very well enough to make many edits if u can do for me ? just put the whole code back to me with only properly removing redudant and fix space please! import sys
import asyncio
import logging
import yaml
import json
import time
from datetime import datetime
from pathlib import Path
import numpy as np
import pandas as pd
from groq import Groq
import websockets
import base64
from solana_rust_bot import RaydiumTrader
from gui import QuantumGUI
from PyQt6.QtWidgets import QApplication

class Config:
    # Marga Fast Mainnet Settings
    HELIUS_WS = 'wss://marga-e56m84-fast-mainnet.helius-rpc.com/'
    HELIUS_RPC = 'https://marga-e56m84-fast-mainnet.helius-rpc.com'
    MAX_TPS = 5  # Marga fast mainnet total TPS
    
    # Priority Settings
    PRIORITY_LEVELS = {
        'SNIPE': {
            'tps': 2,        # 2 TPS reserved for sniping
            'priority_fee': 15000,
            'retry_delay_ms': 5,  # 5ms between retries
            'max_retries': 3
        },
        'SCALP': {
            'tps': 3,        # 3 TPS for scalping
            'priority_fee': 10000,
            'retry_delay_ms': 10  # 10ms between retries
        }
    }

class QuantumBeast:
    def __init__(self):
        self.load_config()
        self.setup_logging()
        self.trader = RaydiumTrader(str(Path("id.json").absolute()))
        self.groq = Groq(api_key=self.config['groq']['api_key'])
        
        self.pending_pools = {}
        self.target_pools = {}
        self.successful_snipes = 0
        self.execution_window = 0.025  # 25ms window for execution
        self.pool_cache = set()  # Track seen pools
        
        # Initialize GUI
        self.app = QApplication(sys.argv)
        self.gui = QuantumGUI()
        
        # Trading state
        self.active_trades = {}
        self.sniper_trades = {}
        self.market_data = []
        
        # Performance tracking
        self.performance_data = {
            'trades': [],
            'pnl': 0.0,
            'win_rate': 0.0
        }
        
        self.trading_enabled = True
        self.sniper_enabled = True
        
        logger.info('💫 Quantum Beast Online')

    def load_config(self):
        config_path = Path("src/python/config.yaml")
        with open(config_path, 'r') as f:
            self.config = yaml.safe_load(f)

    def setup_logging(self):
        global logger
        log_dir = Path("logs")
        log_dir.mkdir(exist_ok=True)
        
        # Setup main logger
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s [%(levelname)s] 🚀 %(message)s',
            handlers=[
                logging.FileHandler(log_dir / "trading.log"),
                logging.StreamHandler()
            ]
        )
        logger = logging.getLogger('QuantumBeast')
        
        # Setup performance logger
        perf_logger = logging.getLogger('Performance')
        perf_logger.addHandler(logging.FileHandler(log_dir / "performance.log"))
        
        # Setup Groq insights logger
        groq_logger = logging.getLogger('GroqInsights')
        groq_logger.addHandler(logging.FileHandler(log_dir / "groq_insights.log"))
    
    def analyze_pool_data(self, raw_data):
        """Analyze new pool data for sniping opportunities"""
        try:
            base = int.from_bytes(raw_data[8:16], 'little')
            quote = int.from_bytes(raw_data[16:24], 'little')
            
            if base > 0 and quote > 0:
                price = quote / base
                liquidity_usd = (quote * price) / 1e9
                
                # Extract mint authority and liquidity lock status
                # Offset 200-208 typically contains mint authority info
                mint_auth = int.from_bytes(raw_data[200:208], 'little')
                # Offset 208-216 typically contains liquidity lock info
                liq_lock = int.from_bytes(raw_data[208:216], 'little')
                
                return {
                    'price': price,
                    'liquidity_usd': liquidity_usd,
                    'mint_authority_revoked': mint_auth == 0,
                    'liquidity_locked': liq_lock / 1e9,
                    'base': base,
                    'quote': quote,
                    'detection_time': time.time()
                }
                
        except Exception as e:
            logger.error(f"Pool analysis error: {e}")
            return None

    async def execute_snipe(self, pool_address, pool_info):
        """Execute precision-timed snipe"""
        for attempt in range(Config.PRIORITY_LEVELS['SNIPE']['max_retries']):
            try:
                # Verify pool still meets criteria
                if await self.validate_timing(pool_address, pool_info):
                    signature = self.trader.execute_trade(
                        "BUY",
                        pool_info['price'],
                        priority_fee=Config.PRIORITY_LEVELS['SNIPE']['priority_fee']
                    )
                    
                    if signature:
                        execution_time = time.time() - pool_info['detection_time']
                        logger.info(f"⚡ Snipe success: {pool_address} in {execution_time*1000:.2f}ms")
                        self.successful_snipes += 1
                        self.gui.add_trade_marker(pool_info['price'], True, is_snipe=True)
                        return signature
                        
                await asyncio.sleep(Config.PRIORITY_LEVELS['SNIPE']['retry_delay_ms'] / 1000)
                
            except Exception as e:
                logger.error(f"Snipe attempt {attempt + 1} failed: {e}")
                
        logger.warning(f"❌ Failed to snipe {pool_address} after {Config.PRIORITY_LEVELS['SNIPE']['max_retries']} attempts")
        return None

    async def validate_timing(self, pool_address, pool_info):
        """Validate perfect entry timing"""
        try:
            current_time = time.time()
            detection_age = current_time - pool_info['detection_time']
            
            # Check if we're in the optimal window (25ms)
            if detection_age > self.execution_window:
                return False
                
            # Quick final check of pool state
            if pool_info['liquidity_locked'] >= 0.95 and pool_info['mint_authority_revoked']:
                return True
                
            return False
            
        except Exception as e:
            logger.error(f"Timing validation error: {e}")
            return False

    async def process_sniper_data(self, pool_address, raw_data):
        """Enhanced sniper data processing"""
        try:
            # Skip if we've seen this pool
            if pool_address in self.pool_cache:
                return
                
            self.pool_cache.add(pool_address)
            pool_info = self.analyze_pool_data(raw_data)
            
            if pool_info and await self.validate_timing(pool_address, pool_info):
                await self.execute_snipe(pool_address, pool_info)
                
        except Exception as e:
            logger.error(f"Sniper processing error: {e}")
    async def monitor_raydium_pools(self):
        """Monitor Raydium pools for both trading and sniping"""
        while True:
            try:
                async with websockets.connect(self.config['helius']['ws_endpoint']) as ws:
                    await ws.send(json.dumps({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "method": "programSubscribe",
                        "params": [
                            "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
                            {"encoding": "base64", "commitment": "confirmed"}
                        ]
                    }))
                    
                    while True:
                        msg = await ws.recv()
                        data = json.loads(msg)
                        
                        if 'params' in data and 'result' in data['params']:
                            result = data['params']['result']['value']
                            pool_address = result['pubkey']
                            raw_data = base64.b64decode(result['account']['data'][0])
                            
                            # Process for trading system
                            if self.trading_enabled:
                                await self.process_trading_data(pool_address, raw_data)
                            
                            # Process for sniper system
                            if self.sniper_enabled:
                                await self.process_sniper_data(pool_address, raw_data)
                                
                        await asyncio.sleep(0.01)  # Small delay to prevent CPU overload
                        
            except Exception as e:
                logger.error(f"Pool monitoring error: {e}")
                await asyncio.sleep(1)

    async def process_trading_data(self, pool_address, raw_data):
        """Process data for main trading system"""
        try:
            # Parse pool data
            base = int.from_bytes(raw_data[8:16], 'little')
            quote = int.from_bytes(raw_data[16:24], 'little')
            
            if base > 0 and quote > 0:
                price = quote / base
                volume = (quote * price) / 1e9
                
                # Update market data
                self.market_data.append({
                    'timestamp': datetime.now(),
                    'price': price,
                    'volume': volume
                })
                
                # Keep last 1000 data points
                if len(self.market_data) > 1000:
                    self.market_data.pop(0)
                
                # Update GUI
                self.gui.update_price_chart(
                    [d['price'] for d in self.market_data],
                    [d['volume'] for d in self.market_data]
                )
                
                # Analyze trading opportunity
                if await self.analyze_trading_opportunity(price, volume):
                    await self.execute_trade(price)
                
        except Exception as e:
            logger.error(f"Trading data processing error: {e}")

    async def analyze_trading_opportunity(self, price, volume):
        """Analyze if we should trade based on current conditions"""
        try:
            if len(self.market_data) < 20:
                return False
                
            # Calculate indicators
            prices = pd.Series([d['price'] for d in self.market_data])
            volumes = pd.Series([d['volume'] for d in self.market_data])
            
            # Get Groq analysis
            analysis = await self.get_groq_insight({
                'price': float(price),
                'volume': float(volume),
                'price_history': prices.tolist()[-20:],
                'volume_history': volumes.tolist()[-20:]
            })
            
            return analysis.get('should_trade', False)
            
        except Exception as e:
            logger.error(f"Analysis error: {e}")
            return False

    async def get_groq_insight(self, data):
        """Get trading insight from Groq"""
        try:
            prompt = f"""
            Analyze this market data and provide trading signal:
            Current Price: ${data['price']:.4f}
            Volume: ${data['volume']:.2f}M
            Recent Price Trend: {data['price_history'][-5:]}
            Recent Volume Trend: {data['volume_history'][-5:]}
            
            Provide specific trading advice with confidence level.
            """
            
            response = await asyncio.get_event_loop().run_in_executor(
                None,
                lambda: self.groq.chat.completions.create(
                    messages=[{'role': 'user', 'content': prompt}],
                    model='mixtral-8x7b-32768'
                )
            )
            
            # Parse response
            analysis = response.choices[0].message.content.lower()
            return {
                'should_trade': 'buy' in analysis or 'sell' in analysis,
                'confidence': 0.8 if 'high confidence' in analysis else 0.6,
                'action': 'BUY' if 'buy' in analysis else 'SELL'
            }
            
        except Exception as e:
            logger.error(f"Groq analysis error: {e}")
            return {}

    async def execute_trade(self, price):
        """Execute scalp trade with Marga priority"""
        try:
            signature = self.trader.execute_trade(
                "BUY",
                price,
                priority_fee=Config.PRIORITY_LEVELS['SCALP']['priority_fee']
            )
            
            if signature:
                self.total_trades += 1
                logger.info(f"💫 Marga Fast Trade at ${price:.4f}")
                self.gui.add_trade_marker(price, True)
                
        except Exception as e:
            logger.error(f"Trade execution error: {e}")

    def validate_sniper_opportunity(self, pool_info):
        """Validate if pool meets sniper criteria"""
        return (
            pool_info['mint_authority_revoked'] and
            pool_info['liquidity_locked'] >= 0.95 and
            500 <= pool_info['liquidity_usd'] <= 10000
        )
    
    async def monitor_active_trades(self):
    """Monitor and manage all active trades"""
    while True:
        try:
            # Monitor snipe positions
            for pool_address, trade in list(self.sniper_trades.items()):
                current_price = trade.get('entry_price', 0)
                entry_price = trade.get('entry_price', 0)
                
                # Calculate P&L
                pnl_percent = (current_price - entry_price) / entry_price
                
                # Take profit at 30%
                if pnl_percent >= 0.30:
                    await self.execute_exit(pool_address, current_price, "TAKE_PROFIT", True)
                    
                # Stop loss at 5%
                elif pnl_percent <= -0.05:
                    await self.execute_exit(pool_address, current_price, "STOP_LOSS", True)
            
            # Monitor scalp positions
            for trade_id, trade in list(self.active_trades.items()):
                if trade['action'] == 'BUY':
                    profit_target = trade['entry_price'] * 1.05  # 5% profit
                    stop_loss = trade['entry_price'] * 0.98     # 2% loss
                    
                    current_price = self.market_data[-1]['price'] if self.market_data else trade['entry_price']
                    
                    if current_price >= profit_target:
                        await self.execute_exit(trade_id, current_price, "TAKE_PROFIT", False)
                    elif current_price <= stop_loss:
                        await self.execute_exit(trade_id, current_price, "STOP_LOSS", False)
            
            await asyncio.sleep(0.1)  # Fast monitoring
            
        except Exception as e:
            logger.error(f"Trade monitoring error: {e}")
            await asyncio.sleep(1)

async def execute_exit(self, trade_id, current_price, reason, is_snipe=False):
    """Execute position exit"""
    try:
        trade_data = self.sniper_trades[trade_id] if is_snipe else self.active_trades[trade_id]
        entry_price = trade_data['entry_price']
        
        # Calculate P&L
        pnl = (current_price - entry_price) / entry_price
        
        # Execute sell with appropriate priority
        signature = self.trader.execute_trade(
            "SELL",
            current_price,
            priority_fee=Config.PRIORITY_LEVELS['SNIPE' if is_snipe else 'SCALP']['priority_fee']
        )
        
        if signature:
            # Log trade result
            logger.info(f"{'🎯 Snipe' if is_snipe else '💫 Scalp'} {reason}: {pnl*100:.1f}% profit")
            
            # Update performance tracking
            self.performance_data['trades'].append({
                'type': 'SNIPE' if is_snipe else 'SCALP',
                'entry_price': entry_price,
                'exit_price': current_price,
                'pnl': pnl,
                'reason': reason,
                'timestamp': datetime.now()
            })
            
            # Update GUI
            self.gui.add_trade_marker(current_price, False, is_snipe)
            
            # Remove from active trades
            if is_snipe:
                del self.sniper_trades[trade_id]
            else:
                del self.active_trades[trade_id]
            
            # Save performance data
            self.save_performance_data()
            
    except Exception as e:
        logger.error(f"Exit execution error: {e}")

async def monitor_pool_creation(self):
    """Monitor for new pool creation and validate opportunities"""
    pool_creation_cache = {}
    
    while True:
        try:
            current_time = time.time()
            
            # Clean old cache entries
            pool_creation_cache = {k: v for k, v in pool_creation_cache.items()
                                 if current_time - v['timestamp'] < 60}  # Keep 60s history
            
            # Process pool cache
            for pool_address, data in pool_creation_cache.items():
                # Skip if we've already acted on this pool
                if data.get('processed'):
                    continue
                
                # Check if pool is ready for trading
                if await self.validate_pool_readiness(pool_address, data):
                    pool_info = self.analyze_pool_data(data['raw_data'])
                    
                    if pool_info and self.validate_sniper_opportunity(pool_info):
                        await self.execute_snipe(pool_address, pool_info)
                        data['processed'] = True
                        
            await asyncio.sleep(0.001)  # Ultra-fast monitoring
            
        except Exception as e:
            logger.error(f"Pool creation monitoring error: {e}")
            await asyncio.sleep(1)

async def validate_pool_readiness(self, pool_address, data):
    """Validate if pool is ready for trading"""
    try:
        # Check creation time
        if time.time() - data['timestamp'] > 60:  # Too old
            return False
            
        # Verify liquidity
        raw_data = data['raw_data']
        base = int.from_bytes(raw_data[8:16], 'little')
        quote = int.from_bytes(raw_data[16:24], 'little')
        
        if base == 0 or quote == 0:
            return False
            
        # Quick final validation
        pool_info = self.analyze_pool_data(raw_data)
        if not pool_info:
            return False
            
        return (
            pool_info['mint_authority_revoked'] and
            pool_info['liquidity_locked'] >= 0.95 and
            500 <= pool_info['liquidity_usd'] <= 10000
        )
        
    except Exception as e:
        logger.error(f"Pool readiness validation error: {e}")
        return False

# Add this to your run method:
async def run(self):
    """Main run loop"""
    self.gui.show()
    try:
        # Start monitoring tasks
        await asyncio.gather(
            self.monitor_raydium_pools(),
            self.monitor_active_trades(),
            self.monitor_pool_creation()
        )
    except Exception as e:
        logger.error(f"Fatal error: {e}")
    finally:
        self.save_performance_data()

    def save_performance_data(self):
        """Save performance data to CSV"""
        try:
            df = pd.DataFrame(self.performance_data['trades'])
            df.to_csv(Path("data/performance.csv"), index=False)
        except Exception as e:
            logger.error(f"Error saving performance data: {e}")

if __name__ == "__main__":
    beast = QuantumBeast()
    
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(beast.run())
    except KeyboardInterrupt:
        logger.info("Shutting down gracefully...")
    finally:
        loop.close()