from tda import auth, client import json token_path = '/path/to/token.pickle' api_key = '*****@*****.**' redirect_uri = 'https://your.redirecturi.com' try: c = auth.client_from_token_file(token_path, api_key) except FileNotFoundError: from selenium import webdriver 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.DAILY, frequency=client.Client.PriceHistory.Frequency.DAILY) assert r.ok, r.raise_for_status() print(json.dumps(r.json(), indent=4))
from tda import auth, client import os, json, datetime from chalice import Chalice from chalicelib import config app = Chalice(app_name='trading-view-tdameritrade-option-alert') token_path = os.path.join(os.path.dirname(__file__), 'chalicelib', 'token') c = auth.client_from_token_file(token_path, config.api_key) @app.route('/quote/{symbol}') def quote(symbol): response = c.get_quote(symbol) return response.json() @app.route('/option/chain/{symbol}') def option_chain(symbol): response = c.get_option_chain(symbol) return response.json() @app.route('/option/order', methods=['POST']) def option_order(): webhook_message = app.current_request.json_body print(webhook_message)
from trader.forms import StartTradeForm from trader.models import StartTrade from django.views.generic import ListView from tda import auth, client from tda.client import Client from tda.orders.common import OrderType, Session, Duration from tda.orders.equities import equity_buy_market, equity_buy_limit from tda.orders.generic import OrderBuilder import pandas as pd import requests import json import config # authenticates the client try: c = auth.client_from_token_file(config.TOKEN_PATH, config.API_KEY) except FileNotFoundError: from selenium import webdriver with webdriver.Chrome(executable_path=config.CHROMEDRIVER_PATH) as driver: c = auth.client_from_login_flow( driver, config.API_KEY, config.REDIRECT_URI, config.TOKEN_PATH) def Standing_Orders(headers, account_id): endpoint = 'https://api.tdameritrade.com/v1/orders' payload = { 'accountId': account_id, 'maxResults': 6 } content = requests.get(url=endpoint, json=payload, headers=headers)
def test_no_such_file(self): with self.assertRaises(FileNotFoundError): auth.client_from_token_file(self.json_path, API_KEY)
def main(): print('Script start time: ' + datetime.now().strftime('%Y-%m-%d %H:%M:%S')) # Get our log file and make headers with open(FILE, 'a', newline='') as f: wr = csv.writer(f, dialect='excel') wr.writerow([ 'symbol', 'expdate', 'strike', 'bid', 'ask', 'lastPrice', 'volatility', 'dataObtained' ]) # Auth with gmail and make token if not already existing SCOPES = ['https://www.googleapis.com/auth/gmail.modify'] creds = None if os.path.exists('gmailtoken.json'): creds = Credentials.from_authorized_user_file('gmailtoken.json', SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('gmailtoken.json', 'w') as token: token.write(creds.to_json()) service = build('gmail', 'v1', credentials=creds) # Auth with tda and make token if not already existing try: c = auth.client_from_token_file('tdatoken.pickle', API_KEY) except FileNotFoundError: with webdriver.Chrome() as driver: c = auth.client_from_login_flow(driver, API_KEY, REDIRECT_URI, 'tdatoken.pickle') # Calls the Gmail API every 5 minutes while True: instruments = [] print('Checking for unread [email protected] emails') messages = service.users().messages().list( userId='me', q='is:UNREAD from:[email protected]').execute().get( 'messages', []) if not messages: print('None found.') else: print('Message(s) found:') for message in messages: msg = service.users().messages().get( userId='me', id=message['id']).execute() print(msg['snippet'][0:60] + '[...]') service.users().messages().modify(userId='me', id=message['id'], body={ 'removeLabelIds': ['UNREAD'] }).execute() print('Message marked as read') instruments.append(parse_instrument_from_email(msg['snippet'])) print(instruments) quote = c.get_quotes(symbols=instruments) assert quote.status_code == 200, quote.raise_for_status() log_data(quote) print('Waiting 5 minutes...') print('Press Ctrl+C to end this script') time.sleep(300)
# from excel import OpenExcel import os, sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) import config from tda import auth, client import json redirect_uri = 'https://localhost' try: c = auth.client_from_token_file(config.token_path, api_key) except FileNotFoundError: from selenium import webdriver 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.DAILY, frequency=client.Client.PriceHistory.Frequency.DAILY) assert r.status_code == 200, r.raise_for_status() print(json.dumps(r.json(), indent=4))
from tda import auth, client from datetime import datetime import pytz # import files # //Authentication from config import client_id, token_path, redirect_uri # //Looping from close_order import close_order from company_name import symbols from portfolio import my_portfolio from strategies import long_strategy # Config - Authentication try: c = auth.client_from_token_file(token_path, client_id) except FileNotFoundError: from selenium import webdriver with webdriver.Chrome( executable_path= 'D:\Documents\Python\Project\TD Ameritrade\chromedriver.exe' ) as driver: c = auth.client_from_login_flow(driver, client_id, redirect_uri, token_path) # set current time def get_current_time(): now = datetime.now(pytz.timezone('America/New_York')) return (9, 50) # (now.hour, now.minute) # <-- Need to change back # time - Tuple containing hours and minutes