Class HttpTdaClient
- All Implemented Interfaces:
TdaClient
TdaClient
which uses OKHttp3 under the hood and uses the new OAuth
based security.
This is a thread safe class.- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final String
protected static final DateTimeFormatter
protected static final int
-
Constructor Summary
ConstructorsConstructorDescriptionUsing this constructor will assume there are properties found atclasspath:/tda-api.properties
.HttpTdaClient
(Properties props) To avoid using a properties file, you can define anything that would be intda-api.properties
file. -
Method Summary
Modifier and TypeMethodDescriptionprotected okhttp3.HttpUrl.Builder
void
cancelOrder
(String accountId, String orderId) Cancel an order by account Id and order Id.fetchMovers
(MoversReq moversReq) Note that this call can return an empty list on days the market is closed.fetchOrder
(String accountId, Long orderId) This call assumes the order under the given parameters definitely exists.Fetch all orders for all accounts using TDA defaults.fetchOrders
(OrderRequest orderRequest) Fetch all orders for all accounts using the criteria of the orderRequest.fetchOrders
(String accountId, OrderRequest orderRequest) Fetch all orders for a given account using the criteria of the orderRequest.fetchQuote
(String symbol) Fetch Detailed quote information for one or more symbols.fetchQuotes
(List<String> symbols) Fetch detailed quote information for one or more symbols.fetchTransactions
(String accountId) fetchTransactions
(String accountId, TransactionRequest request) getAccount
(String accountId, boolean positions, boolean orders) Fetch an account by the id.getAccounts
(boolean positions, boolean orders) Fetch all your accounts.Get basic info for a bond via its CUSIP number.Get full fundamental data for a specific security via its CUSIP number or ticker symbol (e.g.Get basic data for an instrument via its CUSIP number.getMarketHours
(List<Hours.MarketType> marketTypes) getMarketHours
(List<Hours.MarketType> marketTypes, LocalDateTime date) Fetch market hours.getOptionChain
(OptionChainReq chainRequest) getOptionChain
(String symbol) getPreferences
(String accountId) Get preferences for a specific accountprotected StreamerSubscriptionKeys
getSubscriptionKeys
(List<String> accountsIds) getTransaction
(String accountId, Long transactionId) getUserPrincipals
(UserPrincipals.Field... fields) protected static Properties
void
placeOrder
(String accountId, Order order) Place an Order.placeOrderReturnId
(String accountId, Order order) Place an Order and return the order ID.priceHistory
(PriceHistReq priceHistReq) Retrieve historical intraday and end of day quote data for an equity, index, mutual fund, forex, option chain, etc.priceHistory
(String symbol) Retrieve historical intraday and end of day quote data for an equity, index, mutual fund, forex, option chain, etc.queryInstruments
(Query query) Query TDA forInstruments
using symbol, name, description, cusip, etc.protected static void
validateProps
(Properties tdaProps) validates the necessary props like refresh token and client id (consumer key).
-
Field Details
-
LOGGING_BYTES
protected static final int LOGGING_BYTES- See Also:
-
ISO_FORMATTER
-
DEFAULT_PATH
- See Also:
-
-
Constructor Details
-
HttpTdaClient
public HttpTdaClient()Using this constructor will assume there are properties found atclasspath:/tda-api.properties
. This props file can include:- tda.token.refresh
- tda.client_id (or sometimes referenced as Consumer Key and it should not have @AMER.OAUTHAP appended
- tda.url=https://api.tdameritrade.com/v1
- tda.debug.bytes.length=-1 (How many bytes of logging interceptor debug to print, -1 is unlimited)
There are no defaults for the tda.token.refresh and tda.client_id (your consumer key). If they are not set, an exception will be thrown Note that the client id should not have appended the @AMER.OAUTHAP part that is used when refreshing your OAuth token.
-
HttpTdaClient
To avoid using a properties file, you can define anything that would be in
tda-api.properties
file. This includes:- tda.token.refresh
- tda.client_id
- tda.url=https://api.tdameritrade.com/v1
- tda.debug.bytes.length=-1 (How many bytes of logging interceptor debug to print, -1 is unlimited)
There are no defaults for tda.token.refresh and tda.client_id (consumer key). If they are not set, an exception will be thrown. Note that sometimes TDA uses Consumer Key instead of the term client id. They are the same. The client id should not have appended the @AMER.OAUTHAP part that is used when refreshing your OAuth token
- Parameters:
props
- required properties
-
-
Method Details
-
initTdaProps
-
validateProps
validates the necessary props like refresh token and client id (consumer key). If others are missing, just use friendly defaults.- Parameters:
tdaProps
- the required props to validate
-
priceHistory
Description copied from interface:TdaClient
Retrieve historical intraday and end of day quote data for an equity, index, mutual fund, forex, option chain, etc. See
AssetType
for possible types, though your account must explicitly have access for some of these. TDA has not implemented all the API calls either (Sep 2019).- periodType: day
- period: 10
- frequencyType: minute
- frequency: 1
- Specified by:
priceHistory
in interfaceTdaClient
- Parameters:
symbol
- uppercase symbol- Returns:
- PriceHistory using all other TDA default request parameters. This appears to be a quote every minute for 10 days.
-
priceHistory
Description copied from interface:TdaClient
Retrieve historical intraday and end of day quote data for an equity, index, mutual fund, forex, option chain, etc. See
AssetType
for possibly types, though your account must explicitly have access for some of these. TDA has not implemented all the API calls either (Sep 2019). Note that some of the parameters within thePriceHistReq
param be null, and then some of the other arguments will be assumed by the non null parameters.- Specified by:
priceHistory
in interfaceTdaClient
- Parameters:
priceHistReq
- validated object of request parameters- Returns:
- PriceHistory with a list of
Candle
Candles based on the frequency and period / date length.
-
fetchQuotes
Description copied from interface:TdaClient
Fetch detailed quote information for one or more symbols. Currently the API allows symbol types of Stocks, Options, Mutual Funds Indexes, and ETFs. Quotes are real-time for accounts subscribed to this service; otherwise, quotes are delayed according to exchange and TDA rules. The following types of Quote are actually returned and can be casted:
Quote quote = client.fetchQuote("ATD"); EquityQuote equityQuote = (EquityQuote)quote;
- Specified by:
fetchQuotes
in interfaceTdaClient
- Parameters:
symbols
- list of valid symbols. Max of 300 based on TDA docs. Index symbols need to be prefixed with a $, e.g. $INX or $SPX.X. Options are in a format like the following: MSFT_061518P60 for a put, or MSFT_061518C60 for a call. This is the Microsoft June 15, 2018 Put/Call at $60.- Returns:
- list of quotes. The
Quote
is the base class, but all objects in the list can be cast to their actual types by looking at theAssetType
attribute. field.
-
fetchQuote
Description copied from interface:TdaClient
Fetch Detailed quote information for one or more symbols. Currently the API allows symbol types of Stocks, Options, Mutual Funds and Indexes, and ETFs. Quotes are real-time for accounts subscribed to this service; otherwise, quotes are delayed according to exchange and TDA rules.
Quote quote = client.fetchQuote("ATD"); EquityQuote equityQuote = (EquityQuote)quote;
- Specified by:
fetchQuote
in interfaceTdaClient
- Parameters:
symbol
- list of valid symbols. Max of 300 based on TDA docs. Index symbols need to be prefixed with a $, e.g. $INX or $SPX.X. Options are in a format like the following: MSFT_061518P60 for a put, or MSFT_061518C60 for a call. This is the Microsoft June 15, 2018 Put/Call at $60.- Returns:
- a quote. The
Quote
is the base class, but all quotes can be cast to their actual types by looking at thecom.studerw.tda.model.quote.Quote.assetType
field.
-
getAccount
Description copied from interface:TdaClient
Fetch an account by the id. By default, balances are included. Positions and Orders can also be included based on the parameters.- Specified by:
getAccount
in interfaceTdaClient
- Parameters:
accountId
- the account. Most users only have a single accountpositions
- whether to include positionsorders
- whether to include orders- Returns:
SecuritiesAccount
with the passed id.
-
getAccounts
Description copied from interface:TdaClient
Fetch all your accounts. By default, balances are included. Positions and Orders can also be included based on the parameters.- Specified by:
getAccounts
in interfaceTdaClient
- Parameters:
positions
- whether to include positionsorders
- whether to include orders- Returns:
- List of all the user's
SecuritiesAccount
.
-
getMarketHours
- Specified by:
getMarketHours
in interfaceTdaClient
-
getMarketHours
Description copied from interface:TdaClient
Fetch market hours.- Specified by:
getMarketHours
in interfaceTdaClient
- Parameters:
marketTypes
- the market of the hours to return Valid markets are EQUITY, OPTION, FUTURE, BOND, FOREX.date
- the date of the market hours (default is now)- Returns:
Hours
-
placeOrder
Description copied from interface:TdaClient
Place an Order.- Specified by:
placeOrder
in interfaceTdaClient
- Parameters:
accountId
- the account under which the order is to be placedorder
- the order to place- See Also:
-
placeOrderReturnId
Description copied from interface:TdaClient
Place an Order and return the order ID. According to TDA docs, this order ID can be obtained from the response within a location header. Users need to check the response code as it is wrapped in aOptional
.Note the documentation on the official TDA site is not all that clear on what kinds of orders and in which cases the order ID will and will not be returned.
For example, if the TDA system is overloaded, the order may be queued and the ID cannot yet be known by the time the call must return (it is synchronous). Users are then required to poll for the new order using
TdaClient.fetchOrders()
or similar.In order to deal with this case without throwing an exception we return the ID wrapped in a
Optional
. We do this instead of throwing an exception to differentiate between an order that likely failed and one that will eventually be placed but didn't have the order ID at the time of return. Users need check the Optional themselves and handle accordingly.- Specified by:
placeOrderReturnId
in interfaceTdaClient
- Parameters:
accountId
- the account under which the order is to be placedorder
- the order to place- Returns:
- the order ID wrapped in an Optional which will be empty if the order ID was not returned by TDA, but the call otherwise returned a successful response. It's likely the order will eventually be placed, and users will need to poll for that ordeer ID using existing methods.
- See Also:
-
fetchOrders
Description copied from interface:TdaClient
Fetch all orders for a given account using the criteria of the orderRequest. You can just use a blank order to use sane defaults.
Order order = client.fetchOrders("123456789", new OrderRequest());
- Specified by:
fetchOrders
in interfaceTdaClient
- Parameters:
accountId
- the orders from only this accountorderRequest
- the request.- Returns:
- list of orders specified by the
OrderRequest
param.
-
fetchOrders
Description copied from interface:TdaClient
Fetch all orders for all accounts using the criteria of the orderRequest. You can use a blank order to use sane defaults.
Order order = client.fetchOrders(new OrderRequest());
- Specified by:
fetchOrders
in interfaceTdaClient
- Parameters:
orderRequest
- the request.- Returns:
- list of orders specified by the
OrderRequest
param.
-
fetchOrders
Description copied from interface:TdaClient
Fetch all orders for all accounts using TDA defaults.- Specified by:
fetchOrders
in interfaceTdaClient
- Returns:
- list of orders for all accounts, using TDA default criteria.
-
fetchOrder
Description copied from interface:TdaClient
This call assumes the order under the given parameters definitely exists. If not, aRuntimeException
is thrown as, behind the scenes, the TDA API will return a 404 response.- Specified by:
fetchOrder
in interfaceTdaClient
- Parameters:
accountId
- account under which the order was originally placedorderId
- the id of the order- Returns:
- Order or a RuntimeException if it doesn't exist.
-
cancelOrder
Description copied from interface:TdaClient
Cancel an order by account Id and order Id.- Specified by:
cancelOrder
in interfaceTdaClient
- Parameters:
accountId
- the account under which this order was placedorderId
- the order to cancel
-
getBond
Description copied from interface:TdaClient
Get basic info for a bond via its CUSIP number. -
queryInstruments
Description copied from interface:TdaClient
Query TDA for
Instruments
using symbol, name, description, cusip, etc. Apparently the following instrument types are queryable:Instrument.AssetType
.The following
QueryTypes
can be made:- SYMBOL_SEARCH: retrieve an instrument using the exact symbol name or CUSIP
- SYMBOL_REGEX: Retrieve instrument data for all symbols matching regex. For example XYZ.* will return all symbols beginning with XYZ
- DESCRIPTION_SEARCH: Retrieve instrument data for instruments whose description contains the word supplied. Example: Bank will return all instruments with Bank in the description.
- DESCRIPTION_REGEX: Search description with full regex support. For example XYZ.[A-C] returns all instruments whose descriptions contain a word beginning with XYZ followed by a character A through C.
- Specified by:
queryInstruments
in interfaceTdaClient
- Parameters:
query
- contains the type of query and the search string.- Returns:
- List of 0 or more instruments that matched the query. If you want the full data of an
instrument, you must use
TdaClient.getFundamentalData(java.lang.String)
using the exact CUSIP or symbol. Note thatInstrument.getBondPrice()
will return null for any instruments not of type BOND. - See Also:
-
getFundamentalData
Description copied from interface:TdaClient
Get full fundamental data for a specific security via its CUSIP number or ticker symbol (e.g. MSFT). Not all CUSIP numbers work, for example those referencing BONDs, at least as of Nov. 2019.- Specified by:
getFundamentalData
in interfaceTdaClient
- Parameters:
id
- CUSIP number or symbol (e.g. MSFT)- Returns:
- full fundamentals of an instrument using a CUSIP or symbol. The
Instrument.getBondPrice()
will be empty unless it is a bond referenced bycusip
. - See Also:
-
fetchMovers
Description copied from interface:TdaClient
Note that this call can return an empty list on days the market is closed. Top 10 (up or down) movers by value or percent for a particular market- Specified by:
fetchMovers
in interfaceTdaClient
- Parameters:
moversReq
- Index must be set, the other fields can be null which will use TDA defaults.- Returns:
- List of top 10 market movers defined by the request.
-
getOptionChain
- Specified by:
getOptionChain
in interfaceTdaClient
- Parameters:
chainRequest
- - should be upper case (e.g. MSFT)- Returns:
- an option chain using all TDA Default parameters
-
getOptionChain
- Specified by:
getOptionChain
in interfaceTdaClient
- Parameters:
symbol
- - should be upper case (e.g. MSFT)- Returns:
- an option chain using all TDA Default parameters
-
fetchTransactions
- Specified by:
fetchTransactions
in interfaceTdaClient
- Parameters:
accountId
- the account under which these transactions occurredrequest
- transaction request which may be empty or using one or more parameters. If you add a startDate then you do need an endDate and vice versa.- Returns:
- list of all transactions
-
getTransaction
- Specified by:
getTransaction
in interfaceTdaClient
- Parameters:
accountId
- the account under which this transactions occurredtransactionId
- transaction id- Returns:
- single transaction
-
getPreferences
Description copied from interface:TdaClient
Get preferences for a specific account- Specified by:
getPreferences
in interfaceTdaClient
- Parameters:
accountId
- user's account id- Returns:
- user's preferences
-
getUserPrincipals
- Specified by:
getUserPrincipals
in interfaceTdaClient
- Parameters:
fields
- zero or more additonalUserPrincipals.Field
fields to return.- Returns:
- user principals
-
fetchTransactions
- Specified by:
fetchTransactions
in interfaceTdaClient
- Parameters:
accountId
- the account under which these transactions occurred- Returns:
- list of all transactions
-
getInstrumentByCUSIP
Description copied from interface:TdaClient
Get basic data for an instrument via its CUSIP number. Data includes attributes such as description, possible symbol, exchange, etc.Apparently the following instrument types are able to be looked up:
Instrument.AssetType
.- Specified by:
getInstrumentByCUSIP
in interfaceTdaClient
- Parameters:
id
- (committee on uniform securities identification procedures numbers).- Returns:
- Basic data using a security's CUSIP. The
Instrument.getBondPrice()
will return null unless thecusip
parameter references a bond. - See Also:
-
getSubscriptionKeys
-
baseUrl
-