Your cart is currently empty!
February 5, 2025
Ethereum: Accurate Binance API Prices from Historical Data
As a Python developer, you’re probably familiar with the importance of having accurate and up-to-date historical price data for Ethereum. In this article, we’ll explore how to fetch accurate Binance API prices in Python at specific points in time.
Prerequisites
- A Binance API key
- A library that can handle asynchronous data fetching (e.g.
requests
,aiohttp
)
- A Python environment with the required libraries installed
Method 1: Using requests
and a callback function
We’ll use the requests
library to make an HTTP request to the Binance API. We’ll create a callback function that will be triggered whenever a new data point is received from the API.
import requests
from datetime import datetime
def get_api_price(start_date_str, end_date_str):
Set your Binance API key and API endpoint URL hereapi_key = "YOUR_API_KEY"
api_url = f"
whileTrue:
try:
response = requests.get(api_url, headers={"x-api-key": api_key})
data = response.json()
Find the price of ETH on the specified datefor item in data["result"]:
if "timestamp" in item and int(item["timestamp"]) >= start_date_str:
return float(item["price"])
except requests.exceptions.RequestException as e:
print(f"Error: {e}")
Method 2: Using aiohttp
and a Loop
If you prefer a more asynchronous approach, we can use the aiohttp
library to fetch data from the API.
import aiohttp
async def get_api_price(start_date_str, end_date_str):
async with aiohttp.ClientSession() as session:
api_url = f"
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
while start_date <= end_date:
try:
response = await session.get(api_url)
data = await response.json()
Find the price of ETH on the specified datefor item in data["result"]:
if "timestamp" in item and int(item["timestamp"]) >= start_date:
return float(item["price"])
except aiohttp.ClientResponseError as e:
print(f"Error: {e}")
Example usage:start_date_str = "2022-01-01"
end_date_str = "2022-12-31"
get_api_price(start_date_str, end_date_str)
Tips and Variations
- Make sure to replace
YOUR_API_KEY
with your actual Binance API key.
- You can adjust the
limit
parameter in both examples to fetch more or fewer data points.
- Consider adding error handling for cases where the API request fails or returns an invalid response.
- If you need to perform additional processing on the received prices, feel free to modify the callback functions accordingly.