add this def initializestate(self): """Initialize bot state with proper trade limits"""…
- User
add this def _initialize_state(self): """Initialize bot state with proper trade limits""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.active_trades = 0 self.MAX_ACTIVE_TRADES = 1 self.MIN_TRADE_INTERVAL = 0.5 # 2 TPS max self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] }
async def _execute_trade_sequence(self, trade_info: dict): """Execute trade with proper rate limiting""" try: current_time = time.time() if self.active_trades >= self.MAX_ACTIVE_TRADES: return
if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL: return async with self.execution_lock: market_accounts = config.get_market_accounts() trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol market_accounts["amm_authority"], # AMM Authority needs to be before market market_accounts["market"], # market market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ]to this import asyncioimport json import websockets import time import base64 import numpy as np import torch from pathlib import Path import os import platform from solana_rust_bot import TradingCore, TradeParams from config_loader import config from solana_logger import logger
Fix Windows event loop
if platform.system() == 'Windows': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class ProductionMEVBot: def init(self): logger.info("Initializing Production MEV Bot")
# System Optimization self._setup_system() # Initialize trading core network_config = config.get_network_config() self.trading_core = TradingCore( rpc_url=network_config["rpc_url"], keypair_bytes=config.get_keypair_bytes() ) # Constants self.WSOL_MINT = "So11111111111111111111111111111111111111112" self.SOL_DECIMALS = 9 self.MAX_RETRIES = 3 self.RETRY_DELAY = 0.1 # Trading Parameters self._setup_trading_params() # Initialize state self._initialize_state() # Setup CUDA self._setup_cuda() logger.info("Bot initialization complete") def _setup_system(self): """Configure system settings""" os.environ["MKL_NUM_THREADS"] = str(os.cpu_count()) os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count()) os.environ["OMP_NUM_THREADS"] = str(os.cpu_count()) np.set_printoptions(precision=4, suppress=True) def _setup_trading_params(self): """Initialize trading parameters""" self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0)) self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0)) self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002)) self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4)) self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05)) self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000)) self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100)) def _setup_cuda(self): """Configure CUDA for optimal performance""" if not torch.cuda.is_available(): raise RuntimeError("CUDA required for production!") torch.cuda.set_device(0) torch.cuda.empty_cache() torch.set_float32_matmul_precision('high') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True self.stream = torch.cuda.Stream(priority=-1) cuda_info = torch.cuda.get_device_properties(0) logger.info(f"""🚀 CUDA Configuration: GPU: {torch.cuda.get_device_name()} Memory: {cuda_info.total_memory/1e9:.1f}GB Position Size: {self.POSITION_SIZE} WSOL Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL Min Profit: {self.MIN_PROFIT} SOL """)
def _initialize_state(self): """Initialize bot state""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] } self.ata_cache = {} def _calculate_profit(self, victim_size: float) -> float: """Calculate potential profit for trade size""" with torch.cuda.stream(self.stream): impact = self.POSITION_SIZE / victim_size if victim_size >= 35: rate = 0.012 # Premium rate elif victim_size >= 20: rate = 0.010 # Standard rate else: rate = 0.008 # Mini rate return float(victim_size * impact * rate - 0.001) def _decode_ray_log(self, raw_data: bytes) -> dict: """Decode and validate ray log data""" try: size = int.from_bytes(raw_data[1:9], "little") / 1e9 if not (self.MIN_SIZE <= size <= self.MAX_SIZE): return None profit = self._calculate_profit(size) if profit > self.MIN_PROFIT: return { 'size': size, 'profit': profit, 'data': raw_data } except Exception as e: logger.error(f"Ray log decode error: {str(e)}") return None async def _execute_trade_sequence(self, trade_info: dict): """Execute complete trade sequence""" try: market_accounts = config.get_market_accounts() trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol config.get("raydium"), # raydium_program market_accounts["market"], # market market_accounts["amm_authority"], # amm_authority market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ] # Entry trade entry_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=True, victim_data=base64.b64encode(trade_info['data']).decode(), reuse_blockhash=False, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) start_time = time.time() entry_sig = await self.trading_core.execute_trade_py(entry_params) if not entry_sig: logger.error("Entry trade failed") return # Quick exit trade exit_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=False, victim_data=None, reuse_blockhash=True, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) exit_sig = await self.trading_core.execute_trade_py(exit_params) execution_time = (time.time() - start_time) * 1000 # convert to ms if exit_sig: self.metrics['successful_trades'] += 1 self.metrics['total_profit'] += trade_info['profit'] self.metrics['execution_times'].append(execution_time) self.last_trade_time = time.time() trade_type = ( "PREMIUM" if trade_info['size'] >= 35 else "STANDARD" if trade_info['size'] >= 20 else "MINI" ) logger.info(f"""💫 Trade #{self.metrics['successful_trades']} [{trade_type}] Entry: {entry_sig} Exit: {exit_sig} Size: {trade_info['size']:.2f} SOL Profit: {trade_info['profit']:.6f} SOL Time: {execution_time:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
except Exception as e: logger.error(f"Trade sequence error: {str(e)}") async def _process_message(self, msg: str): """Process incoming WebSocket messages""" try: data = json.loads(msg) if "params" in data: logs = data["params"].get("result", {}).get("value", {}).get("logs", []) for log in logs: if "ray_log:" in log: raw_data = base64.b64decode(log.split("ray_log:")[1].strip()) trade_info = self._decode_ray_log(raw_data) if trade_info: self.metrics['trades_found'] += 1 async with self.execution_lock: await self._execute_trade_sequence(trade_info) except Exception as e: logger.error(f"Message processing error: {str(e)}") async def start(self): """Start the MEV bot""" network = config.get_network_config() logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50) while self.active: try: async with websockets.connect( network['ws_url'], extra_headers={'api-key': network['api_key']}, ping_interval=None, ping_timeout=None ) as ws: await ws.send(json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "logsSubscribe", "params": [ {"mentions": [config.get('raydium')]}, {"commitment": "processed"} ] })) while True: msg = await ws.recv() await self._process_message(msg) except Exception as e: logger.error(f"WebSocket error: {str(e)}") await asyncio.sleep(1) async def cleanup(self): """Cleanup resources""" logger.info("Starting cleanup...") self.active = False torch.cuda.empty_cache() if len(self.metrics['execution_times']) > 0: avg_execution = np.mean(self.metrics['execution_times']) success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100 logger.info(f"""🔚 Bot Statistics: Trades Found: {self.metrics['trades_found']} Trades Executed: {self.metrics['trades_executed']} Successful Trades: {self.metrics['successful_trades']} Success Rate: {success_rate:.1f}% Average Execution: {avg_execution:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
async def main(): bot = ProductionMEVBot() try: await bot.start() except KeyboardInterrupt: await bot.cleanup() logger.info("Bot stopped by user") except Exception as e: logger.error(f"Fatal error: {str(e)}") await bot.cleanup()
if name == "main": try: asyncio.run(main()) except KeyboardInterrupt: pass
- Assistant
To incorporate the
_initialize_stateand_execute_trade_sequencemethods you provided into the existingProductionMEVBotcode, you will first need to ensure that the method_initialize_statesets up the bot's state correctly. Then, you can replace the earlier definition of_execute_trade_sequencewith the modified version that includes the rate limiting logic.Here’s how you can modify your original
ProductionMEVBotclass to include these changes:import asyncio import json import websockets import time import base64 import numpy as np import torch from pathlib import Path import os import platform from solana_rust_bot import TradingCore, TradeParams from config_loader import config from solana_logger import logger # Fix Windows event loop if platform.system() == 'Windows': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) class ProductionMEVBot: def __init__(self): logger.info("Initializing Production MEV Bot") # System Optimization self._setup_system() # Initialize trading core network_config = config.get_network_config() self.trading_core = TradingCore( rpc_url=network_config["rpc_url"], keypair_bytes=config.get_keypair_bytes() ) # Constants self.WSOL_MINT = "So11111111111111111111111111111111111111112" self.SOL_DECIMALS = 9 self.MAX_RETRIES = 3 self.RETRY_DELAY = 0.1 # Trading Parameters self._setup_trading_params() # Initialize state self._initialize_state() # Setup CUDA self._setup_cuda() logger.info("Bot initialization complete") def _setup_system(self): """Configure system settings""" os.environ["MKL_NUM_THREADS"] = str(os.cpu_count()) os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count()) os.environ["OMP_NUM_THREADS"] = str(os.cpu_count()) np.set_printoptions(precision=4, suppress=True) def _setup_trading_params(self): """Initialize trading parameters""" self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0)) self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0)) self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002)) self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4)) self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05)) self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000)) self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100)) def _setup_cuda(self): """Configure CUDA for optimal performance""" if not torch.cuda.is_available(): raise RuntimeError("CUDA required for production!") torch.cuda.set_device(0) torch.cuda.empty_cache() torch.set_float32_matmul_precision('high') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True self.stream = torch.cuda.Stream(priority=-1) cuda_info = torch.cuda.get_device_properties(0) logger.info(f""" 🚀 CUDA Configuration: GPU: {torch.cuda.get_device_name()} Memory: {cuda_info.total_memory/1e9:.1f}GB Position Size: {self.POSITION_SIZE} WSOL Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL Min Profit: {self.MIN_PROFIT} SOL """) def _initialize_state(self): """Initialize bot state with proper trade limits""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.active_trades = 0 self.MAX_ACTIVE_TRADES = 1 self.MIN_TRADE_INTERVAL = 0.5 # 2 TPS max self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] } self.ata_cache = {} def _calculate_profit(self, victim_size: float) -> float: """Calculate potential profit for trade size""" with torch.cuda.stream(self.stream): impact = self.POSITION_SIZE / victim_size if victim_size >= 35: rate = 0.012 # Premium rate elif victim_size >= 20: rate = 0.010 # Standard rate else: rate = 0.008 # Mini rate return float(victim_size * impact * rate - 0.001) def _decode_ray_log(self, raw_data: bytes) -> dict: """Decode and validate ray log data""" try: size = int.from_bytes(raw_data[1:9], "little") / 1e9 if not (self.MIN_SIZE <= size <= self.MAX_SIZE): return None profit = self._calculate_profit(size) if profit > self.MIN_PROFIT: return { 'size': size, 'profit': profit, 'data': raw_data } except Exception as e: logger.error(f"Ray log decode error: {str(e)}") return None async def _execute_trade_sequence(self, trade_info: dict): """Execute trade with proper rate limiting""" try: current_time = time.time() if self.active_trades >= self.MAX_ACTIVE_TRADES: return if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL: return async with self.execution_lock: market_accounts = config.get_market_accounts() trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol market_accounts["amm_authority"], # AMM Authority needs to be before market market_accounts["market"], # market market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ] # Entry trade entry_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=True, victim_data=base64.b64encode(trade_info['data']).decode(), reuse_blockhash=False, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) start_time = time.time() entry_sig = await self.trading_core.execute_trade_py(entry_params) if not entry_sig: logger.error("Entry trade failed") return # Quick exit trade exit_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=False, victim_data=None, reuse_blockhash=True, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) exit_sig = await self.trading_core.execute_trade_py(exit_params) execution_time = (time.time() - start_time) * 1000 # convert to ms if exit_sig: self.metrics['successful_trades'] += 1 self.metrics['total_profit'] += trade_info['profit'] self.metrics['execution_times'].append(execution_time) self.last_trade_time = time.time() trade_type = ( "PREMIUM" if trade_info['size'] >= 35 else "STANDARD" if trade_info['size'] >= 20 else "MINI" ) logger.info(f""" 💫 Trade #{self.metrics['successful_trades']} [{trade_type}] Entry: {entry_sig} Exit: {exit_sig} Size: {trade_info['size']:.2f} SOL Profit: {trade_info['profit']:.6f} SOL Time: {execution_time:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """) self.active_trades += 1 self.metrics['trades_executed'] += 1 except Exception as e: logger.error(f"Trade sequence error: {str(e)}") async def _process_message(self, msg: str): """Process incoming WebSocket messages""" try: data = json.loads(msg) if "params" in data: logs = data["params"].get("result", {}).get("value", {}).get("logs", []) for log in logs: if "ray_log:" in log: raw_data = base64.b64decode(log.split("ray_log:")[1].strip()) trade_info = self._decode_ray_log(raw_data) if trade_info: self.metrics['trades_found'] += 1 async with self.execution_lock: await self._execute_trade_sequence(trade_info) except Exception as e: logger.error(f"Message processing error: {str(e)}") async def start(self): """Start the MEV bot""" network = config.get_network_config() logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50) while self.active: try: async with websockets.connect( network['ws_url'], extra_headers={'api-key': network['api_key']}, ping_interval=None, ping_timeout=None ) as ws: await ws.send(json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "logsSubscribe", "params": [ {"mentions": [config.get('raydium')]}, {"commitment": "processed"} ] })) while True: msg = await ws.recv() await self._process_message(msg) except Exception as e: logger.error(f"WebSocket error: {str(e)}") await asyncio.sleep(1) async def cleanup(self): """Cleanup resources""" logger.info("Starting cleanup...") self.active = False torch.cuda.empty_cache() if len(self.metrics['execution_times']) > 0: avg_execution = np.mean(self.metrics['execution_times']) success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100 logger.info(f""" 🔚 Bot Statistics: Trades Found: {self.metrics['trades_found']} Trades Executed: {self.metrics['trades_executed']} Successful Trades: {self.metrics['successful_trades']} Success Rate: {success_rate:.1f}% Average Execution: {avg_execution:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """) async def main(): bot = ProductionMEVBot() try: await bot.start() except KeyboardInterrupt: await bot.cleanup() logger.info("Bot stopped by user") except Exception as e: logger.error(f"Fatal error: {str(e)}") await bot.cleanup() if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: passKey Changes Made:
-
Initialization of State: The
_initialize_statemethod has been modified to initialize the fields related to active trades and trade limits. -
Rate Limiting Logic: The
_execute_trade_sequencemethod has been adjusted to implement rate limiting, checking if the bot is allowed to perform trades based on the number of active trades and the interval since the last trade. -
Metrics Update: After the trade is executed, metrics are updated accordingly, reflecting the number of trades executed.
This code now integrates your requested features into the bot's trading logic while maintaining the intended functionality.
-
- User
whats the difference import asyncio import json import websockets import time import base64 import numpy as np import torch from pathlib import Path import os import platform from solana_rust_bot import TradingCore, TradeParams from config_loader import config from solana_logger import logger
Fix Windows event loop
if platform.system() == 'Windows': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class ProductionMEVBot: def init(self): logger.info("Initializing Production MEV Bot")
# System Optimization self._setup_system() # Initialize trading core network_config = config.get_network_config() self.trading_core = TradingCore( rpc_url=network_config["rpc_url"], keypair_bytes=config.get_keypair_bytes() ) # Constants self.SOL_DECIMALS = 9 self.MAX_RETRIES = 3 self.RETRY_DELAY = 0.1 # Trading Parameters self._setup_trading_params() # Initialize state self._initialize_state() # Setup CUDA self._setup_cuda() logger.info("Bot initialization complete") def _setup_system(self): """Configure system settings""" os.environ["MKL_NUM_THREADS"] = str(os.cpu_count()) os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count()) os.environ["OMP_NUM_THREADS"] = str(os.cpu_count()) np.set_printoptions(precision=4, suppress=True) def _setup_trading_params(self): """Initialize trading parameters""" self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0)) self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0)) self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002)) self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4)) self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05)) self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000)) self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100)) def _setup_cuda(self): """Configure CUDA for optimal performance""" if not torch.cuda.is_available(): raise RuntimeError("CUDA required for production!") torch.cuda.set_device(0) torch.cuda.empty_cache() torch.set_float32_matmul_precision('high') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True self.stream = torch.cuda.Stream(priority=-1) cuda_info = torch.cuda.get_device_properties(0) logger.info(f"""🚀 CUDA Configuration: GPU: {torch.cuda.get_device_name()} Memory: {cuda_info.total_memory/1e9:.1f}GB Position Size: {self.POSITION_SIZE} WSOL Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL Min Profit: {self.MIN_PROFIT} SOL """)
def _initialize_state(self): """Initialize bot state with proper trade limits""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.active_trades = 0 self.MAX_ACTIVE_TRADES = 1 self.MIN_TRADE_INTERVAL = 0.5 # 2 TPS max self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] } self.ata_cache = {} def _calculate_profit(self, victim_size: float) -> float: """Calculate potential profit for trade size""" with torch.cuda.stream(self.stream): impact = self.POSITION_SIZE / victim_size if victim_size >= 35: rate = 0.012 # Premium rate elif victim_size >= 20: rate = 0.010 # Standard rate else: rate = 0.008 # Mini rate return float(victim_size * impact * rate - 0.001) def _decode_ray_log(self, raw_data: bytes) -> dict: """Decode and validate ray log data""" try: size = int.from_bytes(raw_data[1:9], "little") / 1e9 if not (self.MIN_SIZE <= size <= self.MAX_SIZE): return None profit = self._calculate_profit(size) if profit > self.MIN_PROFIT: return { 'size': size, 'profit': profit, 'data': raw_data } except Exception as e: logger.error(f"Ray log decode error: {str(e)}") return None async def _execute_trade_sequence(self, trade_info: dict, pair: str): """Execute trade with proper rate limiting""" try: current_time = time.time() if self.active_trades >= self.MAX_ACTIVE_TRADES: return if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL: return async with self.execution_lock: market_accounts = config.get_market_accounts(pair) trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol market_accounts["amm_authority"], # AMM Authority needs to be before market market_accounts["market"], # market market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ] # Entry trade entry_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=True, victim_data=base64.b64encode(trade_info['data']).decode(), reuse_blockhash=False, token_a_mint=market_accounts["token_a_mint"], token_b_mint=market_accounts["token_b_mint"] ) start_time = time.time() entry_sig = await self.trading_core.execute_trade_py(entry_params) if not entry_sig: logger.error("Entry trade failed") return # Quick exit trade exit_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=False, victim_data=None, reuse_blockhash=True, token_a_mint=market_accounts["token_a_mint"], token_b_mint=market_accounts["token_b_mint"] ) exit_sig = await self.trading_core.execute_trade_py(exit_params) execution_time = (time.time() - start_time) * 1000 # convert to ms if exit_sig: self.metrics['successful_trades'] += 1 self.metrics['total_profit'] += trade_info['profit'] self.metrics['execution_times'].append(execution_time) self.last_trade_time = time.time() trade_type = ( "PREMIUM" if trade_info['size'] >= 35 else "STANDARD" if trade_info['size'] >= 20 else "MINI" ) logger.info(f"""💫 Trade #{self.metrics['successful_trades']} [{trade_type}] Entry: {entry_sig} Exit: {exit_sig} Size: {trade_info['size']:.2f} SOL Profit: {trade_info['profit']:.6f} SOL Time: {execution_time:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
self.active_trades += 1 self.metrics['trades_executed'] += 1 except Exception as e: logger.error(f"Trade sequence error: {str(e)}", exc_info=True) async def _process_message(self, msg: str): """Process incoming WebSocket messages""" try: data = json.loads(msg) if "params" in data: logs = data["params"].get("result", {}).get("value", {}).get("logs", []) for log in logs: if "ray_log:" in log: raw_data = base64.b64decode(log.split("ray_log:")[1].strip()) trade_info = self._decode_ray_log(raw_data) if trade_info: self.metrics['trades_found'] += 1 async with self.execution_lock: # Here you would need to determine the pair from the log or some context # For simplicity, let's assume it's always SOL-WSOL await self._execute_trade_sequence(trade_info, "SOL-WSOL") except Exception as e: logger.error(f"Message processing error: {str(e)}", exc_info=True) async def start(self): """Start the MEV bot""" network = config.get_network_config() logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50) while self.active: try: async with websockets.connect( network['ws_url'], extra_headers={'api-key': network['api_key']}, ping_interval=None, ping_timeout=None ) as ws: await ws.send(json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "logsSubscribe", "params": [ {"mentions": [config.get('raydium')]}, {"commitment": "processed"} ] })) while True: msg = await ws.recv() await self._process_message(msg) except Exception as e: logger.error(f"WebSocket error: {str(e)}", exc_info=True) await asyncio.sleep(1) async def cleanup(self): """Cleanup resources""" logger.info("Starting cleanup...") self.active = False torch.cuda.empty_cache() if len(self.metrics['execution_times']) > 0: avg_execution = np.mean(self.metrics['execution_times']) success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100 logger.info(f"""🔚 Bot Statistics: Trades Found: {self.metrics['trades_found']} Trades Executed: {self.metrics['trades_executed']} Successful Trades: {self.metrics['successful_trades']} Success Rate: {success_rate:.1f}% Average Execution: {avg_execution:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
async def main(): bot = ProductionMEVBot() try: await bot.start() except KeyboardInterrupt: await bot.cleanup() logger.info("Bot stopped by user") except Exception as e: logger.error(f"Fatal error: {str(e)}", exc_info=True) await bot.cleanup()
if name == "main": try: asyncio.run(main()) except KeyboardInterrupt: pass use lazy_static::lazy_static; use log::info; use pyo3::{prelude::*, exceptions}; use pyo3_asyncio::tokio::future_into_py; use solana_client::{ nonblocking::rpc_client::RpcClient, rpc_config::RpcSendTransactionConfig, }; use solana_sdk::{ commitment_config::{CommitmentConfig, CommitmentLevel}, compute_budget::ComputeBudgetInstruction, message::Message, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::Transaction, instruction::{Instruction, AccountMeta}, }; use spl_associated_token_account::{instruction as associated_instruction, get_associated_token_address}; use spl_token::instruction as token_instruction; use std::{ str::FromStr, sync::Arc, time::{Duration, Instant}, collections::HashMap, }; use tokio::sync::RwLock;
const LAMPORTS_PER_SOL: u64 = 1_000_000_000; const HELIUS_PRIORITY_FEE: u64 = 750_000; const BLOCKHASH_CACHE_DURATION: Duration = Duration::from_secs(2); const COMPUTE_UNITS: u32 = 50_000;
#[derive(Debug)] struct TradeState { active_trades: u32, last_blockhash: Option, last_blockhash_time: Option, token_atas: HashMap<String, Pubkey>, last_ata_check: HashMap<String, Instant>, }
impl Default for TradeState { fn default() -> Self { Self { active_trades: 0, last_blockhash: None, last_blockhash_time: None, token_atas: HashMap::new(), last_ata_check: HashMap::new(), } } }
lazy_static! { static ref RAYDIUM_PROGRAM_ID: Pubkey = Pubkey::from_str("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8").unwrap(); static ref TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap(); static ref SYSTEM_PROGRAM_ID: Pubkey = Pubkey::from_str("11111111111111111111111111111111").unwrap(); static ref ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL").unwrap(); }
#[pyclass] #[derive(Clone)] pub struct TradeParams { #[pyo3(get, set)] pub accounts: Vec, #[pyo3(get, set)] pub amount_in: Option, #[pyo3(get, set)] pub is_buy: bool, #[pyo3(get, set)] pub victim_data: Option, #[pyo3(get, set)] pub reuse_blockhash: bool, #[pyo3(get, set)] pub token_a_mint: String, #[pyo3(get, set)] pub token_b_mint: String, }
#[pymethods] impl TradeParams { #[new] #[pyo3(signature = (accounts, amount_in=None, is_buy=false, victim_data=None, reuse_blockhash=false, token_a_mint=String::new(), token_b_mint=String::new()))] fn new( accounts: Vec, amount_in: Option, is_buy: bool, victim_data: Option, reuse_blockhash: bool, token_a_mint: String, token_b_mint: String, ) -> PyResult { Ok(Self { accounts, amount_in, is_buy, victim_data, reuse_blockhash, token_a_mint, token_b_mint, }) } }
#[pyclass] #[derive(Clone)] pub struct TradingCore { client: Arc, keypair: Arc, trade_state: Arc<RwLock>, }
impl TradingCore { async fn verify_account_balance(&self, account: &Pubkey) -> Result<u64, PyErr> { match self.client.get_token_account_balance(account).await { Ok(balance) => { info!("Account {} balance: {}", account, balance.ui_amount.unwrap_or(0.0)); Ok(balance.amount.parse().unwrap_or(0)) }, Err(e) => { info!("Failed to get balance for {}: {}", account, e); Err(PyErr::new::<exceptions::PyRuntimeError, _>(format!("Balance check failed: {}", e))) } } }
async fn ensure_ata_exists( &self, mint: &Pubkey, owner: &Pubkey, ) -> Result<Pubkey, PyErr> { let ata = get_associated_token_address(owner, mint); info!("🔍 Checking ATA: {} for mint: {}", ata, mint); match self.client.get_account(&ata).await { Ok(account) => { info!("✅ ATA exists: {} with balance: {}", ata, account.lamports); Ok(ata) }, Err(_) => { info!("❌ ATA doesn't exist, creating new one..."); let create_ata_ix = associated_instruction::create_associated_token_account( owner, owner, mint, &TOKEN_PROGRAM_ID ); let recent_blockhash = self.client.get_latest_blockhash().await .map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>( format!("Blockhash error: {}", e) ))?; let message = Message::new(&[create_ata_ix], Some(owner)); let mut tx = Transaction::new_unsigned(message); tx.message.recent_blockhash = recent_blockhash; tx.sign(&[self.keypair.as_ref()], recent_blockhash); info!("📝 Creating ATA transaction"); self.client.send_transaction(&tx).await .map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>( format!("Failed to create ATA: {}", e) ))?; tokio::time::sleep(Duration::from_millis(200)).await; Ok(ata) } } } fn create_trade_instruction( &self, accounts: &[Pubkey], amount_in: u64, is_buy: bool, victim_data: Option<Vec<u8>>, wsol_token_account: &Pubkey, ) -> Result<Vec<Instruction>, PyErr> { let mut instructions = Vec::new(); if let Some(victim) = victim_data { info!("📥 Creating atomic entry trade"); let mut data = vec![9u8]; // Raydium atomic swap data.extend_from_slice(&amount_in.to_le_bytes()); data.extend_from_slice(&victim); info!("📊 Account setup for atomic trade"); let swap_accounts = vec![ AccountMeta::new(accounts[0], true), // Wallet (signer with keypair) AccountMeta::new(accounts[0], false), // User wallet AccountMeta::new(*wsol_token_account, false), // WSOL account AccountMeta::new(accounts[2], false), // User token account AccountMeta::new(accounts[4], false), // AMM Authority AccountMeta::new(accounts[5], false), // Market AccountMeta::new(accounts[6], false), // AMM Open Orders AccountMeta::new(accounts[7], false), // Pool Target AccountMeta::new(accounts[8], false), // Serum Market AccountMeta::new(accounts[9], false), // Serum Bids AccountMeta::new(accounts[10], false), // Serum Asks AccountMeta::new(accounts[11], false), // Event Queue AccountMeta::new(accounts[12], false), // Base Vault AccountMeta::new(accounts[13], false), // Quote Vault AccountMeta::new(accounts[14], false), // Vault Signer AccountMeta::new(*TOKEN_PROGRAM_ID, false), // Token Program AccountMeta::new(*SYSTEM_PROGRAM_ID, false) // System Program ]; instructions.push(Instruction { program_id: *RAYDIUM_PROGRAM_ID, accounts: swap_accounts, data, }); } else { info!("📤 Creating regular exit trade to WSOL account"); instructions.push( token_instruction::transfer( &TOKEN_PROGRAM_ID, &accounts[2], // Source token account wsol_token_account, // Your WSOL account &accounts[0], // Owner &[&accounts[0]], // Added signer amount_in, ).map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>( format!("Transfer error: {:?}", e) ))? ); } Ok(instructions) }}
#[pymethods] impl TradingCore { #[new] fn new(rpc_url: &str, keypair_bytes: Vec) -> PyResult { if keypair_bytes.len() != 64 { return Err(exceptions::PyValueError::new_err( format!("Invalid keypair length: {} bytes (expected 64)", keypair_bytes.len()) )); }
let keypair = Keypair::from_bytes(&keypair_bytes).map_err(|_| { exceptions::PyValueError::new_err("Invalid keypair bytes") })?; info!("Initialized TradingCore with pubkey: {}", keypair.pubkey()); Ok(Self { client: Arc::new(RpcClient::new_with_commitment( rpc_url.to_string(), CommitmentConfig::processed(), )), keypair: Arc::new(keypair), trade_state: Arc::new(RwLock::new(TradeState::default())), }) } #[pyo3(text_signature = "(self, mint_str)")] fn create_ata_py<'py>(&self, mint_str: String, py: Python<'py>) -> PyResult<&'py PyAny> { let self_clone = self.clone(); future_into_py(py, async move { let mint = Pubkey::from_str(&mint_str).map_err(|e| { PyErr::new::<exceptions::PyValueError, _>(format!("Invalid mint: {}", e)) })?; let owner = self_clone.keypair.pubkey(); let result = self_clone.ensure_ata_exists(&mint, &owner).await?; Ok(result.to_string()) }) } fn get_token_balance_py<'py>(&self, account_str: String, py: Python<'py>) -> PyResult<&'py PyAny> { let self_clone = self.clone(); future_into_py(py, async move { let account = Pubkey::from_str(&account_str).map_err(|e| { PyErr::new::<exceptions::PyValueError, _>(format!("Invalid account: {}", e)) })?; let balance = self_clone.verify_account_balance(&account).await?; Ok(balance as f64 / LAMPORTS_PER_SOL as f64) }) } #[pyo3(text_signature = "(self, params)")] fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> { let params_clone = params.clone(); let self_clone = self.clone(); future_into_py(py, async move { info!("🚀 Starting trade execution"); let owner = self_clone.keypair.pubkey(); info!("📝 Owner pubkey: {}", owner); let account_pubkeys: Result<Vec<Pubkey>, _> = params_clone.accounts .iter() .map(|s| { let pubkey = Pubkey::from_str(s); info!("Account conversion: {} -> {:?}", s, pubkey); pubkey }) .collect(); let account_pubkeys = account_pubkeys.map_err(|e| { info!("❌ Account conversion failed: {}", e); PyErr::new::<exceptions::PyValueError, _>(format!("Invalid account: {}", e)) })?; let token_a = Pubkey::from_str(¶ms_clone.token_a_mint) .map_err(|e| PyErr::new::<exceptions::PyValueError, _>( format!("Invalid token A mint: {}", e) ))?; let token_b = Pubkey::from_str(¶ms_clone.token_b_mint) .map_err(|e| PyErr::new::<exceptions::PyValueError, _>( format!("Invalid token B mint: {}", e) ))?; info!("🔍 Token A: {}", token_a); info!("🔍 Token B: {}", token_b); let token_ata = self_clone.ensure_ata_exists(&token_a, &owner).await?; let wsol_token_account = get_associated_token_address(&owner, &token_b); info!("📋 Account Setup Complete:"); info!("Token ATA: {}", token_ata); info!("WSOL Account: {}", wsol_token_account); let mut ixs = vec![ ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS), ComputeBudgetInstruction::set_compute_unit_price(HELIUS_PRIORITY_FEE), ]; let amount_in = (params_clone.amount_in.unwrap_or(0.0) * LAMPORTS_PER_SOL as f64) as u64; info!("💰 Amount in: {} lamports", amount_in); // Verify balances let victim_data = params_clone.victim_data .map(|s| base64::decode(&s).unwrap_or_default()); if victim_data.is_some() { let wsol_balance = self_clone.verify_account_balance(&wsol_token_account).await?; if wsol_balance < amount_in { return Err(PyErr::new::<exceptions::PyRuntimeError, _>( format!("Insufficient WSOL balance: {} < {}", wsol_balance, amount_in) )); } } else { let token_balance = self_clone.verify_account_balance(&token_ata).await?; if token_balance < amount_in { return Err(PyErr::new::<exceptions::PyRuntimeError, _>( format!("Insufficient token balance: {} < {}", token_balance, amount_in) )); } } info!("📦 Creating trade instructions"); let mut trade_ixs = self_clone.create_trade_instruction( &account_pubkeys, amount_in, params_clone.is_buy, victim_data.clone(), &wsol_token_account, )?; ixs.append(&mut trade_ixs); info!("🔄 Getting blockhash"); let blockhash = if params_clone.reuse_blockhash { let state = self_clone.trade_state.read().await; match (&state.last_blockhash, state.last_blockhash_time) { (Some(hash_str), Some(time)) if time.elapsed() < BLOCKHASH_CACHE_DURATION => { info!("♻️ Reusing cached blockhash"); solana_sdk::hash::Hash::from_str(hash_str).unwrap() } _ => { info!("🔄 Getting new blockhash"); drop(state); let new_blockhash = self_clone.client.get_latest_blockhash().await .map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>( format!("Blockhash error: {}", e) ))?; let mut state = self_clone.trade_state.write().await; state.last_blockhash = Some(new_blockhash.to_string()); state.last_blockhash_time = Some(Instant::now()); new_blockhash } } } else { info!("🆕 Getting fresh blockhash"); self_clone.client.get_latest_blockhash().await .map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>( format!("Blockhash error: {}", e) ))? }; info!("📝 Building and signing transaction"); let message = Message::new(&ixs, Some(&owner)); let mut tx = Transaction::new_unsigned(message); tx.message.recent_blockhash = blockhash; tx.sign(&[self_clone.keypair.as_ref()], blockhash); info!("Transaction details:"); info!("Instructions: {}", tx.message.instructions.len()); info!("Signers: {}", tx.signatures.len()); info!("Blockhash: {}", blockhash); let config = RpcSendTransactionConfig { skip_preflight: false, preflight_commitment: Some(CommitmentLevel::Processed), encoding: None, max_retries: Some(3), min_context_slot: None, }; info!("🚀 Sending transaction"); match self_clone.client.send_transaction_with_config(&tx, config).await { Ok(signature) => { info!("✅ Transaction sent: {}", signature); match self_clone.client.confirm_transaction_with_spinner( &signature, &blockhash, CommitmentConfig::processed() ).await { Ok(_) => { info!("✅ Transaction confirmed!"); let mut state = self_clone.trade_state.write().await; state.active_trades += 1; Ok(signature.to_string()) }, Err(e) => { info!("❌ Transaction failed to confirm: {}", e); Err(PyErr::new::<exceptions::PyRuntimeError, _>( format!("Confirmation failed: {}", e) )) } } }, Err(e) => { info!("❌ Transaction failed!"); info!("Error: {:?}", e); info!("Transaction dump: {:?}", tx); Err(PyErr::new::<exceptions::PyRuntimeError, _>( format!("Transaction failed: {}", e) )) } } }) }}
#[pymodule] fn solana_rust_bot(py: Python<'>, m: &PyModule) -> PyResult<()> { pyo3_log::init(); m.add_class::()?; m.add_class::()?; m.add("LAMPORTS_PER_SOL", LAMPORTS_PER_SOL)?; m.add("HELIUS_PRIORITY_FEE", HELIUS_PRIORITY_FEE)?; m.add("COMPUTE_UNITS", COMPUTE_UNITS)?; Ok(()) }
- Assistant
The code snippets you provided showcase two different implementations pertaining to a trading bot, presumably for the Solana blockchain. Each one adopts a different programming language and framework, and they serve similar objectives but differ significantly in their architecture, language features, and frameworks used. Below, I've outlined the main differences and characteristics between the Python-based implementation and the Rust-based implementation with PyO3.
1. Language and Environment
-
Python Implementation:
- The bot is developed using Python, an interpreted, high-level programming language.
- It relies on libraries like
asynciofor asynchronous programming andwebsocketsfor handling WebSocket connections. - The bot uses PyTorch for computation, particularly for trading parameters, and utilizes various Python packages for interacting with the Solana blockchain.
-
Rust Implementation:
- The bot is implemented in Rust, a compiled programming language known for its performance and safety, especially regarding memory.
- Rust uses
tokiofor asynchronous runtime andsolana-client, which allows interaction with the Solana blockchain in a non-blocking manner. - The
PyO3crate is used to bridge Python and Rust, allowing the Rust code to be called from Python as a native extension.
2. Architecture and State Management
-
Python Implementation:
- The architecture follows an object-oriented programming pattern, encapsulated in a
ProductionMEVBotclass. - State management relies heavily on the variables and attributes of the class instance. It handles active trades, execution time, and trade metrics as instance variables.
- Async methods (
async def) are defined for trade execution and message processing, with clear separation of the buying/selling logic.
- The architecture follows an object-oriented programming pattern, encapsulated in a
-
Rust Implementation:
- The Rust implementation uses structs to define the state (
TradeState) and essential parameters (TradeParams). - It manages state using
RwLockandArcfor concurrency, which allows for safe shared access to mutable state across asynchronous tasks. - The trading core is encapsulated within the
TradingCorestruct, and methods are defined to perform specific actions like balance verification and transaction execution.
- The Rust implementation uses structs to define the state (
3. Execution and Trading Logic
-
Python Implementation:
- The trading logic is segmented into various methods that deal with calculation, execution, and processing of incoming messages.
- Incorporates asyncio locks to manage concurrency (rate-limiting trades and ensuring thread-safe trade execution).
- The trade execution logic appears simple, with three main parameters passed to the
TradeParamsobject for trades.
-
Rust Implementation:
- The Rust version has a more complex approach to execution, taking into account factors such as computation limits, blockhash caching, and transaction signing.
- It directly handles account and transaction-level activities with better memory efficiency and safety guarantees, thanks to Rust's compiler checks.
- The bot's methods explicitly handle potential errors with detailed logging and exception management using
PyResult.
4. Logging and Debugging
-
Python Implementation:
- Utilizes a logging mechanism provided by the
solana_loggerlibrary, allowing logging of information with varying levels of detail. - Logging statements are present throughout the execution flow for clarity and debugging during trading operations.
- Utilizes a logging mechanism provided by the
-
Rust Implementation:
- Relies on the
logcrate to handle logging, also providing detailed information about internal state changes and operations. - Similar to the Python version, logging occurs at various critical points to aid in debugging and understanding the execution flow.
- Relies on the
5. Dependency Management
-
Python Implementation:
- Uses a variety of Python libraries, which are typically listed in a requirements.txt or similar for dependency management.
- Utilizes virtual environments for isolation.
-
Rust Implementation:
- Utilizes Cargo, Rust's package manager, for dependency management, with dependencies specified in
Cargo.toml. - Rust's toolchain handles installations and builds, offering an integrated approach to managing links and libraries.
- Utilizes Cargo, Rust's package manager, for dependency management, with dependencies specified in
Summary
In summary, the key differences between the two implementations are based on the programming language used (Python vs. Rust), their environments, state management, trade execution logic, and their architectural patterns. The Python implementation emphasizes simplicity and rapid development, whereas the Rust implementation focuses on performance, safety, and persistence through a more complex but efficient approach. Each has its strengths depending on the context and specific requirements of the trading bot.
-
- User
import asyncio import json import websockets import time import base64 import numpy as np import torch from pathlib import Path import os import platform from solana_rust_bot import TradingCore, TradeParams from config_loader import config from solana_logger import logger
Fix Windows event loop
if platform.system() == 'Windows': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class ProductionMEVBot: def init(self): logger.info("Initializing Production MEV Bot")
# System Optimization self._setup_system() # Initialize trading core network_config = config.get_network_config() self.trading_core = TradingCore( rpc_url=network_config["rpc_url"], keypair_bytes=config.get_keypair_bytes() ) # Constants self.WSOL_MINT = "So11111111111111111111111111111111111111112" self.SOL_DECIMALS = 9 self.MAX_RETRIES = 3 self.RETRY_DELAY = 0.1 # Trading Parameters self._setup_trading_params() # Initialize state self._initialize_state() # Setup CUDA self._setup_cuda() logger.info("Bot initialization complete") def _setup_system(self): """Configure system settings""" os.environ["MKL_NUM_THREADS"] = str(os.cpu_count()) os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count()) os.environ["OMP_NUM_THREADS"] = str(os.cpu_count()) np.set_printoptions(precision=4, suppress=True) def _setup_trading_params(self): """Initialize trading parameters""" self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0)) self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0)) self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002)) self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4)) self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05)) self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000)) self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100)) def _setup_cuda(self): """Configure CUDA for optimal performance""" if not torch.cuda.is_available(): raise RuntimeError("CUDA required for production!") torch.cuda.set_device(0) torch.cuda.empty_cache() torch.set_float32_matmul_precision('high') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True self.stream = torch.cuda.Stream(priority=-1) cuda_info = torch.cuda.get_device_properties(0) logger.info(f"""🚀 CUDA Configuration: GPU: {torch.cuda.get_device_name()} Memory: {cuda_info.total_memory/1e9:.1f}GB Position Size: {self.POSITION_SIZE} WSOL Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL Min Profit: {self.MIN_PROFIT} SOL """)
def _initialize_state(self): """Initialize bot state with proper trade limits""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.active_trades = 0 self.MAX_ACTIVE_TRADES = 1 self.MIN_TRADE_INTERVAL = 0.5 # 2 TPS max self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] } self.ata_cache = {} def _calculate_profit(self, victim_size: float) -> float: """Calculate potential profit for trade size""" with torch.cuda.stream(self.stream): impact = self.POSITION_SIZE / victim_size if victim_size >= 35: rate = 0.012 # Premium rate elif victim_size >= 20: rate = 0.010 # Standard rate else: rate = 0.008 # Mini rate return float(victim_size * impact * rate - 0.001) def _decode_ray_log(self, raw_data: bytes) -> dict: """Decode and validate ray log data""" try: size = int.from_bytes(raw_data[1:9], "little") / 1e9 if not (self.MIN_SIZE <= size <= self.MAX_SIZE): return None profit = self._calculate_profit(size) if profit > self.MIN_PROFIT: return { 'size': size, 'profit': profit, 'data': raw_data } except Exception as e: logger.error(f"Ray log decode error: {str(e)}") return None async def _execute_trade_sequence(self, trade_info: dict): """Execute trade with proper rate limiting""" try: current_time = time.time() if self.active_trades >= self.MAX_ACTIVE_TRADES: return if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL: return async with self.execution_lock: market_accounts = config.get_market_accounts() trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol market_accounts["amm_authority"], # AMM Authority needs to be before market market_accounts["market"], # market market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ] # Entry trade entry_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=True, victim_data=base64.b64encode(trade_info['data']).decode(), reuse_blockhash=False, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) start_time = time.time() entry_sig = await self.trading_core.execute_trade_py(entry_params) if not entry_sig: logger.error("Entry trade failed") return # Quick exit trade exit_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=False, victim_data=None, reuse_blockhash=True, token_a_mint=self.WSOL_MINT, token_b_mint=self.WSOL_MINT ) exit_sig = await self.trading_core.execute_trade_py(exit_params) execution_time = (time.time() - start_time) * 1000 # convert to ms if exit_sig: self.metrics['successful_trades'] += 1 self.metrics['total_profit'] += trade_info['profit'] self.metrics['execution_times'].append(execution_time) self.last_trade_time = time.time() trade_type = ( "PREMIUM" if trade_info['size'] >= 35 else "STANDARD" if trade_info['size'] >= 20 else "MINI" ) logger.info(f"""💫 Trade #{self.metrics['successful_trades']} [{trade_type}] Entry: {entry_sig} Exit: {exit_sig} Size: {trade_info['size']:.2f} SOL Profit: {trade_info['profit']:.6f} SOL Time: {execution_time:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
self.active_trades += 1 self.metrics['trades_executed'] += 1 except Exception as e: logger.error(f"Trade sequence error: {str(e)}") async def _process_message(self, msg: str): """Process incoming WebSocket messages""" try: data = json.loads(msg) if "params" in data: logs = data["params"].get("result", {}).get("value", {}).get("logs", []) for log in logs: if "ray_log:" in log: raw_data = base64.b64decode(log.split("ray_log:")[1].strip()) trade_info = self._decode_ray_log(raw_data) if trade_info: self.metrics['trades_found'] += 1 async with self.execution_lock: await self._execute_trade_sequence(trade_info) except Exception as e: logger.error(f"Message processing error: {str(e)}") async def start(self): """Start the MEV bot""" network = config.get_network_config() logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50) while self.active: try: async with websockets.connect( network['ws_url'], extra_headers={'api-key': network['api_key']}, ping_interval=None, ping_timeout=None ) as ws: await ws.send(json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "logsSubscribe", "params": [ {"mentions": [config.get('raydium')]}, {"commitment": "processed"} ] })) while True: msg = await ws.recv() await self._process_message(msg) except Exception as e: logger.error(f"WebSocket error: {str(e)}") await asyncio.sleep(1) async def cleanup(self): """Cleanup resources""" logger.info("Starting cleanup...") self.active = False torch.cuda.empty_cache() if len(self.metrics['execution_times']) > 0: avg_execution = np.mean(self.metrics['execution_times']) success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100 logger.info(f"""🔚 Bot Statistics: Trades Found: {self.metrics['trades_found']} Trades Executed: {self.metrics['trades_executed']} Successful Trades: {self.metrics['successful_trades']} Success Rate: {success_rate:.1f}% Average Execution: {avg_execution:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
async def main(): bot = ProductionMEVBot() try: await bot.start() except KeyboardInterrupt: await bot.cleanup() logger.info("Bot stopped by user") except Exception as e: logger.error(f"Fatal error: {str(e)}") await bot.cleanup()
if name == "main": try: asyncio.run(main()) except KeyboardInterrupt: pass sorry this one and this one import asyncio import json import websockets import time import base64 import numpy as np import torch from pathlib import Path import os import platform from solana_rust_bot import TradingCore, TradeParams from config_loader import config from solana_logger import logger
Fix Windows event loop
if platform.system() == 'Windows': asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class ProductionMEVBot: def init(self): logger.info("Initializing Production MEV Bot")
# System Optimization self._setup_system() # Initialize trading core network_config = config.get_network_config() self.trading_core = TradingCore( rpc_url=network_config["rpc_url"], keypair_bytes=config.get_keypair_bytes() ) # Constants self.SOL_DECIMALS = 9 self.MAX_RETRIES = 3 self.RETRY_DELAY = 0.1 # Trading Parameters self._setup_trading_params() # Initialize state self._initialize_state() # Setup CUDA self._setup_cuda() logger.info("Bot initialization complete") def _setup_system(self): """Configure system settings""" os.environ["MKL_NUM_THREADS"] = str(os.cpu_count()) os.environ["NUMEXPR_NUM_THREADS"] = str(os.cpu_count()) os.environ["OMP_NUM_THREADS"] = str(os.cpu_count()) np.set_printoptions(precision=4, suppress=True) def _setup_trading_params(self): """Initialize trading parameters""" self.MIN_SIZE = float(config.get("SANDWICH_MIN_VICTIM_SIZE", 5.0)) self.MAX_SIZE = float(config.get("SANDWICH_MAX_VICTIM_SIZE", 50.0)) self.MIN_PROFIT = float(config.get("MIN_PROFIT", 0.002)) self.POSITION_SIZE = float(config.get("FRONT_RUN_AMOUNT", 0.4)) self.MAX_IMPACT = float(config.get("SANDWICH_MAX_IMPACT", 0.05)) self.PRIORITY_FEE_BASE = int(config.get("PRIORITY_FEE", 750000)) self.SLIPPAGE_BPS = int(config.get("SLIPPAGE_BPS", 100)) def _setup_cuda(self): """Configure CUDA for optimal performance""" if not torch.cuda.is_available(): raise RuntimeError("CUDA required for production!") torch.cuda.set_device(0) torch.cuda.empty_cache() torch.set_float32_matmul_precision('high') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True self.stream = torch.cuda.Stream(priority=-1) cuda_info = torch.cuda.get_device_properties(0) logger.info(f"""🚀 CUDA Configuration: GPU: {torch.cuda.get_device_name()} Memory: {cuda_info.total_memory/1e9:.1f}GB Position Size: {self.POSITION_SIZE} WSOL Trade Range: {self.MIN_SIZE}-{self.MAX_SIZE} SOL Min Profit: {self.MIN_PROFIT} SOL """)
def _initialize_state(self): """Initialize bot state with proper trade limits""" self.active = True self.execution_lock = asyncio.Lock() self.last_trade_time = 0 self.active_trades = 0 self.MAX_ACTIVE_TRADES = 1 self.MIN_TRADE_INTERVAL = 0.5 # 2 TPS max self.metrics = { 'trades_found': 0, 'trades_executed': 0, 'successful_trades': 0, 'total_profit': 0.0, 'execution_times': [] } self.ata_cache = {} def _calculate_profit(self, victim_size: float) -> float: """Calculate potential profit for trade size""" with torch.cuda.stream(self.stream): impact = self.POSITION_SIZE / victim_size if victim_size >= 35: rate = 0.012 # Premium rate elif victim_size >= 20: rate = 0.010 # Standard rate else: rate = 0.008 # Mini rate return float(victim_size * impact * rate - 0.001) def _decode_ray_log(self, raw_data: bytes) -> dict: """Decode and validate ray log data""" try: size = int.from_bytes(raw_data[1:9], "little") / 1e9 if not (self.MIN_SIZE <= size <= self.MAX_SIZE): return None profit = self._calculate_profit(size) if profit > self.MIN_PROFIT: return { 'size': size, 'profit': profit, 'data': raw_data } except Exception as e: logger.error(f"Ray log decode error: {str(e)}") return None async def _execute_trade_sequence(self, trade_info: dict, pair: str): """Execute trade with proper rate limiting""" try: current_time = time.time() if self.active_trades >= self.MAX_ACTIVE_TRADES: return if current_time - self.last_trade_time < self.MIN_TRADE_INTERVAL: return async with self.execution_lock: market_accounts = config.get_market_accounts(pair) trade_accounts = [ config.get("wallet"), # signer config.get("wallet"), # user config.get("wsol_token_account"), # user_token config.get("wsol_token_account"), # user_wsol market_accounts["amm_authority"], # AMM Authority needs to be before market market_accounts["market"], # market market_accounts["amm_open_orders"], # amm_open_orders market_accounts["amm_target"], # amm_target market_accounts["serum_market"], # serum_market market_accounts["serum_bids"], # serum_bids market_accounts["serum_asks"], # serum_asks market_accounts["event_queue"], # event_queue market_accounts["base_vault"], # base_vault market_accounts["quote_vault"], # quote_vault market_accounts["vault_signer"] # vault_signer ] # Entry trade entry_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=True, victim_data=base64.b64encode(trade_info['data']).decode(), reuse_blockhash=False, token_a_mint=market_accounts["token_a_mint"], token_b_mint=market_accounts["token_b_mint"] ) start_time = time.time() entry_sig = await self.trading_core.execute_trade_py(entry_params) if not entry_sig: logger.error("Entry trade failed") return # Quick exit trade exit_params = TradeParams( accounts=trade_accounts, amount_in=self.POSITION_SIZE, is_buy=False, victim_data=None, reuse_blockhash=True, token_a_mint=market_accounts["token_a_mint"], token_b_mint=market_accounts["token_b_mint"] ) exit_sig = await self.trading_core.execute_trade_py(exit_params) execution_time = (time.time() - start_time) * 1000 # convert to ms if exit_sig: self.metrics['successful_trades'] += 1 self.metrics['total_profit'] += trade_info['profit'] self.metrics['execution_times'].append(execution_time) self.last_trade_time = time.time() trade_type = ( "PREMIUM" if trade_info['size'] >= 35 else "STANDARD" if trade_info['size'] >= 20 else "MINI" ) logger.info(f"""💫 Trade #{self.metrics['successful_trades']} [{trade_type}] Entry: {entry_sig} Exit: {exit_sig} Size: {trade_info['size']:.2f} SOL Profit: {trade_info['profit']:.6f} SOL Time: {execution_time:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
self.active_trades += 1 self.metrics['trades_executed'] += 1 except Exception as e: logger.error(f"Trade sequence error: {str(e)}", exc_info=True) async def _process_message(self, msg: str): """Process incoming WebSocket messages""" try: data = json.loads(msg) if "params" in data: logs = data["params"].get("result", {}).get("value", {}).get("logs", []) for log in logs: if "ray_log:" in log: raw_data = base64.b64decode(log.split("ray_log:")[1].strip()) trade_info = self._decode_ray_log(raw_data) if trade_info: self.metrics['trades_found'] += 1 async with self.execution_lock: # Here you would need to determine the pair from the log or some context # For simplicity, let's assume it's always SOL-WSOL await self._execute_trade_sequence(trade_info, "SOL-WSOL") except Exception as e: logger.error(f"Message processing error: {str(e)}", exc_info=True) async def start(self): """Start the MEV bot""" network = config.get_network_config() logger.info("\n" + "="*50 + "\n🚀 Starting MEV Bot\n" + "="*50) while self.active: try: async with websockets.connect( network['ws_url'], extra_headers={'api-key': network['api_key']}, ping_interval=None, ping_timeout=None ) as ws: await ws.send(json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "logsSubscribe", "params": [ {"mentions": [config.get('raydium')]}, {"commitment": "processed"} ] })) while True: msg = await ws.recv() await self._process_message(msg) except Exception as e: logger.error(f"WebSocket error: {str(e)}", exc_info=True) await asyncio.sleep(1) async def cleanup(self): """Cleanup resources""" logger.info("Starting cleanup...") self.active = False torch.cuda.empty_cache() if len(self.metrics['execution_times']) > 0: avg_execution = np.mean(self.metrics['execution_times']) success_rate = (self.metrics['successful_trades'] / max(self.metrics['trades_executed'], 1)) * 100 logger.info(f"""🔚 Bot Statistics: Trades Found: {self.metrics['trades_found']} Trades Executed: {self.metrics['trades_executed']} Successful Trades: {self.metrics['successful_trades']} Success Rate: {success_rate:.1f}% Average Execution: {avg_execution:.3f}ms Total Profit: {self.metrics['total_profit']:.6f} SOL """)
async def main(): bot = ProductionMEVBot() try: await bot.start() except KeyboardInterrupt: await bot.cleanup() logger.info("Bot stopped by user") except Exception as e: logger.error(f"Fatal error: {str(e)}", exc_info=True) await bot.cleanup()
if name == "main": try: asyncio.run(main()) except KeyboardInterrupt: pass
- Assistant
The two code snippets you provided for the
ProductionMEVBotclass in Python appear to be quite similar, but there are several key differences and improvements between them. Below, I have compared the two snippets and highlighted their significant differences:Key Differences between the Two Snippets
-
Entry and Exit Logic in
_execute_trade_sequence:- First Snippet:
- The entry and exit trades use a constant minting address (
self.WSOL_MINT) for both the entry and exit trade parameters.
- The entry and exit trades use a constant minting address (
- Second Snippet:
- The entry and exit trades reference dynamic minting addresses for tokens using
market_accounts["token_a_mint"]andmarket_accounts["token_b_mint"]in the trading parameters. - This change allows the trading bot to adapt to different token pairs dynamically rather than being hardcoded to use only WSOL.
- The entry and exit trades reference dynamic minting addresses for tokens using
- First Snippet:
-
Parameters in
_execute_trade_sequence:- First Snippet:
- It has a simplified design, assuming a single trading pair and potentially limiting flexibility.
- Second Snippet:
- Includes an additional
pairparameter in_execute_trade_sequence, which provides more context for trade executions. - This allows the bot to use different pairs when executing trades, enhancing its versatility.
- Includes an additional
- First Snippet:
-
Error Logging and Handling:
- First Snippet:
- Basic error handling with logging in try-except blocks.
- Second Snippet:
- Enhanced error handling that uses
exc_info=Truein logging statements, providing more detailed traceback information in the logs, which is helpful for debugging.
- Enhanced error handling that uses
- First Snippet:
-
Metric Tracking:
- First Snippet:
- After trade executions, it tracks successful trades and updates the metrics accordingly, but there's no flexibility in examining which pair was traded.
- Second Snippet:
- The successful trade metrics update uses a condition to flexibly extract and log the trading type based on trade size.
- It explicitly tracks whether it is trading a "PREMIUM", "STANDARD", or "MINI" trade, adding another layer of detail for analyzing trade performance.
- First Snippet:
-
Potential Performance Improvements:
- Second Snippet:
- By tracking active trades and last trade timestamps using a more dynamic method, it's likely to improve performance when managing active trades.
- The ability to adjust to different trading conditions by incorporating dynamic account parameters leads to better adaptability compared to the first snippet.
- Second Snippet:
-
Miscellaneous Changes:
- Both snippets retain essential functionality, such as setting up CUDA and managing WebSocket connections, but the second version has a cleaner structure that focuses on robustness and flexibility.
Conclusion
Overall, the second snippet incorporates suggestions for improvement over the first one, primarily focusing on trading flexibility, enhanced error logging, and maintaining performance while allowing for better management of different token pairs. The modifications make the bot more capable of adapting to various market conditions and improve its troubleshooting mechanisms. If you are developing or maintaining a trading bot, adopting these enhancements is advisable for better long-term performance and debugging capabilities.
-