IB API Knowledge Base


Knowledge Base of Interactive Brokers (IB) ‘s API

API related

Q: Can OrderId be the same as TickerId?

A: They are not related at all so that the answer is Yes.

Q: How to reset orderId?

A: Go to API configuration->API->Reset API order ID sequence.

Q: When I use reqMktData(ii, contract, ‘236’, False), it returns TicketType=’46’ value=’3.000000′. Does it mean that there are only 3 shares that I can short?

A: 3 indicates there are at least 1000 shares available for a short sale. It is an enum type value that corresponds to GREEN, DARK GREEN, and RED in TWS.

Q: What are the order types?

A: Please refer to https://www.interactivebrokers.co.uk/en/index.php?f=4985

Q: How to test network latency?

A: IB’s server is in Greenwich, CT. You can ping gw1.ibllc.com

Q: What does real time data mean?

A: all tickType are snapshot within 250 milliseconds, which means IB relays bid price, ask price, ask size… 4 times a second. Bid size – the number of shares bid for bid price. For US stocks, the number is multiplied by 100. The volume also updates every 250 ms and it always check the volume from exchange every 30 seconds to make sure it is identical. Volume means the cumulative volume of the day.

Q: If the new price/size info came in at a time when my computer is busy calculating other things, what will happen? Will the info wait or be lost?

A: It uses a socket connection. It should queue up, however even the buffer has a limitation.

Q: How to modify the stop price of the existing stop loss order?

A: Use placeOrder( ). Please refer to the following link.

Q: How to check if a STOP order has executed the STOP limit?

A: You need to examine execution price.

Q: How to obtain the available cash on my account?

A: Use reqAccountUpdates( ) or reqAccountSummary( )

Q: If my computer has multiple cores and only one core is busy, will the tickPrice() and tickSize() use the other cores?

A: You need to examine hardware logic process and socket communication

Q: Can I trade after hours?

A: Include the order attribute outsideRTH, as long as the product trades after market and you are using the proper orderType, you should be able to trade post market. Example: you can’t send a MKT or STP orders because they are only valid during regular trading hours but you can send LMT and STP LMT orders. After-hour trading is active until 20:00. Options and Stocks only trade Monday – Friday. Futures and Forex trade Sunday – Friday.

Q: How do I know which LAST_PRICE corresponds to which LAST_SIZE?

A: Request RTVolume (233) and the values will be returned through tickString( ). The time is measured in MS since 00:00:00.000 on 1/1/1970.

Q: If 10 trades happened in a second, and I requested RTVolume, would tickString() be triggered 10 times, or IB only updates every 250ms?

A: It depends on how they are reported to IB. Typically you would see sub second granularity. If the trade is consolidated the single trade flag at the end would say false. The time stamp in RTVolume is in the unit of second and it won’t update more often than once every second. If you want to just get generic tick, use “off, 233”.

Q: If I place a STP order, how could I know in API that the stop loss has been executed?

A: When you submit an order from an API using the placeOrder( ) method automatically you would receive an openOrder( ) and orderStatus( ) call back which provides the details of the order and the current status. Once the order has executed you would receive an execDetails( ) and commissionReport( ) which relays back the details of the execution and commission and fee’s paid for the order. You can confirm you own the position by invoking the reqAccountUpdates( ) and monitor the updatePortfolio( ) which will relay all current positions you own.

Q: If I have many positions, will updatePortfolio( ) be trigger multiple times and each time updatePortfolio( ) return one position that I own, or updatePortfolio( ) is triggered once and return an array type of thing that contains everything that I own?

A: Multiple times for each position you own. Please note if you invoke reqAccountUpdates( ), once you receive a full batch of updateAccountValue( ) and updatePortfolio( ), you would receive an accountDownloadEnd tag which will indicate when a full batch as completed.

Q: When are orderStatus( ) and openOrder( ) triggered?

A: openOrder( ) is triggered twice automatically. When the order is initially accepted and when the order is fully executed. When the order is initially accepted, you would get an openOrder( ) and orderStatus( ) call back. Then if there are partial fills or any other status changes you would receive additional orderStatus( ) call back. Then if you receive additional orderStatus( ) call back, when the order fully executes you would get a final orderStatus( ) followed by an openOrder( ) and then receive the execDetails( ) and commissionReport( ). If you invoke reqOpenOrders( ), it will only relay the last orderStatus( ) of any current working order.

Q: For a STP order, after the orders are filled but before the stop loss happened, what would be the status parameter in orderStatus( )? Will it be “Filled”, or “Submitted”, or something else? And after the stop loss happens, what would be the status parameter in orderStatus( )?

