Skip to content

Latest commit

 

History

History
2315 lines (1291 loc) · 76.1 KB

API.md

File metadata and controls

2315 lines (1291 loc) · 76.1 KB

API Docs

Index


TDAmeritrade

TD Ameritrade API client


new TDAmeritrade([config])

Arguments

Example

const td = new TDAmeritrade({
    apiKey: process.env.API_KEY,
    redirectUri: 'https://localhost:8443',
    sslKey: './selfsigned.key',
    sslCert: './selfsigned.crt',
})


td.axios : AxiosInstance

The axios instance used by the client.


td.on(event, fn) ⇒ EventEmitter.<(string|symbol), any>

Add a listener for a given event.

Arguments

  • event ('login' | 'token') : The event name
  • fn (EventEmitter.EventListener.<any, any>) : Callback function

Returns

  • EventEmitter.<(string|symbol), any> : Event emitter


td.getAccounts([fields]) ⇒ Promise.<any>

Get account balances, positions, and orders for all linked accounts.

Arguments

Returns

  • Promise.<any> : List of all accounts

Example

const accounts = await td.getAccounts()


td.getAccount(accountId, [fields]) ⇒ Promise.<any>

Get account balances, positions, and orders for a specific account.

Arguments

Returns

  • Promise.<any> : The requested account

Example

const acctInfo = await td.getAccount('45678')


td.getPositions(accountId) ⇒ Promise.<any>

Get account positions for a specific account.

Arguments

  • accountId (string) : The account id

Returns

  • Promise.<any> : The requested account's positions

Example

const acctInfo = await td.getPositions('45678')


td.getPreferences(accountId) ⇒ Promise.<any>

Get preferences for a specific account.

Arguments

  • accountId (string) : The account id

Returns

  • Promise.<any> : The account preferences

Example

const prefs = await td.getPreferences('45678')


td.updatePreferences(accountId, preferences) ⇒ Promise.<any>

Update preferences for a specific account. The directOptionsRouting and directEquityRouting values cannot be modified via this operation.

Arguments

  • accountId (string) : The account id
  • preferences (Preferences) : The updated preferences

Returns

  • Promise.<any> : Success


td.getStreamerSubscriptionKeys([accountIds]) ⇒ Promise.<any>

Get the SubscriptionKey for provided accounts or default accounts.

Arguments

  • [accountIds] (string | Array.<string>) : The account id(s)

Returns

  • Promise.<any> : The susbscription keys

Example

const subsKeys = await td.getStreamerSubscriptionKeys('45678')


td.getUserPrincipals([fields]) ⇒ Promise.<any>

Get user principal details.

Arguments

Returns

  • Promise.<any> : User principal details

Example

const usrPrinc = await td.getUserPrincipals()
// OR
const usrPrinc = await td.getUserPrincipals('streamerSubscriptionKeys')
// OR
const usrPrinc = await td.getUserPrincipals(['streamerSubscriptionKeys', 'streamerConnectionInfo'])


td.getMarketHours(markets, date) ⇒ Promise.<any>

Get the market hours for the specified market(s).

Arguments

  • markets (Market | Array.<Market>) : The market(s) for which you're requesting market hours
  • date (string) : The date for which market hours information is requested. Valid ISO-8601 formats are yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz

Returns

  • Promise.<any> : The market hours

Example

td.getMarketHours('EQUITY', '2021-01-21')
// OR
td.getMarketHours(['EQUITY', 'FUTURE'], '2021-01-21')


td.getMovers(index, direction, change) ⇒ Promise.<any>

Get mover information by index symbol, direction type and change.

Arguments

  • index ('$COMPX' | '$DJI' | '$SPX.X') : The index symbol
  • direction ('up' | 'down') : The direction
  • change ('value' | 'percent') : The change type

Returns

  • Promise.<any> : The mover information

Example

const movers = await td.getMovers('$DJI', 'up', 'percent')


td.getQuotes(symbols) ⇒ Promise.<any>

Get quote data for one or more symbols.

Arguments

  • symbols (string | Array.<string>) : The ticker symbol(s)

Returns

  • Promise.<any> : The quote data

Example

const data = await td.getQuotes(['ABC', 'XYZ'])


td.getQuote(symbol) ⇒ Promise.<any>

Get quote data for a specified symbol.

Arguments

  • symbol (string) : The ticker symbol

Returns

  • Promise.<any> : The quote data

Example

const data = await td.getQuote('XYZ')


td.getPriceHistory(symbol, params) ⇒ Promise.<any>

Get price history for a specified symbol.

Arguments

  • symbol (string) : The ticker symbol
  • params (PriceHistoryQuery) : The query parameters

Returns

  • Promise.<any> : The price history

Example

const prices = await td.getPriceHistory('XYZ', {
    periodType: 'day',
    period: 5,
    frequencyType: 'minute',
    needExtendedHoursData: false
})


