hello there again i fixed it think but i need your assistance please with just rewrite it all with out the spacing issues please and bracket problems the code remains the same just i need all of it rewritten so that i dont have any problems with spacing so that means u have you write all of the code with no place holders or remaining... goes here or rest of the code goes here... just write every single word that belongs mirror the script just fix the spacing and brackets if there are any problems okay use pyo3::prelude::*;
use pyo3::exceptions::PyValueError;
use solana_client::rpc_client::RpcClient;
use solana_client::rpc_request::TokenAccountsFilter;
use solana_sdk::commitment_config::CommitmentConfig;
use solana_sdk::signature::{Keypair, read_keypair_file, Signer};
use solana_sdk::pubkey::Pubkey;
use std::collections::{HashMap, VecDeque};
use tokio::runtime::Runtime;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use serde_json::json;
use chrono::{DateTime, Utc};
use std::sync::{Arc, Mutex};
use serde::{Serialize, Deserialize};
use base64::engine::general_purpose::STANDARD as base64_engine;
use base64::Engine;

const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const HELIUS_API_KEY: &str = "1ea5843b-9daa-4926-a97a-be021922da2f";
const JUPITER_API_V6: &str = "https://quote-api.jup.ag/v6";
const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const SOL_USDC_POOL: &str = "EGZ7tiLeH62TPV1gL8WwbXGzEPa9zmcpVnnkPKKnrE2U";
const KEYPAIR_PATH: &str = "C:\\solana_rust_bot\\id.json";

// Commitment configuration
const COMMITMENT: CommitmentConfig = CommitmentConfig::confirmed();

// Define a struct to represent a position
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Position {
    entry_price: f64,
    size: f64,
    timestamp: DateTime<Utc>,
    tx_signature: String,
    pnl: f64,
    status: String,
}

// Define a Python class for the HeliusBot
#[pyclass(name = "HeliusBot")]
struct PyHeliusBot {
    client: RpcClient,
    runtime: Runtime,
    headers: HeaderMap,
    keypair: Keypair,
    positions: Arc<Mutex<VecDeque<Position>>>,
    last_prices: Arc<Mutex<VecDeque<f64>>>,
}

// Implement methods for the PyHeliusBot class
#[pymethods]
impl PyHeliusBot {
    #[new]
    fn new() -> PyResult<Self> {
        let mut headers = HeaderMap::new();
        headers.insert(
            AUTHORIZATION,
            HeaderValue::from_str(&format!("Bearer {}", HELIUS_API_KEY))
                .map_err(|e| PyValueError::new_err(e.to_string()))?
        );

        let keypair = read_keypair_file(KEYPAIR_PATH)
            .map_err(|e| PyValueError::new_err(format!("Failed to load keypair: {}", e)))?;

        let client = RpcClient::new_with_commitment(
            HELIUS_RPC.to_string(),
            COMMITMENT,
        );

        let runtime = Runtime::new()
            .map_err(|e| PyValueError::new_err(e.to_string()))?;

        Ok(PyHeliusBot {
            client,
            runtime,
            headers,
            keypair,
            positions: Arc::new(Mutex::new(VecDeque::with_capacity(100))),
            last_prices: Arc::new(Mutex::new(VecDeque::with_capacity(1000))),
        })
    }

    fn get_wallet_balance(&self) -> PyResult<f64> {
        let balance = self.client
            .get_balance(&self.keypair.pubkey())
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(balance as f64 / 1e9) // Convert balance to SOL
    }

    fn get_token_balance(&self, token_mint: &str) -> PyResult<f64> {
        let token_mint_bytes: [u8; 32] = token_mint.as_bytes().try_into().unwrap();
        let filter = TokenAccountsFilter::Mint(Pubkey::from(token_mint_bytes));
    
        let token_accounts = self.client
            .get_token_accounts_by_owner(
                &self.keypair.pubkey(),
                filter
            )
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
    
        for account in token_accounts.iter() {
            if account.pubkey.to_string() == token_mint {
                return Ok(account.account.lamports as f64 / 1e9); // Convert lamports to SOL
            }
        }
    
        Ok(0.0) // If not found, return 0.0
    }

    fn scan_token_metrics(&self, token_mint: &str) -> PyResult<String> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": "token-metrics",
            "method": "getTokenSupply",
            "params": [
                token_mint,
                {"commitment": "confirmed"}
            ]
        });

        let response = self.runtime.block_on(async {
            reqwest::Client::new()
                .post(HELIUS_RPC)
                .headers(self.headers.clone())
                .json(&request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))?
                .json::<serde_json::Value>()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))
        })?;

        Ok(serde_json::to_string(&response)
            .map_err(|e| PyValueError::new_err(e.to_string()))?)
    }

    fn get_pool_price(&self) -> PyResult<f64> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": "price-check",
            "method": "getAccountInfo",
            "params": [
                SOL_USDC_POOL,
                {
                    "encoding": "base64",
                    "commitment": "confirmed"
                }
            ]
        });

        let response = self.runtime.block_on(async {
            let resp = reqwest::Client::new()
                .post(HELIUS_RPC)
                .headers(self.headers.clone())
                .json(&request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))?
                .json::<serde_json::Value>()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))?;

            if let Some(data) = resp.get("result").and_then(|r| r.get("data")) {
                if let Some(data_str) = data.get(0).and_then(|d| d.as_str()) {
                    let decoded = base64_engine.decode(data_str)
                        .map_err(|e| PyValueError::new_err(e.to_string()))?;

                    if decoded.len() >= 40 {
                        let sol_reserves = u64::from_le_bytes(decoded[8..16].try_into().unwrap());
                        let usdc_reserves = u64::from_le_bytes(decoded[16..24].try_into().unwrap());

                        let price = (usdc_reserves as f64) / (sol_reserves as f64);

                        // Update price history
                        let mut prices = self.last_prices.lock().unwrap();
                        prices.push_back(price);
                        if prices.len() > 1000 {
                            prices.pop_front();
                        }

                        return Ok(price); // Return the pool price
                    }
                }
            }

            Err(PyValueError::new_err("Failed to parse pool data"))
        })?;

        Ok(response)
    }

    fn monitor_raydium_pools(&self) -> PyResult<String> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": "raydium-pools",
            "method": "getMultipleAccounts",
            "params": [
                [RAYDIUM_PROGRAM_ID],
                {
                    "encoding": "jsonParsed",
                    "commitment": "confirmed",
                    "dataSlice": {
                        "offset": 0,
                        "length": 0
                    }
                }
            ]
        });

        let response = self.runtime.block_on(async {
            let resp = reqwest::Client::new()
            .post(HELIUS_RPC)
            .headers(self.headers.clone())
            .json(&request)
            .send()
            .await
            .map_err(|e| PyValueError::new_err(e.to_string()))?
            .json::<serde_json::Value>()
            .await
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
    
            if let Some(accounts) = resp.get("result") {
                let pools: Vec<_> = accounts
                    .as_array()
                    .unwrap_or(&Vec::new())
                    .iter()
                    .map(|account| {
                        json!({
                            "address": account["pubkey"].as_str().unwrap_or(""),
                            "data": account["account"]["data"][0].as_str().unwrap_or(""),
                            "owner": account["account"]["owner"].as_str().unwrap_or(""),
                            "lamports": account["account"]["lamports"].as_u64().unwrap_or(0)
                        })
                    })
                    .collect();
        
                let pools_json = serde_json::to_string(&pools)
                    .map_err(|e| PyValueError::new_err(e.to_string()))?;
        
                Ok::<std::string::String, E>(pools_json) // Specify the generic arguments for Ok
            } else {
                Ok("[]".to_string()) // Return an empty array if no accounts found
            }
        
        })?;
    fn analyze_pool_data(&self, pool_data: &str) -> PyResult<String> {
        let decoded = base64_engine.decode(pool_data)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
    
        if decoded.len() >= 592 {
            let base_mint = &decoded[8..40];
            let quote_mint = &decoded[40..72];
            let base_reserves = u64::from_le_bytes(decoded[72..80].try_into().unwrap());
            let quote_reserves = u64::from_le_bytes(decoded[80..88].try_into().unwrap());
    
            let analysis = json!({
                "base_mint": base_mint.to_vec(),
                "quote_mint": quote_mint.to_vec(),
                "base_reserves": base_reserves,
                "quote_reserves": quote_reserves,
                "price": (quote_reserves as f64) / (base_reserves as f64),
                "liquidity": base_reserves + quote_reserves,
                "timestamp": chrono::Utc::now().to_rfc3339()
            });
    
            Ok(serde_json::to_string(&analysis)
                .map_err(|e| PyValueError::new_err(e.to_string()))?)
        } else {
            Err(PyValueError::new_err("Invalid pool data size"))
        }
    }
    
    fn open_position(&self, size: f64) -> PyResult<String> {
        let current_price = self.get_pool_price()?;
        let quote = self.get_jupiter_quote("So11111111111111111111111111111111111111112",
                                             "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                                             (size * 1e9) as u64)?;
    
        let tx = self.send_priority_transaction(&quote)?;
    
        let position = Position {
            entry_price: current_price,
            size,
            timestamp: Utc::now(),
            tx_signature: tx.clone(),
            pnl: 0.0,
            status: "OPEN".to_string(),
        };
    
        let mut positions = self.positions.lock().unwrap();
        positions.push_back(position);
    
        Ok(tx)
    }
    
    fn close_position(&self, position_index: usize) -> PyResult<String> {
        let mut positions = self.positions.lock().unwrap();
    
        if let Some(position) = positions.get_mut(position_index) {
            let current_price = self.get_pool_price()?;
            let quote = self.get_jupiter_quote("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
                                                 "So11111111111111111111111111111111111111112",
                                                 (position.size * 1e9) as u64)?;
    
            let tx = self.send_priority_transaction(&quote)?;
    
            position.pnl = (current_price - position.entry_price) * position.size;
            position.status = "CLOSED".to_string();
    
            Ok(tx)
        } else {
            Err(PyValueError::new_err("Invalid position index"))
        }
    }
    
    fn get_jupiter_quote(&self, input_mint: &str, output_mint: &str, amount: u64) -> PyResult<String> {
        let url = format!(
            "{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50&onlyDirectRoutes=true&asLegacyTransaction=false",
            JUPITER_API_V6, input_mint, output_mint, amount
        );
    
        let quote = self.runtime.block_on(async {
            reqwest::get(&url)
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))?
                .json::<serde_json::Value>()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))
        })?;
    
        Ok(serde_json::to_string(&quote)
            .map_err(|e| PyValueError::new_err(e.to_string()))?)
    }
    
    fn send_priority_transaction(&self, transaction_data: &str) -> PyResult<String> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": "helius-priority",
            "method": "sendTransaction",
            "params": [
                transaction_data,
                {
                    "encoding": "base64",
                    "maxRetries": 0,
                    "skipPreflight": true,
                    "preflightCommitment": "confirmed",
                    "priorityFee": 15000
                }
            ]
        });
    
        let response = self.runtime.block_on(async {
            reqwest::Client::new()
                .post(HELIUS_RPC)
                .headers(self.headers.clone())
                .json(&request)
                .send()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))?
                .json::<serde_json::Value>()
                .await
                .map_err(|e| PyValueError::new_err(e.to_string()))
        })?;
    
        Ok(response["result"].to_string())
    }
    
    fn get_positions(&self) -> PyResult<String> {
        let positions = self.positions.lock().unwrap();
        let positions_json = serde_json::to_string(&*positions)
            .map_err(|e| PyValueError::new_err(e.to_string()))?;
        Ok(positions_json)
    }
    
    fn get_market_metrics(&self) -> PyResult<HashMap<String, f64>> {
        let prices = self.last_prices.lock().unwrap();
        let prices_vec: Vec<f64> = prices.iter().cloned().collect();
    
        let mut metrics = HashMap::new();
    
        if !prices_vec.is_empty() {
            // Calculate basic metrics
            metrics.insert("current_price".to_string(), *prices_vec.last().unwrap());
            metrics.insert("price_change".to_string(),
                         (prices_vec.last().unwrap() - prices_vec.first().unwrap()) / prices_vec.first().unwrap());
    
            // Calculate volatility
            if prices_vec.len() > 1 {
                let returns: Vec<f64> = prices_vec.windows(2)
                    .map(|w| (w[1] - w[0]) / w[0])
                    .collect();
                let volatility = returns.iter().map(|r| r * r).sum::<f64>().sqrt() * (252.0_f64).sqrt();
                metrics.insert("volatility".to_string(), volatility);
            }
        }
    
        Ok(metrics)
    }
}
// Define the Python module
#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<PyHeliusBot>()?;
    Ok(())
}