first code

This commit is contained in:
Coldin04 2025-08-13 18:49:19 +08:00
commit b18805aa26
11 changed files with 612 additions and 0 deletions

38
services/base_service.py Normal file
View file

@ -0,0 +1,38 @@
from abc import ABC, abstractmethod
from typing import Dict, Any, Optional
from datetime import datetime, timedelta
class BaseService(ABC):
"""基础服务类,为扩展提供统一接口"""
def __init__(self):
self.cache = {}
self.cache_timeout = timedelta(seconds=30)
@abstractmethod
def get_data(self, **kwargs) -> Optional[Dict[str, Any]]:
"""获取数据的抽象方法"""
pass
def get_cached_data(self, cache_key: str, **kwargs) -> Optional[Dict[str, Any]]:
"""带缓存的数据获取"""
# 检查缓存
if cache_key in self.cache:
cached_item = self.cache[cache_key]
if datetime.now() - cached_item['timestamp'] < self.cache_timeout:
return cached_item['data']
# 获取新数据
data = self.get_data(**kwargs)
if data:
# 更新缓存
self.cache[cache_key] = {
'data': data,
'timestamp': datetime.now()
}
return data
def clear_cache(self):
"""清理缓存"""
self.cache.clear()

View file

@ -0,0 +1,47 @@
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