如何通过Interactive Brokers TWS API获取未提交订单?
问题:如何通过IB API获取未提交的草稿订单
我有一段能打印已提交订单的脚本,但无法获取尚未提交的草稿订单(即TWS中还未点击“T”按钮提交的订单)。尝试使用reqAllOpenOrders()方法,但它仅返回已提交到服务器的活跃订单。相关代码如下:
from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract import threading import time import requests class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def openOrder(self, orderId, contract, order, orderState): print('Open Order: simbol-{:s} secType-{:s}. Type: orderType-{:s} action-{:s} at trailStopPrice-{:f}'. format(contract.symbol, contract.secType, order.orderType, order.action, order.trailStopPrice )) def run_loop(): app.run() app = IBapi() app.connect('127.0.0.1', 7497, 123) # 启动线程处理Socket通信 api_thread = threading.Thread(target=run_loop, daemon=True) api_thread.start() time.sleep(1) # 等待与服务器建立连接 app.reqAllOpenOrders() time.sleep(1) # 等待订单数据返回 app.disconnect()
解决方法
reqAllOpenOrders()仅从IB服务器拉取已提交的活跃订单,要获取TWS本地的未提交草稿订单,需要使用以下方式:
1. 使用reqOpenOrders()获取本地订单
调用reqOpenOrders()方法可以请求TWS发送所有本地存储的订单,包括未提交的草稿,这些订单会通过openOrder回调返回。
2. 通过订单状态区分已提交/未提交订单
在openOrder回调中,可通过orderState.status判断订单状态:
PendingSubmit:订单已创建但未提交到服务器PreSubmitted:订单已提交但未被服务器确认Submitted:已提交到服务器的活跃订单
修改后的代码示例
from ibapi.client import EClient from ibapi.wrapper import EWrapper from ibapi.contract import Contract import threading import time class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def openOrder(self, orderId, contract, order, orderState): # 判断订单是否为未提交草稿 status = orderState.status order_type = "未提交草稿订单" if status in ["PendingSubmit", "PreSubmitted"] else "已提交订单" print(f'{order_type}: 标的-{contract.symbol} 类型-{contract.secType} | 订单类型-{order.orderType} 操作-{order.action} 跟踪止损价-{order.trailStopPrice:.2f}') def openOrderEnd(self): print("所有订单获取完成") def run_loop(): app.run() app = IBapi() app.connect('127.0.0.1', 7497, 123) # 启动线程处理Socket通信 api_thread = threading.Thread(target=run_loop, daemon=True) api_thread.start() time.sleep(1) # 等待连接建立 # 请求获取本地所有订单(含未提交草稿) app.reqOpenOrders() # 开启自动接收订单更新(可选,实时获取新创建的草稿订单) app.reqAutoOpenOrders(True) time.sleep(2) # 等待订单数据返回 app.disconnect()
额外说明
- 确保TWS的API设置中已开启“允许本地连接”,并勾选“连接时下载订单”选项,避免权限问题。
openOrderEnd回调会在所有订单发送完毕后触发,可用于确认订单获取流程结束。
内容的提问来源于stack exchange,提问作者Sergei
相关产品推荐
相关产品推荐

