跳转到内容

订单状态

orderStatus() 是订单状态变化的核心回调。提交订单、部分成交、撤单、完全成交、失效等状态变化,都可能通过它返回。

它不一定只在你主动请求订单时出现。只要 API 客户端能看到某个订单,TWS 就可能推送相关状态。

def orderStatus(
self,
orderId,
status,
filled,
remaining,
avgFillPrice,
permId,
parentId,
lastFillPrice,
clientId,
whyHeld,
mktCapPrice,
) -> None:
...
字段中文说明
orderIdAPI 客户端订单编号。
status订单状态,例如 PreSubmittedSubmittedCancelledFilled
filled已成交数量。可能是 Decimal,保存前可转换为数值。
remaining剩余未成交数量。
avgFillPrice平均成交价。未成交时通常为 0。
permIdIBKR 永久订单编号,适合跨客户端、跨会话追踪订单。
parentId父订单 ID,括号单、条件单等会用到。
lastFillPrice最近一次成交价。没有成交时通常为 0。
clientId订单所属 API 客户端编号。
whyHeld订单被暂挂的原因。为空不代表一定有问题。
mktCapPrice市价保护价格。某些订单被价格保护限制时会出现。
def orderStatus(
self,
orderId,
status,
filled,
remaining,
avgFillPrice,
permId,
parentId,
lastFillPrice,
clientId,
whyHeld,
mktCapPrice,
) -> None:
update_order_status(
order_id=orderId,
status=status,
filled=float(filled),
remaining=float(remaining),
average_fill_price=avgFillPrice,
permanent_id=permId,
parent_id=parentId,
last_fill_price=lastFillPrice,
client_id=clientId,
why_held=whyHeld,
market_cap_price=mktCapPrice,
)
ORDER_STATUS_ROWS=6
ORDER_STATUS=orderId=22;status=PreSubmitted;filled=0;remaining=1;avgFillPrice=0.0;permId=1466795658;clientId=98400;whyHeld=
ORDER_STATUS=orderId=22;status=Submitted;filled=0;remaining=1;avgFillPrice=0.0;permId=1466795658;clientId=98400;whyHeld=
ORDER_STATUS=orderId=22;status=Cancelled;filled=0;remaining=1;avgFillPrice=0.0;permId=1466795658;clientId=98400;whyHeld=

这是一笔模拟账户 AAPL 限价单的生命周期:先被接受,随后进入提交状态,最后被撤单。filled=0remaining=1 说明它没有成交,只是订单生命周期结束。

同一状态可能重复出现,这在 TWS API 中很常见。程序应该按 orderId 更新状态,而不是把每条状态回调都当成一笔新订单。

  1. openOrder() 保存订单静态字段。
  2. orderStatus() 更新成交进度和状态。
  3. execDetails() 保存真实成交。
  4. commissionAndFeesReport() 补充费用。

orderStatus() 对界面展示很有用,但不要把它当成最终成交凭证。真实成交流水仍然要以 execDetails() 为准。