td.getOptionChain(symbol, params) ⇒ Promise.<any>

Get Option Chains for optionable symbols.

Arguments

  • symbol (string) : The ticker symbol
  • params (OptionChainQuery) : The query parameters

Returns

  • Promise.<any> : The option chain


td.searchInstruments(symbol, projection) ⇒ Promise.<any>

Search or retrieve instrument data, including fundamental data.

Arguments

  • symbol (string) : The ticker symbol
  • projection ('symbol-search' | 'symbol-regex' | 'desc-search' | 'desc-regex' | 'fundamental') : The type of request
    • symbol-search: Retrieve instrument data of a specific symbol or cusip
    • symbol-regex: Retrieve instrument data for all symbols matching regex. Example: symbol=XYZ.* will return all symbols beginning with XYZ
    • desc-search: Retrieve instrument data for instruments whose description contains the word supplied. Example: symbol=FakeCompany will return all instruments with FakeCompany in the description.
    • desc-regex: Search description with full regex support. Example: symbol=XYZ.[A-C] returns all instruments whose descriptions contain a word beginning with XYZ followed by a character A through C.
    • fundamental: Returns fundamental data for a single instrument specified by exact symbol.

Returns

  • Promise.<any> : The instrument data

Example

const res = await td.searchInstruments('XYZ', 'symbol-search')


td.getInstrument(cusip) ⇒ Promise.<any>

Get an instrument by its CUSIP.

Arguments

  • cusip (string) : The CUSIP identifier

Returns

  • Promise.<any> : The instrument details

Example

const instr = await td.getInstrument('03074K100')


td.authorize() ⇒ Promise.<any>

Bootstrap a local web server for oauth2 authorization. Will request access token and update config if authorization is successful.

(Available for Nodejs only)

Returns

  • Promise.<any> : Success

Example

td.authorize().then(token => {
    console.log(token)
}).catch(err => {
    console.log(err)
})


td.login() ⇒ Promise.<any>

Authorize or refresh the access token depending on whether the access and/or refresh token exist and are not expired.

(Available for Nodejs only)

Returns

  • Promise.<any> : Success

Example

td.login().then(token => {
    console.log(token)
}).catch(err => {
    console.log(err)
})


td.getOrder(accountId, orderId) ⇒ Promise.<any>

Get a specific order for a specific account.

Arguments

  • accountId (string) : The account id
  • orderId (string) : The order id

Returns

  • Promise.<any> : The order details

Example

const order = await td.getOrder('45678', '98745')


td.getOrders(accountId, params) ⇒ Promise.<any>

Get a list of orders for a specific account.

Arguments

  • accountId (string) : The account id
  • params (OrdersQuery) : The query parameters

Returns

  • Promise.<any> : List of orders

Example

const orders = await td.getOrders('45678', {
    fromEnteredTime: '2021-01-01',
    toEnteredTime: '2021-01-15',
    maxResults: 25,
    status: 'FILLED'
})


td.getAllOrders(params) ⇒ Promise.<any>

Get a list of orders from all accounts.

Arguments

Returns

  • Promise.<any> : List of orders

Example

const orders = await td.getAllOrders({
    fromEnteredTime: '2021-01-01',
    toEnteredTime: '2021-01-15',
    maxResults: 25,
    status: 'FILLED'
})


td.placeOrder(accountId, order) ⇒ Promise.<any>

Place an order for a specific account. Read Place Order Samples for more info.

Arguments

  • accountId (string) : The account id
  • order (object) : The order

Returns

  • Promise.<any> : Success

Example

await td.placeOrder('45678', {
    orderType: 'MARKET',
    session: 'NORMAL',
    duration: 'DAY',
    orderStrategyType: 'SINGLE',
    orderLegCollection: [
        {
            instruction: 'Buy',
            quantity: 15,
            instrument: {
                symbol: 'XYZ',
                assetType: 'EQUITY'
            }
        }
    ]
})


td.replaceOrder(accountId, orderId, order) ⇒ Promise.<any>

Replace an existing order for an account. The existing order will be replaced by the new order. Once replaced, the old order will be canceled and a new order will be created.

Arguments

  • accountId (string) : The account id
  • orderId (string) : The order id
  • order (object) : The new order

Returns

  • Promise.<any> : Success


td.cancelOrder(accountId, orderId) ⇒ Promise.<any>

Cancel a specific order for a specific account.

Arguments

  • accountId (string) : The account id
  • orderId (string) : The order id

Returns

  • Promise.<any> : Success

Example

await td.cancelOrder('45678', '98745')


td.getSavedOrder(accountId, savedOrderId) ⇒ Promise.<any>

Get saved order by its ID, for a specific account.

Arguments

  • accountId (string) : The account id
  • savedOrderId (string) : The saved order id

Returns

  • Promise.<any> : The saved order details


td.getSavedOrders(accountId) ⇒ Promise.<any>

Get saved orders for a specific account.

Arguments

  • accountId (string) : The account id

