Skip to content
William Studer edited this page Nov 17, 2019 · 32 revisions

How To

Instantiate a Client

Client Properties

  • tda.token.refresh (Required) - the refresh token for TDA OAuth. See Simple Auth for Local Apps to create it.
  • tda.client_id (Required) - Your TDA Client ID which is created when you register your app with TDA. See Getting Started.
  • tda.url (Optional) - URL root of the API which defaults to https://apis.tdameritrade.com/v1.
  • tda.debug.bytes.length (Optional) - How many bytes does the logging interceptor debug to output? -1 is unlimited and is the default.

Using a Properties File and Default Constructor

Drop a file named in the root of your classpath named tda-api.properties. With a default Maven project, the location is src/main/resources. Then instantiate a client using the default constructor:

TdaClient client = new HttpTdaClient();`

Setting the Properties in Constructor:

Properties props = new Properties();
props.set("tda.client_id", "...");
props.set("tda.token.refresh", "...")

TdaClient tdaClient = new HttpTdaClient(props);

Fetch Market Quotes:

Quote quote = client.fetchQuotes("MSFT");
EquityQuote equityQuote = (EquityQuote)quote;
System.out.println("Current price of MSFT: " + equityQuote.getAskPrice());

Fetch a single quote:

The TDA api allows fetching quotes for equities, mutual funds, futures, options, etc. The TdaClient always returns one or more Quote objects which can then be cast to the actual class based on the underlying AssetType. For example:

List<String> symbols = Arrays.asList("VTSAX", "MSFT", "NOK/JPY", "$SPX.X", "MSFT_061821P65", "SPY");
final List<Quote> quotes = client.fetchQuotes(stocks);

assertThat(quotes.get(0)).isInstanceOf(MutualFundQuote.class);
assertThat(quotes.get(1)).isInstanceOf(EquityQuote.class);
assertThat(quotes.get(2)).isInstanceOf(ForexQuote.class);
assertThat(quotes.get(3)).isInstanceOf(IndexQuote.class);
assertThat(quotes.get(4)).isInstanceOf(OptionQuote.class);
assertThat(quotes.get(5)).isInstanceOf(EtfQuote.class);

Get Price History

Get a price history for a single security using default parameters which is something like a single quote for every minute of the last ten days:

PriceHistory priceHistory = client.priceHistory("GOOG");

Use a PriceHistoryReq.Builder. For example, get history for VGIAX for the last week, for every one minute.

PriceHistReq request = Builder.priceHistReq()
        .withSymbol("VGIAX")
        .withStartDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 7))
        .withFrequencyType(FrequencyType.minute)
        .withFrequency(1)
        .build();

PriceHistory priceHistory = client.priceHistory(request);

Get Account Information

final List<SecuritiesAccount> accounts = client.getAccounts(true, true);

Trade

Make an Order

Create the Order Object

There are so many types of orders that can be placed, the Order is overkill for simple equity trades.

Order order = new Order();
order.setOrderType(OrderType.MARKET);
order.setSession(Session.NORMAL);
order.setDuration(Duration.DAY);
order.setOrderStrategyType(OrderStrategyType.SINGLE);

OrderLegCollection olc = new OrderLegCollection();
olc.setInstruction(Instruction.BUY);
olc.setQuantity(new BigDecimal("15.0"));
order.getOrderLegCollection().add(olc);

Instrument instrument = new EquityInstrument();
instrument.setSymbol("MSFT");
olc.setInstrument(instrument);

Once the order is created, place it with the client:

client.placeOrder("<account_id">, order);

Cancel an Order

client.cancelOrder("<account_id">, <order_id>);

Fetch Order(s)

Fetch a specific order by ID under a specific account.

Order order = client.fetchOrder("<account_id">, <order_id>);

Fetch all Orders, including cancelled, under all your accounts:

List<Order> client.fetchOrders();

Fetch Orders using criteria:

Last 10 days:

OrderRequest req = new OrderRequest(ZonedDateTime.now().minusDays(10), ZonedDateTime.now());
List<Order> client.fetchOrders(orderRequest);

Symbol Lookup

Lookup all symbols using a regex:

Query query = new Query("ms.*", QueryType.SYMBOL_REGEX);
final List<Instrument> instruments = httpTdaClient.queryInstruments(query);

Lookup all instruments (equities, forex, bonds, options, etc.) by description regex:

Query query = new Query("bank", QueryType.DESCRIPTION_SEARCH);
List<Instrument> instruments = httpTdaClient.queryInstruments(query);

Lookup a bond by explicit CUSIP:

List<String> cusips = Arrays.asList("70153RJT6", "33616CGC8", "06405VDP1", "61690UNX4");
cusips.forEach(cusip -> {
  Instrument instrument = client.getBond(cusip);
  assertThat(instrument.getAssetType()).isEqualTo(AssetType.BOND);
  assertThat(instrument.getBondPrice()).isNotNull();
});

Get Full Fundamentals on an Instrument

final FullInstrument instrument = httpTdaClient.getFundamentalData("msft");
assertThat(instrument.getAssetType()).isEqualTo(AssetType.EQUITY);
assertThat(instrument.getSymbol()).isEqualTo("MSFT");
assertThat(instrument.getExchange()).isEqualTo("NASDAQ");
Fundamental fundamental = instrument.getFundamental();
assertThat(fundamental.getMarketCapFloat()).isGreaterThan(new BigDecimal("1"));
assertThat(fundamental.getDividendDate()).isNotEmpty();
Clone this wiki locally