TD Ameritrade Functions


Note

Even though the functions are written as robin_stocks.module.function, the module name is unimportant when calling a function. Simply use robin_stocks.function for all functions.

Sending Requests to API


robin_stocks.tda.helper.request_get(url, payload, parse_json)[source]

Generic function for sending a get request.

Parameters:
  • url (str) – The url to send a get request to.
  • payload (dict) – Dictionary of parameters to pass to the url. Will append the requests url as url/?key1=value1&key2=value2.
  • parse_json (bool) – Requests serializes data in the JSON format. Set this parameter true to parse the data to a dictionary using the JSON format.
Returns:

Returns a tuple where the first entry is the response and the second entry will be an error message from the get request. If there was no error then the second entry in the tuple will be None. The first entry will either be the raw request response or the parsed JSON response based on whether parse_json is True or not.

robin_stocks.tda.helper.request_post(url, payload, parse_json)[source]

Generic function for sending a post request.

Parameters:
  • url (str) – The url to send a post request to.
  • payload (dict) – Dictionary of parameters to pass to the url. Will append the requests url as url/?key1=value1&key2=value2.
  • parse_json (bool) – Requests serializes data in the JSON format. Set this parameter true to parse the data to a dictionary using the JSON format.
Returns:

Returns a tuple where the first entry is the response and the second entry will be an error message from the get request. If there was no error then the second entry in the tuple will be None. The first entry will either be the raw request response or the parsed JSON response based on whether parse_json is True or not.

Logging In and Authentication


robin_stocks.tda.authentication.login_first_time(encryption_passcode, client_id, authorization_token, refresh_token)[source]

Stores log in information in a pickle file on the computer. After being used once, user can call login() to automatically read in information from pickle file and refresh authorization tokens when needed.

Parameters:
robin_stocks.tda.authentication.login(encryption_passcode)[source]

Set the authorization token so the API can be used. Gets a new authorization token every 30 minutes using the refresh token. Gets a new refresh token every 60 days.

Parameters:encryption_passcode (str) – Encryption key created by generate_encryption_passcode().
robin_stocks.tda.authentication.generate_encryption_passcode()[source]

Returns an encryption key to be used for logging in.

Returns:Returns a byte object to be used with cryptography.

Getting Stock Information


robin_stocks.tda.stocks.get_instrument(cusip, jsonify=None)[source]

Gets instrument data for a specific stock.

Parameters:
  • cusip (str) – The CUSIP for a stock.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.stocks.get_option_chains(ticker, contract_type='ALL', strike_count='10', include_quotes='FALSE', strategy='SINGLE', interval=None, strike_price=None, range_value='ALL', from_date=None, to_date=None, volatility=None, underlying_price=None, interest_rate=None, days_to_expiration=None, exp_month='ALL', option_type='ALL', jsonify=None)[source]

Gets instrument data for a specific stock.

Parameters:
  • ticker (str) – The stock ticker.
  • contract_type (Optional[str]) – Type of contracts to return in the chain. Can be CALL, PUT, or ALL. Default is ALL.
  • strike_count (Optional[str]) – The number of strikes to return above and below the at-the-money price.
  • include_quotes (Optional[str]) – Include quotes for options in the option chain. Can be TRUE or FALSE. Default is FALSE.
  • strategy (Optional[str]) – Passing a value returns a Strategy Chain. Possible values are SINGLE, ANALYTICAL (allows use of the volatility, underlyingPrice, interestRate, and daysToExpiration params to calculate theoretical values), COVERED, VERTICAL, CALENDAR, STRANGLE, STRADDLE, BUTTERFLY, CONDOR, DIAGONAL, COLLAR, or ROLL. Default is SINGLE.
  • interval (Optional[str]) – Strike interval for spread strategy chains (see strategy param).
  • strike_price (Optional[str]) – Provide a strike price to return options only at that strike price.
  • range_value (Optional[str]) –

    Returns options for the given range. Default is ALL. Possible values are:

    • 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
  • from_date (Optional[str]) – 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.
  • to_date (Optional[str]) – 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 (Optional[str]) – Volatility to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • underlying_price (Optional[str]) – Underlying price to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • interest_rate (Optional[str]) – Interest rate to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • days_to_expiration (Optional[str]) – Days to expiration to use in calculations. Applies only to ANALYTICAL strategy chains (see strategy param).
  • exp_month (Optional[str]) – Return only options expiring in the specified month. Month is given in the three character format. Example: JAN. Default is ALL.
  • option_type (Optional[str]) –

    Type of contracts to return. Default is ALL. Possible values are:

    • S: Standard contracts
    • NS: Non-standard contracts
    • ALL: All contracts
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.stocks.get_price_history(ticker, period_type, frequency_type, frequency, period=None, start_date=None, end_date=None, needExtendedHoursData=True, jsonify=None)[source]

Gets the price history of a stock.

