Add Binance REST client with OHLCV, ticker, and volume methods
Implements BinanceRestClient wrapping python-binance with get_top_coins, get_ohlcv, get_all_prices, and get_24h_volume. Includes mocked unit tests for all public methods. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
42
data/binance_rest.py
Normal file
42
data/binance_rest.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import pandas as pd
|
||||
from binance.client import Client
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class BinanceRestClient:
|
||||
def __init__(self, api_key: str, api_secret: str):
|
||||
self.client = Client(api_key, api_secret)
|
||||
|
||||
def get_top_coins(self, limit: int = 50) -> list[str]:
|
||||
tickers = self.client.get_ticker()
|
||||
usdt_pairs = [
|
||||
t for t in tickers
|
||||
if t["symbol"].endswith("USDT") and not t["symbol"].startswith("USDT")
|
||||
]
|
||||
usdt_pairs.sort(key=lambda x: float(x["quoteVolume"]), reverse=True)
|
||||
return [t["symbol"] for t in usdt_pairs[:limit]]
|
||||
|
||||
def get_ohlcv(self, symbol: str, interval: str = "1h", limit: int = 100) -> pd.DataFrame:
|
||||
klines = self.client.get_klines(symbol=symbol, interval=interval, limit=limit)
|
||||
df = pd.DataFrame(klines, columns=[
|
||||
"timestamp", "open", "high", "low", "close", "volume",
|
||||
"close_time", "quote_volume", "trades", "taker_buy_base",
|
||||
"taker_buy_quote", "ignore",
|
||||
])
|
||||
for col in ["open", "high", "low", "close", "volume", "quote_volume"]:
|
||||
df[col] = df[col].astype(float)
|
||||
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
|
||||
return df[["timestamp", "open", "high", "low", "close", "volume", "quote_volume"]]
|
||||
|
||||
def get_all_prices(self) -> dict[str, float]:
|
||||
tickers = self.client.get_all_tickers()
|
||||
return {t["symbol"]: float(t["price"]) for t in tickers}
|
||||
|
||||
def get_24h_volume(self, symbol: str) -> dict:
|
||||
ticker = self.client.get_ticker(symbol=symbol)
|
||||
return {
|
||||
"volume": float(ticker["volume"]),
|
||||
"quote_volume": float(ticker["quoteVolume"]),
|
||||
"price_change_pct": float(ticker["priceChangePercent"]),
|
||||
}
|
||||
Reference in New Issue
Block a user