Schwab TD Ameritrade API Client

website·Indexed 30 days ago

https://allensarkisyan.github.io/schwab-td-ameritrade-api/

A JavaScript and TypeScript client implementation for the TD Ameritrade API. Includes the TDAmeritradeAPI class for managing authentication, access token monitoring, and account data retrieval.

Tokens
9.1K
Snippets
63
Records
78
Agent score
74%

What's inside schwab-td-ameritrade-api

  1. Reference OptionChainData and OptionContractDateMap types

    The OptionChainData object represents a complete option chain, including metadata about the underlying asset, volatility, and interest rates. It contains two primary maps, putExpDateMap and callExpDateMap, both of which use the OptionContractDateMap type (a mapping of expiration date strings to arrays of OptionContractData).

    OptionChainData Properties:

    • symbol: The ticker symbol.
    • status: Status of the chain (e.g., "SUCCESS").
    • underlying: Detailed information about the underlying asset.
    • strategy: Trading strategy (e.g., "SINGLE").
    • interval: The interval value.
    • isDelayed: Boolean indicating if data is delayed.
    • isIndex: Boolean indicating if the data relates to an index.
    • interestRate: The current interest rate.
    • underlyingPrice: Current price of the underlying asset.
    • volatility: The volatility value.
    • daysToExpiration: Number of days until expiration.
    • numberOfContracts: Total number of contracts.
    • putExpDateMap: Map of put expiration dates to contract data.
    • callExpDateMap: Map of call expiration dates to contract data.
  2. Fetch market data and price history

    The TDAmeritradeAPI includes several methods for retrieving market data:

    • getQuotes(): Get current quotes.
    • getInstrument(): Get instrument data.
    • getFundamentals(): Get fundamental data.
    • getPriceHistory(), getDailyPriceHistory(), getWeeklyPriceHistory(), getPeriodicPriceHistory(): Retrieve historical price data.
    • getMarketMovers() and getMarketDirectionalMover(): Get market trend and mover data.
    • getOptionChain(): Retrieve the option chain for a symbol.
  3. Fetch quotes and fundamental data for a symbol

    Use tdApi.getQuotes(symbol) to get real-time pricing (like bid and ask prices) and tdApi.getFundamentals(symbol) to retrieve fundamental metrics such as 10-day average volume.
    const { data: quotes } = await tdApi.getQuotes('TSLA');
    const { data: fundamentals } = await tdApi.getFundamentals('TSLA');
    
    const bidPrice = quotes['TSLA'].bidPrice;
    const askPrice = quotes['TSLA'].askPrice;
    const vol10DayAvg = fundamentals['TSLA'].fundamental.vol10DayAvg;
  4. TDAmeritradeAccount object structure

    The TDAmeritradeAccount object represents a TD Ameritrade account and contains detailed information about the securities account, including balances, account status, and current positions.
    interface TDAmeritradeAccount {
      securitiesAccount: {
        accountId: TDAmeritradeAccountID;
        currentBalances: CurrentBalances;
        initialBalances: InitialBalances;
        projectedBalances: ProjectedBalances;
        isClosingOnlyRestricted: boolean;
        isDayTrader: boolean;
        roundtrips: number;
        type: string;
        positions: Array<PositionData>;
      };
    }
  5. Reference the Fundamentals object structure

    The Fundamentals object provides detailed fundamental and market data for a stock, including pricing, volume, dividend information, and exchange details.
    interface Fundamentals {
      assetType: AssetType;
      assetMainType: string;
      cusip: CUSIP;
      assetSubType: string;
      symbol: TickerSymbol;
      description: string;
      bidPrice: number;
      bidSize: number;
      bidId: string;
      askPrice: number;
      askSize: number;
      askId: string;
      lastPrice: number;
      lastSize: number;
      lastId: string;
      openPrice: number;
      highPrice: number;
      lowPrice: number;
      bidTick: string;
      closePrice: number;
      netChange: number;
      totalVolume: number;
      quoteTimeInLong: number;
      tradeTimeInLong: number;
      mark: number;
      exchange: string;
      exchangeName: string;
      marginable: boolean;
      shortable: boolean;
      volatility: number;
      digits: number;
      nAV: number;
      peRatio: number;
      divAmount: number;
      divYield: number;
      divDate: string;
      securityStatus: string;
      regularMarketLastPrice: number;
      regularMarketLastSize: number;
      regularMarketNetChange: number;
      regularMarketTradeTimeInLong: number;
      netPercentChangeInDouble: number;
      markChangeInDouble: number;
      markPercentChangeInDouble: number;
      delayed: boolean;
      realtimeEntitled: boolean;
    }
  6. Reference the TransactionData object

    The TransactionData object provides comprehensive details about a trade transaction, including dates, order IDs, net amounts, and associated fees.
    interface TransactionData {
      type: string;                 // e.g., "TRADE"
      subAccount: string;
      settlementDate: DateLikeNullable;
      orderId: string;
      netAmount: number;
      transactionDate: DateLikeNullable; // ISO 8601 format
      orderDate: DateLikeNullable;       // ISO 8601 format
      transactionSubType: string;    // e.g., "BY"
      transactionId: number;
      cashBalanceEffectFlag: boolean;
      description: OrderDescription;
      fees: TradeTransactionFees;
      transactionItem: TransactionItem;
    }
  7. Reference FundamentalData object structure

    The FundamentalData object represents the fundamental data for a stock, including its CUSIP, symbol, description, exchange, asset type, and a detailed Fundamentals object containing financial ratios and metrics.
    interface FundamentalData {
      fundamental: Fundamentals;
      cusip: string;
      symbol: TickerSymbol;
      description: string;
      exchange: string;
      assetType: string;
    }
  8. Install the Schwab TD Ameritrade API client

    The @allensarkisyan/schwab-td-ameritrade-api client is available via npm or yarn and works in both Node.js and Browser environments.
    npm install @allensarkisyan/schwab-td-ameritrade-api
    # OR
    yarn add @allensarkisyan/schwab-td-ameritrade-api
  9. Initialize the TDAmeritradeAPI client

    Use the createTDAmeritradeAPIClient(config) function to create a new instance of the TDAmeritradeAPI class. This client is the primary interface for interacting with the TD Ameritrade API.
    const client = createTDAmeritradeAPIClient(config);