Write a python code to retrieve the most volatile tokens in the last 24hr in binance…
- User
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
Here is an example of how you can retrieve the most volatile tokens in the last 24 hours on Binance against the USDT pair, sort them by volatility, and show the data as a dictionary:
codeimport requests import json # Get the ticker data for all USDT pairs on Binance url = "https://api.binance.com/api/v3/ticker/24hr" params = {"symbol": "USDT"} ticker_data = requests.get(url, params=params).json() # Calculate the volatility for each token volatility = {} for ticker in ticker_data: symbol = ticker["symbol"] price_change = float(ticker["priceChangePercent"]) volatility[symbol] = abs(price_change) # Sort the tokens by volatility and show the top 10 sorted_volatility = sorted(volatility.items(), key=lambda x: x[1], reverse=True) top_volatile_tokens = dict(sorted_volatility[:10]) print(top_volatile_tokens)Note: This will only give you the top 10 tokens with the highest volatility. you can adjust the value of 'sorted_volatility[:10]' to get more or less tokens.
This code uses the Binance API to retrieve 24 hour ticker data for all USDT pairs. It then calculates the volatility for each token by taking the absolute value of the price change percentage. Finally, it sorts the tokens by volatility and prints the top 10 as a dictionary.
- User
TypeError: string indices must be integers
- Assistant
The error message "TypeError: string indices must be integers" suggests that the
tickervariable in the for loop is a string, but you are trying to access it as if it were a dictionary.This error message is likely to be caused by the response from the Binance API being a JSON string, but you are trying to access it as a dictionary.
Here's a corrected version of the code that should work:
codeimport requests import json # Get the ticker data for all USDT pairs on Binance url = "https://api.binance.com/api/v3/ticker/24hr" ticker_data = json.loads(requests.get(url).text) # Calculate the volatility for each token volatility = {} for ticker in ticker_data: if ticker['symbol'].endswith("USDT"): symbol = ticker["symbol"] price_change = float(ticker["priceChangePercent"]) volatility[symbol] = abs(price_change) # Sort the tokens by volatility and show the top 10 sorted_volatility = sorted(volatility.items(), key=lambda x: x[1], reverse=True) top_volatile_tokens = dict(sorted_volatility[:10]) print(top_volatile_tokens)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.