# Initialize system manager first
self.system = SystemManager()
if not await self.system.start():
return False
# Initialize trading core
trading_config = {
"compute_limit": int(os.getenv('COMPUTE_LIMIT', '400000')),
"priority_fee": int(os.getenv('PRIORITY_FEE', '500000')),
"max_priority_fee": int(os.getenv('MAX_PRIORITY_FEE', '1000000')),
"slippage": float(os.getenv('EXEC_SLIPPAGE', '0.01')),
"retry_count": int(os.getenv('EXEC_RETRY_COUNT', '3')),
"rpc_url": os.getenv('RPC_URL')
}
self.trading_core = TradingCore(os.getenv('RPC_URL'), json.dumps(trading_config))
# Initialize websocket client first
self.ws_client = HeliusWebSocketClient()
await self.ws_client.connect() # Ensure we await this
# Initialize vector store after GPU setup
self.vector_store = EnhancedVectorStore()
await self.vector_store.initialize() # Add initialization method
# Initialize remaining components
self.impact_calculator = EnhancedImpactCalculator()
self.mempool_analyzer = EnhancedMempoolAnalyzer({})
self.advanced_trading = AdvancedTrading(self, {})
# Pool update
pool_data = {
"amm_id": os.getenv('SOL_WSOL_AMM_ID'),
"amm_authority": os.getenv('SOL_WSOL_AUTHORITY'),
"amm_open_orders": os.getenv('SOL_WSOL_OPEN_ORDERS'),
"amm_target": os.getenv('SOL_WSOL_TARGET'),
"pool_coin_token_account": os.getenv('SOL_WSOL_BASE_VAULT'),
"pool_pc_token_account": os.getenv('SOL_WSOL_QUOTE_VAULT'),
"serum_market": os.getenv('SOL_WSOL_MARKET'),
"serum_bids": os.getenv('SOL_WSOL_BIDS'),
"serum_asks": os.getenv('SOL_WSOL_ASKS'),
"serum_events": os.getenv('SOL_WSOL_EVENTS'),
"vault_signer": os.getenv('SOL_WSOL_VAULT_SIGNER')
}
await self.trading_core.update_pool(pool_data)
# Verify websocket connections
if not self.ws_client.is_connected():
raise Exception("WebSocket connection failed")
self.active = True
logger.info("All components initialized successfully")
return True
except Exception as e:
logger.error(f"Initialization error: {e}")
return False
def _setup_cuda(self):
"""Initialize CUDA with optimal settings"""
torch.cuda.set_device(0)
torch.backends.cuda.matmul.allow_tf32 = os.getenv('ALLOW_TF32', 'true').lower() == 'true'
torch.backends.cudnn.benchmark = os.getenv('CUDNN_BENCHMARK', 'true').lower() == 'true'
# Set memory fraction
torch.cuda.set_per_process_memory_fraction(
float(os.getenv('GPU_MEMORY_FRACTION', '0.8'))
)
# Create CUDA streams with priorities
self.streams = {
'compute': torch.cuda.Stream(priority=int(os.getenv('GPU_COMPUTE_STREAMS', '-1'))),
'process': torch.cuda.Stream(priority=int(os.getenv('GPU_PROCESS_STREAMS', '-2'))),
'update': torch.cuda.Stream(priority=int(os.getenv('GPU_UPDATE_STREAMS', '0')))
}
gpu_info = torch.cuda.get_device_properties(0)
logger.info(f"GPU Initialized: {gpu_info.name} ({gpu_info.total_memory / 1024**3:.2f}GB)")
def _create_gpu_config(self) -> AcceleratorConfig:
"""Create GPU configuration from environment"""
return AcceleratorConfig(
batch_size=int(os.getenv('GPU_BATCH_SIZE', '256')),
matrix_size=int(os.getenv('VECTOR_DIMENSION', '512')),
use_tensor_cores=os.getenv('GPU_USE_TENSOR_CORES', 'true').lower() == 'true',
pipeline_parallel=True,
memory_fraction=float(os.getenv('GPU_MEMORY_FRACTION', '0.8'))
)
async def initialize(self) -> bool:
"""Initialize all trading components"""
try:
logger.info("Starting system initialization...")
# Initialize system manager
self.system = SystemManager()
if not await self.system.start():
return False
# Initialize trading core with full configuration
self.trading_core = TradingCore(
os.getenv('RPC_URL'),
json.dumps({
"compute_limit": int(os.getenv('COMPUTE_LIMIT', '400000')),
"priority_fee": int(os.getenv('PRIORITY_FEE', '500000')),
"max_priority_fee": int(os.getenv('MAX_PRIORITY_FEE', '1000000')),
"slippage": float(os.getenv('EXEC_SLIPPAGE', '0.01')),
"retry_count": int(os.getenv('EXEC_RETRY_COUNT', '3')),
"rpc_url": os.getenv('RPC_URL')
})
)
# Update Pool Data
pool_data = {
"amm_id": os.getenv('SOL_WSOL_AMM_ID'),
"amm_authority": os.getenv('SOL_WSOL_AUTHORITY'),
"amm_open_orders": os.getenv('SOL_WSOL_OPEN_ORDERS'),
"amm_target": os.getenv('SOL_WSOL_TARGET'),
"pool_coin_token_account": os.getenv('SOL_WSOL_BASE_VAULT'),
"pool_pc_token_account": os.getenv('SOL_WSOL_QUOTE_VAULT'),
"serum_market": os.getenv('SOL_WSOL_MARKET'),
"serum_bids": os.getenv('SOL_WSOL_BIDS'),
"serum_asks": os.getenv('SOL_WSOL_ASKS'),
"serum_events": os.getenv('SOL_WSOL_EVENTS'),
"vault_signer": os.getenv('SOL_WSOL_VAULT_SIGNER')
}
if not all(pool_data.values()):
missing = [k for k, v in pool_data.items() if not v]
raise ValueError(f"Missing required pool data: {missing}")
await self.trading_core.update_pool(pool_data)
# Initialize SolanaCLI and start monitoring
self.solana_cli = SolanaCLI(self.trading_core)
await self.solana_cli.start_monitoring()
# Initialize enhanced components with configuration
self.vector_store = EnhancedVectorStore()
self.impact_calculator = EnhancedImpactCalculator()
self.mempool_analyzer = EnhancedMempoolAnalyzer({})
self.advanced_trading = AdvancedTrading(self, {})
# Initialize MEV protection
self.mev_protection = EnhancedMevProtection(MevConfig(
max_fee_multiplier=float(os.getenv('FEE_MULTIPLIER', '1.5')),
min_priority_fee=int(os.getenv('EXEC_PRIORITY_FEE', '500000')),
max_priority_fee=int(os.getenv('EXEC_MAX_PRIORITY_FEE', '1000000')),
compute_budget=int(os.getenv('EXEC_COMPUTE_LIMIT', '400000')),
slippage=float(os.getenv('EXEC_SLIPPAGE', '0.01'))
))
# Initialize price monitor
self.price_monitor = RaydiumMonitor()
# Initialize Helius WebSocket client
self.ws_client = HeliusWebSocketClient()
await self.ws_client.connect()
self.active = True
logger.info("All components initialized successfully")
return True
except Exception as e:
logger.error(f"Initialization error: {e}")
return False
async def _init_components(self):
"""Initialize trading components"""
try:
# Initialize vector store with GPU device
self.vector_store = EnhancedVectorStore()
# Initialize other components
self.impact_calculator = EnhancedImpactCalculator()
self.mempool_analyzer = EnhancedMempoolAnalyzer({})
self.price_monitor = RaydiumMonitor()
# Initialize WebSocket client
self.ws_client = HeliusWebSocketClient()
await self.ws_client.connect()
logger.info("All components initialized")
except Exception as e:
logger.error(f"Component initialization error: {e}")
raise
async def monitor_mempool(self):
"""Monitor mempool for trading opportunities"""
logger.info("Starting mempool monitoring...")
max_trades_per_second = int(os.getenv('MAX_TRADES_PER_SECOND', '2'))
min_profit_pct = float(os.getenv('MIN_PROFIT_PCT', '1.5')) / 100
max_price_impact = float(os.getenv('MAX_PRICE_IMPACT', '0.004'))
while self.active:
try:
async with websockets.connect(
os.getenv('HELIUS_WS_URL'),
ping_interval=int(os.getenv('WS_PING_INTERVAL', '30')),
ping_timeout=int(os.getenv('WS_PING_TIMEOUT', '10')),
close_timeout=int(os.getenv('WS_CLOSE_TIMEOUT', '60')),
max_size=int(os.getenv('WS_MAX_MESSAGE_SIZE', '16777216'))
) as ws:
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "logsSubscribe",
"params": [
{"mentions": [os.getenv('RAYDIUM_PROGRAM_ID')]},
{"commitment": "processed"}
]
}))
while self.active and self.solana_cli.is_trading_active():
msg = await ws.recv()
opportunity = await self.parser.parse_transaction(msg)
if opportunity:
# Split analysis into parallel tasks
analysis_tasks = [
self.mempool_analyzer.analyze_transaction(opportunity.raw_data),
self.advanced_trading.analyze_opportunity(opportunity),
self.mev_protection.check_transaction(opportunity.raw_data)
]
results = await asyncio.gather(*analysis_tasks)
valid_results = [
r for r in results
if r and r.get('profit', 0) > min_profit_pct
and r.get('impact', 1) < max_price_impact
]
if valid_results:
# Select best opportunity by profit/risk ratio
best_opp = max(
valid_results,
key=lambda x: x['profit'] / max(x['impact'], 0.0001)
)
if self.solana_cli.is_trading_active():
await self.execute_opportunity(best_opp)
# Rate limiting
await asyncio.sleep(1 / max_trades_per_second)
except websockets.exceptions.ConnectionClosed:
if self.active:
reconnect_delay = float(os.getenv('WS_RECONNECT_DELAY', '0.1'))
logger.warning(f"WebSocket connection closed. Reconnecting in {reconnect_delay}s...")
await asyncio.sleep(reconnect_delay)
except Exception as e:
if self.active:
logger.error(f"Mempool monitoring error: {e}")
await asyncio.sleep(1)
async def execute_opportunity(self, opportunity: Dict[str, Any]) -> Optional[str]:
"""Execute a trading opportunity"""
try:
if not self.solana_cli.is_trading_active():
return None
trade_params = TradeParams(
pool_address=opportunity['pool_address'],
amount_in=opportunity['amount_in'],
min_amount_out=opportunity['min_amount_out'],
wsol_account=os.getenv('WSOL_TOKEN_ACCOUNT', '')
)
signature = await self.trading_core.execute_trade(trade_params)
if signature:
logger.info(f"Trade executed successfully: {signature}")
self.last_trade_time = time.time()
self.trade_count += 1
return signature
except Exception as e:
logger.error(f"Trade execution error: {e}")
return None
async def cleanup(self):
"""Clean up all resources"""
logger.info("Cleaning up trading system...")
try:
self.active = False
cleanup_tasks = []
# Components to clean up
components = [
self.gpu_accelerator,
self.vector_store,
self.impact_calculator,
self.mempool_analyzer,
self.advanced_trading,
self.price_monitor,
self.parser,
self.solana_cli,
self.ws_client
]
for component in components:
if component and hasattr(component, "cleanup"):
cleanup_method = component.cleanup()
if inspect.iscoroutine(cleanup_method):
cleanup_tasks.append(asyncio.create_task(cleanup_method))
if cleanup_tasks:
await asyncio.gather(*cleanup_tasks)
# Clean up thread pool
self.thread_pool.shutdown(wait=True)
# Clean up CUDA resources
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
for stream in self.streams.values():
stream.synchronize()
logger.info("All components cleaned up successfully")
except Exception as e:
logger.error(f"Cleanup error: {e}")
def get_runtime_hours(self) -> float:
"""Calculate runtime in hours"""
return (time.time() - self.start_time) / 3600