Tracking the latest liquidity pools on Raydium in real-time requires combining several techniques: efficiently retrieving pool data, monitoring for new pools, and formatting time-related information. This comprehensive guide will show you how to accomplish this with Python.
Getting Raydium Pool Data in Real-Time
There are several approaches to retrieve and monitor Raydium pools in real-time:
Method 1: Using WebSockets to Listen for New Pools
WebSockets provide the most efficient way to track new pools as they're created:
python
import asyncio
from solana.rpc.websocket_api import connect
from solana.publickey import PublicKey
RAYDIUM_PROGRAM_ID = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
INSTRUCTION_NAME = "initialize2" # Instruction that creates new liquidity pools
async def listen_for_new_pools():
async with connect("wss://your-solana-rpc-endpoint.com") as websocket:
await websocket.logs_subscribe(
PublicKey(RAYDIUM_PROGRAM_ID),
commitment="confirmed"
)
pools_detected = []
while len(pools_detected) < 10: # Track the latest 10 pools
msg = await websocket.recv()
if "result" in msg and "value" in msg["result"]:
logs = msg["result"]["value"]["logs"]
# Check if logs contain pool initialization
if any(INSTRUCTION_NAME in log for log in logs):
# Process the pool data
pool_info = extract_pool_info(logs)
pools_detected.append(pool_info)
print(f"New pool detected: {pool_info}")
return pools_detected
This method listens directly to the Solana blockchain for new pool creation events on the Raydium program[3][4].
Method 2: Using programAccounts for Faster Retrieval
For a faster way to retrieve existing pool keys:
python
import asyncio
from solana.rpc.api import Client
from solana.publickey import PublicKey
import base64
solana_client = Client("https://your-solana-rpc-endpoint.com")
async def get_raydium_pools():
pools = []
# Define the filters for Raydium pool accounts
filters = [
{"dataSize": 752}, # Size of Raydium pool accounts
]
# Get all program accounts for Raydium AMM program
response = solana_client.get_program_accounts(
PublicKey("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"),
filters=filters
)
# Process the response to extract pool information
for account in response["result"][:10]: # Get the latest 10 pools
account_data = base64.b64decode(account["account"]["data"])
# Decode the account data using appropriate layout
pool_info = decode_pool_data(account_data)
pools.append(pool_info)
return pools
This approach directly queries the Solana blockchain for Raydium pool accounts[1][5].
Method 3: Using Raydium API
You can fetch pools from Raydium's API, though this may not be updated in real-time:
python
import requests
import json
import time
def fetch_raydium_pools():
all_pools = {}
try:
# First try to load from a local cache
with open('all_pools.json', 'r') as file:
all_pools = json.load(file)
except:
# If not available, fetch from Raydium API
response = requests.get('https://api.raydium.io/v2/sdk/liquidity/mainnet.json')
pools_data = response.json()
official = pools_data['official']
unofficial = pools_data['unOfficial']
all_pools = official + unofficial
# Cache the data for faster future access
with open('all_pools.json', 'w') as file:
json.dump(all_pools, file)
# Return the 10 most recent pools
return all_pools[-10:]
This method is simpler but might not provide real-time updates as the API is updated periodically[1].
Adding Current Time and Converting to Human-Readable Format
For converting Unix timestamps to human-readable format:
python
def timestamp_to_readable(timestamp):
# Convert timestamp to datetime object
dt_object = datetime.datetime.fromtimestamp(timestamp)
# Format as readable string
readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
# Alternative format with timezone
alt_format = dt_object.strftime("%I:%M%p %Z on %b %d, %Y")
return readable_time, alt_format
For displaying time durations (e.g., "pool created 5 minutes ago"):
python
def human_time_duration(seconds):
TIME_DURATION_UNITS = (
('week', 60*60*24*7),
('day', 60*60*24),
('hour', 60*60),
('min', 60),
('sec', 1)
)
if seconds == 0:
return 'just now'
parts = []
for unit, div in TIME_DURATION_UNITS:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
parts.append('{} {}{}'.format(amount, unit, "" if amount == 1 else "s"))
return ', '.join(parts)
This function converts a duration in seconds to a human-readable string like "2 hours, 5 mins"[9].
Complete Solution: Track Latest 10 Raydium Pools in Real-Time
Here's a complete solution that combines all the above components:
python
Advanced Implementation: RaydiumPoolInfo Class
For a more structured approach, you can implement a class similar to the one found in the Stochastic-Adventure repository:
python
import asyncio
import json
import time
import datetime
from solana.rpc.api import Client
class RaydiumPoolTracker:
def __init__(self, rpc_endpoint):
self.solana_client = Client(rpc_endpoint)
self.latest_pools = []
async def get_pool_supply(self, lp_address):
"""Get the reserves and LP supply for a specific pool"""
# Implementation would retrieve token balances and supply
# Similar to what's shown in search result #8
pass
async def track_pools_in_real_time(self):
"""Listen for and track new Raydium pools in real-time"""
current_time = int(time.time())
print(f"Starting pool tracking at {timestamp_to_readable(current_time)}")
# Implementation using WebSockets as shown earlier
pass
def display_pool_information(self):
"""Display information about tracked pools with human-readable times"""
current_time = int(time.time())
print(f"\nCurrent time: {timestamp_to_readable(current_time)}")
print("Latest Raydium Pools:")
for i, pool in enumerate(self.latest_pools):
age = current_time - pool["timestamp"]
print(f"{i+1}. {pool['name']} - Created {human_time_duration(age)} ago")
print(f" Liquidity: ${pool['liquidity']:.2f}")
# Additional pool information
This class-based approach provides a more organized structure for tracking and analyzing Raydium pools[8].
By implementing these techniques, you can effectively track the latest 10 Raydium pools in real-time, add current time information, and convert timestamps to human-readable formats.
import asyncio
import json
import time
import datetime
import requests
from solana.rpc.websocket_api import connect
from solana.publickey import PublicKey
# Constants
RAYDIUM_PROGRAM_ID = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"
INSTRUCTION_NAME = "initialize2"
MAX_POOLS = 10
# Time conversion functions
def timestamp_to_readable(timestamp):
dt_object = datetime.datetime.fromtimestamp(timestamp)
return dt_object.strftime("%Y-%m-%d %H:%M:%S")
def human_time_duration(seconds):
TIME_DURATION_UNITS = (
('week', 60*60*24*7),
('day', 60*60*24),
('hour', 60*60),
('min', 60),
('sec', 1)
)
if seconds == 0:
return 'just now'
parts = []
for unit, div in TIME_DURATION_UNITS:
amount, seconds = divmod(int(seconds), div)
if amount > 0:
parts.append('{} {}{}'.format(amount, unit, "" if amount == 1 else "s"))
return ', '.join(parts)
# Pool tracking function
async def track_latest_raydium_pools():
# Storage for the latest pools
latest_pools = []
current_time = int(time.time())
# Connect to Solana WebSocket
async with connect("wss://your-solana-rpc-endpoint.com") as websocket:
# Subscribe to logs for the Raydium program
await websocket.logs_subscribe(
PublicKey(RAYDIUM_PROGRAM_ID),
commitment="confirmed"
)
print(f"Current time: {timestamp_to_readable(current_time)}")
print("Listening for new Raydium pools...")
try:
while True:
msg = await websocket.recv()
# Process message if it contains logs
if "result" in msg and "value" in msg["result"]:
logs = msg["result"]["value"]["logs"]
# Check if the logs indicate a new pool creation
if any(INSTRUCTION_NAME in log for log in logs):
# Extract pool information (implementation depends on log format)
pool_info = {} # Placeholder - extract actual data from logs
# Add time information
detection_time = int(time.time())
pool_info["timestamp"] = detection_time
pool_info["formatted_time"] = timestamp_to_readable(detection_time)
# Add to latest pools and maintain max size
latest_pools.insert(0, pool_info)
if len(latest_pools) > MAX_POOLS:
latest_pools.pop()
# Display pool information
print(f"\nNew pool detected at {pool_info['formatted_time']}:")
print(json.dumps(pool_info, indent=2))
# Display all tracked pools with time since detection
print("\nLatest pools:")
current_time = int(time.time())
for i, pool in enumerate(latest_pools):
age = current_time - pool["timestamp"]
print(f"{i+1}. Detected {human_time_duration(age)} ago")
except KeyboardInterrupt:
print("\nStopping pool tracking...")
# Run the tracking function
if __name__ == "__main__":
current_time = datetime.datetime.now()
print(f"Starting Raydium pool tracker at {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
asyncio.run(track_latest_raydium_pools())