Returns

  • Promise.<any> : List of saved orders


td.createSavedOrder(accountId, savedOrder) ⇒ Promise.<any>

Save an order for a specific account.

Arguments

  • accountId (string) : The account id
  • savedOrder (object) : The saved order

Returns

  • Promise.<any> : Success

Example

await td.createSavedOrder('45678', {
    complexOrderStrategyType: 'NONE',
    orderType: 'LIMIT',
    session: 'NORMAL',
    price: '6.45',
    duration: 'DAY',
    orderStrategyType: 'SINGLE',
    orderLegCollection: [
        {
            instruction: 'BUY_TO_OPEN',
            quantity: 10,
            instrument: {
                symbol: 'XYZ_032015C49',
                assetType: 'OPTION'
            }
        }
    ]
})


td.replaceSavedOrder(accountId, savedOrderId, savedOrder) ⇒ Promise.<any>

Replace an existing saved order for an account. The existing saved order will be replaced by the new order.

Arguments

  • accountId (string) : The account id
  • savedOrderId (string) : The saved order id
  • savedOrder (object) : The new saved order

Returns

  • Promise.<any> : Success


td.deleteSavedOrder(accountId, savedOrderId) ⇒ Promise.<any>

Delete a specific saved order for a specific account.

Arguments

  • accountId (string) : The account id
  • savedOrderId (string) : The saved order id

Returns

  • Promise.<any> : Success

Example

await td.deleteSavedOrder('45678', '98754')


td.getAccessToken(authCode) ⇒ Promise.<any>

Get the access token along with an optional refresh token.

Arguments

  • authCode (string) : The authorization code

Returns

  • Promise.<any> : The token details

Example

const token = await td.getAccessToken('authorization-code-goes-here')


td.refreshAccessToken([refreshToken]) ⇒ Promise.<any>

Refresh the access token.

Arguments

  • [refreshToken] (string) : The refresh token

Returns

  • Promise.<any> : The token details

Example

const token = await td.refreshAccessToken('refresh-token-goes-here')


td.isAccessTokenExpired() ⇒ boolean

Determine if access token is expired.

Returns

  • boolean : True if expired, otherwise false


td.isRefreshTokenExpired() ⇒ boolean

Determine if refresh token is expired.

Returns

  • boolean : True if expired, otherwise false


td.getTransaction(accountId, transactionId) ⇒ Promise.<any>

Get a transaction for a specific account.

Arguments

  • accountId (string) : The account id
  • transactionId (string) : The transaction id

Returns

  • Promise.<any> : The transaction details

Example

const transaction = await td.getTransaction('45678', '98754')


td.getTransactions(accountId, params) ⇒ Promise.<any>

Get all transactions for a specific account.

Arguments

  • accountId (string) : The account id
  • params (TransactionQuery) : The query parameters

Returns

  • Promise.<any> : The transaction history

Example

const transactions = await td.getTransactions('45678', {
    symbol: 'SPY',
    startDate: '2021-01-01',
    endDate: '2021-01-31',
})


td.createWatchlist(accountId, watchlist) ⇒ Promise.<any>

Create watchlist for specific account.

Arguments

  • accountId (string) : The account id
  • watchlist (Watchlist) : The watchlist

Returns

  • Promise.<any> : Success


td.deleteWatchlist(accountId, watchlistId) ⇒ Promise.<any>

Delete watchlist for a specific account.

Arguments

  • accountId (string) : The account id
  • watchlistId (string) : The watchlist id

Returns

  • Promise.<any> : Success

Example

await td.deleteWatchlist('45678', '98754')


td.getWatchlist(accountId, watchlistId) ⇒ Promise.<any>

Get watchlist for a specific account.

Arguments

  • accountId (string) : The account id
  • watchlistId (string) : The watchlist id

Returns

  • Promise.<any> : Success

Example

const watchlist = await td.getWatchlist('45678', '98754')


td.getWatchlists(accountId) ⇒ Promise.<any>

Get all watchlists of an account.

Arguments

  • accountId (string) : The account id

Returns

  • Promise.<any> : List of watchlists

Example

const watchlists = await td.getWatchlists('45678')


td.getAllWatchlists() ⇒ Promise.<any>

All watchlists for all of the user's linked accounts.

Returns

  • Promise.<any> : List of watchlists

Example

const watchlists = await td.getAllWatchlists()


td.replaceWatchlist(accountId, watchlistId, watchlist) ⇒ Promise.<any>

Replace watchlist for a specific account. This method does not verify that the symbol or asset type are valid.

Arguments

  • accountId (string) : The account id
  • watchlistId (string) : The watchlist id
  • watchlist (Watchlist) : The watchlist

Returns

  • Promise.<any> : Success


td.updateWatchlist(accountId, watchlistId, watchlist) ⇒ Promise.<any>

