All Projects → studerw → Td Ameritrade Client

studerw / Td Ameritrade Client

Licence: apache-2.0
TD Ameritrade Java Client

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Td Ameritrade Client

robinhood.tools
📈🤑💰 Advanced trading tools and resources for Robinhood Web.
Stars: ✭ 27 (-22.86%)
Mutual labels:  forex, stock-market, stocks
NSE-Stock-Scanner
National Stock Exchange (NSE), India based Stock screener program. Supports Live Data, Swing / Momentum Trading, Intraday Trading, Connect to online brokers as Zerodha Kite, Risk Management, Emotion Control, Screening, Strategies, Backtesting, Automatic Stock Downloading after closing, live free day trading data and much more
Stars: ✭ 78 (+122.86%)
Mutual labels:  options, stock-market, stocks
Graphvega
Open Source Options Analytics Platform.
Stars: ✭ 189 (+440%)
Mutual labels:  stock-market, stocks, options
market-monitor
Interactive app to monitor market using Python
Stars: ✭ 20 (-42.86%)
Mutual labels:  options, stock-market, stocks
intrinio-realtime-java-sdk
Intrinio Java SDK for Real-Time Stock Prices
Stars: ✭ 22 (-37.14%)
Mutual labels:  forex, stock-market, stocks
Finance-Robinhood
Trade stocks and ETFs with free brokerage Robinhood and Perl
Stars: ✭ 42 (+20%)
Mutual labels:  options, stock-market, stocks
tuneta
Intelligently optimizes technical indicators and optionally selects the least intercorrelated for use in machine learning models
Stars: ✭ 77 (+120%)
Mutual labels:  stock-market, stocks
AIPortfolio
Use AI to generate a optimized stock portfolio
Stars: ✭ 28 (-20%)
Mutual labels:  stock-market, stocks
Ticker
Terminal stock ticker with live updates and position tracking
Stars: ✭ 3,986 (+11288.57%)
Mutual labels:  stock-market, stocks
Gym Anytrading
The most simple, flexible, and comprehensive OpenAI Gym trading environment (Approved by OpenAI Gym)
Stars: ✭ 627 (+1691.43%)
Mutual labels:  stocks, forex
stockscore
A python project to fetch stock financials/statistics and perform preliminary screens to aid in the stock selection process
Stars: ✭ 54 (+54.29%)
Mutual labels:  stock-market, stocks
Finance Go
📊 Financial markets data library implemented in go.
Stars: ✭ 392 (+1020%)
Mutual labels:  stock-market, options
Stocksharp
Algorithmic trading and quantitative trading open source platform to develop trading robots (stock markets, forex, crypto, bitcoins, and options).
Stars: ✭ 4,601 (+13045.71%)
Mutual labels:  stocks, forex
investbook
Оценка эффективности инвестиций с учетом комиссий, налогов (удержанных и ожидающихся), дивидендов и купонов.
Stars: ✭ 83 (+137.14%)
Mutual labels:  stock-market, stocks
Pyex
Python interface to IEX and IEX cloud APIs
Stars: ✭ 311 (+788.57%)
Mutual labels:  stock-market, stocks
sse-option-crawler
SSE 50 index options crawler 上证50期权数据爬虫
Stars: ✭ 17 (-51.43%)
Mutual labels:  stock-market, stocks
Iex Api
The IEX API provides any individual or academic, public or private institution looking to develop applications that require stock market data to access near real-time quote and trade data for all stocks trading on IEX.
Stars: ✭ 683 (+1851.43%)
Mutual labels:  stock-market, stocks
Lean
Lean Algorithmic Trading Engine by QuantConnect (Python, C#)
Stars: ✭ 5,675 (+16114.29%)
Mutual labels:  forex, options
Algotrader
Simple algorithmic stock and option trading for Node.js.
Stars: ✭ 468 (+1237.14%)
Mutual labels:  stock-market, options
Financedatabase
This is a database of 180.000+ symbols containing Equities, ETFs, Funds, Indices, Futures, Options, Currencies, Cryptocurrencies and Money Markets.
Stars: ✭ 554 (+1482.86%)
Mutual labels:  stock-market, options

TD Ameritrade Java Client

TDA_LOGO

Java CI with Maven APL v2


Java rest client for OAuth2 TD Ameritrade Api. Uses OKHttp 3 under the hood.

Required TDA Properties

The client only requires a TDA client ID (consumer key) and current OAuth refresh token. The refresh token expires every 90 days. Note that the client id should not have appended the @AMER.OAUTHAP which is used only when refreshing your OAuth token.

See the Getting Started to set up the developer account itself.
and the wiki has directions on how to generate a refresh token.

Usage

Add the following to your Maven build file:

  <dependency>
    <groupId>com.studerw.tda</groupId>
    <artifactId>td-ameritrade-client</artifactId>
    <version>2.4.0</version>
  </dependency>

Or for Gradle:

dependencies {
  compile "com.studerw.tda:td-ameritrade-client:2.4.0"
}

You need to obtain a valid TDA Developer refresh token every 90 days. See TDA's Simple Auth for Local Apps.

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

  TdaClient tdaClient = new HttpTdaClient(props);
  final Quote quote = tdaClient.fetchQuote("msft");
  EquityQuote equityQuote = (EquityQuote) quote;

  System.out.println("Current price of MSFT: " + equityQuote.getAskPrice());

Build

To build the jar, check out the source and run:

git clone https://github.com/studerw/td-ameritrade-client.git
cd td-ameritrade-client
mvn clean install

You do not need to build the project to use it. The latest release is available on Maven Central, so just include the dependency in your Maven pom or Gradle build file.

Integration Tests

Integration tests do require a client app ID and refresh token to run.

To run integration tests, you will need to rename the file src/test/resources/my-test.properties.changeme to my-test.properties and fill in the necessary TDA properties.

Then run the following command.

mvn failsafe:integration-test

POJO otherfields Property

The TDA API seems to be in a constant state of change, and some documentation is out of sync with the actual responses. Thus, in order to ensure that all properties are deserialized from the returned JSON into our Java pojos, an otherfields Map is contained in most types. You can get any new or undocumented fields using code similar to the following:

Quote quote = tdaClient.fetchQuote("msft");
String someField = (String)quote.getOtherFields().get("someField"))

