Client
ib_interface.api.client
Socket client for communicating with Interactive Brokers.
Client
Replacement for ibapi.client.EClient that uses asyncio.
The client is fully asynchronous and has its own
event-driven networking code that replaces the
networking code of the standard EClient.
It also replaces the infinite loop of EClient.run()
with the asyncio event loop. It can be used as a drop-in
replacement for the standard EClient as provided by IBAPI.
Compared to the standard EClient this client has the following additional features:
-
client.connect()will block until the client is ready to serve requests; It is not necessary to wait fornextValidIdto start requests as the client has already done that. The reqId is directly available with :py:meth:.getReqId(). -
client.connectAsync()is a coroutine for connecting asynchronously. -
When blocking,
client.connect()can be made to time out with the timeout parameter (default 2 seconds). -
Optional
wrapper.priceSizeTick(reqId, tickType, price, size)that combines price and size instead of the two wrapper methods priceTick and sizeTick. -
Automatic request throttling.
-
Optional
wrapper.tcpDataArrived()method; If the wrapper has this method it is invoked directly after a network packet has arrived. A possible use is to timestamp all data in the packet with the exact same time. -
Optional
wrapper.tcpDataProcessed()method; If the wrapper has this method it is invoked after the network packet's data has been handled. A possible use is to write or evaluate the newly arrived data in one batch instead of item by item.
Attributes:
MaxRequests (int):
Throttle the number of requests to MaxRequests per
RequestsInterval seconds. Set to 0 to disable throttling.
RequestsInterval (float):
Time interval (in seconds) for request throttling.
MinClientVersion (int):
Client protocol version.
MaxClientVersion (int):
Client protocol version.
Events:
apiStart()apiEnd()apiError(errorMsg: str)throttleStart()throttleEnd()
reset
def reset()
serverVersion
def serverVersion() -> int
run
def run()
isConnected
def isConnected()
isReady
def isReady() -> bool
Is the API connection up and running?
connectionStats
def connectionStats() -> ConnectionStats
Get statistics about the connection.
getReqId
def getReqId() -> int
Get new request ID.
updateReqId
def updateReqId(minReqId)
Update the next reqId to be at least minReqId.
getAccounts
def getAccounts() -> List[str]
Get the list of account names that are under management.
useProtoBuf
def useProtoBuf(msgId: int) -> bool
Check if a given request should use protobuf encoding.
setConnectOptions
def setConnectOptions(connectOptions: str)
Set additional connect options.
Args: connectOptions: Use "+PACEAPI" to use request-pacing built into TWS/gateway 974+ (obsolete).
connect
def connect(host: str, port: int, clientId: int, timeout: Optional[float] = 2.0)
Connect to a running TWS or IB gateway application.
Args:
host: Host name or IP address.
port: Port number.
clientId: ID number to use for this client; must be unique per
connection.
timeout: If establishing the connection takes longer than
timeout seconds then the asyncio.TimeoutError exception
is raised. Set to 0 to disable timeout.
connectAsync
def connectAsync(host, port, clientId, timeout = 2.0)
disconnect
def disconnect()
Disconnect from IB connection.
send
def send(fields = (), makeEmpty = True)
Serialize and send the given fields using the IB socket protocol.
sendMsg
def sendMsg(msg: str)
sendProtobuf
def sendProtobuf(msgId: int, protobufData: bytes) -> None
Send a protobuf-encoded message to TWS/Gateway.
reqMktData
def reqMktData(reqId, contract, genericTickList, snapshot, regulatorySnapshot, mktDataOptions)
cancelMktData
def cancelMktData(reqId)
placeOrder
def placeOrder(orderId, contract, order)
cancelOrder
def cancelOrder(orderId, manualCancelOrderTime = '')
reqOpenOrders
def reqOpenOrders()
reqAccountUpdates
def reqAccountUpdates(subscribe, acctCode)
reqExecutions
def reqExecutions(reqId, execFilter)
reqIds
def reqIds(numIds)
reqContractDetails
def reqContractDetails(reqId, contract)
reqMktDepth
def reqMktDepth(reqId, contract, numRows, isSmartDepth, mktDepthOptions)
cancelMktDepth
def cancelMktDepth(reqId, isSmartDepth)
reqNewsBulletins
def reqNewsBulletins(allMsgs)
cancelNewsBulletins
def cancelNewsBulletins()
setServerLogLevel
def setServerLogLevel(logLevel)
reqAutoOpenOrders
def reqAutoOpenOrders(bAutoBind)
reqAllOpenOrders
def reqAllOpenOrders()
reqManagedAccts
def reqManagedAccts()
requestFA
def requestFA(faData)
replaceFA
def replaceFA(reqId, faData, cxml)
reqHistoricalData
def reqHistoricalData(reqId, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate, keepUpToDate, chartOptions)
reqConfig
def reqConfig(reqId: int) -> None
Request API configuration from TWS/Gateway.
Response arrives via wrapper.configResponse() callback. Requires Protobuf support (server version 219+).
Args: reqId: Request identifier for tracking response
Raises: ConnectionError: If protobuf not supported
updateConfig
def updateConfig(reqId: int, config_params: dict) -> None
Update API configuration settings.
Response arrives via wrapper.updateConfigResponse() callback. Requires Protobuf support (server version 219+).
Args: reqId: Request identifier for tracking response config_params: Dictionary of config key-value pairs
Raises: ConnectionError: If protobuf not supported
exerciseOptions
def exerciseOptions(reqId, contract, exerciseAction, exerciseQuantity, account, override)
reqScannerSubscription
def reqScannerSubscription(reqId, subscription, scannerSubscriptionOptions, scannerSubscriptionFilterOptions)
cancelScannerSubscription
def cancelScannerSubscription(reqId)
reqScannerParameters
def reqScannerParameters()
cancelHistoricalData
def cancelHistoricalData(reqId)
reqCurrentTime
def reqCurrentTime()
reqRealTimeBars
def reqRealTimeBars(reqId, contract, barSize, whatToShow, useRTH, realTimeBarsOptions)
cancelRealTimeBars
def cancelRealTimeBars(reqId)
reqFundamentalData
def reqFundamentalData(reqId, contract, reportType, fundamentalDataOptions)
cancelFundamentalData
def cancelFundamentalData(reqId)
calculateImpliedVolatility
def calculateImpliedVolatility(reqId, contract, optionPrice, underPrice, implVolOptions)
calculateOptionPrice
def calculateOptionPrice(reqId, contract, volatility, underPrice, optPrcOptions)
cancelCalculateImpliedVolatility
def cancelCalculateImpliedVolatility(reqId)
cancelCalculateOptionPrice
def cancelCalculateOptionPrice(reqId)
reqGlobalCancel
def reqGlobalCancel()
reqMarketDataType
def reqMarketDataType(marketDataType)
reqPositions
def reqPositions()
reqAccountSummary
def reqAccountSummary(reqId, groupName, tags)
cancelAccountSummary
def cancelAccountSummary(reqId)
cancelPositions
def cancelPositions()
verifyRequest
def verifyRequest(apiName, apiVersion)
verifyMessage
def verifyMessage(apiData)
queryDisplayGroups
def queryDisplayGroups(reqId)
subscribeToGroupEvents
def subscribeToGroupEvents(reqId, groupId)
updateDisplayGroup
def updateDisplayGroup(reqId, contractInfo)
unsubscribeFromGroupEvents
def unsubscribeFromGroupEvents(reqId)
startApi
def startApi()
verifyAndAuthRequest
def verifyAndAuthRequest(apiName, apiVersion, opaqueIsvKey)
verifyAndAuthMessage
def verifyAndAuthMessage(apiData, xyzResponse)
reqPositionsMulti
def reqPositionsMulti(reqId, account, modelCode)
cancelPositionsMulti
def cancelPositionsMulti(reqId)
reqAccountUpdatesMulti
def reqAccountUpdatesMulti(reqId, account, modelCode, ledgerAndNLV)
cancelAccountUpdatesMulti
def cancelAccountUpdatesMulti(reqId)
reqSecDefOptParams
def reqSecDefOptParams(reqId, underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId)
reqSoftDollarTiers
def reqSoftDollarTiers(reqId)
reqFamilyCodes
def reqFamilyCodes()
reqMatchingSymbols
def reqMatchingSymbols(reqId, pattern)
reqMktDepthExchanges
def reqMktDepthExchanges()
reqSmartComponents
def reqSmartComponents(reqId, bboExchange)
reqNewsArticle
def reqNewsArticle(reqId, providerCode, articleId, newsArticleOptions)
reqNewsProviders
def reqNewsProviders()
reqHistoricalNews
def reqHistoricalNews(reqId, conId, providerCodes, startDateTime, endDateTime, totalResults, historicalNewsOptions)
reqHeadTimeStamp
def reqHeadTimeStamp(reqId, contract, whatToShow, useRTH, formatDate)
reqHistogramData
def reqHistogramData(tickerId, contract, useRTH, timePeriod)
cancelHistogramData
def cancelHistogramData(tickerId)
cancelHeadTimeStamp
def cancelHeadTimeStamp(reqId)
reqMarketRule
def reqMarketRule(marketRuleId)
reqPnL
def reqPnL(reqId, account, modelCode)
cancelPnL
def cancelPnL(reqId)
reqPnLSingle
def reqPnLSingle(reqId, account, modelCode, conid)
cancelPnLSingle
def cancelPnLSingle(reqId)
reqHistoricalTicks
def reqHistoricalTicks(reqId, contract, startDateTime, endDateTime, numberOfTicks, whatToShow, useRth, ignoreSize, miscOptions)
reqTickByTickData
def reqTickByTickData(reqId, contract, tickType, numberOfTicks, ignoreSize)
cancelTickByTickData
def cancelTickByTickData(reqId)
reqCompletedOrders
def reqCompletedOrders(apiOnly)
reqWshMetaData
def reqWshMetaData(reqId)
cancelWshMetaData
def cancelWshMetaData(reqId)
reqWshEventData
def reqWshEventData(reqId, data: WshEventData)
cancelWshEventData
def cancelWshEventData(reqId)
reqUserInfo
def reqUserInfo(reqId)