Partially update watchlist for a specific account: change watchlist name, add to the beginning/end of a watchlist, update or delete items in a watchlist. This method does not verify that the symbol or asset type are valid.

Arguments

  • accountId (string) : The account id
  • watchlistId (string) : The watchlist id
  • watchlist (Watchlist) : The new watchlist

Returns

  • Promise.<any> : Success


td.account(accountId) ⇒ TDAccount

Create a new instance of Account.

Arguments

  • accountId (string) : The account id

Returns

Example

const ira_account = td.account('45678')


td.streamer() ⇒ Promise.<TDStreamer>

Create a new instance of TDStreamer. For the time being, this will select the first available account.

Returns

Example

const streamer = await td.streamer()


TDAccount


new TDAccount(accountId, [config])

Arguments

  • accountId (string) : The account id
  • [config] (Config) : Config


account.getAccount([fields]) ⇒ Promise.<any>

Get account balances, positions, and orders.

Arguments

Returns

  • Promise.<any> : The requested account


account.getPositions() ⇒ Promise.<any>

Get account positions.

Returns

  • Promise.<any> : The requested account's positions


account.getPreferences() ⇒ Promise.<any>

Get account preferences.

Returns

  • Promise.<any> : The account preferences


account.updatePreferences(preferences) ⇒ Promise.<any>

Update account preferences. The directOptionsRouting and directEquityRouting values cannot be modified via this operation.

Arguments

Returns

  • Promise.<any> : Success


account.getStreamerSubscriptionKeys() ⇒ Promise.<any>

Get the SubscriptionKey.

Returns

  • Promise.<any> : The susbscription keys


account.getOrders(params) ⇒ Promise.<any>

Get a list of orders.

Arguments

Returns

  • Promise.<any> : List of orders


account.getOrder(orderId) ⇒ Promise.<any>

Get a specific order.

Arguments

  • orderId (string) : The order id

Returns

  • Promise.<any> : The order details


account.placeOrder(order) ⇒ Promise.<any>

Place an order. Read Place Order Samples for more info.

Arguments

  • order (object) : The order

Returns

  • Promise.<any> : Success


account.replaceOrder(orderId, order) ⇒ Promise.<any>

Replace an existing order. The existing order will be replaced by the new order. Once replaced, the old order will be canceled and a new order will be created.

Arguments

  • orderId (string) : The order id
  • order (object) : The new order

Returns

  • Promise.<any> : Success


account.cancelOrder(orderId) ⇒ Promise.<any>

Cancel a specific order.

Arguments

  • orderId (string) : The order id

Returns

  • Promise.<any> : Success


account.createSavedOrder(savedOrder) ⇒ Promise.<any>

Save an order.

Arguments

  • savedOrder (object) : The saved order

Returns

  • Promise.<any> : Success


account.deleteSavedOrder(savedOrderId) ⇒ Promise.<any>

Delete a specific saved order.

Arguments

  • savedOrderId (string) : The saved order id

Returns

  • Promise.<any> : Success


account.getSavedOrder(savedOrderId) ⇒ Promise.<any>

Get saved order by its ID.

Arguments

  • savedOrderId (string) : The saved order id

Returns

  • Promise.<any> : The saved order details


account.getSavedOrders() ⇒ Promise.<any>

Get saved orders.

Returns

  • Promise.<any> : List of saved orders


account.replaceSavedOrder(savedOrderId, savedOrder) ⇒ Promise.<any>

Replace an existing saved order for an account. The existing saved order will be replaced by the new order.

Arguments

  • savedOrderId (string) : The saved order id
  • savedOrder (object) : The new saved order

Returns

  • Promise.<any> : Success


account.createWatchlist(watchlist) ⇒ Promise.<any>

Create watchlist.

Arguments

Returns

  • Promise.<any> : Success


account.deleteWatchlist(watchlistId) ⇒ Promise.<any>

Delete watchlist.

Arguments

  • watchlistId (string) : The watchlist id

Returns

  • Promise.<any> : Success


account.getWatchlist(watchlistId) ⇒ Promise.<any>

Get watchlist.

Arguments

  • watchlistId (string) : The watchlist id

Returns

  • Promise.<any> : Success


account.getWatchlists() ⇒ Promise.<any>

Get all watchlists.

Returns

  • Promise.<any> : List of watchlists


account.replaceWatchlist(watchlistId, watchlist) ⇒ Promise.<any>

Replace watchlist. This method does not verify that the symbol or asset type are valid.

Arguments

  • watchlistId (string) : The watchlist id
  • watchlist (Watchlist) : The watchlist

Returns

  • Promise.<any> : Success


account.updateWatchlist(watchlistId, watchlist) ⇒ Promise.<any>

Partially update watchlist: change watchlist name, add to the beginning/end of a watchlist, update or delete items in a watchlist. This method does not verify that the symbol or asset type are valid.

Arguments

  • watchlistId (string) : The watchlist id
  • watchlist (Watchlist) : The new watchlist

