import asyncio
import logging
import json
import os
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
import torch
from pathlib import Path
from datetime import datetime
from solders.keypair import Keypair
from solders.pubkey import Pubkey
from base58 import b58encode, b58decode
from solana_rust_bot import TradingCore
from groq_analysis import GroqAnalyzer
from quantum_indicators import QuantumIndicators
from ml_engine import MLEngine
from market_data import MarketData
from dashboard_server import DashboardServer
from safeguards import TradingSafeguards
from position_scaler import PositionScaler
from tps_manager import TPSManager
from market_signals import MarketSignals
from market_poller import MarketPoller
from metrics import TokenMetricsAnalyzer
import base58
from strategy_analyzer import QuantumStrategyAnalyzer
from vector_store import VectorStore
from quantum_optimized import QuantumOptimized
from config_validator import ConfigValidator
from mega_benchmark import MegaTradingEngine
from monitor import MonitorServer
import time
def setup_logging():
"""Configure logging with proper Unicode support"""
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers = [
logging.FileHandler('quantum.log', 'a', encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
logging.basicConfig(
level=logging.INFO,
format=log_format,
handlers=handlers
)
return logging.getLogger('quantum')
def setup_quantum_logging():
"""Configure comprehensive logging for the quantum trading system"""
# Create logs directory if it doesn't exist
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
# Create timestamp for log file
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
log_file = log_dir / f"quantum_trading_{timestamp}.log"
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s | %(name)s | %(levelname)s | %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler() # Also print to console
]
)
# Create specialized loggers for different components
loggers = {
'market': logging.getLogger('market'),
'trading': logging.getLogger('trading'),
'ml': logging.getLogger('ml'),
'quantum': logging.getLogger('quantum'),
'system': logging.getLogger('system')
}
return loggers
class QuantumTradingSystem:
def init(self):
self.logger = self.setup_logging()
self.root_dir = self.get_project_root()
self.config = self.load_config()
self.loggers = setup_quantum_logging()
self.logger = self.loggers['system']
# Verify keypair before initializing
keypair_path = Path(self.config["wallet"]["keypair_path"])
self.verify_keypair(keypair_path)
# Initialize core components
self.trading_core = TradingCore(str(keypair_path))
self.indicators = QuantumIndicators()
self.ml_engine = MLEngine(self.config)
self.market_data = MarketData(self.config)
self.market_poller = MarketPoller(self.config)
self.market_signals = MarketSignals(self.config)
self.safeguards = TradingSafeguards(self.config)
self.position_scaler = PositionScaler(self.config)
self.tps_manager = TPSManager(self.config)
# Initialize dashboard server last
self.dashboard = DashboardServer(
trading_core=self.trading_core,
market_data=self.market_data,
ml_engine=self.ml_engine,
groq_analyzer=self.groq_analyzer,
config=self.config,
indicators=self.indicators,
market_signals=self.market_signals
)
self.logger.info("🚀 Quantum Trading System initialized successfully")
def verify_keypair(self, keypair_path: Path) -> None:
"""Verify keypair exists and is valid using environment variables"""
try:
# Get keypair info from environment
private_key_b58 = os.environ.get('SOLANA_PRIVATE_KEY')
public_key_b58 = os.environ.get('SOLANA_PUBLIC_KEY')
if not private_key_b58 or not public_key_b58:
raise ValueError("Missing SOLANA_PRIVATE_KEY or SOLANA_PUBLIC_KEY in environment")
self.logger.info(f"Found keypair info in environment variables")
self.logger.info(f"Public key from env: {public_key_b58}")
# Decode private key from base58
private_bytes = base58.b58decode(private_key_b58)
# Create JSON array of bytes
keypair_bytes = [b for b in private_bytes]
# Write to keypair file
with open(keypair_path, 'w') as f:
json.dump(keypair_bytes, f)
self.logger.info(f"Wrote keypair to: {keypair_path}")
# Verify we can load it with Solders
keypair = Keypair.from_bytes(bytes(keypair_bytes))
loaded_pubkey = str(keypair.pubkey())
# Verify public key matches
if loaded_pubkey != public_key_b58:
raise ValueError(f"Public key mismatch: {loaded_pubkey} != {public_key_b58}")
self.logger.info(f"Successfully verified keypair matches environment")
# Verify against config
if 'wallet' in self.config and 'address' in self.config['wallet']:
expected_pubkey = self.config['wallet']['address']
if loaded_pubkey != expected_pubkey:
raise ValueError(f"Keypair pubkey {loaded_pubkey} doesn't match config address {expected_pubkey}")
self.logger.info("Keypair matches configuration address")
except Exception as e:
self.logger.error(f"Keypair verification failed: {e}")
raise ValueError(f"Invalid keypair data: {e}")
def get_project_root(self) -> Path:
"""Get the project root directory."""
current_file = Path(__file__).resolve()
root_dir = current_file.parent.parent.parent
if not (root_dir / "config.json").exists():
raise FileNotFoundError(
f"config.json not found in {root_dir}. "
"Make sure you're running from the correct directory."
)
return root_dir
def setup_logging(self) -> logging.Logger:
"""Configure logging with timestamps"""
logger = logging.getLogger(__name__)
log_format = '%(asctime)s | %(levelname)s | %(message)s'
log_file = datetime.now().strftime('quantum_%Y%m%d_%H%M%S.log')
logging.basicConfig(
level=logging.INFO,
format=log_format,
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
return logger
def load_config(self) -> dict:
"""Load configuration from config.json"""
try:
config_path = self.root_dir / "config.json"
self.logger.info(f"Loading config from: {config_path}")
if not config_path.exists():
raise FileNotFoundError(f"Config file not found at {config_path}")
with open(config_path) as f:
return json.load(f)
except Exception as e:
self.logger.error(f"Failed to load config: {e}")
raise
async def start(self):
"""Start the trading system"""
try:
self.running = True
# Initialize GPU if available
if torch.cuda.is_available():
self.logger.info(f"GPU: {torch.cuda.get_device_name(0)}")
self.logger.info(f"CUDA Version: {torch.version.cuda}")
self.logger.info(f"PyTorch Version: {torch.__version__}")
self.logger.info(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f}GB")
# Start services
await asyncio.gather(
self.dashboard.start_server(),
self.market_data.start(),
self.process_trades()
)
except Exception as e:
self.logger.error(f"System startup error: {e}")
await self.cleanup()
async def process_trades(self):
"""Main trading loop with enhanced logging"""
while self.running:
try:
# Get market data
market_data = await self.market_data.get_latest_market_data()
if not market_data:
await asyncio.sleep(0.1)
continue
# Log market data
self.loggers['market'].info(
f"Market Update | "
f"Price: {market_data.get('price', 0):.6f} | "
f"Volume: {market_data.get('volume_5min', 0):.2f} | "
f"Pool: {market_data.get('pool_address', 'unknown')}"
)
# Update indicators and log
self.indicators.update_market_data(
market_data["price"],
market_data["volume_5min"]
)
# Get and log ML prediction
ml_signal = await self.ml_engine.predict_trade_signal(market_data)
self.loggers['ml'].info(
f"ML Signal | "
f"Confidence: {ml_signal.get('confidence', 0):.2f} | "
f"Signal: {ml_signal.get('signal', 'none')} | "
f"Execution Time: {ml_signal.get('execution_time', 0):.2f}ms"
)
# Get and log Groq analysis
groq_analysis = await self.groq_analyzer.analyze_trade_opportunity(market_data)
self.loggers['quantum'].info(
f"Quantum Analysis | "
f"Confidence: {groq_analysis.get('confidence', 0):.2f} | "
f"Optimization Level: {groq_analysis.get('optimization', 0):.2f}"
)
# Log system metrics periodically
if hasattr(self, 'last_metric_log'):
if time.time() - self.last_metric_log >= 60: # Log every minute
self._log_system_metrics()
self.last_metric_log = time.time()
else:
self.last_metric_log = time.time()
# Validate and potentially execute trade
if await self.validate_trade(market_data, ml_signal, groq_analysis):
await self.execute_trade(market_data)
await asyncio.sleep(0.01)
except Exception as e:
self.logger.error(f"Trade processing error: {e}")
await asyncio.sleep(1)
def _log_system_metrics(self):
"""Log system performance metrics"""
try:
if torch.cuda.is_available():
gpu_util = torch.cuda.utilization()
vram_used = torch.cuda.memory_allocated() / 1024**2
self.loggers['system'].info(
f"System Metrics | "
f"GPU Util: {gpu_util}% | "
f"VRAM: {vram_used:.1f}MB | "
f"TPS: {self.tps_manager.get_current_tps():.1f} | "
f"Active Pools: {len(self.market_data.active_pools)} | "
f"Trade Count: {len(self.market_data.successful_trades)}"
)
except Exception as e:
self.logger.error(f"Error logging metrics: {e}")
async def execute_trade(self, market_data: dict):
"""Execute trade with detailed logging"""
try:
position_size = self.position_scaler.calculate_position_size(market_data)
self.loggers['trading'].info(
f"Trade Execution | "
f"Pool: {market_data['pool_address']} | "
f"Size: {position_size / 1e9:.4f} SOL | "
f"Price: {market_data['price']:.6f}"
)
trade_data = {
"pool_address": market_data["pool_address"],
"amount_in": position_size,
"min_amount_out": int(position_size * 0.995)
}
signature = self.trading_core.execute_trade(json.dumps(trade_data))
if signature:
self.loggers['trading'].info(f"Trade Success | Signature: {signature}")
self.tps_manager.record_successful_trade()
except Exception as e:
self.loggers['trading'].error(f"Trade Execution Error: {e}")
self.tps_manager.record_failed_trade()
async def validate_trade(self, market_data: dict, ml_signal: dict, groq_analysis: dict) -> bool:
"""Validate trade opportunity"""
try:
# Check safeguards
safeguards = self.safeguards.validate_token(
market_data["token_mint"],
market_data
)
if not safeguards[0]:
return False
# Check ML confidence
if ml_signal["confidence"] < self.config["ml_signal"]["confidence_score"]:
return False
# Check Groq confidence
if groq_analysis and groq_analysis.get("confidence", 0) < 70:
return False
# Check TPS capacity
if not self.tps_manager.can_execute_trade():
return False
return True
except Exception as e:
self.logger.error(f"Trade validation error: {e}")
return False
async def update_metrics(self, market_data: dict, ml_signal: dict, groq_analysis: dict):
"""Update dashboard metrics"""
try:
metrics = {
"neural": {
"confidence": ml_signal.get("confidence", 0),
"predictions": self.ml_engine.get_recent_predictions(),
"execution_time": self.ml_engine.get_last_execution_time()
},
"groq": {
"analysis": self.groq_analyzer.get_analysis_history(),
"latency": self.groq_analyzer.get_latency()
},
"performance": {
"total_profit": await self.market_data.calculate_total_profit(),
"win_rate": await self.market_data.calculate_win_rate(),
"trades": len(self.market_data.successful_trades),
"throughput": self.tps_manager.get_current_tps()
},
"system": {
"gpu_util": torch.cuda.utilization(),
"vram_usage": torch.cuda.memory_allocated() / 1024**2,
"batch_size": self.config["system"]["batch_size"]
}
}
await self.dashboard.broadcast_metrics(metrics)
except Exception as e:
self.logger.error(f"Metrics update error: {e}")
async def cleanup(self):
"""Cleanup system resources"""
self.running = False
try:
await asyncio.gather(
self.market_data.cleanup(),
self.ml_engine.cleanup(),
self.groq_analyzer.cleanup(),
self.dashboard.cleanup()
)
self.logger.info("System cleanup completed")
except Exception as e:
self.logger.error(f"Cleanup error: {e}")
def main():
"""Main entry point with error handling."""
try:
system = QuantumTradingSystem()
asyncio.run(system.start())
except KeyboardInterrupt:
logging.info("Shutting down by user request...")
asyncio.run(system.cleanup())
except Exception as e:
logging.error(f"Fatal error: {e}")
raise
finally:
logging.info("Shutdown complete")
if name == "main":
main() import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
def setup_logging():
"""Configure logging with proper Unicode support"""
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers = [
logging.FileHandler('quantum.log', 'a', encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
logging.basicConfig(
level=logging.INFO,
format=log_format,
handlers=handlers
)
return logging.getLogger('quantum')
Update MLEngine initialization
class MLEngine:
def init(self, config):
self.logger = logging.getLogger(name)
# Fix dictionary access
self.batch_size = config["system"]["batch_size"]
self.feature_size = config["system"]["vector_dim"]
self.hidden_size = self.feature_size * 2
# Initialize GPU resources
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.gpu_streams = [torch.cuda.Stream() for _ in range(16)] if torch.cuda.is_available() else []
self.logger.info(f"ML Engine initialized on {self.device}")
Update QuantumIndicators initialization
class QuantumIndicators:
def init(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.logger = logging.getLogger(name)
# Use plain text instead of emoji
self.logger.info(f"Quantum Indicators initialized on {self.device}")
Main system initialization
class QuantumTradingSystem:
def init(self):
# Setup logging first
self.logger = setup_logging()
try:
# Load config
self.root_dir = self.get_project_root()
self.config = self.load_config()
# Verify config has required sections
required_sections = ["system", "wallet", "rpc", "trading"]
missing = [s for s in required_sections if s not in self.config]
if missing:
raise ValueError(f"Missing required config sections: {missing}")
# Verify config values
if not isinstance(self.config["system"], dict):
raise ValueError("Config 'system' section must be a dictionary")
if "batch_size" not in self.config["system"]:
raise ValueError("Missing 'batch_size' in system config")
if "vector_dim" not in self.config["system"]:
raise ValueError("Missing 'vector_dim' in system config")
# Verify keypair
keypair_path = Path(self.config["wallet"]["keypair_path"])
self.verify_keypair(keypair_path)
# Initialize components
self.trading_core = TradingCore(str(keypair_path))
self.indicators = QuantumIndicators()
self.ml_engine = MLEngine(self.config)
self.market_data = MarketData(self.config)
self.market_signals = MarketSignals(self.config)
self.safeguards = TradingSafeguards(self.config)
self.position_scaler = PositionScaler(self.config)
self.tps_manager = TPSManager(self.config)
# Initialize dashboard
self.dashboard = DashboardServer(
trading_core=self.trading_core,
market_data=self.market_data,
ml_engine=self.ml_engine,
config=self.config
)
self.logger.info("Quantum Trading System initialized successfully")
except Exception as e:
self.logger.error(f"Initialization error: {str(e)}")
raise
def load_config(self) -> dict:
"""Load and validate configuration"""
try:
config_path = self.root_dir / "config.json"
self.logger.info(f"Loading config from: {config_path}")
if not config_path.exists():
raise FileNotFoundError(f"Config file not found at {config_path}")
with open(config_path) as f:
config = json.load(f)
# Add default values if missing
if "system" not in config:
config["system"] = {
"batch_size": 312500,
"vector_dim": 640,
"gpu_threads": 24
}
return config
except Exception as e:
self.logger.error(f"Failed to load config: {e}")
raise please add maximum logging and include no redundant code. you know how it should be please dont lessen weaken or remove code that belongs.