File size: 9,554 Bytes
7843862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf49534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c08e4cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf49534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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