-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
tastyAPI.py
198 lines (185 loc) · 8.95 KB
/
tastyAPI.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# Donald Ryan Gullett
# TastyTrade API
import asyncio
import os
import traceback
from decimal import Decimal as D
from dotenv import load_dotenv
from tastytrade import Session
from tastytrade.account import Account
from tastytrade.dxfeed import Profile, Quote
from tastytrade.instruments import Equity
from tastytrade.order import NewOrder, OrderAction, OrderTimeInForce, OrderType
from tastytrade.streamer import DXLinkStreamer
from tastytrade.utils import TastytradeError
from helperAPI import Brokerage, maskString, printAndDiscord, printHoldings, stockOrder
def order_setup(tt: Session, order_type, stock_price, stock, amount):
symbol = Equity.get_equity(tt, stock)
if order_type[2] == "Buy to Open":
leg = symbol.build_leg(D(amount), OrderAction.BUY_TO_OPEN)
elif order_type[2] == "Sell to Close":
leg = symbol.build_leg(D(amount), OrderAction.SELL_TO_CLOSE)
else:
raise ValueError("Invalid order type")
new_order = NewOrder(
time_in_force=OrderTimeInForce.DAY,
order_type=OrderType.MARKET,
legs=[leg],
price=stock_price if order_type[0] == "Limit" else None,
)
return new_order
def tastytrade_init(TASTYTRADE_EXTERNAL=None):
# Initialize .env file
load_dotenv()
# Import Tastytrade account
if not os.getenv("TASTYTRADE") and TASTYTRADE_EXTERNAL is None:
print("Tastytrade not found, skipping...")
return None
accounts = (
os.environ["TASTYTRADE"].strip().split(",")
if TASTYTRADE_EXTERNAL is None
else TASTYTRADE_EXTERNAL.strip().split(",")
)
tasty_obj = Brokerage("Tastytrade")
# Log in to Tastytrade account
print("Logging in to Tastytrade...")
for account in accounts:
index = accounts.index(account) + 1
account = account.strip().split(":")
name = f"Tastytrade {index}"
try:
tasty = Session(account[0], account[1])
tasty_obj.set_logged_in_object(name, tasty, "session")
an = Account.get_accounts(tasty)
tasty_obj.set_logged_in_object(name, an, "accounts")
for acct in an:
tasty_obj.set_account_number(name, acct.account_number)
tasty_obj.set_account_totals(
name, acct.account_number, acct.get_balances(tasty).cash_balance
)
print("Logged in to Tastytrade!")
except Exception as e:
traceback.print_exc()
print(f"Error logging in to {name}: {e}")
return None
return tasty_obj
def tastytrade_holdings(tt_o: Brokerage, loop=None):
for key in tt_o.get_account_numbers():
obj: Session = tt_o.get_logged_in_objects(key, "session")
for index, account in enumerate(tt_o.get_logged_in_objects(key, "accounts")):
try:
an = tt_o.get_account_numbers(key)[index]
positions = account.get_positions(obj)
for pos in positions:
tt_o.set_holdings(
key,
an,
pos.symbol,
pos.quantity,
pos.average_daily_market_close_price,
)
except Exception as e:
printAndDiscord(f"{key}: Error getting account holdings: {e}", loop)
print(traceback.format_exc())
continue
printHoldings(tt_o, loop=loop)
async def tastytrade_execute(tt_o: Brokerage, orderObj: stockOrder, loop=None):
print()
print("==============================")
print("Tastytrade")
print("==============================")
print()
for s in orderObj.get_stocks():
for key in tt_o.get_account_numbers():
obj: Session = tt_o.get_logged_in_objects(key, "session")
accounts: Account = tt_o.get_logged_in_objects(key, "accounts")
printAndDiscord(
f"{key}: {orderObj.get_action()}ing {orderObj.get_amount()} of {s}",
loop=loop,
)
for i, acct in enumerate(tt_o.get_account_numbers(key)):
print_account = maskString(acct)
try:
acct: Account = accounts[i]
# Set order type
if orderObj.get_action() == "buy":
order_type = ["Market", "Debit", "Buy to Open"]
else:
order_type = ["Market", "Credit", "Sell to Close"]
# Set stock price
stock_price = 0
# Skip day trade check for now
# Place order
new_order = order_setup(
obj, order_type, stock_price, s, orderObj.get_amount()
)
try:
placed_order = acct.place_order(
obj, new_order, dry_run=orderObj.get_dry()
)
order_status = placed_order.order.status.value
except Exception as e:
printAndDiscord(
f"{key} {print_account}: Error placing order: {e}",
loop=loop,
)
continue
# Check order status
if order_status in ["Received", "Routed"]:
message = f"{key} {print_account}: {orderObj.get_action()} {orderObj.get_amount()} of {s} Order: {placed_order.order.id} Status: {order_status}"
if orderObj.get_dry():
message = f"{key} Running in DRY mode. Transaction would've been: {orderObj.get_action()} {orderObj.get_amount()} of {s}"
printAndDiscord(message, loop=loop)
elif order_status == "Rejected":
# Retry with limit order
streamer = await DXLinkStreamer.create(obj)
stock_limit = await streamer.subscribe(Profile, [s])
stock_quote = await streamer.subscribe(Quote, [s])
stock_limit = await streamer.get_event(Profile)
stock_quote = await streamer.get_event(Quote)
printAndDiscord(
f"{key} {print_account} Error: {order_status} Trying Limit order...",
loop=loop,
)
# Get limit price
if orderObj.get_action() == "buy":
stock_limit = D(stock_limit.highLimitPrice)
stock_price = (
D(stock_quote.askPrice)
if stock_limit.is_nan()
else stock_limit
)
order_type = ["Market", "Debit", "Buy to Open"]
elif orderObj.get_action() == "sell":
stock_limit = D(stock_limit.lowLimitPrice)
stock_price = (
D(stock_quote.bidPrice)
if stock_limit.is_nan()
else stock_limit
)
order_type = ["Market", "Credit", "Sell to Close"]
print(f"{s} limit price is: ${round(stock_price, 2)}")
# Retry order
new_order = order_setup(
obj, order_type, stock_price, s, orderObj.get_amount()
)
placed_order = acct.place_order(
obj, new_order, dry_run=orderObj.get_dry()
)
# Check order status
if order_status in ["Received", "Routed"]:
message = f"{key} {print_account}: {orderObj.get_action()} {orderObj.get_amount()} of {s} Order: {placed_order.order.id} Status: {order_status}"
if orderObj.get_dry():
message = f"{key} Running in DRY mode. Transaction would've been: {orderObj.get_action()} {orderObj.get_amount()} of {s}"
printAndDiscord(message, loop=loop)
elif order_status == "Rejected":
# Only want this message if it fails both orders.
printAndDiscord(
f"{key} Error placing order: {placed_order.order.id} on account {print_account}: {order_status}",
loop=loop,
)
except (TastytradeError, KeyError) as te:
printAndDiscord(f"{key} {print_account}: Error: {te}", loop=loop)
continue
def tastytrade_transaction(tt: Brokerage, orderObj: stockOrder, loop=None):
asyncio.run(tastytrade_execute(tt_o=tt, orderObj=orderObj, loop=loop))