ws_client.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import traceback
  2. import websocket
  3. import threading
  4. from logger_config import logger
  5. from data_processing import on_message_depth, stop_event
  6. # Binance WebSocket API URL
  7. SYMBOL = "ethfi" + "usdt"
  8. SOCKET_DEPTH = "wss://fstream.binance.com/stream?streams=" + SYMBOL + "@depth20@100ms"
  9. def on_error(_ws, error):
  10. traceback.print_exc() # 打印完整的错误堆栈信息
  11. # raise error # 重新抛出错误
  12. def on_open(_ws):
  13. logger.info("### binance_ws opened ###")
  14. # Create a WebSocket app
  15. ws_depth = websocket.WebSocketApp(SOCKET_DEPTH, on_message=on_message_depth, on_error=on_error, on_open=on_open)
  16. # 定义要传递给 run_forever 的参数
  17. http_proxy_host = "127.0.0.1"
  18. http_proxy_port = 7890
  19. proxy_type = "http"
  20. depth_thread = threading.Thread(target=ws_depth.run_forever, kwargs={
  21. 'http_proxy_host': http_proxy_host,
  22. 'http_proxy_port': http_proxy_port,
  23. 'proxy_type': proxy_type
  24. })
  25. def start_ws_clients():
  26. depth_thread.start()
  27. def stop_all_threads():
  28. stop_event.set()
  29. depth_thread.join()