def req_head_time_stamp(self, input_contract: Contract, what_to_show: str, use_rth: int, format_date: int): req_id = self.gen_req_id() self.reqHeadTimeStamp(req_id, input_contract, what_to_show, use_rth, format_date) self.log_req(req_id, current_fn_name(), vars()) return req_id
def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float): """This event is called whenever the status of an order changes. It is also fired after reconnecting to TWS if the client has any open orders. orderId: OrderId - The order ID that was specified previously in the call to placeOrder() status:str - The order status. Possible values include: PendingSubmit - indicates that you have transmitted the order, but have not yet received confirmation that it has been accepted by the order destination. NOTE: This order status is not sent by TWS and should be explicitly set by the API developer when an order is submitted. PendingCancel - indicates that you have sent a request to cancel the order but have not yet received cancel confirmation from the order destination. At this point, your order is not confirmed canceled. You may still receive an execution while your cancellation request is pending. NOTE: This order status is not sent by TWS and should be explicitly set by the API developer when an order is canceled. PreSubmitted - indicates that a simulated order type has been accepted by the IB system and that this order has yet to be elected. The order is held in the IB system until the election criteria are met. At that time the order is transmitted to the order destination as specified. Submitted - indicates that your order has been accepted at the order destination and is working. Cancelled - indicates that the balance of your order has been confirmed canceled by the IB system. This could occur unexpectedly when IB or the destination has rejected your order. Filled - indicates that the order has been completely filled. Inactive - indicates that the order has been accepted by the system (simulated orders) or an exchange (native orders) but that currently the order is inactive due to system, exchange or other issues. filled:int - Specifies the number of shares that have been executed. For more information about partial fills, see Order Status for Partial Fills. remaining:int - Specifies the number of shares still outstanding. avgFillPrice:float - The average price of the shares that have been executed. This parameter is valid only if the filled parameter value is greater than zero. Otherwise, the price parameter will be zero. permId:int - The TWS id used to identify orders. Remains the same over TWS sessions. parentId:int - The order ID of the parent order, used for bracket and auto trailing stop orders. lastFilledPrice:float - The last price of the shares that have been executed. This parameter is valid only if the filled parameter value is greater than zero. Otherwise, the price parameter will be zero. clientId:int - The ID of the client (or TWS) that placed the order. Note that TWS orders have a fixed clientId and orderId of 0 that distinguishes them from API orders. whyHeld:str - This field is used to identify an order held when TWS is trying to locate shares for a short sell. The value used to indicate this is 'locate'. """ self.logAnswer(current_fn_name(), vars())
def place_order(self, contract: Contract, input_order: Order): # we don't know if order id can be the same as request id req_id = self.gen_req_id() order_id = self.next_order_id self.placeOrder(order_id, contract, input_order) self.log_req(req_id, current_fn_name(), vars()) return req_id
def req_open_orders(self): # this is a refresh of the open orders self.clean_orders() req_id = self.gen_req_id() self.reqOpenOrders() self.log_req(req_id, current_fn_name(), vars()) return req_id
def securityDefinitionOptionParameterEnd(self, reqId: int): """ Called when all callbacks to securityDefinitionOptionParameter are complete reqId - the ID used in the call to securityDefinitionOptionParameter """ self.logAnswer(current_fn_name(), vars())
def req_mkt_depth(self, contract, num_rows: int, is_smart_depth: bool, mkt_depth_options: List): req_id = self.gen_req_id() self.reqMktDepth(req_id, contract, num_rows, is_smart_depth, mkt_depth_options) self.log_req(req_id, current_fn_name(), vars()) return req_id
def req_mkt_data(self, contract: Contract, generic_tick_list='', snapshot=False, regulatory_snapshot=False, mkt_data_options=None): """ :param contract: :param generic_tick_list: consists of list of tick fields requested https://interactivebrokers.github.io/tws-api/tick_types.html :param snapshot: :param regulatory_snapshot: :param mkt_data_options: """ req_id = self.gen_req_id() if mkt_data_options is None: _mk_options = [] else: _mk_options = mkt_data_options self.reqMktData(req_id, contract, generic_tick_list, snapshot, regulatory_snapshot, _mk_options) self.log_req(req_id, current_fn_name(), vars()) return req_id
def softDollarTiers(self, reqId: int, tiers: list): """ Called when receives Soft Dollar Tier configuration information reqId - The request ID used in the call to EEClient::reqSoftDollarTiers tiers - Stores a list of SoftDollarTier that contains all Soft Dollar Tiers information """ self.logAnswer(current_fn_name(), vars())
def updatePortfolio(self, contract: Contract, position: float, marketPrice: float, marketValue: float, averageCost: float, unrealizedPNL: float, realizedPNL: float, accountName: str): """This function is called only when reqAccountUpdates on EEClientSocket object has been called.""" self.logAnswer(current_fn_name(), vars())
def deltaNeutralValidation(self, reqId: int, underComp: UnderComp): """Upon accepting a Delta-Neutral RFQ(request for quote), the server sends a deltaNeutralValidation() message with the UnderComp structure. If the delta and price fields are empty in the original request, the confirmation will contain the current values from the server. These values are locked when the RFQ is processed and remain locked until the RFQ is canceled.""" self.logAnswer(current_fn_name(), vars())
def req_tick_by_tick_data(self, contract: Contract, tick_type: TickType, ignore_size: bool = True): req_id = self.gen_req_id() self.reqTickByTickData(req_id, contract, tick_type.value, 0, ignore_size) self.log_req(req_id, current_fn_name(), vars()) return req_id
def req_real_time_bars(self, input_contract: Contract, bar_size: int, what_to_show: str, use_rth: bool, real_time_bars_options: List): req_id = self.gen_req_id() assert what_to_show in REAL_TIME_BAR_TYPES, f'what_to_show {what_to_show} is not supported' self.reqRealTimeBars(req_id, input_contract, bar_size, what_to_show, use_rth, real_time_bars_options) self.log_req(req_id, current_fn_name(), vars()) return req_id
def req_historical_ticks(self, contract: Contract, start_date_time: str, end_date_time: str, number_of_ticks: int, what_to_show: str, use_rth: int, ignore_size: bool, misc_options: List): req_id = self.gen_req_id() self.reqHistoricalTicks(req_id, contract, start_date_time, end_date_time, number_of_ticks, what_to_show, use_rth, ignore_size, misc_options) self.log_req(req_id, current_fn_name(), vars()) return req_id
def displayGroupList(self, reqId: int, groups: str): """This callback is a one-time response to queryDisplayGroups(). reqId - The requestId specified in queryDisplayGroups(). groups - A list of integers representing visible group ID separated by the | character, and sorted by most used group first. This list will not change during TWS session (in other words, user cannot add a new group; sorting can change though).""" self.logAnswer(current_fn_name(), vars())
def marketDataType(self, reqId: TickerId, marketDataType: int): """TWS sends a marketDataType(type) callback to the API, where type is set to Frozen or RealTime, to announce that market data has been switched between frozen and real-time. This notification occurs only when market data switches between real-time and frozen. The marketDataType( ) callback accepts a reqId parameter and is sent per every subscription because different contracts can generally trade on a different schedule.""" self.logAnswer(current_fn_name(), vars())
def tickOptionComputation(self, reqId: TickerId, tickType: TickType, impliedVol: float, delta: float, optPrice: float, pvDividend: float, gamma: float, vega: float, theta: float, undPrice: float): """This function is called when the market in an option or its underlier moves. TWS's option model volatilities, prices, and deltas, along with the present value of dividends expected on that options underlier are received.""" self.logAnswer(current_fn_name(), vars())
def updateNewsBulletin(self, msgId: int, msgType: int, newsMessage: str, originExch: str): """ provides IB's bulletins msgId - the bulletin's identifier msgType - one of: 1 - Regular news bulletin 2 - Exchange no longer available for trading 3 - Exchange is available for trading message - the message origExchange - the exchange where the message comes from. """ self.logAnswer(current_fn_name(), vars())
def req_historical_data_blocking(self, input_contract: Contract, end_date_time: str, duration_str: str, bar_size_setting: str, what_to_show: str, use_rth: int, format_date: int, chart_options: List): req_id = self.gen_req_id() self.reqHistoricalData(req_id, input_contract, end_date_time, duration_str, bar_size_setting, what_to_show, use_rth, format_date, False, chart_options) self.log_req(req_id, current_fn_name(), vars()) return req_id
def req_smart_components(self, exchange_char): """ The tick types 'bidExch' (tick type 32), 'askExch' (tick type 33), 'lastExch' (tick type 84) are used to identify the source of a quote. To find the full exchange name corresponding to a single letter code returned in tick types 32, 33, or 84, and API function IBApi::EClient::reqSmartComponents is available. """ req_id = self.gen_req_id() self.reqSmartComponents(req_id, exchange_char) self.log_req(req_id, current_fn_name(), vars()) return req_id
def openOrder(self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState): """This function is called to feed in open orders. orderID: OrderId - The order ID assigned by TWS. Use to cancel or update TWS order. contract: Contract - The Contract class attributes describe the contract. order: Order - The Order class gives the details of the open order. orderState: OrderState - The orderState class includes attributes Used for both pre and post trade margin and commission data.""" self.logAnswer(current_fn_name(), vars())
def tickEFP(self, reqId: TickerId, tickType: TickType, basisPoints: float, formattedBasisPoints: str, totalDividends: float, holdDays: int, futureLastTradeDate: str, dividendImpact: float, dividendsToLastTradeDate: float): self.logAnswer(current_fn_name(), vars()) """ market data call back for Exchange for Physical tickerId - The request's identifier. tickType - The type of tick being received. basisPoints - Annualized basis points, which is representative of the financing rate that can be directly compared to broker rates. formattedBasisPoints - Annualized basis points as a formatted string that depicts them in percentage form. impliedFuture - The implied Futures price. holdDays - The number of hold days until the lastTradeDate of the EFP. futureLastTradeDate - The expiration date of the single stock future. dividendImpact - The dividend impact upon the annualized basis points interest rate. dividendsToLastTradeDate - The dividends expected until the expiration of the single stock future.""" self.logAnswer(current_fn_name(), vars())
def receiveFA(self, faData: FaDataType, cxml: str): """ receives the Financial Advisor's configuration available in the TWS faDataType - one of: Groups: offer traders a way to create a group of accounts and apply a single allocation method to all accounts in the group. Profiles: let you allocate shares on an account-by-account basis using a predefined calculation value. Account Aliases: let you easily identify the accounts by meaningful names rather than account numbers. faXmlData - the xml-formatted configuration """ self.logAnswer(current_fn_name(), vars())
def error(self, reqId: int, errorCode: int, errorString: str) -> None: """Receive error from IB and print it. Args: reqId: the id of the failing request errorCode: the error code errorString: text to explain the error """ self.logAnswer(current_fn_name(), vars()) logger.error("ERROR %s %s %s", reqId, errorCode, errorString) print("Error: ", reqId, " ", errorCode, " ", errorString) self.error_reqId = reqId
def scannerData(self, reqId: int, rank: int, contractDetails: ContractDetails, distance: str, benchmark: str, projection: str, legsStr: str): """ Provides the data resulting from the market scanner request. reqid - the request's identifier. rank - the ranking within the response of this bar. contractDetails - the data's ContractDetails distance - according to query. benchmark - according to query. projection - according to query. legStr - describes the combo legs when the scanner is returning EFP""" self.logAnswer(current_fn_name(), vars())
def updateMktDepth(self, reqId: TickerId, position: int, operation: int, side: int, price: float, size: int): """Returns the order book. tickerId - the request's identifier position - the order book's row being updated operation - how to refresh the row: 0 = insert (insert this new order into the row identified by 'position') 1 = update (update the existing order in the row identified by 'position') 2 = delete (delete the existing order at the row identified by 'position'). side - 0 for ask, 1 for bid price - the order's price size - the order's size""" self.logAnswer(current_fn_name(), vars())
def displayGroupUpdated(self, reqId: int, contractInfo: str): """This is sent by TWS to the API client once after receiving the subscription request subscribeToGroupEvents(), and will be sent again if the selected contract in the subscribed display group has changed. requestId - The requestId specified in subscribeToGroupEvents(). contractInfo - The encoded value that uniquely represents the contract in IB. Possible values include: none = empty selection contractID@exchange = any non-combination contract. Examples: 8314@SMART for IBM SMART; 8314@ARCA for IBM @ARCA. combo = if any combo is selected. """ self.logAnswer(current_fn_name(), vars())
def orderStatus(self, orderId: OrderId, status: str, filled: float, remaining: float, avgFillPrice: float, permId: int, parentId: int, lastFillPrice: float, clientId: int, whyHeld: str, mktCapPrice: float): self.logAnswer(current_fn_name(), vars()) if self._order_id_awaiting_submit == orderId and status in [ 'PreSubmitted', 'Submitted', 'PendingSubmit' ]: self.logger.info('===> Order ID: {}, status: {}'.format( orderId, status)) self.action_event_lock.set() if self._order_id_awaiting_cancel == orderId and status == 'Cancelled': self.logger.info('===> Order ID: {}, status: {}'.format( orderId, status)) self.action_event_lock.set()
def historicalData(self, reqId: int, bar: BarData): """ returns the requested historical data bars reqId - the request's identifier date - the bar's date and time (either as a yyyymmss hh:mm:ssformatted string or as system time according to the request) open - the bar's open point high - the bar's high point low - the bar's low point close - the bar's closing point volume - the bar's traded volume if available count - the number of trades during the bar's timespan (only available for TRADES). WAP - the bar's Weighted Average Price hasGaps -indicates if the data has gaps or not. """ self.logAnswer(current_fn_name(), vars())
def realtimeBar(self, reqId: TickerId, time: int, open: float, high: float, low: float, close: float, volume: int, wap: float, count: int): """ Updates the real time 5 seconds bars reqId - the request's identifier bar.time - start of bar in unix (or 'epoch') time bar.endTime - for synthetic bars, the end time (requires TWS v964). Otherwise -1. bar.open - the bar's open value bar.high - the bar's high value bar.low - the bar's low value bar.close - the bar's closing value bar.volume - the bar's traded volume if available bar.WAP - the bar's Weighted Average Price bar.count - the number of trades during the bar's timespan (only available for TRADES).""" self.logAnswer(current_fn_name(), vars())
def securityDefinitionOptionParameter(self, reqId: int, exchange: str, underlyingConId: int, tradingClass: str, multiplier: str, expirations: SetOfString, strikes: SetOfFloat): """ Returns the option chain for an underlying on an exchange specified in reqSecDefOptParams There will be multiple callbacks to securityDefinitionOptionParameter if multiple exchanges are specified in reqSecDefOptParams reqId - ID of the request initiating the callback underlyingConId - The conID of the underlying security tradingClass - the option trading class multiplier - the option multiplier expirations - a list of the expiries for the options of this underlying on this exchange strikes - a list of the possible strikes for options of this underlying on this exchange """ self.logAnswer(current_fn_name(), vars())