IntroductionCopy Location
Copy Location
Beginning with TWSAPI version 10.35.01, Interactive Brokers has begun to produce the TWS API using Google’s Protocol Buffer. As a result, many new objects are produced using protocol buffer classes directly that developers will need to utilize and understand in order to produce effective code that can access all systems provided by the TWSAPI.
Users unfamiliar with Protocol Buffers should visit the official development page for more insight on what it is, what it may offer, and context for the built-in systems it provides.
Important Protobuf FunctionsCopy Location
Copy Location
When interacting directly with protobuf classes, proto-specific functions need to be used.
CopyFromCopy Location
Copy Location
CopyFrom
A standard method of the Message class of protobuf. Is used to copy items in a field from one object to another.
See See Details
apiConfigProto = ApiConfigProto()
apiSettingsConfigProto = ApiSettingsConfigProto()
apiSettingsConfigProto.createApiMessageLogFile = True
apiSettingsConfigProto.includeMarketDataInLogFile = True
apiSettingsConfigProto.loggingLevel = "Detail"
apiConfigProto.settings.CopyFrom(apiSettingsConfigProto)
ApiConfigCopy Location
Copy Location
ApiPrecautionsConfig – Container Object for API precautionary settings.ApiSettingsConfig – Container object for API settings.apiConfig = ApiConfig() apiConfig.precautions = ApiPrecautionsConfig() apiConfig.settings = ApiSettingsConfig()
ApiSettingsConfigCopy Location
Copy Location
totalQuantityForMutualFunds: Boolean – Enables the display of total quantity instead of monetary value for mutual fund positions.
downloadOpenOrdersOnConnection: Boolean – Automatically downloads all open orders when the API client establishes a connection to TWS.
includeVirtualFxPositions: Boolean – Includes virtual foreign exchange positions in position updates sent to the API client.
prepareDailyPnL: Boolean – Enables the calculation and delivery of daily profit and loss data to the API client.
sendStatusUpdatesForVolatilityOrders: Boolean – Configures the system to send status updates for orders with volatility-based parameters.
encodeApiMessages: String – Specifies the character encoding format used for API message transmission (e.g., “osCodePage”).
socketPort: Integer – Defines the TCP socket port number on which the API listens for incoming client connections.
useNegativeAutoRange: Boolean – Allows the use of negative values in automatic range calculations for order parameters.
createApiMessageLogFile: Boolean – Enables the creation of a log file that records all API message traffic.
includeMarketDataInLogFile: Boolean – Controls whether market data messages are included in the API message log file.
exposeTradingScheduleToApi: Boolean – Makes trading schedule information available to API clients for contract and exchange queries.
splitInsuredDepositFromCashBalance: Boolean – Separates insured deposit amounts from the total cash balance in account value reports.
sendZeroPositionsForTodayOnly: Boolean – Limits the transmission of zero-quantity positions to only those closed during the current trading day.
useAccountGroupsWithAllocationMethods: Boolean – Enables the use of account groups when applying order allocation methods across multiple accounts.
loggingLevel: String – Sets the verbosity level for API logging output (e.g., “error”, “warning”, “info”, “debug”).
masterClientId: Integer – Designates a specific client ID as the master client with elevated privileges for API operations.
bulkDataTimeout: Integer – Specifies the timeout duration in seconds for bulk data request operations.
componentExchSeparator: String – Defines the character used to separate component exchange identifiers in composite contract symbols.
roundAccountValuesToNearestWholeNumber: Boolean – Rounds all account value figures to the nearest whole number for simplified display.
showAdvancedOrderRejectInUi: Boolean – Displays detailed order rejection messages in the TWS user interface for troubleshooting purposes.
rejectMessagesAboveMaxRate: Boolean – Automatically rejects API messages that exceed the configured maximum message rate threshold.
maintainConnectionOnIncorrectFields: Boolean – Preserves the API connection even when requests contain incorrect or invalid field values.
compatibilityModeNasdaqStocks: Boolean – Enables legacy compatibility mode for NASDAQ stock symbol formatting and handling.
sendInstrumentTimezone: String – Specifies the timezone format for instrument trading hours and schedule data (e.g., “utc”, “exchange”).
sendForexDataInCompatibilityMode: Boolean – Transmits foreign exchange market data using legacy format for backward compatibility with older API clients.
maintainAndResubmitOrdersOnReconnect: Boolean – Automatically preserves and resubmits active orders when the API client reconnects after a disconnection.
historicalDataMaxSize: Integer – Sets the maximum size level for historical data requests to control bandwidth and processing requirements.
autoReportNettingEventContractTrades: Boolean – Automatically reports trades generated by netting events for contract position reconciliation.
optionExerciseRequestType: String – Determines the type of option exercise requests accepted by the system (e.g., “final”, “preliminary”).
trustedIPs: List<String> – Contains a collection of IP addresses that are authorized to establish API connections without additional authentication.
apiSettingsConfigProto = ApiSettingsConfigProto()
apiSettingsConfigProto.totalQuantityForMutualFunds = True
apiSettingsConfigProto.downloadOpenOrdersOnConnection = True
apiSettingsConfigProto.includeVirtualFxPositions = True
apiSettingsConfigProto.prepareDailyPnL = True
apiSettingsConfigProto.sendStatusUpdatesForVolatilityOrders = True
apiSettingsConfigProto.encodeApiMessages = "osCodePage"
apiSettingsConfigProto.socketPort = 7497
apiSettingsConfigProto.useNegativeAutoRange = True
apiSettingsConfigProto.createApiMessageLogFile = True
apiSettingsConfigProto.includeMarketDataInLogFile = True
apiSettingsConfigProto.exposeTradingScheduleToApi = True
apiSettingsConfigProto.splitInsuredDepositFromCashBalance = True
apiSettingsConfigProto.sendZeroPositionsForTodayOnly = True
apiSettingsConfigProto.useAccountGroupsWithAllocationMethods = True
apiSettingsConfigProto.loggingLevel = "error"
apiSettingsConfigProto.masterClientId = 3
apiSettingsConfigProto.bulkDataTimeout = 25
apiSettingsConfigProto.componentExchSeparator = "#"
apiSettingsConfigProto.roundAccountValuesToNearestWholeNumber = True
apiSettingsConfigProto.showAdvancedOrderRejectInUi = True
apiSettingsConfigProto.rejectMessagesAboveMaxRate = True
apiSettingsConfigProto.maintainConnectionOnIncorrectFields = True
apiSettingsConfigProto.compatibilityModeNasdaqStocks = True
apiSettingsConfigProto.sendInstrumentTimezone = "utc"
apiSettingsConfigProto.sendForexDataInCompatibilityMode = True
apiSettingsConfigProto.maintainAndResubmitOrdersOnReconnect = True
apiSettingsConfigProto.historicalDataMaxSize = 4
apiSettingsConfigProto.autoReportNettingEventContractTrades = True
apiSettingsConfigProto.optionExerciseRequestType = "final"
apiSettingsConfigProto.trustedIPs.append("127.0.0.1")
ConfigRequestCopy Location
Copy Location
reqId: Integer – Request identifier
configRequest = ConfigRequest() configRequest.reqId = 123
ConfigResponseCopy Location
Copy Location
reqId: Integer – Request identifier
lockAndExit: LockAndExitConfig– Container object for all Lock And Exit Configurations.
messages: MessageConfig– Container object for repeated message objects.
api: ApiConfig – Container object for API Configuration page details
orders: OrdersConfig– Container object for the Orders settings.
reqId: 1784381601
lockAndExit {
autoLogoffTime: "12:07"
autoLogoffPeriod: "AM"
autoLogoffType: "restart"
}
messages {
id: 3
title: "Simultaneous market data limit exceeded"
message: "<html>You have requested data for %s instruments simultaneously, which exceeds your current account limit of %s<br>lines of simultaneous market data. You can increase your data limit by subscribing to market data <a href=\'#action\'>Booster packs</a>%s</html>"
defaultAction: "Hidden"
enabled: false
}
...
messages {
id: 11001
title: "Exchange-specific warning: LMTDOWN"
defaultAction: "Hidden"
enabled: true
}
api {
precautions {
bypassOrderPrecautions: true
...
bypassRouteMarketableToBBO: false
}
settings {
readOnlyApi: false
totalQuantityForMutualFunds: false
...
allowLocalhostOnly: false
trustedIPs: "127.0.0.1"
}
}
orders {
smartRouting {
seekPriceImprovement: false
doNotRouteToDarkPools: false
defaultAlgorithm: "SMART"
}
}
LockAndExitCopy Location
Copy Location
autoLogoffTime: String – Time the system should automatically logout or shut down.
autoLogoffPeriod: String – Declare autoLogoffTime as AM or PM.
autoLogoffType: String – Declare if platform should logout or restart and continue running.
lockAndExitProto = LockAndExitConfigProto() lockAndExitProto.autoLogoffTime = "11:59" lockAndExitProto.autoLogoffPeriod = "PM" lockAndExitProto.autoLogoffType = "restart"
MessageConfigCopy Location
Copy Location
id: Integer – Unique identifier that specifies the particular message type or category to be configured.
enabled: Boolean – Controls whether the specified message type is active and will be transmitted to the API client.
messageConfigProto.id = 131 messageConfigProto.enabled = False
OrdersConfigCopy Location
Copy Location
smartRouting: OrdersSmartRoutingConfig – Container object declaring how Smart Routed orders should behave.
ordersConfig = OrdersConfig() ordersConfig.smartRouting = OrdersSmartRoutingConfig()
OrdersSmartRoutingConfigCopy Location
Copy Location
seekPriceImprovement: Boolean – Enables the smart routing algorithm to actively search for better execution prices across available market venues.
doNotRouteToDarkPools: Boolean – Prevents the smart routing system from directing orders to dark pool venues for execution.
ordersSmartRoutingConfigProto.seekPriceImprovement = True ordersSmartRoutingConfigProto.doNotRouteToDarkPools = True
UpdateConfigRequestCopy Location
Copy Location
reqId: Integer – Request identifier
lockAndExit: LockAndExitConfig– Container object for all Lock And Exit Configurations.
messages: MessageConfig– Container object for repeated message objects.
api: ApiConfig – Container object for API Configuration page details
orders: OrdersConfig– Container object for the Orders settings.
acceptedWarnings: UpdateConfigWarning– Container object for repeated warning objects
resetApiOrderSequence: Boolean – Determine if the Order ID sequence should be reset to 0.
updateConfigRequest = UpdateConfigRequest() updateConfigRequest.reqId = 123 updateConfigRequest.lockAndExit = LockAndExitConfig updateConfigRequest.messages = MessageConfig updateConfigRequest.api = ApiConfig updateConfigRequest.orders = OrdersConfig updateConfigRequest.acceptedWarnings = UpdateConfigWarning updateConfigRequest.resetApiOrderSequence = True
UpdateConfigResponseCopy Location
Copy Location
reqId: Integer – Request identifier
status: String – Status of the request for modification.
message: String – Response message about the changes. Successful changes will return “Configuration updated”.
changedFields: String – List of fields changed by the updateConfigProtoBuf request.
errors: String – Any errors that arose during setting changes.
warnings: UpdateConfigWarning – Any additional warnings that arose from changing settings.
Success:
reqId: 1784381601 status: "success" message: "Configuration updated" changedFields: "configuration.api.settings.createApiMessageLogFile" changedFields: "configuration.api.settings.includeMarketDataInLogFile" changedFields: "configuration.api.settings.loggingLevel"
Failed:
reqId: 1784381601 status: "error" message: "Validating configuration update request has failed" errors: "configuration.lockAndExit.autoLogoffTime" errors: "configuration.lockAndExit.autoLogoffPeriod" errors: "configuration.lockAndExit.autoLogoffType"
UpdateConfigWarningCopy Location
Copy Location
messageId: Integer – Unique identifier that specifies the particular message type or category to be configured.
title: String – Title of the warning message
message: String – The content of the warning message.
updateConfigWarning = UpdateConfigWarning() updateConfigWarning.messageId = 131 messageConfigProto.enabled = False messageConfigProto.enabled = False