Date and Time Handling

Most TDA dates and times are returned as longs (i.e. milliseconds since the epoch UTC). An easy way to convert them to Java's new DateTime is via the following:

long someMilliseconds= ...
ZonedDateTime dateTime = Instant.ofEpochMilli(someDateTime)
  .atZone(ZoneId.systemDefault());

Or you could use the deprecated java.util.Date.

long someDateTime = ...
Date date = new Date(someDateTime);

To convert a long to human readable ISO 8601 String, use the following:

long currentTime = System.currentTimeMillis();
String formattedDate = Utils.epochToStr(currentTime);
System.out.println(formattedDate) //   2019-09-13T19:59-04:00[America/New_York]

Error Handling

Only unchecked exceptions are thrown to avoid littering your code with try / catch blocks.

Before the call is made, request parameter validation exceptions can be thrown. Usually you won't have to catch these in your program, though they'll be helpful when testing.

Once the call is made, the TDA server can return 200 success responses even if the call was not successful, for example, you've sent an invalid request type or set of parameters. Often this means the body is an empty JSON string.

The rules are this:

  • OAuth authentication problems, explicitly signalled by a 401 response codes, usually mean an invalid TDA client id (consumer key) or an expired refresh token, and this will throw an IllegalStateException.

  • Validation issues that are known before the call is made, e.g. null or empty required parameters, will throw unchecked IllegalArgumentException.

  • All non 200 HTTP responses throw unchecked RuntimeExceptions since there is no way for the API to recover.

  • Responses that are completely empty but should have returned a full json body throw a RunTimeException as well.

  • If there is an error parsing the JSON into a Java pojo, the RuntimeException wrapping the IOException from Jackson will be thrown.

Logging

The API uses SLF4J as does OKHttp 3. You can use any implementation like Logback or Log4j2.

Specific Loggers that you can tune:

  • TDA_HTTP - set this to INFO for basic request / response info, or DEBUG to see full headers and body.
  • com.studerw.tda.client.OauthInterceptor - detailed info on OAUTH can be seen using either INFO or DEBUG
  • com.studerw.tda - basic API logging with either INFO or DEBUG
  • com.squareup.okhttp3 - lower level OKHTTP library.

Logback

Add Logback to your pom:

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>

Add a logback.xml file to you classpath (e.g. src/main/resources/)

<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="false" scanPeriod="3 seconds" debug="false">
  <contextName>main</contextName>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>
        %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n
      </pattern>
    </encoder>
  </appender>

  <logger name="TDA_HTTP" level="INFO"/>
  <logger name="com.studerw.tda" level="INFO"/>
  <logger name="com.studerw.tda.client.OauthInterceptor" level="INFO"/>
  <logger name="com.squareup.okhttp3" level="INFO"/>

  <root level="WARN">
    <appender-ref ref="STDOUT"/>
  </root>

</configuration>

Old API Deprecated

See the old-xml-api branch for the previous project based on the soon-to-be-deprecated TDA XML API.

Sometime in-between the beginning of this project (based on TDA's older XML API) and now, TDA released a restful API. Unfortunately the old API is being deprecated in 2020 and so the original source code for this project has been moved to the old-xml-api branch and is now known as version 1.0.0.

TODO

  • Junit 5
  • OptionChain query parameters are commented out in HttpTdaClient
  • Streaming API
  • convert to jakarta packages for validation / javax (or maybe get rid of it completely)
  • Maybe get rid of Commons IO and Commons Lang to pare down dependencies
  • Add EZ order abstraction (e.g. simple buy and sell equity)
  • JSON Client
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].