ib_async TWS API仅首个订单传输成功,其余订单未显示求助
解决IB API止盈止损单无法显示在TWS的问题
问题根源
你当前代码中单独提交的止盈(TP)和止损(SL)订单是独立订单,未与主市价单建立关联。IB TWS/API要求这类订单必须关联到主订单作为子订单,否则不会在TWS中正常显示或激活,即便API日志显示订单已创建。
解决方案:将TP/SL设为主订单的附加子订单
通过设置订单的parentId属性,将TP和SL订单绑定到主市价单,同时调整订单的transmit参数,确保三个订单作为一个组被TWS接收,主订单成交后自动激活子订单。
修改后的代码
from ib_async import * ib = IB() ib.connect('127.0.0.1', 7497, clientId=0) def place_order(tradeDirection: str, ticker: str, riskSize: float, entryPrice: float, exitPrice: float): logger.info(f"====== Placing order for {ticker} ======") positionSize = get_position_size(get_risk(riskSize), entryPrice, exitPrice, tradeDirection) contract = Stock(ticker, 'SMART', 'USD') # 生成主订单ID并创建市价单 parent_order_id = ib.client.getReqId() parent_order = MarketOrder(tradeDirection, positionSize) parent_order.orderId = parent_order_id # 计算TP/SL价格并创建子订单 if tradeDirection == "BUY": takeProfitPrice = entryPrice + 2 * (entryPrice - exitPrice) stopLossPrice = exitPrice tp_order = LimitOrder("SELL", positionSize, takeProfitPrice) sl_order = StopOrder("SELL", positionSize, stopLossPrice) elif tradeDirection == "SELL": takeProfitPrice = entryPrice - 2 * (exitPrice - entryPrice) stopLossPrice = exitPrice tp_order = LimitOrder("BUY", positionSize, takeProfitPrice) sl_order = StopOrder("BUY", positionSize, stopLossPrice) # 绑定子订单到主订单,设置传输规则 tp_order.parentId = parent_order_id sl_order.parentId = parent_order_id tp_order.transmit = False # 子订单暂不单独传输 sl_order.transmit = False parent_order.transmit = True # 主订单触发整体传输 # 提交订单组 ib.placeOrder(contract, tp_order) ib.placeOrder(contract, sl_order) ib.placeOrder(contract, parent_order) logger.info(f"Main Order placed: {parent_order}") logger.info(f"TP order placed: {tp_order}") logger.info(f"SL order placed: {sl_order}")
关键修改说明
- 关联主订单ID:通过
parentId将TP/SL订单与主市价单绑定,TWS会识别这是一组关联订单,主订单成交后自动激活子订单。 - 传输控制:设置子订单
transmit=False,确保它们不会被单独发送,直到主订单以transmit=True提交,避免订单分散导致的显示问题。 - 订单ID管理:手动获取并分配主订单ID,确保子订单能准确关联。
额外检查点
- 确认TWS API设置中已开启「允许API发送订单」「允许修改订单」等权限。
- 检查TP/SL价格是否符合IB的价格规则(如股票最小变动单位),不合理的价格会被TWS静默拒绝。
- 主订单成交后,可在TWS的「待处理订单」列表中查看激活的TP/SL订单。
内容的提问来源于stack exchange,提问作者0xLasadie
相关产品推荐
相关产品推荐

