forked from DerekNPelkey/auto-rsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtastyAPI.py
220 lines (205 loc) · 9.76 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# Donald Ryan Gullett
# TastyTrade API
import asyncio
import os
import traceback
from decimal import Decimal as D
from dotenv import load_dotenv
from tastytrade.account import Account
from tastytrade.dxfeed.event import EventType
from tastytrade.instruments import Equity
from tastytrade.order import (
NewOrder,
OrderAction,
OrderTimeInForce,
OrderType,
PriceEffect,
)
from tastytrade.session import Session
from tastytrade.streamer import DataStreamer
from helperAPI import Brokerage, printAndDiscord, printHoldings, stockOrder
def day_trade_check(tt: Session, acct: Account, cash_balance, loop=None):
trading_status = acct.get_trading_status(tt)
day_trade_count = trading_status.day_trade_count
if (
acct.margin_or_cash == "Margin"
and float(cash_balance) <= 25000
and day_trade_count > 3
):
printAndDiscord(
f"Tastytrade account {acct.account_number}: day trade count is {day_trade_count}. More than 3 day trades will cause a strike on your account!",
loop=loop,
)
return False
return True
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)
new_order = NewOrder(
time_in_force=OrderTimeInForce.DAY,
order_type=OrderType.MARKET,
legs=[leg],
price=stock_price if order_type[0] == "Limit" else None,
price_effect=PriceEffect.DEBIT,
)
elif order_type[2] == "Sell to Close":
leg = symbol.build_leg(D(amount), OrderAction.SELL_TO_CLOSE)
new_order = NewOrder(
time_in_force=OrderTimeInForce.DAY,
order_type=OrderType.MARKET,
legs=[leg],
price=stock_price if order_type[0] == "Limit" else None,
price_effect=PriceEffect.CREDIT,
)
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:
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)):
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
# Day trade check
balances = acct.get_balances(obj)
cash_balance = float(balances["cash-balance"])
if day_trade_check(obj, acct, cash_balance):
# Place order
new_order = order_setup(
obj, order_type, stock_price, s, orderObj.get_amount()
)
placed_order = accounts[i].place_order(
obj, new_order, dry_run=orderObj.get_dry()
)
# Check order status
if placed_order.order.status.value == "Routed":
message = f"{key} {acct.account_number}: {orderObj.get_action()} {orderObj.get_amount()} of {s}"
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 placed_order.order.status.value == "Rejected":
# Retry with limit order
streamer = await DataStreamer.create(obj)
stock_limit = await streamer.oneshot(EventType.PROFILE, [s])
stock_quote = await streamer.oneshot(EventType.QUOTE, [s])
printAndDiscord(
f"{key} {acct.account_number} Error: Order Rejected! Trying Limit order...",
loop=loop,
)
# Get limit price
if orderObj.get_action() == "buy":
stock_limit = D(stock_limit[0].highLimitPrice)
stock_price = (
D(stock_quote[0].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[0].lowLimitPrice)
stock_price = (
D(stock_quote[0].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 = accounts[i].place_order(
obj, new_order, dry_run=orderObj.get_dry()
)
# Check order status
if placed_order.order.status.value == "Routed":
message = f"{key} {acct.account_number}: {orderObj.get_action()} {orderObj.get_amount()} of {s}"
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 placed_order.order.status.value == "Rejected":
printAndDiscord(
f"{key} {acct.account_number}: Error: Limit Order Rejected! Skipping Account...",
loop=loop,
)
printAndDiscord(
f"{key} {acct.account_number}: Error placing order: {placed_order.order.id} on account {acct.account_number}: {placed_order.order.status.value}",
loop=loop,
)
except Exception as te:
printAndDiscord(
f"{key} {acct.account_number}: Error: {te}", loop=loop
)
def tastytrade_transaction(tt: Brokerage, orderObj: stockOrder, loop=None):
asyncio.run(tastytrade_execute(tt_o=tt, orderObj=orderObj, loop=loop))