secret = 'YOUR_SECRET_KEY'
url = f'
try:
response = requests.get(url, headers={'x-api-key': api_key})
if response.status_code == 200:
data = json.loads(response.text)
return data['price']
otherwise:
print(f"Failed to get price for {symbol}. Status code: {response.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
symbol = 'ETH'
price = get_eth_price(symbol)
if price is not None:
print(f"Last price for {symbol}: {price}")
Important Notes:
- Authentication:
You need to replace
YOUR_API_KEYandYOUR_SECRET_KEYwith your actual Binance API credentials.
- API Key: The
x-api-keyheader is required to authenticate the request. Make sure you understand how to get an access token from Binance for this purpose.
- Symbol Restriction: Please note that some symbols such as Bitcoin (BTC) are restricted for use in certain regions or due to market forces.
Code Explanation:
- The
get_eth_pricefunction takes a symbol as input and creates an API endpoint URL using thesymbol,tokenSymbol, andintervalparameters.
- It sends a GET request to the API with the generated URL.
- If the request is successful, it parses the JSON data from the response and returns the latest price for the specified symbol.
- The function also catches any exceptions that may occur during the request.
Remember: Always check the Binance API documentation for the most up-to-date information on available symbols, pricing intervals, and authentication methods.
