You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IB TWS API C#获取订单限价:已知Order Id求代码示例

用C#通过IB TWS API根据订单ID获取限价(LmtPrice)

要获取指定订单ID的限价,核心是通过API请求订单详情,在回调方法中接收并提取Order对象的LmtPrice属性。以下是完整的可运行代码示例:

代码实现

using IBApi;
using System;
using System.Collections.Generic;

public class TwsOrderClient : EWrapper
{
    private readonly EClientSocket _twsSocket;
    private readonly Dictionary<int, Order> _orderCache = new Dictionary<int, Order>();
    private int _targetOrderId;

    public TwsOrderClient()
    {
        _twsSocket = new EClientSocket(this);
        // 连接到本地TWS/IB网关,根据实际情况修改端口和客户端ID
        _twsSocket.eConnect("127.0.0.1", 7497, 1);
    }

    // 接收订单详情的回调方法
    public override void openOrder(int orderId, Contract contract, Order order, OrderState orderState)
    {
        // 缓存订单,方便后续根据ID查找
        if (_orderCache.ContainsKey(orderId))
            _orderCache[orderId] = order;
        else
            _orderCache.Add(orderId, order);

        // 匹配目标订单ID,提取限价
        if (orderId == _targetOrderId)
        {
            if (order.LmtPrice > 0)
                Console.WriteLine($"订单ID {_targetOrderId} 的限价: {order.LmtPrice}");
            else
                Console.WriteLine($"订单ID {_targetOrderId} 非限价订单,无有效LmtPrice");
        }
    }

    // 发起订单查询请求
    public void GetOrderLimitPrice(int targetOrderId)
    {
        _targetOrderId = targetOrderId;
        // 请求所有未成交订单,回调会返回每个订单的详情
        _twsSocket.reqOpenOrders();
    }

    // 必须实现的EWrapper空方法(避免编译错误)
    public override void error(int id, int errorCode, string errorMsg) {}
    public override void nextValidId(int orderId) {}
    public override void contractDetails(int reqId, ContractDetails contractDetails) {}
    public override void orderStatus(int orderId, string status, double filled, double remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld, double mktCapPrice) {}
    // 其他未实现的EWrapper方法均需添加空实现
}

// 调用示例
class Program
{
    static void Main(string[] args)
    {
        var client = new TwsOrderClient();
        // 替换为你需要查询的订单ID
        client.GetOrderLimitPrice(123);

        // 保持程序运行,等待API回调返回结果
        Console.ReadLine();
        client._twsSocket.eDisconnect();
    }
}

关键说明

  • 连接配置:根据你的TWS/IB网关类型(实时/模拟)修改端口号,默认模拟账户端口7497,实时账户7496;IB网关模拟端口4002,实时4001。
  • 订单缓存:用字典缓存所有订单,方便后续多次查询同一订单时直接读取,无需重复请求。
  • 限价判断:只有限价订单的LmtPrice会返回有效值,市价订单的该属性通常为0,需要做判断避免误解。
  • 权限设置:确保TWS/IB网关已开启API接入权限(在TWS设置中勾选"Enable Active X and Socket Clients")。

内容的提问来源于stack exchange,提问作者Globe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:25:40