def authenticateAndLoad():
    print("Authenticating with TDAmeritrade...")
    try:
        td = tdameritrade.TDClient()
        td.quote('SPY')
    except tdameritrade.exceptions.InvalidAuthToken:
        print("Token Expired: Getting new token.")
        getTokens()
        td = tdameritrade.TDClient()
    except KeyError:
        print('Invalid Auth Token. Getting new Token.')
        getTokens()
        td = tdameritrade.TDClient()
    print("\n")
    return td
示例#2
0
    def refresh_tdClient(self):
        # Get account details from .env file
        client_id = os.getenv('TDAMERITRADE_CLIENT_ID')
        account_id = os.getenv('TDAMERITRADE_ACCOUNT_ID')
        refresh_token = os.getenv('TDAMERITRADE_REFRESH_TOKEN')

        # Refresh Access token
        refresh_data = tdameritrade.auth.refresh_token(refresh_token, client_id)

        # Set up client
        self.tdclient = tdameritrade.TDClient(refresh_data['access_token'], [account_id])
示例#3
0
    def __init__(self):
        self.client_id = os.getenv('TDAMERITRADE_CLIENT_ID',
                                   default='FGCT7QNS3OXYT0R6DZQIDVIAYE3KFQA3')
        self.account_id = os.getenv('TDAMERITRADE_ACCOUNT_ID',
                                    default='493918836')
        self.refresh_token = os.getenv(
            'TDAMERITRADE_REFRESH_TOKEN',
            default=
            'il0eggPn3999znfXxkJKBwkLsawtEUb1Uub2Oma6FjaRY5+a/CVEPybOC/GAmTwDx9nOGI+qfZDKU1yit4qc56R9Keolj0zINrL0LdgFM3unmdwudyRCwL4YG33iqYxZcRY3FnRj8HwkVVrVUtoDsTfAbycsVY6qHpm1/MRrJganGTEzurt2Yu63/cRdRre2n7Yr+hZQWsyVivByHkM3zj6m8I50Hrk5TSznUDN1k/vZLkqpUNFRmHOtpDRddJN+oVEVdoqytRF0MGW+TMka+G9i1n/fiUZzytEUM7pC02aOd5cR/rAf/FwuN0MQeVHt4kd06t8C5kskq0cPzm4Z8g3zLYR0D3de4O3PQXjS9CLfRdoFbeD+j7FXb30yY703Zx+9/WjN02oUSMtblqrgvJn9SYpPtltUDILhbe3RcdOwWGrydz06I0WyHBN100MQuG4LYrgoVi/JHHvl/UhFrpcXcpEUIqNb7ESHW+9px9bnFVCAtr9oBbTpP0eJ8SUsUNI5OkH2/x+zq4v1fiqasYeeLbwhhuOcFXz8WYHPGdokcQ7oB8aoybS5Fg6V0QlJqhzx/KanbWcQKhTPSjytbykt5UKBKwgmC6lIPqaTmbHstHEGW0S3cyhha1dRkqHbc7XELj54I8obKHbhB76MoOtL6rjDExiuExhQh+8f6n7H/OkH7CzPbx8vXeYBmdUq7ejszxcNiJIE0QaDDH7qtsr8Ah4e6yTfxm2GaEuc1gNOcoVK/c29e8XGf2lrC8sLoR/9B+i+qRdoy4bRMtkadsdmn/YFsexzL46Ohk4cvA+yu/+FRq++H77Zi5d/1rQVWy5o4y1BpS/WYf3Q0uaHmmZzgznMB4qemzosMz2fVboi5MLaYX62fqtZIbe8WG+4xnNrQG8+0gc=212FD3x19z9sWBHDJACbC00B75E'
        )
        self.access_token = os.getenv(
            'TDAMERITRADE_ACCESS_TOKEN',
            default=
            '0cX5kefJbuTmoxGIxkQ+1KxskU05wVENPtkGn5EsoB0sKTvXbz64LdmEads09YTkGFXw4RI1nrkPOinwyx3GxiC4STsloneRrQWV4BuergeUs1KHkVfdYFoWQnVpbjBb0o0IvdeD2KgK1gFdRp+QAG5+JzDT4Flg87nFwR7yZqkS01VIRPxdw6kFzCe3G96N1Dfp3dA0NlXGa/WvC8gH3HIh/NhzYlKXMfHAiMKs3GvIybQo3vxaLwXplO33pa7jwDAFvGn6mnzWPuH6zxpkbRx1HOZyjONdX78EaN53ydBzEF0Ansm5M+I2AQGv5b3DC8zgiu49U2+cmbr/EQJxSnhxM30j+7omvMtSIF4vAz7xIXDcRheJDVL3XBNDagHOiFmEl+nSIp7YIQO/EG/sTsI9jySwzY/xkQJZ9HpnTFtDPNBoO424S3xbEsHnTNec/W1QIUITcKyaz95tIplSBRP7M38yIUqkXr1qxSyCBGRQV4cF+c7/ZtPrE+if2UCXMqSX9iWa2iNmy0ZDQIjebFyD+NXfd7au+Ef2MhWEVKcgtnx9M100MQuG4LYrgoVi/JHHvlQHUJaLeydgtvA1Fn71UVioaYAOPIitVuUabrG1dESyWNL17l7ISy1wYx7Zqa7xPiUutbIsfwPc5aHzFKJ/XGinFhj/x9MssARPvNV5iwFRB9iD+2fdP4uRqcBZUlX2pqh8SVPSclVd4iScWZbpfNx7Jo4/E8ooeD3zX/6wDBHlodvrDO4DVhCtVhB8D7kNwMe/X1QiHqK0ZkvLhqh0UFlLeupqiW3+3/XjmQ52WSd+YJSOHInLT0viuIr4ZrL+hCTzw9Fdyr7Vopk1FV4Pf+aaXCRlL55txTAhOdz0ZnvAC5a5ZG8RE7wUnd19wzTjIblen02nNnKgfVklQKBcECxBmoedAqfuKlDyVF3OUf0QLTt45M2Q5AlOWLpazKV4J3C8PtMruCSN/rMw+ZAM9eAId/pi3qsQKq7oVAV5Qs91GGIQSvATn1fFVZkkYToSuvLjpDkSp0Qa9SIrjYc3LGFz89R9Fi8B3dultssIsJsJelAkrLLzLGcmcDaNlbXZ4XI+t4eiRkE+GQ+YzjBSBfnpY9I8Q/5hLdmrqf5LtKfmaqtmbw==212FD3x19z9sWBHDJACbC00B75E'
        )

        self.tdclient = td.TDClient(self.client_id, self.refresh_token,
                                    self.account_id)
