can you create the best pyqt6 gui dash control station for my rust project its going to be pyo3 operated by my cuda 12.4 python its downloaded from anaconda pytorch or w/e so it might need to use tensorflow ? can u provide me the perfect blend of useful tools and functional buttons and tabs widgets and data information rich and appealing smooth and error resistant and userfriendly with all the requirements a professional grade gui would have  heres the rust script that the pyo3 will be controling from the gui pyqt6 using cuda 12.4 python 3.12.3 use anyhow::{anyhow, Result};
use dashmap::DashMap;
use futures_util::{StreamExt, SinkExt};
use log::{error, info, warn};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::{
    cmp::min,
    path::PathBuf,
    sync::Arc,
    time::{Duration, Instant, SystemTime},
};
use tokio::{fs::File, io::{AsyncReadExt, AsyncWriteExt}, sync::{broadcast, Mutex}};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use url::Url;

// Configuration Constants
const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com/";
const WALLET_PUBLIC_KEY: &str = "EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA";
const HELIUS_API_KEY: &str = "1ea5843b-9daa-4926-a97a-be021922da2f";
const SOL_MINT: &str = "So11111111111111111111111111111111111111112";

// Trading Parameters - Carefully tuned for optimal performance
const MIN_SUPPLY: u64 = 900_000_000;       // Minimum token supply
const LIQUIDITY_MIN: f64 = 4.0;            // Minimum liquidity in SOL (~1000 USD)
const LIQUIDITY_MAX: f64 = 50.0;           // Maximum liquidity in SOL (~20000 USD)
const TRADE_AMOUNT: u64 = 10_000_000;       // Trade size
const MAX_TRADES: usize = 5;               // Maximum concurrent trades
const TAKE_PROFIT: f64 = 20.0;            // Take profit percentage
const STOP_LOSS: f64 = -5.0;              // Stop loss percentage
const MAX_RETRIES: u32 = 3;               // Maximum retry attempts for trades
const RETRY_DELAY: Duration = Duration::from_secs(0.01); // Delay between retries
const STATE_SAVE_INTERVAL: Duration = Duration::from_secs(300); // Save state every 5 minutes

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TradeState {
    token_mint: String,
    entry_price: f64,
    amount: u64,
    timestamp: u64,
    last_price: f64,
    success_count: u32,
    profit_loss: f64,
}

#[derive(Debug, Clone)]
struct ActiveTrade {
    token_mint: String,
    entry_price: f64,
    amount: u64,
    start_time: Instant,
    last_price: Arc<Mutex<f64>>,
    success_count: u32,
    profit_loss: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SystemMetrics {
    total_trades: u32,
    successful_trades: u32,
    failed_trades: u32,
    total_profit_loss: f64,
    start_time: u64,
    last_restart: u64,
}

#[derive(Debug, Clone)]
struct TradingSystem {
    active_trades: DashMap<String, ActiveTrade>,
    last_prices: DashMap<String, f64>,
    known_tokens: DashMap<String, Instant>,
    metrics: Arc<Mutex<SystemMetrics>>,
    state_file: PathBuf,
    metrics_file: PathBuf,
    shutdown_signal: broadcast::Sender<()>,
}

// Trade validation result with detailed reason
#[derive(Debug)]
enum ValidationResult {
    Valid,
    Invalid(String),
    Error(String),
}
// Add these new structures to match the JSON format
#[derive(Debug, Clone, Serialize, Deserialize)]
struct KnownToken {
    mint: String,
    last_seen: u64,
    reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct LastPrice {
    mint: String,
    price: f64,
    last_update: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SystemInfo {
    uptime_seconds: u64,
    active_trades_count: usize,
    known_tokens_count: usize,
    tracked_prices_count: usize,
    last_save: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RejectedStats {
    low_supply: u32,
    low_liquidity: u32,
    invalid_attributes: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ValidationStats {
    tokens_seen: u32,
    tokens_validated: u32,
    tokens_rejected: RejectedStats,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TradingParameters {
    min_supply: u64,
    liquidity_min: f64,
    liquidity_max: f64,
    trade_amount: u64,
    max_trades: usize,
    take_profit: f64,
    stop_loss: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct CompleteState {
    active_trades: Vec<TradeState>,
    known_tokens: Vec<KnownToken>,
    metrics: SystemMetrics,
    last_prices: Vec<LastPrice>,
    system_info: SystemInfo,
    validation_stats: ValidationStats,
    trading_parameters: TradingParameters,
}
// Custom error type for better error handling
#[derive(Debug, thiserror::Error)]
enum TradeError {
    #[error("Invalid token data: {0}")]
    InvalidToken(String),
    
    #[error("Trading error: {0}")]
    TradingError(String),
    
    #[error("Network error: {0}")]
    NetworkError(String),
    
    #[error("State error: {0}")]
    StateError(String),
}
// Core Helper Functions
async fn get_quote(input_mint: &str, output_mint: &str, amount: u64) -> Result<Value> {
    let url = format!(
        "{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50&onlyDirectRoutes=true&wrapUnwrapSOL=true",
        JUPITER_API, input_mint, output_mint, amount
    );
    
    match reqwest::get(&url).await {
        Ok(response) => {
            match response.json::<Value>().await {
                Ok(quote) => {
                    info!("💫 Quote received successfully for {} -> {}", input_mint, output_mint);
                    Ok(quote)
                },
                Err(e) => {
                    warn!("Failed to parse quote response: {}", e);
                    Err(anyhow!("Quote parsing error: {}", e))
                }
            }
        },
        Err(e) => {
            error!("Failed to get quote: {}", e);
            Err(anyhow!("Quote request failed: {}", e))
        }
    }
}

async fn get_swap_data(quote: Value) -> Result<String> {
    let swap_request = json!({
        "quoteResponse": quote,
        "userPublicKey": WALLET_PUBLIC_KEY,
        "wrapUnwrapSOL": true,
        "computeUnitPriceMicroLamports": 15000,
        "priorityFeeLamports": 15000,
        "asLegacyTransaction": false,
        "maxAccounts": 64,
        "verifyWallet": true
    });

    let client = reqwest::Client::new();
    match client.post(format!("{}/swap", JUPITER_API))
        .json(&swap_request)
        .send()
        .await 
    {
        Ok(response) => {
            match response.json::<Value>().await {
                Ok(data) => {
                    if let Some(error) = data.get("error") {
                        if error.as_str().unwrap_or("").contains("Market") {
                            info!("🔄 Market setup in progress, waiting...");
                            return Ok("retry".to_string());
                        }
                        return Err(anyhow!("Swap error: {}", error));
                    }

                    match data.get("swapTransaction") {
                        Some(tx) => Ok(tx.as_str()
                            .ok_or_else(|| anyhow!("Invalid transaction format"))?
                            .to_string()),
                        None => Ok("retry".to_string())
                    }
                },
                Err(e) => Err(anyhow!("Failed to parse swap response: {}", e))
            }
        },
        Err(e) => Err(anyhow!("Swap request failed: {}", e))
    }
}

async fn send_priority_tx(swap_data: String) -> Result<String> {
    // Skip if we got a retry signal
    if swap_data == "retry" {
        return Ok("waiting_for_market".to_string());
    }

    let helius_request = json!({
        "jsonrpc": "2.0",
        "id": "helius-priority",
        "method": "sendTransaction",
        "params": [
            swap_data,
            {
                "encoding": "base64",
                "maxRetries": 0,
                "skipPreflight": true,
                "preflightCommitment": "processed",
                "priorityFee": 15000
            }
        ]
    });

    let client = reqwest::Client::new();
    match client.post(HELIUS_RPC)
        .header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
        .json(&helius_request)
        .send()
        .await 
    {
        Ok(response) => {
            match response.json::<Value>().await {
                Ok(data) => {
                    match data.get("result") {
                        Some(result) => Ok(result.as_str()
                            .ok_or_else(|| anyhow!("Invalid result format"))?
                            .to_string()),
                        None => {
                            if let Some(error) = data.get("error") {
                                error!("Transaction error: {:?}", error);
                                Err(anyhow!("Transaction failed: {:?}", error))
                            } else {
                                Ok("transaction_pending".to_string())
                            }
                        }
                    }
                },
                Err(e) => Err(anyhow!("Failed to parse transaction response: {}", e))
            }
        },
        Err(e) => Err(anyhow!("Transaction request failed: {}", e))
    }
}

impl TradingSystem {
    fn new() -> Self {
        let (shutdown_tx, _) = broadcast::channel(1);
        info!("🔧 Initializing trading system...");
        
        let system = Self {
            active_trades: DashMap::new(),
            last_prices: DashMap::new(),
            known_tokens: DashMap::new(),
            metrics: Arc::new(Mutex::new(SystemMetrics {
                total_trades: 0,
                successful_trades: 0,
                failed_trades: 0,
                total_profit_loss: 0.0,
                start_time: SystemTime::now()
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
                last_restart: SystemTime::now()
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .unwrap()
                    .as_secs(),
            })),
            state_file: PathBuf::from("trading_state.json"),
            metrics_file: PathBuf::from("system_metrics.json"),
            shutdown_signal: shutdown_tx,
        };

        info!("✅ Trading system initialized successfully");
        info!("📊 Max concurrent trades: {}", MAX_TRADES);
        info!("💰 Trade amount: {} lamports", TRADE_AMOUNT);
        info!("📈 Take profit: {}%", TAKE_PROFIT);
        info!("📉 Stop loss: {}%", STOP_LOSS);

        system
    }

    async fn check_liquidity_and_price(&self, token_mint: &str) -> Result<(f64, f64)> {
        let start = Instant::now();
        let quote = get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
        
        let in_amount = quote["inAmount"].as_str()
            .ok_or_else(|| anyhow!("Invalid input amount"))?
            .parse::<f64>()? / 1e9;
            
        let out_amount = quote["outAmount"].as_str()
            .ok_or_else(|| anyhow!("Invalid output amount"))?
            .parse::<f64>()?;
            
        let price = in_amount / out_amount;
        let liquidity = in_amount * price;

        info!("💧 Liquidity check completed in {:?}: {} SOL", start.elapsed(), liquidity);
        Ok((liquidity, price))
    }
    async fn validate_new_token(&self, token_data: &Value) -> Result<ValidationResult> {
        // First check if we have account data
        let account = match token_data.get("value").and_then(|v| v.get("account")) {
            Some(acc) => acc,
            None => {
                return Ok(ValidationResult::Invalid("Invalid token data structure".to_string()));
            }
        };

        // Get the token mint from pubkey field
        let token_mint = match token_data.get("value").and_then(|v| v.get("pubkey")).and_then(|p| p.as_str()) {
            Some(mint) => mint,
            None => {
                return Ok(ValidationResult::Invalid("Missing mint address".to_string()));
            }
        };

        // Only log for new tokens we haven't seen
        if !self.known_tokens.contains_key(token_mint) {
            info!("🔍 Validating new token: {}", token_mint);
        }

        // Check if we're already tracking this token
        if self.known_tokens.contains_key(token_mint) {
            return Ok(ValidationResult::Invalid("Token already known".to_string()));
        }

        if self.active_trades.contains_key(token_mint) {
            return Ok(ValidationResult::Invalid("Already trading this token".to_string()));
        }

        // Extract and validate token data
        let mint_data = match account
            .get("data")
            .and_then(|d| d.get("parsed"))
            .and_then(|p| p.get("info"))
        {
            Some(data) => data,
            None => {
                self.known_tokens.insert(token_mint.to_string(), Instant::now());
                return Ok(ValidationResult::Invalid("Invalid token data structure".to_string()));
            }
        };

        // Check token attributes
        let mint_authority_null = mint_data["mintAuthority"].is_null();
        let freeze_authority_null = mint_data["freezeAuthority"].is_null();

        if !mint_authority_null || !freeze_authority_null {
            self.known_tokens.insert(token_mint.to_string(), Instant::now());
            return Ok(ValidationResult::Invalid("Token not properly locked".to_string()));
        }

        // Check supply
        let supply = mint_data["supply"].as_str()
            .unwrap_or("0")
            .parse::<u64>()?;

        if supply < MIN_SUPPLY {
            self.known_tokens.insert(token_mint.to_string(), Instant::now());
            return Ok(ValidationResult::Invalid(format!("Supply too low: {} < {}", supply, MIN_SUPPLY)));
        }

        // Check liquidity and price
        match self.check_liquidity_and_price(token_mint).await {
            Ok((liquidity, price)) => {
                info!("💧 Token {} - Liquidity: {} SOL, Price: {} SOL", token_mint, liquidity, price);
                
                if !(LIQUIDITY_MIN..=LIQUIDITY_MAX).contains(&liquidity) {
                    self.known_tokens.insert(token_mint.to_string(), Instant::now());
                    return Ok(ValidationResult::Invalid(format!("Liquidity outside range: {} SOL", liquidity)));
                }

                info!("✅ Found valid token! Mint: {}", token_mint);
                info!("   Supply: {}", supply);
                info!("   Liquidity: {} SOL", liquidity);
                info!("   Price: {} SOL", price);

                self.last_prices.insert(token_mint.to_string(), price);
            }
            Err(e) => {
                self.known_tokens.insert(token_mint.to_string(), Instant::now());
                return Ok(ValidationResult::Error(format!("Failed to check liquidity: {}", e)));
            }
        }

        Ok(ValidationResult::Valid)
    }


    async fn monitor_trades(&self) -> Result<()> {
        info!("👀 Starting trade monitor...");
        let mut interval = tokio::time::interval(Duration::from_secs(1));
        let mut save_interval = tokio::time::interval(STATE_SAVE_INTERVAL);
        let mut shutdown_rx = self.shutdown_signal.subscribe();

        loop {
            tokio::select! {
                _ = interval.tick() => {
                    for trade in self.active_trades.iter() {
                        let token_mint = &trade.token_mint;
                        let trade_duration = trade.start_time.elapsed();
                        
                        match self.check_liquidity_and_price(token_mint).await {
                            Ok((liquidity, current_price)) => {
                                // Update last price using async lock
                                if let Ok(mut last_price) = trade.last_price.try_lock() {
                                    *last_price = current_price;
                                }

                                let profit_percent = (current_price - trade.entry_price) / trade.entry_price * 100.0;
                                
                                // Emergency sell if liquidity drops
                                if !(LIQUIDITY_MIN..=LIQUIDITY_MAX).contains(&liquidity) {
                                    info!("⚠️ Emergency sell - Liquidity outside range for {} ({} SOL)", token_mint, liquidity);
                                    match self.execute_trade_with_retry(token_mint, false, trade.amount).await {
                                        Ok(sig) => {
                                            info!("💰 Emergency sell executed - TX: {}", sig);
                                            let mut metrics = self.metrics.lock().await;
                                            metrics.total_trades += 1;
                                            self.active_trades.remove(token_mint);
                                            self.save_state().await?;
                                        }
                                        Err(e) => error!("Failed to execute emergency sell: {}", e)
                                    }
                                    continue;
                                }

                                // Take profit
                                if profit_percent >= TAKE_PROFIT {
                                    info!("🎯 Take profit hit for {}: {:.2}%", token_mint, profit_percent);
                                    match self.execute_trade_with_retry(token_mint, false, trade.amount).await {
                                        Ok(sig) => {
                                            info!("💰 Profit taken - TX: {} (Duration: {:?})", sig, trade_duration);
                                            let mut metrics = self.metrics.lock().await;
                                            metrics.successful_trades += 1;
                                            metrics.total_profit_loss += profit_percent;
                                            self.active_trades.remove(token_mint);
                                            self.save_state().await?;
                                        }
                                        Err(e) => error!("Failed to execute take profit: {}", e)
                                    }
                                } 
                                // Stop loss
                                else if profit_percent <= STOP_LOSS {
                                    warn!("⚠️ Stop loss hit for {}: {:.2}%", token_mint, profit_percent);
                                    match self.execute_trade_with_retry(token_mint, false, trade.amount).await {
                                        Ok(sig) => {
                                            info!("🛑 Stop loss executed - TX: {} (Duration: {:?})", sig, trade_duration);
                                            let mut metrics = self.metrics.lock().await;
                                            metrics.failed_trades += 1;
                                            metrics.total_profit_loss -= profit_percent.abs();
                                            self.active_trades.remove(token_mint);
                                            self.save_state().await?;
                                        }
                                        Err(e) => error!("Failed to execute stop loss: {}", e)
                                    }
                                }
                                // Regular update
                                else {
                                    info!("📊 Trade status - {}: {:.2}% P/L, Duration: {:?}", 
                                        token_mint, profit_percent, trade_duration);
                                }
                            }
                            Err(e) => warn!("Failed to fetch price for {}: {}", token_mint, e)
                        }
                    }
                }
                _ = save_interval.tick() => {
                    info!("💾 Performing periodic state save...");
                    if let Err(e) = self.save_state().await {
                        error!("Failed to save state: {}", e);
                    }
                }
                _ = shutdown_rx.recv() => {
                    info!("🛑 Received shutdown signal in monitor_trades");
                    break;
                }
            }
        }

        info!("👋 Trade monitor shutting down...");
        Ok(())
    }


    async fn save_state(&self) -> Result<()> {
        let current_time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Create state in a non-blocking way
        let mut active_trades_state = Vec::new();
        for trade in self.active_trades.iter() {
            let last_price = *trade.last_price.lock().await;
            active_trades_state.push(TradeState {
                token_mint: trade.token_mint.clone(),
                entry_price: trade.entry_price,
                amount: trade.amount,
                timestamp: current_time,
                last_price,
                success_count: trade.success_count,
                profit_loss: trade.profit_loss,
            });
        }

        let mut known_tokens_state = Vec::new();
        for entry in self.known_tokens.iter() {
            known_tokens_state.push(KnownToken {
                mint: entry.key().clone(),
                last_seen: entry.value().elapsed().as_secs(),
                reason: "pending_validation".to_string(),
            });
        }

        let mut last_prices_state = Vec::new();
        for entry in self.last_prices.iter() {
            last_prices_state.push(LastPrice {
                mint: entry.key().clone(),
                price: *entry.value(),
                last_update: current_time,
            });
        }

        let metrics = self.metrics.lock().await;
        
        let state = CompleteState {
            active_trades: active_trades_state,
            known_tokens: known_tokens_state,
            metrics: metrics.clone(),
            last_prices: last_prices_state,
            system_info: SystemInfo {
                uptime_seconds: current_time - metrics.start_time,
                active_trades_count: self.active_trades.len(),
                known_tokens_count: self.known_tokens.len(),
                tracked_prices_count: self.last_prices.len(),
                last_save: current_time,
            },
            validation_stats: ValidationStats {
                tokens_seen: 0,
                tokens_validated: 0,
                tokens_rejected: RejectedStats {
                    low_supply: 0,
                    low_liquidity: 0,
                    invalid_attributes: 0,
                },
            },
            trading_parameters: TradingParameters {
                min_supply: MIN_SUPPLY,
                liquidity_min: LIQUIDITY_MIN,
                liquidity_max: LIQUIDITY_MAX,
                trade_amount: TRADE_AMOUNT,
                max_trades: MAX_TRADES,
                take_profit: TAKE_PROFIT,
                stop_loss: STOP_LOSS,
            },
        };

        let mut file = File::create(&self.state_file).await?;
        let state_json = serde_json::to_string_pretty(&state)?;
        file.write_all(state_json.as_bytes()).await?;

        info!("💾 System state saved successfully");
        Ok(())
    }

    async fn load_state(&self) -> Result<()> {
        info!("📂 Loading saved state...");

        if self.state_file.exists() {
            let mut file = File::open(&self.state_file).await?;
            let mut contents = String::new();
            file.read_to_string(&mut contents).await?;

            if !contents.trim().is_empty() {
                let state: CompleteState = serde_json::from_str(&contents)
                    .map_err(|e| anyhow!("Failed to parse state file: {}", e))?;

                // Restore active trades
                for trade in state.active_trades {
                    let age = SystemTime::now()
                        .duration_since(SystemTime::UNIX_EPOCH)
                        .unwrap()
                        .as_secs() - trade.timestamp;

                    if age < 3600 {
                        info!("📊 Restoring trade: {} (Age: {}s)", trade.token_mint, age);
                        self.active_trades.insert(
                            trade.token_mint.clone(),
                            ActiveTrade {
                                token_mint: trade.token_mint,
                                entry_price: trade.entry_price,
                                amount: trade.amount,
                                start_time: Instant::now(),
                                last_price: Arc::new(Mutex::new(trade.last_price)),
                                success_count: trade.success_count,
                                profit_loss: trade.profit_loss,
                            }
                        );
                    }
                }

                // Restore known tokens
                for token in state.known_tokens {
                    self.known_tokens.insert(token.mint, Instant::now() - Duration::from_secs(token.last_seen));
                }

                // Restore metrics
                let mut metrics = self.metrics.lock().await;
                *metrics = state.metrics;
                metrics.last_restart = SystemTime::now()
                    .duration_since(SystemTime::UNIX_EPOCH)
                    .unwrap()
                    .as_secs();

                // Restore last prices
                for price in state.last_prices {
                    self.last_prices.insert(price.mint, price.price);
                }
            }
        }

        self.print_status().await;
        Ok(())
    }


    async fn print_status(&self) {
        let metrics = self.metrics.lock().await;
        let current_time = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let uptime = current_time - metrics.start_time;
        let restart_age = current_time - metrics.last_restart;

        info!("📊 System Status");
        info!("├── Active Trades: {}", self.active_trades.len());
        info!("├── Total Trades: {}", metrics.total_trades);
        info!("├── Successful: {}", metrics.successful_trades);
        info!("├── Failed: {}", metrics.failed_trades);
        info!("├── Total P/L: {:.4} SOL", metrics.total_profit_loss);
        info!("├── Uptime: {}h {}m", uptime / 3600, (uptime % 3600) / 60);
        info!("└── Last Restart: {} minutes ago", restart_age / 60);
    }

    async fn execute_trade(&self, token_mint: &str, is_buy: bool, amount: u64) -> Result<String> {
        let (input_mint, output_mint) = if is_buy {
            (SOL_MINT, token_mint)
        } else {
            (token_mint, SOL_MINT)
        };

        let quote = get_quote(input_mint, output_mint, amount).await?;
        let swap_data = get_swap_data(quote).await?;
        let signature = send_priority_tx(swap_data).await?;

        Ok(signature)
    }

    // Fix the execute_trade_with_retry method
    async fn execute_trade_with_retry(&self, token_mint: &str, is_buy: bool, amount: u64) -> Result<String> {
        let trade_type = if is_buy { "Buy" } else { "Sell" };
        info!("🚀 Executing {} trade for {}", trade_type, token_mint);
        
        let mut attempt = 1;
        loop {
            match self.execute_trade(token_mint, is_buy, amount).await {
                Ok(signature) => {
                    info!("✅ {} successful on attempt {} - TX: {}", trade_type, attempt, signature);
                    return Ok(signature);
                },
                Err(e) => {
                    warn!("❌ {} failed attempt {}/{}: {}", trade_type, attempt, MAX_RETRIES, e);
                    if attempt < MAX_RETRIES {
                        info!("⏳ Waiting {:?} before retry...", RETRY_DELAY);
                        tokio::time::sleep(RETRY_DELAY).await;
                    } else {
                        break; // Break out of the loop if all attempts fail
                    }
                }
            }
            attempt += 1;
        }
        
        Err(anyhow!("{} failed after {} attempts", trade_type, MAX_RETRIES))
    }

    // Fix the run method's error handling
    async fn run(self: Arc<Self>) -> Result<()> {
        self.load_state().await?;
    
        let monitor_system = self.clone();
        let monitor_handle = tokio::spawn(async move {
            if let Err(e) = monitor_system.monitor_trades().await {
                error!("Trade monitor error: {}", e);
            }
        });
    
        let ws_url = Url::parse(WS_URL)?;
        let mut reconnection_delay = Duration::from_secs(1);
        let mut shutdown_rx = self.shutdown_signal.subscribe();
    
        loop {
            tokio::select! {
                _ = shutdown_rx.recv() => {
                    info!("🛑 Received shutdown signal in main loop");
                    break;
                }
                _ = async {
                    loop {
                        match connect_async(ws_url.clone()).await {
                            Ok((ws_stream, _)) => {
                                info!("📡 WebSocket connected");
                                let (mut write, mut read) = ws_stream.split();
                                
                                let subscribe_msg = json!({
                                    "jsonrpc": "2.0",
                                    "id": 1,
                                    "method": "programSubscribe",
                                    "params": [
                                        "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
                                        {
                                            "encoding": "jsonParsed",
                                            "filters": [{"dataSize": 82}]
                                        }
                                    ]
                                });
        
                                if let Err(e) = write.send(Message::Text(subscribe_msg.to_string())).await {
                                    warn!("WebSocket subscription error: {}", e);
                                    break;
                                }
        
                                info!("✅ Subscribed to token program successfully");
        
                                while let Some(msg) = read.next().await {
                                    match msg {
                                        Ok(Message::Text(text)) => {
                                            if let Ok(data) = serde_json::from_str::<Value>(&text) {
                                                if data.get("method").map_or(false, |m| m.as_str() == Some("programNotification")) {
                                                    if let Some(params) = data.get("params") {
                                                        if self.active_trades.len() >= MAX_TRADES {
                                                            continue;
                                                        }
        
                                                        match self.validate_new_token(params).await {
                                                            Ok(ValidationResult::Valid) => {
                                                                if let Some(token_mint) = params
                                                                    .get("value")
                                                                    .and_then(|v| v.get("pubkey"))
                                                                    .and_then(|p| p.as_str()) 
                                                                {
                                                                    info!("🎯 Opening trade for {}", token_mint);
                                                                    
                                                                    // Wrap the trade execution in a block to handle errors
                                                                    if let Ok(signature) = self.execute_trade_with_retry(token_mint, true, TRADE_AMOUNT).await {
                                                                        if let Ok((_, entry_price)) = self.check_liquidity_and_price(token_mint).await {
                                                                            self.active_trades.insert(
                                                                                token_mint.to_string(),
                                                                                ActiveTrade {
                                                                                    token_mint: token_mint.to_string(),
                                                                                    entry_price,
                                                                                    amount: TRADE_AMOUNT,
                                                                                    start_time: Instant::now(),
                                                                                    last_price: Arc::new(Mutex::new(entry_price)),
                                                                                    success_count: 0,
                                                                                    profit_loss: 0.0,
                                                                                }
                                                                            );
                                                                            info!("✨ New trade opened - TX: {}", signature);
                                                                            let _ = self.save_state().await;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            Ok(ValidationResult::Invalid(_)) => (), // Skip invalid silently
                                                            Ok(ValidationResult::Error(e)) => {
                                                                warn!("❌ Validation error: {}", e);
                                                            }
                                                            Err(e) => {
                                                                warn!("Failed to validate token: {}", e);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        Ok(Message::Close(_)) => {
                                            info!("WebSocket connection closed by server");
                                            break;
                                        }
                                        Err(e) => {
                                            warn!("WebSocket error: {}", e);
                                            break; // Break out of the loop on WebSocket error
                                        }
                                        _ => ()
                                    }
                                }
                            }
                            Err(e) => {
                                error!("WebSocket connection error: {}. Retrying in {:?}...", e, reconnection_delay);
                                tokio::time::sleep(reconnection_delay).await;
                                reconnection_delay = min(reconnection_delay * 2, Duration::from_secs(30));
                                continue; // Continue to the next iteration on WebSocket connection error
                            }
                        }
                    }
                } => ()
            }
        }
    
        info!("🔄 Shutting down trade monitor...");
        monitor_handle.abort();
        self.save_state().await?;
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();
    info!("🚀 Starting trading system v2.0");
    
    let system = Arc::new(TradingSystem::new());
    
    ctrlc::set_handler({
        let shutdown_signal = system.shutdown_signal.clone();
        move || {
            info!("Received Ctrl+C, initiating graceful shutdown...");
            let _ = shutdown_signal.send(());
        }
    })?;

    if let Err(e) = Arc::clone(&system).run().await {
        error!("System error: {}", e);
    }

    info!("👋 Trading system shutdown complete");
    Ok(())
}