Advertisement
den4ik2003

Untitled

Apr 10th, 2024
842
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.92 KB | None | 0 0
  1. import asyncio
  2. import nest_asyncio
  3. import json
  4. import logging
  5.  
  6. # TODO обавить обработку ошибок и try
  7.  
  8. from okx.websocket.WsPublicAsync import WsPublicAsync
  9.  
  10. nest_asyncio.apply()
  11.  
  12. logger = logging.getLogger()
  13. logger.setLevel(logging.CRITICAL)
  14.  
  15. file1 = open('okx_trades.logs', 'w')
  16. file2 = open('okx_depth.logs', 'w')
  17.  
  18. def publicCallback(msg): # snapshot and update data
  19.     msg = json.loads(msg)
  20.     ev = msg.get('event')
  21.     data = msg.get('data')
  22.    
  23.     if msg['arg']['channel'] == 'trades':
  24.         if data:
  25.             data = data[0]
  26.             renamed_fields = {'ts': 'ts', 'price': 'px', 'size': 'sz', 'side': 'side'}
  27.             file1.write(json.dumps({field: data[renamed_fields[field]] for field in renamed_fields}))
  28.             file1.write('\n')
  29.             file1.flush()
  30.    
  31.     elif msg['arg']['channel'] == 'books':
  32.         if data:
  33.             data = data[0]
  34.             file2.write('asks len: ' + str(len(data['asks'])) + '\n')
  35.             file2.write('bids len: ' + str(len(data['bids'])) + '\n')
  36.            
  37.             depth_lvl = {
  38.                 'asks':    data['asks'][:min(len(data['asks']), 50)],
  39.                 'bids':    data['bids'][:min(len(data['bids']), 50)],
  40.                 'ts':      data['ts'],
  41.                 'action':  msg['action']
  42.             }
  43.            
  44.             file2.write(json.dumps(depth_lvl))
  45.             file2.write('\n')
  46.             file2.flush()
  47.    
  48.  
  49. async def main():
  50.     url = "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999"
  51.     ws = WsPublicAsync(url=url)
  52.     await ws.start()
  53.    
  54.     args = []
  55.     arg1 = {"channel": "trades", "instId": "BTC-USDT"}
  56.     args.append(arg1)
  57.     arg2 = {"channel": "books", "instId": "BTC-USDT"}
  58.     args.append(arg2)
  59.    
  60.     await ws.subscribe(args, publicCallback)
  61.    
  62.     while True:
  63.         await asyncio.sleep(20)
  64.    
  65.  
  66. if __name__ == "__main__":
  67.     asyncio.run(main())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement