currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) import config # stored in parent directory for security token_path = 'token' redirect_uri = "https://localhost" DRIVER_PATH = "/home/hopper/chromedriver" driver = webdriver.Chrome(DRIVER_PATH) try: c = auth.client_from_token_file(token_path, config.api_key) except FileNotFoundError: c = auth.client_from_login_flow(driver, config.api_key, redirect_uri, token_path) time.sleep(2) # print(c.place_order(config.tda_acct_num, equity_buy_market('SNDL', 1).set_duration(Duration.GOOD_TILL_CANCEL).set_session(Session.SEAMLESS).build())) builder = EquityOrderBuilder('') builder.set_instruction(EquityOrderBuilder.instruction.SELL) builder.set_order_type(EquityOrderBuilder.OrderType.MARKET) builder.set_duration(duration.DAY) builder.set_session(Session.NORMAL) response = c.place_order(config.tda_acct_num, builder.build()) print(response) time.sleep(2)
from tda import auth, client import json import TDConfig import time import urllib try: c = auth.client_from_token_file(TDConfig.token_path, TDConfig.api_key) except FileNotFoundError: from selenium import webdriver with webdriver.Chrome(executable_path = 'C:/Users/user/Desktop/TD AMR/chromedriver') as driver: c = auth.client_from_login_flow( driver, TDConfig.api_key, TDConfig.redirect_uri, TDConfig.token_path)
from tda.auth import client_from_login_flow from Resources.config import client_id, redirect_url from selenium import webdriver import pandas as pd try: # Tries to initialize tda client client = easy_client(api_key=client_id, redirect_uri=redirect_url, token_path='resources/token.txt', webdriver_func=webdriver.Chrome) except Exception as exc: # Gets new token if previous token is expired client = client_from_login_flow(webdriver.Chrome(), api_key=client_id, redirect_url=redirect_url, token_path='resources/token.txt', redirect_wait_time_seconds=0.1, max_waits=3000, asyncio=False, token_write_func=None) traceback.print_exc(exc) def get_price_history(symbol, start, end, frequencyType, periodType, frequency): r = client.get_price_history(symbol, period_type=periodType, frequency=frequency, frequency_type=frequencyType, start_datetime=start, end_datetime=end, need_extended_hours_data=False)
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) order_info = content.json() print(order_info) # performs the trade def trader(request):
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)
# //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 # set valid time def is_valid_time(time): return (time[0] == 9 and time[1] >= 30) or (time[0] > 9 and time[0] < 16) # check if the symbol already contain in my_portfolio