ws_client.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import traceback
  2. import websocket
  3. import threading
  4. from logger_config import logger
  5. from data_processing import on_message_depth, on_message_trade, stop_event
  6. # Binance WebSocket API URL
  7. SYMBOL = "1000pepe" + "usdt"
  8. SOCKET_TRADE = "wss://fstream.binance.com/stream?streams=" + SYMBOL + "@trade"
  9. SOCKET_DEPTH = "wss://fstream.binance.com/stream?streams=" + SYMBOL + "@depth20@100ms"
  10. def on_error(_ws, _error):
  11. logger.error('捕获到一个异常。')
  12. traceback.print_exc() # 打印完整的错误堆栈信息
  13. # raise error # 重新抛出错误
  14. def on_open(_ws):
  15. logger.info("### binance_ws opened ###")
  16. # Create a WebSocket app
  17. ws_trade = websocket.WebSocketApp(SOCKET_TRADE, on_message=on_message_trade, on_error=on_error, on_open=on_open)
  18. ws_depth = websocket.WebSocketApp(SOCKET_DEPTH, on_message=on_message_depth, on_error=on_error, on_open=on_open)
  19. # 定义要传递给 run_forever 的参数
  20. http_proxy_host = "127.0.0.1"
  21. http_proxy_port = 7890
  22. proxy_type = "http"
  23. # Run the WebSocket with proxy settings
  24. trade_thread = threading.Thread(target=ws_trade.run_forever, kwargs={
  25. 'http_proxy_host': http_proxy_host,
  26. 'http_proxy_port': http_proxy_port,
  27. 'proxy_type': proxy_type
  28. })
  29. depth_thread = threading.Thread(target=ws_depth.run_forever, kwargs={
  30. 'http_proxy_host': http_proxy_host,
  31. 'http_proxy_port': http_proxy_port,
  32. 'proxy_type': proxy_type
  33. })
  34. def start_ws_clients():
  35. trade_thread.start()
  36. depth_thread.start()
  37. def stop_all_threads():
  38. stop_event.set()
  39. trade_thread.join()
  40. depth_thread.join()