```rust
use pyo3::prelude::*;
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
    commitment_config::CommitmentConfig,
    pubkey::Pubkey,
    signature::{Keypair, Signer},
    transaction::Transaction,
    instruction::{Instruction, AccountMeta},
    system_program,
};
use std::{
    str::FromStr,
    collections::HashMap,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::{
    sync::RwLock,
    time,
};
use serde::{Deserialize, Serialize};
use log::{info, warn, error, debug};
use reqwest::Client as HttpClient;
use anyhow::Result;
use base64::{Engine as _, engine::general_purpose::STANDARD as base64};

// Constants
const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const TOKEN_PROGRAM_ID: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const MARGA_TPS_LIMIT: u64 = 5;
const XYZ_TPS_LIMIT: u64 = 100;

#[derive(Debug, Serialize, Deserialize)]
struct PoolData {
    pool_address: String,
    token_mint: String,
    volume_24h: f64,
    liquidity: f64,
    price: f64,
    buy_pressure: u64,
    sell_pressure: u64,
    market_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Position {
    token_mint: String,
    pool_address: String,
    entry_price: f64,
    size: f64,
    stop_loss: f64,
    take_profit: f64,
    timestamp: i64,
}

#[derive(Debug, Serialize, Deserialize)]
struct TradeInstruction {
    side: String,
    size: f64,
    price: f64,
    pool_address: String,
    token_mint: String,
}

#[derive(Clone)]
struct RpcEndpoint {
    url: String,
    tps_limit: u64,
    last_request: Arc<RwLock<Instant>>,
    request_count: Arc<RwLock<u64>>,
}

#[pyclass]
struct ScalpingBot {
    marga_rpc: RpcClient,
    xyz_rpc: RpcClient,
    http_client: HttpClient,
    keypair: Keypair,
    marga_endpoint: RpcEndpoint,
    xyz_endpoint: RpcEndpoint,
    ws_url: String,
    pool_cache: HashMap<String, PoolData>,
    active_positions: HashMap<String, Position>,
    config: Arc<Config>,
}

#[derive(Debug, Deserialize, Clone)]
struct Config {
    helius_key: String,
    position_size: f64,
    max_position: f64,
    min_volume: f64,
    min_bs_ratio: f64,
    min_liquidity: f64,
    priority_fee: u64,
    take_profit: f64,
    stop_loss: f64,
    scaling_threshold: u32,
    scaling_increment: f64,
}

#[pymethods]
impl ScalpingBot {
    #[new]
    fn new(config_path: &str) -> PyResult<Self> {
        // Load configuration
        let config_str = std::fs::read_to_string(config_path)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to read config: {}", e)
            ))?;
        
        let config: Config = serde_json::from_str(&config_str)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to parse config: {}", e)
            ))?;
        
        // Initialize RPC endpoints
        let marga_endpoint = RpcEndpoint {
            url: "https://marga-e56m84-fast-mainnet.helius-rpc.com/".to_string(),
            tps_limit: MARGA_TPS_LIMIT,
            last_request: Arc::new(RwLock::new(Instant::now())),
            request_count: Arc::new(RwLock::new(0)),
        };

        let xyz_endpoint = RpcEndpoint {
            url: format!("https://rpc.helius.xyz/?api-key={}", config.helius_key),
            tps_limit: XYZ_TPS_LIMIT,
            last_request: Arc::new(RwLock::new(Instant::now())),
            request_count: Arc::new(RwLock::new(0)),
        };

        // Initialize RPC clients
        let marga_rpc = RpcClient::new_with_commitment(
            &marga_endpoint.url,
            CommitmentConfig::confirmed()
        );

        let xyz_rpc = RpcClient::new_with_commitment(
            &xyz_endpoint.url,
            CommitmentConfig::confirmed()
        );

        // Load keypair
        let keypair_bytes = std::fs::read("C:/solana_rust_bot/id.json")
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to read keypair: {}", e)
            ))?;
            
        let keypair = Keypair::from_bytes(&keypair_bytes)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Invalid keypair: {}", e)
            ))?;

        Ok(ScalpingBot {
            marga_rpc,
            xyz_rpc,
            http_client: HttpClient::new(),
            keypair,
            marga_endpoint,
            xyz_endpoint,
            ws_url: "wss://marga-e56m84-fast-mainnet.helius-rpc.com/".to_string(),
            pool_cache: HashMap::new(),
            active_positions: HashMap::new(),
            config: Arc::new(config),
        })
    }
```

Would you like me to continue with:
1. Trade execution implementation
2. Pool monitoring
3. Position management
4. WebSocket handling

Let me know which part you'd like to see next and I'll provide the complete production-ready code for that section.```rust
use pyo3::prelude::*;
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
    commitment_config::CommitmentConfig,
    pubkey::Pubkey,
    signature::{Keypair, Signer},
    transaction::Transaction,
    instruction::{Instruction, AccountMeta},
    system_program,
};
use std::{
    str::FromStr,
    collections::HashMap,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::{
    sync::RwLock,
    time,
};
use serde::{Deserialize, Serialize};
use log::{info, warn, error, debug};
use reqwest::Client as HttpClient;
use anyhow::Result;
use base64::{Engine as _, engine::general_purpose::STANDARD as base64};

// Constants
const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const TOKEN_PROGRAM_ID: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const MARGA_TPS_LIMIT: u64 = 5;
const XYZ_TPS_LIMIT: u64 = 100;

#[derive(Debug, Serialize, Deserialize)]
struct PoolData {
    pool_address: String,
    token_mint: String,
    volume_24h: f64,
    liquidity: f64,
    price: f64,
    buy_pressure: u64,
    sell_pressure: u64,
    market_id: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct Position {
    token_mint: String,
    pool_address: String,
    entry_price: f64,
    size: f64,
    stop_loss: f64,
    take_profit: f64,
    timestamp: i64,
}

#[derive(Debug, Serialize, Deserialize)]
struct TradeInstruction {
    side: String,
    size: f64,
    price: f64,
    pool_address: String,
    token_mint: String,
}

#[derive(Clone)]
struct RpcEndpoint {
    url: String,
    tps_limit: u64,
    last_request: Arc<RwLock<Instant>>,
    request_count: Arc<RwLock<u64>>,
}

#[pyclass]
struct ScalpingBot {
    marga_rpc: RpcClient,
    xyz_rpc: RpcClient,
    http_client: HttpClient,
    keypair: Keypair,
    marga_endpoint: RpcEndpoint,
    xyz_endpoint: RpcEndpoint,
    ws_url: String,
    pool_cache: HashMap<String, PoolData>,
    active_positions: HashMap<String, Position>,
    config: Arc<Config>,
}

#[derive(Debug, Deserialize, Clone)]
struct Config {
    helius_key: String,
    position_size: f64,
    max_position: f64,
    min_volume: f64,
    min_bs_ratio: f64,
    min_liquidity: f64,
    priority_fee: u64,
    take_profit: f64,
    stop_loss: f64,
    scaling_threshold: u32,
    scaling_increment: f64,
}

#[pymethods]
impl ScalpingBot {
    #[new]
    fn new(config_path: &str) -> PyResult<Self> {
        // Load configuration
        let config_str = std::fs::read_to_string(config_path)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to read config: {}", e)
            ))?;
        
        let config: Config = serde_json::from_str(&config_str)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to parse config: {}", e)
            ))?;
        
        // Initialize RPC endpoints
        let marga_endpoint = RpcEndpoint {
            url: "https://marga-e56m84-fast-mainnet.helius-rpc.com/".to_string(),
            tps_limit: MARGA_TPS_LIMIT,
            last_request: Arc::new(RwLock::new(Instant::now())),
            request_count: Arc::new(RwLock::new(0)),
        };

        let xyz_endpoint = RpcEndpoint {
            url: format!("https://rpc.helius.xyz/?api-key={}", config.helius_key),
            tps_limit: XYZ_TPS_LIMIT,
            last_request: Arc::new(RwLock::new(Instant::now())),
            request_count: Arc::new(RwLock::new(0)),
        };

        // Initialize RPC clients
        let marga_rpc = RpcClient::new_with_commitment(
            &marga_endpoint.url,
            CommitmentConfig::confirmed()
        );

        let xyz_rpc = RpcClient::new_with_commitment(
            &xyz_endpoint.url,
            CommitmentConfig::confirmed()
        );

        // Load keypair
        let keypair_bytes = std::fs::read("C:/solana_rust_bot/id.json")
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Failed to read keypair: {}", e)
            ))?;
            
        let keypair = Keypair::from_bytes(&keypair_bytes)
            .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                format!("Invalid keypair: {}", e)
            ))?;

        Ok(ScalpingBot {
            marga_rpc,
            xyz_rpc,
            http_client: HttpClient::new(),
            keypair,
            marga_endpoint,
            xyz_endpoint,
            ws_url: "wss://marga-e56m84-fast-mainnet.helius-rpc.com/".to_string(),
            pool_cache: HashMap::new(),
            active_positions: HashMap::new(),
            config: Arc::new(config),
        })
    }
```

Would you like me to continue with:
1. Trade execution implementation
2. Pool monitoring
3. Position management
4. WebSocket handling
```rust
    // Add to previous ScalpingBot implementation

    #[pymethods]
    impl ScalpingBot {
        // Execute scalp trade with Helius priority fee
        async fn execute_scalp(&self, pool_data: String) -> PyResult<String> {
            let trade: TradeInstruction = serde_json::from_str(&pool_data)
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
                    format!("Invalid trade data: {}", e)
                ))?;

            let priority_fee = self.get_helius_priority_fee().await?;
            info!("Using priority fee: {} lamports", priority_fee);

            let amount_lamports = (trade.size * 1e9) as u64;
            let instructions = vec![
                self.create_swap_instruction(&trade, amount_lamports)?,
                self.create_priority_fee_instruction(priority_fee)?,
            ];

            // Get latest blockhash from fastest available RPC
            let recent_blockhash = self.execute_rpc_request(|client| {
                Ok(client.get_latest_blockhash()?)
            }).await?;

            let mut transaction = Transaction::new_with_payer(
                &instructions,
                Some(&self.keypair.pubkey())
            );
            transaction.sign(&[&self.keypair], recent_blockhash);

            // Send via XYZ RPC if available (higher TPS), fallback to Marga
            let signature = self.execute_rpc_request(|client| {
                Ok(client.send_and_confirm_transaction_with_spinner(&transaction)?)
            }).await?;

            // Update position tracking
            if trade.side.to_lowercase() == "buy" {
                self.active_positions.insert(
                    trade.token_mint.clone(),
                    Position {
                        token_mint: trade.token_mint,
                        pool_address: trade.pool_address,
                        entry_price: trade.price,
                        size: trade.size,
                        stop_loss: trade.price * (1.0 - self.config.stop_loss / 100.0),
                        take_profit: trade.price * (1.0 + self.config.take_profit / 100.0),
                        timestamp: chrono::Utc::now().timestamp(),
                    }
                );
            }

            info!("Trade executed: {} | Side: {} | Size: {} SOL | Price: {}",
                signature, trade.side, trade.size, trade.price);

            Ok(signature.to_string())
        }

        // WebSocket connection for pool monitoring
        async fn start_pool_monitor(&self) -> PyResult<()> {
            info!("Starting pool monitor...");
            
            let ws_stream = tokio_tungstenite::connect_async(&self.ws_url).await
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("WebSocket connection failed: {}", e)
                ))?;

            let (mut write, mut read) = ws_stream.0.split();

            // Subscribe to Raydium program updates
            let subscribe_msg = serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "programSubscribe",
                "params": [
                    RAYDIUM_PROGRAM_ID,
                    {
                        "encoding": "base64",
                        "commitment": "confirmed",
                        "filters": [
                            {
                                "memcmp": {
                                    "offset": 0,
                                    "bytes": TOKEN_PROGRAM_ID
                                }
                            }
                        ]
                    }
                ]
            });

            write.send(tokio_tungstenite::tungstenite::Message::Text(
                subscribe_msg.to_string()
            )).await.map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                format!("Subscribe failed: {}", e)
            ))?;

            // Process pool updates
            while let Some(msg) = read.next().await {
                match msg {
                    Ok(msg) => {
                        if let Ok(pool_data) = self.process_pool_message(&msg) {
                            if self.is_valid_opportunity(&pool_data).await? {
                                self.handle_trading_opportunity(pool_data).await?;
                            }
                        }
                    }
                    Err(e) => {
                        error!("WebSocket error: {}", e);
                        time::sleep(Duration::from_secs(1)).await;
                    }
                }
            }

            Ok(())
        }

        // Position monitoring and management
        async fn monitor_positions(&self) -> PyResult<()> {
            info!("Starting position monitor...");
            
            loop {
                for (token_mint, position) in self.active_positions.iter() {
                    match self.get_current_price(token_mint).await {
                        Ok(current_price) => {
                            // Check stop loss
                            if current_price <= position.stop_loss {
                                info!("Stop loss triggered for {}", token_mint);
                                self.execute_scalp(serde_json::to_string(&TradeInstruction {
                                    side: "sell".to_string(),
                                    size: position.size,
                                    price: current_price,
                                    pool_address: position.pool_address.clone(),
                                    token_mint: token_mint.clone(),
                                })?).await?;
                            }
                            // Check take profit
                            else if current_price >= position.take_profit {
                                info!("Take profit triggered for {}", token_mint);
                                self.execute_scalp(serde_json::to_string(&TradeInstruction {
                                    side: "sell".to_string(),
                                    size: position.size,
                                    price: current_price,
                                    pool_address: position.pool_address.clone(),
                                    token_mint: token_mint.clone(),
                                })?).await?;
                            }
                        }
                        Err(e) => error!("Error getting price for {}: {}", token_mint, e),
                    }
                }
                time::sleep(Duration::from_millis(100)).await;
            }
        }

        // Helper methods
        async fn get_helius_priority_fee(&self) -> PyResult<u64> {
            let url = format!(
                "https://api.helius.xyz/v0/priority-fee?api-key={}",
                self.config.helius_key
            );

            let response = self.http_client.get(&url)
                .send()
                .await
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?
                .json::<serde_json::Value>()
                .await
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

            Ok(response["priorityFee"].as_u64()
                .unwrap_or(self.config.priority_fee))
        }

        async fn is_valid_opportunity(&self, pool_data: &PoolData) -> PyResult<bool> {
            // Volume check
            if pool_data.volume_24h < self.config.min_volume {
                return Ok(false);
            }

            // Buy/Sell pressure ratio
            let bs_ratio = pool_data.buy_pressure as f64 / 
                         pool_data.sell_pressure.max(1) as f64;
            if bs_ratio < self.config.min_bs_ratio {
                return Ok(false);
            }

            // Liquidity check
            if pool_data.liquidity < self.config.min_liquidity {
                return Ok(false);
            }

            // Position size check
            let current_position = self.active_positions.values()
                .map(|p| p.size)
                .sum::<f64>();
            if current_position + self.config.position_size > self.config.max_position {
                return Ok(false);
            }

            Ok(true)
        }

        fn create_swap_instruction(
            &self,
            trade: &TradeInstruction,
            amount_lamports: u64
        ) -> PyResult<Instruction> {
            let pool_pubkey = Pubkey::from_str(&trade.pool_address)
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;

            // Calculate minimum amount out with slippage protection
            let minimum_out = if trade.side.to_lowercase() == "buy" {
                (amount_lamports as f64 * 0.995) as u64  // 0.5% slippage
            } else {
                (amount_lamports as f64 * 0.995) as u64
            };

            let mut instruction_data = vec![
                if trade.side.to_lowercase() == "buy" { 1u8 } else { 2u8 }
            ];
            instruction_data.extend_from_slice(&amount_lamports.to_le_bytes());
            instruction_data.extend_from_slice(&minimum_out.to_le_bytes());

            Ok(Instruction {
                program_id: Pubkey::from_str(RAYDIUM_PROGRAM_ID).unwrap(),
                accounts: vec![
                    AccountMeta::new(pool_pubkey, false),
                    AccountMeta::new(self.keypair.pubkey(), true),
                    AccountMeta::new_readonly(system_program::id(), false),
                ],
                data: instruction_data,
            })
        }
```

I'll continue with:
1. Position scaling implementation
2. Error handling and recovery
3. Performance monitoring
4. Additional helper functions

Would you like to see those parts next?  ```rust
        // Position scaling and performance tracking
        async fn handle_position_scaling(&mut self) -> PyResult<()> {
            let mut successful_trades = Vec::new();
            let mut trade_performance = HashMap::new();

            // Track scaling metrics
            #[derive(Default)]
            struct ScalingMetrics {
                successful_trades: u32,
                total_profit: f64,
                current_scale: f64,
            }

            let mut scaling_metrics = ScalingMetrics {
                successful_trades: 0,
                total_profit: 0.0,
                current_scale: self.config.position_size,
            };

            loop {
                // Clean old trades
                let now = chrono::Utc::now().timestamp();
                successful_trades.retain(|&timestamp| {
                    now - timestamp < 24 * 3600  // Keep last 24 hours
                });

                // Update metrics for completed trades
                for (token_mint, metrics) in trade_performance.iter() {
                    if metrics.successful_trades >= self.config.scaling_threshold {
                        let new_scale = scaling_metrics.current_scale + self.config.scaling_increment;
                        if new_scale <= self.config.max_position {
                            scaling_metrics.current_scale = new_scale;
                            info!(
                                "Scaling up position size to {} SOL after {} successful trades",
                                new_scale, metrics.successful_trades
                            );
                        }
                        trade_performance.remove(token_mint);
                    }
                }

                time::sleep(Duration::from_secs(60)).await;
            }
        }

        // Performance monitoring and error recovery
        async fn monitor_system_health(&self) -> PyResult<()> {
            let mut last_check = Instant::now();
            let mut consecutive_errors = 0;
            let mut rpc_latencies = HashMap::new();

            loop {
                if last_check.elapsed() >= Duration::from_secs(60) {
                    // Check RPC health
                    for (name, endpoint) in [
                        ("Marga", &self.marga_endpoint),
                        ("XYZ", &self.xyz_endpoint)
                    ].iter() {
                        let start = Instant::now();
                        match self.execute_rpc_request(|client| {
                            Ok(client.get_health()?)
                        }).await {
                            Ok(_) => {
                                let latency = start.elapsed().as_millis();
                                rpc_latencies.insert(*name, latency);
                                info!("{} RPC latency: {}ms", name, latency);
                                consecutive_errors = 0;
                            }
                            Err(e) => {
                                error!("{} RPC health check failed: {}", name, e);
                                consecutive_errors += 1;
                            }
                        }
                    }

                    // Check WebSocket connection
                    if let Err(e) = self.verify_websocket_connection().await {
                        error!("WebSocket connection error: {}", e);
                        consecutive_errors += 1;
                    }

                    // System metrics
                    info!("System Status:");
                    info!("Active Positions: {}", self.active_positions.len());
                    info!("Pool Cache Size: {}", self.pool_cache.len());
                    info!("RPC Latencies: {:?}", rpc_latencies);

                    // Error recovery
                    if consecutive_errors >= 3 {
                        warn!("Multiple consecutive errors detected, initiating recovery...");
                        self.initiate_recovery().await?;
                        consecutive_errors = 0;
                    }

                    last_check = Instant::now();
                }

                time::sleep(Duration::from_secs(1)).await;
            }
        }

        // Error recovery procedures
        async fn initiate_recovery(&self) -> PyResult<()> {
            info!("Starting system recovery...");

            // Close any at-risk positions
            for (token_mint, position) in self.active_positions.iter() {
                info!("Closing position for {} during recovery", token_mint);
                if let Err(e) = self.execute_scalp(serde_json::to_string(&TradeInstruction {
                    side: "sell".to_string(),
                    size: position.size,
                    price: position.entry_price,  // Market sell during recovery
                    pool_address: position.pool_address.clone(),
                    token_mint: token_mint.clone(),
                })?).await {
                    error!("Failed to close position during recovery: {}", e);
                }
            }

            // Clear caches
            self.pool_cache.clear();
            self.active_positions.clear();

            // Reconnect to WebSocket
            self.restart_websocket().await?;

            info!("Recovery complete");
            Ok(())
        }

        // WebSocket management
        async fn verify_websocket_connection(&self) -> PyResult<()> {
            let ws_stream = tokio_tungstenite::connect_async(&self.ws_url).await
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("WebSocket verification failed: {}", e)
                ))?;

            let (mut write, _) = ws_stream.0.split();

            // Send ping
            write.send(tokio_tungstenite::tungstenite::Message::Ping(vec![1]))
                .await
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("WebSocket ping failed: {}", e)
                ))?;

            Ok(())
        }

        async fn restart_websocket(&self) -> PyResult<()> {
            info!("Restarting WebSocket connection...");
            
            // Close existing connection if any
            // Start new connection
            self.start_pool_monitor().await
        }

        // Helper method to execute RPC requests with rate limiting
        async fn execute_rpc_request<F, T>(&self, request: F) -> PyResult<T>
        where
            F: Fn(&RpcClient) -> Result<T, Box<dyn std::error::Error>>,
        {
            // Try XYZ first (higher TPS)
            if self.can_use_rpc(&self.xyz_endpoint).await {
                match request(&self.xyz_rpc) {
                    Ok(result) => {
                        self.update_rpc_stats(&self.xyz_endpoint).await;
                        return Ok(result);
                    }
                    Err(_) => {}
                }
            }

            // Fallback to Marga
            if self.can_use_rpc(&self.marga_endpoint).await {
                match request(&self.marga_rpc) {
                    Ok(result) => {
                        self.update_rpc_stats(&self.marga_endpoint).await;
                        return Ok(result);
                    }
                    Err(e) => return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string())),
                }
            }

            Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>("Rate limit exceeded on all RPCs"))
        }
```

Would you like me to continue with:
1. More error handling and recovery scenarios
2. Additional performance optimizations
3. Detailed logging implementations
4. Any specific component you want to focus on?   // Finalize the main implementation with essential production components

        // Main entry point for Python
        #[pyo3(name = "start_trading")]
        fn py_start_trading(&mut self) -> PyResult<()> {
            info!("Initializing Solana scalping system...");
            
            // Create runtime for async operations
            let rt = tokio::runtime::Runtime::new()
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("Failed to create runtime: {}", e)
                ))?;

            // Run all core components
            rt.block_on(async {
                let mut tasks = vec![
                    tokio::spawn(self.start_pool_monitor()),
                    tokio::spawn(self.monitor_positions()),
                    tokio::spawn(self.handle_position_scaling()),
                    tokio::spawn(self.monitor_system_health())
                ];

                // Wait for any task to complete/fail
                if let Some(result) = futures::future::select_all(&mut tasks).await.0.ok() {
                    match result {
                        Ok(_) => info!("Trading system stopped normally"),
                        Err(e) => error!("Trading system error: {}", e),
                    }
                }

                Ok(())
            })
        }

        // Clean shutdown implementation
        fn shutdown(&mut self) -> PyResult<()> {
            info!("Initiating graceful shutdown...");

            // Close all positions
            let rt = tokio::runtime::Runtime::new()
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()))?;

            rt.block_on(async {
                for (token_mint, position) in self.active_positions.iter() {
                    info!("Closing position for {}", token_mint);
                    if let Err(e) = self.execute_scalp(serde_json::to_string(&TradeInstruction {
                        side: "sell".to_string(),
                        size: position.size,
                        price: position.entry_price,
                        pool_address: position.pool_address.clone(),
                        token_mint: token_mint.clone(),
                    })?).await {
                        error!("Failed to close position during shutdown: {}", e);
                    }
                }
                Ok(())
            })
        }

        // Get current status
        fn get_status(&self) -> PyResult<String> {
            let status = serde_json::json!({
                "active_positions": self.active_positions.len(),
                "cached_pools": self.pool_cache.len(),
                "current_balance": self.get_balance()?,
                "scaling_level": self.config.position_size,
            });

            Ok(status.to_string())
        }

        // Get balance implementation
        fn get_balance(&self) -> PyResult<f64> {
            self.marga_rpc.get_balance(&self.keypair.pubkey())
                .map(|b| b as f64 / 1e9)
                .map_err(|e| PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
                    format!("Failed to get balance: {}", e)
                ))
        }
}

#[pymodule]
fn solana_rust_bot(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
    // Initialize logging
    env_logger::init();
    
    // Register the ScalpingBot class
    m.add_class::<ScalpingBot>()?;
    
    Ok(())
}   please fix this to be all in the right format without text or anything that doesnt belong in the final script please and add logging where its most important okay thank you.