订阅tick数据,while中执行
api.wait_update()
后立即下单
api.insert_order(symbol=SYMBOL, direction="BUY", offset="OPEN", volume=1, limit_price=buy_open_price)
会陷入死循环,tick数据不会推进。具体见以下可复现代码:
from datetime import date import sys import time import numpy as np from tqsdk import TqApi, TqAccount, TargetPosTask, BacktestFinished, TqBacktest, TqSim, tafunc def test3(): api = None ticks = None SYMBOL = "SHFE.fu1909" target_pos = None try: api = TqApi(backtest=TqBacktest(start_dt=date(2019, 4, 5), end_dt=date(2019, 7, 9))) ticks = api.get_tick_serial(symbol=SYMBOL, data_length=8964) target_pos = TargetPosTask(api, SYMBOL) pass except Exception as e: print("进入Exception") pass try: start_time = time.time() max_oi = 10 count_oi = 0 while True: sys.stdout.flush() api.wait_update() tick_datetime_str = tafunc.time_to_str(ticks.iloc[-1]["datetime"]) h_m_s = (tick_datetime_str.split(" ")[-1]).split(".")[0] if h_m_s == "09:00:00" or h_m_s == "21:00:00": print("elapse time:", time.time() - start_time) start_time = time.time() #continue print("ticks datetime:%s tick_last_price:%f" % ( tafunc.time_to_datetime(ticks.iloc[-1]["datetime"]), ticks.iloc[-1]["last_price"])) print("ticks datetime:%s tick_last_price:%f" % ( tafunc.time_to_datetime(ticks.iloc[-2]["datetime"]), ticks.iloc[-2]["last_price"])) print("ticks datetime:%s tick_last_price:%f" % ( tafunc.time_to_datetime(ticks.iloc[-3]["datetime"]), ticks.iloc[-3]["last_price"])) print("ticks datetime:%s tick_last_price:%f" % ( tafunc.time_to_datetime(ticks.iloc[-4]["datetime"]), ticks.iloc[-4]["last_price"])) sys.stdout.flush() buy_open_price = ticks.iloc[-1]["last_price"] + 1 if count_oi < max_oi: order = api.insert_order(symbol=SYMBOL, direction="BUY", offset="OPEN", volume=1, limit_price=buy_open_price) count_oi += 1 sys.stdout.flush() #target_pos.set_target_volume(1) sys.stdout.flush() except BacktestFinished as e: api.close() print("进入BacktestFinished") pass return 123 for _ in range(5): ret = 0 try: test3() except Exception as e: print("Exception!!!!!!!!!!") print(test3())
zhengyk 发表新评论 2021年6月15日
一年多了,有改进了吗
https://doc.shinnytech.com/tqsdk/latest/usage/backtest.html#backtest
已经找到解答。
如下:
回测框架的规则是当没有新的事件需要用户处理时才推进到下一个行情, 也就是这样:
q = api.get_quote(“SHFE.cu1901”)
api.wait_update() # 这个 wait_update 更新了行情
api.insert_order(“SHFE.cu1901”, …) # 程序下单
api.wait_update() # 这个 wait_update 只会更新委托单状态, 行情还是停在原处
api.insert_order(“SHFE.cu1901”, …) # 如果又下了一个单
api.wait_update() # 这个 wait_update 还是只会更新委托单状态, 行情还是停在原处
api.wait_update() # 这个 wait_update 更新了行情