主力合约回测
This commit is contained in:
@@ -41,7 +41,7 @@ class SimpleLimitBuyStrategy(Strategy):
|
||||
|
||||
self.order_id_counter = 0
|
||||
|
||||
self._bar_history: deque[Bar] = deque(maxlen=7)
|
||||
self._bar_history: deque[Bar] = deque(maxlen=10)
|
||||
self._last_order_id: Optional[str] = None # 用于跟踪上一根K线发出的订单ID
|
||||
|
||||
self.log(f"策略初始化: symbol={self.symbol}, trade_volume={self.trade_volume}, "
|
||||
@@ -58,6 +58,7 @@ class SimpleLimitBuyStrategy(Strategy):
|
||||
next_bar_open (Optional[float]): 下一根K线的开盘价,此处策略未使用。
|
||||
"""
|
||||
current_datetime = bar.datetime # 获取当前K线时间
|
||||
self.symbol = bar.symbol
|
||||
|
||||
# --- 1. 撤销上一根K线未成交的订单 ---
|
||||
# 检查是否记录了上一笔订单ID,并且该订单仍然在待处理列表中
|
||||
@@ -87,7 +88,6 @@ class SimpleLimitBuyStrategy(Strategy):
|
||||
# --- 3. 平仓逻辑 (止损/止盈) ---
|
||||
# 只有当有持仓时才考虑平仓
|
||||
if current_pos_volume > 0: # 假设只做多,所以持仓量 > 0
|
||||
|
||||
avg_entry_price = self.get_average_position_price(self.symbol)
|
||||
if avg_entry_price is not None:
|
||||
pnl_per_unit = bar.close - avg_entry_price # 当前浮动盈亏(以收盘价计算)
|
||||
@@ -140,7 +140,7 @@ class SimpleLimitBuyStrategy(Strategy):
|
||||
|
||||
# 获取前1根K线 (倒数第二根) 和前7根K线 (队列中最老的一根)
|
||||
bar_1_ago = self._bar_history[-2]
|
||||
bar_7_ago = self._bar_history[0]
|
||||
bar_7_ago = self._bar_history[-8]
|
||||
|
||||
# 计算历史 K 线的 Range
|
||||
range_1_ago = bar_1_ago.high - bar_1_ago.low
|
||||
@@ -174,10 +174,21 @@ class SimpleLimitBuyStrategy(Strategy):
|
||||
new_order = self.send_order(order)
|
||||
# 记录下这个订单的ID,以便在下一根K线开始时进行撤销
|
||||
if new_order:
|
||||
self._last_order_id = new_order.order_id
|
||||
self._last_order_id = new_order.id
|
||||
self.log(f"[{current_datetime}] 策略: 发送限价买入订单 {self._last_order_id} @ {target_buy_price:.2f}")
|
||||
else:
|
||||
self.log(f"[{current_datetime}] 策略: 发送订单失败。")
|
||||
|
||||
# else:
|
||||
# self.log(f"[{current_datetime}] 不满足开仓条件:持仓={current_pos_volume}, 待处理订单={len(pending_orders_after_cancel)}, K线历史长度={len(self._bar_history)}")
|
||||
# self.log(f"[{current_datetime}] 不满足开仓条件:持仓={current_pos_volume}, 待处理订单={len(pending_orders_after_cancel)}, K线历史长度={len(self._bar_history)}")
|
||||
|
||||
def on_rollover(self, old_symbol: str, new_symbol: str):
|
||||
"""
|
||||
在合约换月时清空历史K线数据和上次订单ID,避免使用旧合约数据进行计算。
|
||||
"""
|
||||
super().on_rollover(old_symbol, new_symbol) # 调用基类方法打印日志
|
||||
self._bar_history.clear() # 清空历史K线
|
||||
self._last_order_id = None # 清空上次订单ID,因为旧合约订单已取消
|
||||
|
||||
self.log(f"换月完成,清空历史K线数据和上次订单ID,准备新合约交易。")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user