VeighNa量化社区
你的开源社区量化交易平台
Member
加入于:
帖子: 23
声望: 0

我想做一个止损程序,用script_trader,但这个程序要针对所有期货合约,由于合约太多,所以我不想一开始就订阅行情,希望能够在判断有持仓后,才订阅行情,然后再根据行情来判断是否要止损。

我写了如下一些代码,然后实际运行中,却无法获得行情,返回的tick为None,哪位大神帮忙看看是什么问题?

engine.connect_gateway(ctp_setting, "CTP")
subscribe_list = []
while True:
positions = engine.get_all_positions(use_df=False)
for item in positions:
volume = item.volume
if volume != 0:
if vt_symbol not in subscribe_list:
engine.subscribe(vt_symbol)
subscribe_list.append(vt_symbol)
tick = engine.get_tick(vt_symbol=vt_symbol)

以上最后一句,tick总是取不到。

Member
加入于:
帖子: 23
声望: 0

完整代码如下:

`engine.connect_gateway(ctp_setting, "CTP")
sleep(10)
subscribe_list = []
mindiff_dict = {}
ContractMultiplier_dict = {}

# 持续运行
while True:
    positions = engine.get_all_positions(use_df=False)
    for item in positions:
        volume = item.volume
        if volume != 0:
            vt_symbol = item.vt_symbol
             if vt_symbol not in subscribe_list:
                 engine.subscribe(vt_symbol)
                 subscribe_list.append(vt_symbol)
                 contract = engine.get_contract(vt_symbol)
                 mindiff_dict[vt_symbol] = contract.pricetick
                 ContractMultiplier_dict[vt_symbol] = contract.size
                 sleep(2)
            mindiff = mindiff_dict[vt_symbol]
            ContractMultiplier = ContractMultiplier_dict[vt_symbol]
            # print(item.pnl, mindiff*ContractMultiplier*volume)
            tick = engine.get_tick(vt_symbol=vt_symbol)
            if not tick:
                print("no tick")
                continue
            if item.pnl < -mindiff*ContractMultiplier*volume:
                direction = item.direction
                frozen = item.frozen
                print(vt_symbol, direction, volume, frozen)
                if frozen > 0:
                    active_orders = engine.get_all_active_orders()
                    for item in active_orders:
                        if item.vt_symbol == vt_symbol:
                            vt_orderid = item.vt_orderid
                            engine.cancel_order(vt_orderid)
                    pass
                else:
                    if direction == Direction.LONG:
                        engine.sell(vt_symbol, tick.limit_down, volume)
                    else:
                        engine.cover(vt_symbol, tick.limit_up, volume)

    # 等待3秒进入下一轮
    sleep(3)`
Member
avatar
加入于:
帖子: 1401
声望: 92

订阅后要等待服务器数据推送过来,才会有行情能get_tick获取到。

所以subscribe后要等一段时间,另外subscribe函数的入参是vt_symbols合约代码列表,而不是单一的合约代码字符串

Member
加入于:
帖子: 23
声望: 0

多谢回答

© 2015-2022 上海韦纳软件科技有限公司
备案服务号:沪ICP备18006526号

沪公网安备 31011502017034号

【用户协议】
【隐私政策】
【免责条款】