File tree Expand file tree Collapse file tree 1 file changed +84
-0
lines changed
Expand file tree Collapse file tree 1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ import asyncio
2+ import logging
3+ import json
4+ from websockets .asyncio .client import connect
5+
6+ # import debugpy
7+
8+ # # Allow VS Code to attach
9+ # debugpy.listen(("0.0.0.0", 5678)) # Use the port you've specified
10+ # print("Waiting for debugger to attach...")
11+ # debugpy.wait_for_client()
12+
13+ logging .getLogger (__name__ )
14+ logging .basicConfig (
15+ format = "%(asctime)s %(module)s:%(lineno)d %(levelname)8s | %(message)s" ,
16+ datefmt = "%Y/%m/%d %H:%M:%S" ,
17+ level = logging .DEBUG ,
18+ )
19+
20+ class MyClient :
21+
22+ def __init__ (self ):
23+ self .keep_alive = True
24+
25+ async def run (self ):
26+
27+ async with connect (
28+ f"wss://ws.kraken.com/v2" ,
29+ ping_interval = 30 ,
30+ # max_queue=None, # having this enabled doesn't cause problems
31+ ) as socket :
32+ await socket .send (
33+ json .dumps (
34+ {
35+ "method" : "subscribe" ,
36+ "params" : {
37+ "channel" : "book" ,
38+ "symbol" : [
39+ "BTC/USD" ,
40+ "DOT/USD" ,
41+ "ETH/USD" ,
42+ "MATIC/USD" ,
43+ "BTC/EUR" ,
44+ "DOT/EUR" ,
45+ "ETH/EUR" ,
46+ "XLM/USD" ,
47+ "XLM/EUR" ,
48+ ],
49+ "depth" : 100
50+ },
51+ }
52+ )
53+ )
54+
55+ while self .keep_alive :
56+ try :
57+ _message = await asyncio .wait_for (socket .recv (), timeout = 10 )
58+ except TimeoutError :
59+ pass
60+ except asyncio .CancelledError :
61+ self .keep_alive = False
62+ else :
63+ try :
64+ message = json .loads (_message )
65+ except ValueError :
66+ pass
67+
68+ async def __aenter__ (self ):
69+ self .task : asyncio .Task = asyncio .create_task (self .run ())
70+ return self
71+
72+ async def __aexit__ (self , * args , ** kwargs ):
73+ self .keep_alive = False
74+ if hasattr (self , "task" ) and not self .task .done ():
75+ await self .task
76+
77+
78+ async def main ():
79+ async with MyClient ():
80+ await asyncio .sleep (3 )
81+
82+
83+ if __name__ == "__main__" :
84+ asyncio .run (main ())
You can’t perform that action at this time.
0 commit comments