TD Ameritrade APIs Getting start

1. Register

2. Create an App

  • App name: StudyApp
  • Callback URL: http://td.miaowa.pro/getauth.html
  • Purpose: learning and study
  • Order limit: 120

after filled the above fields, you will get the Customer Key of this App

  • Customer key: XXXXXX
  • Issue Date: Fri, 10/01/2021 - 08:00
  • Expires: Never

3. Start a webserver using python

  • create a directory for this webapp
    • mkdir /home/kylindai/work/webapp/td.miaopro.com
    • enter this directory
    • create a html file named getauth.html
  • run python3 -m http.server
  • so you will get a webserver to response the auth callback

4. Authentication

  • Auth URL: https://auth.tdameritrade.com/auth?response_type=code&redirect_uri=http%3A//td.miaowa.pro/getauth.html&client_id={Customer Key}%40AMER.OAUTHAP
  • then you will get the authorization_code from the callback url
  • call the API: https://api.tdameritrade.com/v1/oauth2/token, you will get the access token, the details of this API is as below:
  • after you get the access token, you could call any APIs provided by TD Ameritrade

5. Github tda-api opensource package

from tda import auth, client
import json
import ssl

# ssl._create_default_https_context = ssl._create_unverified_context

# 保存token的文件路径
token_path = '/Users/kylindai/python/tda-api/token.json'
# {Customer Key}@AMER.OAUTHAP
api_key = 'XXXXXX@AMER.OAUTHAP'
# 回调地址
redirect_uri = 'http://td.miaowa.pro/getauth.html'

try:
    # 获取AccessToke,保存到token_path 
    c = auth.client_from_token_file(token_path, api_key)
except FileNotFoundError:
    from selenium import webdriver
    # 如果token.json不存在,则弹出chrome,登录授权窗口获取token
    with webdriver.Chrome() as driver:
        c = auth.client_from_login_flow(
            driver, api_key, redirect_uri, token_path)

# 获取苹果股票的月线报价
r = c.get_price_history('AAPL',
        period_type=client.Client.PriceHistory.PeriodType.YEAR,
        period=client.Client.PriceHistory.Period.TWENTY_YEARS,
        frequency_type=client.Client.PriceHistory.FrequencyType.MONTHLY,
        frequency=client.Client.PriceHistory.Frequency.MONTHLY)
assert r.status_code == 200, r.raise_for_status()

# 打印结果
print(json.dumps(r.json(), indent=4))

here is the result after running:

{
    "candles": [
        {
            "open": 0.315178575,
            "high": 0.384821425,
            "low": 0.308035725,
            "close": 0.38035715,
            "volume": 5369744800,
            "datetime": 1004594400000
        },
        {
            "open": 0.376071425,
            "high": 0.42910725,
            "low": 0.35875,
            "close": 0.391071425,
            "volume": 4629839200,
            "datetime": 1007186400000
        },
        {
            "open": 0.39375,
            "high": 0.44160725,
            "low": 0.36160715,
            "close": 0.4414285,
            "volume": 8515376800,
            "datetime": 1009864800000
        },
        {
            "open": 0.4175,
            "high": 0.4673215,
            "low": 0.410714275,
            "close": 0.43339275,
            "volume": 6422836000,
            "datetime": 1017640800000
        },
        {
            "open": 0.43375,
            "high": 0.4639285,
            "low": 0.39535715,
            "close": 0.416071425,
            "volume": 5976157600,
            "datetime": 1020229200000
        },
        {
            "open": 141.9,
            "high": 142.92,
            "low": 139.1101,
            "close": 142.65,
            "volume": 94639581,
            "datetime": 1633064400000
        }
    ],
    "symbol": "AAPL",
    "empty": false
}

6. Get option chain of NIO

  • test to get NIO’s option chain:
from tda import auth, client
import json

token_path = '/Users/kylindai/python/tda-api/token.json'
api_key = 'XXXXXX@AMER.OAUTHAP'

c = auth.client_from_token_file(token_path, api_key)

"""
Client.get_option_chain(
    symbol, *, 
    contract_type=None,       -- 合约类型
    strike_count=None,        -- 行权价数量
    include_quotes=None, 
    strategy=None, 
    interval=None, 
    strike=None, 
    strike_range=None, 
    from_date=None, 
    to_date=None, 
    volatility=None,         -- 波动率
    underlying_price=None, 
    interest_rate=None, 
    days_to_expiration=None, -- 还有多少天过期
    exp_month=None, 
    option_type=None)
"""

# 获取蔚来NIO,最近10月份的,2个行权价的看涨期权
r = c.get_option_chain('NIO',
                       contract_type=client.Client.Options.ContractType.CALL,
                       strike_count=2,
                       exp_month=client.Client.Options.ExpirationMonth.OCTOBER)
