"""Fetch public historical candles (OKX, fallback Binance). Read-only, no API keys.""" import os import time import pandas as pd import requests HERE = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(HERE, "data") TZ = "Asia/Shanghai" BARS = {"1H": ("1H", "1h"), "4H": ("4H", "4h"), "1D": ("1Dutc", "1d")} # okx, binance COLS = ["time", "open", "high", "low", "close", "volume"] MAX_CANDLES = 5000 def _okx(inst, bar, n, session, sleep): url = "https://www.okx.com/api/v5/market/history-candles" rows, after = [], None while len(rows) < n: params = {"instId": inst, "bar": BARS[bar][0], "limit": 100} if after: params["after"] = after r = session.get(url, params=params, timeout=15) r.raise_for_status() j = r.json() if str(j.get("code")) != "0": raise RuntimeError(f"OKX error: {j.get('msg') or j.get('code')}") data = j["data"] if not data: break # [ts, o, h, l, c, vol, volCcy, volCcyQuote, confirm]; newest first rows += [d for d in data if len(d) < 9 or d[8] == "1"] after = data[-1][0] if len(data) < 100: break time.sleep(sleep) # OKX limit: 20 req / 2 s return [[int(d[0])] + [float(x) for x in d[1:6]] for d in rows] def _binance(inst, bar, n, session, sleep): sym = inst.replace("-", "").upper() rows, end = [], None for host in ("https://data-api.binance.vision", "https://api.binance.com"): try: while len(rows) < n: params = {"symbol": sym, "interval": BARS[bar][1], "limit": 1000} if end: params["endTime"] = end r = session.get(host + "/api/v3/klines", params=params, timeout=15) r.raise_for_status() data = r.json() if not isinstance(data, list) or not data: break now = int(time.time() * 1000) rows = [[int(d[0])] + [float(x) for x in d[1:6]] for d in data if int(d[6]) < now] + rows end = int(data[0][0]) - 1 if len(data) < 1000: break time.sleep(sleep) return rows except Exception: if host.endswith("binance.com"): raise rows, end = [], None def fetch_candles(inst="BTC-USDT", bar="1H", n=2000, session=None, sleep=0.15, cache=True): """Return (DataFrame[time, open, high, low, close, volume], source, cache_path).""" inst = inst.strip().upper() if bar not in BARS: raise ValueError(f"bar must be one of {list(BARS)}") n = max(50, min(int(n), MAX_CANDLES)) s = session or requests.Session() errors = [] for name, fn in (("OKX", _okx), ("Binance", _binance)): try: rows = fn(inst, bar, n, s, sleep) if rows: break errors.append(f"{name}: no data") except Exception as e: errors.append(f"{name}: {e}") else: raise ValueError(f"could not fetch {inst}: " + "; ".join(errors)) df = pd.DataFrame(rows, columns=COLS).drop_duplicates("time").sort_values("time").tail(n) df["time"] = pd.to_datetime(df["time"], unit="ms", utc=True).dt.tz_convert(TZ).dt.tz_localize(None) df = df.reset_index(drop=True) path = None if cache: os.makedirs(DATA_DIR, exist_ok=True) path = os.path.join(DATA_DIR, f"{inst}_{bar}.xlsx") df.to_excel(path, index=False) return df, name, path def latest(inst, bar="1H", session=None, limit=100): """Recent candles incl. the current unfinished one (OKX), plus ticker last price. Returns (DataFrame[time, close, live], {"price", "time"}). """ inst = inst.strip().upper() s = session or requests.Session() r = s.get("https://www.okx.com/api/v5/market/candles", params={"instId": inst, "bar": BARS[bar][0], "limit": limit}, timeout=10) r.raise_for_status() j = r.json() if str(j.get("code")) != "0": raise RuntimeError(f"OKX error: {j.get('msg') or j.get('code')}") rows = [(int(d[0]), float(d[4]), len(d) >= 9 and d[8] == "0") for d in j["data"]] df = pd.DataFrame(rows, columns=["time", "close", "live"]).sort_values("time") df["time"] = _to_local(df["time"]) tk = s.get("https://www.okx.com/api/v5/market/ticker", params={"instId": inst}, timeout=10).json() if str(tk.get("code")) != "0" or not tk.get("data"): raise RuntimeError(f"OKX error: {tk.get('msg') or tk.get('code')}") d = tk["data"][0] ts = _to_local(pd.Series([int(d["ts"])])).iloc[0] price = float(d["last"]) if len(df) and df["live"].iloc[-1]: df.loc[df.index[-1], "close"] = price # live candle close = ticker price return df.reset_index(drop=True), {"price": price, "time": str(ts)} def _to_local(ms): return pd.to_datetime(ms, unit="ms", utc=True).dt.tz_convert(TZ).dt.tz_localize(None)