IB API knowledge base IB API knowledge base
IB API knowledge base IB API knowledge base: Essential information for working with the Interactive Brokers API in Python

Understanding IB API knowledge base Python Integration
IB API knowledge base Python programming enables automated trading through Interactive Brokers’ platform. the IB API knowledge base provides programmatic access to market data, order management, and account information. However, the native API presents complexity that challenges many developers. Therefore, understanding common issues and solutions accelerates development significantly.
This IB API knowledge base addresses frequent questions encountered during IB API knowledge base Python implementation. Moreover, it covers API-related topics, trading requirements, and programming considerations. Consequently, developers avoid common pitfalls and implement solutions efficiently. The information derives from real-world implementation experiences across thousands of trading systems.
IBridgePy simplifies IB API knowledge base Python integration by abstracting complexities. Furthermore, it provides intuitive functions replacing low-level API calls. In addition, the platform supports backtesting and live trading seamlessly. As a result, development time decreases dramatically while maintaining full functionality. Visit our documentation for detailed implementation guidance.
IB API knowledge base Python: API Related Questions
Q: Can OrderId be the same as TickerId?
A: They are not related at all. Therefore, the answer is yes. Order IDs track order submissions while Ticker IDs manage market data requests. Consequently, these values operate in separate namespaces without conflicts.
Q: How to reset orderId?
A: Go to API configuration → API → Reset API order ID sequence. This action resets the counter to zero. However, use this feature carefully in production environments to avoid order tracking confusion.
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 shorting. It represents an enum type value corresponding to GREEN, DARK GREEN, and RED in TWS. Moreover, these colors indicate shortability levels visually in the trading platform.
Q: What are the order types?
A: Please refer to https://www.interactivebrokers.co.uk/en/index.php?f=4985. Interactive Brokers supports market, limit, stop, and numerous advanced order types. Furthermore, bracket orders and conditional orders enable sophisticated risk management strategies.
Q: How to test network latency?
A: IB’s server is in Greenwich, CT. You can ping gw1.ibllc.com to measure latency. Lower latency improves execution speed for algorithmic trading strategies. Therefore, server location impacts performance for latency-sensitive strategies.
Q: What does real time data mean?
A: All tickTypes are snapshots within 250 milliseconds. IB relays bid price, ask price, and size 4 times per second. Furthermore, bid size represents the number of shares at the bid price. For US stocks, multiply the number by 100. Volume updates every 250ms with validation checks every 30 seconds. Consequently, volume represents cumulative daily trading volume.
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 that queues data. However, even the buffer has limitations. Therefore, ensure your processing keeps pace with incoming data to avoid buffer overflow and data loss.
Q: How to modify the stop price of the existing stop loss order?
A: Use placeOrder() with the existing order ID. Please refer to the following link. Consequently, the system modifies the order rather than creating a new one.
Q: How to check if a STOP order has executed the STOP limit?
A: You need to examine execution price in the execDetails callback. Moreover, compare it against the stop price to confirm trigger execution. This verification ensures accurate position tracking.
Q: How to obtain the available cash on my account?
A: Use reqAccountUpdates() or reqAccountSummary(). These functions return comprehensive account information including cash balances. Furthermore, they provide buying power and margin details essential for stock trading Python implementations.
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. Python’s GIL can limit multi-core utilization. Therefore, consider process-based parallelism for CPU-intensive calculations.
Q: Can I trade after hours?
A: Include the order attribute outsideRTH. As long as the product trades after market and you use the proper orderType, you can trade post-market. For example, MKT and STP orders only work during regular hours. However, LMT and STP LMT orders function after hours. After-hour trading operates until 20:00. Moreover, options and stocks trade Monday through Friday while futures and forex trade Sunday through Friday.
Q: How do I know which LAST_PRICE corresponds to which LAST_SIZE?
A: Request RTVolume (233) and values return through tickString(). The timestamp measures milliseconds since 00:00:00.000 on 1/1/1970. Consequently, you can match prices with sizes accurately via timestamps.
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 trades report to IB. Typically you see sub-second granularity. Furthermore, if trades consolidate, the single trade flag indicates false. The RTVolume timestamp updates in second units. Therefore, it won’t update more frequently than once per second. For generic tick data, 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 via placeOrder(), you automatically receive openOrder() and orderStatus() callbacks. These provide order details and current status. Moreover, upon execution you receive execDetails() and commissionReport() callbacks. These relay execution details and fees paid. Consequently, you can confirm position ownership by invoking reqAccountUpdates() and monitoring updatePortfolio().
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. When you invoke reqAccountUpdates(), you receive a full batch of updateAccountValue() and updatePortfolio() calls. Furthermore, an accountDownloadEnd tag indicates when the full batch completes.
Q: When are orderStatus() and openOrder() triggered?
A: openOrder() triggers twice automatically. First, when the order is initially accepted. Second, when the order fully executes. Moreover, you get openOrder() and orderStatus() callbacks upon acceptance. Partial fills or status changes trigger additional orderStatus() callbacks. Consequently, when the order fully executes, you receive final orderStatus(), then openOrder(), followed by execDetails() and commissionReport(). If you invoke reqOpenOrders(), it relays only the last orderStatus() of current working orders.
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”. This indicates your order has been accepted at the order destination and is working. After stop loss triggers and fills, status becomes “Filled”.
Q: For a STP order, the status become “Filled” only after stop loss happen?
A: Correct. Once the order fully executes, it relays back status = Filled. Therefore, monitor status changes to track order lifecycle accurately.
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 on whether status changes occur. For marketable orders, immediate execution is possible. In this case, you don’t get status = Submitted. Instead, you only get status = Filled. However, you get status = Submitted then status = Filled if the order isn’t immediately executed and goes to the exchange to be worked. Consequently, when orders immediately fill, you get orderStatus() with status = Filled, followed by openOrders() with order details, then execDetails() and commissionReport() with execution and fee details.
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 cross-related order restrictions. This happens because you’re not a market maker and cannot sell back an order you’re currently buying. Moreover, you need to offset the price to avoid trading your own orders. You can buy and sell the same product but cannot sell an order you’re currently trying to buy. For example, submitting a buy order for 100 shares of XYZ at 12.31 prevents selling 100 shares of XYZ at 12.31 simultaneously because this attempts to trade your own order.
Q: How to buy stocks with a STOP price?
A: You submit two orders. First, open the position. Second, submit the sell stop to close it. Furthermore, the stop order should include the parent order ID. Consequently, the child order doesn’t become eligible until the parent fills. For the child order object: childOrder.action=’SELL’, childOrder.orderType=’STP’, childOrder.auxPrice = xxx, childOrder.parentId = xxx. Moreover, set parent order transmit attribute to false. For child order, assign transmit attribute to true. Therefore, the parent order submits to the exchange first while the child order stores server-side. This approach avoids accidental cancellation or transmitting before linking the child order.
When placing orders with child orders, the parent order needs transmit = false to prevent execution before binding child orders. Furthermore, the first child order leg includes transmit = false and parentOrderId = parent order ID. The second child order includes transmit = true and parentOrderId = parent order ID. Consequently, since both child orders have the parentId, they bind to the parent order. Since the second child order has transmit = true, all three orders 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: This indicates the decimal place for the order price is incorrect. For example, contract XYZ supports a minTick of .01 but you send an order with price 35.013. Consequently, the order is rejected since it doesn’t conform to price variation for the contract. The exchange dictates this and it varies depending on the trading price. There’s a contract search on our website providing it: https://www.interactivebrokers.com/cgi-pub/contractSearch/symbolsearch.pl
Most programmers monitor market data and use decimal places from market data to submit orders. Another possible reason is order price increment is 0.05 but the order price sent 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 IB API knowledge base if you invoke reqGlobalCancel(), it cancels all open orders regardless if the order originated from an API client or TWS. See https://www.interactivebrokers.com/en/software/api/apiguide/java/reqglobalcancel.htm
Regarding flattening existing positions, unfortunately there’s no API function to accomplish this. You need to flatten your positions one at a time by invoking placeOrder(). For example, if you’re long 100 shares of XYZ, you 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 relays all your current positions. acctCode is only relevant for customers with access to more than one account. Furthermore, for Financial Advisors or linked accounts, acctCode would be the Account number. However, if you only have an individual account, leave that parameter set to null. If you have many positions, updatePortfolio() is called multiple times, each time containing info for one position. Moreover, 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 IB API knowledge base?
A: Unfortunately the IB API knowledge base doesn’t have any function to provide short sale restrictions. However, you can identify if a contract is available for shorting or hard to short using an API. Please refer to https://www.interactivebrokers.com/en/software/api/apiguide/tables/using_the_shortable_tick.htm
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 https://www.interactivebrokers.com/en/software/api/apiguide/tables/supported_time_zones.htm
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’ll 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’s an execution and you now own the position. If there’s a status change and the order hasn’t been executed, it won’t fire back the positions() event. This behavior isn’t in the IB API knowledge base 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. Verify exchange routing and primary exchange settings match the security requirements.
Q: Some errorCode not documented at IB
errorCode = 509, error message: Exception caught while reading socket – Connection reset by peer
A non-exhaustive error message list is explained at this webpage: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClientErrors.html
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 exchanges which govern data dissemination and retransmission. Moreover, a given subscription can be associated with only one account or user ID. However, sharing that user ID between different devices is permitted as long as the user ID doesn’t 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 to share market data subscriptions. If concurrent logins on different devices are detected, the live account session receives real-time market data subscriptions and the paper trading account session receives 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 results in additional fees for subscriptions elected, one can maintain a different subscription set from the main user and run 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.
IB API knowledge base Python: Trading Related Questions
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 sources. Therefore, expect variations across providers.
Q: What does volume mean in currency trading?
A: The volume in Currency trading means NOTHING. There’s not a centralized trading center so the volume is simply the volume at one trading firm. Never use volume for your models. For Forex, you’ll 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. Leverage adjustments require account configuration changes through customer service.
Q: Can we use leverage on stocks? What is the margin requirement for Forex and stocks?
A: You need a margin account to leverage. To request a Margin account, log into Account Management and click Manage Account. Then, click Settings → Configure Account → Account Type. Furthermore, if you have over 100,000 equity, you can choose Portfolio Margin. If you have at least 2,000 USD, you can choose Reg T Margin. For Reg T Margin account, stock leverage is 2x and Forex leverage is 40x. Leverage is not adjustable. Moreover, IB uses all available cash first before loaning money on margin. If your account value drops below 2,000 USD, you may not carry any margin loan. If you hold a margin loan, the system immediately liquidates some positions to clear the cash debit balance. This is a Fed Reserve requirement.
SEC Reg T requirement sets a $25k minimum balance on ‘pattern day trading’ accounts. An account is classified as a pattern day trader account if there are 4 or more round trip trades in any 5 consecutive trading day period. Consequently, 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, you cannot 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 IB’s server only takes a few milliseconds. Therefore, the total delay for a market order should be network latency plus milliseconds for validity check. The real bottleneck is 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. This provides comprehensive order history and execution details for verification purposes.
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 use a demo account to test, the order you’re trying to cancel was likely originally placed by another clientId. Consequently, you cannot cancel it. Ensure you track orders by clientId for proper management.
IB API Python: Programming Related Questions
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 occurs if you’re still using pandas v0.16. Therefore, upgrade your pandas installation to resolve this issue.
Q: How differently do the demo account and paper account behave?
A: You won’t receive callbacks from IB server if using demo account. For example, scannerParameters and scannerData. Another example, positions() callback may be skipped when IB server is busy. Moreover, demo account is only used for demo purposes because it behaves differently than a paper account. If you’re developing something serious, it’s highly recommended to use your own paper account. See https://www.interactivebrokers.com/en/software/am/am/manageaccount/paper_trading_limitations.htm
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 to get account updates for all sub-accounts.
As an alternative you can use reqAccountSummary() to request information about multiple accounts. reqAccountSummary() allows any multi-account structure to specify “All” accounts. You can also use reqAccountUpdatesMulti() if you want all key tags. Furthermore, you can specify “All” for that function.
Q: To manage multiple accounts, reqAccountSummary vs reqAccountUpdatesMulti, which one is preferred?
A: It depends what account key values you’re monitoring. If you only need certain key values then reqAccountSummary() is more ideal as you can manually specify which key values you want returned. However, if your program requires all key values then reqAccountUpdatesMulti() would be used.
Q: Will weekends and holidays be counted when using IBApi.EClient.reqHistoricalData?
A: Generally speaking historical data requests relay back the number of trading days. There are some bugs and issues where the exact number of days aren’t relayed back. However, generally we don’t count (or shouldn’t count) weekends for the request.
For example, requesting daily bars for 10 Days for AAPL stock gives bars back from 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 returns 115 hourly bars. Moreover, the first one is Mar 11th 2019 14:15:00 EST, which means it goes back 5 trading days.
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. Consequently, NYSE is NYSE, NYSE/ARCA is ARCA, NYSE/AMEX is AMEX.
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”. Therefore, use UTC timezone for historical data requests.
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 is called back, followed by openOrder. Then, executionDetails and commissionReport are called back. updatePortfolio is the last. Moreover, updateAccountValue will NOT be called back immediately. Instead, it’s called back strictly every 3 minutes with the latest accurate information. The missing of immediate updateAccountValue callback causes an issue where cash value and overall position_value aren’t accurate immediately after order execution and before updateAccountValue is called back. Consequently, the IB recommended method is to use whatIf field of placeOrder to predict the consequences of order execution.
As of 20200820, IB doesn’t reduce availableFunds after limit order is placed, at least for paper account. After market order executes, updateAccountValue is immediately called back. Therefore, there’s no need to handle availableFunds. Consequently, the user should be responsible to manage availableFunds during IBridgePy session.
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. Consequently, the user of IBridgePy doesn’t need to do anything to address it. This represents a temporary connectivity issue that resolves automatically.
Need Help with IB API Python?
Explore our comprehensive resources or connect with our expert development team.
Visit our tutorials, check the Q&A section, or explore about IBridgePy for more information.
