Class IBApi

Typescript implementation of the Interactive Brokers TWS (or IB Gateway) API.

Refer to the official Workstation API documentation for details.

Hierarchy

  • EventEmitter
    • IBApi

Constructors

Properties

Accessors

Methods

Constructors

Properties

controller: Controller

The I/O queue controller object.

prefixed: string | boolean

Accessors

  • get isConnected(): boolean
  • Returns true if currently connected to server, false otherwise.

    Returns boolean

  • get serverVersion(): number
  • Get the IB API Server version.

    Returns number

    See

    [[MIN_SERVER_VER]]

Methods

  • Type Parameters

    • T extends string | symbol

    Parameters

    • event: T
    • fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    • Optional context: any

    Returns 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.

    Parameters

    • reqId: number

      Unique identifier of the request.

    • contract: Contract

      The option's contract for which the volatility wants to be calculated.

    • optionPrice: number

      Hypothetical option price.

    • underPrice: number

      Hypothetical option's underlying price.

    Returns IBApi

    See

    [[cancelCalculateImpliedVolatility]]

  • Calculates an option's price based on the provided volatility and its underlying price. The calculation will be emitted as tickOptionComputation event.

    Parameters

    • reqId: number

      Unique identifier of the request.

    • contract: Contract

      The option's contract for which the price wants to be calculated.

    • volatility: number

      Hypothetical volatility.

    • underPrice: number

      Hypothetical underlying price.

    Returns IBApi

    See

    [[cancelCalculateOptionPrice]]

  • Cancels the account's summary request. After requesting an account's summary, invoke this function to cancel it.

    Parameters

    • reqId: number

      The identifier of the previously performed account request.

    Returns IBApi

    See

    [[reqAccountSummary]]

  • Cancels account updates request for account and/or model.

    Parameters

    • reqId: number

      Account subscription to cancel.

    Returns IBApi

    See

    [[reqAccountUpdatesMulti]]

  • Cancels an option's implied volatility calculation request.

    Parameters

    • reqId: number

      The identifier of the implied volatility's calculation request.

    Returns IBApi

    See

    [[calculateImpliedVolatility]]

  • Cancels an option's price calculation request.

    Parameters

    • reqId: number

      The identifier of the option's price's calculation request.

    Returns IBApi

    See

    [[calculateOptionPrice]]

  • Cancels Fundamental data request.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqFundamentalData]]

  • Cancels a pending [[reqHeadTimeStamp]] request.

    Parameters

    • reqId: number

      Id of the request

    Returns IBApi

    See

    [[reqHeadTimeStamp]]

  • Cancels a historical data request.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqHistogramData]]

  • Cancels a historical data request.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqHistoricalData]]

  • Cancels a RT Market Data request.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqMktData]]

  • Cancel a market depth's request.

    Parameters

    • reqId: number

      The request's identifier.

    • isSmartDepth: boolean

      TODO document

    Returns IBApi

    See

    [[reqMktDepth]]

  • 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.

    Parameters

    • orderId: number

    Returns IBApi

    See

    [[placeOrder]], [[reqGlobalCancel]]

  • Cancels subscription for real time updated daily PnL.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqPnL]]

  • Cancels real time subscription for a positions daily PnL information.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

    See

    [[reqPnLSingle]]

  • Cancels a previous position subscription request made with reqPositions.

    Returns IBApi

    See

    [[reqPositions]]

  • Cancels positions request for account and/or model.

    Parameters

    • reqId: number

      The identifier of the request to be canceled.

    Returns IBApi

    See

    [[reqPositionsMulti]]

  • Cancels Real Time Bars' subscription.

    Parameters

    • reqId: number

      The request's identifier.

    Returns IBApi

  • Cancels Scanner Subscription.

    Parameters

    • reqId: number

      The subscription's unique identifier.

    Returns IBApi

    See

    [[reqScannerSubscription]], [[reqScannerParameters]]

  • Cancels tick-by-tick data.

    Parameters

    • reqId: number

      Unique identifier of the request.

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Connect to the TWS or IB Gateway.

    Parameters

    • Optional clientId: number

      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.

    Returns IBApi

  • Allows to switch between different current (V100+) and previous connection mechanisms.

    Returns void

    Deprecated

    pre-V100 support will be removed. Please consider updating your TWS and/or IB Gateway version.

  • Calls each of the listeners registered for a given event.

    Type Parameters

    • T extends string | symbol

    Parameters

    • event: T
    • Rest ...args: any[]

    Returns boolean

  • Return an array listing the events for which the emitter has registered listeners.

    Returns (string | symbol)[]

  • Exercises an options contract.

    Note: this function is affected by a TWS setting which specifies if an exercise request must be finalized.

    Parameters

    • reqId: number

      The exercise request's identifier.

    • contract: Contract

      The option [[Contract]] to be exercised.

    • exerciseAction: OptionExerciseAction

      1 to exercise the option, 2 to let the option lapse.

    • exerciseQuantity: number

      Number of contracts to be exercised.

    • account: string

      Destination account.

    • override: number

      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.

    Returns IBApi

  • Return the number of listeners listening to a given event.

    Parameters

    • event: string | symbol

    Returns number

  • Return the listeners registered for a given event.

    Type Parameters

    • T extends string | symbol

    Parameters

    • event: T

    Returns ((...args) => void)[]

  • Type Parameters

    • T extends string | symbol

    Parameters

    • event: T
    • Optional fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    • Optional context: any
    • Optional once: boolean

    Returns IBApi

  • Notifies when an event has been received (called for the any type for event).

    Parameters

    • event: all
    • listener: ((event, arguments) => void)

      event: Name of the event.

      arguments: event arguments.

        • (event, arguments): void
        • Parameters

          • event: string
          • arguments: string[]

          Returns void

    Returns IBApi

  • Notifies when the connection to TWS/IB Gateway has been established successfully.

    Parameters

    • event: connected
    • listener: (() => void)

      Notification callback.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[connect]]

  • Notifies that the TCP socket connection to the TWS/IB Gateway has been disconnected.

    Parameters

    • event: disconnected
    • listener: (() => void)

      Notification callback.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[disconnect]]

  • Provides status information messages for development / logging purpose.

    message: Message text. code: Message code.

    Parameters

    • event: info
    • listener: ((message, code) => void)
        • (message, code): void
        • Parameters

          • message: string
          • code: number

          Returns void

    Returns IBApi

  • Notifies about an error and TCP socket connection to the TWS/IB Gateway.

    disconnected event will arrive soon afterwards.

    Parameters

    • event: error
    • listener: ((error, code, reqId, advancedOrderReject?) => void)

      error: The error details.

      code: The code identifying the error.

      reqId: The request identifier which generated the error.

        • (error, code, reqId, advancedOrderReject?): void
        • Parameters

          • error: Error
          • code: ErrorCode
          • reqId: number
          • Optional advancedOrderReject: unknown

          Returns void

    Returns IBApi

  • Notifies about the API server version.

    Will arrive soon after connected event.

    Parameters

    • event: server
    • listener: ((serverVersion, serverConnectionTime) => void)

      serverVersion: The server version.

      serverConnectionTime: The connection time.

        • (serverVersion, serverConnectionTime): void
        • Parameters

          • serverVersion: number
          • serverConnectionTime: string

          Returns void

    Returns IBApi

    See

    [[connect]]

  • Notifies when data has been received from the server.

    Parameters

    • event: received
    • listener: ((tokens) => void)

      tokens: Array of received tokens.

        • (tokens): void
        • Parameters

          • tokens: string[]

          Returns void

    Returns IBApi

  • Notifies when data is sent to the server.

    Parameters

    • event: sent
    • listener: ((tokens) => void)

      tokens: Array of token to be sent.

        • (tokens): void
        • Parameters

          • tokens: string[]

          Returns void

    Returns IBApi

  • Notifies about the the result to request.

    Parameters

    • event: result
    • listener: ((event, arguments) => void)

      event: Name of the event.

      arguments: event arguments.

        • (event, arguments): void
        • Parameters

          • event: string
          • arguments: string[]

          Returns void

    Returns IBApi

  • Notifies when all the account's information has finished.

    Parameters

    • event: accountDownloadEnd
    • listener: ((account) => void)

      account: The account's id

        • (account): void
        • Parameters

          • account: string

          Returns void

    Returns IBApi

    See

    [[reqAccountUpdates]]

  • Receives the account information. This method will receive the account information just as it appears in the TWS' Account Summary Window.

    Parameters

    • event: accountSummary
    • listener: ((reqId, account, tag, value, currency) => void)

      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.

        • (reqId, account, tag, value, currency): void
        • Parameters

          • reqId: number
          • account: string
          • tag: string
          • value: string
          • currency: string

          Returns void

    Returns IBApi

    See

    [[reqAccountSummary]]

  • Notifies when all the accounts' information has ben received.

    Requires TWS 967+ to receive accountSummaryEnd in linked account structures.

    Parameters

    • event: accountSummaryEnd
    • listener: ((reqId) => void)

      reqID: The request's unique identifier.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqAccountSummary]]

  • Provides the account updates.

    Parameters

    • event: accountUpdateMulti
    • listener: ((reqId, account, modelCode, key, value, currency) => void)

      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.

        • (reqId, account, modelCode, key, value, currency): void
        • Parameters

          • reqId: number
          • account: string
          • modelCode: string
          • key: string
          • value: string
          • currency: string

          Returns void

    Returns IBApi

    See

    [[reqAccountUpdatesMulti]]

  • Indicates all the account updates have been transmitted.

    Parameters

    • event: accountUpdateMultiEnd
    • listener: ((reqId) => void)

      requestId: The id of request.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqAccountUpdatesMulti]]

  • Delivers the Bond contract data after this has been requested via reqContractDetails.

    Parameters

    • event: bondContractDetails
    • listener: ((reqId, contract) => void)

      reqId: The request's identifier.

      contract: The bond contract's information.

        • (reqId, contract): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqAccountUpdatesMulti]]

  • Provides the [[CommissionReport]] of an [[Execution]]

    Parameters

    • event: commissionReport
    • listener: ((commissionReport) => void)

      commissionReport: The commission report.

        • (commissionReport): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqExecutions]]

  • Feeds in completed orders.

    Parameters

    • event: completedOrder
    • listener: ((contract, order, orderState) => void)

      contract: The order's [[Contract]].

      order: The completed [[Order]].

      orderState: The order's [[OrderState]].

        • (contract, order, orderState): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqCompletedOrders]]

  • Notifies the end of the completed orders' reception.

    Parameters

    • event: completedOrdersEnd
    • listener: (() => void)

      Completion callback function.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[reqCompletedOrders]]

  • Returns meta data from the WSH calendar.

    Parameters

    • event: wshMetaData
    • listener: ((reqId, dataJson) => void)

      reqId: The unique request identifier.

      dataJson: metadata in json format

        • (reqId, dataJson): void
        • Parameters

          • reqId: number
          • dataJson: string

          Returns void

    Returns IBApi

    See

    [[reqWshMetaData]]

  • Returns calendar events from the WSH.

    Parameters

    • event: wshEventData
    • listener: ((reqId, dataJson) => void)

      reqId: The unique request identifier.

      dataJson: event data in json format

        • (reqId, dataJson): void
        • Parameters

          • reqId: number
          • dataJson: string

          Returns void

    Returns IBApi

    See

    [[reqWshEventData]]

  • 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.

    Parameters

    • event: connectionClosed
    • listener: (() => void)

      Connection closed callback function.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[disconnect]]

  • Receives the full contract's definitions. This method will return all contracts matching the requested via [[reqContractDetails]] For example, one can obtain the whole option chain with it.

    Parameters

    • event: contractDetails
    • listener: ((reqId, contractDetails) => void)

      reqId: The unique request identifier.

      contractDetails: The instrument's complete definition.

        • (reqId, contractDetails): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqContractDetails]]

  • After all contracts matching the request were returned, this method will mark the end of their reception.

    Parameters

    • event: contractDetailsEnd
    • listener: ((reqId) => void)

      reqId: the request's identifier

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqContractDetails]]

  • 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.

    Parameters

    • event: currentTime
    • listener: ((time) => void)

      time: The current time in TWS.

        • (time): void
        • Parameters

          • time: number

          Returns void

    Returns IBApi

    See

    [[reqCurrentTime]]

  • 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.

    Parameters

    • event: deltaNeutralValidation
    • listener: ((reqId, deltaNeutralContract) => void)

      reqId: The request's identifier.

      deltaNeutralContract Delta-Neutral [[Contract]].

        • (reqId, deltaNeutralContract): void
        • Parameters

          Returns void

    Returns IBApi

  • When requesting market data snapshots, this market will indicate the snapshot reception is finished.

    Expected to occur 11 seconds after beginning of request.

    Parameters

    • event: tickSnapshotEnd
    • listener: ((reqId) => void)

      reqId: The request's identifier.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

  • Returns the market data type (real-time, frozen, delayed, delayed-frozen) of ticker sent by [[reqMktData]] when TWS switches from real-time to frozen and back and from delayed to delayed-frozen and back.

    Parameters

    • event: marketDataType
    • listener: ((reqId, marketDataType) => void)

      reqId: The request's identifier.

      marketDataType: Signals that now API starts to tick with the following market data:

      • 1: real-time
      • 2: frozen
      • 3: delayed
      • 4: delayed-frozen
        • (reqId, marketDataType): void
        • Parameters

          • reqId: number
          • marketDataType: number

          Returns void

    Returns IBApi

  • A one-time response to querying the display groups.

    Parameters

    • event: displayGroupList
    • listener: ((reqId, groups) => void)

      reqId: The ID of the request.

      groups: A list of integers representing visible Group ID separated by the "|" character, and sorted by most used group first.

        • (reqId, groups): void
        • Parameters

          • reqId: number
          • groups: string

          Returns void

    Returns IBApi

    See

    [[queryDisplayGroups]]

  • Call triggered once after receiving the subscription request, and will be sent again if the selected contract in the subscribed display group has changed.

    Parameters

    • event: displayGroupUpdated
    • listener: ((reqId, contractInfo) => void)

      reqId: The ID of the request.

      contractInfo: The contract information.

        • (reqId, contractInfo): void
        • Parameters

          • reqId: number
          • contractInfo: string

          Returns void

    Returns IBApi

    See

    [[subscribeToGroupEvents]]

  • 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 API implementation.

    Parameters

    • event: error
    • listener: ((error) => void)

      error: The thrown exception.

        • (error): void
        • Parameters

          • error: Error

          Returns void

    Returns IBApi

  • Errors sent by the TWS are received here.

    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 API implementation.

    Parameters

    • event: error
    • listener: ((id, errorCode, errorMsg, advancedOrderReject?) => void)

      id: The request identifier which generated the error. Note: -1 will indicate a notification and not true error condition.

      errorCode: The code identifying the error.

      errorMsg: Error's description. Currently Latin-1 encoded error messages are supported. If logged into TWS in a different language it is recommended to enabled the setting in TWS Global Configuration -> API -> Settings -> Show API errors in English.

        • (id, errorCode, errorMsg, advancedOrderReject?): void
        • Parameters

          • id: number
          • errorCode: number
          • errorMsg: string
          • Optional advancedOrderReject: unknown

          Returns void

    Returns IBApi

  • Provides the executions which happened in the last 24 hours.

    Parameters

    • event: execDetails
    • listener: ((reqId, contract, execution) => void)

      reqId: The request's identifier.

      contract: The [[Contract]] of the [[Order]].

      execution: The [[Execution]] details.

        • (reqId, contract, execution): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqExecutions]]

  • Indicates the end of the [[Execution]] reception.

    Parameters

    • event: execDetailsEnd
    • listener: ((reqId) => void)

      reqId The request's identifier.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqExecutions]]

  • Returns array of family codes.

    Parameters

    • event: familyCodes
    • listener: ((familyCodes) => void)

      familyCodes Array of family codes.

        • (familyCodes): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqFamilyCodes]]

  • Returns array of sample contract descriptions.

    Parameters

    • event: contractDescriptions
    • listener: ((reqId, contractDescriptions) => void)

      contractDescriptions Array of contract descriptions.

        • (reqId, contractDescriptions): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqFamilyCodes]]

  • Returns fundamental data.

    Parameters

    • event: fundamentalData
    • listener: ((reqId, data) => void)

      reqId: The request's identifier.

      data: xml-formatted fundamental data.

        • (reqId, data): void
        • Parameters

          • reqId: number
          • data: string

          Returns void

    Returns IBApi

    See

    [[reqFundamentalData]]

  • Returns beginning of data for contract for specified data type.

    Parameters

    • event: headTimestamp
    • listener: ((reqId, headTimestamp) => void)

      reqId: The request's identifier.

      headTimestamp: string identifying earliest data.

        • (reqId, headTimestamp): void
        • Parameters

          • reqId: number
          • headTimestamp: string

          Returns void

    Returns IBApi

    See

    [[reqHeadTimestamp]]

  • Returns data histogram.

    Parameters

    • event: histogramData
    • listener: ((reqId, data) => void)

      reqId: The request's identifier.

      data: Tuple of histogram data, number of trades at specified price level.

        • (reqId, data): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqHistogramData]]

  • Returns the requested historical data bars.

    Parameters

    • event: historicalData
    • listener: ((reqId, time, open, high, low, close, volume, count, WAP, hasGaps) => void)

      reqId: the request's identifier

      time: the time the bar represents open: price at open of time period high: high price during time period low: low price during time period close: price at close of time period volume: share volume during time period count: trade count during time period WAP: weighted average price hasGaps: identifies whether or not there are gaps in the data. The time zone of the bar is the time zone chosen on the TWS login screen. Smallest bar size is 1 second.

        • (reqId, time, open, high, low, close, volume, count, WAP, hasGaps): void
        • Parameters

          • reqId: number
          • time: string
          • open: number
          • high: number
          • low: number
          • close: number
          • volume: number
          • count: number
          • WAP: number
          • hasGaps: boolean

            Deprecated

          Returns void

    Returns IBApi

    See

    https://interactivebrokers.github.io/tws-api/historical_bars.html#hd_what_to_show for additional context regarding meaning of price for different bar types

  • Receives bars in real time if keepUpToDate is 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.

    Parameters

    • event: historicalDataUpdate
    • listener: ((reqId, time, open, high, low, close, volume, count, WAP) => void)

      reqId: The request's identifier.

      time: the time the bar represents open: price at open of time period high: high price during time period low: low price during time period close: price at close of time period volume: share volume during time period count: trade count during time period WAP: weighted average price The time zone of the bar is the time zone chosen on the TWS login screen. Smallest bar size is 1 second.

        • (reqId, time, open, high, low, close, volume, count, WAP): void
        • Parameters

          • reqId: number
          • time: string
          • open: number
          • high: number
          • low: number
          • close: number
          • volume: number
          • count: number
          • WAP: number

          Returns void

    Returns IBApi

    See

    [[reqHistoricalData]]

  • Parameters

    • event: historicalNews
    • listener: ((reqId, time, providerCode, articleId, headline) => void)
        • (reqId, time, providerCode, articleId, headline): void
        • Parameters

          • reqId: number
          • time: string
          • providerCode: string
          • articleId: string
          • headline: string

          Returns void

    Returns IBApi

  • Returns news headline.

    Parameters

    • event: historicalNewsEnd
    • listener: ((reqId, hasMore) => void)

      reqId: The request's identifier.

      hasMore: true if there are more results available, false otherwise

        • (reqId, hasMore): void
        • Parameters

          • reqId: number
          • hasMore: boolean

          Returns void

    Returns IBApi

    See

    [[reqHistoricalNews]]

  • Returns historical price tick data.

    Parameters

    • event: historicalTicks
    • listener: ((reqId, ticks, done) => void)

      reqId: The request's identifier.

      ticks: Array of [[HistoricalTick]] objects.

      done: Flag to indicate if all historical tick data has been received.

        • (reqId, ticks, done): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqHistoricalTicks]]

  • Returns historical bid/ask tick data.

    Parameters

    • event: historicalTicksBidAsk
    • listener: ((reqId, ticks, done) => void)

      reqId: The request's identifier.

      ticks: Array of [[HistoricalTickBidAsk]] objects.

      done: Flag to indicate if all historical tick data has been received.

        • (reqId, ticks, done): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqHistoricalTicks]]

  • Returns historical last price tick data.

    Parameters

    • event: historicalTicksLast
    • listener: ((reqId, ticks, done) => void)

      reqId: The request's identifier.

      ticks: Array of [[HistoricalTickLas]] objects.

      done: Flag to indicate if all historical tick data has been received.

        • (reqId, ticks, done): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqHistoricalTicks]]

  • Receives a comma-separated string with the managed account ids. Occurs automatically on initial API client connection.

    Parameters

    • event: managedAccounts
    • listener: ((accountsList) => void)

      accountsList: A comma-separated string with the managed account ids.

        • (accountsList): void
        • Parameters

          • accountsList: string

          Returns void

    Returns IBApi

    See

    [[reqManagedAccts]]

  • 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.

    Parameters

    • event: marketRule
    • listener: ((marketRuleId, priceIncrements) => void)

      marketRuleId: The Market rule IDs.

      priceIncrements: Array of price increments.

        • (marketRuleId, priceIncrements): void
        • Parameters

          • marketRuleId: number
          • priceIncrements: unknown[]

          Returns void

    Returns IBApi

    See

    [[reqMarketRule]]

  • Called when receives Depth Market Data Descriptions.

    Parameters

    • event: mktDepthExchanges
    • listener: ((depthMktDataDescriptions) => void)

      depthMktDataDescriptions: Array of [[DepthMktDataDescription]] objects.

    Returns IBApi

    See

    [[reqMktDepthExchanges]]

  • Called when receives News Article.

    Parameters

    • event: newsArticle
    • listener: ((reqId, articleType, articleText) => void)

      reqId: The request ID.

      articleType: The type of news article (0 - plain text or html, 1 - binary data / pdf)

      articleText: The body of article (if articleType == 1, the binary data is encoded using the Base64 scheme)

        • (reqId, articleType, articleText): void
        • Parameters

          • reqId: number
          • articleType: number
          • articleText: string

          Returns void

    Returns IBApi

    See

    [[reqNewsArticle]]

  • Returns array of subscribed API news providers for this user

    Parameters

    • event: newsProviders
    • listener: ((newsProviders) => void)

      newsProviders: Array of [NewsProvider]] objects.

        • (newsProviders): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqNewsProviders]]

  • Receives next valid order id. Will be invoked automatically upon successful API client connection, or after call to [[reqIds]].

    Important: the next valid order ID is only valid at the time it is received.

    Parameters

    • event: nextValidId
    • listener: ((orderId) => void)

      orderId: The next order id.

        • (orderId): void
        • Parameters

          • orderId: number

          Returns void

    Returns IBApi

    See

    [[reqIds]]

  • Feeds in currently open orders.

    Parameters

    • event: openOrder
    • listener: ((orderId, contract, order, orderState) => void)

      orderId: The order's unique id.

      contract: The order's [[Contract]]

      order: The currently active [[Order]]

      orderState: The order's [[OrderState]]

        • (orderId, contract, order, orderState): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[placeOrder]], [[reqAllOpenOrders]], [[reqAutoOpenOrders]]

  • Notifies the end of the open orders' reception.

    Parameters

    • event: openOrderEnd
    • listener: (() => void)

      Completion callback.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[placeOrder]], [[reqAllOpenOrders]], [[reqAutoOpenOrders]]

  • Response to API bind order control message.

    Parameters

    • event: orderBound
    • listener: ((orderId, apiClientId, apiOrderId) => void)

      Completion callback. orderId: permId

      apiClientId: API client id.

      apiOrderId: API order id.

        • (orderId, apiClientId, apiOrderId): void
        • Parameters

          • orderId: number
          • apiClientId: number
          • apiOrderId: number

          Returns void

    Returns IBApi

    See

    [[reqOpenOrders]]

  • Gives the up-to-date information of an order every time it changes. Often there are duplicate orderStatus messages.

    Parameters

    • event: orderStatus
    • listener: ((orderId, status, filled, remaining, avgFillPrice, permId?, parentId?, lastFillPrice?, clientId?, whyHeld?, mktCapPrice?) => void)

      Completion callback. orderId: The order's client id.

      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 cancellation, 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.

      filled: Number of filled positions.

      remaining: The remnant positions.

      avgFillPrice: Average filling price.

      permId the order's permId used by the TWS to identify orders.

      parentId: parent's id. Used for bracket and auto trailing stop orders.

      lastFillPrice: Price at which the last positions were filled.

      clientId: API client which submitted the order.

      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'.

      mktCapPrice: If an order has been capped, this indicates the current capped price. Requires TWS 967+ and API v973.04+.

        • (orderId, status, filled, remaining, avgFillPrice, permId?, parentId?, lastFillPrice?, clientId?, whyHeld?, mktCapPrice?): void
        • Parameters

          • orderId: number
          • status: string
          • filled: number
          • remaining: number
          • avgFillPrice: number
          • Optional permId: number
          • Optional parentId: number
          • Optional lastFillPrice: number
          • Optional clientId: number
          • Optional whyHeld: string
          • Optional mktCapPrice: number

          Returns void

    Returns IBApi

    See

    [[placeOrder]], [[reqAllOpenOrders]], [[reqAutoOpenOrders]]

  • Receives PnL updates in real time for the daily PnL and the total unrealized PnL for an account.

    Parameters

    • event: pnl
    • listener: ((reqId, dailyPnL, unrealizedPnL?, realizedPnL?) => void)

      reqId: The request ID.

      dailyPnL: The dailyPnL updates for the account in real time.

      unrealizedPnL: The total unrealized PnL updates for the account in real time.

      unrealizedPnL: The total realized PnL updates for the account in real time.

        • (reqId, dailyPnL, unrealizedPnL?, realizedPnL?): void
        • Parameters

          • reqId: number
          • dailyPnL: number
          • Optional unrealizedPnL: number
          • Optional realizedPnL: number

          Returns void

    Returns IBApi

    See

    [[reqPnL]]

  • Receives real time updates for single position daily PnL values.

    Parameters

    • event: pnlSingle
    • listener: ((reqId, pos, dailyPnL, unrealizedPnL, realizedPnL, value) => void)

      reqId: The request ID.

      pos: Current size of the position

      dailyPnL: The daily PnL for the position

      unrealizedPnL: The total unrealized PnL for the position (since inception) updating in real time.

      value: The current market value of the position.

        • (reqId, pos, dailyPnL, unrealizedPnL, realizedPnL, value): void
        • Parameters

          • reqId: number
          • pos: number
          • dailyPnL: number
          • unrealizedPnL: number
          • realizedPnL: number
          • value: number

          Returns void

    Returns IBApi

    See

    [[reqSinglePnL]]

  • Provides the portfolio's open positions.

    Parameters

    • event: position
    • listener: ((account, contract, pos, avgCost?) => void)

      account: The account holding the position.

      contract: The position's [[Contract]]

      pos: The number of positions held.

      avgCost: The average cost of the position.

        • (account, contract, pos, avgCost?): void
        • Parameters

          • account: string
          • contract: Contract
          • pos: number
          • Optional avgCost: number

          Returns void

    Returns IBApi

    See

    [[reqPositions]]

  • Indicates all the positions have been transmitted.

    Parameters

    • event: positionEnd
    • listener: (() => void)

      Completion callback.

        • (): void
        • Returns void

    Returns IBApi

    See

    [[reqPnL]]

  • Provides the portfolio's open positions.

    Parameters

    • event: positionMulti
    • listener: ((reqId, account, modelCode, contract, pos, avgCost) => void)

      reqId: The request ID.

      account: The account holding the position.

      modelCode: The model code holding the position.

      contract: The position's [[Contract]]

      pos: The number of positions held.

      avgCost: The average cost of the position.

        • (reqId, account, modelCode, contract, pos, avgCost): void
        • Parameters

          • reqId: number
          • account: string
          • modelCode: string
          • contract: Contract
          • pos: number
          • avgCost: number

          Returns void

    Returns IBApi

    See

    [[reqPositionsMulti]]

  • Indicates all the positions have been transmitted.

    Parameters

    • event: positionMultiEnd
    • listener: ((reqId) => void)

      reqId: The request ID.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqPositionsMulti]]

  • Updates the real time 5 seconds bars.

    Parameters

    • event: realtimeBar
    • listener: ((reqId, date, open, high, low, close, volume, WAP, count) => void)

      reqId: The request ID. date: The bar's date and time (Epoch/Unix time). open: The bar's open point. high: The bar's high point. low: The bar's low point. close: The bar's closing point. volume: The bar's traded volume (only returned for TRADES data). WAP: the bar's Weighted Average Price rounded to minimum increment (only available for TRADES). count: the number of trades during the bar's timespan (only available for TRADES).

        • (reqId, date, open, high, low, close, volume, WAP, count): void
        • Parameters

          • reqId: number
          • date: number
          • open: number
          • high: number
          • low: number
          • close: number
          • volume: number
          • WAP: number
          • count: number

          Returns void

    Returns IBApi

    See

    [[reqRealTimeBars]]

  • Receives the Financial Advisor's configuration available in the TWS.

    Parameters

    • event: receiveFA
    • listener: ((faDataType, faXmlData) => void)

      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.

      faXmlData: The xml-formatted configuration.

        • (faDataType, faXmlData): void
        • Parameters

          • faDataType: number
          • faXmlData: string

          Returns void

    Returns IBApi

    See

    [[requestFA]], [[replaceFA]]

  • Notifies the end of the FA replace.

    Parameters

    • event: replaceFAEnd
    • listener: ((reqId, text) => void)

      reqId: The id of request.

      text: The message text.

        • (reqId, text): void
        • Parameters

          • reqId: number
          • text: string

          Returns void

    Returns IBApi

    See

    [[requestFA]], [[replaceFA]]

  • Returns conId and exchange for CFD market data request re-route.

    Parameters

    • event: rerouteMktDataReq
    • listener: ((reqId, conId, exchange) => void)

      reqId: The id of request.

      conId: Contract Id of the underlying instrument which has market data.

      exchange: Exchange code of the underlying.

        • (reqId, conId, exchange): void
        • Parameters

          • reqId: number
          • conId: number
          • exchange: string

          Returns void

    Returns IBApi

  • 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.

    Parameters

    • event: rerouteMktDepthReq
    • listener: ((reqId, conId, exchange) => void)

      reqId: The id of request.

      conId: Contract Id of the underlying instrument which has market data.

      exchange: Exchange code of the underlying.

        • (reqId, conId, exchange): void
        • Parameters

          • reqId: number
          • conId: number
          • exchange: string

          Returns void

    Returns IBApi

  • Provides the data resulting from the market scanner request.

    Parameters

    • event: scannerData
    • listener: ((reqId, rank, contractDetails, distance, benchmark, projection, legsStr?) => void)

      reqId: The id of request.

      rank: The ranking within the response of this bar.

      contractDetails: The data [[ContractDetails].

      distance: variable, according to query.

      benchmark: variable, according to query.

      projection: variable, according to query.

      legStr: Describes the combo legs when the scanner is returning EFP.

        • (reqId, rank, contractDetails, distance, benchmark, projection, legsStr?): void
        • Parameters

          • reqId: number
          • rank: number
          • contractDetails: ContractDetails
          • distance: string
          • benchmark: string
          • projection: string
          • Optional legsStr: string

          Returns void

    Returns IBApi

    See

    [[reqScannerSubscription]]

  • Indicates the scanner data reception has terminated.

    Parameters

    • event: scannerDataEnd
    • listener: ((reqId) => void)

      reqId: The id of request.

        • (reqId): void
        • Parameters

          • reqId: number

          Returns void

    Returns IBApi

    See

    [[reqScannerSubscription]]

  • Provides the xml-formatted parameters available from TWS market scanners (not all available in API).

    Parameters

    • event: scannerParameters
    • listener: ((xml) => void)

      xml: The xml-formatted string with the available parameters.

        • (xml): void
        • Parameters

          • xml: string

          Returns void

    Returns IBApi

    See

    [[reqScannerParameters]]

  • Provides 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.

    Parameters

    • event: securityDefinitionOptionParameter
    • listener: ((reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes) => void)

      reqId: The id of request.

      underlyingConId: The conID of the underlying security.

      tradingClass: The option trading class.

      multiplier: The option multiplier.

      expirations: An array of the expiries for the options of this underlying on this exchange.

      strikes: An array of of the possible strikes for options of this underlying on this exchange.

        • (reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes): void
        • Parameters

          • reqId: number
          • exchange: string
          • underlyingConId: number
          • tradingClass: string
          • multiplier: string
          • expirations: string[]
          • strikes: number[]

          Returns void

    Returns IBApi

    See

    [[reqSecDefOptParams]]

  • Called when all callbacks to securityDefinitionOptionParameter are complete.

    Parameters

    Returns IBApi

    See

    [[reqSecDefOptParams]]

  • Bit number to exchange + exchange abbreviation dictionary.

    Parameters

    • event: smartComponents
    • listener: ((reqId, theMap) => void)

      reqId: The id of request.

        • (reqId, theMap): void
        • Parameters

          • reqId: number
          • theMap: Map<number, [string, string]>

          Returns void

    Returns IBApi

    See

    [[reqSmartComponents]]

  • Called when receives Soft Dollar Tier configuration information.

    Parameters

    • event: softDollarTiers
    • listener: ((reqId, tiers) => void)

      reqId: The id of request.

      tiers: An array of [[SoftDollarTier]] objects that contains all Soft Dollar Tiers information.

        • (reqId, tiers): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqSoftDollarTiers]]

  • Provides an array of sample contract descriptions.

    Parameters

    • event: symbolSamples
    • listener: ((reqId, contractDescriptions) => void)

      reqId: The id of request.

      tiers: An array of [[ContractDescription]] objects.

        • (reqId, contractDescriptions): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqMatchingSymbols]]

  • Provides "Last" or "AllLast" tick-by-tick real-time tick.

    Parameters

    • event: tickByTickAllLast
    • listener: ((reqId, tickType, time, price, size, tickAttribLast) => void)

      reqId: The id of request.

      tickType: The tick-by-tick real-time tick type: "Last" or "AllLast".

      time: The tick-by-tick real-time tick timestamp.

      price: The tick-by-tick real-time tick last price.

      size: The tick-by-tick real-time tick last size.

      tickAttribLast: The tick-by-tick real-time last tick attribs (bit 0 - past limit, bit 1 - unreported).

      exchange: The tick-by-tick real-time tick exchange.

      specialConditions: The tick-by-tick real-time tick special conditions.

        • (reqId, tickType, time, price, size, tickAttribLast): void
        • Parameters

          • reqId: number
          • tickType: number
          • time: number
          • price: number
          • size: number
          • tickAttribLast: unknown

          Returns void

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Provides "BidAsk" tick-by-tick real-time tick.

    Parameters

    • event: tickByTickBidAsk
    • listener: ((reqId, time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk) => void)

      reqId: The id of request.

      time: The tick-by-tick real-time tick timestamp.

      bidPrice: The tick-by-tick real-time tick bid price.

      askPrice: The tick-by-tick real-time tick ask price.

      bidSize: The tick-by-tick real-time tick bid size.

      askSize: The tick-by-tick real-time tick ask size.

      tickAttribLast: The tick-by-tick real-time bid/ask tick attribs (bit 0 - bid past low, bit 1 - ask past high).

        • (reqId, time, bidPrice, askPrice, bidSize, askSize, tickAttribBidAsk): void
        • Parameters

          • reqId: number
          • time: number
          • bidPrice: number
          • askPrice: number
          • bidSize: number
          • askSize: number
          • tickAttribBidAsk: unknown

          Returns void

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Provides "MidPoint" tick-by-tick real-time tick.

    Parameters

    • event: tickByTickMidPoint
    • listener: ((reqId, time, midPoint) => void)

      reqId: The id of request.

      time: The tick-by-tick real-time tick timestamp.

      midPoint: The tick-by-tick real-time tick mid point.

        • (reqId, time, midPoint): void
        • Parameters

          • reqId: number
          • time: number
          • midPoint: number

          Returns void

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Exchange for Physicals.

    Parameters

    • event: tickEFP
    • listener: ((reqId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate) => void)

      reqId: The request's identifier.

      tickType: The type of tick being received.

      basisPoints: Annualized basis points, which is representative of the financing rate that can be directly compared to broker rates.

      formattedBasisPoints: Annualized basis points as a formatted string that depicts them in percentage form.

      impliedFuture: The implied Futures price.

      holdDays: The number of hold days until the lastTradeDate of the EFP.

      futureLastTradeDate: The expiration date of the single stock future.

      dividendImpact: The dividend impact upon the annualized basis points interest rate.

      dividendsToLastTradeDate: The dividends expected until the expiration of the single stock future.

        • (reqId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate): void
        • Parameters

          • reqId: number
          • tickType: number
          • basisPoints: number
          • formattedBasisPoints: string
          • impliedFuture: number
          • holdDays: number
          • futureLastTradeDate: string
          • dividendImpact: number
          • dividendsToLastTradeDate: number

          Returns void

    Returns IBApi

  • Provides a market data generic tick.

    Parameters

    • event: tickGeneric
    • listener: ((reqId, field, value) => void)

      reqId: The id of request.

      field: The type of tick being received.

      value: The tick value.

        • (reqId, field, value): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Provides a news headline tick.

    Parameters

    • event: tickNews
    • listener: ((reqId, timeStamp, providerCode, articleId, headline, extraData) => void)

      reqId: The id of request.

      field: The type of tick being received.

      value: The tick value.

        • (reqId, timeStamp, providerCode, articleId, headline, extraData): void
        • Parameters

          • reqId: number
          • timeStamp: number
          • providerCode: string
          • articleId: string
          • headline: string
          • extraData: string

          Returns void

    Returns IBApi

    See

    [[reqTickByTickData]]

  • Provides option specific market data. This method is called when the market in an option or its underlier moves. TWS option model volatilities, prices, and deltas, along with the present value of dividends expected on that options underlier are received.

    Parameters

    • event: tickOptionComputation
    • listener: ((reqId, field, impliedVolatility?, delta?, optPrice?, pvDividend?, gamma?, vega?, theta?, undPrice?) => void)

      reqId: The id of request.

      field: Specifies the type of option computation. Pass the field value into [[TickType.getField]] to retrieve the field description. For example, a field value of 13 will map to modelOptComp, etc. 10 = Bid 11 = Ask 12 = Last

      impliedVolatility: The implied volatility calculated by the TWS option modeler, using the specified tick type value.

      delta: The option delta value.

      value: The tick value.

      optPrice: The option price.

      pvDividend: The present value of dividends expected on the option's underlying.

      gamma:The option gamma value.

      vega: The option vega value.

      theta: The option theta value.

      undPrice: The price of the underlying.

        • (reqId, field, impliedVolatility?, delta?, optPrice?, pvDividend?, gamma?, vega?, theta?, undPrice?): void
        • Parameters

          • reqId: number
          • field: IBApiTickType
          • Optional impliedVolatility: number
          • Optional delta: number
          • Optional optPrice: number
          • Optional pvDividend: number
          • Optional gamma: number
          • Optional vega: number
          • Optional theta: number
          • Optional undPrice: number

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • 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).

    Parameters

    • event: tickPrice
    • listener: ((reqId, field, value, attribs?) => void)

      reqId: The id of request.

      field: The type of the price being received.

      price: The actual price.

      value: The tick value.

      attribs: An [[TickAttrib]] object that contains price attributes.

        • (reqId, field, value, attribs?): void
        • Parameters

          • reqId: number
          • field: IBApiTickType
          • value: number
          • Optional attribs: unknown

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • A tick with BOO exchange and snapshot permissions.

    Parameters

    • event: tickReqParams
    • listener: ((reqId, minTick, bboExchange, snapshotPermissions) => void)

      reqId: The id of request.

        • (reqId, minTick, bboExchange, snapshotPermissions): void
        • Parameters

          • reqId: number
          • minTick: number
          • bboExchange: string
          • snapshotPermissions: number

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • Market data tick size callback. Handles all size-related ticks.

    Parameters

    • event: tickSize
    • listener: ((reqId, field?, value?) => void)

      reqId: The id of request.

      field: The type of size being received (i.e. bid size)

      size: The actual size.

        • (reqId, field?, value?): void
        • Parameters

          • reqId: number
          • Optional field: IBApiTickType
          • Optional value: number

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • 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.

    Parameters

    • event: tickString
    • listener: ((reqId, field, value) => void)

      reqId: The id of request.

      field: The type of size being received (i.e. bid size)

      value: The tick value.

        • (reqId, field, value): void
        • Parameters

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • Receives the last time on which the account was updated.

    Parameters

    • event: updateAccountTime
    • listener: ((timestamp) => void)

      timestamp: The last update system time.

        • (timestamp): void
        • Parameters

          • timestamp: string

          Returns void

    Returns IBApi

    See

    [[reqMktData]]

  • 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.

    Parameters

    • event: updateAccountValue
    • listener: ((key, value, currency, accountName) => void)

      key: The value being updated. Possible values:

      • 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.
        • (key, value, currency, accountName): void
        • Parameters

          • key: string
          • value: string
          • currency: string
          • accountName: string

          Returns void

    Returns IBApi

    See

    [[reqAccountUpdates]]

  • 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 [[reqPosition]].

    After the initial callback to updatePortfolio, callbacks only occur for positions which have changed.

    Parameters

    • event: updatePortfolio
    • listener: ((contract, position, marketPrice, marketValue, averageCost?, unrealizedPNL?, realizedPNL?, accountName?) => void)

      contract: The Contract for which a position is held.

      position: The number of positions held.

      marketPrice: Instrument's unitary price.

      marketValue: Total market value of the instrument.

      averageCost: Average acquiring price of the instrument.

      unrealizedPNL: Unrealized Profit/Loss.

      realizedPNL: Realized Profit/Loss.

      accountName: The account name.

        • (contract, position, marketPrice, marketValue, averageCost?, unrealizedPNL?, realizedPNL?, accountName?): void
        • Parameters

          • contract: Contract
          • position: number
          • marketPrice: number
          • marketValue: number
          • Optional averageCost: number
          • Optional unrealizedPNL: number
          • Optional realizedPNL: number
          • Optional accountName: string

          Returns void

    Returns IBApi

  • Returns the order book.

    Parameters

    • event: updateMktDepth
    • listener: ((reqId, position, operation, side, price, size) => void)

      reqId: The request's identifier.

      position: The order book's row being updated.

      operation: How to refresh the row:

      • 0 = insert (insert this new order into the row identified by 'position')
      • 1 = update (update the existing order in the row identified by 'position')
      • 2 = delete (delete the existing order at the row identified by 'position')

      side: 0 for ask, 1 for bid.

      price: The order's price.

      size: The order's size.

        • (reqId, position, operation, side, price, size): void
        • Parameters

          • reqId: number
          • position: number
          • operation: number
          • side: number
          • price: number
          • size: number

          Returns void

    Returns IBApi

    See

    [[reqMktDepth]]

  • Returns the order book (level 2).

    Parameters

    • event: updateMktDepthL2
    • listener: ((reqId, position, marketMaker, operation, side, price, size, isSmartDepth?) => void)

      reqId: The request's identifier.

      position: The order book's row being updated.

      marketMaker: The exchange holding the order if isSmartDepth is true, otherwise the MPID of the market maker.

      operation: How to refresh the row:

      • 0 = insert (insert this new order into the row identified by 'position')
      • 1 = update (update the existing order in the row identified by 'position')
      • 2 = delete (delete the existing order at the row identified by 'position')

      side: 0 for ask, 1 for bid.

      price: The order's price.

      size: The order's size.

      isSmartDepth: A flag indicating if this is smart depth response (aggregate data from multiple exchanges, v974+)

        • (reqId, position, marketMaker, operation, side, price, size, isSmartDepth?): void
        • Parameters

          • reqId: number
          • position: number
          • marketMaker: string
          • operation: number
          • side: number
          • price: number
          • size: number
          • Optional isSmartDepth: boolean

          Returns void

    Returns IBApi

    See

    [[reqMktDepth]]

  • Provides IB's bulletins.

    Parameters

    • event: updateNewsBulletin
    • listener: ((msgId, msgType, message, origExchange) => void)

      msgId: The bulletin's identifier.

      msgType: one of:

      • 1: Regular news bulletin
      • 2: Exchange no longer available for trading
      • 3: Exchange is available for trading

      message: The message.

      origExchange: The exchange where the message comes from.

        • (msgId, msgType, message, origExchange): void
        • Parameters

          • msgId: number
          • msgType: number
          • message: string
          • origExchange: string

          Returns void

    Returns IBApi

  • Notifies when new user info has arrived.

    Parameters

    • event: userInfo
    • listener: ((whiteBrandingId) => void)

      whiteBrandingId: The user's info

        • (whiteBrandingId): void
        • Parameters

          • whiteBrandingId: string

          Returns void

    Returns IBApi

    See

    [[reqUserInfo]]

  • Add a one-time listener for a given event.

    Type Parameters

    • T extends string | symbol

    Parameters

    • event: T
    • fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    • Optional context: any

    Returns IBApi

  • Places or modifies an order.

    Parameters

    • id: number

      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.

    • contract: Contract

      The order's [[Contract]].

    • order: Order

      The [[Order]] object.

    Returns IBApi

    See

    [[reqAllOpenOrders]], [[reqAutoOpenOrders]], [[reqOpenOrders]], [[cancelOrder]], [[reqGlobalCancel]]

  • Requests all available Display Groups in TWS.

    Parameters

    • reqId: number

      The ID of this request.

    Returns IBApi

  • Remove all listeners, or those of the specified event.

    Parameters

    • Optional event: string | symbol

    Returns IBApi

  • Remove the listeners of a given event.

    Type Parameters

    • T extends string | symbol

    Parameters

    • event: T
    • Optional fn: ((...args) => void)
        • (...args): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    • Optional context: any
    • Optional once: boolean

    Returns 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

    Parameters

    • reqId: number

      The unique request identifier.

    • group: string

      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.

    • tags: string

      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.

    Returns IBApi

    See

    [[cancelAccountSummary]]

  • 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.

    Parameters

    • subscribe: boolean

      Set to true to start the subscription and to false to stop it.

    • acctCode: string

      The account id (i.e. U123456) for which the information is requested.

    Returns IBApi

    See

    [[reqPositions]]

  • Requests account updates for account and/or model.

    Parameters

    • reqId: number

      Identifier to label the request.

    • acctCode: string

      Account values can be requested for a particular account

    • modelCode: string

      Values can also be requested for a model

    • ledgerAndNLV: boolean

      returns light-weight request; only currency positions as opposed to account values and currency positions.

    Returns IBApi

    See

    [[cancelAccountUpdatesMulti]]

  • 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.

    Returns IBApi

    See

    [[reqAutoOpenOrders]], [[reqOpenOrders]]

  • Requests status updates about future orders placed from TWS. Can only be used with client ID 0.

    Parameters

    • bAutoBind: boolean

      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.

    Returns IBApi

    See

    [[reqAllOpenOrders]], [[reqOpenOrders]], [[cancelOrder]], [[reqGlobalCancel]]

  • Cancels pending WSH event data request.

    Parameters

    • reqId: number

      The unique request identifier.

    Returns IBApi

  • Cancels pending request for WSH metadata.

    Parameters

    • reqId: number

      The unique request identifier.

    Returns IBApi

  • Requests completed orders.

    Parameters

    • apiOnly: boolean

      Request only API orders.

    Returns IBApi

  • 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.

    Parameters

    • reqId: number

      The unique request identifier.

    • contract: Contract

      The contract used as sample to query the available contracts.

    Returns 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.

    Parameters

    • reqId: number

      The request's unique identifier.

    • filter: ExecutionFilter

      The filter criteria used to determine which execution reports are returned.

    Returns IBApi

  • Requests family codes for an account, for instance if it is a FA, IBroker, or associated account.

    Returns IBApi

  • Requests the contract's fundamental data. Fundamental data is emitted as fundamentalData event.

    Parameters

    • reqId: number

      The request's unique identifier.

    • contract: Contract

      The contract's description for which the data will be returned.

    • reportType: string

      there are three available report types:

      • ReportSnapshot: Company overview.
      • ReportsFinSummary: Financial summary.
      • ReportRatios: Financial ratios.
      • ReportsFinStatements: Financial statements.
      • RESC: Analyst estimates.
    • fundamentalDataOptions: TagValue[] = []

    Returns IBApi

  • Cancels all active orders. This method will cancel ALL open orders including those placed directly from TWS.

    Returns IBApi

    See

    [[cancelOrder]]

  • Returns the timestamp of earliest available historical data for a contract and data type.

    Parameters

    • reqId: number

      An identifier for the request.

    • contract: Contract

      [[Contract]] object for which head timestamp is being requested.

    • whatToShow: WhatToShow

      Type of data for head timestamp - "BID", "ASK", "TRADES", etc

    • useRTH: boolean

      Use regular trading hours only, true for yes or false for no.

    • formatDate: number

      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.

    Returns IBApi

  • Returns data histogram of specified contract.

    Parameters

    • reqId: number

      An identifier for the request.

    • contract: Contract

      [[Contract]] object for which histogram is being requested

    • useRTH: boolean

      Use regular trading hours only, true for yes or false for no.

    • period: number

      Period of which data is being requested

    • periodUnit: DurationUnit

      Unit of the period of which data is being requested

    Returns 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 0 to obtain the data which was also generated outside of the Regular Trading Hours, set to 1 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.

    Parameters

    • reqId: number
    • contract: Contract
    • endDateTime: string
    • durationStr: string
    • barSizeSetting: BarSizeSetting
    • whatToShow: WhatToShow
    • useRTH: number
    • formatDate: number
    • keepUpToDate: boolean

    Returns IBApi

  • Requests historical news headlines.

    Parameters

    • reqId: number

      ID of the request.

    • conId: number

      Contract id of ticker.

    • providerCodes: string

      A '+'-separated list of provider codes .

    • startDateTime: string

      Marks the (exclusive) start of the date range. The format is yyyy-MM-dd HH:mm:ss.0

    • endDateTime: string

      Marks the (inclusive) end of the date range. The format is yyyy-MM-dd HH:mm:ss.0

    • totalResults: number

      The maximum number of headlines to fetch (1 - 300).

    • historicalNewsOptions: TagValue[] = []

    Returns IBApi

  • Requests historical Time&Sales data for an instrument.

    Parameters

    • reqId: number

      ID of the request.

    • contract: Contract

      [[Contract]] object that is subject of query

    • startDateTime: string

      "20170701 12:01:00". Uses TWS timezone specified at login.

    • endDateTime: string

      "20170701 13:01:00". In TWS timezone. Exactly one of start time and end time has to be defined.

    • numberOfTicks: number

      Number of distinct data points. Max currently 1000 per request.

    • whatToShow: WhatToShow

      (Bid_Ask, Midpoint, Trades) Type of data requested.

    • useRTH: number

      Data from regular trading hours (1), or all available hours (0)

    • ignoreSize: boolean

      A filter only used when the source price is Bid_Ask

    Returns IBApi

  • Requests the next valid order ID at the current moment.

    Parameters

    • numIds: number = 0

      deprecated- this parameter will not affect the value returned to nextValidId

    Returns 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.

    Parameters

    • marketDataType: 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.

    Returns 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.

    Parameters

    • marketRuleId: number

      The id of market rule.

    Returns IBApi

  • Requests matching stock symbols.

    Thr result will be emitted as symbolSamples event.

    Parameters

    • reqId: number

      ID to specify the request

    • pattern: string

      Either start of ticker symbol or (for larger strings) company name.

    Returns 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).

    Parameters

    • reqId: number

      The request's identifier.

    • contract: Contract

      The [[Contract]] for which the data is being requested

    • genericTickList: string

      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
    • snapshot: boolean

      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.

    • regulatorySnapshot: boolean

      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.

    Returns IBApi

    See

    [[cancelMktData]]

  • 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.

    Parameters

    • reqId: number

      The request's identifier.

    • contract: Contract

      The [[Contract]] for which the depth is being requested.

    • numRows: number

      The number of rows on each side of the order book.

    • isSmartDepth: boolean

      Flag indicates that this is smart depth request.

    • Optional mktDepthOptions: TagValue[]

      TODO document

    Returns IBApi

    See

    [[cancelMktDepth]]

  • Requests venues for which market data is returned to updateMktDepthL2 (those with market makers)

    Returns IBApi

  • Requests news article body given articleId.

    Parameters

    • requestId: number

      ID of the request.

    • providerCode: string

      Short code indicating news provider, e.g. FLY

    • articleId: string

      ID of the specific article.

    • newsArticleOptions: TagValue[] = []

    Returns IBApi

  • Subscribes to IB's News Bulletins.

    Parameters

    • allMsgs: boolean

      If set to true, will return all the existing bulletins for the current day. If set to false` to receive only the new bulletins.

    Returns IBApi

    See

    [[cancelNewsBulletin]]

  • 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.

    Returns IBApi

  • Creates subscription for real time daily PnL and unrealized PnL updates.

    Parameters

    • reqId: number

      ID of the request.

    • account: string

      Account for which to receive PnL updates.

    • Optional modelCode: string

      Specify to request PnL updates for a specific model.

    Returns IBApi

  • Requests real time updates for daily PnL of individual positions.

    Parameters

    • reqId: number

      ID of the request.

    • account: string

      Account in which position exists.

    • modelCode: string

      Model in which position exists.

    • conId: number

      Contract ID (conId) of contract to receive daily PnL updates for. Note: does not return message if invalid conId is entered.

    Returns IBApi

  • Subscribes to position updates for all accessible accounts. All positions sent initially, and then only updates as positions change.

    Returns IBApi

    See

    [[cancelPositions]]

  • 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.

    Parameters

    • reqId: number

      Request's identifier.

    • account: string

      If an account Id is provided, only the account's positions belonging to the specified model will be delivered.

    • modelCode: string

      The code of the model's positions we are interested in.

    Returns IBApi

    See

    [[cancelPositionsMulti]]

  • 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.

    Parameters

    • reqId: number

      The request's unique identifier.

    • contract: Contract

      The [[Contract]] for which the depth is being requested

    • barSize: number

      currently being ignored

    • whatToShow: WhatToShow

      the nature of the data being retrieved:

      • TRADES
      • MIDPOINT
      • BID
      • ASK
    • useRTH: boolean

      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

    • realTimeBarsOptions: TagValue[] = []

    Returns IBApi

    See

    [[cancelRealTimeBars]]

  • Requests an XML list of scanner parameters valid in TWS.

    Not all parameters are valid from API scanner.

    Returns IBApi

    Sse

    [[reqScannerSubscription]]

  • Starts a subscription to market scan results based on the provided parameters.

    Parameters

    • reqId: number

      The request's identifier.

    • subscription: ScannerSubscription

      Summary of the scanner subscription including its filters.

    • scannerSubscriptionOptions: TagValue[] = []

      TODO document

    • scannerSubscriptionFilterOptions: TagValue[] = []

      TODO document

    Returns IBApi

    See

    [[reqScannerParameters]]

  • Requests security definition option parameters for viewing a contract's option chain.

    Parameters

    • reqId: number

      The request's identifier.

    • underlyingSymbol: string

      Underlying symbol name.

    • futFopExchange: string

      The exchange on which the returned options are trading. Can be set to the empty string "" for all exchanges.

    • underlyingSecType: string

      The type of the underlying security, i.e. STK

    • underlyingConId: number

      the contract ID of the underlying security

    Returns IBApi

  • Returns the mapping of single letter codes to exchange names given the mapping identifier.

    Parameters

    • reqId: number

      The id of the request.

    • bboExchange: string

      The mapping identifier received from on tickReqParams event.

    Returns IBApi

  • Requests tick-by-tick data.

    Parameters

    • reqId: number

      Unique identifier of the request.

    • contract: Contract

      The [[Contract]] for which tick-by-tick data is requested.

    • tickType: TickByTickDataType

      tick-by-tick data type: "Last", "AllLast", "BidAsk" or "MidPoint".

    • numberOfTicks: number

      number of ticks.

    • ignoreSize: boolean

      ignore size flag.

    Returns IBApi

  • Requests event data from the wSH calendar.

    Parameters

    • reqId: number

      The unique request identifier.

    • wshEventData: number | WshEventData

    Returns IBApi

    See

    [[reqCancelWshEventData]]

  • Requests metadata from the WSH calendar.

    Parameters

    • reqId: number

      The unique request identifier.

    Returns IBApi

    See

    [[reqCancelWshMetaData]]

  • Changes the TWS/GW log level.

    The default is [[LOG_LEVEL.ERROR]]

    Parameters

    Returns IBApi

  • Integrates API client and TWS window grouping.

    Parameters

    • reqId: number

      The Id chosen for this subscription request.

    • groupId: number

      The display group for integration.

    Returns IBApi

  • Cancels a TWS Window Group subscription.

    Parameters

    • reqId: number

      The request ID.

    Returns IBApi

    Sse

    [[subscribeToGroupEvents]]

  • Updates the contract displayed in a TWS Window Group.

    Parameters

    • reqId: number

      The ID chosen for this request.

    • contractInfo: string

      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.

    Returns IBApi

Generated using TypeDoc