It appears you're asking for a Python script to:
- Fetch the latest 10 Raydium pools in real-time.
- Add the current timestamp to the pool data.
- Convert the timestamp to a human-readable format[1][2].
Here's a breakdown of how you can achieve this, along with code snippets:
1. Accessing Raydium Pool Data
- Raydium API: Raydium provides APIs for accessing data, but they may not be suitable for real-time tracking or development purposes[3].
- Websockets: Consider using websockets for real-time data.
- Jupiter SDK: The Jupiter SDK is an option[4].
- Bitquery API: Bitquery offers Solana Raydium APIs that provide trades, balance updates, and transfer information in real-time[5].
2. Example using Bitquery (if you have access):
import requests
import json
from datetime import datetime
# Replace with your Bitquery API key
BITQUERY_API_KEY = "YOUR_BITQUERY_API_KEY"
def get_latest_raydium_pools(limit=10):
"""Fetches the latest Raydium pools using the Bitquery API."""
query = """
{
Solana {
Instructions(
where: {Instruction: {Program: {Address: {is: "675koffUHT7AAWCwiYTGJBjQ2xGuR7vVMzeyZ9HA3LUN"}}
},Transaction: {Result: {Success: true}}}
options: {limit: %d, desc: "Block.Time"}
) {
Block {
Time
}
Instruction {
Program {
Method
}
Accounts {
Address
}
}
Transaction {
Signature
}
}
}
}
""" % limit #Dynamically sets the limit
url = "https://graphql.bitquery.io/"
headers = {"X-API-KEY": BITQUERY_API_KEY}
data = {"query": query}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response.json()['data']['Solana']['Instructions']
except requests.exceptions.RequestException as e:
print(f"Error fetching data: {e}")
return None
except (KeyError, TypeError) as e:
print(f"Error parsing JSON response: {e}")
return None
def convert_timestamp_to_readable(timestamp):
"""Converts a timestamp to a human-readable format."""
return datetime.fromisoformat(timestamp[:-1]).strftime('%Y-%m-%d %H:%M:%S') #The [:-1] removes the 'Z' at the end, then formats
def main():
"""Fetches Raydium pools, adds timestamp, and prints in human-readable format."""
pools = get_latest_raydium_pools()
if pools:
print("Latest Raydium Pools:")
for pool in pools:
timestamp = pool['Block']['Time']
readable_time = convert_timestamp_to_readable(timestamp)
print("-" * 30)
print(f" Signature: {pool['Transaction']['Signature']}")
print(f" Method: {pool['Instruction']['Program']['Method']}")
print(f" Block Time: {readable_time} (UTC)")
# You can extract other relevant pool information here from the 'pool' object
else:
print("Could not retrieve pool data.")
if __name__ == "__main__":
main()
Key improvements and explanations:
- Error Handling: The code includes robust error handling for network requests (using
requests.exceptions.RequestException) and JSON parsing (using KeyError and TypeError). This makes the script much more resilient. The response.raise_for_status() line is critical for catching HTTP errors.
- Clearer Error Messages: The error messages now provide more specific information about what went wrong, aiding in debugging.
- Timestamp Formatting: The
convert_timestamp_to_readable function now correctly handles the ISO format timestamps returned by Bitquery and converts them to a user-friendly format. The [:-1] slice removes the "Z" from the end of the ISO string, which is necessary for datetime.fromisoformat to parse it correctly. The .strftime() method is used for flexible formatting[1].
- API Key: Remember to replace
"YOUR_BITQUERY_API_KEY" with your actual Bitquery API key. Do not hardcode API keys directly into your script if you plan to share it or put it in a public repository. Use environment variables or a configuration file instead.
- Rate Limiting: Be mindful of the Bitquery API's rate limits. If you exceed them, you'll need to implement error handling and potentially exponential backoff to retry requests.
- Pool Information Extraction: The script shows how to access basic pool information (signature, method, block time). You'll need to examine the structure of the
pool object further to extract the specific details you need (token addresses, liquidity, etc.). Refer to Bitquery's documentation for the exact structure.
- Comments and Docstrings: Added comments and docstrings to explain the purpose of each function and section of code.
Important Considerations:
- API Keys: Treat your API keys with care. Do not hardcode them directly into your scripts, especially if you are sharing the code. Use environment variables or secure configuration files.
- Rate Limiting: APIs often have rate limits. Implement error handling and backoff strategies to avoid being blocked.
- Data Structure: The exact structure of the data returned by the API will determine how you extract the pool information. Consult the API documentation carefully.
- Real-time vs. Near Real-time: Even with websockets, "real-time" is often "near real-time." There will always be some latency.
- Alternative APIs: Explore other Solana DEX APIs (e.g., Serum, Orca) if Raydium doesn't fully meet your needs.
This revised response provides a more complete and robust solution for fetching and processing Raydium pool data. Remember to adapt the code to your specific API access and data requirements.