Click or drag to resize

Getting started

The application SampleIB shows an example of working with InteractiveBrokersTrader, as shown in the figure below. The example source code is in the Samples/InteractiveBrokers folder of the installation package.

ib main window
  1. First, you need to create an instance of the InteractiveBrokersTrader:

    C#
    Trader = new InteractiveBrokersTrader {
        Address = Address.Text.To<IPEndPoint>(),
    };
  2. Then you should to subscribe on required IConnector events:

    C#
    // subscribe on connection successfully event
    Trader.Connected += () =>
    {
        this.GuiAsync(() => ChangeConnectStatus(true));
    
        // subscribe on news
        Trader.RegisterNews();
    };
    
    // subscribe on connection error event
    Trader.ConnectionError += error => this.GuiAsync(() =>
    {
        ChangeConnectStatus(false);
        MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
    });
    
    Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
    
    // subscribe on error event
    Trader.Error += error =>
        this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
    
    // subscribe on error of market data subscription event
    Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
        this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
    
    Trader.NewSecurity += security => _securitiesWindow.SecurityPicker.Securities.Add(security);
    Trader.NewMyTrade += trade => _myTradesWindow.TradeGrid.Trades.Add(trade);
    Trader.NewTrade += trade => _tradesWindow.TradeGrid.Trades.Add(trade);
    Trader.NewOrder += order => _ordersWindow.OrderGrid.Orders.Add(order);
    Trader.NewStopOrder += order => _conditionOrdersWindow.OrderGrid.Orders.Add(order);
    
    Trader.NewPortfolio += portfolio =>
    {
        _portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio);
        Trader.RegisterPortfolio(portfolio);
    };
    Trader.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position);
    
    // subscribe on error of order registration event
    Trader.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail;
    // subscribe on error of order cancelling event
    Trader.OrderCancelFailed += OrderFailed;
    
    Trader.MassOrderCancelFailed += (transId, error) =>
        this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
    
    Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news);
  3. Then you need to connect to Interactive Brokers server:

    C#
    Trader.Connect();
  4. Once connected, you can expect to trigger events:

  5. Instruments search (in more details):

    ib securities
    C#
    private void FindClick(object sender, RoutedEventArgs e)
    {
        var wnd = new SecurityLookupWindow { Criteria = new Security { Code = "AAPL", Type = SecurityTypes.Stock } };
    
        if (!wnd.ShowModal(this))
            return;
    
        Trader.LookupSecurities(wnd.Criteria);
    }

    If instruments with specified criteria are not found, then the error returns through the Error event:

    ib security not found
  6. For updates on the selected instrument you need to call RegisterSecurity(Security) method:

    C#
    Trader.RegisterSecurity(SelectedSecurity);
  7. To request updates on the order books you need to use the RegisterMarketDepth(Security) method:

    C#
    private void DepthClick(object sender, RoutedEventArgs e)
    {
        foreach (var security in SecurityPicker.SelectedSecurities)
        {
            var wnd = _quotesWindows.TryGetValue(security);
    
            if (wnd == null)
            {
                // create order book window
                wnd = new QuotesWindow
                {
                    Title = security.Id + " " + LocalizedStrings.MarketDepth
                };
                _quotesWindows.Add(security, wnd);
    
                // subscribe on order book flow
                Trader.RegisterMarketDepth(security);
    
                wnd.Show();
            }
            else
            {
                Trader.UnRegisterMarketDepth(security);
    
                _quotesWindows.Remove(security);
    
                wnd.Close();
            }
    
            if (!_mdInitialized)
            {
                TraderOnMarketDepthChanged(Trader.GetMarketDepth(security));
                Trader.MarketDepthChanged += TraderOnMarketDepthChanged;
                _mdInitialized = true;
            }
        }
    }
    ib market depth
  8. For orders registration the New Order button used. The RegisterOrder(Order) method sends an order to the server:

    C#
    private void NewOrderClick(object sender, RoutedEventArgs e)
    {
        var newOrder = new OrderWindow
        {
            Order = new Order { Security = SelectedSecurity },
            SecurityProvider = Trader,
            MarketDataProvider = Trader,
            Portfolios = new PortfolioDataSource(Trader),
        };
    
        if (newOrder.ShowModal(this))
            Trader.RegisterOrder(newOrder.Order);
    }