Returns

  • Promise.<any> : Success


account.getTransaction(transactionId) ⇒ Promise.<any>

Get a transaction.

Arguments

  • transactionId (string) : The transaction id

Returns

  • Promise.<any> : The transaction details


account.getTransactions(params) ⇒ Promise.<any>

Get all transactions.

Arguments

Returns

  • Promise.<any> : The transaction history


TDStreamer


new TDStreamer(userPrincipals)

Arguments

  • userPrincipals (object) : User principals object


streamer.state ⇒ State

Returns


streamer.on(event, fn) ⇒ EventEmitter.<(string|symbol), any>

Add a listener for a given event.

Arguments

  • event (State | Event | Error) : The event name
  • fn (EventEmitter.EventListener.<any, any>) : Callback function

Returns

  • EventEmitter.<(string|symbol), any> : Event emitter


streamer.once(event, fn) ⇒ EventEmitter.<(string|symbol), any>

Add a one-time listener for a given event.

Arguments

  • event (State | Event | Error) : The event name
  • fn (EventEmitter.EventListener.<any, any>) : Callback function

Returns

  • EventEmitter.<(string|symbol), any> : Event emitter


streamer.removeListener(event, fn) ⇒ void

Remove the listeners of a given event.

Arguments

  • event (State | Event) : The event name
  • fn (EventEmitter.EventListener.<any, any>) : Callback function


streamer.removeAllListeners([event]) ⇒ void

Remove all listeners, or those of the specified event.

Arguments


streamer.eventNames() ⇒ Array.<(string|symbol)>

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

Returns

  • Array.<(string|symbol)> : event names


streamer.listeners(event) ⇒ Array.<EventEmitter.EventListener.<any, any>>

Return the listeners registered for a given event.

Arguments

Returns

  • Array.<EventEmitter.EventListener.<any, any>> : List of listeners


streamer.listenerCount(event) ⇒ number

Return the number of listeners listening to a given event.

Arguments

Returns

  • number : Number of listeners


streamer.connect() ⇒ void

Connect to the server


streamer.disconnect(options) ⇒ void

Disconnect from the server

Arguments


streamer.createRequest(requests) ⇒ object

Create a request object

Arguments

Returns

  • object : The requests object


streamer.sendRequest(requests) ⇒ Array.<object>

Send a request to the server

Arguments

Returns

  • Array.<object> : The requests sent to the server


streamer.send(message) ⇒ void

Send a message to the server

Arguments

  • message (object) : The JSON message to send to server


streamer.subscribe(services) ⇒ Array.<object>

Subscribe for service updates

Arguments

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubscribe(services) ⇒ Array.<object>

Unsubscribe from services updates

Arguments

Returns

  • Array.<object> : The request objects sent to the server


streamer.setQOS(level) ⇒ Array.<object>

Set Quality of Service

Arguments

  • level ('express' | 'realtime' | 'fast' | 'moderate' | 'slow' | 'delayed') : level

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsAccountActivity([fields]) ⇒ Array.<object>

Subscribe to Account Activity updates

Arguments

  • [fields] (Array.<('subscriptionKey'|'accountNumber'|'messageType'|'messageData')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsAccountActivity() ⇒ Array.<object>

Unsubscribe from Account Activity updates

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsChartEquity(symbols, [fields]) ⇒ Array.<object>

Susbscribe to Chart Equity updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('key'|'openPrice'|'highPrice'|'lowPrice'|'closePrice'|'volume'|'sequence'|'chartTime'|'chartDay')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsChartEquity(symbols) ⇒ Array.<object>

Unsubscribe from Chart Equity updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsChartFutures(symbols, [fields]) ⇒ Array.<object>

Susbscribe to Chart Futures updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('key'|'chartTime'|'openPrice'|'highPrice'|'lowPrice'|'closePrice'|'volume')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsChartFutures(symbols) ⇒ Array.<object>

Unsubscribe from Chart Futures updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsChartOptions(symbols, [fields]) ⇒ Array.<object>

Subscribe to Chart Options updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('key'|'chartTime'|'openPrice'|'highPrice'|'lowPrice'|'closePrice'|'volume')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsChartOptions(symbols) ⇒ Array.<object>

Unsbscribe from Chart Options updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsNewsHeadline(symbols, [fields]) ⇒ Array.<object>

Subscribe to News Headline updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'errorCode'|'storyDatetime'|'headlineId'|'status'|'headline'|'storyId'|'countForKeyword'|'keywordArray'|'isHot'|'storySource')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsNewsHeadline(symbols) ⇒ Array.<object>

Unsbscribe from News Headline updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsTimesaleEquity(symbols, [fields]) ⇒ Array.<object>

Subscribe to Timesale Equity updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'tradeTime'|'lastPrice'|'lastSize'|'lastSequence')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsTimesaleEquity(symbols) ⇒ Array.<object>

