Perps-Terminal / tests /test_chart.py
Naufal Arhab
feat(chart): aggregate candles, volume, and CVD across 4 exchanges (Binance + Bybit + OKX + Bitget)
c08e4cd
Raw History Blame Contribute Delete
9.55 kB
"""
Test Suite for Real-Time Chart & Multi-Exchange Endpoints
"""
import sys
import os
import pytest
from unittest.mock import AsyncMock, MagicMock
from fastapi.testclient import TestClient
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
from main import app
@pytest.fixture
def test_client():
# Set up mock exchange clients on app.state
mock_binance = MagicMock()
mock_binance.get_ohlcv = AsyncMock(return_value=[
{
"timestamp": 1730000000000,
"open": 68000.0,
"high": 68500.0,
"low": 67900.0,
"close": 68400.0,
"volume": 100.0,
"taker_buy_volume": 60.0,
},
{
"timestamp": 1730000900000,
"open": 68400.0,
"high": 68700.0,
"low": 68300.0,
"close": 68650.0,
"volume": 120.0,
"taker_buy_volume": 70.0,
},
])
mock_binance.get_mark_price = AsyncMock(return_value={"mark_price": 68650.0, "index_price": 68640.0})
mock_binance.get_funding_rate = AsyncMock(return_value={"funding_rate": 0.0001})
mock_binance.get_open_interest = AsyncMock(return_value={"open_interest": 50000.0})
mock_bybit = MagicMock()
mock_bybit.get_ohlcv = AsyncMock(return_value=[])
mock_bybit.get_mark_price = AsyncMock(return_value={"mark_price": 68648.0, "index_price": 68640.0})
mock_bybit.get_funding_rate = AsyncMock(return_value={"funding_rate": 0.00012})
mock_bybit.get_open_interest = AsyncMock(return_value={"open_interest": 35000.0})
app.state.binance = mock_binance
app.state.bybit = mock_bybit
app.state.okx = None
app.state.bitget = None
app.state.hyperliquid = None
return TestClient(app)
def test_get_market_candles(test_client):
response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m&limit=10")
assert response.status_code == 200, f"Expected 200, got {response.status_code}: {response.text}"
data = response.json()
assert data["symbol"] == "BTCUSDT"
assert data["exchange"] == "binance"
assert len(data["candles"]) == 2
c0 = data["candles"][0]
assert c0["time"] == 1730000000 # converted to seconds
assert c0["open"] == 68000.0
assert c0["close"] == 68400.0
assert "delta" in c0
assert "cvd" in c0
# taker_buy_volume was 60, total vol 100 -> sell = 40 -> delta = +20
assert c0["delta"] == 20.0
assert c0["cvd"] == 20.0
def test_get_multi_exchange_stream(test_client):
response = test_client.get("/api/market/BTCUSDT/multi-stream")
assert response.status_code == 200
data = response.json()
assert data["symbol"] == "BTCUSDT"
assert "ref_price" in data
assert "exchanges" in data
assert "binance" in data["exchanges"]
assert "bybit" in data["exchanges"]
assert data["exchanges"]["binance"]["mark_price"] is not None
assert data["exchanges"]["binance"]["mark_price"] > 0
def test_get_multi_exchange_stream_with_client_exceptions(test_client):
# Simulate an exchange client raising network exceptions
failing_client = MagicMock()
failing_client.get_mark_price = AsyncMock(side_effect=Exception("Connection timed out"))
failing_client.get_funding_rate = AsyncMock(side_effect=Exception("502 Bad Gateway"))
failing_client.get_open_interest = AsyncMock(side_effect=Exception("Rate limit exceeded"))
app.state.okx = failing_client
app.state.bitget = failing_client
response = test_client.get("/api/market/BTCUSDT/multi-stream")
assert response.status_code == 200
data = response.json()
assert data["symbol"] == "BTCUSDT"
# Even with OKX and Bitget failing completely, Binance and Bybit data remain intact
assert data["exchanges"]["binance"]["available"] is True
assert data["exchanges"]["okx"]["available"] is False
assert data["exchanges"]["bitget"]["available"] is False
def test_get_market_candles_with_null_and_malformed_candles(test_client):
mock_binance = MagicMock()
mock_binance.get_ohlcv = AsyncMock(return_value=[
{
"timestamp": 1730000000000,
"open": None,
"high": 68500.0,
"low": None,
"close": 68400.0,
"volume": None,
"taker_buy_volume": None,
},
])
app.state.binance = mock_binance
response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m")
assert response.status_code == 200
data = response.json()
assert len(data["candles"]) == 1
assert data["candles"][0]["open"] == 0.0
assert data["candles"][0]["low"] == 0.0
assert data["candles"][0]["volume"] == 0.0
assert data["candles"][0]["delta"] == 0.0
def test_ws_chart_handshake(test_client):
with test_client.websocket_connect("/ws/chart/BTCUSDT") as ws:
init_msg = ws.receive_json()
assert init_msg["type"] == "chart_init"
assert init_msg["symbol"] == "BTCUSDT"
# Test ping-pong
ws.send_json({"type": "ping"})
pong_msg = ws.receive_json()
# Either pong or first tick
assert pong_msg["type"] in ("pong", "chart_tick")
def test_get_market_candles_aggregated(test_client):
# Mock Binance + Bybit returning overlapping candles
mock_binance = MagicMock()
mock_binance.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68000.0, "high": 68500.0, "low": 67900.0, "close": 68400.0, "volume": 100.0, "taker_buy_volume": 60.0},
])
mock_binance.get_oi_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open_interest": 500.0, "open_interest_usd": 34000000.0},
])
mock_bybit = MagicMock()
mock_bybit.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68002.0, "high": 68501.0, "low": 67905.0, "close": 68401.0, "volume": 80.0, "taker_buy_volume": None},
])
mock_bybit.get_oi_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open_interest": 300.0},
])
app.state.binance = mock_binance
app.state.bybit = mock_bybit
response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m")
assert response.status_code == 200
data = response.json()
assert data["is_aggregated"] is True
assert data["exchange"] == "aggregated"
assert "binance" in data["exchanges_included"]
assert "bybit" in data["exchanges_included"]
c0 = data["candles"][0]
# Binance vol (100) + Bybit vol (80) = 180
assert c0["volume"] == 180.0
# OI should be Binance ($34M) + Bybit (300 BTC * 68400 = $20.52M) = ~$54.52M
assert c0["open_interest"] is not None
assert c0["open_interest"] > 50000000.0
def test_get_market_candles_4_exchanges_aggregated(test_client):
# Mock Binance + Bybit + OKX + Bitget returning overlapping candles
mock_binance = MagicMock()
mock_binance.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68000.0, "high": 68500.0, "low": 67900.0, "close": 68400.0, "volume": 100.0, "taker_buy_volume": 60.0},
])
mock_binance.get_oi_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open_interest": 500.0, "open_interest_usd": 34000000.0},
])
mock_bybit = MagicMock()
mock_bybit.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68002.0, "high": 68501.0, "low": 67905.0, "close": 68401.0, "volume": 80.0, "taker_buy_volume": None},
])
mock_bybit.get_oi_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open_interest": 300.0},
])
mock_okx = MagicMock()
mock_okx.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68001.0, "high": 68502.0, "low": 67902.0, "close": 68400.5, "volume": 50.0},
])
mock_bitget = MagicMock()
mock_bitget.get_ohlcv = AsyncMock(return_value=[
{"timestamp": 1730000000000, "open": 68000.5, "high": 68500.5, "low": 67901.0, "close": 68400.0, "volume": 30.0},
])
app.state.binance = mock_binance
app.state.bybit = mock_bybit
app.state.okx = mock_okx
app.state.bitget = mock_bitget
response = test_client.get("/api/market/BTCUSDT/candles?timeframe=15m")
assert response.status_code == 200
data = response.json()
assert data["is_aggregated"] is True
assert "binance" in data["exchanges_included"]
assert "bybit" in data["exchanges_included"]
assert "okx" in data["exchanges_included"]
assert "bitget" in data["exchanges_included"]
c0 = data["candles"][0]
# Sum: Binance (100) + Bybit (80) + OKX (50) + Bitget (30) = 260
assert c0["volume"] == 260.0
def test_get_market_funding_history(test_client):
mock_binance = MagicMock()
mock_binance.get_funding_rate_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "funding_rate": 0.0001, "mark_price": 68400.0},
])
mock_bybit = MagicMock()
mock_bybit.get_funding_rate_history = AsyncMock(return_value=[
{"timestamp": 1730000000000, "funding_rate": 0.00012},
])
app.state.binance = mock_binance
app.state.bybit = mock_bybit
response = test_client.get("/api/market/BTCUSDT/funding-history")
assert response.status_code == 200
data = response.json()
assert data["symbol"] == "BTCUSDT"
assert len(data["history"]) >= 1
h0 = data["history"][0]
assert h0["binance"] == 0.0001
assert h0["bybit"] == 0.00012
assert h0["avg_funding"] == 0.00011