if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class RaydiumSPLTrader:
def init(self, config_path: str):
"""
Initialize the RaydiumSPLTrader with the provided config file.
"""
# Load the configuration file
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
code
# Setup logging and CUDA
self.setup_logging()
self.setup_cuda()
# Initialize the trader
self.trader = QuantumTrader(
keypair_path="C:/solana_rust_bot/id.json",
priority_fee=50000
)
# Constants
self.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.BASE_UNIT = 4294967296 # 64-byte engine constant
self.CHUNK_SIZE = 64
# Trading parameters
self.position_size = 0.05
self.min_volume = 5000.0
self.min_bs_ratio = 2.0
self.min_liquidity = 40000.0
# Stats
self.trades_executed = 0
self.pools_scanned = 0
# Log wallet address
self.logger.info(f"Wallet loaded: {self.trader.get_wallet_address()}")
def setup_logging(self):
"""
Setup logging handlers for console and file.
"""
# Create logger
self.logger = logging.getLogger('RaydiumSPL')
self.logger.setLevel(logging.INFO)
# Create formatters and add handlers
formatter = logging.Formatter('%(asctime)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
file_handler = logging.FileHandler(f'raydium_trades_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def setup_cuda(self):
"""
Setup CUDA if available.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.cuda.empty_cache()
self.logger.info(f"CUDA initialized: {torch.cuda.get_device_name()}")
@torch.amp.autocast('cuda') # Updated decorator
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
"""
Analyze pool data and extract relevant metrics.
Returns None if no suitable metrics found or on error.
"""
try:
metrics = {}
for i in range(0, len(data), self.CHUNK_SIZE):
chunk = data[i:i+self.CHUNK_SIZE]
if len(chunk) != self.CHUNK_SIZE:
continue # Skip if chunk is not of the expected size
# Extract pool metrics
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
# Skip if base or quote reserve is zero
if base_reserve == 0 or quote_reserve == 0:
continue
price = quote_reserve / base_reserve
bs_ratio = base_reserve / quote_reserve
liquidity = min(base_reserve, quote_reserve)
# Check trading conditions
if volume >= self.min_volume and bs_ratio >= self.min_bs_ratio and liquidity >= self.min_liquidity:
metrics = {
'address': token_address,
'price': price,
'volume': volume,
'bs_ratio': bs_ratio,
'liquidity': liquidity
}
self.logger.info(
f"\nPool Metrics:"
f"\nToken: {token_address}"
f"\nPrice: ${price:.6f}"
f"\nVolume: {volume:,.2f}"
f"\nB/S Ratio: {bs_ratio:.2f}" # Fixed formatting
f"\nLiquidity: {liquidity:,.2f}"
)
break
return metrics
except Exception as e:
self.logger.error(f"Analysis error: {str(e)}")
return None
async def execute_trade(self, metrics: Dict):
"""
Execute a trade based on the provided metrics.
"""
try:
self.logger.info(f"\nExecuting trade for {metrics['address']}")
# Execute direct swap
signature = await self.trader.execute_swap(
metrics['address'],
self.position_size,
True,
50000
)
if signature:
self.trades_executed += 1
self.logger.info(f"Trade executed: {signature}")
# Execute exit trade if bs_ratio is high
if metrics['bs_ratio'] > 3.0:
await asyncio.sleep(2)
sell_sig = await self.trader.execute_swap(
metrics['address'],
self.position_size,
False,
50000
)
if sell_sig:
self.logger.info(f"Exit trade executed: {sell_sig}")
except Exception as e:
self.logger.error(f"Trade execution error: {str(e)}")
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("\nStarting Raydium pool monitoring...")
retry_count = 0
while True:
try:
# Connect to the websocket
async with websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
) as ws:
# Subscribe to Raydium AMM
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": "raydium-amm",
"method": "programSubscribe",
"params": [
self.RAYDIUM_AMM,
{"encoding": "base64", "commitment": "confirmed"}
]
}))
response = await ws.recv()
if json.loads(response).get('result'):
self.logger.info("Connected to Raydium feed")
while True:
# Receive messages
msg = await ws.recv()
data = json.loads(msg)
# Process pool data
if "params" in data and "result" in data["params"]:
self.pools_scanned += 1
# Log stats every 100 pools scanned
if self.pools_scanned % 100 == 0:
self.logger.info(
f"Stats: {self.pools_scanned} pools scanned | "
f"{self.trades_executed} trades executed"
)
# Decode and analyze pool data
pool_data = base64.b64decode(data["params"]["result"]["value"]["account"]["data"][0])
metrics = self.analyze_pool_data(pool_data)
# Execute trade if suitable metrics found
if metrics:
await self.execute_trade(metrics)
except websockets.exceptions.ConnectionClosed:
retry_count += 1
wait_time = min(30, retry_count * 3)
self.logger.warning(f"Connection closed, retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
except Exception as e:
self.logger.error(f"Monitor error: {str(e)}")
await asyncio.sleep(1)
def start(self):
"""
Start the RaydiumSPLTrader.
"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.monitor_pools())
except KeyboardInterrupt:
self.logger.info("\nShutting down gracefully...")
finally:
loop.close()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if name == "main":
trader = RaydiumSPLTrader("config.yaml")
trader.start() ADD MAXIMUM LOGGING PLEASE
Assistant
To implement maximum logging in your RaydiumSPLTrader class, you can modify the logging setup to include different levels of logging (e.g., DEBUG, INFO, WARNING, ERROR, CRITICAL). Additionally, you might want to log more detailed information in various parts of your code to aid in debugging and provide insights into your program's operation. Below is an updated version of your code with added maximum logging functionality.
Updated Code with Enhanced Logging
python
User
Enhanced pool analysis with optimized metrics calculation
@torch.amp.autocast('cuda')
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
metrics = {}
self.logger.debug(f"Analyzing pool data of length: {len(data)} bytes.")
code
# Process chunks in parallel using torch
chunks = torch.tensor([data[i:i+self.CHUNK_SIZE] for i in range(0, len(data), self.CHUNK_SIZE)])
for chunk in chunks:
if len(chunk) == self.CHUNK_SIZE:
# Extract metrics with vectorized operations
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
if base_reserve > 0 and quote_reserve > 0:
metrics = self._calculate_pool_metrics(
base_reserve, quote_reserve, volume, token_address
)
if self._validate_trading_conditions(metrics):
return metrics
return None
Enhanced trade execution with retry logic
async def execute_trade(self, metrics: Dict):
max_retries = 3
for attempt in range(max_retries):
try:
signature = await self._execute_swap_with_validation(metrics)
if signature:
await self._handle_successful_trade(metrics, signature)
return True
except Exception as e:
if attempt == max_retries - 1:
self.logger.error(f"Final trade attempt failed: {str(e)}")
return False
await asyncio.sleep(1)
Add robust connection management
async def monitor_pools(self):
while True:
try:
async with self._create_websocket_connection() as ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
add this to the script and also maximum logging please
Assistant
To incorporate the requested enhancements to the analyze_pool_data, execute_trade, and monitor_pools methods while ensuring maximum logging, we should implement optimized metric calculations, retry logic for trade execution, and robust connection management. Below I've added these enhancements along with detailed logging for better traceability.
Updated Code with Enhancements
python
User
(quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\raydium_scalper.py"
2024-12-04 07:20:58,458 - INFO - CUDA initialized: NVIDIA GeForce RTX 4070 Ti
2024-12-04 07:20:58,458 - INFO - Wallet loaded: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
Traceback (most recent call last):
File "C:\solana_rust_bot\raydium_scalper.py", line 254, in
trader.start()
File "C:\solana_rust_bot\raydium_scalper.py", line 244, in start
loop.run_until_complete(self.monitor_pools())
^^^^^^^^^^^^^^^^^^
AttributeError: 'RaydiumSPLTrader' object has no attribute 'monitor_pools'
(quantum_beast) PS C:\solana_rust_bot>
Assistant
The error message you're encountering indicates that the RaydiumSPLTrader class does not have a method called monitor_pools, which is causing an AttributeError when you attempt to call loop.run_until_complete(self.monitor_pools()) in the start method.
This suggests that there might be one of two issues:
The method monitor_pools isn't defined in the class.
There might have been a typo or an oversight in the code.
From the previous code examples provided, the monitor_pools method was indeed defined. However, if the last provided snippet has a typo or if there were any changes in the structure of the program that led to that method not being correctly attributed to the class, it could cause this error.
Steps to Resolve the Issue
Check for the monitor_pools Method: Ensure that the monitor_pools method is properly defined inside the RaydiumSPLTrader class. Here’s a minimal version of the monitor_pools method to ensure you can include it correctly:
python
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
async with self._create_websocket_connection() as ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
Ensure the Method Definition Exists: When you copy the code, make sure the monitor_pools definition is included with the proper indentation. It should be aligned with the other methods of the RaydiumSPLTrader class.
Class Initialization: Double-check that there are no issues with class initialization or scope that might be affecting the visibility of the method. All methods must be inside the class's indentation level.
Reload Your Script: If you've made any changes in an interactive environment or from a script that uses caching or static variable handling, ensure you restart your Python interpreter or clear caches if applicable.
User
please full write the script now
Assistant
Certainly! Below is a complete implementation of the RaydiumSPLTrader class with all the enhancements and improvements we've discussed, including the full definition of the monitor_pools method and other related methods.
Full Script: raydium_scalper.py
python
User
(quantum_beast) PS C:\solana_rust_bot> python "C:\solana_rust_bot\raydium_scalper.py"
2024-12-04 07:22:40,345 - INFO - CUDA initialized: NVIDIA GeForce RTX 4070 Ti
2024-12-04 07:22:40,345 - INFO - Wallet loaded: EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA
2024-12-04 07:22:40,345 - INFO - Starting Raydium pool monitoring...
C:\solana_rust_bot\raydium_scalper.py:244: RuntimeWarning: coroutine 'RaydiumSPLTrader._create_websocket_connection' was never awaited
async with self._create_websocket_connection() as ws:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2024-12-04 07:22:40,345 - ERROR - Connection error: 'coroutine' object does not support the asynchronous context manager protocol
2024-12-04 07:22:40,345 - WARNING - Connection error, retrying in 5 seconds...
2024-12-04 07:22:45,348 - ERROR - Connection error: 'coroutine' object does not support the asynchronous context manager protocol
2024-12-04 07:22:45,349 - WARNING - Connection error, retrying in 5 seconds...
Assistant
The error message you are encountering, specifically RuntimeWarning: coroutine 'RaydiumSPLTrader._create_websocket_connection' was never awaited, indicates that you are trying to use an asynchronous function (_create_websocket_connection) as if it were synchronous, which is not valid.
Issue Explanation
In Python, when you define an asynchronous function with async def, you need to use the await keyword when you call it. This tells Python to pause execution until the asynchronous operation completes. If you try to use an asynchronous function in a context that doesn't support it (like using it with async with directly without await), you'll encounter this error.
Fixing the Asynchronous Context Manager
To resolve this issue, you need to change the _create_websocket_connection method so that it returns the websocket connection awaited properly. Here’s how you can fix it:
Change the way you create your websocket connection.
Directly use await when calling the function, since async functions should always be awaited.
Here’s the corrected version of the monitor_pools function and the _create_websocket_connection method:
python
async def _create_websocket_connection(self):
"""
Create a new websocket connection.
"""
self.logger.debug("Creating websocket connection...")
return await websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
)
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
# Await the websocket connection properly
ws = await self._create_websocket_connection()
async with ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
User
okay show me the fully operational fully working real deal last iteration best known working script
Assistant
Certainly! Below is the fully operational RaydiumSPLTrader script, incorporating all the improvements we've discussed—including robust error handling, websocket connection management, detailed logging, and performance optimizations. This version is designed to be your best-known working iteration.
import asyncio
import logging
import yaml
import torch
import torch.amp
import websockets
import json
import base64
from datetime import datetime
from typing import Dict, Optional
from solana_rust_bot import QuantumTrader
import platform
# Set the event loop policy for Windows
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class RaydiumSPLTrader:
def __init__(self, config_path: str):
"""
Initialize the RaydiumSPLTrader with the provided config file.
"""
# Load the configuration file
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
# Setup logging and CUDA
self.setup_logging()
self.setup_cuda()
# Initialize the trader
self.trader = QuantumTrader(
keypair_path="C:/solana_rust_bot/id.json",
priority_fee=50000
)
# Constants
self.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.BASE_UNIT = 4294967296 # 64-byte engine constant
self.CHUNK_SIZE = 64
# Trading parameters
self.position_size = 0.05
self.min_volume = 5000.0
self.min_bs_ratio = 2.0
self.min_liquidity = 40000.0
# Stats
self.trades_executed = 0
self.pools_scanned = 0
# Log wallet address
self.logger.info(f"Wallet loaded: {self.trader.get_wallet_address()}")
def setup_logging(self):
"""
Setup logging handlers for console and file.
"""
# Create logger
self.logger = logging.getLogger('RaydiumSPL')
self.logger.setLevel(logging.DEBUG) # Set to DEBUG for maximum logging
# Create formatters and add handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
file_handler = logging.FileHandler(f'raydium_trades_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def setup_cuda(self):
"""
Setup CUDA if available.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.cuda.empty_cache()
self.logger.info(f"CUDA initialized: {torch.cuda.get_device_name()}")
else:
self.logger.warning("CUDA not available, using CPU.")
@torch.amp.autocast('cuda')
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
"""
Analyze pool data and extract relevant metrics.
Returns None if no suitable metrics found or on error.
"""
try:
metrics = {}
self.logger.debug(f"Analyzing pool data of length: {len(data)} bytes.")
for i in range(0, len(data), self.CHUNK_SIZE):
chunk = data[i:i+self.CHUNK_SIZE]
if len(chunk) != self.CHUNK_SIZE:
self.logger.warning(f"Skipped chunk of invalid size: {len(chunk)} bytes.")
continue
# Extract pool metrics
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
# Check for valid reserves
if base_reserve == 0 or quote_reserve == 0:
self.logger.debug(f"Base or quote reserve is zero for token: {token_address}, skipping.")
continue
price = quote_reserve / base_reserve
bs_ratio = base_reserve / quote_reserve
liquidity = min(base_reserve, quote_reserve)
# Log the metrics being evaluated
self.logger.debug(f"Evaluating metrics for token {token_address}: Price={price}, Volume={volume}, B/S Ratio={bs_ratio}, Liquidity={liquidity}")
# Check trading conditions
if volume >= self.min_volume and bs_ratio >= self.min_bs_ratio and liquidity >= self.min_liquidity:
metrics = {
'address': token_address,
'price': price,
'volume': volume,
'bs_ratio': bs_ratio,
'liquidity': liquidity
}
self.logger.info(
f"\nPool Metrics:"
f"\nToken: {token_address}"
f"\nPrice: ${price:.6f}"
f"\nVolume: {volume:,.2f}"
f"\nB/S Ratio: {bs_ratio:.2f}"
f"\nLiquidity: {liquidity:,.2f}"
)
break
return metrics
except Exception as e:
self.logger.error(f"Analysis error: {str(e)}")
return None
async def execute_trade(self, metrics: Dict):
"""
Execute a trade based on the provided metrics.
"""
try:
self.logger.info(f"\nExecuting trade for {metrics['address']}")
# Execute direct swap
signature = await self.trader.execute_swap(
metrics['address'],
self.position_size,
True,
50000
)
if signature:
self.trades_executed += 1
self.logger.info(f"Trade executed: {signature}")
# Execute exit trade if bs_ratio is high
if metrics['bs_ratio'] > 3.0:
await asyncio.sleep(2)
sell_sig = await self.trader.execute_swap(
metrics['address'],
self.position_size,
False,
50000
)
if sell_sig:
self.logger.info(f"Exit trade executed: {sell_sig}")
else:
self.logger.warning(f"Exit trade failed for {metrics['address']}")
except Exception as e:
self.logger.error(f"Trade execution error: {str(e)}")
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
retry_count = 0
while True:
try:
# Connect to the websocket
async with websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
) as ws:
# Subscribe to Raydium AMM
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": "raydium-amm",
"method": "programSubscribe",
"params": [
self.RAYDIUM_AMM,
{"encoding": "base64", "commitment": "confirmed"}
]
}))
response = await ws.recv()
if json.loads(response).get('result'):
self.logger.info("Connected to Raydium feed")
while True:
# Receive messages
msg = await ws.recv()
data = json.loads(msg)
# Process pool data
if "params" in data and "result" in data["params"]:
self.pools_scanned += 1
# Log stats every 100 pools scanned
if self.pools_scanned % 100 == 0:
self.logger.info(
f"Stats: {self.pools_scanned} pools scanned | "
f"{self.trades_executed} trades executed"
)
# Decode and analyze pool data
pool_data = base64.b64decode(data["params"]["result"]["value"]["account"]["data"][0])
metrics = self.analyze_pool_data(pool_data)
# Execute trade if suitable metrics found
if metrics:
await self.execute_trade(metrics)
except websockets.exceptions.ConnectionClosed:
retry_count += 1
wait_time = min(30, retry_count * 3)
self.logger.warning(f"Connection closed, retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
except Exception as e:
self.logger.error(f"Monitor error: {str(e)}")
await asyncio.sleep(1)
def start(self):
"""
Start the RaydiumSPLTrader.
"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.monitor_pools())
except KeyboardInterrupt:
self.logger.info("Shutting down gracefully...")
finally:
loop.close()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if __name__ == "__main__":
trader = RaydiumSPLTrader("config.yaml")
trader.start()
Key Changes
Logging Level: Set the log level to DEBUG to capture all messages.
More Detailed Logging:
Added logs to track detailed actions like chunk processing, connection statuses, and any errors that might occur.
Additional logs are included before executing trades and when trading conditions are evaluated.
Metrics Evaluation Logging: Log before evaluating the metrics for better traceability when debugging.
Exit Trade Error Handling: Added a warning log if an exit trade fails.
These changes enhance the level of detail captured in the logs, making it easier to monitor the application's behavior and diagnose issues.
import asyncio
import logging
import yaml
import torch
import torch.amp
import websockets
import json
import base64
from datetime import datetime
from typing import Dict, Optional
from solana_rust_bot import QuantumTrader
import platform
# Set the event loop policy for Windows
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class RaydiumSPLTrader:
def __init__(self, config_path: str):
"""
Initialize the RaydiumSPLTrader with the provided config file.
"""
# Load the configuration file
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
# Setup logging and CUDA
self.setup_logging()
self.setup_cuda()
# Initialize the trader
self.trader = QuantumTrader(
keypair_path="C:/solana_rust_bot/id.json",
priority_fee=50000
)
# Constants
self.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.BASE_UNIT = 4294967296 # 64-byte engine constant
self.CHUNK_SIZE = 64
# Trading parameters
self.position_size = 0.05
self.min_volume = 5000.0
self.min_bs_ratio = 2.0
self.min_liquidity = 40000.0
# Stats
self.trades_executed = 0
self.pools_scanned = 0
# Log wallet address
self.logger.info(f"Wallet loaded: {self.trader.get_wallet_address()}")
def setup_logging(self):
"""
Setup logging handlers for console and file.
"""
# Create logger
self.logger = logging.getLogger('RaydiumSPL')
self.logger.setLevel(logging.DEBUG) # Set to DEBUG for maximum logging
# Create formatters and add handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
file_handler = logging.FileHandler(f'raydium_trades_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def setup_cuda(self):
"""
Setup CUDA if available.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.cuda.empty_cache()
self.logger.info(f"CUDA initialized: {torch.cuda.get_device_name()}")
else:
self.logger.warning("CUDA not available, using CPU.")
@torch.amp.autocast('cuda')
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
metrics = {}
self.logger.debug(f"Analyzing pool data of length: {len(data)} bytes.")
# Process chunks
chunk_count = len(data) // self.CHUNK_SIZE
for i in range(chunk_count):
chunk = data[i * self.CHUNK_SIZE:(i + 1) * self.CHUNK_SIZE]
if len(chunk) == self.CHUNK_SIZE:
# Extract metrics
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
# Log extracted metrics
self.logger.debug(f"Extracted metrics - Token: {token_address}, Base Reserve: {base_reserve}, Quote Reserve: {quote_reserve}, Volume: {volume}")
if base_reserve > 0 and quote_reserve > 0:
metrics = self._calculate_pool_metrics(base_reserve, quote_reserve, volume, token_address)
if self._validate_trading_conditions(metrics):
self.logger.info(f"Valid trading conditions met for token: {token_address}, Metrics: {metrics}")
return metrics
else:
self.logger.warning(f"Skipped metric extraction due to zero reserves for token: {token_address}")
self.logger.debug("No valid trading conditions found in pool data.")
return None
def _calculate_pool_metrics(self, base_reserve: float, quote_reserve: float, volume: float, token_address: str) -> Dict:
price = quote_reserve / base_reserve
bs_ratio = base_reserve / quote_reserve
liquidity = min(base_reserve, quote_reserve)
return {
'address': token_address,
'price': price,
'volume': volume,
'bs_ratio': bs_ratio,
'liquidity': liquidity
}
def _validate_trading_conditions(self, metrics: Dict) -> bool:
return (metrics['volume'] >= self.min_volume and
metrics['bs_ratio'] >= self.min_bs_ratio and
metrics['liquidity'] >= self.min_liquidity)
async def execute_trade(self, metrics: Dict):
"""
Execute a trade based on the provided metrics with retry logic.
"""
max_retries = 3
for attempt in range(max_retries):
try:
self.logger.info(f"Attempting to execute trade for {metrics['address']} (Attempt {attempt + 1})")
signature = await self._execute_swap_with_validation(metrics)
if signature:
await self._handle_successful_trade(metrics, signature)
return True
except Exception as e:
self.logger.error(f"Trade execution error: {str(e)}")
if attempt == max_retries - 1:
self.logger.error(f"Final trade attempt failed for {metrics['address']}: {str(e)}")
return False
await asyncio.sleep(1)
async def _execute_swap_with_validation(self, metrics: Dict):
self.logger.debug(f"Executing swap for {metrics['address']} with position size {self.position_size}")
signature = await self.trader.execute_swap(
metrics['address'],
self.position_size,
True,
50000
)
if signature:
self.logger.debug(f"Swap executed with signature: {signature}")
return signature
async def _handle_successful_trade(self, metrics: Dict, signature: str):
self.trades_executed += 1
self.logger.info(f"Trade executed successfully for {metrics['address']} with signature: {signature}")
# Exit trade logic if necessary
if metrics['bs_ratio'] > 3.0:
self.logger.info(f"Handling exit trade for {metrics['address']} due to high B/S ratio.")
await asyncio.sleep(2)
sell_sig = await self.trader.execute_swap(
metrics['address'],
self.position_size,
False,
50000
)
if sell_sig:
self.logger.info(f"Exit trade executed: {sell_sig}")
else:
self.logger.warning(f"Exit trade failed for {metrics['address']}.")
async def _create_websocket_connection(self):
"""
Create a new websocket connection.
"""
self.logger.debug("Creating websocket connection...")
return await websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
)
async def _handle_websocket_connection(self, ws):
"""
Handle the websocket connection and process incoming messages.
"""
self.logger.info("Subscribing to Raydium AMM...")
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": "raydium-amm",
"method": "programSubscribe",
"params": [
self.RAYDIUM_AMM,
{"encoding": "base64", "commitment": "confirmed"}
]
}))
response = await ws.recv()
if json.loads(response).get('result'):
self.logger.info("Connected to Raydium feed")
while True:
msg = await ws.recv()
data = json.loads(msg)
if "params" in data and "result" in data["params"]:
self.pools_scanned += 1
if self.pools_scanned % 100 == 0:
self.logger.info(f"Stats: {self.pools_scanned} pools scanned | {self.trades_executed} trades executed")
pool_data = base64.b64decode(data["params"]["result"]["value"]["account"]["data"][0])
metrics = self.analyze_pool_data(pool_data)
if metrics:
await self.execute_trade(metrics)
async def _handle_reconnection(self):
"""
Handles reconnection logic in case of connection loss.
"""
wait_time = 5 # Initial wait time
self.logger.warning(f"Connection error, retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
def start(self):
"""
Start the RaydiumSPLTrader.
"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.monitor_pools())
except KeyboardInterrupt:
self.logger.info("Shutting down gracefully...")
finally:
loop.close()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if __name__ == "__main__":
trader = RaydiumSPLTrader("config.yaml")
trader.start()
Summary of Enhancements
Pool Analysis:
Optimized the pool metric calculations with a _calculate_pool_metrics method that is called only when conditions are met.
Introduced a _validate_trading_conditions method to encapsulate the logic for validating metrics, enhancing readability and maintainability.
Trade Execution:
Implemented retry logic in the execute_trade method, allowing multiple attempts to execute trades before giving up.
Introduced _execute_swap_with_validation for encapsulating the swap execution, making it easier to handle errors and log them effectively.
Included _handle_successful_trade to streamline actions taken after a successful trade, including exit trade opportunities.
Robust Connection Management:
Added _create_websocket_connection for better management of the websocket connection setup.
Encapsulated websocket handling in _handle_websocket_connection, improving the structure and readability of the code.
Maximum Logging:
Enhanced logging throughout the methods to provide detailed insights into the process execution, data processing, and trades attempted or executed.
These enhancements should improve the performance and maintainability of your RaydiumSPLTrader, making it more robust and easier to debug.
Confirm the File: Ensure that the script you are running (raydium_scalper.py) is indeed the latest version with all the changes you've made. Sometimes, scripts may not save properly, leading to older versions being executed.
Here's a Complete Snippet with the monitor_pools:
Just to provide clarity, here’s how your RaydiumSPLTrader class should look with the monitor_pools included:
python
class RaydiumSPLTrader:
# ... [Other methods and init logic as before]
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
async with self._create_websocket_connection() as ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
# ... [Other methods as before]
Running the Script Again
After you’ve ensured the monitor_pools method is correctly present in your class, save your changes and run the script again. This should resolve the AttributeError you encountered. If the error persists, please provide a snippet of the relevant code, and we can troubleshoot further.
import asyncio
import logging
import yaml
import torch
import torch.amp
import websockets
import json
import base64
from datetime import datetime
from typing import Dict, Optional
from solana_rust_bot import QuantumTrader
import platform
# Set the event loop policy for Windows
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class RaydiumSPLTrader:
def __init__(self, config_path: str):
"""
Initialize the RaydiumSPLTrader with the provided config file.
"""
# Load the configuration file
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
# Setup logging and CUDA
self.setup_logging()
self.setup_cuda()
# Initialize the trader
self.trader = QuantumTrader(
keypair_path="C:/solana_rust_bot/id.json",
priority_fee=50000
)
# Constants
self.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.BASE_UNIT = 4294967296 # 64-byte engine constant
self.CHUNK_SIZE = 64
# Trading parameters
self.position_size = 0.05
self.min_volume = 5000.0
self.min_bs_ratio = 2.0
self.min_liquidity = 40000.0
# Stats
self.trades_executed = 0
self.pools_scanned = 0
# Log wallet address
self.logger.info(f"Wallet loaded: {self.trader.get_wallet_address()}")
def setup_logging(self):
"""
Setup logging handlers for console and file.
"""
# Create logger
self.logger = logging.getLogger('RaydiumSPL')
self.logger.setLevel(logging.DEBUG) # Set to DEBUG for maximum logging
# Create formatters and add handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
file_handler = logging.FileHandler(f'raydium_trades_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def setup_cuda(self):
"""
Setup CUDA if available.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.cuda.empty_cache()
self.logger.info(f"CUDA initialized: {torch.cuda.get_device_name()}")
else:
self.logger.warning("CUDA not available, using CPU.")
@torch.amp.autocast('cuda')
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
metrics = {}
self.logger.debug(f"Analyzing pool data of length: {len(data)} bytes.")
# Process chunks
chunk_count = len(data) // self.CHUNK_SIZE
for i in range(chunk_count):
chunk = data[i * self.CHUNK_SIZE:(i + 1) * self.CHUNK_SIZE]
if len(chunk) == self.CHUNK_SIZE:
# Extract metrics
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
# Log extracted metrics
self.logger.debug(f"Extracted metrics - Token: {token_address}, Base Reserve: {base_reserve}, Quote Reserve: {quote_reserve}, Volume: {volume}")
if base_reserve > 0 and quote_reserve > 0:
metrics = self._calculate_pool_metrics(base_reserve, quote_reserve, volume, token_address)
if self._validate_trading_conditions(metrics):
self.logger.info(f"Valid trading conditions met for token: {token_address}, Metrics: {metrics}")
return metrics
else:
self.logger.warning(f"Skipped metric extraction due to zero reserves for token: {token_address}")
self.logger.debug("No valid trading conditions found in pool data.")
return None
def _calculate_pool_metrics(self, base_reserve: float, quote_reserve: float, volume: float, token_address: str) -> Dict:
price = quote_reserve / base_reserve
bs_ratio = base_reserve / quote_reserve
liquidity = min(base_reserve, quote_reserve)
return {
'address': token_address,
'price': price,
'volume': volume,
'bs_ratio': bs_ratio,
'liquidity': liquidity
}
def _validate_trading_conditions(self, metrics: Dict) -> bool:
return (metrics['volume'] >= self.min_volume and
metrics['bs_ratio'] >= self.min_bs_ratio and
metrics['liquidity'] >= self.min_liquidity)
async def execute_trade(self, metrics: Dict):
"""
Execute a trade based on the provided metrics with retry logic.
"""
max_retries = 3
for attempt in range(max_retries):
try:
self.logger.info(f"Attempting to execute trade for {metrics['address']} (Attempt {attempt + 1})")
signature = await self._execute_swap_with_validation(metrics)
if signature:
await self._handle_successful_trade(metrics, signature)
return True
except Exception as e:
self.logger.error(f"Trade execution error: {str(e)}")
if attempt == max_retries - 1:
self.logger.error(f"Final trade attempt failed for {metrics['address']}: {str(e)}")
return False
await asyncio.sleep(1)
async def _execute_swap_with_validation(self, metrics: Dict):
self.logger.debug(f"Executing swap for {metrics['address']} with position size {self.position_size}")
signature = await self.trader.execute_swap(
metrics['address'],
self.position_size,
True,
50000
)
if signature:
self.logger.debug(f"Swap executed with signature: {signature}")
return signature
async def _handle_successful_trade(self, metrics: Dict, signature: str):
self.trades_executed += 1
self.logger.info(f"Trade executed successfully for {metrics['address']} with signature: {signature}")
# Exit trade logic if necessary
if metrics['bs_ratio'] > 3.0:
self.logger.info(f"Handling exit trade for {metrics['address']} due to high B/S ratio.")
await asyncio.sleep(2)
sell_sig = await self.trader.execute_swap(
metrics['address'],
self.position_size,
False,
50000
)
if sell_sig:
self.logger.info(f"Exit trade executed: {sell_sig}")
else:
self.logger.warning(f"Exit trade failed for {metrics['address']}.")
async def _create_websocket_connection(self):
"""
Create a new websocket connection.
"""
self.logger.debug("Creating websocket connection...")
return await websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
)
async def _handle_websocket_connection(self, ws):
"""
Handle the websocket connection and process incoming messages.
"""
self.logger.info("Subscribing to Raydium AMM...")
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": "raydium-amm",
"method": "programSubscribe",
"params": [
self.RAYDIUM_AMM,
{"encoding": "base64", "commitment": "confirmed"}
]
}))
response = await ws.recv()
if json.loads(response).get('result'):
self.logger.info("Connected to Raydium feed")
while True:
msg = await ws.recv()
data = json.loads(msg)
if "params" in data and "result" in data["params"]:
self.pools_scanned += 1
if self.pools_scanned % 100 == 0:
self.logger.info(f"Stats: {self.pools_scanned} pools scanned | {self.trades_executed} trades executed")
pool_data = base64.b64decode(data["params"]["result"]["value"]["account"]["data"][0])
metrics = self.analyze_pool_data(pool_data)
if metrics:
await self.execute_trade(metrics)
async def _handle_reconnection(self):
"""
Handles reconnection logic in case of connection loss.
"""
wait_time = 5 # Initial wait time
self.logger.warning(f"Connection error, retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
async with self._create_websocket_connection() as ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
def start(self):
"""
Start the RaydiumSPLTrader.
"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.monitor_pools())
except KeyboardInterrupt:
self.logger.info("Shutting down gracefully...")
finally:
loop.close()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if __name__ == "__main__":
trader = RaydiumSPLTrader("config.yaml")
trader.start()
Key Components of the Script
Configuration File: Assumes you have a config.yaml file that contains the necessary websocket endpoints and API keys.
Logging: Detailed logging is set up for both console and file outputs, capturing all relevant actions and errors.
CUDA Support: The script checks for CUDA availability and initializes it if possible.
Trade Execution: Includes retry logic for executing trades, with detailed success and error logging.
Important Notes
Ensure Dependencies: Make sure you have the necessary libraries installed, such as torch, websockets, and any other required packages you're using.
Update Configuration: Fill in your config.yaml with the required details to connect to the correct websocket and use the appropriate API keys.
Environment Set-Up: Ensure that your Solana wallet keypair is available in the specified path when initializing QuantumTrader.
This full script should be ready for you to run. Just ensure your environment is set up, and you have the required permissions and configurations. If you encounter any issues while running it, please let me know!
Full Corrected Script
Here's the relevant section of your script with the corrected monitor_pools and _create_websocket_connection methods integrated:
python
# [...] Previous code remains unchanged
async def _create_websocket_connection(self):
"""
Create a new websocket connection.
"""
self.logger.debug("Creating websocket connection...")
return await websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
)
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
# Await the websocket connection properly
ws = await self._create_websocket_connection()
async with ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
# [...] Remaining code
Summary of Changes
Ensure that await self._create_websocket_connection() is used properly to create a websocket connection.
Use an async with block only after the connection has been established, which is now done by assigning ws to the awaited connection.
Next Steps
After making these changes to your script, save it and run it again. This should resolve the error about the coroutine not being awaited, allowing your websocket connection to be created and used properly for monitoring the Raydium pools. If you encounter any further issues, please share the details so I can assist you further.
import asyncio
import logging
import yaml
import torch
import torch.amp
import websockets
import json
import base64
from datetime import datetime
from typing import Dict, Optional
from solana_rust_bot import QuantumTrader
import platform
# Set the event loop policy for Windows
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
class RaydiumSPLTrader:
def __init__(self, config_path: str):
"""
Initialize the RaydiumSPLTrader with the provided config file.
"""
# Load the configuration file
with open(config_path, 'r') as f:
self.config = yaml.safe_load(f)
# Setup logging and CUDA
self.setup_logging()
self.setup_cuda()
# Initialize the trader
self.trader = QuantumTrader(
keypair_path="C:/solana_rust_bot/id.json",
priority_fee=50000
)
# Constants
self.RAYDIUM_AMM = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
self.BASE_UNIT = 4294967296 # 64-byte engine constant
self.CHUNK_SIZE = 64
# Trading parameters
self.position_size = 0.05
self.min_volume = 5000.0
self.min_bs_ratio = 2.0
self.min_liquidity = 40000.0
# Stats
self.trades_executed = 0
self.pools_scanned = 0
# Log wallet address
self.logger.info(f"Wallet loaded: {self.trader.get_wallet_address()}")
def setup_logging(self):
"""
Setup logging handlers for console and file.
"""
# Create logger
self.logger = logging.getLogger('RaydiumSPL')
self.logger.setLevel(logging.DEBUG) # Set to DEBUG for maximum logging
# Create formatters and add handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
self.logger.addHandler(console_handler)
file_handler = logging.FileHandler(f'raydium_trades_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
file_handler.setFormatter(formatter)
self.logger.addHandler(file_handler)
def setup_cuda(self):
"""
Setup CUDA if available.
"""
if torch.cuda.is_available():
self.device = torch.device("cuda:0")
torch.cuda.set_device(self.device)
torch.cuda.empty_cache()
self.logger.info(f"CUDA initialized: {torch.cuda.get_device_name()}")
else:
self.logger.warning("CUDA not available, using CPU.")
@torch.amp.autocast('cuda')
def analyze_pool_data(self, data: bytes) -> Optional[Dict]:
metrics = {}
self.logger.debug(f"Analyzing pool data of length: {len(data)} bytes.")
# Process chunks
chunk_count = len(data) // self.CHUNK_SIZE
for i in range(chunk_count):
chunk = data[i * self.CHUNK_SIZE:(i + 1) * self.CHUNK_SIZE]
if len(chunk) == self.CHUNK_SIZE:
# Extract metrics
base_reserve = int.from_bytes(chunk[0:8], 'little') / self.BASE_UNIT
quote_reserve = int.from_bytes(chunk[8:16], 'little') / self.BASE_UNIT
volume = int.from_bytes(chunk[16:24], 'little') / self.BASE_UNIT
token_address = chunk[24:56].hex()
# Log extracted metrics
self.logger.debug(f"Extracted metrics - Token: {token_address}, Base Reserve: {base_reserve}, Quote Reserve: {quote_reserve}, Volume: {volume}")
if base_reserve > 0 and quote_reserve > 0:
metrics = self._calculate_pool_metrics(base_reserve, quote_reserve, volume, token_address)
if self._validate_trading_conditions(metrics):
self.logger.info(f"Valid trading conditions met for token: {token_address}, Metrics: {metrics}")
return metrics
else:
self.logger.warning(f"Skipped metric extraction due to zero reserves for token: {token_address}")
self.logger.debug("No valid trading conditions found in pool data.")
return None
def _calculate_pool_metrics(self, base_reserve: float, quote_reserve: float, volume: float, token_address: str) -> Dict:
price = quote_reserve / base_reserve
bs_ratio = base_reserve / quote_reserve
liquidity = min(base_reserve, quote_reserve)
return {
'address': token_address,
'price': price,
'volume': volume,
'bs_ratio': bs_ratio,
'liquidity': liquidity
}
def _validate_trading_conditions(self, metrics: Dict) -> bool:
return (metrics['volume'] >= self.min_volume and
metrics['bs_ratio'] >= self.min_bs_ratio and
metrics['liquidity'] >= self.min_liquidity)
async def execute_trade(self, metrics: Dict):
"""
Execute a trade based on the provided metrics with retry logic.
"""
max_retries = 3
for attempt in range(max_retries):
try:
self.logger.info(f"Attempting to execute trade for {metrics['address']} (Attempt {attempt + 1})")
signature = await self._execute_swap_with_validation(metrics)
if signature:
await self._handle_successful_trade(metrics, signature)
return True
except Exception as e:
self.logger.error(f"Trade execution error: {str(e)}")
if attempt == max_retries - 1:
self.logger.error(f"Final trade attempt failed for {metrics['address']}: {str(e)}")
return False
await asyncio.sleep(1)
async def _execute_swap_with_validation(self, metrics: Dict):
self.logger.debug(f"Executing swap for {metrics['address']} with position size {self.position_size}")
signature = await self.trader.execute_swap(
metrics['address'],
self.position_size,
True,
50000
)
if signature:
self.logger.debug(f"Swap executed with signature: {signature}")
return signature
async def _handle_successful_trade(self, metrics: Dict, signature: str):
self.trades_executed += 1
self.logger.info(f"Trade executed successfully for {metrics['address']} with signature: {signature}")
# Exit trade logic if necessary
if metrics['bs_ratio'] > 3.0:
self.logger.info(f"Handling exit trade for {metrics['address']} due to high B/S ratio.")
await asyncio.sleep(2)
sell_sig = await self.trader.execute_swap(
metrics['address'],
self.position_size,
False,
50000
)
if sell_sig:
self.logger.info(f"Exit trade executed: {sell_sig}")
else:
self.logger.warning(f"Exit trade failed for {metrics['address']}.")
async def _create_websocket_connection(self):
"""
Create a new websocket connection.
"""
self.logger.debug("Creating websocket connection...")
return await websockets.connect(
self.config['helius']['ws_endpoint'],
extra_headers={'Authorization': f"Bearer {self.config['helius']['api_key']}"},
ping_interval=30,
ping_timeout=10,
close_timeout=5
)
async def _handle_websocket_connection(self, ws):
"""
Handle the websocket connection and process incoming messages.
"""
self.logger.info("Subscribing to Raydium AMM...")
await ws.send(json.dumps({
"jsonrpc": "2.0",
"id": "raydium-amm",
"method": "programSubscribe",
"params": [
self.RAYDIUM_AMM,
{"encoding": "base64", "commitment": "confirmed"}
]
}))
response = await ws.recv()
if json.loads(response).get('result'):
self.logger.info("Connected to Raydium feed")
while True:
msg = await ws.recv()
data = json.loads(msg)
if "params" in data and "result" in data["params"]:
self.pools_scanned += 1
if self.pools_scanned % 100 == 0:
self.logger.info(f"Stats: {self.pools_scanned} pools scanned | {self.trades_executed} trades executed")
pool_data = base64.b64decode(data["params"]["result"]["value"]["account"]["data"][0])
metrics = self.analyze_pool_data(pool_data)
if metrics:
await self.execute_trade(metrics)
async def _handle_reconnection(self):
"""
Handles reconnection logic in case of connection loss.
"""
wait_time = 5 # Initial wait time
self.logger.warning(f"Connection error, retrying in {wait_time} seconds...")
await asyncio.sleep(wait_time)
async def monitor_pools(self):
"""
Monitor Raydium pools and execute trades based on conditions.
"""
self.logger.info("Starting Raydium pool monitoring...")
while True:
try:
# Await the websocket connection properly
ws = await self._create_websocket_connection()
async with ws:
await self._handle_websocket_connection(ws)
except Exception as e:
self.logger.error(f"Connection error: {str(e)}")
await self._handle_reconnection()
def start(self):
"""
Start the RaydiumSPLTrader.
"""
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.monitor_pools())
except KeyboardInterrupt:
self.logger.info("Shutting down gracefully...")
finally:
loop.close()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if __name__ == "__main__":
trader = RaydiumSPLTrader("config.yaml")
trader.start()
Key Features and Improvements
Asynchronous WebSocket Management: Uses async/await to manage WebSocket connections and message handling properly.
Trade Execution with Retry Logic: Implements retries for trade execution with logging for successful and failed attempts.
Detailed Logging: Logs provide insights into the steps being taken, making it easier to debug and understand the flow of the program.
Configurable Parameters: The trader's behavior can be adjusted via the config.yaml file, ensuring flexibility for different trading strategies.
CUDA Support: If available, CUDA is initialized for potential performance advantages.
Additional Considerations
Configuration File (config.yaml): Ensure that this YAML file exists and contains the correct websocket endpoint and API key.
Dependencies: Make sure you have the necessary libraries installed in your environment. You may need to install packages like torch, websockets, pyyaml, and any others your script depends on.
Environment Setup: Ensure your Solana wallet's keypair file is accessible, and the path is correct in the script.
This script should work correctly and provide you with a robust framework for interacting with the Raydium pools. If you encounter any issues, feel free to ask for further assistance!