Write a python code to retrieve the most volatile tokens in the last 24hr in binance against USDT pair, sorting them by the most volatile, and showing the data as a dictionary
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To achieve this, we'll follow these steps in Python:
Fetch 24hr Ticker Data for All USDT Pairs from Binance using the Binance API.
Calculate Volatility for each token (we'll use a simple measure: the percentage change between the highest and lowest price over the last 24 hours as a proxy for volatility).
Sort Tokens by Volatility in descending order (most volatile first).
Output the Data as a Dictionary with the token, its volatility measure, highest, lowest, and last price.
Please note, to run this script, you'll need to have python and requests library installed. If you haven't installed requests yet, you can do so by running pip install requests.
python
import requests
import operator
def fetch_binance_24hr_tickers():
"""
Fetch 24hr ticker data for all USDT pairs from Binance.
Handles potential API errors and ensures data integrity.
"""
url = "https://api.binance.com/api/v3/ticker/24hr"
try:
response = requests.get(url)
response.raise_for_status() # Raise an error for bad status codes
data = response.json()
# Filter USDT pairs
usdt_pairs_data = [pair for pair in data if pair.get('symbol', '').endswith('USDT')]
return usdt_pairs_data
except requests.exceptions.RequestException as e:
print(f"API Request Error: {e}")
return []
def calculate_vatility(pair_data):
"""
Calculate a simple volatility measure: (high - low) / low * 100.
This represents the percentage price swing over 24 hours.
"""
high = float(pair_data.get('highPrice', 0))
low = float(pair_data.get('lowPrice', 0))
# Avoid division by zero
if low == 0:
return 0
volatility = ((high - low) / low) * 100
return volatility
def main():
# Fetch data
all_usdt_pairs = fetch_binance_24hr_tickers()
# Calculate volatility and store in a dictionary
volatility_data = {}
for pair in all_usdt_pairs:
symbol = pair.get('symbol', 'Unknown')
volatility = calculate_vatility(pair)
last_price = pair.get('lastPrice', 'N/A')
high = pair.get('highPrice', 'N/A')
low = pair.get('lowPrice', 'N/A')
volatility_data[symbol] = {
'Volatility (%)': round(volatility, 2),
'Highest (24hr)': high,
'Lowest (24hr)': low,
'Last Price': last_price
}
# Sort by volatility in descending order
sorted_volatility_data = dict(sorted(volatility_data.items(), key=lambda item: item[1]['Volatility (%)'], reverse=True))
# Display the first N most volatile tokens (adjust N as needed)
N = 20 # Show the top 20 most volatile tokens
print("Most Volatile USDT Pairs (Last 24hrs):")
for symbol, data in list(sorted_volatility_data.items())[:N]:
print(f"**{symbol}**")
for metric, value in data.items():
print(f"{metric}: {value}")
print("---")
if __name__ == "__main__":
main()
Important Considerations:
API Limits: Be mindful of Binance API rate limits. For heavy usage or production environments, consider using a paid API plan or caching mechanisms.
Volatility Measure: This script uses a simple volatility measure. For more sophisticated analyses, consider using historical standard deviation, Bollinger Bands, or other financial metrics.
Token Filtering: The script fetches all USDT pairs. If you're interested in a specific subset (e.g., only tokens with a minimum trading volume), you'll need to add additional filtering logic.
Edge Cases: The script now handles API errors and missing data more gracefully, ensuring it doesn't crash unexpectedly.