Close Navigation

ProtoBuf Reference

Introduction

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.

Protocol Buffer Documentatino

Important Protobuf Functions

When interacting directly with protobuf classes, proto-specific functions need to be used.

CopyFrom

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)

 

ApiConfig

precautions: ApiPrecautionsConfig –   Container Object for API precautionary settings.
settings: ApiSettingsConfig – Container object for API settings.
apiConfig = ApiConfig()
apiConfig.precautions = ApiPrecautionsConfig()
apiConfig.settings = ApiSettingsConfig()

 

ApiSettingsConfig

totalQuantityForMutualFundsBoolean – Enables the display of total quantity instead of monetary value for mutual fund positions.

downloadOpenOrdersOnConnectionBoolean – Automatically downloads all open orders when the API client establishes a connection to TWS.

includeVirtualFxPositionsBoolean – Includes virtual foreign exchange positions in position updates sent to the API client.

prepareDailyPnLBoolean – Enables the calculation and delivery of daily profit and loss data to the API client.

sendStatusUpdatesForVolatilityOrdersBoolean – Configures the system to send status updates for orders with volatility-based parameters.

encodeApiMessagesString – Specifies the character encoding format used for API message transmission (e.g., “osCodePage”).

socketPortInteger – Defines the TCP socket port number on which the API listens for incoming client connections.

useNegativeAutoRangeBoolean – Allows the use of negative values in automatic range calculations for order parameters.

createApiMessageLogFileBoolean – Enables the creation of a log file that records all API message traffic.

includeMarketDataInLogFileBoolean – Controls whether market data messages are included in the API message log file.

exposeTradingScheduleToApiBoolean – Makes trading schedule information available to API clients for contract and exchange queries.

splitInsuredDepositFromCashBalanceBoolean – Separates insured deposit amounts from the total cash balance in account value reports.

sendZeroPositionsForTodayOnlyBoolean – Limits the transmission of zero-quantity positions to only those closed during the current trading day.

useAccountGroupsWithAllocationMethodsBoolean – Enables the use of account groups when applying order allocation methods across multiple accounts.

loggingLevelString – Sets the verbosity level for API logging output (e.g., “error”, “warning”, “info”, “debug”).

masterClientIdInteger – Designates a specific client ID as the master client with elevated privileges for API operations.

bulkDataTimeoutInteger – Specifies the timeout duration in seconds for bulk data request operations.

componentExchSeparatorString – Defines the character used to separate component exchange identifiers in composite contract symbols.

roundAccountValuesToNearestWholeNumberBoolean – Rounds all account value figures to the nearest whole number for simplified display.

showAdvancedOrderRejectInUiBoolean – Displays detailed order rejection messages in the TWS user interface for troubleshooting purposes.

rejectMessagesAboveMaxRateBoolean – Automatically rejects API messages that exceed the configured maximum message rate threshold.

maintainConnectionOnIncorrectFieldsBoolean – Preserves the API connection even when requests contain incorrect or invalid field values.

compatibilityModeNasdaqStocksBoolean – Enables legacy compatibility mode for NASDAQ stock symbol formatting and handling.

sendInstrumentTimezoneString – Specifies the timezone format for instrument trading hours and schedule data (e.g., “utc”, “exchange”).

sendForexDataInCompatibilityModeBoolean – Transmits foreign exchange market data using legacy format for backward compatibility with older API clients.

maintainAndResubmitOrdersOnReconnectBoolean – Automatically preserves and resubmits active orders when the API client reconnects after a disconnection.

historicalDataMaxSizeInteger – Sets the maximum size level for historical data requests to control bandwidth and processing requirements.

autoReportNettingEventContractTradesBoolean – Automatically reports trades generated by netting events for contract position reconciliation.

optionExerciseRequestTypeString – Determines the type of option exercise requests accepted by the system (e.g., “final”, “preliminary”).

trustedIPsList<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")

 

ConfigRequest

reqId: Integer – Request identifier

configRequest = ConfigRequest()
configRequest.reqId = 123

 

ConfigResponse

reqIdInteger – Request identifier

lockAndExitLockAndExitConfig– Container object for all Lock And Exit Configurations.

messagesMessageConfig– Container object for repeated message objects.

apiApiConfig – Container object for API Configuration page details

ordersOrdersConfig– 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"
  }
}

 

LockAndExit

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"

 

MessageConfig

idInteger – Unique identifier that specifies the particular message type or category to be configured.

enabledBoolean – Controls whether the specified message type is active and will be transmitted to the API client.

messageConfigProto.id = 131
messageConfigProto.enabled = False

 

OrdersConfig

smartRoutingOrdersSmartRoutingConfig – Container object declaring how Smart Routed orders should behave.

ordersConfig = OrdersConfig()
ordersConfig.smartRouting = OrdersSmartRoutingConfig()

 

OrdersSmartRoutingConfig

seekPriceImprovementBoolean – Enables the smart routing algorithm to actively search for better execution prices across available market venues.

doNotRouteToDarkPoolsBoolean – Prevents the smart routing system from directing orders to dark pool venues for execution.

ordersSmartRoutingConfigProto.seekPriceImprovement = True
ordersSmartRoutingConfigProto.doNotRouteToDarkPools = True

 

UpdateConfigRequest

reqIdInteger – Request identifier

lockAndExitLockAndExitConfig– Container object for all Lock And Exit Configurations.

messagesMessageConfig– Container object for repeated message objects.

apiApiConfig – Container object for API Configuration page details

ordersOrdersConfig– Container object for the Orders settings.

acceptedWarningsUpdateConfigWarning– Container object for repeated warning objects

resetApiOrderSequenceBoolean – 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

 

UpdateConfigResponse

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"

 

UpdateConfigWarning

messageIdInteger – Unique identifier that specifies the particular message type or category to be configured.

titleString – Title of the warning message

messageString – The content of the warning message.

updateConfigWarning = UpdateConfigWarning()
updateConfigWarning.messageId = 131
messageConfigProto.enabled = False
messageConfigProto.enabled = False

 

IBKR Campus Newsletters

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.