File size: 5,975 Bytes
15151cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""Market data: OHLCV candles from public exchange endpoints or local files.

Public candle endpoints need no API key. All adapters return a pandas
DataFrame with columns [timestamp(UTC), open, high, low, close, volume],
sorted ascending, one row per candle.
"""
from __future__ import annotations

import time
from dataclasses import dataclass
from pathlib import Path
from typing import Optional

import pandas as pd
import requests

COLUMNS = ["timestamp", "open", "high", "low", "close", "volume"]

_TF_SECONDS = {
    "1m": 60, "5m": 300, "15m": 900, "30m": 1800,
    "1h": 3600, "2h": 7200, "4h": 14400, "1d": 86400,
}


def timeframe_seconds(tf: str) -> int:
    if tf not in _TF_SECONDS:
        raise ValueError(f"unsupported timeframe {tf}; use one of {list(_TF_SECONDS)}")
    return _TF_SECONDS[tf]


def _frame(rows, unit="ms") -> pd.DataFrame:
    df = pd.DataFrame(rows, columns=COLUMNS)
    df["timestamp"] = pd.to_datetime(df["timestamp"], unit=unit, utc=True)
    for c in ["open", "high", "low", "close", "volume"]:
        df[c] = pd.to_numeric(df[c], errors="coerce")
    df = df.dropna().sort_values("timestamp").drop_duplicates("timestamp")
    return df.reset_index(drop=True)


@dataclass
class ExchangeInfo:
    name: str
    symbol_format: str  # e.g. "BTCUSDT" or "XBTUSD"


class MarketData:
    """Fetches candles from a public exchange REST endpoint."""

    def __init__(self, exchange: str = "binance", session: Optional[requests.Session] = None, timeout: int = 20):
        self.exchange = exchange.lower()
        self.session = session or requests.Session()
        self.timeout = timeout
        if self.exchange not in ("binance", "kraken", "coinbase"):
            raise ValueError("exchange must be binance, kraken or coinbase")

    # --- symbol helpers -------------------------------------------------
    @staticmethod
    def split(symbol: str) -> tuple[str, str]:
        base, quote = symbol.upper().split("/")
        return base, quote

    def native_symbol(self, symbol: str) -> str:
        base, quote = self.split(symbol)
        if self.exchange == "binance":
            return f"{base}{quote}"
        if self.exchange == "kraken":
            base = "XBT" if base == "BTC" else base
            return f"{base}{quote}"
        return f"{base}-{quote}"  # coinbase

    # --- fetch ------------------------------------------------------------
    def candles(self, symbol: str, timeframe: str = "1h", limit: int = 500) -> pd.DataFrame:
        tf_s = timeframe_seconds(timeframe)
        if self.exchange == "binance":
            r = self.session.get(
                "https://api.binance.com/api/v3/klines",
                params={"symbol": self.native_symbol(symbol), "interval": timeframe, "limit": min(limit, 1000)},
                timeout=self.timeout,
            )
            r.raise_for_status()
            rows = [[k[0], k[1], k[2], k[3], k[4], k[5]] for k in r.json()]
            return _frame(rows, "ms")
        if self.exchange == "kraken":
            r = self.session.get(
                "https://api.kraken.com/0/public/OHLC",
                params={"pair": self.native_symbol(symbol), "interval": tf_s // 60},
                timeout=self.timeout,
            )
            r.raise_for_status()
            payload = r.json()
            if payload.get("error"):
                raise RuntimeError(f"kraken: {payload['error']}")
            key = next(k for k in payload["result"] if k != "last")
            rows = [[k[0], k[1], k[2], k[3], k[4], k[6]] for k in payload["result"][key]]
            return _frame(rows, "s").tail(limit).reset_index(drop=True)
        # coinbase exchange public candles: [time, low, high, open, close, volume]
        end = int(time.time())
        start = end - tf_s * min(limit, 300)
        r = self.session.get(
            f"https://api.exchange.coinbase.com/products/{self.native_symbol(symbol)}/candles",
            params={"granularity": tf_s, "start": start, "end": end},
            timeout=self.timeout,
        )
        r.raise_for_status()
        rows = [[k[0], k[3], k[2], k[1], k[4], k[5]] for k in r.json()]
        return _frame(rows, "s")

    def last_price(self, symbol: str) -> float:
        df = self.candles(symbol, "1m", limit=2)
        return float(df["close"].iloc[-1])


def load_csv(path: str | Path, symbol: Optional[str] = None) -> pd.DataFrame:
    """Load candles from CSV with columns timestamp[,asset],open,high,low,close,volume."""
    df = pd.read_csv(path)
    if "asset" in df.columns and symbol:
        df = df[df["asset"] == symbol]
    if "datetime" in df.columns and "timestamp" not in df.columns:
        df = df.rename(columns={"datetime": "timestamp"})
    df = df[COLUMNS].copy()
    df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
    return df.sort_values("timestamp").reset_index(drop=True)


def load_parquet(path: str | Path) -> pd.DataFrame:
    df = pd.read_parquet(path)
    if "datetime" in df.columns:
        df = df.rename(columns={"datetime": "timestamp"})
    df = df[COLUMNS].copy()
    df["timestamp"] = pd.to_datetime(df["timestamp"], utc=True)
    return df.sort_values("timestamp").reset_index(drop=True)


def synthetic(n: int = 2000, seed: int = 7, start_price: float = 30000.0, tf: str = "1h") -> pd.DataFrame:
    """Random-walk candles for tests. Not a market model — just plumbing data."""
    import numpy as np

    rng = np.random.default_rng(seed)
    rets = rng.normal(0, 0.01, n)
    close = start_price * np.exp(np.cumsum(rets))
    open_ = np.concatenate([[start_price], close[:-1]])
    high = np.maximum(open_, close) * (1 + rng.uniform(0, 0.005, n))
    low = np.minimum(open_, close) * (1 - rng.uniform(0, 0.005, n))
    vol = rng.uniform(10, 100, n)
    ts = pd.date_range("2024-01-01", periods=n, freq=f"{timeframe_seconds(tf)}s", tz="UTC")
    return pd.DataFrame({"timestamp": ts, "open": open_, "high": high, "low": low, "close": close, "volume": vol})