示例#4
0
def main() -> None:
    logger.debug("Attempting to create tda-api client")
    client = tdameritrade.TDClient(
        client_id=API_KEY, refresh_token=read_refresh_token(TOKEN_PATH))

    logger.debug("Starting prometheus metrics server")
    prometheus_client.start_http_server(int(PROMETHEUS_PORT))

    while True:
        start_time = current_milli_time()
        time_sec = int(time.time())

        # Only record data after 9pm and before 5pm
        # Not exactly 9:30 so we can sleep for a minute at a time...
        # Additionally, if the weekday is 5 (saturday) or 6 (sunday) - sleep.
        now = datetime.datetime.now(pytz.utc)
        if now.hour < 14 or now.hour > 22 or \
            now.weekday() is 6 or now.weekday() is 5:

            logger.debug("Not time yet... Sleeping for 60s")
            sleeper_inactive.inc()
            time.sleep(60)
            continue

        logger.debug("Getting quotes data")
        asyncio.run(
            get_and_save_quotes(client, QUOTE_SYMBOLS, start_time, time_sec))
        """ Sleeping Calculations """
        actual_sleep = 1.0 - ((current_milli_time() - start_time) / 1000.0)

        if actual_sleep <= 0.0:
            skipped_sleep.inc()
            skipped_sleep_duration.inc(abs(actual_sleep) + 1.0)
            logger.debug(
                "Not sleeping, sleep was too small: '{}'".format(actual_sleep))
            continue

        logger.debug("Sleeping for: '{}'".format(actual_sleep))
        time_slept.inc(actual_sleep)
        time.sleep(actual_sleep)