Parameters:
  • ticker (str) – The stock ticker.
  • period_type (str) – The type of period to show. Valid values are day, month, year, or ytd (year to date). Default is day.
  • frequency_type (str) –

    The type of frequency with which a new candle is formed. Valid frequencyTypes by period_type (defaults marked with an asterisk):

    • day: minute*
    • month: daily, weekly*
    • year: daily, weekly, monthly*
    • ytd: daily, weekly*
  • frequency (str) –

    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*
  • period (Optional[str]) –

    The number of periods to show. Valid periods by periodType (defaults marked with an asterisk):

    • day: 1, 2, 3, 4, 5, 10*
    • month: 1*, 2, 3, 6
    • year: 1*, 2, 3, 5, 10, 15, 20
    • ytd: 1*
  • start_date (Optional[str]) – Start date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided.
  • end_date (Optional[str]) – End date as milliseconds since epoch. If startDate and endDate are provided, period should not be provided. Default is previous trading day.
  • needExtendedHoursData (Optional[str]) – true to return extended hours data, false for regular market hours only. Default is true.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.stocks.get_quote(ticker, jsonify=None)[source]

Gets quote information for a single stock.

Parameters:
  • ticker (str) – The ticker of the stock.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.stocks.get_quotes(tickers, jsonify=None)[source]

Gets quote information for multiple stocks. The stock string should be comma separated with no spaces.

Parameters:
  • ticker (str) – The string list of stock tickers.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.stocks.search_instruments(ticker_string, projection, jsonify=None)[source]

Gets a list of all the instruments data for tickers that match a search string.

Parameters:
  • ticker_string (str) – Value to pass to the search. See projection description for more information.
  • projection (str) –

    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.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

Placing and Cancelling Orders


robin_stocks.tda.orders.cancel_order(account_id, order_id, jsonify=None)[source]

Cancel an order for a given account.

Parameters:
  • account_id (str) – The account id.
  • order_id (str) – The order id.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.orders.get_order(account_id, order_id, jsonify=None)[source]

Gets information for an order for a given account.

Parameters:
  • account_id (str) – The account id.
  • order_id (str) – The order id.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.orders.get_orders_for_account(account_id, max_results=None, from_time=None, to_time=None, status=None, jsonify=None)[source]

Gets all the orders for a given account.

Parameters:
  • account_id (Optional[str]) – The account id.
  • max_results (Optional[str]) – The max number of orders to retrieve.
  • from_time (Optional[str]) – 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.
  • to_time (Optional[str]) – 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 (Optional[str]) – Specifies that only orders of this status should be returned. Possible values are 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
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.orders.place_order(account_id, order_payload, jsonify=None)[source]

Place an order for a given account.

Parameters:
  • account_id (str) – The account id.
  • order_payload (str) – A dictionary of key value pairs for the infromation you want to send to order.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

Getting Account Information


robin_stocks.tda.accounts.get_account(id, options=None, jsonify=None)[source]

Get account information for a specific account.

Parameters:
  • id (str) – The account id.
  • options (str) – Balances displayed by default, additional fields can be added here by adding positions or orders As a comma separated list. Example:”positions,orders”
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.accounts.get_accounts(options=None, jsonify=None)[source]

Gets all accounts associated with your API keys.

Parameters:
  • options (str) – Balances displayed by default, additional fields can be added here by adding positions or orders As a comma separated list. Example:”positions,orders”
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.accounts.get_transaction(account_id, transaction_id, jsonify=None)[source]

Get account information for a specific account.

Parameters:
  • account_id (str) – The account id.
  • transaction_id (str) – The transaction id.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.accounts.get_transactions(id, type_value=None, symbol=None, start_date=None, end_date=None, jsonify=None)[source]

Get account information for a specific account.

Parameters:
  • id (str) – The account id.
  • type_value (Optional[str]) – Only transactions with the specified type will be returned. ALL, TRADE, BUY_ONLY, SELL_ONLY, CASH_IN_OR_CASH_OUT, CHECKING, DIVIDEND, INTEREST, OTHER, ADVISOR_FEES

param symbol: Only transactions with the specified symbol will be returned. :type symbol: Optional[str] param start_date: 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. :type start_date: Optional[str] param end_date: 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. :type end_date: Optional[str] :param jsonify: If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format. :type jsonify: Optional[str] :returns: Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

Getting Market Information


robin_stocks.tda.markets.get_hours_for_market(market, date, jsonify=None)[source]

Gets market hours for a specific market.

Parameters:
  • market (str) – The market for which you’re requesting market hours, comma-separated. Valid markets are EQUITY, OPTION, FUTURE, BOND, or FOREX.
  • date (str) – 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.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.markets.get_hours_for_markets(markets, date, jsonify=None)[source]

Gets market hours for various markets.

Parameters:
  • markets (str) – The markets for which you’re requesting market hours, comma-separated. Valid markets are EQUITY, OPTION, FUTURE, BOND, or FOREX.
  • date (str) – 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.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.

robin_stocks.tda.markets.get_movers(market, direction, change, jsonify=None)[source]

Gets market hours for a specific market.

Parameters:
  • market (str) – The market for which you’re requesting market hours, comma-separated. Valid markets are $DJI, $COMPX, or $SPX.X.
  • direction (str) – To return movers with the specified directions of “up” or “down”.
  • change (str) – To return movers with the specified change types of “percent” or “value”.
  • jsonify (Optional[str]) – If set to false, will return the raw response object. If set to True, will return a dictionary parsed using the JSON format.
Returns:

Returns a tuple where the first entry in the tuple is a requests reponse object or a dictionary parsed using the JSON format and the second entry is an error string or None if there was not an error.