跳到主要内容

三、缓存管理

三、缓存管理

3.1 缓存操作

💾 cache_save(data)

功能: 将数据保存到缓存系统

参数:

  • data: 要保存的数据对象,可以是Python字典、列表或任何可序列化的数据结构

返回值: 无

示例:

# 保存策略状态到缓存
import time

# 准备要保存的策略状态(直接使用Python字典)
state = {
"positions": [
{"symbol": "BTC_USDT", "amount": 0.05, "entry_price": 49800, "unrealized_pnl": 120},
{"symbol": "ETH_USDT", "amount": 0.8, "entry_price": 3200, "unrealized_pnl": 80}
],
"orders": [
{"symbol": "BTC_USDT", "order_id": "123456", "status": "open"},
{"symbol": "ETH_USDT", "order_id": "789012", "status": "filled"}
],
"statistics": {
"total_profit": 1250.5,
"trade_count": 48,
"win_rate": 0.75
},
"last_update": int(time.time())
}

# 直接保存Python对象,无需手动转换为JSON
trader.cache_save(state)

# 也可以保存简单的数据类型
trader.cache_save({"last_price": 50000.0, "timestamp": int(time.time())})

# 保存列表数据
positions_list = [
{"symbol": "BTC_USDT", "side": "long", "amount": 0.1},
{"symbol": "ETH_USDT", "side": "short", "amount": 2.0}
]
trader.cache_save(positions_list)

📂 cache_load()

功能: 从缓存系统加载数据

参数: 无

返回值:

  • 缓存数据对象,如果没有缓存则返回None。返回的数据保持原始的Python数据类型

示例:

# 从缓存加载策略状态
cached_data = trader.cache_load()

if cached_data is not None:
# 数据已自动转换为Python对象,无需手动解析JSON
print(f"加载的策略状态: {cached_data}")

# 直接使用加载的数据
if isinstance(cached_data, dict):
positions = cached_data.get("positions", [])
orders = cached_data.get("orders", [])
statistics = cached_data.get("statistics", {})

print(f"已恢复 {len(positions)} 个持仓, {len(orders)} 个订单")
print(f"总盈利: {statistics.get('total_profit', 0)}, 胜率: {statistics.get('win_rate', 0)*100}%")

# 如果保存的是列表
elif isinstance(cached_data, list):
print(f"加载的持仓列表: {len(cached_data)} 个持仓")
for pos in cached_data:
print(f" {pos['symbol']}: {pos['side']} {pos['amount']}")

else:
print("缓存为空,使用默认配置")
# 初始化默认状态
positions = []
orders = []
statistics = {"total_profit": 0, "trade_count": 0, "win_rate": 0}

# 安全的缓存加载模式
def load_strategy_state():
"""安全加载策略状态"""
try:
cached_state = trader.cache_load()

if cached_state and isinstance(cached_state, dict):
# 验证缓存数据的完整性
required_keys = ["positions", "orders", "statistics"]
if all(key in cached_state for key in required_keys):
return cached_state
else:
print("缓存数据不完整,使用默认状态")

# 返回默认状态
return {
"positions": [],
"orders": [],
"statistics": {"total_profit": 0, "trade_count": 0, "win_rate": 0},
"last_update": int(time.time())
}

except Exception as e:
print(f"加载缓存失败: {e}")
return {
"positions": [],
"orders": [],
"statistics": {"total_profit": 0, "trade_count": 0, "win_rate": 0},
"last_update": int(time.time())
}

# 使用安全加载函数
strategy_state = load_strategy_state()

3.2 缓存系统说明

Trader提供的缓存系统分为两部分,它们是互相独立的机制:

  1. 策略缓存 📊: 通过cache_savecache_load方法管理的缓存,主要用于保存策略状态,如交易记录、统计数据等。
    • cache_save: 保存任意Python数据结构(字典、列表等)到缓存
    • cache_load: 从缓存加载数据,返回原始的Python数据类型
    • 数据格式: 支持自动序列化/反序列化,无需手动转换JSON