示例#5
0
文件: TD_API.py 项目: ziran137/td_api
###############  TD API functions  ###############
import sys, os, time
sys.path.append('./tdameritrade')
sys.path.append('./data')
# sys.path.append('./tdameritrade')
import tdameritrade as td
import pandas as pd
import datetime
import json
## get stored token data
with open('token.json') as json_file:
    token = json.load(json_file)

conn = td.TDClient(api_key=token['api_key'],
                   refresh_token=token['refresh_token'],
                   access_token=token['access_token'],
                   accountIds=token['accountIds'])

## update token data with refreshed access token

with open('token.json', 'w') as f:
    token['access_token'] = conn._access_token
    token['timestamp'] = datetime.datetime.now().strftime('%Y%m%d %H:%M:%S')
    json.dump(token, f, indent=4)

# read stock list in excel
equitylist_file = './EquityList.xlsx'
elist = pd.read_excel(equitylist_file)
# read stock list in csv
# equitylist_file = './data/Instrument.csv'
# elist = pd.read_csv(equitylist_file)
    def get_client(self):
        self.ensureAuth()

        # Return the client
        return td.TDClient(access_token=self.config['_oauth2']['access_token'],
                           accountIds=None)
示例#7
0
    f.close()
    return mensaje


pToken = get_token()

client_id_ = os.getenv('TDAMERITRADE_CLIENT_ID',
                       default='FGCT7QNS3OXYT0R6DZQIDVIAYE3KFQA3')
account_id_ = os.getenv('TDAMERITRADE_ACCOUNT_ID', default='493918836')
refresh_token_ = os.getenv(
    'TDAMERITRADE_REFRESH_TOKEN',
    default=
    'il0eggPn3999znfXxkJKBwkLsawtEUb1Uub2Oma6FjaRY5+a/CVEPybOC/GAmTwDx9nOGI+qfZDKU1yit4qc56R9Keolj0zINrL0LdgFM3unmdwudyRCwL4YG33iqYxZcRY3FnRj8HwkVVrVUtoDsTfAbycsVY6qHpm1/MRrJganGTEzurt2Yu63/cRdRre2n7Yr+hZQWsyVivByHkM3zj6m8I50Hrk5TSznUDN1k/vZLkqpUNFRmHOtpDRddJN+oVEVdoqytRF0MGW+TMka+G9i1n/fiUZzytEUM7pC02aOd5cR/rAf/FwuN0MQeVHt4kd06t8C5kskq0cPzm4Z8g3zLYR0D3de4O3PQXjS9CLfRdoFbeD+j7FXb30yY703Zx+9/WjN02oUSMtblqrgvJn9SYpPtltUDILhbe3RcdOwWGrydz06I0WyHBN100MQuG4LYrgoVi/JHHvl/UhFrpcXcpEUIqNb7ESHW+9px9bnFVCAtr9oBbTpP0eJ8SUsUNI5OkH2/x+zq4v1fiqasYeeLbwhhuOcFXz8WYHPGdokcQ7oB8aoybS5Fg6V0QlJqhzx/KanbWcQKhTPSjytbykt5UKBKwgmC6lIPqaTmbHstHEGW0S3cyhha1dRkqHbc7XELj54I8obKHbhB76MoOtL6rjDExiuExhQh+8f6n7H/OkH7CzPbx8vXeYBmdUq7ejszxcNiJIE0QaDDH7qtsr8Ah4e6yTfxm2GaEuc1gNOcoVK/c29e8XGf2lrC8sLoR/9B+i+qRdoy4bRMtkadsdmn/YFsexzL46Ohk4cvA+yu/+FRq++H77Zi5d/1rQVWy5o4y1BpS/WYf3Q0uaHmmZzgznMB4qemzosMz2fVboi5MLaYX62fqtZIbe8WG+4xnNrQG8+0gc=212FD3x19z9sWBHDJACbC00B75E'
)
access_token_ = os.getenv('TDAMERITRADE_ACCESS_TOKEN', default=pToken)
tc = td.TDClient(access_token=access_token_, accountIds=[account_id_])
MY_SECRET = os.getenv(
    'TDAMERITRADE_ACCOUNT_ID',
    default=
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImVsdG91Y2hAZ21haWwuY29tIiwiaWF0IjoxNTkwMjUxMDU2LCJleHAiOjc4OTc0NTEwNTZ9.vQtvoFRLaTbAe935CRZHPr-gjalbVAuCYXbv7GgE_f4'
)