Unsbscribe from Timesale Equity updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsTimesaleFutures(symbols, [fields]) ⇒ Array.<object>

Subscribe to Timesale Futures updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'tradeTime'|'lastPrice'|'lastSize'|'lastSequence')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsTimesaleFutures(symbols) ⇒ Array.<object>

Unsbscribe from Timesale Futures updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsTimesaleOptions(symbols, [fields]) ⇒ Array.<object>

Subscribe to Timesale Options updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'tradeTime'|'lastPrice'|'lastSize'|'lastSequence')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsTimesaleOptions(symbols) ⇒ Array.<object>

Unsbscribe from Timesale Options updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsTimesaleForex(symbols, [fields]) ⇒ Array.<object>

Subscribe to Timesale Forex updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'tradeTime'|'lastPrice'|'lastSize'|'lastSequence')>) : Fields to include (default all)

Returns

  • Array.<object> : The request objects sent to the server


streamer.unsubsTimesaleForex(symbols) ⇒ Array.<object>

Unsbscribe from Timesale Forex updates

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.getChartHistoryFutures(symbols, options) ⇒ Array.<object>

Get historical data for Futures

Arguments

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsLevelOneEquity(symbols, [fields]) ⇒ Array.<object>

Subscribe to Level One Equity service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'bidPrice'|'askPrice'|'lastPrice'|'bidSize'|'askSize'|'askID'|'bidID'|'totalVolume'|'lastSize'|'tradeTime'|'quoteTime'|'highPrice'|'lowPrice'|'bidTick'|'closePrice'|'exchangeID'|'marginable'|'shortable'|'quoteDay'|'tradeDay'|'volatility'|'description'|'lastID'|'digits'|'openPrice'|'netChange'|'52WeekHigh'|'52WeekLow'|'peRatio'|'dividendAmount'|'dividendYield'|'nav'|'fundPrice'|'exchangeName'|'dividendDate'|'regularMarketQuote'|'regularMarketTrade'|'regularMarketLastPrice'|'regularMarketLastSize'|'regularMarketTradeTime'|'regularMarketTradeDay'|'regularMarketNetChange'|'securityStatus'|'mark'|'quoteTimeInLong'|'tradeTimeInLong'|'regularMarketTradeTimeInLong')>) : Fields to include (default all)

Returns

  • Array.<object> : object


streamer.unsubsLevelOneEquity(symbols) ⇒ Array.<object>

Unsbscribe from Level One Equity service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsLevelOneFutures(symbols, [fields]) ⇒ Array.<object>

Subscribe to Level One Equity service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'bidPrice'|'askPrice'|'lastPrice'|'bidSize'|'askSize'|'askID'|'bidID'|'totalVolume'|'lastSize'|'quoteTime'|'tradeTime'|'highPrice'|'lowPrice'|'closePrice'|'exchangeID'|'description'|'lastID'|'openPrice'|'netChange'|'futurePercentChange'|'exhangeName'|'securityStatus'|'openInterest'|'mark'|'tick'|'tickAmount'|'product'|'futurePriceFormat'|'futureTradingHours'|'futureIsTradable'|'futureMultiplier'|'futureIsActive'|'futureSettlementPrice'|'futureActiveSymbol'|'futureExpirationDate')>) : Fields to include (default all)

Returns

  • Array.<object> : object


streamer.unsubsLevelOneFutures(symbols) ⇒ Array.<object>

Unsbscribe from Level One Futures service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


streamer.subsLevelOneOption(symbols, [fields]) ⇒ Array.<object>

Subscribe to Level One Option service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to subscribe to
  • [fields] (Array.<('symbol'|'bidPrice'|'askPrice'|'lastPrice'|'bidSize'|'askSize'|'askID'|'bidID'|'totalVolume'|'lastSize'|'quoteTime'|'tradeTime'|'highPrice'|'lowPrice'|'closePrice'|'exchangeID'|'description'|'lastID'|'openPrice'|'netChange'|'futurePercentChange'|'exhangeName'|'securityStatus'|'openInterest'|'mark'|'tick'|'tickAmount'|'product'|'futurePriceFormat'|'futureTradingHours'|'futureIsTradable'|'futureMultiplier'|'futureIsActive'|'futureSettlementPrice'|'futureActiveSymbol'|'futureExpirationDate')>) : Fields to include (default all)

Returns

  • Array.<object> : object


streamer.unsubsLevelOneOption(symbols) ⇒ Array.<object>

Unsbscribe from Level One Option service

Arguments

  • symbols (string | Array.<string>) : Ticker symbols to unsubscribe from

Returns

  • Array.<object> : The request objects sent to the server


Type Definitions


Config : object

Properties

  • baseURL (string) : TD Ameritrade's API URL
  • apiKey (string) : The API key (Client ID) provided by TD Ameritrade
  • refreshAndRetry (boolean) : Refresh token and retry request if a 401 response is received
  • returnFullResponse (boolean) : Return the full axios response instead of only the data
  • accessToken (string) : The OAuth2 access token
  • refreshToken (string) : The OAuth2 refresh token
  • accessTokenExpiresAt (string) : The access token's date and time of expiration
  • refreshTokenExpiresAt (string) : The refresh token's date and time of expiration
  • redirectUri (string) : The local uri to receive the access code from TD Ameritrade's OAuth2
  • sslKey (string) : The path to your private SSL key
  • sslCert (string) : The path to your public SSL key


AccountFields : 'positions' | 'orders'


Preferences : object

Properties

  • expressTrading (boolean) : Express trading
  • defaultEquityOrderLegInstruction ('BUY' | 'SELL' | 'BUY_TO_COVER' | 'SELL_SHORT' | 'NONE') : Default equity order leg instruction
  • defaultEquityOrderType ('MARKET' | 'LIMIT' | 'STOP' | 'STOP_LIMIT' | 'TRAILING_STOP' | 'MARKET_ON_CLOSE' | 'NONE') : Default order type
  • defaultEquityOrderPriceLinkType ('VALUE' | 'PERCENT' | 'NONE') : Default equity order price link type
  • defaultEquityOrderDuration ('DAY' | 'GOOD_TILL_CANCEL' | 'NONE') : Default equity order duration
  • defaultEquityOrderMarketSession ('AM' | 'PM' | 'NORMAL' | 'SEAMLESS' | 'NONE') : Default equity order market session
  • defaultEquityQuantity (number) : Default equity quantity
  • mutualFundTaxLotMethod ('FIFO' | 'LIFO' | 'HIGH_COST' | 'LOW_COST' | 'MINIMUM_TAX' | 'AVERAGE_COST' | 'NONE') : Mutual fund taxlot method
  • optionTaxLotMethod ('FIFO' | 'LIFO' | 'HIGH_COST' | 'LOW_COST' | 'MINIMUM_TAX' | 'AVERAGE_COST' | 'NONE') : Option taxlot method
  • equityTaxLotMethod ('FIFO' | 'LIFO' | 'HIGH_COST' | 'LOW_COST' | 'MINIMUM_TAX' | 'AVERAGE_COST' | 'NONE') : Equity taxlot method
  • defaultAdvancedToolLaunch ('TA' | 'N' | 'Y' | 'TOS' | 'NONE' | 'CC2') : Default advanced tool launch
  • authTokenTimeout ('FIFTY_FIVE_MINUTES' | 'TWO_HOURS' | 'FOUR_HOURS' | 'EIGHT_HOURS') : Auth token timeout


UserPrincipalFields : 'streamerSubscriptionKeys' | 'streamerConnectionInfo' | 'preferences' | 'surrogateIds'


Market : 'EQUITY' | 'OPTION' | 'FUTURE' | 'BOND' | 'FOREX'


PriceHistoryQuery : object

Properties

  • periodType ('day' | 'month' | 'year' | 'ytd') : The type of period to show
  • period (1 | 2 | 3 | 4 | 5 | 6 | 10 | 15 | 20) : The number of periods to show
    • day : 1, 2, 3, 4, 5, 10*
    • month : 1*, 2, 3, 6
    • year : 1*, 2, 3, 5, 10, 15, 20
    • ytd : 1*
  • frequencyType ('minute' | 'daily' | 'weekly' | 'monthly') : The type of frequency with which a new candle is formed
    • day : minute*
    • month : daily, weekly*
    • year : daily, weekly, monthly*
    • ytd : daily, weekly*
  • frequency (1 | 5 | 10 | 15 | 30) : The number of the frequencyType to be included in each candle. Valid frequencies by frequencyType (defaults marked with an asterisk):
    • minute: 1*, 5, 10, 15, 30
    • daily: 1*
    • weekly: 1*
    • monthly: 1*
  • startDate (string) : Start date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided
  • endDate (string) : End date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided. Default is previous trading day
  • needExtendedHoursData (boolean) : Include extended hours data. Default is true


OptionStrategy : 'SINGLE' | 'ANALYTICAL' | 'COVERED' | 'VERTICAL' | 'CALENDAR' | 'STRANGLE' | 'STRADDLE' | 'BUTTERFLY' | 'CONDOR' | 'DIAGONAL' | 'COLLAR' | 'ROLL'


OptionChainQuery : object

