File size: 11,222 Bytes
712f4ea
 
 
 
 
 
 
80df99b
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6219d0
 
 
80df99b
 
 
 
 
d6219d0
 
80df99b
d6219d0
80df99b
 
 
 
 
 
 
d6219d0
80df99b
d6219d0
 
 
 
 
80df99b
 
 
 
 
d6219d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80df99b
 
 
 
 
65ccdcd
80df99b
 
 
 
 
 
 
 
 
 
 
 
 
 
65ccdcd
 
80df99b
 
 
 
 
054ee3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
712f4ea
 
 
 
 
 
 
 
740fcec
712f4ea
 
 
 
 
 
 
 
 
 
 
 
 
48f60d7
 
 
740fcec
712f4ea
 
 
 
740fcec
 
712f4ea
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
Abstract base class for exchange clients.
Each concrete client must implement all abstract methods.
All methods are async-first and must NOT block the event loop.
"""

from abc import ABC, abstractmethod
import time
from typing import Any


class BaseExchange(ABC):
    """Minimal contract every exchange adapter must fulfil."""

    name: str = "base"

    # ------------------------------------------------------------------
    # Market info
    # ------------------------------------------------------------------

    @abstractmethod
    async def get_mark_price(self, symbol: str) -> dict[str, Any]:
        """
        Return:
            {
                "mark_price": float,
                "index_price": float,
                "basis_pct": float,
            }
        """

    @abstractmethod
    async def get_funding_rate(self, symbol: str) -> dict[str, Any]:
        """
        Return:
            {
                "funding_rate": float,   # e.g. 0.0001
                "next_funding_time": int | None,
            }
        """

    @abstractmethod
    async def get_open_interest(self, symbol: str) -> dict[str, Any]:
        """
        Return:
            {
                "open_interest": float,    # in USD notional
                "open_interest_value": float | None,
            }
        """

    @abstractmethod
    async def get_long_short_ratio(self, symbol: str, period: str = "1h") -> dict[str, Any]:
        """
        Top-trader account long/short ratio.
        Return:
            {
                "long_ratio": float,   # 0.0–1.0
                "short_ratio": float,
                "source": "top_trader" | "global",
            }
        """

    @abstractmethod
    async def get_ohlcv(self, symbol: str, timeframe: str, limit: int = 100) -> list[dict]:
        """
        Return list of candles:
            [{"timestamp": int, "open": float, "high": float,
              "low": float, "close": float, "volume": float}, ...]
        """

    @abstractmethod
    async def get_recent_trades(self, symbol: str, limit: int = 500) -> list[dict]:
        """
        Return list:
            [{"price": float, "qty": float, "is_buyer_maker": bool, "time": int}, ...]
        """

    @abstractmethod
    async def get_orderbook(self, symbol: str, depth: int = 20) -> dict[str, Any]:
        """
        Return:
            {
                "bids": [[price, qty], ...],   # best bid first
                "asks": [[price, qty], ...],   # best ask first
            }
        """

    @abstractmethod
    async def check_symbol_exists(self, symbol: str) -> bool:
        """Return True if the perpetual symbol exists on this exchange."""

    # ------------------------------------------------------------------
    # Convenience
    # ------------------------------------------------------------------

    @staticmethod
    def record_oi_change_with_meta(
        snaps_map: dict[str, list[tuple[float, float]]],
        symbol_key: str,
        current_oi: float,
        window_sec: float = 300.0,
        min_sample_gap_sec: float = 30.0,
        max_age_sec: float = 3600.0,
    ) -> tuple[float | None, float | None]:
        """Compute percentage OI change against rolling baseline and return (oi_change_pct, window_sec)."""
        if current_oi <= 0:
            return None, None
        now_ts = time.time()
        raw_snaps = snaps_map.get(symbol_key, [])
        # Drop stale snapshots (e.g. after long idle/sleep) to avoid spurious percentage jumps
        snaps = [(ts, val) for ts, val in raw_snaps if (now_ts - ts) <= max_age_sec and val > 0]
        snaps_map[symbol_key] = snaps

        oi_change_pct = None
        window_sec_actual = None
        if snaps:
            anchor_pair = next(((ts, val) for ts, val in reversed(snaps) if (now_ts - ts) >= window_sec), snaps[0])
            anchor_ts, anchor_val = anchor_pair
            if anchor_val > 0:
                oi_change_pct = round((current_oi - anchor_val) / anchor_val * 100.0, 4)
                window_sec_actual = round(now_ts - anchor_ts, 2)

        if not snaps or (now_ts - snaps[-1][0]) >= min_sample_gap_sec:
            snaps.append((now_ts, current_oi))
            if len(snaps) > 64:
                del snaps[:-64]
        return oi_change_pct, window_sec_actual

    def _record_oi_change_with_meta(
        self,
        symbol_key: str,
        current_oi: float,
        window_sec: float = 300.0,
        min_sample_gap_sec: float = 30.0,
        max_age_sec: float = 3600.0,
    ) -> tuple[float | None, float | None]:
        snaps_map = getattr(self, "_oi_snapshots", None)
        if snaps_map is None:
            snaps_map = {}
            self._oi_snapshots = snaps_map
        return self.record_oi_change_with_meta(
            snaps_map, symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec
        )

    def _record_oi_change(
        self,
        symbol_key: str,
        current_oi: float,
        window_sec: float = 300.0,
        min_sample_gap_sec: float = 30.0,
        max_age_sec: float = 3600.0,
    ) -> float | None:
        """Compute percentage OI change against a rolling ~5m (or oldest recent) baseline."""
        pct, _ = self._record_oi_change_with_meta(
            symbol_key, current_oi, window_sec, min_sample_gap_sec, max_age_sec
        )
        return pct

    @staticmethod
    def _compute_oi_horizons(
        oi_series_oldest_first: list[float],
    ) -> tuple[float | None, float | None, float | None]:
        """Compute 15m, 1h (>=5 bars), and 4h (>=17 bars) OI % changes without mislabeling short history."""
        if len(oi_series_oldest_first) < 2:
            return None, None, None

        curr_oi = oi_series_oldest_first[-1]
        prev_15m = oi_series_oldest_first[-2]
        oi_15m = round(((curr_oi - prev_15m) / prev_15m) * 100.0, 4) if prev_15m > 0 else None

        oi_1h = None
        if len(oi_series_oldest_first) >= 5:
            prev_1h = oi_series_oldest_first[-5]
            if prev_1h > 0:
                oi_1h = round(((curr_oi - prev_1h) / prev_1h) * 100.0, 4)

        oi_4h = None
        if len(oi_series_oldest_first) >= 17:
            prev_4h = oi_series_oldest_first[-17]
            if prev_4h > 0:
                oi_4h = round(((curr_oi - prev_4h) / prev_4h) * 100.0, 4)

        return oi_15m, oi_1h, oi_4h

    def _is_spot_unlisted(self, symbol_key: str, ttl_sec: float = 1800.0) -> bool:
        cache = getattr(self, "_spot_negative_cache", None)
        if not cache:
            return False
        ts = cache.get(symbol_key.upper())
        if ts is None:
            return False
        if (time.time() - ts) < ttl_sec:
            return True
        cache.pop(symbol_key.upper(), None)
        return False

    def _mark_spot_unlisted(self, symbol_key: str) -> None:
        cache = getattr(self, "_spot_negative_cache", None)
        if cache is None:
            cache = {}
            self._spot_negative_cache = cache
        cache[symbol_key.upper()] = time.time()

    def _clear_spot_unlisted(self, symbol_key: str) -> None:
        cache = getattr(self, "_spot_negative_cache", None)
        if cache:
            cache.pop(symbol_key.upper(), None)

    @staticmethod
    def _normalize_taker_buy_volume(
        buy_vol: float,
        sell_vol: float | None,
        candle_vol: float,
    ) -> float:
        """
        Convert exchange taker buy/sell stats into base-coin candle volume units.
        When both buy and sell volumes exist (even in USD or contracts), preserve the exact
        taker buy share proportionally onto candle_vol and clamp safely to [0, candle_vol].
        """
        b = max(0.0, float(buy_vol or 0.0))
        c_vol = max(0.0, float(candle_vol or 0.0))
        if sell_vol is not None:
            s = max(0.0, float(sell_vol or 0.0))
            tot = b + s
            if tot > 0 and c_vol > 0:
                return round(min(c_vol, (b / tot) * c_vol), 8)
        if c_vol > 0:
            return round(min(c_vol, b), 8)
        return round(b, 8)

    @staticmethod
    def _match_taker_buy_volume(
        taker_map: dict[int, tuple[float, float | None]],
        candle_ts: int,
        interval_ms: int,
        candle_vol: float,
    ) -> float | None:
        """Match closest taker volume entry to candle_ts and return normalized base-coin buy volume."""
        if not taker_map:
            return None
        if candle_ts in taker_map:
            tb_buy, tb_sell = taker_map[candle_ts]
            return BaseExchange._normalize_taker_buy_volume(tb_buy, tb_sell, candle_vol)
        best_pair = None
        min_diff = interval_ms
        for t_ts, pair_vals in taker_map.items():
            diff = abs(candle_ts - t_ts)
            if diff < min_diff:
                min_diff = diff
                best_pair = pair_vals
        if best_pair is not None:
            return BaseExchange._normalize_taker_buy_volume(best_pair[0], best_pair[1], candle_vol)
        return None

    async def get_full_snapshot(self, symbol: str) -> dict[str, Any]:
        """
        Collect all data for a symbol in one call.
        Partial failures are tolerated – missing keys will be None.
        """
        import asyncio

        results: dict[str, Any] = {
            "symbol": symbol,
            "exchange": self.name,
            "mark_price_data": None,
            "funding_rate_data": None,
            "open_interest_data": None,
            "ls_ratio_data": None,
            "ohlcv": {},
            "trades": [],
            "spot_trades": [],
            "orderbook": None,
            "liquidations": [],
        }

        async def safe(coro, key):
            try:
                results[key] = await coro
            except Exception as exc:
                results[key] = None

        timeframes = ["1m", "5m", "15m", "1h", "4h", "1d"]

        tasks = [
            safe(self.get_mark_price(symbol), "mark_price_data"),
            safe(self.get_funding_rate(symbol), "funding_rate_data"),
            safe(self.get_open_interest(symbol), "open_interest_data"),
            safe(self.get_long_short_ratio(symbol), "ls_ratio_data"),
            safe(self.get_recent_trades(symbol, limit=500), "trades"),
            safe(self.get_orderbook(symbol, depth=20), "orderbook"),
        ]

        if hasattr(self, "get_spot_trades"):
            tasks.append(safe(self.get_spot_trades(symbol, limit=500), "spot_trades"))

        if hasattr(self, "get_liquidations"):
            tasks.append(safe(self.get_liquidations(symbol, limit=100), "liquidations"))

        # OHLCV per timeframe (30 recent 1m bars for FakeDetector, 100 bars for higher TFs)
        ohlcv_results: dict[str, list] = {}
        for tf in timeframes:
            async def _fetch_ohlcv(tf=tf):
                try:
                    tf_limit = 30 if tf == "1m" else 100
                    ohlcv_results[tf] = await self.get_ohlcv(symbol, tf, limit=tf_limit)
                except Exception:
                    ohlcv_results[tf] = []

            tasks.append(_fetch_ohlcv())

        await asyncio.gather(*tasks, return_exceptions=True)
        results["ohlcv"] = ohlcv_results

        return results