# import time
# import asyncio
# from threading import Thread

# # async def cor1(jsonData):
# #     texto = jsonData["texto"]
# #     print("texto", texto)
# #     print(f"cor{texto} start")
# #     for i in range(10):
示例#8
0
                              tdapass=config['tda_pass']))
    config['_oauth2']['access_token_timestamp'] = now
    config['_oauth2']['refresh_token_timestamp'] = now
elif (now > int(config['_oauth2']['access_token_timestamp']) +
      int(config['_oauth2']['expires_in']) - (5 * 60)):
    print(
        "Refresh Authentication Required: Access Token Expired, Exchanging Valid Refresh Token"
    )
    config['_oauth2'].update(
        tdauth.refresh_token(refresh_token=config['_oauth2']['refresh_token'],
                             client_id=config['client_id']))
    config['_oauth2']['access_token_timestamp'] = now
else:
    print("Current Authentication Tokens Valid")

# Write back to the configuration file
if YamlUtils.yaml_dict_to_string(config) != YamlUtils.yaml_dict_to_string(
        YamlUtils.yaml_dict_from_file(CONFIG_FILE)):
    print(f"Updating configuration file at {CONFIG_FILE}")
    YamlUtils.yaml_dict_to_file(config, CONFIG_FILE)

#
c = td.TDClient(access_token=config['_oauth2']['access_token'],
                accountIds=None)

df = c.optionsDF('SPY')

import ipdb

ipdb.set_trace()
示例#9
0
def main():
    # Read TDA credentials file.
    with open(args.credentials_path, "r") as fileh:
        config = yaml.safe_load(fileh.read())

    # Connect to TDA's API.
    client = td.TDClient(client_id=config["client_id"],
                         refresh_token=config["refresh_token"])

    # Set the max DTE for options chains.
    max_exp = dt.datetime.now() + dt.timedelta(days=args.dte_max)

    # Get the options chain as a pandas dataframe. (Thanks dobby. 🤗)
    chains = []
    for ticker in args.ticker:
        try:
            chain = client.optionsDF(
                ticker,
                contractType="PUT",
                includeQuotes=True,
                toDate=max_exp.strftime("%Y-%m-%d"),
                optionType="S",
            )
            chains.append(chain)
        except KeyError:
            sys.exit(f"Could not find ticker: {ticker}")

    options = pd.concat(chains)

    # Calculate a return for the trade and an annualized return.
    options["putReturn"], options["annualReturn"] = get_returns(
        options["bid"], options["strikePrice"], options["daysToExpiration"])

    # Handle situations where 'delta' is NaN for a certain strike. Usually all
    # of the greeks are missing for these.
    options["delta"] = pd.to_numeric(options["delta"], errors="coerce")

    # Calculate PoP based on the delta.
    options["pop"] = (1 - options["delta"].abs()) * 100

    # Remove the time of day information from the expiration date.
    options["expirationDate"] = options["expirationDate"].dt.strftime(
        "%Y-%m-%d")

    # Select options that meet all of our requirements.
    selected = options[(options["annualReturn"] >= args.min_return)
                       & (args.pop_min <= options["pop"])
                       & (options["pop"] <= args.pop_max)].sort_values(
                           "annualReturn", ascending=False)

    # Create a view with the columns we care about.
    view = selected[[
        "symbol",
        "strikePrice",
        "expirationDate",
        "daysToExpiration",
        "bid",
        "pop",
        "putReturn",
        "annualReturn",
    ]]
    print(
        view.rename(
            columns={
                "symbol": "💸",
                "strikePrice": "Strike",
                "expirationDate": "Exp Date",
                "daysToExpiration": "DTE",
                "bid": "Bid",
                "pop": "PoP %",
                "putReturn": "Ret. %",
                "annualReturn": "Annual %",
            }).to_markdown(index=False))
