1
|
|
|
import asyncio |
2
|
|
|
import time |
3
|
|
|
from typing import Optional, List |
4
|
|
|
|
5
|
|
|
from tests import APITestCase, MAINNET_WS_URI, WEBSOCKET_TIMEOUT_GET_REQUEST |
6
|
|
|
from tradehub.websocket_client import DemexWebsocket |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
class TestWSGetCandlesticks(APITestCase): |
10
|
|
|
|
11
|
|
|
def test_get_candlesticks_structure(self): |
12
|
|
|
""" |
13
|
|
|
Check if response match expected dict structure. |
14
|
|
|
:return: |
15
|
|
|
""" |
16
|
|
|
|
17
|
|
|
expect: dict = { |
18
|
|
|
'id': str, |
19
|
|
|
'sequence_number': int, |
20
|
|
|
'result': [ |
21
|
|
|
{ |
22
|
|
|
'id': int, |
23
|
|
|
'market': str, |
24
|
|
|
'time': str, |
25
|
|
|
'resolution': int, |
26
|
|
|
'open': str, |
27
|
|
|
'close': str, |
28
|
|
|
'high': str, |
29
|
|
|
'low': str, |
30
|
|
|
'volume': str, |
31
|
|
|
'quote_volume': str |
32
|
|
|
} |
33
|
|
|
] |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
# connect to websocket |
37
|
|
|
client = DemexWebsocket(uri=MAINNET_WS_URI) |
38
|
|
|
# little work around to save the response |
39
|
|
|
self.response: List[Optional[dict]] = [] |
40
|
|
|
|
41
|
|
|
async def on_connect(): |
42
|
|
|
for granularity in [1, 5, 15, 30, 60, 360, 1440]: |
43
|
|
|
from_epoch = int(time.time() - granularity * 1000) |
44
|
|
|
to_epoch = int(time.time()) |
45
|
|
|
await client.get_candlesticks('candlesticks', "eth1_usdc1", granularity, from_epoch, to_epoch) |
46
|
|
|
|
47
|
|
|
async def on_message(message: dict): |
48
|
|
|
# save response into self |
49
|
|
|
self.response.append(message) |
50
|
|
|
|
51
|
|
|
try: |
52
|
|
|
loop = asyncio.get_event_loop() |
53
|
|
|
loop.run_until_complete(asyncio.wait_for(client.connect(on_connect_callback=on_connect, |
54
|
|
|
on_receive_message_callback=on_message), |
55
|
|
|
WEBSOCKET_TIMEOUT_GET_REQUEST)) |
56
|
|
|
except asyncio.TimeoutError: |
57
|
|
|
loop = asyncio.get_event_loop() |
58
|
|
|
loop.run_until_complete(client.disconnect()) |
59
|
|
|
|
60
|
|
|
if not self.response: |
61
|
|
|
raise RuntimeError("Did not receive a response.") |
62
|
|
|
|
63
|
|
|
for response in self.response: |
64
|
|
|
if response["result"]: |
65
|
|
|
self.assertDictStructure(expect, response) |
66
|
|
|
|
67
|
|
|
def test_get_candlesticks_wrong_granularity(self): |
68
|
|
|
""" |
69
|
|
|
Check if the method catches wrong granularities. |
70
|
|
|
:return: |
71
|
|
|
""" |
72
|
|
|
|
73
|
|
|
# connect to websocket |
74
|
|
|
client = DemexWebsocket(uri="") |
75
|
|
|
for wrong_granularity in [0, 2, 4, 6, 100, 1500]: |
76
|
|
|
with self.assertRaises(ValueError): |
77
|
|
|
loop = asyncio.get_event_loop() |
78
|
|
|
loop.run_until_complete(client.get_candlesticks("candle", "swth_eth1", wrong_granularity, 0, 0)) |
79
|
|
|
|