Spaces:
Runtime error
Runtime error
Create binance_api/client.py
Browse files- binance_api/client.py +42 -0
binance_api/client.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from binance.client import Client
|
2 |
+
import pandas as pd
|
3 |
+
from datetime import datetime
|
4 |
+
|
5 |
+
class BinanceClient:
|
6 |
+
def __init__(self, api_key, api_secret):
|
7 |
+
"""Initialize the Binance client with user's API key and secret."""
|
8 |
+
self.client = Client(api_key, api_secret)
|
9 |
+
|
10 |
+
def fetch_historical_prices(self, symbol, interval, days):
|
11 |
+
"""Fetch historical prices for a given symbol and interval.
|
12 |
+
|
13 |
+
Args:
|
14 |
+
symbol (str): The cryptocurrency symbol, e.g., 'BTCUSDT'.
|
15 |
+
interval (str): The candlestick chart intervals.
|
16 |
+
days (int): Number of days back to fetch data for.
|
17 |
+
|
18 |
+
Returns:
|
19 |
+
pd.DataFrame: A DataFrame with columns: date, open, high, low, close, volume.
|
20 |
+
"""
|
21 |
+
# Calculate the timestamp for 'days' days ago
|
22 |
+
end_time = datetime.utcnow()
|
23 |
+
start_str = (end_time - pd.Timedelta(days=days)).strftime('%d %b %Y %H:%M:%S')
|
24 |
+
|
25 |
+
# Fetch historical candlestick data from Binance
|
26 |
+
candles = self.client.get_historical_klines(symbol, interval, start_str)
|
27 |
+
|
28 |
+
# Create a DataFrame from the fetched data
|
29 |
+
df = pd.DataFrame(candles, columns=['date', 'open', 'high', 'low', 'close', 'volume', 'close_time', 'quote_asset_volume', 'number_of_trades', 'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
|
30 |
+
|
31 |
+
# Convert timestamp to datetime and adjust columns
|
32 |
+
df['date'] = pd.to_datetime(df['date'], unit='ms')
|
33 |
+
df = df[['date', 'open', 'high', 'low', 'close', 'volume']].copy()
|
34 |
+
|
35 |
+
# Convert columns to the appropriate data type
|
36 |
+
df['open'] = df['open'].astype(float)
|
37 |
+
df['high'] = df['high'].astype(float)
|
38 |
+
df['low'] = df['low'].astype(float)
|
39 |
+
df['close'] = df['close'].astype(float)
|
40 |
+
df['volume'] = df['volume'].astype(float)
|
41 |
+
|
42 |
+
return df
|