1.60K 浏览
0

def my_tar_position_task(api, tar_pos_task, contract, tar_vol, margin_vol_limit=4):
    """
     Parameters
    ----------
    api
    tar_pos_task
    contract
    tar_vol
    margin_vol_limit
     Returns
    -------
     """
    cur_pos = api.get_position(contract)
    new_pos, orders = simulated_trade(cur_pos, tar_vol)
    if new_pos.margin_vol <= margin_vol_limit:
        try:
            tar_pos_task = TargetPosTask(api, contract, offset_priority='昨开')
        except Exception:
            print(traceback.format_exc())
            tar_pos_task.cancel()
            while not tar_pos_task.is_finished():
                api.wait_update()
            tar_pos_task = TargetPosTask(api, contract, offset_priority='昨开')
        tar_pos_task.set_target_volume(tar_vol)
     else:
        tar_pos_task.cancel()
        while not tar_pos_task.is_finished():
            api.wait_update()
         print("tar_pos_task is finished")
        new_tar_pos_task = TargetPosTask(api, contract)
        new_tar_pos_task.set_target_volume(tar_vol)
        print("new_task created")
        api.wait_update()

tqacc = TqKq()
api = TqApi(tqacc, auth=TqAuth('', ''))
contract = 'CFFEX.IM2405'
tar_pos_task = TargetPosTask(api, contract, offset_priority='昨开')
while True:
    api.wait_update()
    my_tar_position_task(api, tar_pos_task, contract, 4, margin_vol_limit=4)

自定义函数的作用是在股指期货交易时判断用 ‘昨开”参数开仓(这种锁仓方式可以节省交易费用)是否满足保证金条件,如果超出了,就重新建一个默认参数的tar_position_task进行下单。如果没有超出保证金限制,就新建一个参数“昨开”的task进行下单。

但是程序貌似在新建new_tar_pos_task之后一直没有成交,一直重复在29和32行,是什么原因?貌似是因为实例化TargetPosTask不能放在循环内,但是在实盘中随时都有可能要新建一个新的task,要怎么修改才能正常运行呢

李思恒 已回答的问题 2024年4月25日