Search code examples
c#interactive-brokerstws

IB TWS API C# foreach symbol get Level II


I try to get Level II for list of symbols:

IBApi.Contract contract = new IBApi.Contract();
List<IBApi.TagValue> mktDataOptions = new List<IBApi.TagValue>();

int Ticker = 1;

foreach (var line in File.ReadLines(textBox1.Text))
{
     contract.Symbol = line;
     contract.SecType = "STK";
     contract.Exchange = "SMART";
     contract.Currency = "GBP";
            
     ibClient.ClientSocket.reqMarketDepth(Ticker, contract, 5, true, new List<TagValue>());

     ibClient.ClientSocket.cancelMktDepth(Ticker, false);

     Ticker++;
}

and after 3 symbols I get error:

Code: 309, Msg: Max number (3) of market depth requests has been reached.

Why, so Im using cancelMktDepth for stop data?

Thanks for help!

Marc Jone


Solution

  • If you press the keys [Ctrl][Alt]= in TWS, a small window will popup letting you know your current limitations for data requests. It appears you have 3 depth requests available (default).

    Looking at your code, there is no delay between requesting the data and cancelling it. It is likely the requests just don't have time to be processed.

    Also Level2 is constantly updated via a 'Add' 'Update' 'Delete' model, so you will not receive the entire table at once.

    You may find the following useful;

    private readonly List<DeepBookMessage> bids, asks;
    
    
    private void Recv_UpdateMktDepth(DeepBookMessage msg)
    {
        List<DeepBookMessage> book = msg.Side == 0 ? asks : bids;
    
        switch(msg.Operation)
        {
            case 0:   // 0 = Insert quote in new position
                book.Insert(msg.Position, msg);
                break;
            case 1:   // 1 = Update quote in existing position
                while(book.Count < msg.Position) 
                    book.Add(new(-1, -1, -1, msg.Side, -1, -1, "", true));
                book[msg.Position] = msg;
                break;
            case 2:   // 2 = Delete current quote. Make sure we have a quote at this level
                if(book.Count > msg.Position) book.RemoveAt(msg.Position);
                break;
        }
    }