import asyncio
import logging
import os
import sys
import json
import time
import torch
from pathlib import Path
from typing import Optional, Dict
import inspect
import signal
from decimal import Decimal
from dotenv import load_dotenv
Load environment variables
load_dotenv()
Import optimized components
from solana_rust_bot import TradeParams, TradingCore
from solana_cli import SolanaCLI, WSOLState, TokenBalances
from advanced_trading import AdvancedTrading, TradingMetrics
from price_monitor import RaydiumMonitor
from price_impact import EnhancedImpactCalculator
from mev_protection import EnhancedMevProtection, MevConfig
from system_manager import SystemManager
from helius_client import HeliusWebSocketClient
from vector_store import EnhancedVectorStore, VectorConfig, PoolPattern
from trading_config import (
SystemConfig,
ExecutionConfig,
SandwichConfig,
ImpactConfig,
GPUConfig,
TradingConfig,
ConfigEncoder
)
from mempool_analyzer import EnhancedMempoolAnalyzer
from gpu_accelerator import GPUAccelerator, AcceleratorConfig
from trade_executor import TradeExecutor, ExecutionResult
Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
handlers=[
logging.StreamHandler(),
logging.FileHandler('trading_bot.log')
]
)
logger = logging.getLogger(name)
class RaydiumTrader:
def init(self):
"""Initialize RaydiumTrader with all components"""
print("[INFO] Initializing RaydiumTrader...")
self.start_time = time.time()
# Validate environment variables
required_vars = [
'SOLANA_PRIVATE_KEY',
'HELIUS_API_KEY',
'QUICKNODE_WEBSOCKET',
'QUICKNODE_API_KEY'
]
for var in required_vars:
if not os.getenv(var):
raise ValueError(f"Missing required environment variable: {var}")
# Create base configuration
self.config = TradingConfig()
# Initialize state variables
self.active = False
self.trading_active = False
self.last_trade_time = 0
self.trade_count = 0
# Metrics tracking
self.metrics = TradingMetrics()
# Initialize Vector Store
self.vector_config = VectorConfig()
self.vector_store = EnhancedVectorStore(self.config)
# Initialize WebSocket client
self.ws_client = HeliusWebSocketClient(self.config)
# Initialize GPU
self._init_gpu()
# Initialize components that don't require async
self.trading_core = TradingCore(
rpc_url=self.config.helius_endpoint,
config_json=json.dumps(self.config, cls=ConfigEncoder)
)
self.system = SystemManager()
self.price_monitor = RaydiumMonitor(self.config) # Initialize price monitor
self.advanced_trading = AdvancedTrading(self, self.config) # Initialize advanced trading
self.impact_calculator = EnhancedImpactCalculator(self.trading_core, self.config) # Initialize impact calculator
self.mev_protection = EnhancedMevProtection(MevConfig()) # Initialize MEV protection
self.mempool_analyzer = EnhancedMempoolAnalyzer(
self.trading_core,
self.config.gpu.batch_size,
self.config.system.metrics_interval
) # Initialize mempool analyzer
self.solana_cli = SolanaCLI(self.trading_core) # Initialize Solana CLI
self.trade_executor = TradeExecutor(self.trading_core, self.config) # Initialize trade executor
# Add signal handlers
signal.signal(signal.SIGINT, self._handle_shutdown)
signal.signal(signal.SIGTERM, self._handle_shutdown)
print("[INFO] RaydiumTrader initialized")
def _init_gpu(self):
"""Initialize GPU with optimal settings"""
logger.debug("[INFO] Initializing GPU...")
if torch.cuda.is_available():
gpu_config = self.config.gpu
# Set CUDA optimization flags
torch.backends.cudnn.benchmark = gpu_config.cudnn_benchmark
torch.backends.cuda.matmul.allow_tf32 = gpu_config.allow_tf32
# Create accelerator config
accelerator_config = AcceleratorConfig(
memory_fraction=gpu_config.memory_fraction,
use_tensor_cores=gpu_config.use_tensor_cores,
batch_size=gpu_config.batch_size
)
self.gpu_accelerator = GPUAccelerator(accelerator_config)
self.gpu_accelerator.initialize()
gpu_info = torch.cuda.get_device_properties(0)
print(f"[INFO] GPU Initialized: {gpu_info.name} ({gpu_info.total_memory / 1024 ** 3:.2f}GB)")
logger.info(f"GPU Initialized: {gpu_info.name} ({gpu_info.total_memory / 1024 ** 3:.2f}GB)")
else:
print("[WARNING] No GPU available, using CPU")
logger.warning("No GPU available, using CPU")
async def initialize(self) -> bool:
"""Initialize all trading components"""
logger.debug("[INFO] Starting system initialization...")
try:
await self.system.start() # Start the system manager
print("[INFO] SystemManager started")
await self.ws_client.start() # Start WebSocket client
print("[INFO] WebSocket client initialized")
print("[INFO] TradingCore initialized")
# There are additional components to initialize
await self.advanced_trading.start() # Start advanced trading
print("[INFO] Advanced trading initialized")
await self.price_monitor.start_monitoring() # Start price monitor
print("[INFO] Price monitor initialized")
await self.mempool_analyzer.start_monitoring() # Start mempool analyzer
print("[INFO] Mempool analyzer initialized")
# Initialize SolanaCLI last
await self.solana_cli.start_monitoring()
print("[INFO] SolanaCLI initialized")
# Get initial balance
try:
raw_balance = await self.trading_core.get_balance()
if raw_balance is not None:
sol_balance = int(raw_balance) / 1_000_000_000
print(f"[INFO] Initial SOL Balance: {sol_balance:.6f} SOL")
except Exception as e:
print(f"[WARNING] Could not get initial balance: {e}")
self.active = True
self.trading_active = True
print("[INFO] All components initialized successfully")
return True
except Exception as e:
logger.exception("[ERROR] Initialization error")
print(f"[ERROR] Initialization error: {e}")
return False
async def start_trading(self):
"""Start all trading processes"""
print("[INFO] Starting trading processes...")
try:
tasks = [
asyncio.create_task(self.process_ws_messages()),
asyncio.create_task(self.monitor_opportunities()),
asyncio.create_task(self.monitor_system_metrics()),
asyncio.create_task(self.update_token_balances()),
asyncio.create_task(self.price_monitor.start_monitoring()),
asyncio.create_task(self.system.monitor_loop()),
asyncio.create_task(self.mempool_analyzer.start_monitoring()),
asyncio.create_task(self.vector_store.start_pattern_monitoring())
]
# Wait for any task to complete or fail
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
# Check for exceptions
for task in done:
if task.exception():
raise task.exception()
except Exception as e:
logger.exception("[ERROR] Trading error")
print(f"[ERROR] Trading error: {e}")
await self.cleanup()
raise
async def process_ws_messages(self):
"""Process WebSocket messages with enhanced handling"""
while self.trading_active:
try:
# Get price updates
price_data = await self.ws_client.get_current_price()
if price_data:
await self.price_monitor.update_price(price_data)
# Process messages from the process queue
if not self.ws_client.process_queue.empty():
message = await self.ws_client.process_queue.get()
await self.advanced_trading.process_market_update(message)
await asyncio.sleep(0.001)
except Exception as e:
logger.error(f"WS message processing error: {e}")
await asyncio.sleep(0.1)
async def monitor_opportunities(self):
"""Monitor for trading opportunities"""
print("[INFO] Starting opportunity monitoring...")
while self.trading_active:
try:
if not self.system.is_healthy():
logger.warning("System health check failed, pausing trading")
await asyncio.sleep(5)
continue
opportunity = await self.advanced_trading.get_next_opportunity()
if opportunity:
await self.process_opportunity(opportunity)
await asyncio.sleep(0.001)
except Exception as e:
logger.error(f"Opportunity monitoring error: {e}")
await asyncio.sleep(1)
async def process_opportunity(self, opportunity: Dict):
"""Process trading opportunity"""
try:
if not self.trading_active:
logger.warning("Trading is not active; opportunity processing aborted.")
return
logger.info(f"Processing opportunity: {opportunity}")
# Fetch the current price from the WebSocket client
current_price_data = await self.ws_client.get_current_price()
if current_price_data is None:
logger.warning("Current price data is unavailable; opportunity validation failed.")
return
current_price = current_price_data.price # Extract the price from the price data
# Validate the opportunity
valid, metrics = await self.impact_calculator.validate_trade(
opportunity['pool'],
opportunity['amount_in'],
opportunity['min_amount_out'],
opportunity['type']
)
if valid:
# Store pattern in vector store
pattern_vector = torch.randn(self.vector_store.config.vector_dim).to(self.vector_store.device)
pattern = PoolPattern(
vector=pattern_vector,
timestamp=time.time(),
metadata=opportunity
)
await self.vector_store.store_pattern(opportunity['pool'], pattern_vector, opportunity)
# Update metrics for successful trades
self.metrics.successful_trades += 1
self.metrics.total_profit += Decimal(str(opportunity['profit']))
if opportunity['type'] == 'sandwich':
self.metrics.sandwich_profits += Decimal(str(opportunity['profit']))
else:
self.metrics.impact_profits += Decimal(str(opportunity['profit']))
# Execute the trade using the TradeExecutor
execution_result = await self.trade_executor.execute_trade(opportunity)
if execution_result.success:
self.trade_count += 1
self.last_trade_time = time.time()
logger.info(f"Trade executed successfully: {execution_result.signature}")
print(f"[INFO] Trade executed successfully: {execution_result.signature}")
else:
logger.error(f"Trade execution failed: {execution_result.error}")
else:
logger.info(f"Opportunity is invalid: {metrics.get('reason')}")
except Exception as e:
logger.error(f"Opportunity processing error: {e}")
async def update_token_balances(self):
"""Update token balances"""
try:
balances = await self.solana_cli.get_token_balances()
self.token_balances = TokenBalances(
wsol=WSOLState(
balance=balances['wsol'],
last_update=time.time()
),
tokens=balances['tokens']
)
print(f"[INFO] Token balances updated: {balances}")
except Exception as e:
logger.error(f"Balance update error: {e}")
async def monitor_system_metrics(self):
"""Monitor system metrics"""
print("[INFO] Starting system metrics monitoring...")
while self.trading_active:
try:
metrics = {
'gpu_utilization': self.gpu_accelerator.get_utilization(),
'memory_usage': self.system.get_memory_usage(),
'trade_count': self.metrics.successful_trades,
'total_profit': float(self.metrics.total_profit),
'uptime_hours': self.get_runtime_hours()
}
await self.system.update_metrics(metrics)
print(f"[INFO] System metrics: {metrics}")
await asyncio.sleep(1)
except Exception as e:
logger.error(f"Metrics monitoring error: {e}")
def _handle_shutdown(self, signum, frame):
"""Handle shutdown signals"""
print("[INFO] Shutdown signal received")
asyncio.create_task(self.cleanup())
async def cleanup(self):
"""Clean up all resources properly."""
print("[INFO] Cleaning up trading system...")
try:
self.active = False
self.trading_active = False
# Cleanup WebSocket client
if self.ws_client:
await self.ws_client.cleanup()
print("[INFO] WebSocket client cleaned up")
# Cleanup components
cleanup_tasks = []
components = [
self.advanced_trading,
self.impact_calculator,
self.price_monitor,
self.system,
self.mev_protection,
self.mempool_analyzer,
self.vector_store,
self.solana_cli,
self.gpu_accelerator
]
for component in components:
if component and hasattr(component, "cleanup"):
try:
cleanup_method = component.cleanup()
if inspect.iscoroutine(cleanup_method):
cleanup_tasks.append(asyncio.create_task(cleanup_method))
print(f"[INFO] Cleaning up component: {component.__class__.__name__}")
except Exception as e:
logger.error(f"Error cleaning up component: {e}")
if cleanup_tasks:
await asyncio.wait(cleanup_tasks, return_when=asyncio.ALL_COMPLETED)
# Save final metrics
final_metrics = self.get_metrics()
self._save_metrics(final_metrics)
# Clear GPU memory if it exists
if torch.cuda.is_available():
torch.cuda.empty_cache()
print("[INFO] GPU memory cache cleared")
# Clear message queues
if hasattr(self, 'ws_queues'):
await self.ws_queues.clear_all()
print("[INFO] Message queues cleared")
runtime_hours = self.get_runtime_hours()
print(f"[INFO] Trading session complete. Runtime: {runtime_hours:.2f} hours")
logger.info(f"Trading session complete. Runtime: {runtime_hours:.2f} hours")
# Log final statistics
print("\n=== Final Trading Statistics ===")
print(f"Total Trades: {self.metrics.successful_trades}")
print(f"Total Profit: {float(self.metrics.total_profit):.6f} SOL")
print(f"Sandwich Profits: {float(self.metrics.sandwich_profits):.6f} SOL")
print(f"Impact Profits: {float(self.metrics.impact_profits):.6f} SOL")
print(f"Opportunities Found: {self.metrics.opportunities_found}")
print("==============================\n")
except Exception as e:
logger.exception("[ERROR] Cleanup error")
print(f"[ERROR] Cleanup error: {e}")
finally:
self.active = False
self.trading_active = False
def _save_metrics(self, metrics: Dict):
"""Save trading metrics to file"""
try:
metrics_file = Path("trading_metrics.json")
metrics['timestamp'] = time.time()
if metrics_file.exists():
with open(metrics_file, 'r') as f:
historical_metrics = json.load(f)
historical_metrics.append(metrics)
else:
historical_metrics = [metrics]
with open(metrics_file, 'w') as f:
json.dump(historical_metrics, f, indent=2)
print("[INFO] Trading metrics saved successfully")
except Exception as e:
logger.error(f"Error saving metrics: {e}")
def get_metrics(self) -> Dict:
"""Get current trading metrics"""
return {
'successful_trades': self.metrics.successful_trades,
'opportunities_found': self.metrics.opportunities_found,
'total_profit': float(self.metrics.total_profit),
'sandwich_profits': float(self.metrics.sandwich_profits),
'impact_profits': float(self.metrics.impact_profits),
'runtime_hours': self.get_runtime_hours(),
'avg_profit_per_trade': float(self.metrics.total_profit / max(1, self.metrics.successful_trades)),
'success_rate': self.metrics.successful_trades / max(1, self.metrics.opportunities_found),
'system_metrics': {
'gpu_utilization': self.gpu_accelerator.get_utilization() if hasattr(self, 'gpu_accelerator') else None,
'memory_usage': self.system.get_memory_usage() if hasattr(self, 'system') else None,
}
}
def get_runtime_hours(self) -> float:
"""Calculate runtime in hours"""
return (time.time() - self.start_time) / 3600
async def get_current_balances(self) -> Dict:
"""Get current SOL and wSOL balances"""
try:
sol_balance = await self.trading_core.get_balance()
wsol_balance = await self.solana_cli.get_token_balance(
self.config.sol_wsol_accounts['pool_coin_token_account']
)
return {
'sol': sol_balance / 1_000_000_000, # Convert lamports to SOL
'wsol': wsol_balance,
'timestamp': time.time()
}
except Exception as e:
logger.error(f"Error getting balances: {e}")
return {'sol': 0.0, 'wsol': 0.0, 'timestamp': time.time()}
async def main():
"""Main entry point with enhanced error handling."""
bot = None
try:
print("[INFO] Starting Raydium Trading Bot...")
# Initialize bot with proper path resolution
config_path = str(Path(__file__).parent / "config.json")
bot = RaydiumTrader()
# Initialize components
await bot.initialize()
# Start trading
await bot.start_trading()
except KeyboardInterrupt:
print("[INFO] Keyboard interrupt received")
logger.info("Keyboard interrupt received")
except Exception as e:
logger.exception("[ERROR] Critical system error")
print(f"[ERROR] Critical system error: {e}")
finally:
if bot:
await bot.cleanup()
if name == "main":
if sys.platform == 'win32':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Create a new event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
print("[INFO] Running the event loop...")
loop.run_until_complete(main())
except KeyboardInterrupt:
print("[INFO] Shutdown signal received")
logger.info("Shutdown signal received")
finally:
loop.close() THIS ISNT BEING USED AND IT NEEDS TO BE "ExecutionResult" is not accessedPylance
(module) ExecutionResult # Initialize TradingCore
self.trading_core = TradingCore(
rpc_url=self.config.helius_endpoint,
config_json=json.dumps(self.config, cls=ConfigEncoder)
)
print("[INFO] TradingCore initialized")
Initialize TradeExecutor - Add this line
self.trade_executor = TradeExecutor(self.trading_core, self.config)
print("[INFO] TradeExecutor initialized")def init(self):
"""Initialize RaydiumTrader with all components"""
print("[INFO] Initializing RaydiumTrader...")
self.start_time = time.time()
# ... other initialization code ...
# Initialize components that don't require async
self.trading_core = None
self.system = None
self.price_monitor = None
self.advanced_trading = None
self.impact_calculator = None
self.mev_protection = None
self.mempool_analyzer = None
self.solana_cli = None
self.trade_executor = None # Add this lineBut I see you're not actually initializing the trade_executor in your __init__ method of RaydiumTrader. Add this line in your __init__ method: