Connect & Start Connection

View as MarkdownOpen in Claude

After creating the class object reference with sync wrapper, connect_and_start() must be used to connect the Python program with the active Trader Workstation implementation. Identical to EClient’s connect() function, connect_and_start() supports arguments for host, port, and client_id.

connect_and_start(

host: String. Determine the connecting host IP for the API to connect to. Connections on the same computer should use “localhost” or “127.0.0.1”.

port: Integer. Determine the connecting port number configured in the Global Configuration in the “Socket Port” field.

Defaults: {TWS Live: 7496; TWS Paper: 7497; IBG Live: 4001; IBG Paper: 4002′}

client_id: Integer. Determine the connecting client ID. TWS Supports up to 32 simultaneous API connections.

Users should connect with a client_id of 0 for [optimal order management functionality](/tws-api/doc/order-management/client-id-0-and-the-master-client-id).

)

app.connect_and_start(host="127.0.0.1", port=7496, client_id=0)

Response Object

While it is not necessary to handle the response from connect_and_start(), the function will return the result of EClient.isConnected() to help with connection validation.

The function call will return a single Boolean value, True or False, in reference to the connection status at the time of reference.

Developers may look to implement code such as this that will gracefully handle the connection procedure should it fail to connect rather than proceeding with the rest of the code implementation.

# Connect to TWS
# If the connection succeeded, notify the user.
# If the connection fails and False is returned, notify the user and gracefully exit the application.
if not app.connect_and_start(host="127.0.0.1", port=7496, client_id=0):
print("Failed to connect to TWS")
exit(1)
else:
print("Connected to TWS")