Skip to content

Instantly share code, notes, and snippets.

@nicmcd
Created June 3, 2020 21:50
Show Gist options
  • Save nicmcd/7e1a4f8c595e7ecd2828e006cde3301a to your computer and use it in GitHub Desktop.
Save nicmcd/7e1a4f8c595e7ecd2828e006cde3301a to your computer and use it in GitHub Desktop.
An example for tda-api buying and selling
#!/usr/bin/env python3.8
import argparse
import json
import tda
import time
ap = argparse.ArgumentParser()
ap.add_argument('credentials_file', type=argparse.FileType('r'),
help='The file of credentials information')
ap.add_argument('ticker', type=str,
help='The ticker to buy and sell (\'-\' to skip buy/sell)')
args = ap.parse_args()
# import the credentials
try:
cred = json.load(args.credentials_file)
TOKEN_PATH = cred['token_path']
API_KEY = cred['api_key']
REDIRECT_URI = cred['redirect_uri']
ACCOUNT_NUMBER = cred['account_number']
except:
print('Credentials file must be a JSON file with the following format:\n'
'{\n'
' "token_path": "/some/path/to/your/token.pickle",\n'
' "api_key": "YOURAPIKEYHERE@AMER.OAUTHAP",\n'
' "redirect_uri": "https://your.uri.goes.here",\n'
' "account_number": "1234567890"\n'
'}')
exit(-1)
def make_webdriver():
from selenium import webdriver
driver = webdriver.Chrome()
atexit.register(lambda: driver.quit())
return driver
# create Client and Utils objects
client = tda.auth.easy_client(
API_KEY,
REDIRECT_URI,
TOKEN_PATH,
make_webdriver)
util = tda.utils.Utils(client, ACCOUNT_NUMBER)
# get basic account information
resp = client.get_account(ACCOUNT_NUMBER, fields=[
tda.client.Client.Account.Fields.POSITIONS,
tda.client.Client.Account.Fields.ORDERS])
assert resp.ok, resp.raise_for_status()
acct = resp.json()
print(('Account Info:\n'
' Total Value: {}\n'
' Cash Value: {}'
.format(
acct['securitiesAccount']['currentBalances']['liquidationValue'],
acct['securitiesAccount']['currentBalances']['availableFunds'])))
# exit now if ticker is '-'
if args.ticker == '-':
exit(0)
# submit an order to buy 1 share
buy_spec = {
"orderType": "MARKET",
"session": "NORMAL",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection": [
{
"instruction": "Buy",
"quantity": 1,
"instrument": {
"symbol": args.ticker,
"assetType": "EQUITY"
}
}
]
}
print('Submitting order to buy {}...'.format(args.ticker))
resp = client.place_order(ACCOUNT_NUMBER, buy_spec)
if not resp.ok:
print('Error: {}'.format(r.status_code))
try:
print(resp.json()['error'])
except:
resp.raise_for_status()
else:
buy_order = util.extract_order_id(resp)
print('Success! Order number: {}'.format(order))
# wait until the buy order is filled
while True:
print('Checking order status...')
resp = client.get_order(buy_order, ACCOUNT_NUMBER)
if not resp.ok:
print('Error: {}'.format(r.status_code))
try:
print(resp.json()['error'])
except:
resp.raise_for_status()
else:
sts = resp.json()
print('Status is: {}'.format(sts['status']))
if sts['status'] != 'FILLED':
time.sleep(5)
else:
break
# submit an order to sell 1 share
sell_spec = {
"orderType": "MARKET",
"session": "NORMAL",
"duration": "DAY",
"orderStrategyType": "SINGLE",
"orderLegCollection": [
{
"instruction": "Sell",
"quantity": 1,
"instrument": {
"symbol": args.ticker,
"assetType": "EQUITY"
}
}
]
}
print('Submitting order to sell {}...'.format(args.ticker))
resp = client.place_order(ACCOUNT_NUMBER, sell_spec)
if not resp.ok:
print('Error: {}'.format(r.status_code))
try:
print(resp.json()['error'])
except:
resp.raise_for_status()
else:
sell_order = util.extract_order_id(resp)
print('Success! Order number: {}'.format(order))
# wait until the sell order is filled
while True:
print('Checking order status...')
resp = client.get_order(sell_order, ACCOUNT_NUMBER)
if not resp.ok:
print('Error: {}'.format(r.status_code))
try:
print(resp.json()['error'])
except:
resp.raise_for_status()
else:
sts = resp.json()
print('Status is: {}'.format(sts['status']))
if sts['status'] != 'FILLED':
time.sleep(5)
else:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment