e "C:\solanarustbot\src\python\main.py", line 68, in start marketdata = await…
- User
e "C:\solana_rust_bot\src\python\main.py", line 68, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 30, in get_market_data 'prices': await self.trading_core.get_market_prices(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 94, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 89, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 68, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 30, in get_market_data 'prices': await self.trading_core.get_market_prices(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 94, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 89, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 68, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 30, in get_market_data 'prices': await self.trading_core.get_market_prices(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 94, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 89, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 68, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 30, in get_market_data 'prices': await self.trading_core.get_market_prices(), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 94, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 89, in main await bot.start()
- Assistant
The error message you provided indicates multiple issues occurring in your Python application, particularly when trying to retrieve market data. Let's break down the main issues and possible fixes:
1. AttributeError on
get_market_pricesAttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'This error means that the
TradingCoreclass does not have a method namedget_market_prices. Here are steps to address this error:-
Check the
TradingCoreClass: Make sure that theget_market_pricesmethod is implemented in theTradingCoreclass. If it isn't there, you need to create it. -
Check for Typos: Ensure there are no typos in the method name. The method is case-sensitive.
-
Check the Imports: Ensure that you are importing the correct
TradingCoreclass if you have multiple definitions or if it's defined in different modules. -
Verify Instantiation: Make sure that you are creating an instance of the
TradingCoreclass correctly. If it’s supposed to be an instance method, confirm that you are not mistakenly trying to access it as a class method.
2. Logging Error
The error message indicates a problem with your logging setup:
ValueError: Invalid format stringThis error often occurs when the logging configuration has an invalid date format. To fix this:
-
Check Your Logger Configuration: Look at how you've configured your logger, specifically the
datefmtparameter. Here’s how you might have set it up incorrectly:logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')Ensure that
datefmtis a correct format string. If there’s a mistake, correct it. -
Example of Correct Logger Configuration:
import logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' )
Summary of Actions
-
Fix the AttributeError:
- Check if the
get_market_pricesmethod exists in yourTradingCoreclass. - Correct any typos or incorrect method calls.
- Check if the
-
Fix the Logging Issue:
- Review the logging setup and ensure that the format string is correct.
- Test changing the
datefmtto a more basic format if you suspect issues there.
After making these changes, run your application again to see if the issues are resolved. If you encounter errors after addressing these points, please share the updated error messages for further assistance.
-
- User
use base64::{engine::general_purpose::STANDARD as base64_engine, Engine}; use dashmap::DashMap; use dotenv::dotenv; use log::{debug, error, info}; use pyo3::prelude::*; use pyo3::types::PyBytes; use reqwest::{header, Client}; use serde::{Deserialize, Serialize}; use solana_client::{rpc_client::RpcClient, rpc_config::RpcSendTransactionConfig}; use solana_sdk::{ commitment_config::CommitmentConfig, compute_budget::ComputeBudgetInstruction, instruction::{AccountMeta, Instruction}, message::Message, pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::Transaction, }; use std::collections::HashMap; use std::env; use std::str::FromStr; use std::sync::Arc; use std::time::{Duration, Instant}; use tokio::runtime::Runtime; use tokio::sync::Mutex;
const LAMPORTS_PER_SOL: u64 = 1_000_000_000; const MIN_PRIORITY_FEE: u64 = 500_000; const PRIORITY_FEE_INTERVAL: Duration = Duration::from_secs(30); const SOLANA_CLI_VERSION: &str = "solana-cli/1.18.23 (src:aeb3a2e1; feat:4215500110, client:SolanaLabs)";
#[derive(Debug, Serialize, Deserialize)] struct PriorityFeeResponse { jsonrpc: String, result: PriorityFeeResult, id: String, }
#[derive(Debug, Serialize, Deserialize)] struct PriorityFeeResult { priority_fee_estimate: Option, }
#[pyclass] #[derive(Clone, Debug)] pub struct PoolState { #[pyo3(get)] pub amm_id: String, #[pyo3(get)] pub authority: String, #[pyo3(get)] pub open_orders: String, #[pyo3(get)] pub target_orders: String, #[pyo3(get)] pub base_vault: String, #[pyo3(get)] pub quote_vault: String, #[pyo3(get)] pub market: String, #[pyo3(get)] pub bids: String, #[pyo3(get)] pub asks: String, #[pyo3(get)] pub event_queue: String, #[pyo3(get)] pub vault_signer: String, }
#[pyclass] #[derive(Deserialize, Clone, Debug)] pub struct TradeConfig { #[pyo3(get, set)] pub compute_limit: u32, #[pyo3(get, set)] pub priority_fee: u64, #[pyo3(get, set)] pub skip_preflight: bool, #[pyo3(get, set)] pub max_retries: u32, #[pyo3(get, set)] pub commitment: String, }
#[pymethods] impl TradeConfig { #[new] fn new() -> Self { Self { compute_limit: 800000, priority_fee: MIN_PRIORITY_FEE, skip_preflight: true, max_retries: 4, commitment: "confirmed".to_string(), } } }
#[pyclass] #[derive(Deserialize, Clone, Debug)] pub struct TradeParams { #[pyo3(get, set)] pub pool_address: String, #[pyo3(get, set)] pub amount_in: f64, #[pyo3(get, set)] pub min_amount_out: f64, #[pyo3(get, set)] pub wsol_account: String, }
#[pymethods] impl TradeParams { #[new] fn new( pool_address: String, amount_in: f64, min_amount_out: f64, wsol_account: String, ) -> Self { Self { pool_address, amount_in, min_amount_out, wsol_account, } } }
#[pyclass] pub struct TradingCore { client: Arc, keypair: Arc, pool_cache: Arc<DashMap<String, PoolState>>, http_client: Arc, config: Arc<Mutex>, last_priority_update: Arc<Mutex>, runtime: Arc, }
#[pymethods] impl TradingCore { #[new] #[pyo3(signature = (private_key_bytes))] fn new(private_key_bytes: &[u8]) -> PyResult { info!("Initializing TradingCore"); dotenv().ok();
let runtime = Arc::new(Runtime::new().unwrap()); let keypair = match Keypair::from_bytes(private_key_bytes) { Ok(keypair) => { info!("Created keypair with pubkey: {}", keypair.pubkey()); Arc::new(keypair) } Err(e) => { error!("Failed to create keypair: {}", e); return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>( "Invalid keypair bytes", )); } }; let rpc_url = env::var("RPC_URL").expect("RPC_URL not set"); info!("Connecting to RPC: {}", rpc_url); let client = RpcClient::new_with_commitment(rpc_url, CommitmentConfig::confirmed()); let http_client = Client::builder() .timeout(Duration::from_secs(30)) .default_headers({ let mut headers = header::HeaderMap::new(); headers.insert( "User-Agent", header::HeaderValue::from_static(SOLANA_CLI_VERSION), ); headers.insert( "Content-Type", header::HeaderValue::from_static("application/json"), ); headers }) .build() .map_err(|e| { error!("Failed to create HTTP client: {}", e); PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()) })?; Ok(Self { client: Arc::new(client), keypair, pool_cache: Arc::new(DashMap::new()), http_client: Arc::new(http_client), config: Arc::new(Mutex::new(TradeConfig::new())), last_priority_update: Arc::new(Mutex::new(Instant::now())), runtime, }) } fn get_mempool_data(&self) -> PyResult<Option<PyObject>> { Python::with_gil(|py| { Ok(None) }) } fn get_wsol_balance(&self, token_account: String) -> PyResult<f64> { let wsol_pubkey = match Pubkey::from_str(&token_account) { Ok(pubkey) => pubkey, Err(_) => { error!("Invalid WSOL account provided: {}", token_account); return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>( "Invalid WSOL account", )); } }; match self.client.get_token_account_balance(&wsol_pubkey) { Ok(balance) => { let amount = balance.ui_amount.unwrap_or(0.0); info!( "Retrieved WSOL balance for account {}: {}", token_account, amount ); Ok(amount) } Err(e) => { error!( "Failed to get WSOL balance for account {}: {}", token_account, e ); Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>( e.to_string(), )) } } } fn get_wallet_balance(&self) -> PyResult<f64> { match self.client.get_balance(&self.keypair.pubkey()) { Ok(balance) => { let sol_balance = balance as f64 / LAMPORTS_PER_SOL as f64; info!("Retrieved wallet balance: {} SOL", sol_balance); Ok(sol_balance) } Err(e) => { error!("Failed to get wallet balance: {}", e); Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>( e.to_string(), )) } } } fn update_config(&self, config: TradeConfig) -> PyResult<()> { let runtime = self.runtime.clone(); runtime.block_on(async { *self.config.lock().await = config; }); Ok(()) } fn execute_trade(&self, params: TradeParams) -> PyResult<Option<String>> { info!("Starting trade execution for pool: {}", params.pool_address); let runtime = self.runtime.clone(); let result = runtime.block_on(async { let config = self.config.lock().await; info!("Trade Parameters:"); info!("Pool Address: {}", params.pool_address); info!("Amount In: {}", params.amount_in); info!("Min Amount Out: {}", params.min_amount_out); info!("WSOL Account: {}", params.wsol_account); let pool = match self.pool_cache.get(¶ms.pool_address) { Some(pool) => { info!("Pool found in cache: {}", params.pool_address); pool } None => { error!("Pool not found in cache: {}", params.pool_address); return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>( format!("Pool not found in cache: {}", params.pool_address), )); } }; let priority_fee = self.get_helius_priority_fee().await?; info!("Priority fee retrieved: {}", priority_fee); let mut instructions = vec![ ComputeBudgetInstruction::set_compute_unit_limit(config.compute_limit), ComputeBudgetInstruction::set_compute_unit_price(priority_fee), ]; let amount_in = (params.amount_in * LAMPORTS_PER_SOL as f64) as u64; let min_amount_out = (params.min_amount_out * LAMPORTS_PER_SOL as f64) as u64; info!("Amounts in lamports - In: {}, Min Out: {}", amount_in, min_amount_out); let raydium_program_id = Pubkey::from_str( &env::var("RAYDIUM_PROGRAM_ID").expect("RAYDIUM_PROGRAM_ID not set"), ) .map_err(|e| { error!("Invalid Raydium program ID: {}", e); PyErr::new::<pyo3::exceptions::PyValueError, _>( format!("Invalid Raydium program ID: {}", e), ) })?; let swap_accounts = self.get_swap_accounts(&pool, ¶ms.wsol_account); info!("Swap accounts prepared: {} accounts", swap_accounts.len()); let swap_data = self.create_swap_data(amount_in, min_amount_out); info!("Swap data prepared: {} bytes", swap_data.len()); instructions.push(Instruction { program_id: raydium_program_id, accounts: swap_accounts, data: swap_data, }); let blockhash = self.client.get_latest_blockhash().map_err(|e| { error!("Failed to get blockhash: {}", e); PyErr::new::<pyo3::exceptions::PyRuntimeError, _>( format!("Blockhash retrieval failed: {}", e), ) })?; let message = Message::new(&instructions, Some(&self.keypair.pubkey())); let mut transaction = Transaction::new_unsigned(message); transaction.sign(&[&*self.keypair], blockhash); match self.client.send_and_confirm_transaction_with_spinner_and_config( &transaction, CommitmentConfig::from_str(&config.commitment).unwrap(), RpcSendTransactionConfig { skip_preflight: config.skip_preflight, preflight_commitment: None, encoding: None, max_retries: Some(config.max_retries as usize), min_context_slot: None, }, ) { Ok(signature) => { info!("Transaction successful: {}", signature); Ok(Some(signature.to_string())) } Err(e) => { error!("Transaction failed: {}", e); Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>( format!("Transaction failed: {}", e), )) } } }); result } fn update_pool(&self, pool_data: HashMap<String, String>) -> PyResult<()> { info!("Updating pool state with data: {:?}", pool_data); let pool_state = PoolState { amm_id: pool_data["amm_id"].clone(), authority: pool_data["amm_authority"].clone(), open_orders: pool_data["amm_open_orders"].clone(), target_orders: pool_data["amm_target"].clone(), base_vault: pool_data["pool_coin_token_account"].clone(), quote_vault: pool_data["pool_pc_token_account"].clone(), market: pool_data["serum_market"].clone(), bids: pool_data["serum_bids"].clone(), asks: pool_data["serum_asks"].clone(), event_queue: pool_data["serum_events"].clone(), vault_signer: pool_data["vault_signer"].clone(), }; self.pool_cache.insert(pool_data["amm_id"].clone(), pool_state); info!("Pool state updated successfully"); Ok(()) } fn subscribe_to_mempool(&self) -> PyResult<()> { // Placeholder logic for subscribing to the mempool info!("Subscribed to mempool"); // Return Ok to indicate successful subscription Ok(()) }}
impl TradingCore { async fn get_helius_priority_fee(&self) -> PyResult { let mut last_update = self.last_priority_update.lock().await; let now = Instant::now();
if now.duration_since(*last_update) < PRIORITY_FEE_INTERVAL { debug!( "Using cached priority fee: {}", self.config.lock().await.priority_fee ); return Ok(self.config.lock().await.priority_fee); } let helius_url = env::var("RPC_URL").expect("RPC_URL not set"); let request = serde_json::json!({ "jsonrpc": "2.0", "id": "helius-priority-fee", "method": "getPriorityFeeEstimate", "params": [{ "accountKeys": [env::var("RAYDIUM_PROGRAM_ID").expect("RAYDIUM_PROGRAM_ID not set")], "options": { "includeAllPriorityFeeLevels": false, "priorityLevel": "High" } }] }); let response = self .http_client .post(&helius_url) .json(&request) .send() .await .map_err(|e| { error!("Priority fee request failed: {}", e); PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(e.to_string()) })?; let fee_response: PriorityFeeResponse = response.json().await.map_err(|e| { error!("Failed to parse priority fee response: {}", e); PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()) })?; let fee = fee_response.result.priority_fee_estimate.unwrap_or(10000.0); *last_update = now; info!("Retrieved priority fee: {}", fee); Ok((fee.max(MIN_PRIORITY_FEE as f64)) as u64) } fn get_swap_accounts(&self, pool: &PoolState, wsol_account: &str) -> Vec<AccountMeta> { vec![ AccountMeta::new_readonly( Pubkey::from_str(&env::var("TOKEN_PROGRAM_ID").expect("TOKEN_PROGRAM_ID not set")) .expect("Invalid token program ID"), false, ), AccountMeta::new(Pubkey::from_str(&pool.amm_id).unwrap(), false), AccountMeta::new_readonly(Pubkey::from_str(&pool.authority).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.open_orders).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.target_orders).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.base_vault).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.quote_vault).unwrap(), false), AccountMeta::new_readonly(Pubkey::from_str(&pool.market).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.bids).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.asks).unwrap(), false), AccountMeta::new(Pubkey::from_str(&pool.event_queue).unwrap(), false), AccountMeta::new(Pubkey::from_str(wsol_account).unwrap(), false), AccountMeta::new(self.keypair.pubkey(), true), ] } fn create_swap_data(&self, amount_in: u64, min_amount_out: u64) -> Vec<u8> { let mut data = Vec::with_capacity(17); data.push(9); // Raydium swap instruction discriminator data.extend_from_slice(&amount_in.to_le_bytes()); data.extend_from_slice(&min_amount_out.to_le_bytes()); data }}
#[pymodule] fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> { dotenv().ok(); env_logger::init_from_env(env_logger::Env::default().default_filter_or("info"));
m.add_class::<TradingCore>()?; m.add_class::<TradeConfig>()?; m.add_class::<TradeParams>()?; m.add_class::<PoolState>()?; info!("solana_rust_bot module loaded successfully"); Ok(())}
- Assistant
This Rust code implements a Python extension using the PyO3 library and interacts with the Solana blockchain. It provides functionality for trading by retrieving the user's wallet balance, executing trades, updating pool data, and subscribing to the mempool. Let's go through the key components of your implementation to ensure everything is well understood and to identify areas for improvement or clarification.
Key Components Explanation
-
Dependencies:
- The code uses several libraries, including
reqwestfor HTTP requests,serdefor serialization/deserialization, andsolana_clientfor interacting with the Solana blockchain. It also usesdashmap,log, andpyo3, which are crucial for async operations, concurrent data structures, logging, and Python-C interoperability, respectively.
- The code uses several libraries, including
-
Data Structures:
- The
PriorityFeeResponseandTradeConfigstructs are defined usingserdeattributes to facilitate JSON serialization and deserialization for interacting with APIs. - The
PoolState,TradeParams, andTradingCorestructs are crucial for your application's logic. These hold relevant data such as pool information, trade parameters, and the core trading logic.
- The
-
Initialization:
- The
TradingCorestruct's initialization includes setting up an RPC client for Solana, reading environment variables usingdotenv, and initializing payment configurations, which helps maintain a clean environment for your trading operations.
- The
-
Key Methods:
get_wsol_balance: This retrieves the balance of Wrapped SOL (WSOL) for a specific token account.get_wallet_balance: It fetches the balance of SOL for the user's wallet.execute_trade: This method is central to your trading logic, performing all steps needed to execute a trade, including validating pool data, creating transaction instructions, and sending transactions to the Solana network.update_pool: Updates the pool information in a cache using the provided data.
-
Async Operations:
- The implementation uses async functions via
tokiofor making network requests and interacting with Solana's RPC API. This approach improves performance and responsiveness by preventing blocking I/O operations.
- The implementation uses async functions via
-
Priority Fee:
- The priority fee is fetched from an external source to help ensure that transactions are processed efficiently on the Solana network. This is critical for trading, where timing is essential.
Suggestions for Improvement
-
Error Handling: While you've implemented basic error handling, you might want to enrich the responses by providing more context in your error messages, particularly in areas where multiple things could go wrong, such as network requests. Consider implementing a custom error type to encapsulate more granular error states.
-
Logging Improvements: Ensure that your logging provides useful insights. For example, you can include more contextual data in your debug logs to trace operation flows effectively.
-
Testing: Make sure to implement unit tests to verify the functionality of your trading logic. Pay special attention to edge cases, such as handling invalid inputs or network failures.
-
Documentation: Add comments or documentation for the public methods to help future maintainers (or yourself) understand the purpose and functionality of different sections.
-
Security: Be cautious with how keys and sensitive data are handled, ensuring they are not accidentally logged. Consider mechanisms for securely managing secrets and sensitive configurations.
Conclusion
Overall, the implementation is structured well, and it appears to provide robust functionality for trading on the Solana blockchain. By focusing on areas like error handling, testing, and documentation, you can enhance maintainability and reliability. If you have specific questions or need guidance on any part of the implementation, feel free to ask!
-
- User
import os import base58 import psutil import torch import torch.amp as amp import asyncio from concurrent.futures import ThreadPoolExecutor from time import perf_counter_ns from typing import Dict, Optional from solana_rust_bot import TradingCore from config_loader import config from solana_logger import logger
class MarketDataManager: def init(self, trading_core): self.trading_core = trading_core self.last_update = 0 self._cache = { 'prices': [], 'volumes': [], 'timestamp': 0 }
async def get_market_data(self): current_time = perf_counter_ns() if current_time - self.last_update > 100_000_000: # 100ms refresh try: # Get market data from trading core self._cache = { 'prices': await self.trading_core.get_market_prices(), 'volumes': await self.trading_core.get_market_volumes(), 'timestamp': current_time } self.last_update = current_time except Exception as e: logger.warning(f"Market data fetch failed: {str(e)}") return self._cacheclass TradingBot: def init(self): # Hardware optimization self.p_cores = list(range(8)) psutil.Process().cpu_affinity(self.p_cores) self.device = torch.device('cuda') self.compute_streams = [torch.cuda.Stream() for _ in range(4)]
# Initialize trading core private_key = os.getenv('SOLANA_PRIVATE_KEY') if not private_key: raise ValueError("SOLANA_PRIVATE_KEY environment variable is required") private_key_bytes = base58.b58decode(private_key) self.trading_core = TradingCore(private_key_bytes=private_key_bytes) # Initialize market manager self.market_manager = MarketDataManager(self.trading_core) self.running = False logger.info("Trading bot initialized successfully") async def start(self): self.running = True logger.info("Trading bot started") print("\n🚀 Trading Bot Started") print(f"CPU: Intel i9-13900K") print(f"GPU: {torch.cuda.get_device_name()}") while self.running: try: market_data = await self.market_manager.get_market_data() if market_data['prices']: # Process market data with torch.cuda.stream(self.compute_streams[0]): result = await self.trading_core.process_market_data(market_data) if result: await self.trading_core.execute_trade(result) await asyncio.sleep(config.get('SCAN_INTERVAL', 0.001)) except Exception as e: logger.error(f"Trading loop error: {str(e)}") await asyncio.sleep(1) def stop(self): self.running = False logger.info("Trading bot stopped")async def main(): bot = TradingBot() try: await bot.start() except KeyboardInterrupt: bot.stop()
if name == "main": asyncio.run(main()) fix please
- Assistant
Based on the provided code snippet for the
TradingBotclass and its associatedMarketDataManager, I'll address some potential improvements and fixes to ensure that the bot runs smoothly. Here's a revised version of your code along with explanations of the changes made:Fixes and Changes
-
Check for Missing Methods: Ensure that methods like
get_market_prices,get_market_volumes, andprocess_market_dataexist in yourTradingCoreclass. If they do not exist, you'll need to implement them. -
Stream Management: The code initializes multiple CUDA streams but does not seem to utilize them effectively. If you plan to leverage these streams for parallel processing, you might need to adjust data processing accordingly.
-
Market Data Caching: The
get_market_datamethod updates_cacheonly if the update is successful. Make sure the code handles the scenario correctly when an exception is raised. -
Environment Variable Handling: Better handling of the
SOLANA_PRIVATE_KEYenvironment variable can enhance robustness. -
Fix Loop Logic: Make sure the trading loop handles errors gracefully without causing issues with continuous execution.
-
Configuration Handling: Ensure that the config dictionary is being accessed correctly.
Revised Code
Here’s a fixed and improved version of your
TradingBotandMarketDataManagerclasses:import os import base58 import psutil import torch import asyncio from time import perf_counter_ns from typing import Dict from solana_rust_bot import TradingCore from config_loader import config from solana_logger import logger class MarketDataManager: def __init__(self, trading_core): self.trading_core = trading_core self.last_update = 0 self._cache = { 'prices': [], 'volumes': [], 'timestamp': 0 } async def get_market_data(self): current_time = perf_counter_ns() if current_time - self.last_update > 100_000_000: # 100ms refresh try: # Get market data from trading core prices = await self.trading_core.get_market_prices() volumes = await self.trading_core.get_market_volumes() self._cache = { 'prices': prices, 'volumes': volumes, 'timestamp': current_time } self.last_update = current_time except Exception as e: logger.warning(f"Market data fetch failed: {str(e)}") return self._cache class TradingBot: def __init__(self): # Hardware optimization self.p_cores = list(range(psutil.cpu_count(logical=False))) # Use all available cores psutil.Process().cpu_affinity(self.p_cores) # Set device for computation self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Initialize trading core private_key = os.getenv('SOLANA_PRIVATE_KEY') if not private_key: raise ValueError("The SOLANA_PRIVATE_KEY environment variable is required") private_key_bytes = base58.b58decode(private_key) self.trading_core = TradingCore(private_key_bytes=private_key_bytes) # Initialize market manager self.market_manager = MarketDataManager(self.trading_core) self.running = False logger.info("Trading bot initialized successfully") async def start(self): self.running = True logger.info("Trading bot started") print("\n🚀 Trading Bot Started") print(f"CPU: Intel i9-13900K") print(f"GPU: {torch.cuda.get_device_name()}") while self.running: try: market_data = await self.market_manager.get_market_data() if market_data['prices']: # Process market data result = await self.trading_core.process_market_data(market_data) if result: await self.trading_core.execute_trade(result) await asyncio.sleep(config.get('SCAN_INTERVAL', 0.001)) # Ensure the SCAN_INTERVAL defaults correctly except Exception as e: logger.error(f"Trading loop error: {str(e)}") await asyncio.sleep(1) # Delay to avoid tight loop def stop(self): self.running = False logger.info("Trading bot stopped") async def main(): bot = TradingBot() try: await bot.start() except KeyboardInterrupt: bot.stop() if __name__ == "__main__": asyncio.run(main())Additional Considerations
-
Error Handling: Ensure that whatever operations are being performed in
process_market_dataandexecute_tradehave the appropriate error handling as well. This will help prevent failures from propagating and crashing your bot. -
Testing: After making changes, it's important to test the bot in a controlled environment before deploying it for live trading to ensure it behaves as expected.
-
Configuration Management: If you're using a specific configuration for your bot (like
SCAN_INTERVAL), make sure it's correctly set in yourconfigmodule to avoid runtime errors. -
Logger: Verify that the logger is set up correctly in your application to capture different levels of logs as desired.
Conclusion
These changes should improve the resilience and performance of your trading bot. Make sure to run this updated version in a safe environment first and monitor its behavior closely. If you encounter any more specific issues or errors, feel free to ask!
-
- User
Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 27, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 71, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 36, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 654, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\solana_rust_bot\src\python\main.py", line 92, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 78, in start await asyncio.sleep(config.get('SCAN_INTERVAL', 0.001)) # Ensure the SCAN_INTERVAL defaults correctly ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\tasks.py", line 649, in sleep return await future ^^^^^^^^^^^^ asyncio.exceptions.CancelledError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 97, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 123, in run raise KeyboardInterrupt() KeyboardInterrupt
- Assistant
The error message you're encountering indicates two main issues: an
AttributeErrorfor the methodget_market_prices, which is missing from yourTradingCoreobject, and a secondary issue related to logging that likely stems fromextraparameters not being handled correctly during logging.Let's break down how to address these problems step-by-step:
1. Fixing the AttributeError
The first error is due to the absence of the
get_market_pricesmethod in theTradingCoreclass. You need to ensure that:- The
TradingCoreclass has this method implemented. If it's not there, you'll need to add it:
#[pymethods] impl TradingCore { // Other methods... // Example implementation for get_market_prices pub async fn get_market_prices(&self) -> PyResult<Vec<f64>> { // Logic to fetch market prices, return a vector of prices // This is a placeholder, actual logic will depend on your trading setup Ok(vec![/* prices here */]) } // Similarly for get_market_volumes pub async fn get_market_volumes(&self) -> PyResult<Vec<f64>> { // Logic to fetch market volumes Ok(vec![/* volumes here */]) } }Ensure that the methods are implemented according to your needs. The example function above is just a placeholder.
2. Fixing the Logging Error
The logging error you're seeing is related to the
logmethod not being able to format the log message, specifically when it tries to format the timestamp (asctime). This indicates that the date format string supplied is likely invalid.Here are the steps to troubleshoot and fix the issue:
- Check your Logger Configuration: In the
solana_logger.py(or where you have configured your logging), ensure that thedatefmtparameter provided to the logging configuration is correct.
Here's an example of how to set up logging properly:
import logging import sys # Configure logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', handlers=[ logging.StreamHandler(sys.stderr), # Log to stderr ] )Make sure that the format and date format are correct and conform to Python's formatting expectations.
3. Graceful Handling of asyncio CancelledError
The
asyncio.exceptions.CancelledErroris raised when a coroutine is cancelled. It can occur when your bot receives a keyboard interrupt or other cancellation signals. You can handle this gracefully:In your
main()function, wrap the call toawait bot.start()with atry/exceptblock to catchasyncio.CancelledErrorspecifically:async def main(): bot = TradingBot() try: await bot.start() except asyncio.CancelledError: bot.stop() # Ensure you stop the bot gracefully except Exception as e: logger.error(f"An error occurred in the main loop: {str(e)}")This way, when the bot is interrupted, it can stop gracefully rather than propagate an unhandled exception.
Summary of Actions
-
Implement Missing Method: Ensure
get_market_pricesandget_market_volumesare implemented in yourTradingCoreclass. -
Validate Logger Configuration: Check and fix the
datefmtin your logging configuration. -
Handle Cancelling Errors: Update the
main()function to gracefully handleasyncio.CancelledError.
After implementing these changes, run the application again, and you should see improved stability without the current errors. If new issues arise or if there are any specific concerns, please provide the error messages or more details so that further assistance can be offered!
- The
- User
fix the main.py
- Assistant
Sure! Let's go ahead and fix
main.pyto address the issues you've been experiencing based on the error messages you've provided. The focus will be on resolving the missing method issue, improving error handling, and ensuring the logging works properly.Fixed
main.pyBelow is a revised version of
main.pythat addresses the highlighted issues:import os import base58 import psutil import torch import asyncio from time import perf_counter_ns from solana_rust_bot import TradingCore from config_loader import config from solana_logger import logger class MarketDataManager: def __init__(self, trading_core): self.trading_core = trading_core self.last_update = 0 self._cache = { 'prices': [], 'volumes': [], 'timestamp': 0 } async def get_market_data(self): current_time = perf_counter_ns() if current_time - self.last_update > 100_000_000: # 100ms refresh try: # Get market data from trading core prices = await self.trading_core.get_market_prices() volumes = await self.trading_core.get_market_volumes() self._cache = { 'prices': prices, 'volumes': volumes, 'timestamp': current_time } self.last_update = current_time except Exception as e: logger.warning(f"Market data fetch failed: {str(e)}") return self._cache class TradingBot: def __init__(self): # Hardware optimization self.p_cores = list(range(psutil.cpu_count(logical=False))) # Use all available cores psutil.Process().cpu_affinity(self.p_cores) # Set device for computation self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Initialize trading core private_key = os.getenv('SOLANA_PRIVATE_KEY') if not private_key: raise ValueError("The SOLANA_PRIVATE_KEY environment variable is required") private_key_bytes = base58.b58decode(private_key) self.trading_core = TradingCore(private_key_bytes=private_key_bytes) # Initialize market manager self.market_manager = MarketDataManager(self.trading_core) self.running = False logger.info("Trading bot initialized successfully") async def start(self): self.running = True logger.info("Trading bot started") print("\n🚀 Trading Bot Started") print(f"CPU: {psutil.cpu_count(logical=False)} cores") if torch.cuda.is_available(): print(f"GPU: {torch.cuda.get_device_name()}") while self.running: try: market_data = await self.market_manager.get_market_data() if market_data['prices']: # Process market data result = await self.trading_core.process_market_data(market_data) if result: await self.trading_core.execute_trade(result) await asyncio.sleep(config.get('SCAN_INTERVAL', 0.001)) # Ensure the SCAN_INTERVAL defaults correctly except asyncio.CancelledError: logger.info("Trading bot was stopped.") break # Graceful exit from the loop except Exception as e: logger.error(f"Trading loop error: {str(e)}") await asyncio.sleep(1) # Delay to avoid tight loop def stop(self): self.running = False logger.info("Trading bot stopped") async def main(): bot = TradingBot() try: await bot.start() except asyncio.CancelledError: bot.stop() # Ensure you call stop() gracefully except Exception as e: logger.error(f"An error occurred in the main loop: {str(e)}") if __name__ == "__main__": asyncio.run(main())Key Changes Made:
-
MarketDataManager Class:
- Ensure that
get_market_pricesandget_market_volumesmethods are assumed to be added to theTradingCoreclass. Make sure they exist in your Rust/Python interop.
- Ensure that
-
Error Handling:
- Added a specific
except asyncio.CancelledErrorto handle coroutine cancellations gracefully. - General exceptions are logged with a clear message format in the
startmethod ofTradingBot.
- Added a specific
-
Logger Configuration:
- Validation of your logger in
solana_logger.pyremains essential. Make sure thatdatefmtandformatare implemented correctly to avoid logging issues. - Example log configuration if needed:
import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) - Validation of your logger in
-
Device Handling:
- Added checks to confirm if CUDA is available to prevent errors if the script is run on a non-GPU machine.
-
Print Statements:
- More robust output for the CPU and GPU.
Conclusion
Make sure you have the relevant methods implemented in the
TradingCoreand that your logger is correctly configured to avoid logging-related errors. Once you make these adjustments, you should have a more robustmain.pythat allows your trading bot to run effectively. If you encounter more specific issues, please relay those, and we can further assist! -
- User
-- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 26, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 100, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 93, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 70, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 35, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 26, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 73, in emit if self.shouldRollover(record): ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging\handlers.py", line 196, in shouldRollover msg = "%s\n" % self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 100, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 93, in main await bot.start() File "C:\solana_rust_bot\src\python\main.py", line 70, in start market_data = await self.market_manager.get_market_data() File "C:\solana_rust_bot\src\python\main.py", line 35, in get_market_data logger.warning(f"Market data fetch failed: {str(e)}") File "C:\solana_rust_bot\src\python\solana_logger.py", line 76, in warning self._log(logging.WARNING, message, extra) File "C:\solana_rust_bot\src\python\solana_logger.py", line 63, in _log self.logger.log( Message: "Market data fetch failed: 'builtins.TradingCore' object has no attribute 'get_market_prices'" Arguments: () --- Logging error --- Traceback (most recent call last): File "C:\solana_rust_bot\src\python\main.py", line 26, in get_market_data prices = await self.trading_core.get_market_prices() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'builtins.TradingCore' object has no attribute 'get_market_prices'
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 1110, in emit msg = self.format(record) ^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 953, in format return fmt.format(record) ^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 689, in format record.asctime = self.formatTime(record, self.datefmt) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\logging_init_.py", line 626, in formatTime s = time.strftime(datefmt, ct) ^^^^^^^^^^^^^^^^^^^^^^^^^^ ValueError: Invalid format string Call stack: File "C:\solana_rust_bot\src\python\main.py", line 100, in asyncio.run(main()) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 190, in run return runner.run(main) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 641, in run_until_complete self.run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\windows_events.py", line 321, in run_forever super().run_forever() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 608, in run_forever self._run_once() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\base_events.py", line 1936, in _run_once handle._run() File "C:\Users\Orsen\anaconda3\envs\quantum_beast\Lib\asyncio\events.py", line 84, in _run self._context.run(self._callback, *self._args) File "C:\solana_rust_bot\src\python\main.py", line 93, fix last chance
- Assistant
Based on the latest error traceback you provided, the main issues can be summarized as follows:
-
Missing Method
get_market_pricesin yourTradingCoreclass: This method needs to be implemented in Rust and exposed to Python to provide market prices. -
Invalid Format String in Logging: The logging configuration has an invalid date format string causing
ValueError.
Let's address these issues directly:
Step 1: Implement Missing Methods in
TradingCoreMake sure you have these methods implemented in your Rust code that corresponds to your
TradingCoreclass. Here’s an example implementation:#[pymethods] impl TradingCore { // Other methods... // Assuming you have some way to fetch market prices pub async fn get_market_prices(&self) -> PyResult<Vec<f64>> { // Simulated fetching of market prices // Replace with actual fetching logic Ok(vec![1.0, 2.0, 3.0]) // Replace with real price data } pub async fn get_market_volumes(&self) -> PyResult<Vec<f64>> { // Simulated fetching of market volumes Ok(vec![100.0, 200.0, 300.0]) // Replace with real volume data } }Step 2: Fix Logging Configuration
To avoid the
ValueErrorregarding the invalid format string, check your logging setup in thesolana_logger.pyfile or wherever you configure the logger. Here’s a basic example of a proper configuration:import logging # Set up logging in your solana_logger.py or main.py logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', # Standard log format datefmt='%Y-%m-%d %H:%M:%S', # Correct date format )Step 3: Revised
main.pyAfter ensuring that both the methods in
TradingCoreare set up and your logging functionality is established correctly, here’s the finalizedmain.pyfor your trading bot:import os import base58 import psutil import torch import asyncio from time import perf_counter_ns from solana_rust_bot import TradingCore from config_loader import config from solana_logger import logger class MarketDataManager: def __init__(self, trading_core): self.trading_core = trading_core self.last_update = 0 self._cache = { 'prices': [], 'volumes': [], 'timestamp': 0 } async def get_market_data(self): current_time = perf_counter_ns() if current_time - self.last_update > 100_000_000: # 100ms refresh try: # Get market data from trading core prices = await self.trading_core.get_market_prices() volumes = await self.trading_core.get_market_volumes() self._cache = { 'prices': prices, 'volumes': volumes, 'timestamp': current_time } self.last_update = current_time except Exception as e: logger.warning(f"Market data fetch failed: {str(e)}") return self._cache class TradingBot: def __init__(self): # Hardware optimization self.p_cores = list(range(psutil.cpu_count(logical=False))) # Use all available cores psutil.Process().cpu_affinity(self.p_cores) # Set device for computation self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # Initialize trading core private_key = os.getenv('SOLANA_PRIVATE_KEY') if not private_key: raise ValueError("The SOLANA_PRIVATE_KEY environment variable is required") private_key_bytes = base58.b58decode(private_key) self.trading_core = TradingCore(private_key_bytes=private_key_bytes) # Initialize market manager self.market_manager = MarketDataManager(self.trading_core) self.running = False logger.info("Trading bot initialized successfully") async def start(self): self.running = True logger.info("Trading bot started") print("\n🚀 Trading Bot Started") print(f"CPU: {psutil.cpu_count(logical=False)} cores") if torch.cuda.is_available(): print(f"GPU: {torch.cuda.get_device_name()}") while self.running: try: market_data = await self.market_manager.get_market_data() if market_data['prices']: # Process market data result = await self.trading_core.process_market_data(market_data) if result: await self.trading_core.execute_trade(result) await asyncio.sleep(config.get('SCAN_INTERVAL', 0.001)) # Ensure the SCAN_INTERVAL defaults correctly except asyncio.CancelledError: logger.info("Trading bot was stopped.") break # Graceful exit from the loop except Exception as e: logger.error(f"Trading loop error: {str(e)}") await asyncio.sleep(1) # Delay to avoid tight loop def stop(self): self.running = False logger.info("Trading bot stopped") async def main(): bot = TradingBot() try: await bot.start() except asyncio.CancelledError: bot.stop() # Ensure you call stop() gracefully except Exception as e: logger.error(f"An error occurred in the main loop: {str(e)}") if __name__ == "__main__": asyncio.run(main())Summary
- Method Implementation: Ensure
get_market_pricesandget_market_volumesare correctly implemented and returning real data in yourTradingCore. - Logging Configuration: Ensure the logger configuration has a valid
datefmtto preventValueError. - Testing: Run your application after implementing these changes and monitor for any further exceptions. If new issues arise, please share those details for further assistance.
-