A: It should be submitted. Submitted – indicates that your order has been accepted at the order destination and is working.

Q: For a STP order, the status become “Filled” only after stop loss happen?

A: Correct, once the order is fully executed it will then relay back status = Filled.

Q: For a market order when the status will be “Submitted”? For market order once it is accepted the status will be “Filled”, right?

A: It depends if there is a status change. For marketable orders, there is a chance the order can immediately execute. In this case, you would not get status = Submitted, you would only get status = Filled. The only time you get status = Submitted then status = Filled if the order is not immediately executed and is being sent to the exchange to be worked on. If the order immediately fills, then you would get an orderStatus( ) with status = Filled, followed by an openOrders( ) with the details of your order, followed by execDetails( ) with the details of the execution and commissionReport( ) with the details of the fees and commission.

Q: If I place a STP order with orderId of 1, and the STP is submitted and I bought the stocks, but stop loss didn’t happen. Then I submit a SELL order with orderId of 2 to sell the stocks that I bought with the previous STP order. What would be the orderStatus() or orderId 1 and 2?

A: orderId = 2 will be rejected due to a cross related order. This is because you are not a market maker and cannot Sell back an order you are currently buying. You would need to offset the price to make sure you are not trying to trade your own orders. You can buy and sell the same product but you just cannot sell an order you currently trying to buy. Example: if you submit a buy order for 100 shares of XYZ at 12.31 and the order is currently working on the exchange, you cannot send a sell order for 100 shares of XYZ at 12.31 because this will attempt to trade the order you own.

Q: How to buy stocks with a STOP price?

A: You would have to submit two orders: one to open the position, and then the sell stop to close it. The stop order should include the order ID of the parent as well, so that the child order does not become eligible until the parent order fills. Assuming you call your child order object childOrder: childOrder.action=’SELL’, childOrder.orderType=’STP’, childOrder.auxPrice = xxx, childOrder.parentId = xxx. for parent order, please set the transmit attribute of order object to false. For child order, make sure the transmit attribute is assigned to true. Then parent order is submitted to the exchange first and the child order is stored on the server side. The reason of doing this is to avoid accidental cancellation or transmitting before linking the child order.

When placing orders with child order, the parent order will need to have transmit = false included to ensure the order does not execute before you can bind the child orders. Then for the first leg of the child order you would include transmit = false and parentOrderId = the orderId of the parent order. Then the second child order would need to include transmit = true and parentOrderId = the orderId of the parent order. Since both child orders has the parentId it will bind to the parent order and since the second child order has transmit = true automatically all three orders will automatically transmit.

Q: I got the following error message: The price does not conform to the minimum price variation for this contract. What does it mean?

A: That is an indication that the decimal place for the price of the order is not properly set. Example contract XYZ supports has a minTick of .01 but yet you send an order with a price of 35.013. The order will be rejected since this does not conform to the price variation for the contract. This is dictated by the exchange and can vary depending on the price the contract is trading. There is a contract search on our website that provides it:


Most programmers would monitor the market data and use the decimal places from the market data to submit orders.

Another possible reason is that the order price increment is 0.05 but the order price that you send is 20.01.

A convenient function of roundToMinTick in IBridgePy is provided to round a float number.

Q: How can I say “close” all my position, meaning regardless my positions are long or short, I just want to clear all my positions?

A: Through the API if you invoke the reqGlobalCancel( ) method, it will cancel all open orders, regardless if the order originated from an API client or TWS.


Regarding flatten existing positions, unfortunately, there is no API function to accomplish this. You would need to essentially flatten your positions one at a time by invoking placeOrder( ) method. Example: you are long 100 shares of XYZ, you would need to send a Sell Order for 100 shares of XYZ to flatten the position.

Q: How do I check my existing positions? For example, I want to know how many shares that I have on XYZ, is there a way to do that?

A: You can invoke reqAccountUpdates( ). Through the updatePortfolio( ) event, it will relay all your current positions. acctCode is only relevant for customers who has access to more than one account. Like a Financial Advisor or linked account in that case the acctCode would be the Account # but if you only have an individual account then leave that parameter set to null. If you have many positions, the updatePortfolio() will be called multiple times, and each time containing the info for one of my position. The position variable in updatePortfolio() can be either positive or negative to represent Long/Short positions.

Q: If I place an order to short XYZ, but there is no stocks available for me to short, is there a way that I can know it in the API?

