File size: 4,676 Bytes
c6262df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ExchangeClient interface (spec Β§12.1: "Build this abstraction from day one").

OKX is the one implemented backend (the only free, geo-reachable source that
exposes all four layers). The ABC is kept deliberately: it documents the data
contract and lets a second source be added later without touching the engine.
Data is returned in normalized shapes regardless of upstream JSON quirks.

The seven core methods are abstract (any backend must implement them). The
universe/taker helpers are optional (default NotImplementedError) so a future
minimal backend can be added without implementing the full surface β€” the active
source (OKX) implements everything.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import AsyncIterator


@dataclass
class LiqEvent:
    """One liquidation order, normalized across exchanges.

    liquidated_side: 'long'  -> a long position was force-closed (a forced SELL)
                     'short' -> a short position was force-closed (a forced BUY)
    notional: price * qty in USD(T).  ts_ms: event time, unix milliseconds.
    """
    symbol: str
    liquidated_side: str   # 'long' | 'short'
    price: float
    qty: float
    notional: float
    ts_ms: int


@dataclass
class Ticker:
    """A perp ticker row used by the universe funnel (spec Β§2.4, D5)."""
    symbol: str            # exchange-native instrument id (e.g. 'BTC-USDT-SWAP')
    last: float            # last price
    turnover_usd: float    # 24h turnover in USD (liquidity ranking key)


class ExchangeClient(ABC):
    """Async interface every exchange backend must implement."""

    name: str = "base"

    # ── REST: market data (core, required) ──────────────────────────────────
    @abstractmethod
    async def funding_rate(self, symbol: str) -> float:
        """Current funding rate (fraction, e.g. 0.0001 = 0.01%)."""

    @abstractmethod
    async def funding_history(self, symbol: str, limit: int) -> list[float]:
        """Historical funding rates (oldest→newest) for rolling z-score."""

    @abstractmethod
    async def open_interest(self, symbol: str) -> float:
        """Current open interest in USD value."""

    @abstractmethod
    async def oi_history(self, symbol: str, period: str, limit: int) -> list[float]:
        """Historical OI (USD) oldest→newest for percentile computation."""

    @abstractmethod
    async def klines(self, symbol: str, interval: str, limit: int) -> list[dict]:
        """OHLCV bars oldest→newest. Each: {ts, open, high, low, close, volume,
        taker_buy_volume}."""

    @abstractmethod
    async def mark_price(self, symbol: str) -> float:
        """Current mark price."""

    # ── REST: universe & order-flow (optional β€” used by the active source) ───
    async def tickers_universe(self) -> list[Ticker]:
        """All USDT-perp tickers for the dynamic-universe funnel (spec Β§2.4/D5)."""
        raise NotImplementedError(f"{self.name} has no tickers_universe()")

    async def open_interest_map(self) -> dict[str, float]:
        """Batch {symbol: oi_base} for all perps (one call) to avoid N requests."""
        raise NotImplementedError(f"{self.name} has no open_interest_map()")

    async def taker_volume(self, symbol: str, period: str, limit: int) -> list[dict]:
        """Taker buy/sell volume bars (oldest→newest) for L3. Each: {ts, buy, sell}."""
        raise NotImplementedError(f"{self.name} has no taker_volume()")

    # ── WebSocket: liquidations (spec Β§2.1) ─────────────────────────────────
    @abstractmethod
    def liquidation_stream(self) -> AsyncIterator[LiqEvent]:
        """Async generator yielding normalized LiqEvents for ALL symbols.
        Implementations must auto-reconnect with exponential backoff."""

    @abstractmethod
    async def aclose(self) -> None:
        """Release HTTP/WS resources."""


def get_client(exchange: str, watchlist: list[str], timeout: float):
    """Factory: return the configured ExchangeClient.

    Only OKX is implemented in v1.0 β€” Binance/Bybit are geo-blocked on free hosts
    (verified: HTTP 451/403) and were removed. Branch here to add a new source.
    """
    exchange = (exchange or "okx").lower().strip()
    if exchange == "okx":
        from .okx import OKXClient
        return OKXClient(watchlist=watchlist, timeout=timeout)
    raise ValueError(
        f"EXCHANGE={exchange!r} is not supported in v1.0 (only 'okx'). "
        f"Binance/Bybit are geo-blocked on free hosts."
    )