2025-08-13 18:49:19 +08:00
|
|
|
|
from typing import Dict, Any, Optional
|
|
|
|
|
|
import logging
|
|
|
|
|
|
from okx import OkxRestClient
|
|
|
|
|
|
from .base_service import BaseService
|
2025-08-13 22:48:17 +08:00
|
|
|
|
from config import Config # 导入配置
|
2025-08-13 18:49:19 +08:00
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
class CryptoService(BaseService):
|
|
|
|
|
|
"""加密货币价格服务"""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, api_key: str = "", secret_key: str = "", passphrase: str = ""):
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
# 对于公共数据,不需要API密钥
|
|
|
|
|
|
self.client = OkxRestClient(api_key, secret_key, passphrase) if api_key else OkxRestClient()
|
|
|
|
|
|
|
2025-08-13 22:48:17 +08:00
|
|
|
|
def get_data(self, pair: str = Config.DEFAULT_CRYPTO_PAIR) -> Optional[Dict[str, Any]]:
|
2025-08-13 18:49:19 +08:00
|
|
|
|
"""获取指定交易对的价格数据"""
|
|
|
|
|
|
try:
|
|
|
|
|
|
# 使用正确的marketdata属性获取ticker数据
|
|
|
|
|
|
response = self.client.marketdata.get_ticker(instId=pair)
|
|
|
|
|
|
|
|
|
|
|
|
if response and response.get('code') == '0' and response.get('data'):
|
|
|
|
|
|
ticker_data = response['data'][0]
|
|
|
|
|
|
|
|
|
|
|
|
# 手动计算24小时百分比变化
|
|
|
|
|
|
last_price = float(ticker_data['last'])
|
|
|
|
|
|
open_price = float(ticker_data['open24h'])
|
|
|
|
|
|
pct_change = ((last_price - open_price) / open_price) * 100
|
|
|
|
|
|
|
|
|
|
|
|
# 格式化数据
|
|
|
|
|
|
return {
|
|
|
|
|
|
'pair': pair,
|
|
|
|
|
|
'price': last_price,
|
|
|
|
|
|
'change_24h': round(pct_change, 2), # 保留两位小数
|
|
|
|
|
|
'volume_24h': float(ticker_data.get('vol24h', 0)),
|
|
|
|
|
|
'high_24h': float(ticker_data.get('high24h', 0)),
|
|
|
|
|
|
'low_24h': float(ticker_data.get('low24h', 0)),
|
|
|
|
|
|
'timestamp': ticker_data['ts']
|
|
|
|
|
|
}
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.error(f"获取{pair}价格失败: {response}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"获取加密货币价格时出错: {e}")
|
|
|
|
|
|
return None
|
|
|
|
|
|
|