A: Unfortunately the API does not have any function to provide short sale restrictions but you can identify if a contract is available for shorting or hard to short using an API, please refer to the following URL


Q: How do I use the “goodTillDate” in order?

A: order.tif = GTD, order.goodTillDate = “YYYYMMDD hh:mm:ss (optional time zone)”. For timezone info, refer to


Q: If the order is placed in TWS and it is pending, the oderId = 0. How can I cancel the pending order using API?

A: You need to log in as clientId =0, then call reqOpenOrder( ), you will find the orderId = a negative number. Then, use the negative orderId to cancel the order.

Q: I found out that position() will be called when the status of any orders change. Is it correct?

A: Only if there is an execution and you now own the position then yes. If there is a status change and the order has not been executed, it will not fire back the positions( ) event. It is not in the API Reference.

Q: No security definition has been found for the request. What can be wrong?

A: When requesting historical data, for example STK, AAPL, USD, the primaryExchange and exchange in the request must be correct.

Q: Some errorCode not documented at IB

errorCode = 509, error message: Exception caught while reading socket – Connection reset by peer

A non-exhausted error message list is explained at this webpage.


Q: no market data during competing live session

A: To quote from IB:

Market Data Considerations for the Paper Trading Account

As a licensed distributor of exchange market data, IB is obligated to respect constraints imposed by the exchanges which serve to govern the dissemination and/or retransmission of this data. As a general rule, a given >subscription can be associated with only one account or user ID, although the sharing of that user ID between different devices (e.g., stand-alone PC, smart phone) is permitted as long as the user ID does not access multiple devices simultaneously.

Accordingly, clients seeking to simultaneously operate both live and paper trading account TWS sessions must do so on the same device in order to share a given market data subscription. If concurrent logins on >different devices are detected, the live account session will be afforded the real-time market data subscriptions and the paper trading account session delayed data, as available.

Clients who wish to run multiple sessions on different devices may do so by opening a second user for their existing account. While this approach will result in additional fees for any subscriptions elected, one would be >able to maintain a different subscription set from that of the main user and will then be capable of running simultaneous live and paper trading account sessions on different devices. Moving forward, an option will be >provided whereby the same fee-based subscriptions will be offered for the paper trading account independent of those elected in the live account.


Trading related

Q: Why is the daily volume obtained by IB very different from those obtained from Yahoo Finance and Google Finance? For example, IB reported ‘AAPL’ [‘20140320’], close = 528.7, volume = 86164, however Yahoo Finance reports ~7.5M volume on the same day

A: The volume reported by IB is the real trading volume divided by 100 for US stocks. Also, IB, Yahoo Finance and Google Finance use different data source.

Q: What does volume mean in currency trading?

A: The volume in Currency trading means NOTHING, because there is not a centralized trading center so that the volume is simply the volume at one of the trading firms. Never use volume for your models. For Forex, you will never get tickType=8

Q: How to set leverage in currency trading at IB?

A: You cannot set in API. You need to talk to IB representative to reset it.

Q: Can we use leverage on stocks? What is the margin requirement for Forex and stocks?

A: You need to have a margin account in order to leverage. To request a Margin account, log into Account Management and click on Manage Account. Then, click on Settings –> Configure Account –> Account Type. If you have over 100,000 equity, then you can choose Portfolio Margin. If you have at least 2,000 USD, then you can choose Reg T Margin. For Reg T Margin account, stock leverage is 2x and Forex leverage is 40x. Leverage is not adjustable. IB will use all available cash first before loaning any money to you on margin. If your account value drops below 2,000 USD, then you may not carry any margin loan. If you are holding a margin loan, our system would immediately liquidate some positions to clear the cash debit balance.That is a Fed Reserve requirement.

SEC Reg T requirement – the SEC sets a $25k minimum balance on ‘pattern day trading’ accounts. An account will be classified as a pattern day trader account if there are 4 or more round trip trades in any 5 consecutive trading day period. That means if you want to trade DAILY, you need at least $25K in the account. If your account is designated as a PDT and your account is valued below $25,000,then you will not be able to open a new position for 90 days.

Q: How long does it take for a market order to go through?

A: validity check program on the IB’s server only takes a few milliseconds. So, the total delay for a market order I should expect is my network latency + the milliseconds it takes to do validity check. The real bottleneck will be network latency.

Q: Is there any log file in TWS that I can see what order I actually submitted, and how it is executed?

A: Account > Audit Trail. Audit trail should be GMT.

Q: How to define a BOND?

