from tqsdk import TqApi, TqAuth, TqBacktest, TargetPosTask from tqsdk import tafunc # 转换K线的时间格式:tafunc.time_to_datetime(org_time) # org_time: K线起点时间(按北京时间),自unix epoch(1970-01-01 00:00:00 GMT)以来的纳秒数 from datetime import date, datetime # yylh_mode = None web_gui = True # backtest = TqBacktest(start_dt=date(2024, 8, 15), end_dt=date(2024, 8, 16)) backtest = TqBacktest(start_dt=datetime(2024, 8, 16, 14, 40), end_dt=datetime(2024, 8, 16, 14, 50)) api = TqApi(backtest=backtest, auth=TqAuth("账户", "密码"), web_gui=web_gui) # qh_code = "SHFE.ni2409" qh_code = 'DCE.p2501' # 获得 m1901 5分钟K线的引用 klines_df = api.get_kline_serial(qh_code, 5 * 60, data_length=15) # 创建 m1901 的目标持仓 task,该 task 负责调整 m1901 的仓位到指定的目标仓位 target_pos = TargetPosTask(api, qh_code) # 默认:以对手价成交 while True: api.wait_update() if api.is_changing(klines_df): print(klines_df.tail(2)) klines_df['datetime'] = klines_df['datetime'].apply(tafunc.time_to_datetime) print(klines_df.tail(2)) ma = sum(klines_df.close.iloc[-15:]) / 15 print('时间:', tafunc.time_to_datetime(klines_df.datetime.iloc[-1]), "最新价", klines_df.close.iloc[-1], "MA", ma) if klines_df.close.iloc[-1] > ma: print("最新价大于MA: 目标多头1手") # 设置目标持仓为多头5手 target_pos.set_target_volume(1) elif klines_df.close.iloc[-1] < ma: print("最新价小于MA: 目标空仓") # 设置目标持仓为空仓 target_pos.set_target_volume(0)