Based on the code you provided and the context, the relevant code for finding trading opportunities and selecting the appropriate pools would likely be in the parallel_scalper.py file, particularly in the ParallelScalper class, in the _find_opportunities() method.
Here's where to look:
File: parallel_scalper.py
This file contains the main logic for your trading strategy and will typically handle opportunities identification and trade execution. The _find_opportunities() method is where the bot continuously checks for trading opportunities based on active trading pools.
User
import asyncio
import logging
from typing import Optional, Dict
import time
my project is using the wrong thing for trading it needs to be using raydium v4 not jupiter swap's addrss so whats making it use the secondary over the primary import asyncio
import logging
from typing import Dict, Set, List, Optional
from dataclasses import dataclass
import time
from concurrent.futures import ThreadPoolExecutor
import torch
# Thread safety
self._position_lock = asyncio.Lock()
self._trading_lock = asyncio.Lock()
self._active_tokens: Set[str] = set()
# Performance optimization
self.thread_pool = ThreadPoolExecutor(max_workers=32)
self.device = torch.device("cuda")
torch.backends.cudnn.benchmark = True
# State tracking
self.positions: Dict[str, Position] = {}
self.last_trade_time = 0
self.trades_made = 0
self.successful_trades = 0
self.total_profit = 0.0
self.running = True
# Load configuration
self._load_config()
logger.info("Initialized ParallelScalper with enhanced safety checks")
self._log_config()
def _load_config(self):
"""Load and validate configuration"""
try:
trading_cfg = self.config['trading']
self.position_size = trading_cfg['position']['size']
self.max_position = trading_cfg['position']['max_size']
self.max_positions = min(5, trading_cfg['position'].get('max_concurrent', 5))
# Validate critical parameters
assert 0 < self.position_size <= 0.1, "Invalid position size"
assert self.position_size <= self.max_position, "Max position too small"
# Risk parameters
self.take_profit = 0.004 # 0.4%
self.stop_loss = 0.006 # 0.6%
# Trading limits
self.min_volume = trading_cfg['limits']['min_volume']
self.min_liquidity = trading_cfg['limits']['min_liquidity']
self.max_impact = trading_cfg['limits']['max_price_impact']
except (KeyError, AssertionError) as e:
logger.error(f"Configuration error: {e}")
raise ValueError("Invalid configuration") from e
async def start(self):
"""Start the trading system"""
logger.info("Starting trading operations...")
try:
# Start background tasks
position_task = asyncio.create_task(self._manage_positions())
opportunity_task = asyncio.create_task(self._find_opportunities())
# Wait for tasks
await asyncio.gather(position_task, opportunity_task)
except Exception as e:
logger.error(f"Trading error: {e}")
self.running = False
async def stop(self):
"""Stop trading and cleanup"""
logger.info("Stopping trading operations...")
self.running = False
try:
async with self._position_lock:
# Close all positions
for token_mint in list(self.positions.keys()):
await self._emergency_exit(token_mint)
# Cleanup resources
self.thread_pool.shutdown()
torch.cuda.empty_cache()
except Exception as e:
logger.error(f"Cleanup error: {e}")
async def _find_opportunities(self):
"""Background task to find opportunities"""
while self.running:
try:
if len(self.positions) >= self.max_positions:
await asyncio.sleep(1)
continue
# Get active pools from monitor
active_pools = self.monitor.get_active_pools()
if not active_pools:
await asyncio.sleep(0.1)
continue
# Process each pool
for pool in active_pools:
if not self.running:
break
token_mint = pool['token_mint']
if token_mint not in self._active_tokens and await self.validate_trade(token_mint):
await self.enter_position(token_mint)
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"Opportunity finding error: {e}")
await asyncio.sleep(1)
async def _manage_positions(self):
"""Background task to manage positions"""
while self.running:
try:
async with self._position_lock:
current_time = time.time()
for token_mint, position in list(self.positions.items()):
try:
# Get current price from monitor
pool_data = self.monitor.active_pools.get(token_mint)
if not pool_data:
continue
current_price = pool_data['quote_sol'] / pool_data['base_sol']
# Check take profit
if current_price >= position.take_profit_price:
await self._exit_position(token_mint, current_price, "take_profit")
# Check stop loss
elif current_price <= position.stop_loss_price:
await self._exit_position(token_mint, current_price, "stop_loss")
except Exception as e:
logger.error(f"Position management error for {token_mint}: {e}")
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"Position management error: {e}")
await asyncio.sleep(1)
def _log_config(self):
"""Log configuration for monitoring"""
logger.info("Trading Configuration:")
logger.info(f"Position Size: {self.position_size} SOL")
logger.info(f"Max Positions: {self.max_positions}")
logger.info(f"Take Profit: {self.take_profit*100}%")
logger.info(f"Stop Loss: {self.stop_loss*100}%")
logger.info(f"Min Volume: ${self.min_volume}")
logger.info(f"Min Liquidity: ${self.min_liquidity}")
async def validate_trade(self, token_mint: str) -> bool:
"""Validate trade with enhanced checks"""
try:
# Prevent duplicate trading
if token_mint in self._active_tokens:
return False
# Check active positions limit
if len(self.positions) >= self.max_positions:
return False
# Get pool data
pool_data = self.monitor.active_pools.get(token_mint)
if not pool_data:
return False
# Check volume
volume = pool_data.get('base_sol', 0) * 110 # Approximate USD volume
if volume < self.min_volume:
return False
# Check liquidity
liquidity = pool_data.get('quote_sol', 0) * 110 # Approximate USD liquidity
if liquidity < self.min_liquidity:
return False
# Rate limiting
if time.time() - self.last_trade_time < 1.0:
return False
return True
except Exception as e:
logger.error(f"Trade validation error: {e}")
return False
async def enter_position(self, token_mint: str) -> bool:
"""Enter position with retry logic and safeguards"""
try:
async with self._trading_lock:
if not await self.validate_trade(token_mint):
return False
# Mark token as being traded
self._active_tokens.add(token_mint)
try:
# Get pool data
pool_data = self.monitor.active_pools[token_mint]
entry_price = pool_data['quote_sol'] / pool_data['base_sol']
# Prepare trade parameters
trade_params = {
"pool_address": token_mint,
"amount_in": str(int(self.position_size * self.config['system']['scaling_factor'])),
"min_amount_out": str(int(self.position_size * (1 - self.config['trading']['execution']['slippage']) * self.config['system']['scaling_factor']))
}
# Execute with retry
for attempt in range(3):
try:
signature = await self._execute_trade(trade_params)
if signature:
await self._handle_successful_entry(token_mint, entry_price)
return True
except Exception as e:
logger.error(f"Entry attempt {attempt + 1} failed: {e}")
await asyncio.sleep(0.1 * (2 ** attempt)) # Exponential backoff
return False
finally:
self._active_tokens.remove(token_mint)
except Exception as e:
logger.error(f"Position entry error: {e}")
return False
async def _execute_trade(self, params: dict) -> Optional[str]:
"""Execute trade through Rust core with optimized parameters"""
return await self.trading.execute_trade(params)
async def _handle_successful_entry(self, token_mint: str, entry_price: float):
"""Handle successful entry"""
try:
position = Position(
token_mint=token_mint,
entry_price=entry_price,
position_size=self.position_size,
entry_time=time.time(),
take_profit_price=entry_price * (1 + self.take_profit),
stop_loss_price=entry_price * (1 - self.stop_loss)
)
self.positions[token_mint] = position
self.last_trade_time = time.time()
self.trades_made += 1
logger.info(f"Position entered:")
logger.info(f"Token: {token_mint}")
logger.info(f"Entry Price: ${entry_price:.4f}")
logger.info(f"Size: {self.position_size} SOL")
logger.info(f"Take Profit: ${position.take_profit_price:.4f}")
logger.info(f"Stop Loss: ${position.stop_loss_price:.4f}")
except Exception as e:
logger.error(f"Entry handling error: {e}")
async def _exit_position(self, token_mint: str, current_price: float, reason: str):
"""Exit position with reason"""
try:
position = self.positions[token_mint]
# Calculate PnL
pnl = (current_price - position.entry_price) / position.entry_price
profit = position.position_size * current_price * pnl
# Prepare exit parameters
exit_params = {
"pool_address": token_mint,
"amount_in": str(int(position.position_size * self.config['system']['scaling_factor'])),
"min_amount_out": str(int(position.position_size * (1 - self.config['trading']['execution']['slippage']) * self.config['system']['scaling_factor']))
}
# Execute exit
signature = await self._execute_trade(exit_params)
if signature:
self.total_profit += profit
if profit > 0:
self.successful_trades += 1
logger.info(f"Position exited ({reason}):")
logger.info(f"Token: {token_mint}")
logger.info(f"Exit Price: ${current_price:.4f}")
logger.info(f"PnL: {pnl*100:.2f}%")
logger.info(f"Profit: {profit:.6f} SOL")
del self.positions[token_mint]
except Exception as e:
logger.error(f"Exit error for {token_mint}: {e}")
position.attempts += 1
if position.attempts >= position.max_attempts:
await self._emergency_exit(token_mint)
async def _emergency_exit(self, token_mint: str):
"""Emergency exit for problematic positions"""
try:
logger.warning(f"Emergency exit for {token_mint}")
position = self.positions[token_mint]
# Force exit at market
exit_params = {
"pool_address": token_mint,
"amount_in": str(int(position.position_size * self.config['system']['scaling_factor'])),
"min_amount_out": str(int(position.position_size * 0.99 * self.config['system']['scaling_factor'])), # 1% max slippage for emergency
"priority_fee": self.config['trading']['execution']['max_priority_fee'] # Use max priority fee
}
signature = await self._execute_trade(exit_params)
if signature:
logger.info(f"Emergency exit successful: {signature}")
del self.positions[token_mint]
else:
logger.error(f"Emergency exit failed for {token_mint}")
except Exception as e:
logger.error(f"Emergency exit error: {e}")
# Force remove from tracking
self.positions.pop(token_mint, None) # main.py
import asyncio
import logging
import json
import os
from pathlib import Path
import signal
import sys
from logging.handlers import RotatingFileHandler
from solana_rust_bot import TradingCore, TradingConfig
from raydium_monitor import RaydiumMonitor
from parallel_scalper import ParallelScalper
def handle_shutdown(sig, frame):
"""Handle shutdown signals"""
logger.info("Shutdown signal received...")
if not shutdown_event.is_set():
shutdown_event.set()
if name == "main":
# Register signal handlers
signal.signal(signal.SIGINT, handle_shutdown)
signal.signal(signal.SIGTERM, handle_shutdown)
code
try:
asyncio.run(main())
except KeyboardInterrupt:
logger.info("Shutting down via Ctrl+C...")
except Exception as e:
logger.error(f"Fatal error: {str(e)}")
sys.exit(1)# performance_monitor.py
import asyncio
import logging
import time
from typing import Dict, List
import json
from dataclasses import dataclass, asdict
import numpy as np
logger = logging.getLogger(name)
@dataclass
class PerformanceMetrics:
total_trades: int = 0
successful_trades: int = 0
failed_trades: int = 0
total_profit: float = 0.0
win_rate: float = 0.0
avg_latency: float = 0.0
trades_per_minute: float = 0.0
active_positions: int = 0
async def execute_atomic_trade(self, params: Dict) -> Optional[str]:
"""Execute atomic trade with optimized parameters"""
try:
# Rate limiting for Helius
current_time = time.time()
if current_time - self.last_execution < 0.2: # 5 TPS limit
await asyncio.sleep(0.2)
# Prepare optimized parameters
execution_params = {
**params,
"skip_preflight": True,
"compute_limit": self.config['trading']['execution']['compute_limit'],
"priority_fee": await self._get_optimal_priority_fee()
}
# Execute trade
signature = await self.trading.execute_trade(execution_params)
self.last_execution = time.time()
if signature:
logger.info(f"Trade executed: {signature}")
logger.info(f"Priority fee: {execution_params['priority_fee']}")
return signature
return None
except Exception as e:
logger.error(f"Trade execution error: {str(e)}")
return None
async def _get_optimal_priority_fee(self) -> int:
"""Get optimal priority fee from Helius"""
try:
base_fee = self.config['trading']['execution']['priority_fee']
max_fee = self.config['trading']['execution']['max_priority_fee']
# Get recent fee estimate
recent_fee = await self.trading.get_priority_fee()
# Use the higher of base fee or recent estimate
optimal_fee = max(base_fee, recent_fee)
# Cap at maximum
return min(optimal_fee, max_fee)
except Exception as e:
logger.error(f"Fee estimation error: {str(e)}")
return self.config['trading']['execution']['priority_fee']
logger.info("Stopping Raydium monitor...")
It seems you're trying to ensure your trading bot uses Raydium v4 instead of Jupiter's swap address for trading operations. Given the context you've provided, there are several areas where you can check to ensure the correct implementation of pool address determination and selection.
Key Points to Verify
Correct Pool Address Configuration:
Ensure that the correct pool addresses for Raydium v4 are being utilized. You've assigned the Raydium v4 program ID and mentioned pool addresses. Confirm that these are accurately defined in your RaydiumMonitor.
Conditional Logic for Pool Selection:
In your code where pools are processed and selected, make certain that conditions are implemented appropriately to prioritize Raydium pools over others. For instance, explicitly check for Raydium pools in your loop where you are fetching active_pools.
Data Being Read:
When calling self.monitor.get_active_pools(), ensure that this method is indeed returning the right data (i.e., pools related to Raydium). You may want to put logging statements here to confirm if the active pools contain Raydium v4 pools and if they're being handled correctly.
Execution Routing:
In your trading functions, ensure that calls to enter positions and execute trades are pointed to the right pool address based on Raydium v4. Cross-check that the parameters being passed to _execute_trade contain the expected addresses.
Debugging Logs:
Utilize additional logging to track where the logic might be errant. Check if:
The bot detects pools correctly.
It tries to enter positions using the correct pools.
It logs appropriately when it skips any selected pool based on validation criteria.
Example Fix
Consider revising the _find_opportunities method to specifically focus more heavily on Raydium pools. Here’s a modified version incorporating logging and checks:
python
async def _find_opportunities(self):
"""Background task to find opportunities"""
while self.running:
try:
if len(self.positions) >= self.max_positions:
await asyncio.sleep(1)
continue
# Get active pools from monitor
active_pools = self.monitor.get_active_pools()
if not active_pools:
await asyncio.sleep(0.1)
continue
# Filter Raydium pools and process them
raydium_pools = [pool for pool in active_pools if pool['token_mint'] in self.monitor.SOL_POOLS]
if not raydium_pools:
logger.debug("No Raydium pools available for trading.")
await asyncio.sleep(0.1)
continue
# Process each Raydium pool
for pool in raydium_pools:
token_mint = pool['token_mint']
if token_mint not in self._active_tokens and await self.validate_trade(token_mint):
await self.enter_position(token_mint)
await asyncio.sleep(0.1)
except Exception as e:
logger.error(f"Opportunity finding error: {e}")
await asyncio.sleep(1)
Conclusion
By checking the configuration and logic closely as highlighted above, and focusing on precise filtering of pools, you should be able to ensure that your trading bot operates using the correct Raydium v4 pools instead of unintended alternatives like those from Jupiter. Remember to utilize ample logging statements, which can help trace the flow of execution and catch where things may be going awry.
Key Method: Look specifically at the _find_opportunities() method within the ParallelScalper class. This method interacts with the RaydiumMonitor to get active pools and subsequently validates and enters trade positions.
How to Navigate
Open the parallel_scalper.py file.
Locate the ParallelScalper class.
Within that class, find the _find_opportunities() method.
Review and, if necessary, modify the logic that processes the active pools returned by the RaydiumMonitor.
Additional Files to Check
Raydium Monitor: raydium_monitor.py
This file contains the RaydiumMonitor class, which is responsible for tracking the pools and may affect which pools are considered active and valid.
Main Trading Logic:
If there's a separate module that initializes or orchestrates these classes (like in main.py), it's good to check that module as well since it may influence how instances are created and utilized.
By focusing on these files, you'll find where adjustments can be made to ensure that your trading bot correctly utilizes Raydium v4 for trades instead of inadvertently using an alternative like Jupiter.
async def execute_atomic_trade(self, params: Dict) -> Optional[str]:
"""Execute atomic trade with optimized parameters"""
try:
# Rate limiting for Helius
current_time = time.time()
if current_time - self.last_execution < 0.2: # 5 TPS limit
await asyncio.sleep(0.2)
# Prepare optimized parameters
execution_params = {
**params,
"skip_preflight": True,
"compute_limit": self.config['trading']['execution']['compute_limit'],
"priority_fee": await self._get_optimal_priority_fee()
}
# Execute trade
signature = await self.trading.execute_trade(execution_params)
self.last_execution = time.time()
if signature:
logger.info(f"Trade executed: {signature}")
logger.info(f"Priority fee: {execution_params['priority_fee']}")
return signature
return None
except Exception as e:
logger.error(f"Trade execution error: {str(e)}")
return None
async def _get_optimal_priority_fee(self) -> int:
"""Get optimal priority fee from Helius"""
try:
base_fee = self.config['trading']['execution']['priority_fee']
max_fee = self.config['trading']['execution']['max_priority_fee']
# Get recent fee estimate
recent_fee = await self.trading.get_priority_fee()
# Use the higher of base fee or recent estimate
optimal_fee = max(base_fee, recent_fee)
# Cap at maximum
return min(optimal_fee, max_fee)
except Exception as e:
logger.error(f"Fee estimation error: {str(e)}")
return self.config['trading']['execution']['priority_fee'] inside this file?
The code you provided outlines the TradeExecutor class, specifically focusing on executing atomic trades with defined optimization parameters. If you want to ensure that trades are executed using the correct trading router (such as Raydium v4 instead of Jupiter or any other routers), there are a few steps you should consider within this file (trade_executor.py or a similarly named file):
Key Areas to Check or Modify
Ensure Caller Logic Uses the Correct Parameters:
When invoking execute_atomic_trade, ensure that the params dictionary that you're passing includes the correct pool address for Raydium v4. This should be done in the part of your application where you are preparing the params for trades.
Modify Execution Parameters:
If your existing logic does not properly set the trading pool address, you need to trace back to where you're preparing the parameters for params. Make sure it always points to the Raydium v4 pool.
Logging for Debugging:
Consider adding more logging before executing the trade. This could include logging the params that are passed to ensure the trade is directed to the appropriate pool.
Example Modifications
Here's a small code adjustment that adds logging before executing the trade:
python
async def execute_atomic_trade(self, params: Dict) -> Optional[str]:
"""Execute atomic trade with optimized parameters"""
try:
# Rate limiting for Helius
current_time = time.time()
if current_time - self.last_execution < 0.2: # 5 TPS limit
await asyncio.sleep(0.2)
# Prepare optimized parameters
execution_params = {
**params,
"skip_preflight": True,
"compute_limit": self.config['trading']['execution']['compute_limit'],
"priority_fee": await self._get_optimal_priority_fee()
}
# Log the parameters being used for execution
logger.info(f"Executing trade with params: {execution_params}")
# Execute trade
signature = await self.trading.execute_trade(execution_params)
self.last_execution = time.time()
if signature:
logger.info(f"Trade executed: {signature}")
logger.info(f"Priority fee: {execution_params['priority_fee']}")
return signature
return None
except Exception as e:
logger.error(f"Trade execution error: {str(e)}")
return None
Overall Application Structure
From an architectural standpoint, make sure that:
Placement in the Codebase: If your application has separated concerns, ensure this TradeExecutor is used where trades are formulated. For example, in your ParallelScalper or other relevant trading class, when you're calling enter_position() or similar, ensure the pool address you provide is from the Raydium v4 collection.
Raydium Pool Validation: Prior to calling execute_atomic_trade, double-check that the pool addresses being utilized have already been validated to ensure they are from Raydium v4.
Conclusion
After making these adjustments and conducting careful tracing back through your logic to ensure the parameters are directed to the correct trading router, you should achieve the desired trading behavior with Raydium v4 instead of alternative swaps. Keeping track of where parameters originate and where they're passed is key to ensuring everything works correctly.
Not yet included in a published release.
async def start_monitoring(self):
"""Start performance monitoring"""
logger.info("Starting performance monitoring...")
while self._running:
try:
# Update metrics
await self._update_metrics()
# Check safety thresholds
if await self._check_safety_thresholds():
logger.warning("Safety thresholds exceeded!")
# Log current performance
self._log_performance()
# Export metrics
await self._export_metrics()
await asyncio.sleep(60) # Update every minute
except Exception as e:
logger.error(f"Monitoring error: {str(e)}")
await asyncio.sleep(5)
async def _update_metrics(self):
"""Update performance metrics"""
try:
if self.trade_history:
# Calculate win rate
wins = sum(1 for trade in self.trade_history if trade['profit'] > 0)
self.metrics.win_rate = wins / len(self.trade_history) * 100
# Calculate average latency
latencies = [trade['latency'] for trade in self.trade_history]
self.metrics.avg_latency = np.mean(latencies)
# Calculate trades per minute
elapsed_minutes = (time.time() - self.start_time) / 60
self.metrics.trades_per_minute = len(self.trade_history) / elapsed_minutes
except Exception as e:
logger.error(f"Metrics update error: {str(e)}")
async def _check_safety_thresholds(self) -> bool:
"""Check if any safety thresholds are exceeded"""
try:
risk_config = self.config['safety']['risk_management']
# Check drawdown
current_drawdown = self._calculate_drawdown()
if current_drawdown > risk_config['max_drawdown']:
logger.warning(f"Max drawdown exceeded: {current_drawdown:.2%}")
return True
# Check loss limit
daily_loss = self._calculate_daily_loss()
if daily_loss > risk_config['max_daily_loss']:
logger.warning(f"Max daily loss exceeded: {daily_loss:.2%}")
return True
# Check trade frequency
if self.metrics.trades_per_minute > self.config['trading']['limits']['max_trades_per_minute']:
logger.warning("Trade frequency too high")
return True
return False
except Exception as e:
logger.error(f"Safety check error: {str(e)}")
return True
def _log_performance(self):
"""Log current performance metrics"""
metrics = asdict(self.metrics)
logger.info("Performance Metrics:")
for key, value in metrics.items():
if isinstance(value, float):
logger.info(f"{key}: {value:.2f}")
else:
logger.info(f"{key}: {value}")
async def _export_metrics(self):
"""Export metrics to file"""
try:
metrics = asdict(self.metrics)
metrics['timestamp'] = time.time()
with open('performance_metrics.json', 'w') as f:
json.dump(metrics, f, indent=2)
except Exception as e:
logger.error(f"Metrics export error: {str(e)}")
def add_trade_result(self, trade_result: Dict):
"""Add new trade result to history"""
self.trade_history.append({
**trade_result,
'timestamp': time.time()
})
# Update metrics
self.metrics.total_trades += 1
if trade_result['success']:
self.metrics.successful_trades += 1
else:
self.metrics.failed_trades += 1
self.metrics.total_profit += trade_result.get('profit', 0)
def _calculate_drawdown(self) -> float:
"""Calculate current drawdown"""
if not self.trade_history:
return 0.0
profits = [trade['profit'] for trade in self.trade_history]
cumulative = np.cumsum(profits)
peak = np.maximum.accumulate(cumulative)
drawdown = (peak - cumulative) / peak
return np.max(drawdown)
def _calculate_daily_loss(self) -> float:
"""Calculate current day's losses"""
today_start = time.time() - 24*60*60
today_trades = [
trade for trade in self.trade_history
if trade['timestamp'] > today_start
]
if not today_trades:
return 0.0
total_loss = sum(
trade['profit'] for trade in today_trades
if trade['profit'] < 0
)
return abs(total_loss)# C:\solana_rust_bot\src\python\price_impact.py
# Raydium Program IDs
self.RAYDIUM_V4_PROGRAM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.WSOL_MINT = "So11111111111111111111111111111111111111112"
# Primary SOL/WSOL pools
self.SOL_POOLS = [
"58oQChx4yWmvKdwLLZzBi4ChoCc2fqCUWBkwMihLYQo2", # Main SOL-WSOL
"EGZ7tiLeH62TPV1gL8WwbXGzEPa9zmcpVnnkPKKnrE2U" # Secondary SOL-WSOL
]
# State tracking
self.active_pools = {}
self.last_update = {}
self.tps_counter = 0
self.last_tps_reset = time.time()
logger.info("RaydiumMonitor initialized with configuration: %s", json.dumps(config))
def decode_pool_data(self, log_data: str) -> Optional[Dict]:
"""Decode Raydium pool update data"""
try:
# Extract the ray_log data
if "ray_log: " not in log_data:
return None
# Clean and decode base64 log
clean_log = log_data.split("ray_log: ")[1].strip()
raw_data = base64.b64decode(clean_log)
if len(raw_data) < 32:
logger.debug(f"Raw data too short: {len(raw_data)} bytes")
return None
# Extract pool metrics - proper byte offsets for Raydium V4
try:
# Skip discriminator (8 bytes) and status (8 bytes)
base_offset = 16
base_reserve = int.from_bytes(raw_data[base_offset:base_offset+8], 'little')
quote_reserve = int.from_bytes(raw_data[base_offset+8:base_offset+16], 'little')
# Convert to SOL units
SOL_DECIMALS = 10**9
base_sol = base_reserve / SOL_DECIMALS
quote_sol = quote_reserve / SOL_DECIMALS
# Calculate ratio for price impact
ratio = quote_sol / base_sol if base_sol > 0 else 0
logger.debug(f"Decoded pool data:")
logger.debug(f"Base SOL: {base_sol:.4f}")
logger.debug(f"Quote WSOL: {quote_sol:.4f}")
logger.debug(f"Ratio: {ratio:.6f}")
return {
'base_reserve': base_reserve,
'quote_reserve': quote_reserve,
'base_sol': base_sol,
'quote_sol': quote_sol,
'ratio': ratio,
'timestamp': time.time()
}
except Exception as e:
logger.error(f"Pool metric extraction error: {e}")
return None
except Exception as e:
logger.error(f"Pool decode error: {str(e)}")
return None
async def process_transaction(self, tx_data: dict):
"""Process incoming transaction data."""
logger.debug("Processing transaction data...")
try:
# Log raw message for debugging
logger.debug("Received transaction data: %s", json.dumps(tx_data, indent=4)[:200] + "...")
# Extract transaction data
tx_result = tx_data.get("result", {})
if not tx_result:
logger.debug("No result found in transaction data.")
return
# Check for Raydium logs
logs = tx_result.get('meta', {}).get('logMessages', [])
if not any(self.RAYDIUM_V4_PROGRAM in log for log in logs):
logger.debug("No Raydium program logs found in transaction.")
return
signature = tx_result.get('transaction', {}).get('signatures', ['unknown'])[0]
logger.info("Processing Raydium transaction: %s...", signature[:8])
# Log all program interactions
for log in logs:
if "Program " in log:
program_id = log.split("Program ")[1].split()[0]
logger.debug("Program interaction detected: %s", program_id[:8])
# Process pool updates
pool_data_found = False # Flag to track if we find pool data
for log in logs:
if "Program log: " in log and self.RAYDIUM_V4_PROGRAM in log:
pool_data = self.decode_pool_data(log)
if pool_data:
pool_address = next((pool for pool in self.SOL_POOLS if pool in log), None)
if pool_address:
pool_data_found = True # Set flag to true
logger.info("Updating pool: %s", pool_address[:8])
logger.info("Base SOL: %.2f", pool_data['base_sol'])
logger.info("Quote WSOL: %.2f", pool_data['quote_sol'])
logger.info("Ratio: %.6f", pool_data['quote_sol'] / pool_data['base_sol'])
logger.info("USD Value: $%.2f", pool_data['base_sol'] * 110)
# Update pool data
pool_data['token_mint'] = pool_address
pool_data['last_update'] = time.time()
self.active_pools[pool_address] = pool_data
else:
logger.warning("No valid pool address found in log: %s", log)
if not pool_data_found:
logger.warning("No valid pool data found in transaction.")
except Exception as e:
logger.error("Error processing transaction: %s", str(e))
logger.debug("Detailed error: %s", traceback.format_exc())
async def start_monitoring(self):
"""Start monitoring Raydium pools."""
logger.info("Starting Raydium pool monitor...")
ws_url = self.config['rpc']['primary']['endpoint'].replace('https', 'wss')
logger.info("Connecting to websocket: %s", ws_url)
retry_count = 0
ws = None
try:
while not self._shutdown:
try:
ws = await websockets.connect(ws_url)
# Subscribe to program logs
subscribe_msg = {
"jsonrpc": "2.0",
"id": 1,
"method": "logsSubscribe",
"params": [
{"mentions": [self.RAYDIUM_V4_PROGRAM]},
{"commitment": "processed"}
]
}
logger.info("Sending subscription request...")
await ws.send(json.dumps(subscribe_msg))
response = await ws.recv()
if "error" in json.loads(response):
logger.error("Subscription error: %s", response)
raise Exception(f"Subscription error: {response}")
logger.info("Connected to Helius websocket. Monitoring Raydium pools:")
for pool in self.SOL_POOLS:
logger.info("- Listening for updates on pool: %s", pool)
retry_count = 0
while not self._shutdown:
try:
msg = await asyncio.wait_for(ws.recv(), timeout=30)
logger.debug("Raw message received from websocket: %s", msg)
await self.process_transaction(json.loads(msg))
except asyncio.TimeoutError:
logger.debug("Websocket receive timeout occurred.")
if not self._shutdown:
continue
except Exception as e:
logger.error("Message processing error: %s", str(e))
logger.debug("Error details: %s", traceback.format_exc())
if not self._shutdown:
continue
except Exception as e:
if self._shutdown:
logger.info("Shutdown initiated, exiting monitoring loop.")
break
retry_count += 1
wait_time = min(2 ** retry_count, 60)
logger.error("Websocket connection error: %s", str(e))
logger.info("Retrying websocket connection in %d seconds...", wait_time)
await asyncio.sleep(wait_time)
except Exception as e:
logger.error("Monitor encountered an error: %s", str(e))
logger.debug("Detailed error: %s", traceback.format_exc())
finally:
if ws:
try:
await ws.close()
logger.info("Websocket connection closed.")
except Exception as e:
logger.error("Error closing websocket: %s", str(e))
logger.info("Monitor shutdown complete.")
def _extract_pool_address(self, logs: List[str]) -> Optional[str]:
"""Extract pool address from logs."""
logger.debug("Attempting to extract pool address from logs...")
try:
for log in logs:
for pool in self.SOL_POOLS:
if pool in log:
logger.info("Found pool: %s", pool[:8])
return pool
logger.warning("No pool address found in logs.")
return None
except Exception as e:
logger.error("Error extracting pool address: %s", str(e))
logger.debug("Detailed error: %s", traceback.format_exc())
return None
def _update_pool_data(self, pool_address: str, pool_data: dict):
"""Update pool data with logging."""
logger.debug("Updating pool data for %s", pool_address[:8])
try:
pool_data['token_mint'] = pool_address
pool_data['last_update'] = time.time()
base_usd = pool_data['base_sol'] * 110 # Approx SOL price
logger.info("Pool Update:")
logger.info("Pool Address: %s", pool_address[:8])
logger.info("Liquidity: $%.2f", base_usd)
logger.info("Base Reserve: %.2f SOL", pool_data['base_sol'])
logger.info("Quote Reserve: %.2f WSOL", pool_data['quote_sol'])
logger.info("SOL/WSOL Ratio: %.4f", pool_data['quote_sol'] / pool_data['base_sol'])
self.active_pools[pool_address] = pool_data
self.last_update[pool_address] = time.time()
except Exception as e:
logger.error("Error updating pool data: %s", str(e))
logger.debug("Detailed error: %s", traceback.format_exc())
def get_active_pools(self) -> List[Dict]:
"""Get currently active pools."""
current_time = time.time()
active_pools = []
for token_mint, pool_data in self.active_pools.items():
last_update = self.last_update.get(token_mint, 0)
if current_time - last_update <= 300: # 5 minutes
active_pools.append({
'token_mint': token_mint,
**pool_data
})
logger.debug("Active pool added: %s", token_mint)
logger.info("Returning %d active pools.", len(active_pools))
return active_pools
def stop(self):
"""Stop monitoring."""
self._shutdown = Trueimport asyncio