Here is a Python script that retrieves the price of the Ethereum/US Dollar (ETHUSD) futures contract on Binance using their API:
import requests
def get_ethusd_futures_price(symbol, api_key, api_secret):
"""
Retrieves the current ETHUSD futures price from the Binance API.
Arguments:
symbol (str): The symbol of the futures contract. For example, "ETHUSDT" for Ethereum/US Dollar.
api_key (str): Your Binance API key.
api_secret (str): Your Binance API secret.
Returns:
float: The current ETHUSD futures price.
"""

Set your API credentialsbase_url = f'
Set the API endpoint and parametersendpoint = base_url + '/' + symbol
Set the API key and secret as headersheaders = {
"API-Key": api_key,
"API-Secret": api_secret
}
try:
response = requests.get(endpoint, headers=headers)
response.raise_for_status()
Raise an exception for HTTP errors (4xx or 5xx)data = response.json()
Return the first price value if any; otherwise return Noneprices = data[0]
if prices:
return float(prices['price'])
else:
return None
except requests.RequestException as e:
print(f"Error retrieving ETHUSD futures price: {e}")
return None
Usage exampleapi_key = "YOUR_API_CUT"
api_secret = 'YOUR_API_SECRET'
symbol = 'ETHUSDT'
ethusd_price = get_ethusd_futures_price(symbol, api_key, api_secret)
if ethusd_price:
print(f"Current ETHUSD futures price: {ethusd_price}")
else:
print("Failed to retrieve current ETHUSD futures price.")
Please note that you will need to replace 'YOUR_API_KEY' and 'YOUR_API_SECRET' with your actual Binance API credentials. This script also assumes that you are running it in a local environment where the Binance API can be accessed without authentication.
Additionally, please note that there may be rate limits or other restrictions on using the Binance API to access market data. It is always a good idea to review Binance’s documentation and terms and conditions before using their API.
If you need to make multiple requests per second (e.g. for automated trading strategies), consider using a library like ‘yfinance’ to get historical prices or ‘binance-api-client’, which is specifically designed to interact with the Binance API.
Leave a Reply