ws_client.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import websocket
  2. import threading
  3. from logger_config import logger
  4. from data_processing import on_message_trade, on_message_depth, stop_event
  5. # Binance WebSocket API URL
  6. SYMBOL = "tokenusdt"
  7. SOCKET_TRADE = "wss://fstream.binance.com/stream?streams=" + SYMBOL + "@trade"
  8. SOCKET_DEPTH = "wss://fstream.binance.com/stream?streams=" + SYMBOL + "@depth20@100ms"
  9. def on_error(_ws, error):
  10. logger.error(error)
  11. def on_open(_ws):
  12. logger.info("### binance_ws opened ###")
  13. # Create a WebSocket app
  14. ws_trade = websocket.WebSocketApp(SOCKET_TRADE, on_message=on_message_trade, on_error=on_error, on_open=on_open)
  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. # Run the WebSocket with proxy settings
  21. trade_thread = threading.Thread(target=ws_trade.run_forever, kwargs={
  22. 'http_proxy_host': http_proxy_host,
  23. 'http_proxy_port': http_proxy_port,
  24. 'proxy_type': proxy_type
  25. })
  26. depth_thread = threading.Thread(target=ws_depth.run_forever, kwargs={
  27. 'http_proxy_host': http_proxy_host,
  28. 'http_proxy_port': http_proxy_port,
  29. 'proxy_type': proxy_type
  30. })
  31. def start_ws_clients():
  32. trade_thread.start()
  33. depth_thread.start()
  34. def stop_all_threads():
  35. stop_event.set()
  36. trade_thread.join()
  37. depth_thread.join()