i need a favor please my eyes are going so i need all of the code for the entirety of the script you are going to produce its easy just take this script here and ur going to add it to the 2nd script to give me the proper script // Add this at the top with other imports
use solana_sdk::signer::Signer;

// Replace the execute_jupiter_swap function
fn execute_jupiter_swap(&self, quote: &PyAny, _token: &str, priority_fee: u64) -> PyResult<String> {
    self.runtime.block_on(async {
        let quote: Value = serde_json::from_str(
            &quote.get_item("quoteResponse")?.extract::<String>()?
        ).map_err(|e| PyValueError::new_err(format!("Quote parse error: {}", e)))?;

        let swap_request = json!({
            "quoteResponse": quote,
            "userPublicKey": self.keypair.as_ref().pubkey().to_string(), // Fixed pubkey access
            "wrapUnwrapSOL": true,
            "computeUnitPriceMicroLamports": priority_fee,
            "priorityFeeLamports": priority_fee,
            "asLegacyTransaction": false,
            "maxAccounts": 64
        });

        // Rest of the function stays the same...
    })
}

// Replace the execute_trade function
fn execute_trade(&self, token: String, is_buy: bool) -> PyResult<String> {
    self.runtime.block_on(async {
        let settings = self.settings.read().await;
        
        if is_buy && self.active_trades.len() >= self.config.performance.max_concurrent_trades {
            return Err(PyValueError::new_err("Maximum concurrent trades reached"));
        }

        let amount = if is_buy {
            (settings.max_position_size * 1e9) as u64
        } else {
            match self.active_trades.get(&token) {
                Some(trade) => (trade.size * 1e9) as u64,
                None => return Err(PyValueError::new_err("No active trade found"))
            }
        };

        // Fixed return type handling
        let result = Python::with_gil(|py| -> PyResult<String> {
            let quote = self.get_jupiter_quote(&token, amount, is_buy)?;
            self.execute_jupiter_swap(quote.as_ref(py), &token, settings.priority_fee)
        })?;

        if is_buy {
            if let Ok(market_data) = self.get_market_data(token.clone()) {
                self.active_trades.insert(
                    token.clone(),
                    Trade {
                        token,
                        entry_price: market_data.price,
                        current_price: market_data.price,
                        size: amount as f64 / 1e9,
                        profit_loss: 0.0,
                        timestamp: SystemTime::now()
                            .duration_since(UNIX_EPOCH)
                            .unwrap_or_default()
                            .as_secs() as i64,
                        status: "ACTIVE".to_string(),
                    },
                );
            }
        } else {
            self.active_trades.remove(&token);
        }

        Ok(result)
    })
}  use dashmap::DashMap;
use pyo3::{exceptions::*, prelude::*, types::PyDict};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use solana_client::nonblocking::rpc_client::RpcClient;
use solana_sdk::signature::Keypair;
use std::{
    collections::HashMap,
    fs::File,
    io::Read,
    sync::{Arc, Once},
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{runtime::Runtime, sync::RwLock};

const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
const SOL_MINT: &str = "So11111111111111111111111111111111111111112";
const HELIUS_API_HEADER: &str = "Bearer ";

static RUNTIME_INIT: Once = Once::new();
static mut RUNTIME: Option<Runtime> = None;

fn get_runtime() -> PyResult<&'static Runtime> {
    unsafe {
        RUNTIME_INIT.call_once(|| {
            RUNTIME = Some(Runtime::new().unwrap());
        });
        RUNTIME.as_ref().ok_or_else(|| PyRuntimeError::new_err("Runtime not initialized"))
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct NetworkConfig {
    pub api_key: String,
    pub rpc_url: String,
    pub ws_url: String,
    pub backup_rpc: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SnipingConfig {
    pub buy_amount: f64,
    pub max_slippage: f64,
    pub priority_fee: u64,
    pub min_liquidity: f64,
    pub min_market_cap: f64,
    pub min_volume: f64,
    pub buyer_seller_ratio: f64,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ScalpingConfig {
    pub position_size: f64,
    pub take_profit: f64,
    pub stop_loss: f64,
    pub max_position_size: f64,
    pub scaling_threshold: u64,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PerformanceConfig {
    pub max_concurrent_trades: usize,
    pub price_impact_threshold: f64,
    pub volatility_threshold: f64,
    pub update_interval_ms: usize,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct PoolConfig {
    pub raydium_pool: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Config {
    pub network: NetworkConfig,
    pub sniping: SnipingConfig,
    pub scalping: ScalpingConfig,
    pub performance: PerformanceConfig,
    pub pools: Vec<PoolConfig>,
}

#[pyclass]
#[derive(Clone, Debug)]
pub struct MarketData {
    #[pyo3(get)]
    pub price: f64,
    #[pyo3(get)]
    pub volume_24h: f64,
    #[pyo3(get)]
    pub liquidity: f64,
    #[pyo3(get)]
    pub price_change_24h: f64,
    #[pyo3(get)]
    pub timestamp: i64,
}

impl Default for MarketData {
    fn default() -> Self {
        Self {
            price: 0.0,
            volume_24h: 0.0,
            liquidity: 0.0,
            price_change_24h: 0.0,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs() as i64,
        }
    }
}

#[pyclass]
#[derive(Clone, Debug)]
pub struct Trade {
    #[pyo3(get)]
    pub token: String,
    #[pyo3(get)]
    pub entry_price: f64,
    #[pyo3(get)]
    pub current_price: f64,
    #[pyo3(get)]
    pub size: f64,
    #[pyo3(get)]
    pub profit_loss: f64,
    #[pyo3(get)]
    pub timestamp: i64,
    #[pyo3(get)]
    pub status: String,
}

#[pyclass]
#[derive(Clone, Debug)]
pub struct ScalperSettings {
    #[pyo3(get, set)]
    pub min_price_change: f64,
    #[pyo3(get, set)]
    pub max_position_size: f64,
    #[pyo3(get, set)]
    pub take_profit: f64,
    #[pyo3(get, set)]
    pub stop_loss: f64,
    #[pyo3(get, set)]
    pub max_slippage: f64,
    #[pyo3(get, set)]
    pub min_volume: f64,
    #[pyo3(get, set)]
    pub priority_fee: u64,
}

#[pymethods]
impl ScalperSettings {
    #[new]
    fn new() -> Self {
        Self {
            min_price_change: 0.5,
            max_position_size: 0.1,
            take_profit: 1.0,
            stop_loss: -0.5,
            max_slippage: 0.5,
            min_volume: 1000.0,
            priority_fee: 15000,
        }
    }
}

fn load_config(file_path: &str) -> std::io::Result<Config> {
    let mut file = File::open(file_path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    let config: Config = serde_json::from_str(&contents)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    Ok(config)
}

#[pyclass]
pub struct SolanaTrader {
    settings: Arc<RwLock<ScalperSettings>>,
    http_client: Arc<Client>,
    rpc_client: Arc<RpcClient>,
    active_trades: Arc<DashMap<String, Trade>>,
    market_data_cache: Arc<DashMap<String, MarketData>>,
    keypair: Arc<Keypair>,
    runtime: &'static Runtime,
    config: Arc<Config>,
}
#[pymethods]
impl SolanaTrader {
    #[new]
    fn new(config_path: String, keypair_bytes: Vec<u8>) -> PyResult<Self> {
        let runtime = get_runtime()?;
        let keypair = Keypair::from_bytes(&keypair_bytes)
            .map_err(|e| PyValueError::new_err(format!("Invalid keypair: {}", e)))?;

        let config = load_config(&config_path)
            .map_err(|e| PyValueError::new_err(format!("Config error: {}", e)))?;

        let http_client = Client::builder()
            .timeout(Duration::from_secs(10))
            .pool_max_idle_per_host(100)
            .build()
            .map_err(|e| PyValueError::new_err(format!("HTTP client error: {}", e)))?;

        Ok(Self {
            settings: Arc::new(RwLock::new(ScalperSettings::new())),
            http_client: Arc::new(http_client),
            rpc_client: Arc::new(RpcClient::new(config.network.rpc_url.clone())),
            active_trades: Arc::new(DashMap::new()),
            market_data_cache: Arc::new(DashMap::new()),
            keypair: Arc::new(keypair),
            runtime,
            config: Arc::new(config),
        })
    }

    fn get_market_data(&self, token: String) -> PyResult<MarketData> {
        self.runtime.block_on(async {
            let request = json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "getTokenAccountsByOwner",
                "params": [
                    token,
                    {
                        "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
                    }
                ]
            });

            let response = self.http_client
                .post(&self.config.network.rpc_url)
                .header(
                    "Authorization",
                    format!("{}{}", HELIUS_API_HEADER, self.config.network.api_key)
                )
                .json(&request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(format!("Request failed: {}", e)))?
                .json::<Value>()
                .await
                .map_err(|e| PyValueError::new_err(format!("Parse failed: {}", e)))?;

            let market_data = MarketData {
                price: response["result"]["value"][0]["data"]["parsed"]["info"]["tokenAmount"]["uiAmount"]
                    .as_f64()
                    .unwrap_or_default(),
                volume_24h: response["result"]["value"][0]["data"]["parsed"]["info"]["volume24h"]
                    .as_f64()
                    .unwrap_or_default(),
                liquidity: response["result"]["value"][0]["data"]["parsed"]["info"]["liquidity"]
                    .as_f64()
                    .unwrap_or_default(),
                price_change_24h: response["result"]["value"][0]["data"]["parsed"]["info"]["priceChange24h"]
                    .as_f64()
                    .unwrap_or_default(),
                timestamp: SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs() as i64,
            };

            self.market_data_cache.insert(token, market_data.clone());
            Ok(market_data)
        })
    }

    fn get_jupiter_quote(&self, token: &str, amount: u64, is_buy: bool) -> PyResult<PyObject> {
        let url = format!(
            "{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50&onlyDirectRoutes=true&wrapUnwrapSOL=true",
            JUPITER_API,
            if is_buy { SOL_MINT } else { token },
            if is_buy { token } else { SOL_MINT },
            amount
        );

        Python::with_gil(|py| {
            self.runtime.block_on(async {
                let response = self.http_client
                    .get(&url)
                    .send()
                    .await
                    .map_err(|e| PyValueError::new_err(format!("Quote request failed: {}", e)))?
                    .json::<Value>()
                    .await
                    .map_err(|e| PyValueError::new_err(format!("Quote parse failed: {}", e)))?;

                let dict = PyDict::new(py);
                dict.set_item("quoteResponse", response.to_string())?;
                Ok(dict.to_object(py))
            })
        })
    }

    fn execute_jupiter_swap(&self, quote: &PyAny, _token: &str, priority_fee: u64) -> PyResult<String> {
        self.runtime.block_on(async {
            let quote: Value = serde_json::from_str(
                &quote.get_item("quoteResponse")?.extract::<String>()?
            ).map_err(|e| PyValueError::new_err(format!("Quote parse error: {}", e)))?;

            let swap_request = json!({
                "quoteResponse": quote,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "wrapUnwrapSOL": true,
                "computeUnitPriceMicroLamports": priority_fee,
                "priorityFeeLamports": priority_fee,
                "asLegacyTransaction": false,
                "maxAccounts": 64
            });

            let swap_response = self.http_client
                .post(format!("{}/swap", JUPITER_API))
                .json(&swap_request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(format!("Swap request failed: {}", e)))?
                .json::<Value>()
                .await
                .map_err(|e| PyValueError::new_err(format!("Swap response parse failed: {}", e)))?;

            let swap_data = swap_response["swapTransaction"]
                .as_str()
                .ok_or_else(|| PyValueError::new_err("Invalid swap response"))?;

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

            let tx_response = self.http_client
                .post(&self.config.network.rpc_url)
                .header(
                    "Authorization",
                    format!("{}{}", HELIUS_API_HEADER, self.config.network.api_key)
                )
                .json(&helius_request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(format!("Transaction send failed: {}", e)))?
                .json::<Value>()
                .await
                .map_err(|e| PyValueError::new_err(format!("Transaction response parse failed: {}", e)))?;

            match tx_response.get("result") {
                Some(result) => Ok(result.as_str().unwrap_or_default().to_string()),
                None => {
                    if let Some(error) = tx_response.get("error") {
                        Err(PyValueError::new_err(format!("Helius error: {:?}", error)))
                    } else {
                        Err(PyValueError::new_err("Unexpected response format"))
                    }
                }
            }
        })
    }

    fn execute_trade(&self, token: String, is_buy: bool) -> PyResult<String> {
        self.runtime.block_on(async {
            let settings = self.settings.read().await;
            
            if is_buy && self.active_trades.len() >= self.config.performance.max_concurrent_trades {
                return Err(PyValueError::new_err("Maximum concurrent trades reached"));
            }

            let amount = if is_buy {
                (settings.max_position_size * 1e9) as u64
            } else {
                match self.active_trades.get(&token) {
                    Some(trade) => (trade.size * 1e9) as u64,
                    None => return Err(PyValueError::new_err("No active trade found"))
                }
            };

            Python::with_gil(|py| {
                let quote = self.get_jupiter_quote(&token, amount, is_buy)?;
                self.execute_jupiter_swap(quote.as_ref(py), &token, settings.priority_fee)
            })?
        })
    }

    fn get_active_trades(&self) -> PyResult<HashMap<String, Trade>> {
        Ok(self.active_trades
            .iter()
            .map(|entry| (entry.key().clone(), entry.value().clone()))
            .collect())
    }

    fn get_cached_market_data(&self, token: String) -> PyResult<MarketData> {
        self.market_data_cache
            .get(&token)
            .map(|data| data.clone())
            .ok_or_else(|| PyValueError::new_err("No cached market data found"))
    }

    fn update_settings(&self, new_settings: ScalperSettings) -> PyResult<()> {
        self.runtime.block_on(async {
            *self.settings.write().await = new_settings;
            Ok(())
        })
    }
}

#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<SolanaTrader>()?;
    m.add_class::<ScalperSettings>()?;
    m.add_class::<Trade>()?;
    m.add_class::<MarketData>()?;
    Ok(())
} just make the edit and thats it rewrite all my code right back to me thank you