完整代码如下:
`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)`