assert r.status_code == 200, r.raise_for_status()

print(json.dumps(r.json(), indent=4))
  • and here is the result:
{
    "symbol": "NIO",
    "status": "SUCCESS",
    "underlying": null,
    "strategy": "SINGLE",
    "interval": 0.0,
    "isDelayed": false,
    "isIndex": false,
    "interestRate": 0.1,
    "underlyingPrice": 35.36,
    "volatility": 29.0,
    "daysToExpiration": 0.0,
    "numberOfContracts": 10,
    "callExpDateMap": {
        "2021-10-01:-1": {
            "35.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_100121C35",
                    "description": "NIO Oct 1 2021 35 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 0.32,
                    "ask": 0.58,
                    "last": 0.37,
                    "mark": 0.0,
                    "bidSize": 24,
                    "askSize": 190,
                    "bidAskSize": "24X190",
                    "lastSize": 0,
                    "highPrice": 1.74,
                    "lowPrice": 0.35,
                    "openPrice": 0.0,
                    "closePrice": 0.96,
                    "totalVolume": 12259,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118350021,
                    "quoteTimeInLong": 1633118399650,
                    "netChange": -0.59,
                    "volatility": 0.0,
                    "delta": 0.0,
                    "gamma": 0.0,
                    "theta": 0.0,
                    "vega": 0.002,
                    "rho": 0.0,
                    "openInterest": 4671,
                    "timeValue": -0.01,
                    "theoreticalOptionValue": 0.0,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 35.0,
                    "expirationDate": 1633118400000,
                    "daysToExpiration": -1,
                    "expirationType": "S",
                    "lastTradingDay": 1633132800000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -61.28,
                    "markChange": -0.96,
                    "markPercentChange": -100.0,
                    "intrinsicValue": 0.38,
                    "inTheMoney": true,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ],
            "36.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_100121C36",
                    "description": "NIO Oct 1 2021 36 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 0.0,
                    "ask": 0.01,
                    "last": 0.01,
                    "mark": 0.0,
                    "bidSize": 0,
                    "askSize": 114,
                    "bidAskSize": "0X114",
                    "lastSize": 0,
                    "highPrice": 0.87,
                    "lowPrice": 0.01,
                    "openPrice": 0.0,
                    "closePrice": 0.4,
                    "totalVolume": 28306,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118329067,
                    "quoteTimeInLong": 1633118388882,
                    "netChange": -0.38,
                    "volatility": 0.0,
                    "delta": 0.0,
                    "gamma": 0.0,
                    "theta": 0.0,
                    "vega": 0.001,
                    "rho": 0.0,
                    "openInterest": 9893,
                    "timeValue": 0.01,
                    "theoreticalOptionValue": 0.0,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 36.0,
                    "expirationDate": 1633118400000,
                    "daysToExpiration": -1,
                    "expirationType": "S",
                    "lastTradingDay": 1633132800000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -97.47,
                    "markChange": -0.4,
                    "markPercentChange": -100.0,
                    "intrinsicValue": -0.62,
                    "inTheMoney": false,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ]
        },
        "2021-10-08:6": {
            "35.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_100821C35",
                    "description": "NIO Oct 8 2021 35 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 1.15,
                    "ask": 1.2,
                    "last": 1.15,
                    "mark": 1.16,
                    "bidSize": 193,
                    "askSize": 9,
                    "bidAskSize": "193X9",
                    "lastSize": 0,
                    "highPrice": 2.32,
                    "lowPrice": 1.14,
                    "openPrice": 0.0,
                    "closePrice": 1.54,
                    "totalVolume": 5089,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118397520,
                    "quoteTimeInLong": 1633118399901,
                    "netChange": -0.39,
                    "volatility": 47.134,
                    "delta": 0.577,
                    "gamma": 0.162,
                    "theta": -0.062,
                    "vega": 0.02,
                    "rho": 0.004,
                    "openInterest": 4177,
                    "timeValue": 0.77,
                    "theoreticalOptionValue": 1.162,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 35.0,
                    "expirationDate": 1633723200000,
                    "daysToExpiration": 6,
                    "expirationType": "S",
                    "lastTradingDay": 1633737600000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -25.56,
                    "markChange": -0.38,
                    "markPercentChange": -24.75,
                    "intrinsicValue": 0.38,
                    "inTheMoney": true,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ],
            "36.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_100821C36",
                    "description": "NIO Oct 8 2021 36 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 0.67,
                    "ask": 0.68,
                    "last": 0.67,
                    "mark": 0.68,
                    "bidSize": 110,
                    "askSize": 80,
                    "bidAskSize": "110X80",
                    "lastSize": 0,
                    "highPrice": 1.44,
                    "lowPrice": 0.66,
                    "openPrice": 0.0,
                    "closePrice": 1.02,
                    "totalVolume": 13061,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118398831,
                    "quoteTimeInLong": 1633118399413,
                    "netChange": -0.35,
                    "volatility": 46.13,
                    "delta": 0.411,
                    "gamma": 0.164,
                    "theta": -0.06,
                    "vega": 0.02,
                    "rho": 0.003,
                    "openInterest": 5155,
                    "timeValue": 0.67,
                    "theoreticalOptionValue": 0.675,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 36.0,
                    "expirationDate": 1633723200000,
                    "daysToExpiration": 6,
                    "expirationType": "S",
                    "lastTradingDay": 1633737600000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -34.31,
                    "markChange": -0.34,
                    "markPercentChange": -33.82,
                    "intrinsicValue": -0.62,
                    "inTheMoney": false,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ]
        },
        "2021-10-15:13": {
            "35.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_101521C35",
                    "description": "NIO Oct 15 2021 35 Call",
                    "exchangeName": "OPR",
                    "bid": 1.58,
                    "ask": 1.62,
                    "last": 1.6,
                    "mark": 1.61,
                    "bidSize": 3,
                    "askSize": 1,
                    "bidAskSize": "3X1",
                    "lastSize": 0,
                    "highPrice": 2.44,
                    "lowPrice": 1.6,
                    "openPrice": 0.0,
                    "closePrice": 1.94,
                    "totalVolume": 2426,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118374642,
                    "quoteTimeInLong": 1633118399878,
                    "netChange": -0.34,
                    "volatility": 50.255,
                    "delta": 0.562,
                    "gamma": 0.11,
                    "theta": -0.048,
                    "vega": 0.028,
                    "rho": 0.007,
                    "openInterest": 32621,
                    "timeValue": 1.22,
                    "theoreticalOptionValue": 1.608,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 35.0,
                    "expirationDate": 1634328000000,
                    "daysToExpiration": 13,
                    "expirationType": "R",
                    "lastTradingDay": 1634342400000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -17.53,
                    "markChange": -0.33,
                    "markPercentChange": -17.14,
                    "intrinsicValue": 0.38,
                    "inTheMoney": true,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ],
            "36.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_101521C36",
                    "description": "NIO Oct 15 2021 36 Call",
                    "exchangeName": "OPR",
                    "bid": 1.11,
                    "ask": 1.14,
                    "last": 1.12,
                    "mark": 1.13,
                    "bidSize": 2,
                    "askSize": 8,
                    "bidAskSize": "2X8",
                    "lastSize": 0,
                    "highPrice": 1.84,
                    "lowPrice": 1.1,
                    "openPrice": 0.0,
                    "closePrice": 1.38,
                    "totalVolume": 3083,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118386564,
                    "quoteTimeInLong": 1633118399878,
                    "netChange": -0.26,
                    "volatility": 49.662,
                    "delta": 0.449,
                    "gamma": 0.112,
                    "theta": -0.047,
                    "vega": 0.028,
                    "rho": 0.006,
                    "openInterest": 3789,
                    "timeValue": 1.12,
                    "theoreticalOptionValue": 1.125,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 36.0,
                    "expirationDate": 1634328000000,
                    "daysToExpiration": 13,
                    "expirationType": "R",
                    "lastTradingDay": 1634342400000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -18.84,
                    "markChange": -0.25,
                    "markPercentChange": -18.48,
                    "intrinsicValue": -0.62,
                    "inTheMoney": false,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ]
        },
        "2021-10-22:20": {
            "35.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_102221C35",
                    "description": "NIO Oct 22 2021 35 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 1.92,
                    "ask": 2.04,
                    "last": 1.97,
                    "mark": 1.96,
                    "bidSize": 3,
                    "askSize": 2,
                    "bidAskSize": "3X2",
                    "lastSize": 0,
                    "highPrice": 2.63,
                    "lowPrice": 1.92,
                    "openPrice": 0.0,
                    "closePrice": 2.19,
                    "totalVolume": 406,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118379808,
                    "quoteTimeInLong": 1633118399878,
                    "netChange": -0.22,
                    "volatility": 51.55,
                    "delta": 0.56,
                    "gamma": 0.089,
                    "theta": -0.041,
                    "vega": 0.034,
                    "rho": 0.011,
                    "openInterest": 836,
                    "timeValue": 1.59,
                    "theoreticalOptionValue": 1.962,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 35.0,
                    "expirationDate": 1634932800000,
                    "daysToExpiration": 20,
                    "expirationType": "S",
                    "lastTradingDay": 1634947200000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -9.85,
                    "markChange": -0.22,
                    "markPercentChange": -10.2,
                    "intrinsicValue": 0.38,
                    "inTheMoney": true,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ],
            "36.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_102221C36",
                    "description": "NIO Oct 22 2021 36 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 1.45,
                    "ask": 1.46,
                    "last": 1.46,
                    "mark": 1.46,
                    "bidSize": 1,
                    "askSize": 1,
                    "bidAskSize": "1X1",
                    "lastSize": 0,
                    "highPrice": 2.1,
                    "lowPrice": 1.45,
                    "openPrice": 0.0,
                    "closePrice": 1.67,
                    "totalVolume": 339,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118380428,
                    "quoteTimeInLong": 1633118399976,
                    "netChange": -0.21,
                    "volatility": 50.313,
                    "delta": 0.469,
                    "gamma": 0.092,
                    "theta": -0.04,
                    "vega": 0.034,
                    "rho": 0.009,
                    "openInterest": 786,
                    "timeValue": 1.46,
                    "theoreticalOptionValue": 1.455,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 36.0,
                    "expirationDate": 1634932800000,
                    "daysToExpiration": 20,
                    "expirationType": "S",
                    "lastTradingDay": 1634947200000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -12.34,
                    "markChange": -0.21,
                    "markPercentChange": -12.64,
                    "intrinsicValue": -0.62,
                    "inTheMoney": false,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ]
        },
        "2021-10-29:27": {
            "35.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_102921C35",
                    "description": "NIO Oct 29 2021 35 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 2.18,
                    "ask": 2.3,
                    "last": 2.26,
                    "mark": 2.23,
                    "bidSize": 79,
                    "askSize": 77,
                    "bidAskSize": "79X77",
                    "lastSize": 0,
                    "highPrice": 2.96,
                    "lowPrice": 2.25,
                    "openPrice": 0.0,
                    "closePrice": 2.5,
                    "totalVolume": 239,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118171762,
                    "quoteTimeInLong": 1633118399585,
                    "netChange": -0.24,
                    "volatility": 51.595,
                    "delta": 0.559,
                    "gamma": 0.077,
                    "theta": -0.035,
                    "vega": 0.039,
                    "rho": 0.014,
                    "openInterest": 546,
                    "timeValue": 1.88,
                    "theoreticalOptionValue": 2.227,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 35.0,
                    "expirationDate": 1635537600000,
                    "daysToExpiration": 27,
                    "expirationType": "S",
                    "lastTradingDay": 1635552000000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -9.6,
                    "markChange": -0.27,
                    "markPercentChange": -10.9,
                    "intrinsicValue": 0.38,
                    "inTheMoney": true,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ],
            "36.0": [
                {
                    "putCall": "CALL",
                    "symbol": "NIO_102921C36",
                    "description": "NIO Oct 29 2021 36 Call (Weekly)",
                    "exchangeName": "OPR",
                    "bid": 1.71,
                    "ask": 1.81,
                    "last": 1.75,
                    "mark": 1.76,
                    "bidSize": 1,
                    "askSize": 3,
                    "bidAskSize": "1X3",
                    "lastSize": 0,
                    "highPrice": 2.35,
                    "lowPrice": 1.75,
                    "openPrice": 0.0,
                    "closePrice": 2.02,
                    "totalVolume": 251,
                    "tradeDate": null,
                    "tradeTimeInLong": 1633118383611,
                    "quoteTimeInLong": 1633118400109,
                    "netChange": -0.27,
                    "volatility": 51.47,
                    "delta": 0.481,
                    "gamma": 0.078,
                    "theta": -0.036,
                    "vega": 0.04,
                    "rho": 0.012,
                    "openInterest": 1046,
                    "timeValue": 1.75,
                    "theoreticalOptionValue": 1.76,
                    "theoreticalVolatility": 29.0,
                    "optionDeliverablesList": null,
                    "strikePrice": 36.0,
                    "expirationDate": 1635537600000,
                    "daysToExpiration": 27,
                    "expirationType": "S",
                    "lastTradingDay": 1635552000000,
                    "multiplier": 100.0,
                    "settlementType": " ",
                    "deliverableNote": "",
                    "isIndexOption": null,
                    "percentChange": -13.37,
                    "markChange": -0.26,
                    "markPercentChange": -12.87,
                    "intrinsicValue": -0.62,
                    "inTheMoney": false,
                    "mini": false,
                    "nonStandard": false,
                    "pennyPilot": false
                }
            ]
        }
    },
    "putExpDateMap": {}
}

7. Great, good luck!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值