Properties

  • contractType ('CALL' | 'PUT' | 'ALL') : Type of contracts to return in the chain. Default is ALL
  • strikeCount (number) : The number of strikes to return above and below the at-the-money price
  • includeQuotes (boolean) : Include quotes for options in the option chain. Default is false
  • strategy (OptionStrategy) : Passing a value returns a Strategy Chain. Default is SINGLE
  • interval (OptionStrategy) : Strike interval for spread strategy chains
  • strike (number) : Provide a strike price to return options only at that strike price
  • range ('ITM' | 'NTM' | 'OTM' | 'SAK' | 'SBK' | 'SNK' | 'ALL') : Returns options for the given range. Default is ALL
    • ITM : In-the-money
    • NTM : Near-the-money
    • OTM : Out-of-the-money
    • SAK : Strikes Above Market
    • SBK : Strikes Below Market
    • SNK : Strikes Near Market
    • ALL : All Strikes
  • fromDate (string) : Only return expirations after this date. For strategies, expiration refers to the nearest term expiration in the strategy. Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz
  • toDate (string) : Only return expirations before this date. For strategies, expiration refers to the nearest term expiration in the strategy. Valid ISO-8601 formats are: yyyy-MM-dd and yyyy-MM-dd'T'HH:mm:ssz
  • volatility (OptionStrategy) : Volatility to use in calculations.Applies only to ANALYTICAL strategy chains
  • underlyingPrice (OptionStrategy) : Underlying price to use in calculations.Applies only to ANALYTICAL strategy chains
  • interestRate (OptionStrategy) : Interest rate to use in calculations.Applies only to ANALYTICAL strategy chains
  • daysToExpiration (OptionStrategy) : Days to expiration to use in calculations.Applies only to ANALYTICAL strategy chains
  • expMonth (string) : Return only options expiring in the specified month. Month is given in the three character format (eg. JAN). Default is ALL
  • optionType ('S' | 'NS' | 'ALL') : Type of contracts to return. Default is ALL


OrderStatus : 'AWAITING_PARENT_ORDER' | 'AWAITING_CONDITION' | 'AWAITING_MANUAL_REVIEW' | 'ACCEPTED' | 'AWAITING_UR_OUT' | 'PENDING_ACTIVATION' | 'QUEUED' | 'WORKING' | 'REJECTED' | 'PENDING_CANCEL' | 'CANCELED' | 'PENDING_REPLACE' | 'REPLACED' | 'FILLED' | 'EXPIRED'


OrdersQuery : object

Properties

  • maxResults (number) : The max number of orders to retrieve.
  • fromEnteredTime (string) : Specifies that no orders entered before this time should be returned. Valid ISO-8601 formats are: yyyy-MM-dd. Date must be within 60 days from today's date. toEnteredTime must also be set.
  • toEnteredTime (string) : Specifies that no orders entered after this time should be returned. Valid ISO-8601 formats are: yyyy-MM-dd. fromEnteredTime must also be set.
  • status (OrderStatus) : Specifies that only orders of this status should be returned.


TransactionQuery : object

Properties

  • type ('ALL' | 'TRADE' | 'BUY_ONLY' | 'SELL_ONLY' | 'CASH_IN_OR_CASH_OUT' | 'CHECKING' | 'DIVIDEND' | 'INTEREST' | 'OTHER' | 'ADVISOR_FEES') : Only transactions with the specified type will be returned.
  • symbol (string) : Only transactions with the specified symbol will be returned.
  • startDate (string) : Only transactions after the Start Date will be returned. Note: The maximum date range is one year. Valid ISO-8601 formats are: yyyy-MM-dd.
  • endDate (string) : Only transactions before the End Date will be returned. Note: The maximum date range is one year. Valid ISO-8601 formats are: yyyy-MM-dd.


WatchlistInstrument : object

Properties

  • symbol (string) : Symbol
  • description (string) : Description
  • assetType ('EQUITY' | 'OPTION' | 'MUTUAL_FUND' | 'FIXED_INCOME' | 'INDEX') : Asset type


WatchlistItem : object

Properties


Watchlist : object

Properties


State : 'connecting' | 'connected' | 'authenticated' | 'disconnecting' | 'disconnected'


Event : 'state_change' | 'message' | 'account_activity' | 'chart' | 'news_headline' | 'timesale' | 'level_one_equity' | 'level_one_futures' | 'level_one_option' | 'chart_history_futures' | 'error'


Error : 'unknown_error' | 'unknown_message' | 'unknown_response' | 'unknown_notification' | 'unknown_data' | 'invalid_message' | 'connection_refused' | 'authentication_failed'


DisconnectOptions : object

Properties

  • force (boolean) : Disconnect immediately


Request : object

The request object

Properties

  • requestid (string) : A unique request identifier
  • service (string) : The service name
  • parameters (object) : The service parameters
  • command (string) : The command


Service : object

The service object

Properties

  • requestid (string) : A unique request identifier
  • service (string) : The service name
  • parameters (object) : The service parameters


ChartHistoryFuturesOptions : object

The Chart history futures options object

Properties

  • frequency ('m1' | 'm5' | 'm10' | 'm30' | 'h1' | 'd1' | 'w1' | 'n1') : Frequency
  • period (string) : Time period. eg. d5, w4, n10, y1, y10 (d=day, w=week, n=month, y=year)
  • START_TIME (string) : Start time of chart in milliseconds since Epoch
  • END_TIME (string) : End time of chart in milliseconds since Epoch