/* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ using System; using System.Collections.Generic; namespace IBApi { /** * @interface EWrapper * @brief This interface's methods are used by the TWS/Gateway to communicate with the API client. * Every API client application needs to implement this interface in order to handle all the events generated by the TWS/Gateway. Almost every EClientSocket method call will result in at least one event delivered here. * @sa EClientSocket class */ public interface EWrapper { /** @brief Handles errors generated within the API itself. * If an exception is thrown within the API code it will be notified here. Possible cases include errors while reading the information from the socket or even mishandling at EWrapper's implementing class. * @param e the thrown exception. */ void error(Exception e); /** * @param str The error message received. * */ void error(string str); /** * @brief Errors sent by the TWS are received here. * @param id the request identifier which generated the error. Note: -1 will indicate a notification and not true error condition. * @param errorCode the code identifying the error. * @param errorMsg error's description. * @param advancedOrderRejectJson advanced order reject description in json format. * */ void error(int id, int errorCode, string errorMsg, string advancedOrderRejectJson); /** * @brief TWS's current time. TWS is synchronized with the server (not local computer) using NTP and this function will receive the current time in TWS. * @sa EClient::reqCurrentTime */ void currentTime(long time); /** * @brief Market data tick price callback. * Handles all price related ticks. Every tickPrice callback is followed by a tickSize. A tickPrice value of -1 or 0 followed by a tickSize of 0 indicates there is no data for this field currently available, whereas a tickPrice with a positive tickSize indicates an active quote of 0 (typically for a combo contract). * @param tickerId the request's unique identifier. * @param field the type of the price being received (i.e. ask price). * @param price the actual price. * @param attribs an TickAttrib object that contains price attributes such as TickAttrib::CanAutoExecute, TickAttrib::PastLimit and TickAttrib::PreOpen. * @sa TickType, tickSize, tickString, tickEFP, tickGeneric, tickOptionComputation, tickSnapshotEnd, marketDataType, EClientSocket::reqMktData */ void tickPrice(int tickerId, int field, double price, TickAttrib attribs); /** * @brief Market data tick size callback. * Handles all size-related ticks. * @param tickerId the request's unique identifier. * @param field the type of size being received (i.e. bid size) * @param size the actual size. US stocks have a multiplier of 100. * @sa TickType, tickPrice, tickString, tickEFP, tickGeneric, tickOptionComputation, tickSnapshotEnd, marketDataType, EClientSocket::reqMktData */ void tickSize(int tickerId, int field, decimal size); /** * @brief Market data callback. * Every tickPrice is followed by a tickSize. There are also independent tickSize callbacks anytime the tickSize changes, and so there will be duplicate tickSize messages following a tickPrice. * @param tickerId the request's unique identifier. * @param field the type of the tick being received * @sa TickType, tickSize, tickPrice, tickEFP, tickGeneric, tickOptionComputation, tickSnapshotEnd, marketDataType, EClientSocket::reqMktData */ void tickString(int tickerId, int field, string value); /** * @brief Market data callback. * @param tickerId the request's unique identifier. * @param field the type of tick being received. * @param value */ void tickGeneric(int tickerId, int field, double value); /** * @brief Exchange for Physicals. * @param tickerId The request's identifier. * @param tickType The type of tick being received. * @param basisPoints Annualized basis points, which is representative of the financing rate that can be directly compared to broker rates. * @param formattedBasisPoints Annualized basis points as a formatted string that depicts them in percentage form. * @param impliedFuture The implied Futures price. * @param holdDays The number of hold days until the lastTradeDate of the EFP. * @param futureLastTradeDate The expiration date of the single stock future. * @param dividendImpact The dividend impact upon the annualized basis points interest rate. * @param dividendsToLastTradeDate The dividends expected until the expiration of the single stock future. */ void tickEFP(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int holdDays, string futureLastTradeDate, double dividendImpact, double dividendsToLastTradeDate); /** * @brief - * Upon accepting a Delta-Neutral DN RFQ(request for quote), the server sends a deltaNeutralValidation() message with the * DeltaNeutralContract 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 RFQ is processed and remain locked until the RFQ is cancelled. * @param reqId the request's identifier. * @param deltaNeutralContract Delta-Neutral Contract */ void deltaNeutralValidation(int reqId, DeltaNeutralContract deltaNeutralContract); /** * @brief Receive's option specific market data. * This method 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. * @param tickerId the request's unique identifier. * @param field Specifies the type of option computation. Pass the field value into TickType.getField(int tickType) to retrieve the field description. For example, a field value of 13 will map to modelOptComp, etc. * 10 = Bid * 11 = Ask * 12 = Last * @param impliedVolatility the implied volatility calculated by the TWS option modeler, using the specified tick type value. * @param tickAttrib: 0 - return based, 1- price based. * @param delta the option delta value. * @param optPrice the option price. * @param pvDividend the present value of dividends expected on the option's underlying. * @param gamma the option gamma value. * @param vega the option vega value. * @param theta the option theta value. * @param undPrice the price of the underlying. * @sa TickType, tickSize, tickPrice, tickEFP, tickGeneric, tickString, tickSnapshotEnd, marketDataType, EClientSocket::reqMktData */ void tickOptionComputation(int tickerId, int field, int tickAttrib, double impliedVolatility, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice); /** * @brief When requesting market data snapshots, this market will indicate the snapshot reception is finished. Expected to occur 11 seconds after beginning of request. * */ void tickSnapshotEnd(int tickerId); /** * @brief Receives next valid order id. Will be invoked automatically upon successfull API client connection, or after call to EClient::reqIds * Important: the next valid order ID is only valid at the time it is received. * @param orderId the next order id * @sa EClientSocket::reqIds */ void nextValidId(int orderId); /** * @brief Receives a comma-separated string with the managed account ids. Occurs automatically on initial API client connection. * @sa EClientSocket::reqManagedAccts */ void managedAccounts(string accountsList); /** * @brief Callback to indicate the API connection has closed. * Following a API <-> TWS broken socket connection, this function is not called automatically but must be triggered by API client code. * @sa EClientSocket::eDisconnect */ void connectionClosed(); /** * @brief Receives the account information. * This method will receive the account information just as it appears in the TWS' Account Summary Window. * @param reqId the request's unique identifier. * @param account the account id * @param tag the account's attribute being received. * - AccountType — Identifies the IB account structure * - NetLiquidation — The basis for determining the price of the assets in your account. Total cash value + stock value + options value + bond value * - TotalCashValue — Total cash balance recognized at the time of trade + futures PNL * - SettledCash — Cash recognized at the time of settlement - purchases at the time of trade - commissions - taxes - fees * - AccruedCash — Total accrued cash value of stock, commodities and securities * - BuyingPower — Buying power serves as a measurement of the dollar value of securities that one may purchase in a securities account without depositing additional funds * - EquityWithLoanValue — Forms the basis for determining whether a client has the necessary assets to either initiate or maintain security positions. Cash + stocks + bonds + mutual funds * - PreviousEquityWithLoanValue — Marginable Equity with Loan value as of 16:00 ET the previous day * - GrossPositionValue — The sum of the absolute value of all stock and equity option positions * - RegTEquity — Regulation T equity for universal account * - RegTMargin — Regulation T margin for universal account * - SMA — Special Memorandum Account: Line of credit created when the market value of securities in a Regulation T account increase in value * - InitMarginReq — Initial Margin requirement of whole portfolio * - MaintMarginReq — Maintenance Margin requirement of whole portfolio * - AvailableFunds — This value tells what you have available for trading * - ExcessLiquidity — This value shows your margin cushion, before liquidation * - Cushion — Excess liquidity as a percentage of net liquidation value * - FullInitMarginReq — Initial Margin of whole portfolio with no discounts or intraday credits * - FullMaintMarginReq — Maintenance Margin of whole portfolio with no discounts or intraday credits * - FullAvailableFunds — Available funds of whole portfolio with no discounts or intraday credits * - FullExcessLiquidity — Excess liquidity of whole portfolio with no discounts or intraday credits * - LookAheadNextChange — Time when look-ahead values take effect * - LookAheadInitMarginReq — Initial Margin requirement of whole portfolio as of next period's margin change * - LookAheadMaintMarginReq — Maintenance Margin requirement of whole portfolio as of next period's margin change * - LookAheadAvailableFunds — This value reflects your available funds at the next margin change * - LookAheadExcessLiquidity — This value reflects your excess liquidity at the next margin change * - HighestSeverity — A measure of how close the account is to liquidation * - DayTradesRemaining — The Number of Open/Close trades a user could put on before Pattern Day Trading is detected. A value of "-1" means that the user can put on unlimited day trades. * - Leverage — GrossPositionValue / NetLiquidation * @param value the account's attribute's value. * @param currency the currency on which the value is expressed. * @sa accountSummaryEnd, EClientSocket::reqAccountSummary */ void accountSummary(int reqId, string account, string tag, string value, string currency); /** * @brief notifies when all the accounts' information has ben received. * Requires TWS 967+ to receive accountSummaryEnd in linked account structures. * @param reqId the request's identifier. * @sa accountSummary, EClientSocket::reqAccountSummary */ void accountSummaryEnd(int reqId); /** * @brief Delivers the Bond contract data after this has been requested via reqContractDetails * @param reqId the request's identifier * @param contract the bond contract's information. * @sa reqContractDetails */ void bondContractDetails(int reqId, ContractDetails contract); /** * @brief Receives the subscribed account's information. * Only one account can be subscribed at a time. * After the initial callback to updateAccountValue, callbacks only occur for values which have changed. This occurs at the time of a position change, or every 3 minutes at most. This frequency cannot be adjusted. * @param key the value being updated. * - AccountCode — The account ID number * - AccountOrGroup — "All" to return account summary data for all accounts, or set to a specific Advisor Account Group name that has already been created in TWS Global Configuration * - AccountReady — For internal use only * - AccountType — Identifies the IB account structure * - AccruedCash — Total accrued cash value of stock, commodities and securities * - AccruedCash-C — Reflects the current's month accrued debit and credit interest to date, updated daily in commodity segment * - AccruedCash-S — Reflects the current's month accrued debit and credit interest to date, updated daily in security segment * - AccruedDividend — Total portfolio value of dividends accrued * - AccruedDividend-C — Dividends accrued but not paid in commodity segment * - AccruedDividend-S — Dividends accrued but not paid in security segment * - AvailableFunds — This value tells what you have available for trading * - AvailableFunds-C — Net Liquidation Value - Initial Margin * - AvailableFunds-S — Equity with Loan Value - Initial Margin * - Billable — Total portfolio value of treasury bills * - Billable-C — Value of treasury bills in commodity segment * - Billable-S — Value of treasury bills in security segment * - BuyingPower — Cash Account: Minimum (Equity with Loan Value, Previous Day Equity with Loan Value)-Initial Margin, Standard Margin Account: Minimum (Equity with Loan Value, Previous Day Equity with Loan Value) - Initial Margin *4 * - CashBalance — Cash recognized at the time of trade + futures PNL * - CorporateBondValue — Value of non-Government bonds such as corporate bonds and municipal bonds * - Currency — Open positions are grouped by currency * - Cushion — Excess liquidity as a percentage of net liquidation value * - DayTradesRemaining — Number of Open/Close trades one could do before Pattern Day Trading is detected * - DayTradesRemainingT+1 — Number of Open/Close trades one could do tomorrow before Pattern Day Trading is detected * - DayTradesRemainingT+2 — Number of Open/Close trades one could do two days from today before Pattern Day Trading is detected * - DayTradesRemainingT+3 — Number of Open/Close trades one could do three days from today before Pattern Day Trading is detected * - DayTradesRemainingT+4 — Number of Open/Close trades one could do four days from today before Pattern Day Trading is detected * - EquityWithLoanValue — Forms the basis for determining whether a client has the necessary assets to either initiate or maintain security positions * - EquityWithLoanValue-C — Cash account: Total cash value + commodities option value - futures maintenance margin requirement + minimum (0, futures PNL) Margin account: Total cash value + commodities option value - futures maintenance margin requirement * - EquityWithLoanValue-S — Cash account: Settled Cash Margin Account: Total cash value + stock value + bond value + (non-U.S. & Canada securities options value) * - ExcessLiquidity — This value shows your margin cushion, before liquidation * - ExcessLiquidity-C — Equity with Loan Value - Maintenance Margin * - ExcessLiquidity-S — Net Liquidation Value - Maintenance Margin * - ExchangeRate — The exchange rate of the currency to your base currency * - FullAvailableFunds — Available funds of whole portfolio with no discounts or intraday credits * - FullAvailableFunds-C — Net Liquidation Value - Full Initial Margin * - FullAvailableFunds-S — Equity with Loan Value - Full Initial Margin * - FullExcessLiquidity — Excess liquidity of whole portfolio with no discounts or intraday credits * - FullExcessLiquidity-C — Net Liquidation Value - Full Maintenance Margin * - FullExcessLiquidity-S — Equity with Loan Value - Full Maintenance Margin * - FullInitMarginReq — Initial Margin of whole portfolio with no discounts or intraday credits * - FullInitMarginReq-C — Initial Margin of commodity segment's portfolio with no discounts or intraday credits * - FullInitMarginReq-S — Initial Margin of security segment's portfolio with no discounts or intraday credits * - FullMaintMarginReq — Maintenance Margin of whole portfolio with no discounts or intraday credits * - FullMaintMarginReq-C — Maintenance Margin of commodity segment's portfolio with no discounts or intraday credits * - FullMaintMarginReq-S — Maintenance Margin of security segment's portfolio with no discounts or intraday credits * - FundValue — Value of funds value (money market funds + mutual funds) * - FutureOptionValue — Real-time market-to-market value of futures options * - FuturesPNL — Real-time changes in futures value since last settlement * - FxCashBalance — Cash balance in related IB-UKL account * - GrossPositionValue — Gross Position Value in securities segment * - GrossPositionValue-S — Long Stock Value + Short Stock Value + Long Option Value + Short Option Value * - IndianStockHaircut — Margin rule for IB-IN accounts * - InitMarginReq — Initial Margin requirement of whole portfolio * - InitMarginReq-C — Initial Margin of the commodity segment in base currency * - InitMarginReq-S — Initial Margin of the security segment in base currency * - IssuerOptionValue — Real-time mark-to-market value of Issued Option * - Leverage-S — GrossPositionValue / NetLiquidation in security segment * - LookAheadNextChange — Time when look-ahead values take effect * - LookAheadAvailableFunds — This value reflects your available funds at the next margin change * - LookAheadAvailableFunds-C — Net Liquidation Value - look ahead Initial Margin * - LookAheadAvailableFunds-S — Equity with Loan Value - look ahead Initial Margin * - LookAheadExcessLiquidity — This value reflects your excess liquidity at the next margin change * - LookAheadExcessLiquidity-C — Net Liquidation Value - look ahead Maintenance Margin * - LookAheadExcessLiquidity-S — Equity with Loan Value - look ahead Maintenance Margin * - LookAheadInitMarginReq — Initial margin requirement of whole portfolio as of next period's margin change * - LookAheadInitMarginReq-C — Initial margin requirement as of next period's margin change in the base currency of the account * - LookAheadInitMarginReq-S — Initial margin requirement as of next period's margin change in the base currency of the account * - LookAheadMaintMarginReq — Maintenance margin requirement of whole portfolio as of next period's margin change * - LookAheadMaintMarginReq-C — Maintenance margin requirement as of next period's margin change in the base currency of the account * - LookAheadMaintMarginReq-S — Maintenance margin requirement as of next period's margin change in the base currency of the account * - MaintMarginReq — Maintenance Margin requirement of whole portfolio * - MaintMarginReq-C — Maintenance Margin for the commodity segment * - MaintMarginReq-S — Maintenance Margin for the security segment * - MoneyMarketFundValue — Market value of money market funds excluding mutual funds * - MutualFundValue — Market value of mutual funds excluding money market funds * - NetDividend — The sum of the Dividend Payable/Receivable Values for the securities and commodities segments of the account * - NetLiquidation — The basis for determining the price of the assets in your account * - NetLiquidation-C — Total cash value + futures PNL + commodities options value * - NetLiquidation-S — Total cash value + stock value + securities options value + bond value * - NetLiquidationByCurrency — Net liquidation for individual currencies * - OptionMarketValue — Real-time mark-to-market value of options * - PASharesValue — Personal Account shares value of whole portfolio * - PASharesValue-C — Personal Account shares value in commodity segment * - PASharesValue-S — Personal Account shares value in security segment * - PostExpirationExcess — Total projected "at expiration" excess liquidity * - PostExpirationExcess-C — Provides a projected "at expiration" excess liquidity based on the soon-to expire contracts in your portfolio in commodity segment * - PostExpirationExcess-S — Provides a projected "at expiration" excess liquidity based on the soon-to expire contracts in your portfolio in security segment * - PostExpirationMargin — Total projected "at expiration" margin * - PostExpirationMargin-C — Provides a projected "at expiration" margin value based on the soon-to expire contracts in your portfolio in commodity segment * - PostExpirationMargin-S — Provides a projected "at expiration" margin value based on the soon-to expire contracts in your portfolio in security segment * - PreviousDayEquityWithLoanValue — Marginable Equity with Loan value as of 16:00 ET the previous day in securities segment * - PreviousDayEquityWithLoanValue-S — IMarginable Equity with Loan value as of 16:00 ET the previous day * - RealCurrency — Open positions are grouped by currency * - RealizedPnL — Shows your profit on closed positions, which is the difference between your entry execution cost and exit execution costs, or (execution price + commissions to open the positions) - (execution price + commissions to close the position) * - RegTEquity — Regulation T equity for universal account * - RegTEquity-S — Regulation T equity for security segment * - RegTMargin — Regulation T margin for universal account * - RegTMargin-S — Regulation T margin for security segment * - SMA — Line of credit created when the market value of securities in a Regulation T account increase in value * - SMA-S — Regulation T Special Memorandum Account balance for security segment * - SegmentTitle — Account segment name * - StockMarketValue — Real-time mark-to-market value of stock * - TBondValue — Value of treasury bonds * - TBillValue — Value of treasury bills * - TotalCashBalance — Total Cash Balance including Future PNL * - TotalCashValue — Total cash value of stock, commodities and securities * - TotalCashValue-C — CashBalance in commodity segment * - TotalCashValue-S — CashBalance in security segment * - TradingType-S — Account Type * - UnrealizedPnL — The difference between the current market value of your open positions and the average cost, or Value - Average Cost * - WarrantValue — Value of warrants * - WhatIfPMEnabled — To check projected margin requirements under Portfolio Margin model * @param value up-to-date value * @param currency the currency on which the value is expressed. * @param accountName the account * @sa updatePortfolio, updateAccountTime, accountDownloadEnd, EClientSocket::reqAccountUpdates */ void updateAccountValue(string key, string value, string currency, string accountName); /** * @brief Receives the subscribed account's portfolio. * This function will receive only the portfolio of the subscribed account. If the portfolios of all managed accounts are needed, refer to EClientSocket::reqPosition * After the initial callback to updatePortfolio, callbacks only occur for positions which have changed. * @param contract the Contract for which a position is held. * @param position the number of positions held. * @param marketPrice instrument's unitary price * @param marketValue total market value of the instrument. * @sa updateAccountTime, accountDownloadEnd, updateAccountValue, EClientSocket::reqAccountUpdates */ void updatePortfolio(Contract contract, decimal position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, string accountName); /** * @brief Receives the last time on which the account was updated. * @param timestamp the last update system time. * @sa updatePortfolio, accountDownloadEnd, updateAccountValue, EClientSocket::reqAccountUpdates */ void updateAccountTime(string timestamp); /** * @brief Notifies when all the account's information has finished. * @param account the account's id * @sa updateAccountTime, updatePortfolio, updateAccountValue, EClientSocket::reqAccountUpdates */ void accountDownloadEnd(string account); /** * @brief Gives the up-to-date information of an order every time it changes. Often there are duplicate orderStatus messages. * @param orderId the order's client id. * @param status the current status of the order. Possible values: * PendingSubmit - indicates that you have transmitted the order, but have not yet received confirmation that it has been accepted by the order destination. * 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. It is not guaranteed that the cancellation will be successful. * 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 by the system. * ApiCancelled - after an order has been submitted and before it has been acknowledged, an API client client can request its cancelation, producing this state. * 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. Market orders executions will not always trigger a Filled status. * Inactive - indicates that the order was received by the system but is no longer active because it was rejected or canceled. * @param filled number of filled positions. * @param remaining the remnant positions. * @param avgFillPrice average filling price. * @param permId the order's permId used by the TWS to identify orders. * @param parentId parent's id. Used for bracket and auto trailing stop orders. * @param lastFillPrice price at which the last positions were filled. * @param clientId API client which submitted the order. * @param whyHeld 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'. * @param mktCapPrice If an order has been capped, this indicates the current capped price. Requires TWS 967+ and API v973.04+. Python API specifically requires API v973.06+. * @sa openOrder, openOrderEnd, EClientSocket::placeOrder, EClientSocket::reqAllOpenOrders, EClientSocket::reqAutoOpenOrders */ void orderStatus(int orderId, string status, decimal filled, decimal remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, string whyHeld, double mktCapPrice); /** * @brief Feeds in currently open orders. * @param orderId the order's unique id * @param contract the order's Contract. * @param order the currently active Order. * @param orderState the order's OrderState * @sa orderStatus, openOrderEnd, EClientSocket::placeOrder, EClientSocket::reqAllOpenOrders, EClientSocket::reqAutoOpenOrders */ void openOrder(int orderId, Contract contract, Order order, OrderState orderState); /** * @brief Notifies the end of the open orders' reception. * @sa orderStatus, openOrder, EClientSocket::placeOrder, EClientSocket::reqAllOpenOrders, EClientSocket::reqAutoOpenOrders */ void openOrderEnd(); /** * @brief receives the full contract's definitions * This method will return all contracts matching the requested via EClientSocket::reqContractDetails. For example, one can obtain the whole option chain with it. * @param reqId the unique request identifier * @param contractDetails the instrument's complete definition. * @sa contractDetailsEnd, EClientSocket::reqContractDetails */ void contractDetails(int reqId, ContractDetails contractDetails); /** * @brief After all contracts matching the request were returned, this method will mark the end of their reception. * @param reqId the request's identifier * @sa contractDetails, EClientSocket::reqContractDetails */ void contractDetailsEnd(int reqId); /** * @brief Provides the executions which happened in the last 24 hours. * @param reqId the request's identifier * @param contract the Contract of the Order * @param execution the Execution details. * @sa execDetailsEnd, commissionReport, EClientSocket::reqExecutions, Execution */ void execDetails(int reqId, Contract contract, Execution execution); /** * @brief indicates the end of the Execution reception. * @param reqId the request's identifier * @sa execDetails, commissionReport, EClientSocket::reqExecutions */ void execDetailsEnd(int reqId); /** * @brief provides the CommissionReport of an Execution * @sa execDetails, execDetailsEnd, EClientSocket::reqExecutions, CommissionReport */ void commissionReport(CommissionReport commissionReport); /** * @brief returns fundamental data * @param reqId the request's identifier * @param data xml-formatted fundamental data * @sa EClientSocket::reqFundamentalData */ void fundamentalData(int reqId, string data); /** * @brief returns the requested historical data bars * @param reqId the request's identifier * @param bar the OHLC historical data Bar. The time zone of the bar is the time zone chosen on the TWS login screen. Smallest bar size is 1 second. * @sa EClientSocket::reqHistoricalData */ void historicalData(int reqId, Bar bar); /** * @brief Receives bars in real time if keepUpToDate is set as True in reqHistoricalData. Similar to realTimeBars function, except returned data is a composite of historical data and real time data that is equivalent to TWS chart functionality to keep charts up to date. Returned bars are successfully updated using real time data. * @param reqId the requests identifier * @param bar the OHLC historical data Bar. The time zone of the bar is the time zone chosen on the TWS login screen. Smallest bar size is 1 second. */ void historicalDataUpdate(int reqId, Bar bar); /** * @brief Marks the ending of the historical bars reception. */ void historicalDataEnd(int reqId, string start, string end); /** * @brief Returns the market data type (real-time, frozen, delayed, delayed-frozen) of ticker sent by EClientSocket::reqMktData * when TWS switches from real-time to frozen and back and from delayed to delayed-frozen and back * @param reqId the id of ticker sent in reqMktData * @param marketDataType means that now API starts to tick with the following market data: 1 for real-time, 2 for frozen, 3 for delayed, 4 for delayed-frozen * @sa EClientSocket::reqMarketDataType, EClientSocket::reqMktData */ void marketDataType(int reqId, int marketDataType); /** * @brief Returns the order book * @param tickerId the request's identifier * @param position the order book's row being updated * @param 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'). * @param side 0 for ask, 1 for bid * @param price the order's price * @param size the order's size * @sa updateMktDepthL2, EClientSocket::reqMarketDepth */ void updateMktDepth(int tickerId, int position, int operation, int side, double price, decimal size); /** * @brief Returns the order book * @param tickerId the request's identifier * @param position the order book's row being updated * @param marketMaker the exchange holding the order if isSmartDepth is True, otherwise the MPID of the market maker * @param 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'). * @param side 0 for ask, 1 for bid * @param price the order's price * @param size the order's size * @param isSmartDepth flag indicating if this is smart depth response (aggregate data from multiple exchanges, v974+) * @sa updateMktDepth, EClientSocket::reqMarketDepth */ void updateMktDepthL2(int tickerId, int position, string marketMaker, int operation, int side, double price, decimal size, bool isSmartDepth); /** * @brief provides IB's bulletins * @param msgId the bulletin's identifier * @param msgType one of: * 1 - Regular news bulletin * 2 - Exchange no longer available for trading * 3 - Exchange is available for trading * @param message the message * @param origExchange the exchange where the message comes from. */ void updateNewsBulletin(int msgId, int msgType, string message, string origExchange); /** * @brief provides the portfolio's open positions. * @param account the account holding the position. * @param contract the position's Contract * @param pos the number of positions held. * @Param avgCost the average cost of the position. * @sa positionEnd, EClientSocket::reqPositions */ void position(string account, Contract contract, decimal pos, double avgCost); /** * @brief Indicates all the positions have been transmitted. * @sa position, EClient::reqPositions */ void positionEnd(); /** * @brief updates the real time 5 seconds bars * @param reqId the request's identifier * @param date the bar's date and time (Epoch/Unix time) * @param open the bar's open point * @param high the bar's high point * @param low the bar's low point * @param close the bar's closing point * @param volume the bar's traded volume (only returned for TRADES data) * @param WAP the bar's Weighted Average Price rounded to minimum increment (only available for TRADES). * @param count the number of trades during the bar's timespan (only available for TRADES). * @sa EClientSocket::reqRealTimeBars */ void realtimeBar(int reqId, long date, double open, double high, double low, double close, decimal volume, decimal WAP, int count); /** * @brief provides the xml-formatted parameters available from TWS market scanners (not all available in API). * @param xml the xml-formatted string with the available parameters. * @sa scannerData, EClientSocket::reqScannerParameters */ void scannerParameters(string xml); /** * @brief provides the data resulting from the market scanner request. * @param reqid the request's identifier. * @param rank the ranking within the response of this bar. * @param contractDetails the data's ContractDetails * @param distance according to query. * @param benchmark according to query. * @param projection according to query. * @param legStr describes the combo legs when the scanner is returning EFP * @sa scannerParameters, scannerDataEnd, EClientSocket::reqScannerSubscription */ void scannerData(int reqId, int rank, ContractDetails contractDetails, string distance, string benchmark, string projection, string legsStr); /** * @brief Indicates the scanner data reception has terminated. * @param reqId the request's identifier * @sa scannerParameters, scannerData, EClientSocket::reqScannerSubscription */ void scannerDataEnd(int reqId); /** * @brief receives the Financial Advisor's configuration available in the TWS * @param faDataType one of: * 1. Groups: offer traders a way to create a group of accounts and apply a single allocation method to all accounts in the group. * 2. Profiles: let you allocate shares on an account-by-account basis using a predefined calculation value. * 3. Account Aliases: let you easily identify the accounts by meaningful names rather than account numbers. * @param faXmlData the xml-formatted configuration * @sa EClientSocket::requestFA, EClientSocket::replaceFA */ void receiveFA(int faDataType, string faXmlData); /** * @brief Not generally available. */ void verifyMessageAPI(string apiData); /** * @brief Not generally available. */ void verifyCompleted(bool isSuccessful, string errorText); /** * @brief Not generally available. */ void verifyAndAuthMessageAPI(string apiData, string xyzChallenge); /** * @brief Not generally available. */ void verifyAndAuthCompleted(bool isSuccessful, string errorText); /** * @brief a one-time response to querying the display groups. * @param reqId the ID of the request * @param It returns a list of integers representing visible Group ID separated by the "|" character, and sorted by most used group first. * @sa EClientSocket::queryDisplayGroups */ void displayGroupList(int reqId, string groups); /** * @brief call triggered once after receiving the subscription request, and will be sent again if the selected contract in the subscribed * display group has changed. * @param reqId the ID of the request * @param contractInfo * @sa EClient::subscribeToGroupEvents */ void displayGroupUpdated(int reqId, string contractInfo); /** * @brief callback initially acknowledging connection attempt * connection handshake not complete until nextValidID is received */ void connectAck(); /** * @brief provides the portfolio's open positions. * @param requestId the id of request * @param account the account holding the position. * @param modelCode the model code holding the position. * @param contract the position's Contract * @param pos the number of positions held. * @param avgCost the average cost of the position. * @sa positionMultiEnd, EClientSocket::reqPositionsMulti */ void positionMulti(int requestId, string account, string modelCode, Contract contract, decimal pos, double avgCost); /** * @brief Indicates all the positions have been transmitted. * @sa positionMulti, EClient::reqPositionsMulti */ void positionMultiEnd(int requestId); /** * @brief provides the account updates. * @param requestId the id of request * @param account the account with updates * @param modelCode the model code with updates * @param key the name of parameter * @param value the value of parameter * @param currency the currency of parameter * @sa accountUpdateMultiEnd, EClient::reqAccountUpdatesMulti */ void accountUpdateMulti(int requestId, string account, string modelCode, string key, string value, string currency); /** * @brief Indicates all the account updates have been transmitted * @sa EWrapper::accountUpdateMulti, EClientSocket::reqAccountUpdatesMulti */ void accountUpdateMultiEnd(int requestId); /** * @brief 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 * @param reqId ID of the request initiating the callback * @param underlyingConId The conID of the underlying security * @param tradingClass the option trading class * @param multiplier the option multiplier * @param expirations a list of the expiries for the options of this underlying on this exchange * @param strikes a list of the possible strikes for options of this underlying on this exchange * @sa EClient::reqSecDefOptParams */ void securityDefinitionOptionParameter(int reqId, string exchange, int underlyingConId, string tradingClass, string multiplier, HashSet expirations, HashSet strikes); /** * @brief called when all callbacks to securityDefinitionOptionParameter are complete * @param reqId the ID used in the call to securityDefinitionOptionParameter * @sa securityDefinitionOptionParameter, EClient::reqSecDefOptParams */ void securityDefinitionOptionParameterEnd(int reqId); /** * @brief called when receives Soft Dollar Tier configuration information * @param reqId The request ID used in the call to EClient::reqSoftDollarTiers * @param tiers Stores a list of SoftDollarTier that contains all Soft Dollar Tiers information * @sa EClient::reqSoftDollarTiers */ void softDollarTiers(int reqId, SoftDollarTier[] tiers); /** * @brief returns array of family codes * @param FamilyCode[] * @sa EClient::reqFamilyCodes */ void familyCodes(FamilyCode[] familyCodes); /** * @brief returns array of sample contract descriptions * @param ContractDescription[] * @sa EClient::reqMatchingSymbols */ void symbolSamples(int reqId, ContractDescription[] contractDescriptions); /** * @brief called when receives Depth Market Data Descriptions * @param descriptions Stores a list of DepthMktDataDescriprion * @sa EClient::reqMktDepthExchanges */ void mktDepthExchanges(DepthMktDataDescription[] depthMktDataDescriptions); /** * @brief ticks with news headline * @param tickerId * @param timeStamp * @param providerCode * @param articleId * @param headline * @param extraData * @sa EClient::reqMktData */ void tickNews(int tickerId, long timeStamp, string providerCode, string articleId, string headline, string extraData); /** * @brief bit number to exchange + exchange abbreviation dictionary * @param reqId * @param theMap * sa EClient::reqSmartComponents */ void smartComponents(int reqId, Dictionary> theMap); /** * @brief tick with BOO exchange and snapshot permissions * @param tickerId * @param minTick * @param bboExchange * @param snapshotPermissions * sa EClient::reqMktData */ void tickReqParams(int tickerId, double minTick, string bboExchange, int snapshotPermissions); /** * @brief returns array of subscribed API news providers for this user * @param NewsProvider[] * @sa EClient::reqNewsProviders */ void newsProviders(NewsProvider[] newsProviders); /** * @brief called when receives News Article * @param requestId The request ID used in the call to EClient::reqNewsArticle * @param articleType The type of news article (0 - plain text or html, 1 - binary data / pdf) * @param articleText The body of article (if articleType == 1, the binary data is encoded using the Base64 scheme) * @sa EClient::reqNewsArticle */ void newsArticle(int requestId, int articleType, string articleText); /** * @brief returns news headline * @param requestId * @param time * @param providerCode * @param articleId * @param headline * @sa EClient::reqHistoricalNews */ void historicalNews(int requestId, string time, string providerCode, string articleId, string headline); /** * @brief returns news headlines end marker * @param requestId * @param hasMore - indicates whether there are more results available, false otherwise * @sa EClient::reqHistoricalNews */ void historicalNewsEnd(int requestId, bool hasMore); /** * @brief - returns beginning of data for contract for specified data type * @param requestId * @param headTimestamp - string identifying earliest data date * @sa EClient::reqHeadTimestamp */ void headTimestamp(int reqId, string headTimestamp); /** * @brief returns data histogram * @param requestId * @param data - returned Tuple of histogram data, number of trades at specified price level * @sa EClient::reqHistogramData */ void histogramData(int reqId, HistogramEntry[] data); /** * @brief - returns conId and exchange for CFD market data request re-route * @param reqId * @param conId of the underlying instrument which has market data * @param exchange of the underlying */ void rerouteMktDataReq(int reqId, int conId, string exchange); /** * @brief returns the conId and exchange for an underlying contract when a request is made for level 2 data for an instrument which does not have data in IB's database. For example stock CFDs and index CFDs. * @param reqId * @param conId * @param exchange */ void rerouteMktDepthReq(int reqId, int conId, string exchange); /** * @brief returns minimum price increment structure for a particular market rule ID * market rule IDs for an instrument on valid exchanges can be obtained from the contractDetails object for that contract * @param marketRuleId * @param PriceIncrement[] * @sa EClient::reqMarketRule */ void marketRule(int marketRuleId, PriceIncrement[] priceIncrements); /** * @brief receives PnL updates in real time for the daily PnL and the total unrealized PnL for an account * @param reqId * @param dailyPnL dailyPnL updates for the account in real time * @param unrealizedPnL total unRealized PnL updates for the account in real time * @sa EClient::reqPnL */ void pnl(int reqId, double dailyPnL, double unrealizedPnL, double realizedPnL); /** * @brief receives real time updates for single position daily PnL values * @param reqId * @param pos current size of the position * @param dailyPnL dailyPnL for the position * @param unrealizedPnL total unrealized PnL for the position (since inception) updating in real time * @param value current market value of the position * @sa EClient::reqSinglePnL */ void pnlSingle(int reqId, decimal pos, double dailyPnL, double unrealizedPnL, double realizedPnL, double value); /** * @brief * @param reqId * @param ticks list of HistoricalTick data * @param done flag to indicate if all historical tick data has been received */ void historicalTicks(int reqId, HistoricalTick[] ticks, bool done); /** * @brief * @param reqId * @param ticks list of HistoricalBidAsk data * @param done flag to indicate if all historical tick data has been received */ void historicalTicksBidAsk(int reqId, HistoricalTickBidAsk[] ticks, bool done); /** * @brief * @param reqId * @param ticks list of HistoricalTickLast data * @param done flag to indicate if all historical tick data has been received */ void historicalTicksLast(int reqId, HistoricalTickLast[] ticks, bool done); /** * @brief returns "Last" or "AllLast" tick-by-tick real-time tick * @param reqId - unique identifier of the request * @param tickType - tick-by-tick real-time tick type: "Last" or "AllLast" * @param time - tick-by-tick real-time tick timestamp * @param price - tick-by-tick real-time tick last price * @param size - tick-by-tick real-time tick last size * @param tickAttribLast - tick-by-tick real-time last tick attribs (bit 0 - past limit, bit 1 - unreported) * @param exchange - tick-by-tick real-time tick exchange * @param specialConditions - tick-by-tick real-time tick special conditions * @sa EClient::reqTickByTickData */ void tickByTickAllLast(int reqId, int tickType, long time, double price, decimal size, TickAttribLast tickAttribLast, string exchange, string specialConditions); /** * @brief returns "BidAsk" tick-by-tick real-time tick * @param reqId - unique identifier of the request * @param time - tick-by-tick real-time tick timestamp * @param bidPrice - tick-by-tick real-time tick bid price * @param askPrice - tick-by-tick real-time tick ask price * @param bidSize - tick-by-tick real-time tick bid size * @param askSize - tick-by-tick real-time tick ask size * @param tickAttribBidAsk - tick-by-tick real-time bid/ask tick attribs (bit 0 - bid past low, bit 1 - ask past high) * @sa EClient::reqTickByTickData */ void tickByTickBidAsk(int reqId, long time, double bidPrice, double askPrice, decimal bidSize, decimal askSize, TickAttribBidAsk tickAttribBidAsk); /** * @brief returns "MidPoint" tick-by-tick real-time tick * @param reqId - unique identifier of the request * @param time - tick-by-tick real-time tick timestamp * @param midPoint - tick-by-tick real-time tick mid point * @sa EClient::reqTickByTickData */ void tickByTickMidPoint(int reqId, long time, double midPoint); /** * @brief response to API bind order control message * @param orderId - permId * @param apiClientId - API client id * @param apiOrderId - API order id * @sa EClient::reqOpenOrders */ void orderBound(long orderId, int apiClientId, int apiOrderId); /** * @brief Feeds in completed orders. * @param contract the order's Contract. * @param order the completed Order. * @param orderState the order's OrderState * @sa completedOrdersEnd, EClientSocket::reqCompletedOrders */ void completedOrder(Contract contract, Order order, OrderState orderState); /** * @brief Notifies the end of the completed orders' reception. * @sa completedOrder, EClientSocket::reqCompletedOrders */ void completedOrdersEnd(); /** * @brief notifies the end of the FA replace. * @param reqId the id of request * @param text the message text * @sa EClient::replaceFA */ void replaceFAEnd(int reqId, string text); /** * @brief returns meta data from the WSH calendar * @param reqId the id of request * @param dataJson metadata in json format * @sa EClient::reqWshMetaData */ void wshMetaData(int reqId, string dataJson); /** * @brief returns calendar events from the WSH * @param reqId the id of request * @param dataJson event data in json format * @sa EClient::reqWshEventData */ void wshEventData(int reqId, string dataJson); /** * @brief returns historical schedule * @param reqId the id of request * @param startDateTime * @param endDateTime * @param timeZone * @param sessions * @sa EClient::reqHistoricalData with whatToShow=SCHEDULE */ void historicalSchedule(int reqId, string startDateTime, string endDateTime, string timeZone, HistoricalSession[] sessions); /** * @brief returns user info * @param reqId the id of request * @param whiteBrandingId * @sa EClient::reqUserInfo */ void userInfo(int reqId, string whiteBrandingId); } }