#contract = IBCpp.Contract() #contract.secType = ‘BOND’ #contract.exchange = ‘SMART’ #contract.currency = ‘USD’ #contract.symbol = ‘IBCID45650902’ #contract.conId = 37926925 #self.request_data(ReqData.reqContractDetails(contract))

Q: What does this error means errorCode 10147 “that needs to be cancelled is not found”?

A: If you are using a demo account to test, it is very likely that the order that you are trying to cancel was originally placed by another clientId. It means you cannot cancel it.

Rent-a-Coder helps!

Programming related

Q: series.resample(‘3T’).last() is used to down-convert historical data but  got error “last() takes exactly 2 arguments (1 given)”

A: .last( ) method started from Pandas v0.18 The error jumps out if you are still using pandas v0.16

Q: How differently do the demo account and paper account behave?

A: You will not receive callback from IB server if you are using demo account. For example, scannerParameters and scannerData. Another example, positions( ) callback may be skipped when IB server is busy. In general, demo account is only used for demo purposes because it behaves differently than a paper account. If you are developing something serious, it is highly recommend to user your own paper account.


Rent-a-Coder helps!

Q: Can I request multiple reqAccountUpdates at one time?

A: No, reqAccountUpdates() requires one specific account to be specified. The only exception is if you have a Financial Advisor Account structure from the Master Account you can specify the F-Account number with an “A” at the end of it to get account updates for all sub-accounts.

As an alternative you can use the method reqAccountSummary() to request information about multiple accounts. reqAccountSummary() would allow any multi-account structure to specify “All” accounts.

You can also use reqAccountUpdatesMulti() if you want all key tags as well, yes you can specify “All” for that function.

Rent-a-Coder helps!

Q: To manage multiple accounts, reqAccountSummary vs reqAccountUpdatesMulti, which one is preferred?

A: It really depends what account key values are you monitoring. If you only need certain key values then the function reqAccountSummary() would be more ideal as you can manually specify which key values you want to be returned. If your program requires all key values then reqAccountUpdatesMulti() would be used.

Rent-a-Coder helps!

Q: Will weekends and holidays be counted when using IBApi.EClient.reqHistoricalData?

A: Generally speaking historical data requests would relay back the number of trading days. There are some bugs and issues where the exact number of days are not relayed back but generally speaking we don’t count (or shouldn’t count) weekends for the request.

For example I just tested requesting daily bars for 10 Days for APPL stock and it gave me the bars back to Aug 22 to Sep 5th (10 trading days).

For other barSize like “1 hour”, goBack = “5 D” from Mar 18 2019 12:00:00 EST, it returned 115 hourly bars and the first one is Mar 11th 2019 14:15:00 EST, which means it goes back 5 trading days.

Rent-a-Coder helps!

Q: I requested STK, , NASDAQ,TSLA,USD but saw this error “No security definition found”

A: Exchange = Destination, IB is an electronic broker and we route requests to the ECN, for NASDAQ that is ISLAND.  Anytime you want to send a request for NASDAQ make sure to specify ISLAND.

Generally speaking,  NASDAQ is the odd one. So NYSE is NYSE, NYSE/ARCA is ARCA, NYSE/AMEX is AMEX

Rent-a-Coder helps!

Q: Why I got Historical data query end date time string is invalid?

[20181013 12:32:10 EDT] looks pretty normal but IB server complains that “Historical data query end date/time string [20181013 12:32:10 EDT] is invalid. The root cause is the timezone of “EDT”. It worked if the timezone is changed to “UTC”

Rent-a-Coder helps!

Q: What functions will be called back from IB server and what is the sequence of call backs after an order is executed?

A: At first, openStatus will be called back, followed by openOrder. Then, executionDetails and commissionReport will be called back. updatePortfolio will be the last. updateAccountValue will NOT be called back immediately. Instead, it will be called back strictly every 3 minutes with the latest accurate information. The missing of immediate updateAccountValue call-back causes an issues that the cash value and overall position_value are not accurate immediately after an order is executed and before updateAccountValue is called back. The IB recommended method is to use whatIf field of placeOrder to predict the consequences of an order execution. However, IBridgePy’s solution is to use called-back information in execDetails to temporarily update the account cash value and position_value, which will be ultimately and correctly updated by regular updateAccountValue call-backs.

Rent-a-Coder helps!

Q: errorCode = 2105, error message: HMDS data farm connection is broken:fundfarm What does it mean?

A: It means that IB Gateway / IB TWS lose connection to IB’s data server. IB Gateway / IB TWS will get re-connected automatically. The user of IBridgePy does not need to do anything to address it.