import asyncio
import logging
from pathlib import Path
import time
from config import Config
from config_validator import ConfigValidator
from quantum_optimized import QuantumOptimized
from monitor import MonitorServer
from dashboard_server import DashboardServer
import os
import sys
import json
from typing import Optional, Dict, Tuple
def setup_logging() -> None:
"""Configure logging with timestamp and both file/console output"""
log_format = '%(asctime)s | %(levelname)s | %(message)s'
# System checks
verify_system()
config_path = verify_config()
# Initialize components
config, quantum_system, monitor, dashboard = await initialize_components(config_path)
# Get initial balance
initial_balance = await quantum_system.market_data.get_balance()
logger.info(f"Initial balance: {initial_balance:.6f} SOL")
if initial_balance < 0.025:
raise ValueError(f"Insufficient balance: {initial_balance:.6f} SOL")
# Log startup configuration
logger.info("\n=== System Configuration ===")
logger.info(f"Initial Balance: {initial_balance:.6f} SOL")
logger.info(f"Position Size: {config.trading.get('position_size')} SOL")
logger.info(f"Max Position: {config.trading.get('max_position')} SOL")
logger.info(f"Batch Size: {config.system.get('batch_size')}")
logger.info(f"GPU Threads: {config.system.get('gpu_threads')}")
logger.info("Dashboard URL: ws://localhost:8766\n")
# Start all services
async with asyncio.TaskGroup() as tg:
tg.create_task(monitor.start_server())
tg.create_task(dashboard.start_server())
tg.create_task(quantum_system.start())
logger.info("All systems operational! Press Ctrl+C to stop.")
while True:
await asyncio.sleep(1)
except* asyncio.CancelledError:
logger.info("System shutdown initiated")
except* Exception as e:
logger.error(f"Fatal error: {e}", exc_info=True)
raise
finally:
# Cleanup and final status
logger.info("Cleaning up resources...")
try:
if 'quantum_system' in locals():
await quantum_system.cleanup()
final_balance = await quantum_system.market_data.get_balance()
profit = ((final_balance - initial_balance) / initial_balance) * 100
logger.info(f"Final balance: {final_balance:.6f} SOL")
logger.info(f"Session profit: {profit:.2f}%")
except Exception as e:
logger.error(f"Cleanup error: {e}")
if name == "main":
try:
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
except KeyboardInterrupt:
print("\nShutdown requested... closing system.")
except Exception as e:
print(f"Unexpected error: {e}")
raise
To add maximum logging functionality to main.py, you'll want to make some adjustments to the logging level setup and ensure comprehensive logs throughout various parts of your code. Below, I've modified your setup_logging function to set the logging level to DEBUG, added debug logs in several key places throughout your code, and ensured that all parts of your main() function are adequately logged. Here's the updated code:
python
# main.py
import asyncio
import logging
from pathlib import Path
import time
from config import Config
from config_validator import ConfigValidator
from quantum_optimized import QuantumOptimized
from monitor import MonitorServer
from dashboard_server import DashboardServer
import os
import sys
import json
from typing import Optional, Dict, Tuple
def setup_logging() -> None:
"""Configure logging with timestamp and both file/console output"""
log_format = '%(asctime)s | %(levelname)s | %(message)s'
# Create logs directory
Path("logs").mkdir(exist_ok=True)
timestamp = time.strftime('%Y%m%d_%H%M%S')
# Configure handlers
file_handler = logging.FileHandler(
f"logs/quantum_{timestamp}.log",
encoding='utf-8'
)
console_handler = logging.StreamHandler()
# Set formatting
formatter = logging.Formatter(log_format)
file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# Configure root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG) # Set to DEBUG for maximum logging
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
# Suppress noisy logs
logging.getLogger("websockets").setLevel(logging.WARNING)
logging.getLogger("asyncio").setLevel(logging.WARNING)
def verify_system() -> None:
"""Verify system requirements and GPU availability"""
import torch
logger = logging.getLogger(__name__)
logger.debug("Verifying system requirements.")
if not torch.cuda.is_available():
logger.critical("CUDA not available. GPU required for trading.")
raise RuntimeError("CUDA not available. GPU required for trading.")
device_props = torch.cuda.get_device_properties(0)
logger.info(f"GPU: {device_props.name}")
logger.info(f"CUDA Version: {torch.version.cuda}")
logger.info(f"PyTorch Version: {torch.__version__}")
logger.info(f"GPU Memory: {device_props.total_memory / 1024**3:.1f}GB")
if device_props.total_memory < 8 * 1024**3: # 8GB
logger.warning(f"Low GPU memory: {device_props.total_memory / 1024**3:.1f}GB. 8GB+ recommended.")
def verify_config() -> str:
"""Verify configuration files and paths"""
logger = logging.getLogger(__name__)
logger.debug("Verifying configuration file.")
config_path = str(Path(__file__).parent.parent.parent / "config.json")
if not Path(config_path).exists():
logger.critical(f"Config file not found at {config_path}")
raise FileNotFoundError(f"Config file not found at {config_path}")
try:
with open(config_path, 'r') as f:
config_data = json.load(f)
trading_config = config_data.get('trading', {})
required_tps_fields = {
'trades_per_second',
'max_trades_per_second',
'tps_increment',
'tps_increment_interval'
}
missing_fields = required_tps_fields - set(trading_config.keys())
if missing_fields:
logger.error(f"Missing TPS config fields: {missing_fields}")
raise ValueError("Missing required TPS configuration fields")
if not 0 < trading_config['trades_per_second'] <= trading_config['max_trades_per_second']:
logger.error("Invalid trades_per_second range.")
raise ValueError("Invalid trades_per_second range")
if trading_config['tps_increment'] <= 0:
logger.error("TPS increment must be positive.")
raise ValueError("TPS increment must be positive")
if trading_config['tps_increment_interval'] <= 0:
logger.error("TPS increment interval must be positive.")
raise ValueError("TPS increment interval must be positive")
config = Config.load(config_path)
if not config.validate():
logger.error("Failed to validate core configuration.")
raise ValueError("Failed to validate core configuration")
keypair_path = Path(config.wallet.get('keypair_path', ''))
if not keypair_path.exists():
logger.critical(f"Keypair file not found at {keypair_path}")
raise FileNotFoundError(f"Keypair file not found at {keypair_path}")
if not config.rpc.get('primary', {}).get('endpoint'):
logger.critical("Missing primary RPC endpoint.")
raise ValueError("Missing primary RPC endpoint")
logger.info("Configuration validated successfully.")
return config_path
except Exception as e:
logger.error(f"Config verification error: {str(e)}")
raise
async def initialize_components(config_path: str) -> Tuple[Config, QuantumOptimized, MonitorServer, DashboardServer]:
"""Initialize system components"""
logger = logging.getLogger(__name__)
logger.debug("Initializing system components.")
try:
config = Config.load(config_path)
quantum_system = QuantumOptimized(config)
monitor = MonitorServer(
trading_core=quantum_system.market_data.core,
market_data=quantum_system.market_data,
ml_engine=quantum_system.ml_engine,
groq_analyzer=quantum_system.groq_analyzer
)
dashboard = DashboardServer(
trading_core=quantum_system.market_data.core,
market_data=quantum_system.market_data,
ml_engine=quantum_system.ml_engine,
groq_analyzer=quantum_system.groq_analyzer
)
logger.info("System components initialized successfully.")
return config, quantum_system, monitor, dashboard
except Exception as e:
logger.error(f"Failed to initialize components: {e}", exc_info=True)
raise
async def main() -> None:
initial_balance = 0.0
try:
setup_logging()
logger = logging.getLogger(__name__)
logger.info("🚀 Starting Quantum Trading System")
# System checks
logger.debug("Starting system checks.")
verify_system()
config_path = verify_config()
# Initialize components
logger.debug("Initializing components.")
config, quantum_system, monitor, dashboard = await initialize_components(config_path)
initial_balance = await quantum_system.market_data.get_balance()
logger.info(f"Initial balance: {initial_balance:.6f} SOL")
if initial_balance < 0.025:
logger.critical(f"Insufficient balance: {initial_balance:.6f} SOL")
raise ValueError(f"Insufficient balance: {initial_balance:.6f} SOL")
logger.info("\n=== System Configuration ===")
logger.info(f"Initial Balance: {initial_balance:.6f} SOL")
logger.info(f"Position Size: {config.trading.get('position_size')} SOL")
logger.info(f"Max Position: {config.trading.get('max_position')} SOL")
logger.info(f"Batch Size: {config.system.get('batch_size')}")
logger.info(f"GPU Threads: {config.system.get('gpu_threads')}")
logger.info("Dashboard URL: ws://localhost:8766\n")
async with asyncio.TaskGroup() as tg:
tg.create_task(monitor.start_server())
tg.create_task(dashboard.start_server())
tg.create_task(quantum_system.start())
logger.info("All systems operational! Press Ctrl+C to stop.")
while True:
await asyncio.sleep(1)
except asyncio.CancelledError:
logger.info("System shutdown initiated")
except Exception as e:
logger.critical(f"Fatal error: {e}", exc_info=True)
raise
finally:
logger.info("Cleaning up resources...")
try:
if 'quantum_system' in locals():
await quantum_system.cleanup()
final_balance = await quantum_system.market_data.get_balance()
profit = ((final_balance - initial_balance) / initial_balance) * 100
logger.info(f"Final balance: {final_balance:.6f} SOL")
logger.info(f"Session profit: {profit:.2f}%")
except Exception as e:
logger.error(f"Cleanup error: {e}", exc_info=True)
if __name__ == "__main__":
try:
if sys.platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
except KeyboardInterrupt:
print("\nShutdown requested... closing system.")
except Exception as e:
print(f"Unexpected error: {e}")
raise
Changes Made:
Logging Level: Changed the root logging level to DEBUG to capture all log messages.
Debug Information: Added debug logs at various points to provide detailed insights into what the application is doing at each stage, including start and completion of key procedures.
Exception Logs: Enhanced exception handling logs to include exc_info=True to provide stack traces, making troubleshooting easier.
Now, when the application runs, it will produce a very detailed log output that can help track down issues and understand the flow of the application better.
add maximum logging please use pyo3::prelude::*;
use solana_client::{rpc_client::RpcClient, client_error::ClientError};
use solana_sdk::{
commitment_config::CommitmentConfig,
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
instruction::Instruction,
compute_budget::ComputeBudgetInstruction,
};
use std::{
str::FromStr,
collections::HashMap,
sync::Arc,
time::Duration,
fs,
path::Path,
};
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
use serde_json;
use log::{info, error};
To enhance the logging capabilities in your Rust code using log crate and ensure maximum logging for your Solana trading bot, you can add logging statements to various parts of the application. Here's your code with enhanced logging:
rust
use pyo3::prelude::*;
use solana_client::{rpc_client::RpcClient, client_error::ClientError};
use solana_sdk::{
commitment_config::CommitmentConfig,
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
instruction::Instruction,
compute_budget::ComputeBudgetInstruction,
};
use std::{
str::FromStr,
collections::HashMap,
sync::Arc,
time::Duration,
fs,
path::Path,
};
use tokio::sync::RwLock;
use serde::{Deserialize, Serialize};
use serde_json;
use log::{info, error, debug, warn};
#[derive(Debug, Serialize, Deserialize, Clone)]
struct PoolMetrics {
pool_address: String,
token_mint: String,
volume_24h: f64,
liquidity: f64,
price: f64,
buy_pressure: u64,
sell_pressure: u64,
mint_authority_revoked: bool,
liquidity_locked_pct: f64,
market_cap: f64,
}
#[derive(Debug, Deserialize, Clone)]
struct Config {
rpc: RpcConfig,
wallet: WalletConfig,
trading: TradingConfig,
system: SystemConfig,
safety: SafetyConfig,
}
#[derive(Debug, Deserialize, Clone)]
struct SafetyConfig {
mint_auth_required: bool,
lp_lock_check: bool,
holder_check: bool,
max_holder_percent: f64,
blacklist_threshold: u32,
volume_spike_threshold: f64,
price_spike_threshold: f64,
market_cap_min: f64,
}
#[derive(Debug, Deserialize, Clone)]
struct RpcConfig {
primary: PrimaryRpcConfig,
secondary: SecondaryRpcConfig,
websocket: WebsocketConfig,
}
#[derive(Debug, Deserialize, Clone)]
struct PrimaryRpcConfig {
endpoint: String,
timeout: u64,
retry_count: u32,
}
#[derive(Debug, Deserialize, Clone)]
struct SecondaryRpcConfig {
endpoint: String,
api_key: String,
timeout: u64,
retry_count: u32,
}
#[derive(Debug, Deserialize, Clone)]
struct WebsocketConfig {
endpoint: String,
timeout: u64,
}
#[derive(Debug, Deserialize, Clone)]
struct WalletConfig {
keypair_path: String,
address: String,
}
#[derive(Debug, Deserialize, Clone)]
struct TradingConfig {
token_mint: String,
position_size: f64,
max_position: f64,
gas_reserve: f64,
priority_fee: u64,
compute_limit: u32,
min_volume: f64,
min_bs_ratio: f64,
min_liquidity: f64,
max_liquidity: f64,
liquidity_lock_min: f64,
max_holder_pct: f64,
trade_amount: u64,
take_profit: f64,
stop_loss: f64,
}
#[derive(Debug, Deserialize, Clone)]
struct SystemConfig {
gpu_threads: u32,
batch_size: u32,
vector_dim: u32,
}
#[pyclass]
struct TradingCore {
config: Arc<Config>,
primary_rpc: RpcClient,
secondary_rpc: RpcClient,
keypair: Keypair,
pool_metrics: Arc<RwLock<HashMap<String, PoolMetrics>>>,
}
// Load keypair with logging
fn load_keypair(keypair_path: &str) -> PyResult<Keypair> {
let path = Path::new(keypair_path);
info!("Loading keypair from: {}", path.display());
let keypair_str = fs::read_to_string(path)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Failed to read keypair file: {}", e)
))?;
debug!("Keypair file content: {}", keypair_str);
let keypair_data: Vec<u8> = serde_json::from_str(&keypair_str)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Failed to parse keypair JSON: {}", e)
))?;
if keypair_data.len() != 64 {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Invalid keypair length: {}. Expected 64 bytes.", keypair_data.len())
));
}
let keypair_bytes: [u8; 64] = keypair_data.try_into()
.map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>(
"Failed to convert keypair to fixed length array"
))?;
Keypair::from_bytes(&keypair_bytes)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Invalid keypair data: {}", e)
))
}
// TradingCore methods with logging
#[pymethods]
impl TradingCore {
#[new]
fn new() -> PyResult<Self> {
info!("Initializing TradingCore...");
let config_path = "config.json";
let config_str = fs::read_to_string(config_path)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Failed to read config file: {}", e)
))?;
debug!("Config file content: {}", config_str);
let config: Config = serde_json::from_str(&config_str)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Failed to parse config: {}", e)
))?;
let keypair = load_keypair(&config.wallet.keypair_path)?;
let wallet_pubkey = Pubkey::from_str(&config.wallet.address)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Invalid wallet address: {}", e)
))?;
if keypair.pubkey() != wallet_pubkey {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
format!("Keypair pubkey ({}) does not match config wallet address ({})",
keypair.pubkey(), wallet_pubkey)
));
}
let primary_rpc = RpcClient::new_with_timeout_and_commitment(
&config.rpc.primary.endpoint,
Duration::from_secs(config.rpc.primary.timeout),
CommitmentConfig::confirmed(),
);
info!("Primary RPC client initialized with endpoint: {}", config.rpc.primary.endpoint);
let secondary_rpc = RpcClient::new_with_timeout_and_commitment(
&format!("{}?api-key={}", config.rpc.secondary.endpoint, config.rpc.secondary.api_key),
Duration::from_secs(config.rpc.secondary.timeout),
CommitmentConfig::confirmed(),
);
info!("Secondary RPC client initialized with endpoint: {}", config.rpc.secondary.endpoint);
Ok(Self {
config: Arc::new(config),
primary_rpc,
secondary_rpc,
keypair,
pool_metrics: Arc::new(RwLock::new(HashMap::new())),
})
}
#[getter]
fn get_balance(&self) -> PyResult<f64> {
info!("Getting balance for pubkey: {}", self.keypair.pubkey());
let mut last_error = None;
let pubkey = self.keypair.pubkey();
for _ in 0..self.config.rpc.primary.retry_count {
match self.primary_rpc.get_balance(&pubkey) {
Ok(balance) => {
info!("Balance retrieved successfully: {}", balance);
return Ok(balance as f64 / 1e9);
},
Err(e) => {
last_error = Some(e);
error!("Failed to get balance from primary RPC: {:?}", e);
std::thread::sleep(Duration::from_millis(100));
}
}
}
for _ in 0..self.config.rpc.secondary.retry_count {
match self.secondary_rpc.get_balance(&pubkey) {
Ok(balance) => {
info!("Balance retrieved successfully from secondary RPC: {}", balance);
return Ok(balance as f64 / 1e9);
},
Err(e) => {
last_error = Some(e);
error!("Failed to get balance from secondary RPC: {:?}", e);
std::thread::sleep(Duration::from_millis(100));
}
}
}
Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
format!("Failed to get balance: {:?}", last_error)
))
}
fn update_pool_metrics(&self, pool_data: String) -> PyResult<bool> {
info!("Updating pool metrics with data: {}", pool_data);
let metrics: PoolMetrics = serde_json::from_str(&pool_data)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
debug!("Pool metrics parsed: {:?}", metrics);
if self.internal_validate_pool_metrics(&metrics) {
let mut pools = self.pool_metrics.blocking_write();
pools.insert(metrics.token_mint.clone(), metrics);
info!("Pool metrics updated for token mint: {}", metrics.token_mint);
Ok(true)
} else {
warn!("Validation failed for pool metrics: {:?}", metrics);
Ok(false)
}
}
fn execute_trade(&self, instructions: String) -> PyResult<String> {
info!("Executing trade with instructions: {}", instructions);
let instructions: Vec<Instruction> = serde_json::from_str(&instructions)
.map_err(|e| PyErr::new::<pyo3::exceptions::PyValueError, _>(e.to_string()))?;
let compute_ix = ComputeBudgetInstruction::set_compute_unit_limit(
self.config.trading.compute_limit
);
let priority_ix = ComputeBudgetInstruction::set_compute_unit_price(
self.config.trading.priority_fee
);
let mut final_instructions = vec![compute_ix, priority_ix];
final_instructions.extend(instructions);
for retry in 0..self.config.rpc.primary.retry_count {
match self.internal_try_execute_trade(&final_instructions) {
Ok(sig) => {
info!("Trade executed successfully with signature: {}", sig);
return Ok(sig);
}
Err(e) => {
error!("Primary RPC trade failed (attempt {} of {}): {:?}", retry + 1, self.config.rpc.primary.retry_count, e);
std::thread::sleep(Duration::from_millis(100));
}
}
}
for retry in 0..self.config.rpc.secondary.retry_count {
match self.internal_try_execute_trade_secondary(&final_instructions) {
Ok(sig) => {
info!("Trade executed on secondary RPC with signature: {}", sig);
return Ok(sig);
}
Err(e) => {
error!("Secondary RPC trade failed (attempt {} of {}): {:?}", retry + 1, self.config.rpc.secondary.retry_count, e);
if retry == self.config.rpc.secondary.retry_count - 1 {
return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
format!("Failed to execute trade: {:?}", e)
));
}
std::thread::sleep(Duration::from_millis(100));
}
}
}
Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
"Failed to execute trade after all retries"
))
}
fn get_status(&self) -> PyResult<String> {
info!("Getting system status...");
let pools = self.pool_metrics.blocking_read();
let status = serde_json::json!({
"active_pools": pools.len(),
"wallet_balance": self.get_balance()?,
"position_size": self.config.trading.position_size,
"max_position": self.config.trading.max_position,
"gas_reserve": self.config.trading.gas_reserve,
"compute_limit": self.config.trading.compute_limit,
"priority_fee": self.config.trading.priority_fee
});
info!("Current status: {:?}", status);
Ok(status.to_string())
}
}
// Internal implementations with logging
impl TradingCore {
fn internal_validate_pool_metrics(&self, metrics: &PoolMetrics) -> bool {
info!("Validating pool metrics: {:?}", metrics);
let is_valid = metrics.market_cap >= self.config.safety.market_cap_min
&& metrics.volume_24h >= self.config.trading.min_volume
&& metrics.liquidity >= self.config.trading.min_liquidity
&& metrics.liquidity <= self.config.trading.max_liquidity
&& (metrics.buy_pressure as f64 / metrics.sell_pressure.max(1) as f64) >= self.config.trading.min_bs_ratio
&& metrics.mint_authority_revoked
&& metrics.liquidity_locked_pct >= self.config.trading.liquidity_lock_min;
if is_valid {
info!("Pool metrics validated successfully.");
} else {
warn!("Pool metrics validation failed.");
}
is_valid
}
fn internal_try_execute_trade(&self, instructions: &[Instruction]) -> Result<String, ClientError> {
info!("Trying to execute trade on primary RPC...");
let recent_blockhash = self.primary_rpc.get_latest_blockhash()?;
let tx = Transaction::new_signed_with_payer(
instructions,
Some(&self.keypair.pubkey()),
&[&self.keypair],
recent_blockhash,
);
let signature = self.primary_rpc.send_and_confirm_transaction(&tx)?;
info!("Trade executed on primary RPC with signature: {}", signature);
Ok(signature.to_string())
}
fn internal_try_execute_trade_secondary(&self, instructions: &[Instruction]) -> Result<String, ClientError> {
info!("Trying to execute trade on secondary RPC...");
let recent_blockhash = self.secondary_rpc.get_latest_blockhash()?;
let tx = Transaction::new_signed_with_payer(
instructions,
Some(&self.keypair.pubkey()),
&[&self.keypair],
recent_blockhash,
);
let signature = self.secondary_rpc.send_and_confirm_transaction(&tx)?;
info!("Trade executed on secondary RPC with signature: {}", signature);
Ok(signature.to_string())
}
}
#[pymodule]
fn solana_rust_bot(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
m.add_class::<TradingCore>()?;
Ok(())
}
Key Enhancements Made:
Added Debug and Info Logs: Throughout the code, info!, debug!, and error! logs were added to capture key operations, outcomes, and error states.
Function Entry and Exit Logging: Logging was added at the entry and exit of significant functions, helping to trace the flow of execution.
Data Logging: Important data points are logged, such as configurations loaded, keypair validation results, and RPC response handling.
Condition Logging: Logging both successful and failed validations or operations provides transparency in how the data is processed and issues are diagnosed.
Final Notes:
Make sure to set up your logging environment to enhance visibility in your application. Common configurations would include setting a file output in addition to standard output to keep a persistent log of your application’s behavior. You might consider adding timestamps and log levels in your logs.