示例#10
0
###############  test functions  ###############
import tdameritrade as td
import pandas as pd
token={
  "access_token": "as+I4Am/9jXgvNQZdQUTjjv14e1IMk6LwuI/RT6WVaoHt2FXVetix6Faw7pyMZYoGICqh5Vec0rwsck57TQ8/trzR9E2sf06fW+NheCeELWldW1yJaTklTMntkmhiOrXSU+2lb4Tco2I13zfhnnGSc4s6WlpqaqrRth3WMqAh0a1FZlCKNnLeJiaid089+Zm8t9WJ13syGp0QvbDTkKFbOWaU1FhQXs9/gz6lSrxTudiPkiLWyZmSyNtQWzRU3TldI4jYWjfrUxBzTjxaRxtZp1MfrkVmJPVI5IOkcNeD/yVdRuUULg2Wwoo2wru8lhI3ncXrglDOp1keOV3prn1nShWtqllPDSosFMcUEZXvsSsicOEAgKNyiCWbaHqjM5SoMlyAzEFeqYBgx3lNtvdt0RkaOCtJfxVRkKvZQOy2kq3v23R+aHnvXeBQ7Ve8eQAge/DTp1ExdVqbtW1SKduF/tq92gD/fvHqFWSwx7vDVgP3paoj64CmO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Xki2iNdjcg9sbx6GbTp6qBf2312itfx100MQuG4LYrgoVi/JHHvlhn5AWowPg/YMBH7QyaB84FkL1J16BrmffNTwDK/NDoYSXZMndvhyMEMmhQqazLSxwP7MOZuGR5e6/E7nqvwRFKumJcf5WGZVAMYrp1RzA4j/jzn+DLWeEMC2lPUt4/kI2jKKrBVnAgmYjvEUeuOPOyOD9YhfDsAeka80FmdZHfeJpbeLuY2yX9/VLGklHNHF/Nys+25/1RSvg46Z8vGo17+6kImFLNnYPjL+4HDal6sITObYjh/Bei1+7jzo6NLwRGpYopb2jeq5bahaKBYLEfWyGgOHRx1xZRO5XwYC2HoPNx5oK4AcCfChuO+0doGzQD5uvGHrPODEXib/Zo4CbqXhaKVCILExyL/95uWjM/RofZUu4hb9A+3yDG2ROk7WmKbNkoA5lQnQBscoLeAgJ03FI3Y8huPJooc6dJPFlnTagJeZGAy2GPsYFls=212FD3x19z9sWBHDJACbC00B75E",
  "scope": "PlaceTrades AccountAccess MoveMoney",
  "expires_in": 1800,
  "refresh_token_expires_in": 7776000,
  "token_type": "Bearer"
}
token['accountIds'] = ['ziran1206']


c = td.TDClient(access_token=token['access_token'], accountIds=token['accountIds'])
## 1. Search instrument
symbols = ['AAPL', 'GOOG']
c.search(symbols)
c.searchDF(symbols)

## 2. Fundamentals
symbols = ['AAPL', 'GOOG']
c.fundamental(symbols)
x = c.fundamentalDF(symbols)
x['fundamental']

## 3. Get Instrument by CUSIP
cusip = '88160R101'
c.fundamental(cusip)
c.fundamentalDF(cusip)
示例#11
0
import tdameritrade as td
import os
import csv
from datetime import datetime as dt
from pprint import pprint

client_id = os.getenv('TDAMERITRADE_CLIENT_ID')
account_id = os.getenv('TDAMERITRADE_ACCOUNT_ID')
refresh_token = os.getenv('TDAMERITRADE_REFRESH_TOKEN')

# tdclient = td.TDClient(client_id=client_id, refresh_token=refresh_token, account_ids=[account_id])
c = td.TDClient()
# symbol = 'GLD'


def create_ticker_candles_dict(symbol):

    periodType = 'day'
    period = 1
    frequencyType = 'minute'
    tkrhist = c.history(symbol, periodType, period, frequencyType)
    ticker_candles = dict(datetime=[], open=[], close=[])

    for candle in tkrhist['candles']:
        date = candle['datetime'] / 1e3
        ticker_candles['datetime'].append(dt.fromtimestamp(date))
        ticker_candles['open'].append(candle['open'])
        ticker_candles['close'].append(candle['close'])

    return ticker_candles
示例#12
0
 def start_client_session(self):
     self.td_client = tdameritrade.TDClient(self.access_token)
示例#13
0
 def __init__(self):
     self.client = td.TDClient(consumer_id, refresh_token, access_token,
                               [account_id])