- 实现 REST API 客户端,支持股票、加密货币、外汇、期货、基金和指数数据 - 实现 WebSocket 客户端,支持实时数据订阅 - 添加异常处理、工具函数和常量定义 - 包含安装配置和示例代码 - 添加文档爬虫工具用于生成离线文档
134 lines
4.8 KiB
Python
134 lines
4.8 KiB
Python
import asyncio
|
|
import json
|
|
import logging
|
|
import websockets
|
|
from .constants import Environment, WS_URLS, Product
|
|
from .exceptions import ITickError, AuthError, ConnectionError
|
|
from .utils import get_timestamp
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class SocketClient:
|
|
def __init__(self, token, product, environment=Environment.LIVE, on_message=None, on_error=None):
|
|
"""
|
|
:param token: API Token
|
|
:param product: Product enum or string (e.g., 'crypto', 'stock')
|
|
:param environment: Environment.LIVE or Environment.FREE
|
|
:param on_message: Callback for normal messages
|
|
:param on_error: Callback for errors
|
|
"""
|
|
self.token = token
|
|
self.product = product.value if isinstance(product, Product) else product
|
|
self.environment = environment
|
|
self.base_url = WS_URLS.get(environment)
|
|
self.url = f"{self.base_url}/{self.product}"
|
|
|
|
self.on_message_callback = on_message
|
|
self.on_error_callback = on_error
|
|
|
|
self.ws = None
|
|
self.running = False
|
|
self.authenticated = False
|
|
self._lock = asyncio.Lock()
|
|
|
|
async def connect(self):
|
|
"""Connect to the WebSocket server"""
|
|
headers = {"token": self.token}
|
|
try:
|
|
logger.info(f"Connecting to {self.url}...")
|
|
self.ws = await websockets.connect(self.url, extra_headers=headers)
|
|
self.running = True
|
|
logger.info("Connected.")
|
|
|
|
# Start listener and heartbeat
|
|
asyncio.create_task(self._listen())
|
|
asyncio.create_task(self._heartbeat())
|
|
|
|
except Exception as e:
|
|
logger.error(f"Connection failed: {e}")
|
|
if self.on_error_callback:
|
|
self.on_error_callback(ConnectionError(str(e)))
|
|
raise
|
|
|
|
async def subscribe(self, symbols, data_types):
|
|
"""
|
|
Subscribe to data
|
|
:param symbols: List of symbols (e.g., ["BTCUSDT$BA"]) or comma-separated string
|
|
:param data_types: List of types (e.g., ["quote", "depth"]) or comma-separated string
|
|
"""
|
|
if not self.ws or not self.running:
|
|
raise ConnectionError("WebSocket is not connected")
|
|
|
|
if isinstance(symbols, list):
|
|
symbols = ",".join(symbols)
|
|
if isinstance(data_types, list):
|
|
data_types = ",".join(data_types)
|
|
|
|
msg = {
|
|
"ac": "subscribe",
|
|
"params": symbols,
|
|
"types": data_types
|
|
}
|
|
await self._send(msg)
|
|
|
|
async def _send(self, data):
|
|
if self.ws:
|
|
await self.ws.send(json.dumps(data))
|
|
|
|
async def _listen(self):
|
|
while self.running and self.ws:
|
|
try:
|
|
message = await self.ws.recv()
|
|
data = json.loads(message)
|
|
|
|
# Handle system messages
|
|
if "resAc" in data:
|
|
res_ac = data.get("resAc")
|
|
if res_ac == "auth":
|
|
if data.get("code") == 1:
|
|
self.authenticated = True
|
|
logger.info("Authenticated successfully")
|
|
else:
|
|
logger.error(f"Authentication failed: {data.get('msg')}")
|
|
if self.on_error_callback:
|
|
self.on_error_callback(AuthError(data.get("msg")))
|
|
# Should probably close?
|
|
elif res_ac == "pong":
|
|
# logger.debug("Pong received")
|
|
pass
|
|
elif res_ac == "subscribe":
|
|
if data.get("code") != 1:
|
|
logger.error(f"Subscription failed: {data.get('msg')}")
|
|
|
|
# User callback
|
|
if self.on_message_callback:
|
|
self.on_message_callback(data)
|
|
|
|
except websockets.exceptions.ConnectionClosed:
|
|
logger.warning("Connection closed")
|
|
self.running = False
|
|
break
|
|
except Exception as e:
|
|
logger.error(f"Error in listener: {e}")
|
|
if self.on_error_callback:
|
|
self.on_error_callback(e)
|
|
|
|
async def _heartbeat(self):
|
|
while self.running:
|
|
await asyncio.sleep(30)
|
|
if self.ws and self.running:
|
|
try:
|
|
ping_msg = {
|
|
"ac": "ping",
|
|
"params": str(get_timestamp())
|
|
}
|
|
await self._send(ping_msg)
|
|
except Exception as e:
|
|
logger.error(f"Heartbeat failed: {e}")
|
|
break
|
|
|
|
async def close(self):
|
|
self.running = False
|
|
if self.ws:
|
|
await self.ws.close()
|