quote-rss-plugin/services/crypto_service.py
2025-08-13 18:49:19 +08:00

47 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Dict, Any, Optional
import logging
from okx import OkxRestClient
from .base_service import BaseService
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()
def get_data(self, pair: str = "ETH-USDT") -> Optional[Dict[str, Any]]:
"""获取指定交易对的价格数据"""
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