"""Fetch and cache OHLCV candles from Bybit.""" from __future__ import annotations from datetime import datetime, timezone from pathlib import Path import ccxt import pandas as pd CACHE_DIR = Path(__file__).parent / "cache" # Bar duration in ms per timeframe _BAR_MS = {"1m": 60_000, "5m": 300_000, "15m": 900_000} def fetch_candles(symbol: str = "BTC/USDT:USDT", days: int = 60, timeframe: str = "1m") -> pd.DataFrame: """Fetch candles for any supported timeframe, cache to CSV.""" CACHE_DIR.mkdir(exist_ok=True) tag = symbol.replace("/", "_").replace(":", "_") cache = CACHE_DIR / f"{tag}_{days}d_{timeframe}.csv" if cache.exists(): df = pd.read_csv(cache, parse_dates=["timestamp"]) df["timestamp"] = df["timestamp"].dt.tz_localize("UTC") if df["timestamp"].dt.tz is None else df["timestamp"] print(f"Cache: {len(df)} candles from {cache.name}") return df ex = ccxt.bybit({"enableRateLimit": True, "options": {"defaultType": "linear"}}) ex.load_markets() bar_ms = _BAR_MS.get(timeframe, 60_000) since = int((datetime.now(timezone.utc).timestamp() - days * 86400) * 1000) rows = [] while True: batch = ex.fetch_ohlcv(symbol, timeframe, since=since, limit=1000) if not batch: break rows.extend(batch) since = batch[-1][0] + bar_ms print(f"\r {len(rows):,} candles...", end="", flush=True) if len(batch) < 1000: break print(f"\n Total: {len(rows):,}") df = pd.DataFrame(rows, columns=["timestamp", "open", "high", "low", "close", "volume"]) df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True) df.drop_duplicates(subset="timestamp", inplace=True) df.sort_values("timestamp", inplace=True) df.reset_index(drop=True, inplace=True) df.to_csv(cache, index=False) return df def fetch_1m(symbol: str = "BTC/USDT:USDT", days: int = 60) -> pd.DataFrame: """Backward-compatible wrapper.""" return fetch_candles(symbol, days, "1m")