forked from DerekNPelkey/auto-rsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtradierAPI.py
209 lines (200 loc) · 8.68 KB
/
tradierAPI.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
# Nelson Dane
# Tradier API
import os
import traceback
import requests
from dotenv import load_dotenv
from helperAPI import Brokerage, printAndDiscord, printHoldings, stockOrder
def tradier_init(TRADIER_EXTERNAL=None):
# Initialize .env file
load_dotenv()
# Import Tradier account
if not os.getenv("TRADIER") and TRADIER_EXTERNAL is None:
print("Tradier not found, skipping...")
return None
# Get access token and split into list
accounts = (
os.environ["TRADIER"].strip().split(",")
if TRADIER_EXTERNAL is None
else TRADIER_EXTERNAL.strip().split(",")
)
# Login to each account
tradier_obj = Brokerage("Tradier")
print("Logging in to Tradier...")
for account in accounts:
name = f"Tradier {accounts.index(account) + 1}"
try:
response = requests.get(
"https://api.tradier.com/v1/user/profile",
params={},
headers={
"Authorization": f"Bearer {account}",
"Accept": "application/json",
},
)
json_response = response.json()
if json_response is None:
raise Exception("Error: Tradier API returned None")
except Exception as e:
print(f"Error logging in to Tradier: {e}")
return None
# Multiple accounts have different JSON structure
if "'account': {'" in str(json_response):
account_num = 1
else:
account_num = len(json_response["profile"]["account"])
print(f"Tradier accounts found: {account_num}")
for x in range(account_num):
if account_num == 1:
an = json_response["profile"]["account"]["account_number"]
else:
an = json_response["profile"]["account"][x]["account_number"]
print(an)
tradier_obj.set_account_number(name, an)
tradier_obj.set_account_type(
name, an, json_response["profile"]["account"][x]["type"]
)
# Get balances
try:
balances = requests.get(
f"https://api.tradier.com/v1/accounts/{an}/balances",
params={},
headers={
"Authorization": f"Bearer {account}",
"Accept": "application/json",
},
)
json_balances = balances.json()
tradier_obj.set_account_totals(
name, an, json_balances["balances"]["total_equity"]
)
except Exception as e:
print(f"Error getting balances for {an}: {e}")
tradier_obj.set_account_totals(name, an, 0)
# Get balances
tradier_obj.set_logged_in_object(name, account)
print("Logged in to Tradier!")
return tradier_obj
def tradier_holdings(tradier_o: Brokerage, loop=None):
# Loop through accounts
for key in tradier_o.get_account_numbers():
for account_number in tradier_o.get_account_numbers(key):
obj: str = tradier_o.get_logged_in_objects(key)
try:
# Get holdings from API
response = requests.get(
f"https://api.tradier.com/v1/accounts/{account_number}/positions",
params={},
headers={
"Authorization": f"Bearer {obj}",
"Accept": "application/json",
},
)
# Convert to JSON
json_response = response.json()
stocks = []
amounts = []
# Check if there are no holdings
if json_response["positions"] == "null":
continue
# Check if there's only one holding
if "symbol" in json_response["positions"]["position"]:
stocks.append(json_response["positions"]["position"]["symbol"])
amounts.append(json_response["positions"]["position"]["quantity"])
else:
# Loop through holdings
for stock in json_response["positions"]["position"]:
stocks.append(stock["symbol"])
amounts.append(stock["quantity"])
# Get current price of each stock
current_price = []
for sym in stocks:
response = requests.get(
"https://api.tradier.com/v1/markets/quotes",
params={"symbols": sym, "greeks": "false"},
headers={
"Authorization": f"Bearer {obj}",
"Accept": "application/json",
},
)
json_response = response.json()
current_price.append(json_response["quotes"]["quote"]["last"])
# Print and send them
for position in stocks:
# Set index for easy use
i = stocks.index(position)
tradier_o.set_holdings(
key, account_number, position, amounts[i], current_price[i]
)
except Exception as e:
printAndDiscord(f"{key}: Error getting holdings: {e}", loop=loop)
print(traceback.format_exc())
continue
printHoldings(tradier_o, loop=loop)
def tradier_transaction(tradier_o: Brokerage, orderObj: stockOrder, loop=None):
print()
print("==============================")
print("Tradier")
print("==============================")
print()
# Loop through accounts
for s in orderObj.get_stocks():
for key in tradier_o.get_account_numbers():
printAndDiscord(
f"{key}: {orderObj.get_action()}ing {orderObj.get_amount()} of {s}",
loop=loop,
)
for account in tradier_o.get_account_numbers(key):
obj: str = tradier_o.get_logged_in_objects(key)
if not orderObj.get_dry():
try:
response = requests.post(
f"https://api.tradier.com/v1/accounts/{account}/orders",
data={
"class": "equity",
"symbol": s,
"side": orderObj.get_action(),
"quantity": orderObj.get_amount(),
"type": "market",
"duration": "day",
},
headers={
"Authorization": f"Bearer {obj}",
"Accept": "application/json",
},
)
try:
json_response = response.json()
except requests.exceptions.JSONDecodeError as e:
printAndDiscord(
f"Tradier account {account} Error: {e} JSON response: {response}",
loop=loop,
)
continue
if json_response["order"]["status"] == "ok":
printAndDiscord(
f"Tradier account {account}: {orderObj.get_action()} {orderObj.get_amount()} of {s}",
loop=loop,
)
else:
printAndDiscord(
f"Tradier account {account} Error: {json_response['order']['status']}",
loop=loop,
)
continue
except KeyError:
printAndDiscord(
f"Tradier account {account} Error: This order did not route. JSON response: {json_response}",
loop=loop,
)
except Exception as e:
printAndDiscord(
f"Tradier account {account}: Error: {e}", loop=loop
)
print(traceback.format_exc())
print(json_response)
else:
printAndDiscord(
f"Tradier account {account}: Running in DRY mode. Trasaction would've been: {orderObj.get_action()} {orderObj.get_amount()} of {s}",
loop=loop,
)