Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
bf49534
1
Parent(s): 7843862
feat(chart): implement multi-exchange aggregated order flow, aggregated open interest, and LOCF alignment
Browse files- backend/exchanges/binance.py +61 -0
- backend/exchanges/bybit.py +60 -0
- backend/routers/market.py +292 -72
- frontend/src/api/market.ts +33 -0
- frontend/src/components/chart/AggregatedOIChart.tsx +195 -0
- frontend/src/components/chart/FundingRateHistoryChart.tsx +152 -0
- frontend/src/hooks/useChartData.ts +3 -0
- frontend/src/pages/LiveChartTerminal.tsx +84 -13
- tests/test_chart.py +61 -0
backend/exchanges/binance.py
CHANGED
|
@@ -347,5 +347,66 @@ class BinanceClient(BaseExchange):
|
|
| 347 |
"asks": [[float(p), float(q)] for p, q in data["asks"]],
|
| 348 |
}
|
| 349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
async def close(self) -> None:
|
| 351 |
await self._client.aclose()
|
|
|
|
| 347 |
"asks": [[float(p), float(q)] for p, q in data["asks"]],
|
| 348 |
}
|
| 349 |
|
| 350 |
+
async def get_oi_history(self, symbol: str, timeframe: str = "15m", limit: int = 150) -> list[dict]:
|
| 351 |
+
"""Fetch historical Open Interest from Binance (/futures/data/openInterestHist)."""
|
| 352 |
+
sym = self.resolve_symbol(symbol) or symbol
|
| 353 |
+
period_map = {
|
| 354 |
+
"1m": "5m",
|
| 355 |
+
"3m": "5m",
|
| 356 |
+
"5m": "5m",
|
| 357 |
+
"15m": "15m",
|
| 358 |
+
"30m": "30m",
|
| 359 |
+
"1h": "1h",
|
| 360 |
+
"2h": "2h",
|
| 361 |
+
"4h": "4h",
|
| 362 |
+
"1d": "1d",
|
| 363 |
+
}
|
| 364 |
+
period = period_map.get(timeframe, "15m")
|
| 365 |
+
try:
|
| 366 |
+
data = await self._get(
|
| 367 |
+
"/futures/data/openInterestHist",
|
| 368 |
+
{"symbol": sym, "period": period, "limit": min(limit, 500)},
|
| 369 |
+
)
|
| 370 |
+
if not isinstance(data, list):
|
| 371 |
+
return []
|
| 372 |
+
results = []
|
| 373 |
+
for item in data:
|
| 374 |
+
ts = int(item.get("timestamp", 0))
|
| 375 |
+
oi = float(item.get("sumOpenInterest", 0.0) or 0.0)
|
| 376 |
+
oi_val = float(item.get("sumOpenInterestValue", 0.0) or 0.0)
|
| 377 |
+
results.append({
|
| 378 |
+
"timestamp": ts,
|
| 379 |
+
"open_interest": oi,
|
| 380 |
+
"open_interest_usd": oi_val,
|
| 381 |
+
})
|
| 382 |
+
results.sort(key=lambda x: x["timestamp"])
|
| 383 |
+
return results
|
| 384 |
+
except Exception as exc:
|
| 385 |
+
logger.debug("[Binance] Failed to fetch OI history for %s: %s", sym, exc)
|
| 386 |
+
return []
|
| 387 |
+
|
| 388 |
+
async def get_funding_rate_history(self, symbol: str, limit: int = 50) -> list[dict]:
|
| 389 |
+
"""Fetch historical funding rates from Binance (/fapi/v1/fundingRate)."""
|
| 390 |
+
sym = self.resolve_symbol(symbol) or symbol
|
| 391 |
+
try:
|
| 392 |
+
data = await self._get(
|
| 393 |
+
"/fapi/v1/fundingRate",
|
| 394 |
+
{"symbol": sym, "limit": min(limit, 100)},
|
| 395 |
+
)
|
| 396 |
+
if not isinstance(data, list):
|
| 397 |
+
return []
|
| 398 |
+
results = []
|
| 399 |
+
for item in data:
|
| 400 |
+
results.append({
|
| 401 |
+
"timestamp": int(item.get("fundingTime", 0)),
|
| 402 |
+
"funding_rate": float(item.get("fundingRate", 0.0) or 0.0),
|
| 403 |
+
"mark_price": float(item.get("markPrice", 0.0) or 0.0),
|
| 404 |
+
})
|
| 405 |
+
results.sort(key=lambda x: x["timestamp"])
|
| 406 |
+
return results
|
| 407 |
+
except Exception as exc:
|
| 408 |
+
logger.debug("[Binance] Failed to fetch funding history for %s: %s", sym, exc)
|
| 409 |
+
return []
|
| 410 |
+
|
| 411 |
async def close(self) -> None:
|
| 412 |
await self._client.aclose()
|
backend/exchanges/bybit.py
CHANGED
|
@@ -346,5 +346,65 @@ class BybitClient(BaseExchange):
|
|
| 346 |
"asks": [[float(p), float(q)] for p, q in result.get("a", [])],
|
| 347 |
}
|
| 348 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
async def close(self) -> None:
|
| 350 |
await self._client.aclose()
|
|
|
|
| 346 |
"asks": [[float(p), float(q)] for p, q in result.get("a", [])],
|
| 347 |
}
|
| 348 |
|
| 349 |
+
async def get_oi_history(self, symbol: str, timeframe: str = "15m", limit: int = 150) -> list[dict]:
|
| 350 |
+
"""Fetch historical Open Interest from Bybit (/v5/market/open-interest)."""
|
| 351 |
+
sym = self.resolve_symbol(symbol) or symbol
|
| 352 |
+
interval_map = {
|
| 353 |
+
"1m": "5min",
|
| 354 |
+
"3m": "5min",
|
| 355 |
+
"5m": "5min",
|
| 356 |
+
"15m": "15min",
|
| 357 |
+
"30m": "30min",
|
| 358 |
+
"1h": "1h",
|
| 359 |
+
"2h": "1h",
|
| 360 |
+
"4h": "4h",
|
| 361 |
+
"1d": "1d",
|
| 362 |
+
}
|
| 363 |
+
interval = interval_map.get(timeframe, "15min")
|
| 364 |
+
try:
|
| 365 |
+
res = await self._get(
|
| 366 |
+
"/v5/market/open-interest",
|
| 367 |
+
{"category": "linear", "symbol": sym, "intervalTime": interval, "limit": min(limit, 200)},
|
| 368 |
+
)
|
| 369 |
+
raw_list = res.get("list", [])
|
| 370 |
+
if not isinstance(raw_list, list):
|
| 371 |
+
return []
|
| 372 |
+
results = []
|
| 373 |
+
for item in raw_list:
|
| 374 |
+
ts = int(item.get("timestamp", 0))
|
| 375 |
+
oi = float(item.get("openInterest", 0.0) or 0.0)
|
| 376 |
+
results.append({
|
| 377 |
+
"timestamp": ts,
|
| 378 |
+
"open_interest": oi,
|
| 379 |
+
})
|
| 380 |
+
results.sort(key=lambda x: x["timestamp"])
|
| 381 |
+
return results
|
| 382 |
+
except Exception as exc:
|
| 383 |
+
logger.debug("[Bybit] Failed to fetch OI history for %s: %s", sym, exc)
|
| 384 |
+
return []
|
| 385 |
+
|
| 386 |
+
async def get_funding_rate_history(self, symbol: str, limit: int = 50) -> list[dict]:
|
| 387 |
+
"""Fetch historical funding rates from Bybit (/v5/market/funding/history)."""
|
| 388 |
+
sym = self.resolve_symbol(symbol) or symbol
|
| 389 |
+
try:
|
| 390 |
+
res = await self._get(
|
| 391 |
+
"/v5/market/funding/history",
|
| 392 |
+
{"category": "linear", "symbol": sym, "limit": min(limit, 100)},
|
| 393 |
+
)
|
| 394 |
+
raw_list = res.get("list", [])
|
| 395 |
+
if not isinstance(raw_list, list):
|
| 396 |
+
return []
|
| 397 |
+
results = []
|
| 398 |
+
for item in raw_list:
|
| 399 |
+
results.append({
|
| 400 |
+
"timestamp": int(item.get("fundingRateTimestamp", 0)),
|
| 401 |
+
"funding_rate": float(item.get("fundingRate", 0.0) or 0.0),
|
| 402 |
+
})
|
| 403 |
+
results.sort(key=lambda x: x["timestamp"])
|
| 404 |
+
return results
|
| 405 |
+
except Exception as exc:
|
| 406 |
+
logger.debug("[Bybit] Failed to fetch funding history for %s: %s", sym, exc)
|
| 407 |
+
return []
|
| 408 |
+
|
| 409 |
async def close(self) -> None:
|
| 410 |
await self._client.aclose()
|
backend/routers/market.py
CHANGED
|
@@ -3,6 +3,7 @@
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import asyncio
|
|
|
|
| 6 |
import logging
|
| 7 |
import time
|
| 8 |
from typing import Any
|
|
@@ -25,6 +26,43 @@ def _safe_get(data: Any, key: str, default: Any = None) -> Any:
|
|
| 25 |
return default
|
| 26 |
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
@router.get("/{symbol}")
|
| 29 |
async def get_market_snapshot(symbol: str):
|
| 30 |
"""Return the latest market snapshot for each exchange for a given symbol."""
|
|
@@ -43,9 +81,8 @@ async def get_market_candles(
|
|
| 43 |
exchange: str | None = Query(default=None),
|
| 44 |
):
|
| 45 |
"""
|
| 46 |
-
Fetch historical candlestick (OHLCV) data normalized for lightweight-charts.
|
| 47 |
-
|
| 48 |
-
Automatically selects the best exchange if 'exchange' is omitted.
|
| 49 |
"""
|
| 50 |
clean_sym = symbol.strip().upper().replace("/", "").replace("-", "")
|
| 51 |
binance = getattr(request.app.state, "binance", None)
|
|
@@ -53,72 +90,166 @@ async def get_market_candles(
|
|
| 53 |
okx = getattr(request.app.state, "okx", None)
|
| 54 |
bitget = getattr(request.app.state, "bitget", None)
|
| 55 |
|
| 56 |
-
# Determine priority of exchanges to query
|
| 57 |
-
exchanges_to_try: list[tuple[str, Any]] = []
|
| 58 |
-
|
| 59 |
req_exch = exchange.lower().strip() if exchange else ""
|
| 60 |
-
|
| 61 |
-
exchanges_to_try.append(("binance", binance))
|
| 62 |
-
elif req_exch == "bybit" and bybit:
|
| 63 |
-
exchanges_to_try.append(("bybit", bybit))
|
| 64 |
-
elif req_exch == "okx" and okx:
|
| 65 |
-
exchanges_to_try.append(("okx", okx))
|
| 66 |
-
elif req_exch == "bitget" and bitget:
|
| 67 |
-
exchanges_to_try.append(("bitget", bitget))
|
| 68 |
-
else:
|
| 69 |
-
# Auto-detection priority
|
| 70 |
-
pair = await async_get_pair(clean_sym)
|
| 71 |
-
if pair:
|
| 72 |
-
if pair.get("on_binance") and binance:
|
| 73 |
-
exchanges_to_try.append(("binance", binance))
|
| 74 |
-
if pair.get("on_bybit") and bybit:
|
| 75 |
-
exchanges_to_try.append(("bybit", bybit))
|
| 76 |
-
if pair.get("on_okx") and okx:
|
| 77 |
-
exchanges_to_try.append(("okx", okx))
|
| 78 |
-
if pair.get("on_bitget") and bitget:
|
| 79 |
-
exchanges_to_try.append(("bitget", bitget))
|
| 80 |
-
|
| 81 |
-
# Fallbacks in case pair not in DB or missing flag
|
| 82 |
-
if binance and ("binance", binance) not in exchanges_to_try:
|
| 83 |
-
exchanges_to_try.append(("binance", binance))
|
| 84 |
-
if bybit and ("bybit", bybit) not in exchanges_to_try:
|
| 85 |
-
exchanges_to_try.append(("bybit", bybit))
|
| 86 |
-
if okx and ("okx", okx) not in exchanges_to_try:
|
| 87 |
-
exchanges_to_try.append(("okx", okx))
|
| 88 |
-
if bitget and ("bitget", bitget) not in exchanges_to_try:
|
| 89 |
-
exchanges_to_try.append(("bitget", bitget))
|
| 90 |
-
|
| 91 |
-
raw_candles: list[dict] = []
|
| 92 |
-
resolved_exchange = "unknown"
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
if not
|
| 106 |
raise HTTPException(
|
| 107 |
status_code=404,
|
| 108 |
detail=f"Candle data for {clean_sym} ({timeframe}) unavailable across supported exchanges",
|
| 109 |
)
|
| 110 |
|
| 111 |
# Sort candles chronologically by timestamp
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
-
# Calculate per-candle delta & cumulative volume delta (CVD)
|
| 115 |
normalized_candles: list[dict[str, Any]] = []
|
| 116 |
running_cvd = 0.0
|
| 117 |
seen_times: set[int] = set()
|
| 118 |
|
| 119 |
-
for c in
|
| 120 |
ts = c.get("timestamp", 0)
|
| 121 |
-
# Convert ms timestamp to seconds for Lightweight Charts
|
| 122 |
time_sec = int(ts / 1000) if ts > 100_000_000_000 else int(ts)
|
| 123 |
if time_sec in seen_times:
|
| 124 |
continue
|
|
@@ -128,23 +259,36 @@ async def get_market_candles(
|
|
| 128 |
h = float(c.get("high") or 0.0)
|
| 129 |
l = float(c.get("low") or 0.0)
|
| 130 |
cl = float(c.get("close") or 0.0)
|
| 131 |
-
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
else
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
normalized_candles.append({
|
| 150 |
"time": time_sec,
|
|
@@ -152,19 +296,36 @@ async def get_market_candles(
|
|
| 152 |
"high": h,
|
| 153 |
"low": l,
|
| 154 |
"close": cl,
|
| 155 |
-
"volume":
|
| 156 |
-
"delta": round(
|
| 157 |
"cvd": round(running_cvd, 4),
|
|
|
|
| 158 |
})
|
| 159 |
|
| 160 |
current_price = normalized_candles[-1]["close"] if normalized_candles else 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
return {
|
| 163 |
"symbol": clean_sym,
|
| 164 |
-
"exchange": resolved_exchange,
|
| 165 |
"timeframe": timeframe,
|
| 166 |
"count": len(normalized_candles),
|
| 167 |
"current_price": current_price,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
"candles": normalized_candles,
|
| 169 |
}
|
| 170 |
|
|
@@ -311,3 +472,62 @@ async def get_multi_exchange_stream(symbol: str, request: Request):
|
|
| 311 |
},
|
| 312 |
},
|
| 313 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import asyncio
|
| 6 |
+
import inspect
|
| 7 |
import logging
|
| 8 |
import time
|
| 9 |
from typing import Any
|
|
|
|
| 26 |
return default
|
| 27 |
|
| 28 |
|
| 29 |
+
def _calculate_candle_delta(c: dict[str, Any] | None) -> float:
|
| 30 |
+
"""
|
| 31 |
+
Calculate directional or taker-volume delta for a single candle.
|
| 32 |
+
Uses exact taker buy/sell volume when available (e.g. Binance).
|
| 33 |
+
Falls back to a blended Body Momentum + Close Location Value (CLV) model
|
| 34 |
+
when exchange doesn't provide taker volume (e.g. Bybit).
|
| 35 |
+
"""
|
| 36 |
+
if not c:
|
| 37 |
+
return 0.0
|
| 38 |
+
o = float(c.get("open") or 0.0)
|
| 39 |
+
h = float(c.get("high") or 0.0)
|
| 40 |
+
l = float(c.get("low") or 0.0)
|
| 41 |
+
cl = float(c.get("close") or 0.0)
|
| 42 |
+
vol = float(c.get("volume") or 0.0)
|
| 43 |
+
|
| 44 |
+
tbv = c.get("taker_buy_volume")
|
| 45 |
+
if tbv is not None and str(tbv).strip() != "":
|
| 46 |
+
try:
|
| 47 |
+
buy_vol = float(tbv)
|
| 48 |
+
sell_vol = max(0.0, vol - buy_vol)
|
| 49 |
+
return buy_vol - sell_vol
|
| 50 |
+
except (ValueError, TypeError):
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
rng = h - l
|
| 54 |
+
if rng <= 0:
|
| 55 |
+
return 0.0
|
| 56 |
+
|
| 57 |
+
# Blended Body Momentum + Close Location Value (CLV)
|
| 58 |
+
# Body factor: (Close - Open) / (High - Low) -> [-1, 1]
|
| 59 |
+
# Wick/CLV factor: (2 * Close - High - Low) / (High - Low) -> [-1, 1]
|
| 60 |
+
body_factor = (cl - o) / rng
|
| 61 |
+
clv_factor = (2.0 * cl - h - l) / rng
|
| 62 |
+
blended_factor = max(-1.0, min(1.0, 0.5 * body_factor + 0.5 * clv_factor))
|
| 63 |
+
return blended_factor * vol
|
| 64 |
+
|
| 65 |
+
|
| 66 |
@router.get("/{symbol}")
|
| 67 |
async def get_market_snapshot(symbol: str):
|
| 68 |
"""Return the latest market snapshot for each exchange for a given symbol."""
|
|
|
|
| 81 |
exchange: str | None = Query(default=None),
|
| 82 |
):
|
| 83 |
"""
|
| 84 |
+
Fetch historical candlestick (OHLCV) and Open Interest data normalized for lightweight-charts.
|
| 85 |
+
Supports multi-exchange aggregation (Binance + Bybit + OKX volume & delta, plus aggregated OI $).
|
|
|
|
| 86 |
"""
|
| 87 |
clean_sym = symbol.strip().upper().replace("/", "").replace("-", "")
|
| 88 |
binance = getattr(request.app.state, "binance", None)
|
|
|
|
| 90 |
okx = getattr(request.app.state, "okx", None)
|
| 91 |
bitget = getattr(request.app.state, "bitget", None)
|
| 92 |
|
|
|
|
|
|
|
|
|
|
| 93 |
req_exch = exchange.lower().strip() if exchange else ""
|
| 94 |
+
is_aggregated_mode = req_exch in ("", "auto", "aggregated")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
raw_primary_candles: list[dict] = []
|
| 97 |
+
raw_secondary_candles: list[dict] = []
|
| 98 |
+
raw_binance_oi: list[dict] = []
|
| 99 |
+
raw_bybit_oi: list[dict] = []
|
| 100 |
+
resolved_exchange = "unknown"
|
| 101 |
+
exchanges_included: list[str] = []
|
| 102 |
+
|
| 103 |
+
if is_aggregated_mode:
|
| 104 |
+
# 1. Fetch Binance & Bybit candles + OI concurrently
|
| 105 |
+
tasks = {}
|
| 106 |
+
if binance and callable(getattr(binance, "get_ohlcv", None)):
|
| 107 |
+
c = binance.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
|
| 108 |
+
if inspect.isawaitable(c):
|
| 109 |
+
tasks["binance_candles"] = c
|
| 110 |
+
if binance and callable(getattr(binance, "get_oi_history", None)):
|
| 111 |
+
oi = binance.get_oi_history(clean_sym, timeframe=timeframe, limit=limit)
|
| 112 |
+
if inspect.isawaitable(oi):
|
| 113 |
+
tasks["binance_oi"] = oi
|
| 114 |
+
|
| 115 |
+
if bybit and callable(getattr(bybit, "get_ohlcv", None)):
|
| 116 |
+
c = bybit.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
|
| 117 |
+
if inspect.isawaitable(c):
|
| 118 |
+
tasks["bybit_candles"] = c
|
| 119 |
+
if bybit and callable(getattr(bybit, "get_oi_history", None)):
|
| 120 |
+
oi = bybit.get_oi_history(clean_sym, timeframe=timeframe, limit=limit)
|
| 121 |
+
if inspect.isawaitable(oi):
|
| 122 |
+
tasks["bybit_oi"] = oi
|
| 123 |
+
|
| 124 |
+
results: dict[str, Any] = {}
|
| 125 |
+
if tasks:
|
| 126 |
+
keys = list(tasks.keys())
|
| 127 |
+
res_list = await asyncio.gather(*tasks.values(), return_exceptions=True)
|
| 128 |
+
for k, r in zip(keys, res_list):
|
| 129 |
+
results[k] = r if not isinstance(r, Exception) and isinstance(r, list) else []
|
| 130 |
+
|
| 131 |
+
binance_c = results.get("binance_candles", [])
|
| 132 |
+
bybit_c = results.get("bybit_candles", [])
|
| 133 |
+
raw_binance_oi = results.get("binance_oi", [])
|
| 134 |
+
raw_bybit_oi = results.get("bybit_oi", [])
|
| 135 |
+
|
| 136 |
+
if binance_c and len(binance_c) > 0:
|
| 137 |
+
raw_primary_candles = binance_c
|
| 138 |
+
resolved_exchange = "binance"
|
| 139 |
+
exchanges_included.append("binance")
|
| 140 |
+
if bybit_c and len(bybit_c) > 0:
|
| 141 |
+
raw_secondary_candles = bybit_c
|
| 142 |
+
exchanges_included.append("bybit")
|
| 143 |
+
elif bybit_c and len(bybit_c) > 0:
|
| 144 |
+
raw_primary_candles = bybit_c
|
| 145 |
+
resolved_exchange = "bybit"
|
| 146 |
+
exchanges_included.append("bybit")
|
| 147 |
+
else:
|
| 148 |
+
# Fallback to OKX or Bitget if neither Binance nor Bybit had it
|
| 149 |
+
for ex_name, client in [("okx", okx), ("bitget", bitget)]:
|
| 150 |
+
if client:
|
| 151 |
+
try:
|
| 152 |
+
res = await client.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
|
| 153 |
+
if res and len(res) > 0:
|
| 154 |
+
raw_primary_candles = res
|
| 155 |
+
resolved_exchange = ex_name
|
| 156 |
+
exchanges_included.append(ex_name)
|
| 157 |
+
break
|
| 158 |
+
except Exception:
|
| 159 |
+
continue
|
| 160 |
+
else:
|
| 161 |
+
# Explicit single exchange mode (e.g. ?exchange=bybit or ?exchange=binance)
|
| 162 |
+
client = None
|
| 163 |
+
if req_exch == "binance":
|
| 164 |
+
client = binance
|
| 165 |
+
elif req_exch == "bybit":
|
| 166 |
+
client = bybit
|
| 167 |
+
elif req_exch == "okx":
|
| 168 |
+
client = okx
|
| 169 |
+
elif req_exch == "bitget":
|
| 170 |
+
client = bitget
|
| 171 |
+
|
| 172 |
+
if client:
|
| 173 |
+
try:
|
| 174 |
+
res = await client.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
|
| 175 |
+
if res and len(res) > 0:
|
| 176 |
+
raw_primary_candles = res
|
| 177 |
+
resolved_exchange = req_exch
|
| 178 |
+
exchanges_included.append(req_exch)
|
| 179 |
+
except Exception:
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
if req_exch == "binance" and binance and hasattr(binance, "get_oi_history"):
|
| 183 |
+
try:
|
| 184 |
+
raw_binance_oi = await binance.get_oi_history(clean_sym, timeframe=timeframe, limit=limit)
|
| 185 |
+
except Exception:
|
| 186 |
+
pass
|
| 187 |
+
elif req_exch == "bybit" and bybit and hasattr(bybit, "get_oi_history"):
|
| 188 |
+
try:
|
| 189 |
+
raw_bybit_oi = await bybit.get_oi_history(clean_sym, timeframe=timeframe, limit=limit)
|
| 190 |
+
except Exception:
|
| 191 |
+
pass
|
| 192 |
|
| 193 |
+
if not raw_primary_candles:
|
| 194 |
raise HTTPException(
|
| 195 |
status_code=404,
|
| 196 |
detail=f"Candle data for {clean_sym} ({timeframe}) unavailable across supported exchanges",
|
| 197 |
)
|
| 198 |
|
| 199 |
# Sort candles chronologically by timestamp
|
| 200 |
+
raw_primary_candles.sort(key=lambda c: c.get("timestamp", 0))
|
| 201 |
+
|
| 202 |
+
# Index secondary candles by time_sec
|
| 203 |
+
secondary_by_time: dict[int, dict] = {}
|
| 204 |
+
for sc in raw_secondary_candles:
|
| 205 |
+
s_ts = sc.get("timestamp", 0)
|
| 206 |
+
s_sec = int(s_ts / 1000) if s_ts > 100_000_000_000 else int(s_ts)
|
| 207 |
+
secondary_by_time[s_sec] = sc
|
| 208 |
+
|
| 209 |
+
# Index OI data by time_sec
|
| 210 |
+
binance_oi_map: dict[int, float] = {}
|
| 211 |
+
for item in raw_binance_oi:
|
| 212 |
+
ts = int(item.get("timestamp", 0))
|
| 213 |
+
sec = int(ts / 1000) if ts > 100_000_000_000 else ts
|
| 214 |
+
oi_val = float(item.get("open_interest_usd") or 0.0)
|
| 215 |
+
if oi_val > 0:
|
| 216 |
+
binance_oi_map[sec] = oi_val
|
| 217 |
+
|
| 218 |
+
bybit_oi_map: dict[int, float] = {}
|
| 219 |
+
for item in raw_bybit_oi:
|
| 220 |
+
ts = int(item.get("timestamp", 0))
|
| 221 |
+
sec = int(ts / 1000) if ts > 100_000_000_000 else ts
|
| 222 |
+
oi_coins = float(item.get("open_interest") or 0.0)
|
| 223 |
+
if oi_coins > 0:
|
| 224 |
+
bybit_oi_map[sec] = oi_coins
|
| 225 |
+
|
| 226 |
+
import bisect
|
| 227 |
+
|
| 228 |
+
sorted_b_keys = sorted(binance_oi_map.keys())
|
| 229 |
+
sorted_by_keys = sorted(bybit_oi_map.keys())
|
| 230 |
+
|
| 231 |
+
def _get_locf_value(val_map: dict[int, float], sorted_keys: list[int], target_sec: int) -> float | None:
|
| 232 |
+
"""
|
| 233 |
+
Extract continuous state Open Interest using Last Observation Carried Forward (LOCF)
|
| 234 |
+
and baseline backward fill to eliminate artificial step-cliff discontinuities.
|
| 235 |
+
"""
|
| 236 |
+
if not val_map or not sorted_keys:
|
| 237 |
+
return None
|
| 238 |
+
if target_sec in val_map:
|
| 239 |
+
return val_map[target_sec]
|
| 240 |
+
if target_sec < sorted_keys[0]:
|
| 241 |
+
return val_map[sorted_keys[0]]
|
| 242 |
+
if target_sec >= sorted_keys[-1]:
|
| 243 |
+
return val_map[sorted_keys[-1]]
|
| 244 |
+
idx = bisect.bisect_right(sorted_keys, target_sec) - 1
|
| 245 |
+
return val_map[sorted_keys[idx]]
|
| 246 |
|
|
|
|
| 247 |
normalized_candles: list[dict[str, Any]] = []
|
| 248 |
running_cvd = 0.0
|
| 249 |
seen_times: set[int] = set()
|
| 250 |
|
| 251 |
+
for c in raw_primary_candles:
|
| 252 |
ts = c.get("timestamp", 0)
|
|
|
|
| 253 |
time_sec = int(ts / 1000) if ts > 100_000_000_000 else int(ts)
|
| 254 |
if time_sec in seen_times:
|
| 255 |
continue
|
|
|
|
| 259 |
h = float(c.get("high") or 0.0)
|
| 260 |
l = float(c.get("low") or 0.0)
|
| 261 |
cl = float(c.get("close") or 0.0)
|
| 262 |
+
p_vol = float(c.get("volume") or 0.0)
|
| 263 |
+
p_delta = _calculate_candle_delta(c)
|
| 264 |
|
| 265 |
+
# Merge secondary exchange if present (with 1-2s tolerance guard)
|
| 266 |
+
sc = secondary_by_time.get(time_sec)
|
| 267 |
+
if not sc:
|
| 268 |
+
for dt in (1, -1, 2, -2, 30, -30):
|
| 269 |
+
if time_sec + dt in secondary_by_time:
|
| 270 |
+
sc = secondary_by_time[time_sec + dt]
|
| 271 |
+
break
|
| 272 |
+
|
| 273 |
+
s_vol = float(sc.get("volume") or 0.0) if sc else 0.0
|
| 274 |
+
s_delta = _calculate_candle_delta(sc) if sc else 0.0
|
| 275 |
+
|
| 276 |
+
total_vol = p_vol + s_vol
|
| 277 |
+
total_delta = p_delta + s_delta
|
| 278 |
+
running_cvd += total_delta
|
| 279 |
+
|
| 280 |
+
# Calculate Aggregated Open Interest in USD via LOCF continuous alignment
|
| 281 |
+
b_oi_usd = _get_locf_value(binance_oi_map, sorted_b_keys, time_sec)
|
| 282 |
+
by_oi_coins = _get_locf_value(bybit_oi_map, sorted_by_keys, time_sec)
|
| 283 |
+
by_oi_usd = (by_oi_coins * cl) if (by_oi_coins is not None and cl > 0) else None
|
| 284 |
|
| 285 |
+
tot_oi_usd = 0.0
|
| 286 |
+
if b_oi_usd is not None:
|
| 287 |
+
tot_oi_usd += b_oi_usd
|
| 288 |
+
if by_oi_usd is not None:
|
| 289 |
+
tot_oi_usd += by_oi_usd
|
| 290 |
+
|
| 291 |
+
candle_oi = round(tot_oi_usd, 2) if tot_oi_usd > 0 else None
|
| 292 |
|
| 293 |
normalized_candles.append({
|
| 294 |
"time": time_sec,
|
|
|
|
| 296 |
"high": h,
|
| 297 |
"low": l,
|
| 298 |
"close": cl,
|
| 299 |
+
"volume": round(total_vol, 4),
|
| 300 |
+
"delta": round(total_delta, 4),
|
| 301 |
"cvd": round(running_cvd, 4),
|
| 302 |
+
"open_interest": candle_oi,
|
| 303 |
})
|
| 304 |
|
| 305 |
current_price = normalized_candles[-1]["close"] if normalized_candles else 0.0
|
| 306 |
+
is_aggregated = len(exchanges_included) > 1
|
| 307 |
+
|
| 308 |
+
oi_list = [c["open_interest"] for c in normalized_candles if c.get("open_interest")]
|
| 309 |
+
latest_oi = oi_list[-1] if oi_list else None
|
| 310 |
+
first_oi = oi_list[0] if oi_list else None
|
| 311 |
+
oi_change_pct = round(((latest_oi - first_oi) / first_oi) * 100, 2) if (latest_oi and first_oi and first_oi > 0) else 0.0
|
| 312 |
|
| 313 |
return {
|
| 314 |
"symbol": clean_sym,
|
| 315 |
+
"exchange": "aggregated" if is_aggregated else resolved_exchange,
|
| 316 |
"timeframe": timeframe,
|
| 317 |
"count": len(normalized_candles),
|
| 318 |
"current_price": current_price,
|
| 319 |
+
"is_aggregated": is_aggregated,
|
| 320 |
+
"exchanges_included": exchanges_included,
|
| 321 |
+
"summary": {
|
| 322 |
+
"is_aggregated": is_aggregated,
|
| 323 |
+
"exchanges_included": exchanges_included,
|
| 324 |
+
"total_volume": round(sum(c["volume"] for c in normalized_candles), 2),
|
| 325 |
+
"total_delta": round(running_cvd, 4),
|
| 326 |
+
"latest_open_interest": latest_oi,
|
| 327 |
+
"oi_change_period_pct": oi_change_pct,
|
| 328 |
+
},
|
| 329 |
"candles": normalized_candles,
|
| 330 |
}
|
| 331 |
|
|
|
|
| 472 |
},
|
| 473 |
},
|
| 474 |
}
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
@router.get("/{symbol}/funding-history")
|
| 478 |
+
async def get_market_funding_history(
|
| 479 |
+
symbol: str,
|
| 480 |
+
request: Request,
|
| 481 |
+
limit: int = Query(default=30, ge=5, le=100),
|
| 482 |
+
):
|
| 483 |
+
"""
|
| 484 |
+
Fetch historical funding rates across Binance and Bybit for visual comparison.
|
| 485 |
+
"""
|
| 486 |
+
clean_sym = symbol.strip().upper().replace("/", "").replace("-", "")
|
| 487 |
+
binance = getattr(request.app.state, "binance", None)
|
| 488 |
+
bybit = getattr(request.app.state, "bybit", None)
|
| 489 |
+
|
| 490 |
+
tasks: dict[str, Any] = {}
|
| 491 |
+
if binance and callable(getattr(binance, "get_funding_rate_history", None)):
|
| 492 |
+
c = binance.get_funding_rate_history(clean_sym, limit=limit)
|
| 493 |
+
if inspect.isawaitable(c):
|
| 494 |
+
tasks["binance"] = c
|
| 495 |
+
if bybit and callable(getattr(bybit, "get_funding_rate_history", None)):
|
| 496 |
+
c = bybit.get_funding_rate_history(clean_sym, limit=limit)
|
| 497 |
+
if inspect.isawaitable(c):
|
| 498 |
+
tasks["bybit"] = c
|
| 499 |
+
|
| 500 |
+
results: dict[str, list] = {}
|
| 501 |
+
if tasks:
|
| 502 |
+
keys = list(tasks.keys())
|
| 503 |
+
res_list = await asyncio.gather(*tasks.values(), return_exceptions=True)
|
| 504 |
+
for k, r in zip(keys, res_list):
|
| 505 |
+
results[k] = r if not isinstance(r, Exception) and isinstance(r, list) else []
|
| 506 |
+
|
| 507 |
+
# Map timestamps to rate per exchange
|
| 508 |
+
time_map: dict[int, dict[str, float | None]] = {}
|
| 509 |
+
for item in results.get("binance", []):
|
| 510 |
+
ts = int(item.get("timestamp", 0) / 1000)
|
| 511 |
+
time_map.setdefault(ts, {})["binance"] = item.get("funding_rate")
|
| 512 |
+
|
| 513 |
+
for item in results.get("bybit", []):
|
| 514 |
+
ts = int(item.get("timestamp", 0) / 1000)
|
| 515 |
+
time_map.setdefault(ts, {})["bybit"] = item.get("funding_rate")
|
| 516 |
+
|
| 517 |
+
history = []
|
| 518 |
+
for ts in sorted(time_map.keys()):
|
| 519 |
+
rates = time_map[ts]
|
| 520 |
+
valid_rates = [v for v in rates.values() if v is not None]
|
| 521 |
+
avg_fr = sum(valid_rates) / len(valid_rates) if valid_rates else None
|
| 522 |
+
history.append({
|
| 523 |
+
"time": ts,
|
| 524 |
+
"binance": rates.get("binance"),
|
| 525 |
+
"bybit": rates.get("bybit"),
|
| 526 |
+
"avg_funding": round(avg_fr, 6) if avg_fr is not None else None,
|
| 527 |
+
})
|
| 528 |
+
|
| 529 |
+
return {
|
| 530 |
+
"symbol": clean_sym,
|
| 531 |
+
"count": len(history),
|
| 532 |
+
"history": history,
|
| 533 |
+
}
|
frontend/src/api/market.ts
CHANGED
|
@@ -9,6 +9,16 @@ export interface CandleData {
|
|
| 9 |
volume: number;
|
| 10 |
delta?: number;
|
| 11 |
cvd?: number;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
}
|
| 13 |
|
| 14 |
export interface CandlesResponse {
|
|
@@ -17,9 +27,25 @@ export interface CandlesResponse {
|
|
| 17 |
timeframe: string;
|
| 18 |
count: number;
|
| 19 |
current_price: number;
|
|
|
|
|
|
|
|
|
|
| 20 |
candles: CandleData[];
|
| 21 |
}
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
export interface ExchangeLiveStatus {
|
| 24 |
available: boolean;
|
| 25 |
mark_price: number | null;
|
|
@@ -61,4 +87,11 @@ export const marketApi = {
|
|
| 61 |
const res = await apiClient.get<MultiStreamData>(`/api/market/${symbol}/multi-stream`);
|
| 62 |
return res.data;
|
| 63 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
};
|
|
|
|
| 9 |
volume: number;
|
| 10 |
delta?: number;
|
| 11 |
cvd?: number;
|
| 12 |
+
open_interest?: number | null;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export interface CandlesSummary {
|
| 16 |
+
is_aggregated: boolean;
|
| 17 |
+
exchanges_included: string[];
|
| 18 |
+
total_volume: number;
|
| 19 |
+
total_delta: number;
|
| 20 |
+
latest_open_interest: number | null;
|
| 21 |
+
oi_change_period_pct: number;
|
| 22 |
}
|
| 23 |
|
| 24 |
export interface CandlesResponse {
|
|
|
|
| 27 |
timeframe: string;
|
| 28 |
count: number;
|
| 29 |
current_price: number;
|
| 30 |
+
is_aggregated?: boolean;
|
| 31 |
+
exchanges_included?: string[];
|
| 32 |
+
summary?: CandlesSummary;
|
| 33 |
candles: CandleData[];
|
| 34 |
}
|
| 35 |
|
| 36 |
+
export interface FundingHistoryItem {
|
| 37 |
+
time: number; // in seconds
|
| 38 |
+
binance: number | null;
|
| 39 |
+
bybit: number | null;
|
| 40 |
+
avg_funding: number | null;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export interface FundingHistoryResponse {
|
| 44 |
+
symbol: string;
|
| 45 |
+
count: number;
|
| 46 |
+
history: FundingHistoryItem[];
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
export interface ExchangeLiveStatus {
|
| 50 |
available: boolean;
|
| 51 |
mark_price: number | null;
|
|
|
|
| 87 |
const res = await apiClient.get<MultiStreamData>(`/api/market/${symbol}/multi-stream`);
|
| 88 |
return res.data;
|
| 89 |
},
|
| 90 |
+
|
| 91 |
+
getFundingHistory: async (symbol: string, limit: number = 30): Promise<FundingHistoryResponse> => {
|
| 92 |
+
const res = await apiClient.get<FundingHistoryResponse>(`/api/market/${symbol}/funding-history`, {
|
| 93 |
+
params: { limit },
|
| 94 |
+
});
|
| 95 |
+
return res.data;
|
| 96 |
+
},
|
| 97 |
};
|
frontend/src/components/chart/AggregatedOIChart.tsx
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useRef } from 'react';
|
| 2 |
+
import {
|
| 3 |
+
createChart,
|
| 4 |
+
AreaSeries,
|
| 5 |
+
LineStyle,
|
| 6 |
+
ColorType,
|
| 7 |
+
CrosshairMode,
|
| 8 |
+
IChartApi,
|
| 9 |
+
ISeriesApi,
|
| 10 |
+
} from 'lightweight-charts';
|
| 11 |
+
import type { CandleData } from '../../api/market';
|
| 12 |
+
|
| 13 |
+
interface AggregatedOIChartProps {
|
| 14 |
+
candles: CandleData[];
|
| 15 |
+
height?: number;
|
| 16 |
+
exchangesIncluded?: string[];
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
function formatUSD(val: number | null | undefined): string {
|
| 20 |
+
if (!val || isNaN(val) || val <= 0) return '$0';
|
| 21 |
+
if (val >= 1_000_000_000) return `$${(val / 1_000_000_000).toFixed(2)}B`;
|
| 22 |
+
if (val >= 1_000_000) return `$${(val / 1_000_000).toFixed(2)}M`;
|
| 23 |
+
if (val >= 1_000) return `$${(val / 1_000).toFixed(1)}K`;
|
| 24 |
+
return `$${val.toFixed(2)}`;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
export function AggregatedOIChart({
|
| 28 |
+
candles,
|
| 29 |
+
height = 190,
|
| 30 |
+
exchangesIncluded = ['binance', 'bybit'],
|
| 31 |
+
}: AggregatedOIChartProps) {
|
| 32 |
+
const containerRef = useRef<HTMLDivElement>(null);
|
| 33 |
+
const chartRef = useRef<IChartApi | null>(null);
|
| 34 |
+
const oiSeriesRef = useRef<ISeriesApi<'Area'> | null>(null);
|
| 35 |
+
const isInitializedRef = useRef<boolean>(false);
|
| 36 |
+
const prevFirstTimeRef = useRef<number | null>(null);
|
| 37 |
+
|
| 38 |
+
useEffect(() => {
|
| 39 |
+
if (!containerRef.current) return;
|
| 40 |
+
|
| 41 |
+
const chart = createChart(containerRef.current, {
|
| 42 |
+
width: containerRef.current.clientWidth,
|
| 43 |
+
height: height,
|
| 44 |
+
layout: {
|
| 45 |
+
background: { type: ColorType.Solid, color: '#090b0e' },
|
| 46 |
+
textColor: '#94a3b8',
|
| 47 |
+
fontSize: 10,
|
| 48 |
+
fontFamily: 'JetBrains Mono, ui-monospace, monospace',
|
| 49 |
+
},
|
| 50 |
+
grid: {
|
| 51 |
+
vertLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted },
|
| 52 |
+
horzLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted },
|
| 53 |
+
},
|
| 54 |
+
crosshair: {
|
| 55 |
+
mode: CrosshairMode.Normal,
|
| 56 |
+
},
|
| 57 |
+
rightPriceScale: {
|
| 58 |
+
borderColor: '#1e293b',
|
| 59 |
+
autoScale: true,
|
| 60 |
+
},
|
| 61 |
+
timeScale: {
|
| 62 |
+
borderColor: '#1e293b',
|
| 63 |
+
timeVisible: true,
|
| 64 |
+
secondsVisible: false,
|
| 65 |
+
},
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
chartRef.current = chart;
|
| 69 |
+
|
| 70 |
+
// Aggregated Open Interest Area Series
|
| 71 |
+
const oiSeries = chart.addSeries(AreaSeries, {
|
| 72 |
+
topColor: 'rgba(56, 189, 248, 0.35)',
|
| 73 |
+
bottomColor: 'rgba(56, 189, 248, 0.02)',
|
| 74 |
+
lineColor: '#38bdf8',
|
| 75 |
+
lineWidth: 2,
|
| 76 |
+
crosshairMarkerVisible: true,
|
| 77 |
+
priceFormat: {
|
| 78 |
+
type: 'custom',
|
| 79 |
+
formatter: (val: number) => formatUSD(val),
|
| 80 |
+
},
|
| 81 |
+
});
|
| 82 |
+
oiSeriesRef.current = oiSeries;
|
| 83 |
+
|
| 84 |
+
const handleResize = () => {
|
| 85 |
+
if (containerRef.current && chartRef.current) {
|
| 86 |
+
chartRef.current.applyOptions({
|
| 87 |
+
width: containerRef.current.clientWidth,
|
| 88 |
+
});
|
| 89 |
+
}
|
| 90 |
+
};
|
| 91 |
+
window.addEventListener('resize', handleResize);
|
| 92 |
+
const ro = new ResizeObserver(handleResize);
|
| 93 |
+
ro.observe(containerRef.current);
|
| 94 |
+
|
| 95 |
+
return () => {
|
| 96 |
+
window.removeEventListener('resize', handleResize);
|
| 97 |
+
ro.disconnect();
|
| 98 |
+
chart.remove();
|
| 99 |
+
chartRef.current = null;
|
| 100 |
+
oiSeriesRef.current = null;
|
| 101 |
+
};
|
| 102 |
+
}, [height]);
|
| 103 |
+
|
| 104 |
+
useEffect(() => {
|
| 105 |
+
if (!oiSeriesRef.current || !candles || candles.length === 0) {
|
| 106 |
+
return;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
const timeMap = new Map<number, CandleData>();
|
| 110 |
+
for (const c of candles) {
|
| 111 |
+
if (c && c.time && !isNaN(c.time)) {
|
| 112 |
+
timeMap.set(c.time, c);
|
| 113 |
+
}
|
| 114 |
+
}
|
| 115 |
+
const sortedUnique = Array.from(timeMap.values()).sort((a, b) => a.time - b.time);
|
| 116 |
+
if (sortedUnique.length === 0) return;
|
| 117 |
+
|
| 118 |
+
// Filter points that have non-null open interest
|
| 119 |
+
const oiData = sortedUnique
|
| 120 |
+
.filter((c) => c.open_interest !== undefined && c.open_interest !== null && !isNaN(c.open_interest) && c.open_interest > 0)
|
| 121 |
+
.map((c) => ({
|
| 122 |
+
time: c.time as any,
|
| 123 |
+
value: c.open_interest as number,
|
| 124 |
+
}));
|
| 125 |
+
|
| 126 |
+
if (oiData.length === 0) return;
|
| 127 |
+
|
| 128 |
+
const firstTime = oiData[0].time;
|
| 129 |
+
const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime;
|
| 130 |
+
const needsFullReload = !isInitializedRef.current || isFirstTimeChanged;
|
| 131 |
+
|
| 132 |
+
if (needsFullReload) {
|
| 133 |
+
prevFirstTimeRef.current = firstTime;
|
| 134 |
+
try {
|
| 135 |
+
oiSeriesRef.current.setData(oiData);
|
| 136 |
+
isInitializedRef.current = true;
|
| 137 |
+
} catch (e) {
|
| 138 |
+
// ignore
|
| 139 |
+
}
|
| 140 |
+
} else {
|
| 141 |
+
// Incremental live tick update
|
| 142 |
+
const last = oiData[oiData.length - 1];
|
| 143 |
+
try {
|
| 144 |
+
oiSeriesRef.current.update({
|
| 145 |
+
time: last.time as any,
|
| 146 |
+
value: last.value,
|
| 147 |
+
});
|
| 148 |
+
} catch (e) {
|
| 149 |
+
// ignore
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
}, [candles]);
|
| 153 |
+
|
| 154 |
+
// Summary statistics
|
| 155 |
+
const oiValues = candles
|
| 156 |
+
.map((c) => c.open_interest)
|
| 157 |
+
.filter((v): v is number => typeof v === 'number' && v > 0);
|
| 158 |
+
|
| 159 |
+
const latestOI = oiValues[oiValues.length - 1] ?? 0;
|
| 160 |
+
const firstOI = oiValues[0] ?? 0;
|
| 161 |
+
const changePct = firstOI > 0 ? ((latestOI - firstOI) / firstOI) * 100 : 0;
|
| 162 |
+
const isAccumulating = changePct >= 0;
|
| 163 |
+
|
| 164 |
+
return (
|
| 165 |
+
<div className="w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col">
|
| 166 |
+
<div className="px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono">
|
| 167 |
+
<div className="flex items-center gap-2">
|
| 168 |
+
<span className="w-2 h-2 rounded-full bg-accent-blue animate-pulse" />
|
| 169 |
+
<span className="font-semibold text-text-primary text-[11px] tracking-wide">
|
| 170 |
+
Aggregated Open Interest (USD Notional)
|
| 171 |
+
</span>
|
| 172 |
+
<span className="text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase">
|
| 173 |
+
{exchangesIncluded.join(' + ')}
|
| 174 |
+
</span>
|
| 175 |
+
</div>
|
| 176 |
+
<div className="flex items-center gap-3 text-[11px]">
|
| 177 |
+
<span className="text-text-muted">Total OI:</span>
|
| 178 |
+
<span className="font-bold text-accent-blue">
|
| 179 |
+
{formatUSD(latestOI)}
|
| 180 |
+
</span>
|
| 181 |
+
{oiValues.length > 1 && (
|
| 182 |
+
<span
|
| 183 |
+
className={`font-semibold px-1.5 py-0.2 rounded text-[10px] ${
|
| 184 |
+
isAccumulating ? 'bg-emerald-500/10 text-emerald-400' : 'bg-rose-500/10 text-rose-400'
|
| 185 |
+
}`}
|
| 186 |
+
>
|
| 187 |
+
{isAccumulating ? `+${changePct.toFixed(2)}%` : `${changePct.toFixed(2)}%`}
|
| 188 |
+
</span>
|
| 189 |
+
)}
|
| 190 |
+
</div>
|
| 191 |
+
</div>
|
| 192 |
+
<div ref={containerRef} className="w-full flex-1 min-h-[170px]" />
|
| 193 |
+
</div>
|
| 194 |
+
);
|
| 195 |
+
}
|
frontend/src/components/chart/FundingRateHistoryChart.tsx
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useEffect, useRef } from 'react';
|
| 2 |
+
import { useQuery } from '@tanstack/react-query';
|
| 3 |
+
import {
|
| 4 |
+
createChart,
|
| 5 |
+
HistogramSeries,
|
| 6 |
+
LineStyle,
|
| 7 |
+
ColorType,
|
| 8 |
+
CrosshairMode,
|
| 9 |
+
IChartApi,
|
| 10 |
+
ISeriesApi,
|
| 11 |
+
} from 'lightweight-charts';
|
| 12 |
+
import { marketApi } from '../../api/market';
|
| 13 |
+
|
| 14 |
+
interface FundingRateHistoryChartProps {
|
| 15 |
+
symbol: string;
|
| 16 |
+
height?: number;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export function FundingRateHistoryChart({ symbol, height = 190 }: FundingRateHistoryChartProps) {
|
| 20 |
+
const containerRef = useRef<HTMLDivElement>(null);
|
| 21 |
+
const chartRef = useRef<IChartApi | null>(null);
|
| 22 |
+
const seriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
|
| 23 |
+
|
| 24 |
+
const { data: fundingData } = useQuery({
|
| 25 |
+
queryKey: ['fundingHistory', symbol],
|
| 26 |
+
queryFn: () => marketApi.getFundingHistory(symbol, 40),
|
| 27 |
+
staleTime: 60_000,
|
| 28 |
+
refetchInterval: 60_000,
|
| 29 |
+
});
|
| 30 |
+
|
| 31 |
+
useEffect(() => {
|
| 32 |
+
if (!containerRef.current) return;
|
| 33 |
+
|
| 34 |
+
const chart = createChart(containerRef.current, {
|
| 35 |
+
width: containerRef.current.clientWidth,
|
| 36 |
+
height: height,
|
| 37 |
+
layout: {
|
| 38 |
+
background: { type: ColorType.Solid, color: '#090b0e' },
|
| 39 |
+
textColor: '#94a3b8',
|
| 40 |
+
fontSize: 10,
|
| 41 |
+
fontFamily: 'JetBrains Mono, ui-monospace, monospace',
|
| 42 |
+
},
|
| 43 |
+
grid: {
|
| 44 |
+
vertLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted },
|
| 45 |
+
horzLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted },
|
| 46 |
+
},
|
| 47 |
+
crosshair: {
|
| 48 |
+
mode: CrosshairMode.Normal,
|
| 49 |
+
},
|
| 50 |
+
rightPriceScale: {
|
| 51 |
+
borderColor: '#1e293b',
|
| 52 |
+
autoScale: true,
|
| 53 |
+
},
|
| 54 |
+
timeScale: {
|
| 55 |
+
borderColor: '#1e293b',
|
| 56 |
+
timeVisible: true,
|
| 57 |
+
secondsVisible: false,
|
| 58 |
+
},
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
chartRef.current = chart;
|
| 62 |
+
|
| 63 |
+
const series = chart.addSeries(HistogramSeries, {
|
| 64 |
+
priceFormat: {
|
| 65 |
+
type: 'custom',
|
| 66 |
+
formatter: (val: number) => `${(val * 100).toFixed(4)}%`,
|
| 67 |
+
},
|
| 68 |
+
});
|
| 69 |
+
seriesRef.current = series;
|
| 70 |
+
|
| 71 |
+
const handleResize = () => {
|
| 72 |
+
if (containerRef.current && chartRef.current) {
|
| 73 |
+
chartRef.current.applyOptions({
|
| 74 |
+
width: containerRef.current.clientWidth,
|
| 75 |
+
});
|
| 76 |
+
}
|
| 77 |
+
};
|
| 78 |
+
window.addEventListener('resize', handleResize);
|
| 79 |
+
const ro = new ResizeObserver(handleResize);
|
| 80 |
+
ro.observe(containerRef.current);
|
| 81 |
+
|
| 82 |
+
return () => {
|
| 83 |
+
window.removeEventListener('resize', handleResize);
|
| 84 |
+
ro.disconnect();
|
| 85 |
+
chart.remove();
|
| 86 |
+
chartRef.current = null;
|
| 87 |
+
seriesRef.current = null;
|
| 88 |
+
};
|
| 89 |
+
}, [height]);
|
| 90 |
+
|
| 91 |
+
useEffect(() => {
|
| 92 |
+
if (!seriesRef.current || !fundingData?.history || fundingData.history.length === 0) {
|
| 93 |
+
return;
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
const items = fundingData.history
|
| 97 |
+
.filter((h) => h.avg_funding !== null && !isNaN(h.avg_funding))
|
| 98 |
+
.map((h) => {
|
| 99 |
+
const val = h.avg_funding as number;
|
| 100 |
+
return {
|
| 101 |
+
time: h.time as any,
|
| 102 |
+
value: val,
|
| 103 |
+
color:
|
| 104 |
+
val >= 0.0001
|
| 105 |
+
? 'rgba(239, 68, 68, 0.75)' // Extreme positive (crowded long)
|
| 106 |
+
: val >= 0
|
| 107 |
+
? 'rgba(16, 185, 129, 0.65)' // Healthy positive
|
| 108 |
+
: 'rgba(56, 189, 248, 0.75)', // Negative (shorts paying longs)
|
| 109 |
+
};
|
| 110 |
+
});
|
| 111 |
+
|
| 112 |
+
try {
|
| 113 |
+
seriesRef.current.setData(items);
|
| 114 |
+
} catch (e) {
|
| 115 |
+
// ignore
|
| 116 |
+
}
|
| 117 |
+
}, [fundingData]);
|
| 118 |
+
|
| 119 |
+
const latestHistory = fundingData?.history?.[fundingData.history.length - 1];
|
| 120 |
+
const latestRate = latestHistory?.avg_funding ?? 0;
|
| 121 |
+
const apr = latestRate * 3 * 365 * 100;
|
| 122 |
+
|
| 123 |
+
return (
|
| 124 |
+
<div className="w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col">
|
| 125 |
+
<div className="px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono">
|
| 126 |
+
<div className="flex items-center gap-2">
|
| 127 |
+
<span className="w-2 h-2 rounded-full bg-purple-400" />
|
| 128 |
+
<span className="font-semibold text-text-primary text-[11px] tracking-wide">
|
| 129 |
+
Multi-Exchange Funding Rate History (8h Interval)
|
| 130 |
+
</span>
|
| 131 |
+
<span className="text-[10px] px-1.5 py-0.5 rounded bg-bg-elevated text-text-muted border border-border/50 uppercase">
|
| 132 |
+
Binance + Bybit
|
| 133 |
+
</span>
|
| 134 |
+
</div>
|
| 135 |
+
<div className="flex items-center gap-3 text-[11px]">
|
| 136 |
+
<span className="text-text-muted">Current Rate:</span>
|
| 137 |
+
<span
|
| 138 |
+
className={`font-bold ${
|
| 139 |
+
latestRate > 0 ? 'text-emerald-400' : latestRate < 0 ? 'text-sky-400' : 'text-text-primary'
|
| 140 |
+
}`}
|
| 141 |
+
>
|
| 142 |
+
{(latestRate * 100).toFixed(4)}%
|
| 143 |
+
</span>
|
| 144 |
+
<span className="text-text-muted text-[10px]">
|
| 145 |
+
(APR: {apr > 0 ? `+${apr.toFixed(1)}%` : `${apr.toFixed(1)}%`})
|
| 146 |
+
</span>
|
| 147 |
+
</div>
|
| 148 |
+
</div>
|
| 149 |
+
<div ref={containerRef} className="w-full flex-1 min-h-[170px]" />
|
| 150 |
+
</div>
|
| 151 |
+
);
|
| 152 |
+
}
|
frontend/src/hooks/useChartData.ts
CHANGED
|
@@ -192,6 +192,9 @@ export function useChartData({
|
|
| 192 |
candles,
|
| 193 |
currentPrice,
|
| 194 |
multiStream,
|
|
|
|
|
|
|
|
|
|
| 195 |
isLoading: isCandlesLoading,
|
| 196 |
isWsConnected,
|
| 197 |
refetchCandles,
|
|
|
|
| 192 |
candles,
|
| 193 |
currentPrice,
|
| 194 |
multiStream,
|
| 195 |
+
isAggregated: initialCandlesData?.is_aggregated ?? false,
|
| 196 |
+
exchangesIncluded: initialCandlesData?.exchanges_included ?? ['binance'],
|
| 197 |
+
summary: initialCandlesData?.summary,
|
| 198 |
isLoading: isCandlesLoading,
|
| 199 |
isWsConnected,
|
| 200 |
refetchCandles,
|
frontend/src/pages/LiveChartTerminal.tsx
CHANGED
|
@@ -10,12 +10,16 @@ import {
|
|
| 10 |
BarChart2,
|
| 11 |
SlidersHorizontal,
|
| 12 |
Flame,
|
|
|
|
|
|
|
| 13 |
} from 'lucide-react';
|
| 14 |
import { usePairs } from '../hooks/usePairs';
|
| 15 |
import { useSignals } from '../hooks/useSignals';
|
| 16 |
import { useChartData } from '../hooks/useChartData';
|
| 17 |
import { TradingViewChart } from '../components/chart/TradingViewChart';
|
| 18 |
import { CVDVolumeChart } from '../components/chart/CVDVolumeChart';
|
|
|
|
|
|
|
| 19 |
import { MultiExchangeLiveBoard } from '../components/chart/MultiExchangeLiveBoard';
|
| 20 |
import { SignalBadge } from '../components/signals/SignalBadge';
|
| 21 |
import { ExecutionModal } from '../components/execution/ExecutionModal';
|
|
@@ -35,7 +39,7 @@ const TIMEFRAMES = [
|
|
| 35 |
];
|
| 36 |
|
| 37 |
const EXCHANGES = [
|
| 38 |
-
{ id: 'auto', label: '
|
| 39 |
{ id: 'binance', label: 'Binance' },
|
| 40 |
{ id: 'bybit', label: 'Bybit' },
|
| 41 |
{ id: 'okx', label: 'OKX' },
|
|
@@ -59,7 +63,8 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
|
|
| 59 |
const [exchange, setExchange] = useState<string>('auto');
|
| 60 |
const [showLevels, setShowLevels] = useState<boolean>(true);
|
| 61 |
const [showMagnets, setShowMagnets] = useState<boolean>(true);
|
| 62 |
-
const [
|
|
|
|
| 63 |
const [pairSearch, setPairSearch] = useState<string>('');
|
| 64 |
const [isPairDropdownOpen, setIsPairDropdownOpen] = useState<boolean>(false);
|
| 65 |
const [isExecutionModalOpen, setIsExecutionModalOpen] = useState<boolean>(false);
|
|
@@ -79,6 +84,8 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
|
|
| 79 |
candles,
|
| 80 |
currentPrice,
|
| 81 |
multiStream,
|
|
|
|
|
|
|
| 82 |
isLoading: isCandlesLoading,
|
| 83 |
isWsConnected,
|
| 84 |
refetchCandles,
|
|
@@ -273,19 +280,19 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
|
|
| 273 |
<span className="hidden md:inline">Magnets</span>
|
| 274 |
</button>
|
| 275 |
|
| 276 |
-
{/* Toggle
|
| 277 |
<button
|
| 278 |
type="button"
|
| 279 |
-
onClick={() =>
|
| 280 |
-
title="Toggle
|
| 281 |
className={`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${
|
| 282 |
-
|
| 283 |
? 'bg-amber-500/15 border-amber-500/40 text-amber-300 font-semibold'
|
| 284 |
: 'bg-bg-elevated border-border text-text-muted hover:text-text-secondary'
|
| 285 |
}`}
|
| 286 |
>
|
| 287 |
<BarChart2 size={13} />
|
| 288 |
-
<span className="hidden md:inline">
|
| 289 |
</button>
|
| 290 |
|
| 291 |
{/* Refresh */}
|
|
@@ -327,19 +334,83 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
|
|
| 327 |
{/* Left: Candlestick & CVD Chart */}
|
| 328 |
<div className="flex-1 flex flex-col p-3 overflow-y-auto gap-3">
|
| 329 |
{/* Main Candlestick Chart */}
|
| 330 |
-
<div className="flex-1 min-h-[
|
| 331 |
<TradingViewChart
|
| 332 |
candles={candles}
|
| 333 |
symbol={selectedSymbol}
|
| 334 |
overlays={overlays}
|
| 335 |
-
height={
|
| 336 |
/>
|
| 337 |
</div>
|
| 338 |
|
| 339 |
-
{/* CVD
|
| 340 |
-
{
|
| 341 |
-
<div className="
|
| 342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
</div>
|
| 344 |
)}
|
| 345 |
</div>
|
|
|
|
| 10 |
BarChart2,
|
| 11 |
SlidersHorizontal,
|
| 12 |
Flame,
|
| 13 |
+
TrendingUp,
|
| 14 |
+
Percent,
|
| 15 |
} from 'lucide-react';
|
| 16 |
import { usePairs } from '../hooks/usePairs';
|
| 17 |
import { useSignals } from '../hooks/useSignals';
|
| 18 |
import { useChartData } from '../hooks/useChartData';
|
| 19 |
import { TradingViewChart } from '../components/chart/TradingViewChart';
|
| 20 |
import { CVDVolumeChart } from '../components/chart/CVDVolumeChart';
|
| 21 |
+
import { AggregatedOIChart } from '../components/chart/AggregatedOIChart';
|
| 22 |
+
import { FundingRateHistoryChart } from '../components/chart/FundingRateHistoryChart';
|
| 23 |
import { MultiExchangeLiveBoard } from '../components/chart/MultiExchangeLiveBoard';
|
| 24 |
import { SignalBadge } from '../components/signals/SignalBadge';
|
| 25 |
import { ExecutionModal } from '../components/execution/ExecutionModal';
|
|
|
|
| 39 |
];
|
| 40 |
|
| 41 |
const EXCHANGES = [
|
| 42 |
+
{ id: 'auto', label: '⚡ Aggregated (All)' },
|
| 43 |
{ id: 'binance', label: 'Binance' },
|
| 44 |
{ id: 'bybit', label: 'Bybit' },
|
| 45 |
{ id: 'okx', label: 'OKX' },
|
|
|
|
| 63 |
const [exchange, setExchange] = useState<string>('auto');
|
| 64 |
const [showLevels, setShowLevels] = useState<boolean>(true);
|
| 65 |
const [showMagnets, setShowMagnets] = useState<boolean>(true);
|
| 66 |
+
const [showSubChart, setShowSubChart] = useState<boolean>(true);
|
| 67 |
+
const [subChartTab, setSubChartTab] = useState<'cvd' | 'oi' | 'funding'>('cvd');
|
| 68 |
const [pairSearch, setPairSearch] = useState<string>('');
|
| 69 |
const [isPairDropdownOpen, setIsPairDropdownOpen] = useState<boolean>(false);
|
| 70 |
const [isExecutionModalOpen, setIsExecutionModalOpen] = useState<boolean>(false);
|
|
|
|
| 84 |
candles,
|
| 85 |
currentPrice,
|
| 86 |
multiStream,
|
| 87 |
+
isAggregated,
|
| 88 |
+
exchangesIncluded,
|
| 89 |
isLoading: isCandlesLoading,
|
| 90 |
isWsConnected,
|
| 91 |
refetchCandles,
|
|
|
|
| 280 |
<span className="hidden md:inline">Magnets</span>
|
| 281 |
</button>
|
| 282 |
|
| 283 |
+
{/* Toggle Sub-Chart Analytics */}
|
| 284 |
<button
|
| 285 |
type="button"
|
| 286 |
+
onClick={() => setShowSubChart(!showSubChart)}
|
| 287 |
+
title="Toggle Sub-Chart Analytics (CVD, Aggregated OI, Funding History)"
|
| 288 |
className={`px-2.5 py-1.5 rounded-xl border text-xs font-mono flex items-center gap-1.5 transition-all active:scale-95 ${
|
| 289 |
+
showSubChart
|
| 290 |
? 'bg-amber-500/15 border-amber-500/40 text-amber-300 font-semibold'
|
| 291 |
: 'bg-bg-elevated border-border text-text-muted hover:text-text-secondary'
|
| 292 |
}`}
|
| 293 |
>
|
| 294 |
<BarChart2 size={13} />
|
| 295 |
+
<span className="hidden md:inline">Analytics</span>
|
| 296 |
</button>
|
| 297 |
|
| 298 |
{/* Refresh */}
|
|
|
|
| 334 |
{/* Left: Candlestick & CVD Chart */}
|
| 335 |
<div className="flex-1 flex flex-col p-3 overflow-y-auto gap-3">
|
| 336 |
{/* Main Candlestick Chart */}
|
| 337 |
+
<div className="flex-1 min-h-[400px] flex flex-col">
|
| 338 |
<TradingViewChart
|
| 339 |
candles={candles}
|
| 340 |
symbol={selectedSymbol}
|
| 341 |
overlays={overlays}
|
| 342 |
+
height={showSubChart ? 400 : 580}
|
| 343 |
/>
|
| 344 |
</div>
|
| 345 |
|
| 346 |
+
{/* Sub-Chart Analytics (CVD, Aggregated Open Interest, Funding History) */}
|
| 347 |
+
{showSubChart && (
|
| 348 |
+
<div className="flex flex-col gap-2 shrink-0">
|
| 349 |
+
{/* Indicator Switcher Navigation Bar */}
|
| 350 |
+
<div className="flex items-center justify-between px-1">
|
| 351 |
+
<div className="flex items-center gap-1 bg-bg-card p-1 rounded-xl border border-border/80 shadow-inner">
|
| 352 |
+
<button
|
| 353 |
+
type="button"
|
| 354 |
+
onClick={() => setSubChartTab('cvd')}
|
| 355 |
+
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${
|
| 356 |
+
subChartTab === 'cvd'
|
| 357 |
+
? 'bg-amber-500/15 text-amber-300 border border-amber-500/40 shadow-sm'
|
| 358 |
+
: 'text-text-muted hover:text-text-secondary'
|
| 359 |
+
}`}
|
| 360 |
+
>
|
| 361 |
+
<BarChart2 size={12} />
|
| 362 |
+
<span>Aggregated CVD</span>
|
| 363 |
+
</button>
|
| 364 |
+
|
| 365 |
+
<button
|
| 366 |
+
type="button"
|
| 367 |
+
onClick={() => setSubChartTab('oi')}
|
| 368 |
+
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${
|
| 369 |
+
subChartTab === 'oi'
|
| 370 |
+
? 'bg-sky-500/15 text-sky-300 border border-sky-500/40 shadow-sm'
|
| 371 |
+
: 'text-text-muted hover:text-text-secondary'
|
| 372 |
+
}`}
|
| 373 |
+
>
|
| 374 |
+
<TrendingUp size={12} />
|
| 375 |
+
<span>Aggregated OI ($)</span>
|
| 376 |
+
</button>
|
| 377 |
+
|
| 378 |
+
<button
|
| 379 |
+
type="button"
|
| 380 |
+
onClick={() => setSubChartTab('funding')}
|
| 381 |
+
className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-xs font-mono font-semibold transition-all ${
|
| 382 |
+
subChartTab === 'funding'
|
| 383 |
+
? 'bg-purple-500/15 text-purple-300 border border-purple-500/40 shadow-sm'
|
| 384 |
+
: 'text-text-muted hover:text-text-secondary'
|
| 385 |
+
}`}
|
| 386 |
+
>
|
| 387 |
+
<Percent size={12} />
|
| 388 |
+
<span>Funding History</span>
|
| 389 |
+
</button>
|
| 390 |
+
</div>
|
| 391 |
+
|
| 392 |
+
{isAggregated && (
|
| 393 |
+
<div className="hidden sm:flex items-center gap-1.5 text-[10px] font-mono text-text-muted px-2.5 py-1 rounded-xl bg-bg-card border border-border/70">
|
| 394 |
+
<span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
|
| 395 |
+
<span>Aggregated: {exchangesIncluded.join(' + ').toUpperCase()}</span>
|
| 396 |
+
</div>
|
| 397 |
+
)}
|
| 398 |
+
</div>
|
| 399 |
+
|
| 400 |
+
{/* Active Indicator Component */}
|
| 401 |
+
<div className="h-[185px]">
|
| 402 |
+
{subChartTab === 'cvd' && <CVDVolumeChart candles={candles} height={185} />}
|
| 403 |
+
{subChartTab === 'oi' && (
|
| 404 |
+
<AggregatedOIChart
|
| 405 |
+
candles={candles}
|
| 406 |
+
height={185}
|
| 407 |
+
exchangesIncluded={exchangesIncluded}
|
| 408 |
+
/>
|
| 409 |
+
)}
|
| 410 |
+
{subChartTab === 'funding' && (
|
| 411 |
+
<FundingRateHistoryChart symbol={selectedSymbol} height={185} />
|
| 412 |
+
)}
|
| 413 |
+
</div>
|
| 414 |
</div>
|
| 415 |
)}
|
| 416 |
</div>
|
tests/test_chart.py
CHANGED
|
@@ -142,3 +142,64 @@ def test_ws_chart_handshake(test_client):
|
|
| 142 |
pong_msg = ws.receive_json()
|
| 143 |
# Either pong or first tick
|
| 144 |
assert pong_msg["type"] in ("pong", "chart_tick")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
pong_msg = ws.receive_json()
|
| 143 |
# Either pong or first tick
|
| 144 |
assert pong_msg["type"] in ("pong", "chart_tick")
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_get_market_candles_aggregated(test_client):
|
| 148 |
+
# Mock Binance + Bybit returning overlapping candles
|
| 149 |
+
mock_binance = MagicMock()
|
| 150 |
+
mock_binance.get_ohlcv = AsyncMock(return_value=[
|
| 151 |
+
{"timestamp": 1730000000000, "open": 68000.0, "high": 68500.0, "low": 67900.0, "close": 68400.0, "volume": 100.0, "taker_buy_volume": 60.0},
|
| 152 |
+
])
|
| 153 |
+
mock_binance.get_oi_history = AsyncMock(return_value=[
|
| 154 |
+
{"timestamp": 1730000000000, "open_interest": 500.0, "open_interest_usd": 34000000.0},
|
| 155 |
+
])
|
| 156 |
+
|
| 157 |
+
mock_bybit = MagicMock()
|
| 158 |
+
mock_bybit.get_ohlcv = AsyncMock(return_value=[
|
| 159 |
+
{"timestamp": 1730000000000, "open": 68002.0, "high": 68501.0, "low": 67905.0, "close": 68401.0, "volume": 80.0, "taker_buy_volume": None},
|
| 160 |
+
])
|
| 161 |
+
mock_bybit.get_oi_history = AsyncMock(return_value=[
|
| 162 |
+
{"timestamp": 1730000000000, "open_interest": 300.0},
|
| 163 |
+
])
|
| 164 |
+
|
| 165 |
+
app.state.binance = mock_binance
|
| 166 |
+
app.state.bybit = mock_bybit
|
| 167 |
+
|
| 168 |
+
response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m")
|
| 169 |
+
assert response.status_code == 200
|
| 170 |
+
data = response.json()
|
| 171 |
+
assert data["is_aggregated"] is True
|
| 172 |
+
assert data["exchange"] == "aggregated"
|
| 173 |
+
assert "binance" in data["exchanges_included"]
|
| 174 |
+
assert "bybit" in data["exchanges_included"]
|
| 175 |
+
|
| 176 |
+
c0 = data["candles"][0]
|
| 177 |
+
# Binance vol (100) + Bybit vol (80) = 180
|
| 178 |
+
assert c0["volume"] == 180.0
|
| 179 |
+
# OI should be Binance ($34M) + Bybit (300 BTC * 68400 = $20.52M) = ~$54.52M
|
| 180 |
+
assert c0["open_interest"] is not None
|
| 181 |
+
assert c0["open_interest"] > 50000000.0
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_get_market_funding_history(test_client):
|
| 185 |
+
mock_binance = MagicMock()
|
| 186 |
+
mock_binance.get_funding_rate_history = AsyncMock(return_value=[
|
| 187 |
+
{"timestamp": 1730000000000, "funding_rate": 0.0001, "mark_price": 68400.0},
|
| 188 |
+
])
|
| 189 |
+
mock_bybit = MagicMock()
|
| 190 |
+
mock_bybit.get_funding_rate_history = AsyncMock(return_value=[
|
| 191 |
+
{"timestamp": 1730000000000, "funding_rate": 0.00012},
|
| 192 |
+
])
|
| 193 |
+
|
| 194 |
+
app.state.binance = mock_binance
|
| 195 |
+
app.state.bybit = mock_bybit
|
| 196 |
+
|
| 197 |
+
response = test_client.get("/api/market/BTCUSDT/funding-history")
|
| 198 |
+
assert response.status_code == 200
|
| 199 |
+
data = response.json()
|
| 200 |
+
assert data["symbol"] == "BTCUSDT"
|
| 201 |
+
assert len(data["history"]) >= 1
|
| 202 |
+
h0 = data["history"][0]
|
| 203 |
+
assert h0["binance"] == 0.0001
|
| 204 |
+
assert h0["bybit"] == 0.00012
|
| 205 |
+
assert h0["avg_funding"] == 0.00011
|