from tqsdk import TqApi, TargetPosTask import json SYMBOL = "SHFE.au1912" NUM = 3 api = TqApi() target_pos = TargetPosTask(api, SYMBOL) position = api.get_position(SYMBOL) quote = api.get_quote(SYMBOL) print("策略开始运行") try: # 读取数据,本策略目标净持仓数 with open("NUM.json", "r") as r: NUM = json.load(r) # 若读取不成功或第一次运行,则按照之前设定的净持仓目标手数运行 except FileNotFoundError: pass print("当前净持仓数:%d, 目标净持仓数: %d" % (position.pos, NUM)) while True: api.wait_update() target_pos.set_target_volume(NUM) if position.pos == NUM: NUM = NUM + 1 break print("当前净持仓数:%d" % position.pos) api.close() # 保存数据,写入下次净持仓手数 with open("NUM.json", "w") as n: json.dump(NUM, n)
参考示例如下