Naufal Arhab commited on
Commit
c08e4cd
·
1 Parent(s): bf49534

feat(chart): aggregate candles, volume, and CVD across 4 exchanges (Binance + Bybit + OKX + Bitget)

Browse files
Files changed (2) hide show
  1. backend/routers/market.py +50 -47
  2. tests/test_chart.py +47 -0
backend/routers/market.py CHANGED
@@ -94,14 +94,14 @@ async def get_market_candles(
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)
@@ -121,6 +121,16 @@ async def get_market_candles(
121
  if inspect.isawaitable(oi):
122
  tasks["bybit_oi"] = oi
123
 
 
 
 
 
 
 
 
 
 
 
124
  results: dict[str, Any] = {}
125
  if tasks:
126
  keys = list(tasks.keys())
@@ -128,35 +138,33 @@ async def get_market_candles(
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
@@ -199,13 +207,6 @@ async def get_market_candles(
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:
@@ -262,19 +263,21 @@ async def get_market_candles(
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
 
94
  is_aggregated_mode = req_exch in ("", "auto", "aggregated")
95
 
96
  raw_primary_candles: list[dict] = []
 
97
  raw_binance_oi: list[dict] = []
98
  raw_bybit_oi: list[dict] = []
99
  resolved_exchange = "unknown"
100
  exchanges_included: list[str] = []
101
+ aux_exchange_maps: dict[str, dict[int, dict]] = {}
102
 
103
  if is_aggregated_mode:
104
+ # 1. Fetch candles & OI across all supported exchanges concurrently (Binance + Bybit + OKX + Bitget)
105
  tasks = {}
106
  if binance and callable(getattr(binance, "get_ohlcv", None)):
107
  c = binance.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
 
121
  if inspect.isawaitable(oi):
122
  tasks["bybit_oi"] = oi
123
 
124
+ if okx and callable(getattr(okx, "get_ohlcv", None)):
125
+ c = okx.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
126
+ if inspect.isawaitable(c):
127
+ tasks["okx_candles"] = c
128
+
129
+ if bitget and callable(getattr(bitget, "get_ohlcv", None)):
130
+ c = bitget.get_ohlcv(clean_sym, timeframe=timeframe, limit=limit)
131
+ if inspect.isawaitable(c):
132
+ tasks["bitget_candles"] = c
133
+
134
  results: dict[str, Any] = {}
135
  if tasks:
136
  keys = list(tasks.keys())
 
138
  for k, r in zip(keys, res_list):
139
  results[k] = r if not isinstance(r, Exception) and isinstance(r, list) else []
140
 
 
 
141
  raw_binance_oi = results.get("binance_oi", [])
142
  raw_bybit_oi = results.get("bybit_oi", [])
143
 
144
+ # Priority resolution for benchmark OHLC price candle
145
+ candidate_exchanges = [
146
+ ("binance", results.get("binance_candles", [])),
147
+ ("bybit", results.get("bybit_candles", [])),
148
+ ("okx", results.get("okx_candles", [])),
149
+ ("bitget", results.get("bitget_candles", [])),
150
+ ]
151
+
152
+ primary_name = None
153
+ for ex_name, c_list in candidate_exchanges:
154
+ if c_list and len(c_list) > 0 and not primary_name:
155
+ primary_name = ex_name
156
+ raw_primary_candles = c_list
157
+ resolved_exchange = ex_name
158
+ exchanges_included.append(ex_name)
159
+ elif c_list and len(c_list) > 0:
160
+ # Auxiliary exchange for true aggregated volume & CVD
161
+ exchanges_included.append(ex_name)
162
+ m = {}
163
+ for item in c_list:
164
+ s_ts = item.get("timestamp", 0)
165
+ s_sec = int(s_ts / 1000) if s_ts > 100_000_000_000 else int(s_ts)
166
+ m[s_sec] = item
167
+ aux_exchange_maps[ex_name] = m
168
  else:
169
  # Explicit single exchange mode (e.g. ?exchange=bybit or ?exchange=binance)
170
  client = None
 
207
  # Sort candles chronologically by timestamp
208
  raw_primary_candles.sort(key=lambda c: c.get("timestamp", 0))
209
 
 
 
 
 
 
 
 
210
  # Index OI data by time_sec
211
  binance_oi_map: dict[int, float] = {}
212
  for item in raw_binance_oi:
 
263
  p_vol = float(c.get("volume") or 0.0)
264
  p_delta = _calculate_candle_delta(c)
265
 
266
+ total_vol = p_vol
267
+ total_delta = p_delta
268
+
269
+ # Merge all auxiliary exchanges (Bybit, OKX, Bitget) into true aggregated volume & CVD
270
+ for ex_name, ex_map in aux_exchange_maps.items():
271
+ aux_c = ex_map.get(time_sec)
272
+ if not aux_c:
273
+ for dt in (1, -1, 2, -2, 30, -30, 60, -60):
274
+ if time_sec + dt in ex_map:
275
+ aux_c = ex_map[time_sec + dt]
276
+ break
277
+ if aux_c:
278
+ total_vol += float(aux_c.get("volume") or 0.0)
279
+ total_delta += _calculate_candle_delta(aux_c)
280
 
 
 
281
  running_cvd += total_delta
282
 
283
  # Calculate Aggregated Open Interest in USD via LOCF continuous alignment
tests/test_chart.py CHANGED
@@ -181,6 +181,53 @@ def test_get_market_candles_aggregated(test_client):
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=[
 
181
  assert c0["open_interest"] > 50000000.0
182
 
183
 
184
+ def test_get_market_candles_4_exchanges_aggregated(test_client):
185
+ # Mock Binance + Bybit + OKX + Bitget returning overlapping candles
186
+ mock_binance = MagicMock()
187
+ mock_binance.get_ohlcv = AsyncMock(return_value=[
188
+ {"timestamp": 1730000000000, "open": 68000.0, "high": 68500.0, "low": 67900.0, "close": 68400.0, "volume": 100.0, "taker_buy_volume": 60.0},
189
+ ])
190
+ mock_binance.get_oi_history = AsyncMock(return_value=[
191
+ {"timestamp": 1730000000000, "open_interest": 500.0, "open_interest_usd": 34000000.0},
192
+ ])
193
+
194
+ mock_bybit = MagicMock()
195
+ mock_bybit.get_ohlcv = AsyncMock(return_value=[
196
+ {"timestamp": 1730000000000, "open": 68002.0, "high": 68501.0, "low": 67905.0, "close": 68401.0, "volume": 80.0, "taker_buy_volume": None},
197
+ ])
198
+ mock_bybit.get_oi_history = AsyncMock(return_value=[
199
+ {"timestamp": 1730000000000, "open_interest": 300.0},
200
+ ])
201
+
202
+ mock_okx = MagicMock()
203
+ mock_okx.get_ohlcv = AsyncMock(return_value=[
204
+ {"timestamp": 1730000000000, "open": 68001.0, "high": 68502.0, "low": 67902.0, "close": 68400.5, "volume": 50.0},
205
+ ])
206
+
207
+ mock_bitget = MagicMock()
208
+ mock_bitget.get_ohlcv = AsyncMock(return_value=[
209
+ {"timestamp": 1730000000000, "open": 68000.5, "high": 68500.5, "low": 67901.0, "close": 68400.0, "volume": 30.0},
210
+ ])
211
+
212
+ app.state.binance = mock_binance
213
+ app.state.bybit = mock_bybit
214
+ app.state.okx = mock_okx
215
+ app.state.bitget = mock_bitget
216
+
217
+ response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m")
218
+ assert response.status_code == 200
219
+ data = response.json()
220
+ assert data["is_aggregated"] is True
221
+ assert "binance" in data["exchanges_included"]
222
+ assert "bybit" in data["exchanges_included"]
223
+ assert "okx" in data["exchanges_included"]
224
+ assert "bitget" in data["exchanges_included"]
225
+
226
+ c0 = data["candles"][0]
227
+ # Sum: Binance (100) + Bybit (80) + OKX (50) + Bitget (30) = 260
228
+ assert c0["volume"] == 260.0
229
+
230
+
231
  def test_get_market_funding_history(test_client):
232
  mock_binance = MagicMock()
233
  mock_binance.get_funding_rate_history = AsyncMock(return_value=[