UNPKG

@stoqey/ib

Version:

Interactive Brokers TWS/IB Gateway API client library for Node.js (TS)

1,112 lines (1,111 loc) 103 kB
import { EventEmitter } from "eventemitter3"; import { DurationUnit, MarketDataType, OrderCancel, OrderStatus, WhatToShow } from ".."; import { ErrorCode } from "../common/errorCode"; import { Contract } from "./contract/contract"; import { ContractDescription } from "./contract/contractDescription"; import { ContractDetails } from "./contract/contractDetails"; import { DeltaNeutralContract } from "./contract/deltaNeutralContract"; import WshEventData from "./contract/wsh"; import DepthMktDataDescription from "./data/container/depth-mkt-data-description"; import FamilyCode from "./data/container/family-code"; import NewsProvider from "./data/container/news-provider"; import SoftDollarTier from "./data/container/soft-dollar-tier"; import TagValue from "./data/container/tag-value"; import { EventName } from "./data/enum/event-name"; import FADataType from "./data/enum/fa-data-type"; import LogLevel from "./data/enum/log-level"; import MIN_SERVER_VER from "./data/enum/min-server-version"; import OptionExerciseAction from "./data/enum/option-exercise-action"; import { BarSizeSetting } from "./historical/bar-size-setting"; import { HistogramEntry } from "./historical/histogramEntry"; import { HistoricalTick } from "./historical/historicalTick"; import { HistoricalTickBidAsk, TickAttribBidAsk } from "./historical/historicalTickBidAsk"; import { HistoricalTickLast, TickAttribLast } from "./historical/historicalTickLast"; import { ScannerSubscription } from "./market/scannerSubscription"; import { TickByTickDataType } from "./market/tickByTickDataType"; import { TickType } from "./market/tickType"; import { Execution } from "./order/execution"; import { Order } from "./order/order"; import { OrderState } from "./order/orderState"; import { CommissionReport } from "./report/commissionReport"; import { ExecutionFilter } from "./report/executionFilter"; /** * Input arguments on the [[IBApi]] class constructor. */ export interface IBApiCreationOptions { /** * Hostname of the TWS (or IB Gateway). * * Default is 'localhost'. */ host?: string; /** * Hostname of the TWS (or IB Gateway). * * Default is 7496, which is the TWS default (4001 is default for IB Gateway Live-Accounts and 4002 for * Demo-Accounts). */ port?: number; /** * A unique client id (per TWS or IB Gateway instance). * * Default is 0. * * @deprecated The attributes should not be used anymore. * Use clientId argument [[IBApi.connect]] instead. */ clientId?: number; /** * Max. number of requests per second, sent to TWS/IB Gateway. * Default is 40. IB specifies 50 requests/s as maximum. * * Note that sending large amount of requests within a small amount of time, significantly increases resource * consumption of the TWS/IB Gateway (especially memory consumption). If you experience any lags, hangs or crashes * on TWS/IB Gateway while sending request bursts, try to reduce this value. */ maxReqPerSec?: number; } /** Maximum supported version. */ export declare const MAX_SUPPORTED_SERVER_VERSION = MIN_SERVER_VER.CME_TAGGING_FIELDS_IN_OPEN_ORDER; /** Minimum supported version. */ export declare const MIN_SERVER_VER_SUPPORTED = 38; /** * Typescript implementation of the Interactive Brokers TWS (or IB Gateway) API. * * Refer to the official {@link https://interactivebrokers.github.io/tws-api/|Trader Workstation API documentation} for * details. */ export declare class IBApi extends EventEmitter { /** * Create a IB API object. * * @param options Creation options. */ constructor(options?: IBApiCreationOptions); /** The I/O queue controller object. */ private controller; /** * Get the IB API Server version. * * @see [[MIN_SERVER_VER]] */ get serverVersion(): number; /** * Returns `true` if currently connected to server, `false` otherwise. */ get isConnected(): boolean; /** * Allows to switch between different current (V100+) and previous connection mechanisms. * * @deprecated pre-V100 support will be removed. Please consider updating your * TWS and/or IB Gateway version. */ disableUseV100Plus(): void; /** * Connect to the TWS or IB Gateway. * * @param clientId A unique client id (per TWS or IB Gateway instance). * When not specified, the client id from [[IBApiCreationOptions]] or the default client id (0) will used. */ connect(clientId?: number): IBApi; /** * Disconnect from the TWS or IB Gateway. */ disconnect(): IBApi; /** * Calculate the volatility for an option. * Request the calculation of the implied volatility based on hypothetical option and its underlying prices. * The calculation will be emitted as tickOptionComputation event. * * @param reqId Unique identifier of the request. * @param contract The option's contract for which the volatility wants to be calculated. * @param optionPrice Hypothetical option price. * @param underPrice Hypothetical option's underlying price. * * @see [[cancelCalculateImpliedVolatility]] */ calculateImpliedVolatility(reqId: number, contract: Contract, optionPrice: number, underPrice: number): IBApi; /** * Calculates an option's price based on the provided volatility and its underlying price. * The calculation will be emitted as tickOptionComputation event. * * @param reqId Unique identifier of the request. * @param contract The option's contract for which the price wants to be calculated. * @param volatility Hypothetical volatility. * @param underPrice Hypothetical underlying price. * * @see [[cancelCalculateOptionPrice]] */ calculateOptionPrice(reqId: number, contract: Contract, volatility: number, underPrice: number): IBApi; /** * Cancels the account's summary request. * After requesting an account's summary, invoke this function to cancel it. * * @param reqId The identifier of the previously performed account request. * * @see [[reqAccountSummary]] */ cancelAccountSummary(reqId: number): IBApi; /** * Cancels account updates request for account and/or model. * * @param reqId Account subscription to cancel. * * @see [[reqAccountUpdatesMulti]] */ cancelAccountUpdatesMulti(reqId: number): IBApi; /** * Cancels an option's implied volatility calculation request. * * @param reqId The identifier of the implied volatility's calculation request. * * @see [[calculateImpliedVolatility]] */ cancelCalculateImpliedVolatility(reqId: number): IBApi; /** * Cancels an option's price calculation request. * * @param reqId The identifier of the option's price's calculation request. * * @see [[calculateOptionPrice]] */ cancelCalculateOptionPrice(reqId: number): IBApi; /** * Cancels Fundamental data request. * * @param reqId The request's identifier. * * @see [[reqFundamentalData]] */ cancelFundamentalData(reqId: number): IBApi; /** * Cancels a pending [[reqHeadTimeStamp]] request. * * @param reqId Id of the request * * @see [[reqHeadTimeStamp]] */ cancelHeadTimestamp(reqId: number): IBApi; /** * Cancels a historical data request. * * @param reqId The request's identifier. * * @see [[reqHistogramData]] */ cancelHistogramData(reqId: number): IBApi; /** * Cancels a historical data request. * * @param reqId The request's identifier. * * @see [[reqHistoricalData]] */ cancelHistoricalData(reqId: number): IBApi; /** * Cancels a RT Market Data request. * * @param reqId The request's identifier. * * @see [[reqMktData]] */ cancelMktData(reqId: number): IBApi; /** * Cancel a market depth's request. * * @param reqId The request's identifier. * @param isSmartDepth TODO document * * @see [[reqMktDepth]] */ cancelMktDepth(reqId: number, isSmartDepth: boolean): IBApi; /** * Cancels IB's news bulletin subscription. * * @see [[reqNewsBulletins]] */ cancelNewsBulletins(): IBApi; /** * Cancels an active order placed by from the same API client ID. * * Note: API clients cannot cancel individual orders placed by other clients. * Use [[reqGlobalCancel]] instead. * * @param orderId Specify which order should be cancelled by its identifier. * @param orderCancel Specify the time the order should be cancelled. An empty string will cancel the order immediately. * * @see [[placeOrder]], [[reqGlobalCancel]] */ cancelOrder(orderId: number, orderCancelParam?: string | OrderCancel): IBApi; /** * Cancels subscription for real time updated daily PnL. * * @param reqId The request's identifier. * * @see [[reqPnL]] */ cancelPnL(reqId: number): IBApi; /** * Cancels real time subscription for a positions daily PnL information. * * @param reqId The request's identifier. * * @see [[reqPnLSingle]] */ cancelPnLSingle(reqId: number): IBApi; /** * Cancels a previous position subscription request made with reqPositions. * * @see [[reqPositions]] */ cancelPositions(): IBApi; /** * Cancels positions request for account and/or model. * * @param reqId The identifier of the request to be canceled. * * @see [[reqPositionsMulti]] */ cancelPositionsMulti(reqId: number): IBApi; /** * Cancels Real Time Bars' subscription. * * @param reqId The request's identifier. */ cancelRealTimeBars(reqId: number): IBApi; /** * Cancels Scanner Subscription. * * @param reqId The subscription's unique identifier. * * @see [[reqScannerSubscription]], [[reqScannerParameters]] */ cancelScannerSubscription(reqId: number): IBApi; /** * Cancels tick-by-tick data. * * @param reqId Unique identifier of the request. * * @see [[reqTickByTickData]] */ cancelTickByTickData(reqId: number): IBApi; /** * Exercises an options contract. * * Note: this function is affected by a TWS setting which specifies if an exercise request must be finalized. * * @param reqId The exercise request's identifier. * @param contract The option [[Contract]] to be exercised. * @param exerciseAction 1 to exercise the option, 2 to let the option lapse. * @param exerciseQuantity Number of contracts to be exercised. * @param account Destination account. * @param override Specifies whether your setting will override the system's natural action. * For example, if your action is "exercise" and the option is not in-the-money, * by natural action the option would not exercise. * If you have override set to "yes" the natural action would be overridden and the out-of-the money option would be * exercised. Set to 1 to override, set to 0 not to. */ exerciseOptions(reqId: number, contract: Contract, exerciseAction: OptionExerciseAction, exerciseQuantity: number, account: string, override: number): IBApi; /** * Places or modifies an order. * @param id The order's unique identifier. * Use a sequential id starting with the id received at the nextValidId method. * If a new order is placed with an order ID less than or equal to the order ID of a previous order an error will * occur. * @param contract The order's [[Contract]]. * @param order The [[Order]] object. * * @see [[reqAllOpenOrders]], [[reqAutoOpenOrders]], [[reqOpenOrders]], [[cancelOrder]], [[reqGlobalCancel]] */ placeOrder(id: number, contract: Contract, order: Order): IBApi; /** * Requests all available Display Groups in TWS. * * @param reqId The ID of this request. */ queryDisplayGroups(reqId: number): IBApi; /** * Replaces Financial Advisor's settings A Financial Advisor can define three different configurations: * * - 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. * More information at * https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fpdfhighlights%2FPDF-AdvisorAllocations.php%3Fib_entity%3Dllc * * @param faDataType The configuration to change. * @param xml Zhe xml-formatted configuration string. */ replaceFA(reqId: number, faDataType: FADataType, xml: string): IBApi; /** * Requests a specific account's summary. * This method will subscribe to the account summary as presented in the TWS' Account Summary tab. * The data is emitted as accountSummary event. * * https://www.interactivebrokers.com/en/software/tws/accountwindowtop.htm * * @param reqId The unique request identifier. * @param group Set to "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. * @param tags A comma separated list with the desired tags: * - 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 * - PreviousDayEquityWithLoanValue — 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 * - $LEDGER — Single flag to relay all cash balance tags*, only in base currency. * - $LEDGER:CURRENCY — Single flag to relay all cash balance tags*, only in the specified currency. * - $LEDGER:ALL — Single flag to relay all cash balance tags* in all currencies. * * @see [[cancelAccountSummary]] */ reqAccountSummary(reqId: number, group: string, tags: string): IBApi; /** * Subscribes to a specific account's information and portfolio. * Through this method, a single account's subscription can be started/stopped. * As a result from the subscription, the account's information, portfolio and last update time will be emitted as * updateAccountValue, updateAccountPortfolio, updateAccountTime event respectively. * * All account values and positions will be returned initially, and then there will only be updates when there is a * change in a position, or to an account value every 3 minutes if it has changed. * * Only one account can be subscribed at a time. * * A second subscription request for another account when the previous one is still active will cause the first one * to be canceled in favour of the second one. Consider user reqPositions if you want to retrieve all your accounts' * portfolios directly. * * @param subscribe Set to true to start the subscription and to false to stop it. * @param acctCode The account id (i.e. U123456) for which the information is requested. * * @see [[reqPositions]] */ reqAccountUpdates(subscribe: boolean, acctCode: string): IBApi; /** * Requests account updates for account and/or model. * * @param reqId Identifier to label the request. * @param acctCode Account values can be requested for a particular account * @param modelCode Values can also be requested for a model * @param ledgerAndNLV returns light-weight request; only currency positions as opposed to account values and * currency positions. * * @see [[cancelAccountUpdatesMulti]] */ reqAccountUpdatesMulti(reqId: number, acctCode: string, modelCode: string, ledgerAndNLV: boolean): IBApi; /** * Requests all current open orders in associated accounts at the current moment. * The existing orders will be received via the openOrder and orderStatus events. * * Open orders are returned once; this function does not initiate a subscription. * * @see [[reqAutoOpenOrders]], [[reqOpenOrders]] */ reqAllOpenOrders(): IBApi; /** * Requests status updates about future orders placed from TWS. Can only be used with client ID 0. * * @param bAutoBind if set to `true`, the newly created orders will be assigned an API order ID and implicitly * associated with this client. If set to `false, future orders will not be. * * @see [[reqAllOpenOrders]], [[reqOpenOrders]], [[cancelOrder]], [[reqGlobalCancel]] */ reqAutoOpenOrders(bAutoBind: boolean): IBApi; /** * Requests completed orders. * * @param apiOnly Request only API orders. */ reqCompletedOrders(apiOnly: boolean): IBApi; /** * Requests metadata from the WSH calendar. * * @param reqId The unique request identifier. * * @see [[reqCancelWshMetaData]] */ reqWshMetaData(reqId: number): this; /** * Cancels pending request for WSH metadata. * * @param reqId The unique request identifier. */ reqCancelWshMetaData(reqId: number): this; /** * Requests event data from the wSH calendar. * * @param reqId The unique request identifier. * @param wshEventData Contract id (conId) of ticker or WshEventData describing wanted events. * * @see [[reqCancelWshEventData]] */ reqWshEventData(reqId: number, wshEventData: number | WshEventData): this; /** * Cancels pending WSH event data request. * * @param reqId The unique request identifier. */ reqCancelWshEventData(reqId: number): this; /** * Requests contract information. * This method will provide all the contracts matching the contract provided. * * It can also be used to retrieve complete options and futures chains. * Though it is now (in API version > 9.72.12) advised to use reqSecDefOptParams for that purpose. * * This information will be emitted as contractDetails event. * * @param reqId The unique request identifier. * @param contract The contract used as sample to query the available contracts. */ reqContractDetails(reqId: number, contract: Contract): IBApi; /** * Requests TWS's current time. */ reqCurrentTime(): IBApi; /** * Requests current day's (since midnight) executions matching the filter. * Only the current day's executions can be retrieved. * Along with the executions, the CommissionReport will also be returned. * * The execution details will be emitted as execDetails event. * * @param reqId The request's unique identifier. * @param filter The filter criteria used to determine which execution reports are returned. */ reqExecutions(reqId: number, filter: ExecutionFilter): IBApi; /** * Requests family codes for an account, for instance if it is a FA, IBroker, or associated account. */ reqFamilyCodes(): IBApi; /** * Requests the contract's fundamental data. Fundamental data is emitted as fundamentalData event. * * @param reqId The request's unique identifier. * @param contract The contract's description for which the data will be returned. * @param reportType there are three available report types: * - ReportSnapshot: Company overview. * - ReportsFinSummary: Financial summary. * - ReportRatios: Financial ratios. * - ReportsFinStatements: Financial statements. * - RESC: Analyst estimates. */ reqFundamentalData(reqId: number, contract: Contract, reportType: string, fundamentalDataOptions?: TagValue[]): IBApi; /** * Cancels all active orders. * This method will cancel ALL open orders including those placed directly from TWS. * * @see [[cancelOrder]] */ reqGlobalCancel(orderCancel?: OrderCancel): IBApi; /** * Returns the timestamp of earliest available historical data for a contract and data type. * * @param reqId An identifier for the request. * @param contract [[Contract]] object for which head timestamp is being requested. * @param whatToShow Type of data for head timestamp - "BID", "ASK", "TRADES", etc * @param useRTH Use regular trading hours only, `true` for yes or `false` for no. * @param formatDate Set to 1 to obtain the bars' time as yyyyMMdd HH:mm:ss, set to 2 to obtain it like system time * format in seconds. */ reqHeadTimestamp(reqId: number, contract: Contract, whatToShow: WhatToShow, useRTH: boolean, formatDate: number): IBApi; /** * Returns data histogram of specified contract. * * @param reqId An identifier for the request. * @param contract [[Contract]] object for which histogram is being requested * @param useRTH Use regular trading hours only, `true` for yes or `false` for no. * @param period Period of which data is being requested * @param periodUnit Unit of the period of which data is being requested */ reqHistogramData(reqId: number, contract: Contract, useRTH: boolean, period: number, periodUnit: DurationUnit): IBApi; /** * Requests contracts' historical data. When requesting historical data, a finishing time and date is required along * with a duration string. For example, having: * ````- endDateTime: 20130701 23:59:59 GMT``` * ````- durationStr: 3 ``` * will return three days of data counting backwards from July 1st 2013 at 23:59:59 GMT resulting in all the * available bars of the last three days until the date and time specified. * * It is possible to specify a timezone optionally. * * The resulting bars will be emitted as historicalData event. * * @param reqId The request's unique identifier. * @param contract The contract for which we want to retrieve the data. * @param endDateTime Request's ending time with format yyyyMMdd HH:mm:ss {TMZ} * @param durationStr The amount of time for which the data needs to be retrieved (number space unit). * Note: min duration is "30 S", available units: * - S (seconds) * - D (days) * - W (weeks) * - M (months) * - Y (years) * @param barSizeSetting the size of the bar: * - 1 secs * - 5 secs * - 15 secs * - 30 secs * - 1 min * - 2 mins * - 3 mins * - 5 mins * - 15 mins * - 30 mins * - 1 hour * - 1 day * @param whatToShow the kind of information being retrieved: * - TRADES * - MIDPOINT * - BID * - ASK * - BID_ASK * - HISTORICAL_VOLATILITY * - OPTION_IMPLIED_VOLATILITY * - FEE_RATE * - REBATE_RATE * @param useRTH Set to `false` to obtain the data which was also generated outside of the Regular Trading Hours, set to `true` * to obtain only the RTH data * @param formatDate Set to 1 to obtain the bars' time as yyyyMMdd HH:mm:ss, set to 2 to obtain it like system time * format in seconds * @param keepUpToDate Set to `true` to received continuous updates on most recent bar data. If `true`, and * endDateTime cannot be specified. */ reqHistoricalData(reqId: number, contract: Contract, endDateTime: string, durationStr: string, barSizeSetting: BarSizeSetting, whatToShow: WhatToShow, useRTH: number | boolean, formatDate: number, keepUpToDate: boolean): IBApi; /** * Requests historical news headlines. * * @param reqId ID of the request. * @param conId Contract id of ticker. * @param providerCodes A '+'-separated list of provider codes . * @param startDateTime Marks the (exclusive) start of the date range. The format is yyyy-MM-dd HH:mm:ss.0 * @param endDateTime Marks the (inclusive) end of the date range. The format is yyyy-MM-dd HH:mm:ss.0 * @param totalResults The maximum number of headlines to fetch (1 - 300). */ reqHistoricalNews(reqId: number, conId: number, providerCodes: string, startDateTime: string, endDateTime: string, totalResults: number, historicalNewsOptions?: TagValue[]): IBApi; /** * Requests historical Time&Sales data for an instrument. * * @param reqId ID of the request. * @param contract [[Contract]] object that is subject of query * @param startDateTime "20170701 12:01:00". Uses TWS timezone specified at login. * @param endDateTime "20170701 13:01:00". In TWS timezone. Exactly one of start time and end time has to be defined. * @param numberOfTicks Number of distinct data points. Max currently 1000 per request. * @param whatToShow (Bid_Ask, Midpoint, Trades) Type of data requested. * @param useRTH Data from regular trading hours (1), or all available hours (0) * @param ignoreSize A filter only used when the source price is Bid_Ask */ reqHistoricalTicks(reqId: number, contract: Contract, startDateTime: string, endDateTime: string, numberOfTicks: number, whatToShow: WhatToShow, useRTH: number | boolean, ignoreSize: boolean): IBApi; /** * Requests the next valid order ID at the current moment. * * @param numIds deprecated- this parameter will not affect the value returned to nextValidId */ reqIds(numIds?: number): IBApi; /** * Requests the accounts to which the logged user has access to. */ reqManagedAccts(): IBApi; /** * Switches data type returned from reqMktData request to "frozen", "delayed" or "delayed-frozen" market data. * Requires TWS/IBG v963+. * * The API can receive frozen market data from Trader Workstation. * Frozen market data is the last data recorded in our system. * During normal trading hours, the API receives real-time market data. * Invoking this function with argument 2 requests a switch to frozen data immediately or after the close. * When the market reopens, the market data type will automatically switch back to real time if available. * * @param marketDataType By default only real-time (1) market data is enabled. * - 1 (real-time) disables frozen, delayed and delayed-frozen market data. * - 2 (frozen) enables frozen market data. * - 3 (delayed) enables delayed and disables delayed-frozen market data. * - 4 (delayed-frozen) enables delayed and delayed-frozen market data. */ reqMarketDataType(marketDataType: MarketDataType): IBApi; /** * Requests the contract's market depth (order book). * * This request must be direct-routed to an exchange and not smart-routed. * * The number of simultaneous market depth requests allowed in an account is calculated based on a formula * that looks at an accounts equity, commissions, and quote booster packs. * * @param reqId The request's identifier. * @param contract The [[Contract]] for which the depth is being requested. * @param numRows The number of rows on each side of the order book. * @param isSmartDepth Flag indicates that this is smart depth request. * @param mktDepthOptions TODO document * * @see [[cancelMktDepth]] */ reqMktDepth(reqId: number, contract: Contract, numRows: number, isSmartDepth: boolean, mktDepthOptions?: TagValue[]): IBApi; /** * Requests details about a given market rule. * The market rule for an instrument on a particular exchange provides details about how the minimum price increment * changes with price. A list of market rule ids can be obtained by invoking reqContractDetails on a particular * contract. The returned market rule ID list will provide the market rule ID for the instrument in the correspond * valid exchange list in contractDetails. * * @param marketRuleId The id of market rule. */ reqMarketRule(marketRuleId: number): IBApi; /** * Requests matching stock symbols. * * Thr result will be emitted as symbolSamples event. * * @param reqId ID to specify the request * @param pattern Either start of ticker symbol or (for larger strings) company name. */ reqMatchingSymbols(reqId: number, pattern: string): IBApi; /** * Requests real time market data. * Returns market data for an instrument either in real time or 10-15 minutes delayed (depending on the market data * type specified). * * @param reqId The request's identifier. * @param contract The [[Contract]] for which the data is being requested * @param genericTickList comma separated ids of the available generic ticks: * - 100 Option Volume (currently for stocks) * - 101 Option Open Interest (currently for stocks) * - 104 Historical Volatility (currently for stocks) * - 105 Average Option Volume (currently for stocks) * - 106 Option Implied Volatility (currently for stocks) * - 162 Index Future Premium * - 165 Miscellaneous Stats * - 221 Mark Price (used in TWS P&L computations) * - 225 Auction values (volume, price and imbalance) * - 233 RTVolume - contains the last trade price, last trade size, last trade time, total volume, VWAP, and single * trade flag. * - 236 Shortable * - 256 Inventory * - 258 Fundamental Ratios * - 411 Realtime Historical Volatility * - 456 IBDividends * @param snapshot For users with corresponding real time market data subscriptions. * A `true` value will return a one-time snapshot, while a `false` value will provide streaming data. * @param regulatorySnapshot Snapshot for US stocks requests NBBO snapshots for users which have "US Securities * Snapshot Bundle" subscription but not corresponding Network A, B, or C subscription necessary for streaming * * market data. One-time snapshot of current market price that will incur a fee of 1 cent to the account per * snapshot. * * @see [[cancelMktData]] */ reqMktData(reqId: number, contract: Contract, genericTickList: string, snapshot: boolean, regulatorySnapshot: boolean): IBApi; /** * Requests venues for which market data is returned to updateMktDepthL2 (those with market makers) */ reqMktDepthExchanges(): IBApi; /** * Requests news article body given articleId. * * @param requestId ID of the request. * @param providerCode Short code indicating news provider, e.g. FLY * @param articleId ID of the specific article. */ reqNewsArticle(requestId: number, providerCode: string, articleId: string, newsArticleOptions?: TagValue[]): IBApi; /** * Subscribes to IB's News Bulletins. * * @param allMsgs If set to `true, will return all the existing bulletins for the current day. * If set to `false` to receive only the new bulletins. * * @see [[cancelNewsBulletin]] */ reqNewsBulletins(allMsgs: boolean): IBApi; /** * Requests news providers which the user has subscribed to. */ reqNewsProviders(): IBApi; /** * Requests all open orders placed by this specific API client (identified by the API client id). * For client ID 0, this will bind previous manual TWS orders. */ reqOpenOrders(): IBApi; /** * Creates subscription for real time daily PnL and unrealized PnL updates. * * @param reqId ID of the request. * @param account Account for which to receive PnL updates. * @param modelCode Specify to request PnL updates for a specific model. */ reqPnL(reqId: number, account: string, modelCode?: string | null): IBApi; /** * Requests real time updates for daily PnL of individual positions. * * @param reqId ID of the request. * @param account Account in which position exists. * @param modelCode Model in which position exists. * @param conId Contract ID (conId) of contract to receive daily PnL updates for. * Note: does not return message if invalid conId is entered. */ reqPnLSingle(reqId: number, account: string, modelCode: string | null, conId: number): IBApi; /** * Subscribes to position updates for all accessible accounts. * All positions sent initially, and then only updates as positions change. * * @see [[cancelPositions]] */ reqPositions(): IBApi; /** * Requests position subscription for account and/or model. * Initially all positions are returned and then updates are returned for any position changes in real time. * * @param reqId Request's identifier. * @param account If an account Id is provided, only the account's positions belonging to the specified model will be * delivered. * @param modelCode The code of the model's positions we are interested in. * * @see [[cancelPositionsMulti]] */ reqPositionsMulti(reqId: number, account: string, modelCode: string | null): IBApi; /** * Requests real time bars. * * Currently, only 5 seconds bars are provided. * * This request is subject to the same pacing as any historical data request: no more than 60 API queries in more * than 600 seconds. Real time bars subscriptions are also included in the calculation of the number of Level 1 * market data subscriptions allowed in an account. * * @param reqId The request's unique identifier. * @param contract The [[Contract]] for which the depth is being requested * @param barSize currently being ignored * @param whatToShow the nature of the data being retrieved: * - TRADES * - MIDPOINT * - BID * - ASK * @param useRTH Set to `false` to obtain the data which was also generated ourside of the Regular Trading Hours. * Set to `true` to obtain only the RTH data * * @see [[cancelRealTimeBars]] */ reqRealTimeBars(reqId: number, contract: Contract, barSize: number, whatToShow: WhatToShow, useRTH: boolean, realTimeBarsOptions?: TagValue[]): IBApi; /** * Requests an XML list of scanner parameters valid in TWS. * * Not all parameters are valid from API scanner. * * @sse [[reqScannerSubscription]] */ reqScannerParameters(): IBApi; /** * Starts a subscription to market scan results based on the provided parameters. * * @param reqId The request's identifier. * @param subscription Summary of the scanner subscription including its filters. * @param scannerSubscriptionOptions TODO document * @param scannerSubscriptionFilterOptions TODO document * * @see [[reqScannerParameters]] */ reqScannerSubscription(reqId: number, subscription: ScannerSubscription, scannerSubscriptionOptions?: TagValue[], scannerSubscriptionFilterOptions?: TagValue[]): IBApi; /** * Requests security definition option parameters for viewing a contract's option chain. * * @param reqId The request's identifier. * @param underlyingSymbol Underlying symbol name. * @param futFopExchange The exchange on which the returned options are trading. * Can be set to the empty string "" for all exchanges. * @param underlyingSecType The type of the underlying security, i.e. STK * @param underlyingConId the contract ID of the underlying security */ reqSecDefOptParams(reqId: number, underlyingSymbol: string, futFopExchange: string, underlyingSecType: string, underlyingConId: number): IBApi; /** * Returns the mapping of single letter codes to exchange names given the mapping identifier. * * @param reqId The id of the request. * @param bboExchange The mapping identifier received from on tickReqParams event. */ reqSmartComponents(reqId: number, bboExchange: string): IBApi; /** * Requests pre-defined Soft Dollar Tiers. * * This is only supported for registered professional advisors and hedge and mutual funds who have configured Soft * Dollar Tiers in Account Management. * * Refer to: * https://www.interactivebrokers.com/en/software/am/am/manageaccount/requestsoftdollars.htm?Highlight=soft%20dollar%20tier. * * @param reqId The id of the request. */ reqSoftDollarTiers(reqId: number): IBApi; /** * Requests tick-by-tick data. * * @param reqId Unique identifier of the request. * @param contract The [[Contract]] for which tick-by-tick data is requested. * @param tickType tick-by-tick data type: "Last", "AllLast", "BidAsk" or "MidPoint". * @param numberOfTicks number of ticks. * @param ignoreSize ignore size flag. */ reqTickByTickData(reqId: number, contract: Contract, tickType: TickByTickDataType, numberOfTicks: number, ignoreSize: boolean): IBApi; /** * Requests the FA configuration A Financial Advisor can define three different configurations: * * - 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. * * More information at * https://www.interactivebrokers.com/en/?f=%2Fen%2Fsoftware%2Fpdfhighlights%2FPDF-AdvisorAllocations.php%3Fib_entity%3Dllc * * @param faDataType The configuration to change. Set to 1, 2 or 3 as defined above. */ requestFA(faDataType: number): IBApi; /** * Integrates API client and TWS window grouping. * * @param reqId The Id chosen for this subscription request. * @param groupId The display group for integration. */ subscribeToGroupEvents(reqId: number, groupId: number): IBApi; /** * Updates the contract displayed in a TWS Window Group. * * @param reqId The ID chosen for this request. * @param contractInfo An encoded value designating a unique IB contract. * Possible values include: * - none = empty selection * - contractID = any non-combination contract. Examples 8314 for IBM SMART; 8314 for IBM ARCA * - combo = if any combo is selected Note: This request from the API does not get a TWS response unless an error * occurs. */ updateDisplayGroup(reqId: number, contractInfo: string): IBApi; /** * Cancels a TWS Window Group subscription. * * @param reqId The request ID. * * @sse [[subscribeToGroupEvents]] */ unsubscribeFromGroupEvents(reqId: number): IBApi; /** * Changes the TWS/GW log level. * * The default is [[LOG_LEVEL.ERROR]] * * @param logLevel The log level. */ setServerLogLevel(logLevel: LogLevel): IBApi; /** * Requests the user info of the logged user. */ reqUserInfo(reqId: number): IBApi; } export declare interface IBApi { /** * Notifies when an event has been received (called for the any type for event). * * @param listener * event: Name of the event. * * arguments: event arguments. */ on(event: EventName.all, listener: (event: string, arguments: string[]) => void): this; /** * Notifies when the connection to TWS/IB Gateway has been established successfully. * * @param listener Notification callback. * * @see [[connect]] */ on(event: EventName.connected, listener: () => void): this; /** * Notifies that the TCP socket connection to the TWS/IB Gateway has been disconnected. * * @param listener Notification callback. * * @see [[disconnect]] */ on(event: EventName.disconnected, listener: () => void): this; /** * Provides status information messages for development / logging purpose. * * message: Message text. * code: Message code. */ on(event: EventName.info, listener: (message: string, code: number) => void): this; /** * Notifies about an error and TCP socket connection to the TWS/IB Gateway. * * `disconnected` event will arrive soon afterwards. * * @param listener * error: The error details. * * code: The code identifying the error. * * reqId: The request identifier which generated the error. */ on(event: EventName.error, listener: (error: Error, code: ErrorCode, reqId: number, advancedOrderReject?: unknown) => void): this; /** * Notifies about the API server version. * * Will arrive soon after `connected` event. * * @param listener * serverVersion: The server version. * serverConnectionTime: The connection time. * * @see [[connect]] */ on(event: EventName.server, listener: (serverVersion: number, serverConnectionTime: string) => void): this; /** * Notifies when data has been received from the server. * * @param listener * tokens: Array of received tokens. */ on(event: EventName.received, listener: (tokens: string[]) => void): this; /** * Notifies when data is sent to the server. * * @param listener * tokens: Array of token to be sent. */ on(event: EventName.sent, listener: (tokens: string[]) => void): this; /** * Notifies about the the result to request. * * @param listener * event: Name of the event. * * arguments: event arguments. */ on(event: EventName.result, listener: (event: string, arguments: string[]) => void): this; /** * Notifies when all the account's information has finished. * * @param listener * account: The account's id * * @see [[reqAccountUpdates]] */ on(event: EventName.accountDownloadEnd, listener: (account: string) => void): this; /** * Receives the account information. * This method will receive the account information just as it appears in the TWS' Account Summary Window. * * @param listener * reqID: The request's unique identifier. * * account: The account id. * * tag: The account's attribute being received. Possible values: * - 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 * - PreviousDayEquityWithLoanValue: 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 * * value: the account's attribute's value. * * @see [[reqAccountSummary]] */ on(event: EventName.accountSummary, listener: (reqId: number, account: string, tag: string, value: string, currency: string) => void): this; /** * Notifies when all the accounts' information has ben received. * * Requires TWS 967+ to receive accountSummaryEnd in linked account structures. * * @param listener * reqID: The request's unique identifier. * * @see [[reqAccountSummary]] */ on(event: EventName.accountSummaryEnd, listener: (reqId: number) => void): this; /** * Provides the account updates. * * @param listener * requestId: The id of request. * * account: The account with updates. * * modelCode: The model code with updates. * * key: The name of parameter. * * value: The value of parameter. * * currency: The currency of parameter. * * @see [[reqAccountUpdatesMulti]] */ on(event: EventName.accountUpdateMulti, listener: (reqId: number, account: string, modelCode: string, key: string, value: string, currency: string) => void): this; /** * Indicates all the account updates have been transmitted. * * @param listener * requestId: The id of request. * * @see [[reqAccountUpdatesMulti]] */ on(event: EventName.accountUpdateMultiEnd, listener: (reqId: number) => void): this; /** * Delivers the Bond cont