This website uses cookies to collect usage information in order to offer a better browsing experience. By browsing this site or by clicking on the "ACCEPT COOKIES" button you accept our Cookie Policy.

Duration: 13:53

Instructor:

Contributor: Interactive Brokers

Level: Intermediate

This lesson will explore the essential components of a TWS API Python program. This includes the API classes EClient and EWrapper, a function call to create a connection to TWS, and a run loop for processing returned messages in the queue. We’ll walk through a simple “Hello World” example which implements each of these components in order to send a query for details about a financial instrument and then print received details to the console. We’ll then discuss the more comprehensive sample program “Program.py” which is included with the API download and shows the syntax of all API functions.

Read More

Study Notes:

What are essential components of an API program?

  • A main class which derives from both EClient and EWrapper.
  • An initial connection call to TWS. (This automatically launches a separate thread which reads messages and places those messages into a queue.)
  • API function calls to request market data, place orders, receive account values, etc.
  • A run loop which processes messages in the queue and invokes the correct functions in EWrapper.
  • Callback functions in EWrapper which are overridden to handle returned data from TWS.

“Hello World” using the TWS Python API example:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

    def contractDetails(self, reqId, contractDetails):
        print("contractDetails: ", reqId, " ", contractDetails)


def main():
    app = TestApp()

    app.connect("127.0.0.1", 7497, 0)  # Should be a pause afterwards before invoking functions

    contract = Contract()
    contract.symbol = "AAPL"
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqContractDetails(1, contract)

    app.run()


if __name__ == "__main__":
    main()

Connecting to the socket-based TWS API

Which function is used to initiate the connection?

connect().

What parameters does this function require?

The IP address, socket port, and client ID

What are common reasons why an API program can’t connect?

(1) TWS (or IB Gateway) is not running,

(2) TWS does not have setting to enable the API checked, or

(3) TWS is configured to list on a different socket port.

Is it possible to have multiple API connections to one TWS (or IB Gateway) session at once?

Yes, by using different client IDs with each API program.

Is it possible to run multiple TWS sessions on the same computer with the API enabled?

Yes, by using different socket port numbers for each API program.

Should API functions be called immediately after invoking the connect function?

No, there should be a brief pause as the program waits for automatic callbacks such as nextValidId which indicate the initial connection is complete.

Running the Python sample program from IB, Program.py

Disclosure: Interactive Brokers

The analysis in this material is provided for information only and is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad-based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation by IBKR to buy, sell or hold such investments. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

Supporting documentation for any claims and statistical information will be provided upon request.

Any stock, options or futures symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

Disclosure: API Examples Discussed

Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.

trading top