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 successfully connect event
    Trader.Connected += () =>
    {
        this.GuiAsync(() => ChangeConnectStatus(true));
    };
    
    // subscribe on connection error event
    Trader.ConnectionError += error => this.GuiAsync(() =>
    {
        ChangeConnectStatus(false);
        MessageBox.Show(this, error.ToString(), "Ошибка соединения");
    });
    
    // subscribe on successfully disconnect event
    Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
    
    Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), "Data processing error"));
    Trader.NewSecurities += securities => this.GuiAsync(() => _securitiesWindow.AddSecurities(securities));
    Trader.NewTrades += trades =>this.GuiAsync(() => _tradesWindow.Trades.AddRange(trades));
    Trader.NewOrders +=orders => this.GuiAsync(() => _ordersWindow.Orders.AddRange(orders));
    Trader.NewMyTrades += trades => this.GuiAsync(() => _myTradesWindow.Trades.AddRange(trades));
    Trader.NewStopOrders += orders => this.GuiAsync(() => _conditionOrdersWindow.Orders.AddRange(orders));
    Trader.NewMarketDepths += _securitiesWindow.ProcessDepths;
    Trader.MarketDepthsChanged += _securitiesWindow.ProcessDepths;
    Trader.NewCandles += _securitiesWindow.AddHistoricalCandles;
    Trader.NewRealTimeCandle += _securitiesWindow.AddRealTimeCandle;
    
    Trader.NewPortfolios += portfolios =>
    {
        _portfoliosWindow.Portfolios.AddRange(portfolios);
        portfolios.ForEach(Trader.RegisterPortfolio);
    };
    Trader.NewPositions += positions => this.GuiAsync(() => _positionsWindow.Positions.AddRange(positions));
    
    Trader.OrdersRegisterFailed += OrdersFailed;
    
    Trader.OrdersCancelFailed += OrdersFailed;
  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#
    var criteria = new Security
    {
        Currency = CurrencyTypes.USD,
        Code = SecCode.Text,
        Type = (SecurityTypes)SecType.GetSelectedValue<SecurityTypes>(),
    };
    
    if (!BoardName.Text.IsEmpty())
    {
        criteria.ExchangeBoard = ExchangeBoard.GetBoard(BoardName.Text, code =>
            new ExchangeBoard
            {
                Code = code,
                Exchange = new Exchange
                {
                    Name = code
                }
            });
    }
    
    if (!ContractId.Text.IsEmpty())
        criteria.SetContractId(ContractId.Text.To<int>());
    
    MainWindow.Instance.Trader.LookupSecurities(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 QuotesClick(object sender, RoutedEventArgs e)
    {
        if (Quotes.IsChecked == true)
        {
            // create order book window
            var wnd = new QuotesWindow { Title = SelectedSecurity.Code + " quotes" };
            _quotesWindows.Add(SelectedSecurity, wnd);
    
            // subscribe on order book flow
            Trader.RegisterMarketDepth(SelectedSecurity);
    
            wnd.Show();
        }
        else
        {
            Trader.UnRegisterMarketDepth(SelectedSecurity);
    
            var wnd = _quotesWindows[SelectedSecurity];
            _quotesWindows.Remove(SelectedSecurity);
            wnd.Close();
        }
    }
    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 Send_Click(object sender, RoutedEventArgs e)
    {
        var order = new Order
        {
            Type = IsMarket.IsChecked == true ? OrderTypes.Market : OrderTypes.Limit,
            Portfolio = Portfolio.SelectedPortfolio,
            Volume = Volume.Text.To<decimal>(),
            Price = Price.Text.To<decimal>(),
            Security = Security,
            Direction = IsBuy.IsChecked == true ? OrderDirections.Buy : OrderDirections.Sell,
        };
    
        MainWindow.Instance.Trader.RegisterOrder(order);
    
        DialogResult = true;
    }