88 浏览
0

我的是运行实盘交易,程序上午盘开盘,可以正常执行,但午盘休市后,到下午就不能自动执行,请问代码是有什么问题?

from datetime import date, datetime
import pandas as pd
from tqsdk import TqAccount, TqApi, TqAuth, TqBacktest, TargetPosTask, BacktestFinished, TqSim
from tqsdk.ta import MA, CCI, KDJ, WR, ATR
import numpy as np
 # ===== 全局参数设置 =====
SYMBOL = "DCE.c2603"  # 合约代码
POSITION_SIZE = 1  # 基础持仓手数
START_DATE = date(2025, 7, 1)  # 回测开始日期
END_DATE = date(2025, 11, 1)  # 回测结束日期
 # 技术指标参数
H_MA12 = 12  # 小时线短期均线周期
H_MA60 = 60  # 小时线长期均线周期
MIN15_CCI_PERIOD = 20  # 15分钟线CCI周期
MIN15_KDJ_PERIOD = (9, 3, 3)  # 15分钟线KDJ周期
MIN15_WR_PERIOD = 14  # 15分钟线威廉指标周期
ATR_PERIOD = 14  # ATR计算周期
 STOP_LOSS_MULTIPLIER = 2.0  # 止损ATR倍数
TAKE_PROFIT_MULTIPLIER = 3.0  # 止盈ATR倍数
 # 创建API实例
# api = TqApi(TqSim(), web_gui=True, backtest=TqBacktest(start_dt=START_DATE, end_dt=END_DATE),
#            auth=TqAuth("wang75000", "0151jerry@@"))
api = TqApi(TqAccount("H宏源期货", "999999999", "00000000000"),
            auth=TqAuth("111111111", "12345678"))
 # 订阅合约的K线数据
hour_klines = api.get_kline_serial(SYMBOL, 60 * 60)  # 小时线
hour4_klines = api.get_kline_serial(SYMBOL, 60 * 60*4)  # 小时线
min15_klines = api.get_kline_serial(SYMBOL, 15 * 60)  # 15分钟线
 # 创建目标持仓任务
target_pos = TargetPosTask(api, SYMBOL)
 # 初始化交易状态变量
current_direction = 0  # 0: 无持仓, 1: 多头, -1: 空头
entry_price = 0
stop_loss_price = 0
highest_since_entry = 0
lowest_since_entry = 0
 # 等待初始数据加载
print("等待数据加载...")
  def format_time_from_ns(timestamp_ns):
    """将纳秒时间戳格式化为可读字符串"""
    # 转换为秒(保留9位小数以保持纳秒精度)
    timestamp_seconds = timestamp_ns / 1e9
    # 使用datetime.fromtimestamp创建datetime对象
    dt = datetime.fromtimestamp(timestamp_seconds)
    # 格式化为字符串
    return dt.strftime('%Y-%m-%d %H:%M:%S')
   while True:
    # 等待更新
    api.wait_update()
     # 如果K线有更新
    if api.is_changing(min15_klines.iloc[-1], "datetime"):
        # 确保有足够的数据计算指标
        if len(hour_klines) < H_MA60 + 5 or \
                len(min15_klines) < max(MIN15_CCI_PERIOD, MIN15_KDJ_PERIOD[0], MIN15_WR_PERIOD) + 5:
            print(f"数据不足,等待更多数据...")
            continue
         # ===== 技术指标计算 =====
        # 计算4小时短期移动平均线(SHORT期)
        hour4_klines["short4_ma"] = MA(hour4_klines, H_MA12).ma
         # 以下均为简单获取技术指标,省略====================================
         # ===== 交易逻辑 =====
        if current_direction == 0:
            # 多头开仓条件
            if (current_short4_ma>current_long4_ma and current_short_ma > current_long_ma and current_price>current_short4_ma
                    and current_wr < -80 ):
                # 设置持仓方向和目标持仓
                current_direction = 1
                target_pos.set_target_volume(POSITION_SIZE)
                # 记录开仓价格
                entry_price = current_price
                # 设置多头止损止盈:止损=开仓价-2*ATR,止盈=开仓价+4*ATR
                stop_loss_price = entry_price - STOP_LOSS_MULTIPLIER * current_atr
                take_profit_price = entry_price + TAKE_PROFIT_MULTIPLIER * current_atr
                print(f"开多仓!时间: {current_time_str}, 价格: {entry_price:.2f}, "
                      f"止损: {stop_loss_price:.2f}, 止盈: {take_profit_price:.2f}")
             # 空头开仓条件
            elif (current_short4_ma<current_long4_ma and current_short_ma < current_long_ma and current_price<current_short4_ma
                  and current_wr > -20 ):
                # 设置持仓方向和目标持仓
                current_direction = -1
                target_pos.set_target_volume(-POSITION_SIZE)
                # 记录开仓价格
                entry_price = current_price
                # 设置空头止损止盈:止损=开仓价+2*ATR,止盈=开仓价-4*ATR
                stop_loss_price = entry_price + STOP_LOSS_MULTIPLIER * current_atr
                take_profit_price = entry_price - TAKE_PROFIT_MULTIPLIER * current_atr
                print(f"开空仓!时间: {current_time_str}, 价格: {entry_price:.2f}, "
                      f"止损: {stop_loss_price:.2f}, 止盈: {take_profit_price:.2f}")
         # ===== 平仓逻辑 =====
        # 情况2:多头持仓 - 检查平仓条件
        elif current_direction == 1:
            # 止损条件:价格跌破止损位
            if current_price <= stop_loss_price:
                profit = (current_price - entry_price) * POSITION_SIZE * 10  # 玉米每手10吨
                profit_pct = (current_price - entry_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"多头止损平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
             # 止盈条件:价格达到止盈位
            elif current_price >= take_profit_price:
                profit = (current_price - entry_price) * POSITION_SIZE * 10
                profit_pct = (current_price - entry_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"多头止盈平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
             # 信号平仓:出现空单信号
            elif current_short_ma < current_long_ma and current_cci > 100:
                profit = (current_price - entry_price) * POSITION_SIZE * 10
                profit_pct = (current_price - entry_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"多头信号平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
         # 情况3:空头持仓 - 检查平仓条件
        elif current_direction == -1:
            # 止损条件:价格涨破止损位
            if current_price >= stop_loss_price:
                profit = (entry_price - current_price) * POSITION_SIZE * 10
                profit_pct = (entry_price - current_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"空头止损平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
             # 止盈条件:价格达到止盈位
            elif current_price <= take_profit_price:
                profit = (entry_price - current_price) * POSITION_SIZE * 10
                profit_pct = (entry_price - current_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"空头止盈平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
             # 信号平仓:出现金叉信号
            elif current_short_ma > current_long_ma and current_cci < -100:
                profit = (entry_price - current_price) * POSITION_SIZE * 10
                profit_pct = (entry_price - current_price) / entry_price * 100
                target_pos.set_target_volume(0)
                current_direction = 0
                print(f"空头信号平仓: 时间={current_time_str}, 价格={current_price:.2f}, "
                      f"盈亏={profit:.2f}元, 盈亏百分比={profit_pct:.2f}%")
 except BacktestFinished as e:
    print("回测结束")
    api.close()

chaos 已回答的问题 4天 前
0

感觉截图和你说的问题不一样,从控制台信息没有看到网络问题

然后跨交易日是需要重启一下软件的

chaos 发表新评论 4天 前

有其他问题欢迎加入官方Q群748265037一起交流

您正在查看1个答案中的1个,单击此处查看所有答案。