forked from phileaton/tradier-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtradier_api.py
More file actions
590 lines (533 loc) · 19.6 KB
/
Copy pathtradier_api.py
File metadata and controls
590 lines (533 loc) · 19.6 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
from dataclasses import dataclass
from urllib.parse import urljoin
import requests
from tradier_python.models import *
class TradierAPI:
"""
Tradier-python is a python client for interacting with the Tradier API.
"""
def __init__(self, token, default_account_id=None, endpoint=None):
self.default_account_id = default_account_id
self.endpoint = endpoint if endpoint else SANDBOX_ENDPOINT
self.session = requests.Session()
self.session.headers.update(
{
"Authorization": f"Bearer {token}",
"Accept": "application/json",
}
)
def request(self, method: str, path: str, params: dict) -> dict:
url = urljoin(self.endpoint, path)
response = self.session.request(method.upper(), url, params=params)
if response.status_code != 200:
raise TradierAPIError(
response.status_code, response.content.decode("utf-8")
)
res_json = response.json()
key = url.rsplit("/", 1)[-1]
if res_json.get(key) == "null":
res_json[key] = []
return res_json
def get(self, path: str, params: dict) -> dict:
"""makes a GET request to an endpoint"""
return self.request("GET", path, params)
def post(self, path: str, params: dict) -> dict:
"""makes a POST request to an endpoint"""
return self.request("POST", path, params)
def delete(self, path: str, params: dict):
"""makes a DELETE request to an endpoint"""
return self.request("DELETE", path, params)
def put(self, path: str, params):
"""makes a PUT request to an endpoint"""
return self.request("PUT", path, params)
def get_profile(self) -> Profile:
"""
The user’s profile contains information pertaining to the user and his/her accounts. In addition to listing
all the accounts a user has, this call should be used to create a personalized experience for your customers
(i.e. displaying their name when they log in).
https://documentation.tradier.com/brokerage-api/user/get-profile
"""
url = "/v1/user/profile"
data = self.get(url, {})
res = AccountsAPIResponse(**data)
return res.profile
def get_balances(self, account_id=None) -> Balances:
"""
Get balances information for a specific user account. Account balances are calculated on each request during
market hours. Each night, balance figures are reconciled with our clearing firm and used as starting point for
the following market session.
https://documentation.tradier.com/brokerage-api/accounts/get-account-balance
"""
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/balances"
data = self.get(url, {})
res = AccountsAPIResponse(**data)
return res.balances
def get_positions(self, account_id=None) -> List[Position]:
"""Get the current positions being held in an account. These positions are updated intraday via trading.
https://documentation.tradier.com/brokerage-api/accounts/get-account-positions
"""
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/positions"
data = self.get(url, {})
res = AccountsAPIResponse(**ensure_list(data, "positions"))
return res.positions.position
def get_history(
self,
account_id=None,
page: int = None,
limit: int = None,
type: str = None,
start: date = None,
end: date = None,
symbol: str = None,
) -> List[Event]:
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/history"
params = {
"page": page,
"limit": limit,
"type": type,
"start": start,
"end": end,
"symbol": symbol,
}
data = self.get(url, params)
res = AccountsAPIResponse(**data)
return res.history.event
def get_gain_loss(
self,
page: int = None,
limit: int = None,
sort_by: str = None,
sort: str = None,
start: date = None,
end: date = None,
symbol: str = None,
account_id=None,
) -> List[ClosedPosition]:
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/gainloss"
params = {
"page": page,
"limit": limit,
"sortBy": sort_by,
"sort": sort,
"start": start,
"end": end,
"symbol": symbol,
}
data = self.get(url, params)
res = AccountsAPIResponse(**data)
return res.gainloss.closed_position
def get_orders(
self,
include_tags: bool = True,
account_id=None,
) -> List[Order]:
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/orders"
params = {"includeTags": include_tags}
data = self.get(url, params)
res = AccountsAPIResponse(**ensure_list(data, "orders"))
return res.orders.order
def get_order(
self,
id: str,
include_tags: bool = False,
account_id=None,
):
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/orders/{id}"
params = {"includeTags": include_tags}
data = self.get(url, params)
res = AccountsAPIResponse(**data)
return res.order
def order(
self,
order_class: str,
symbol: str,
order_type: str,
duration: str,
quantity: Optional[int],
side: Optional[str],
limit_price: float = None,
stop_price: float = None,
tag: str = None,
account_id: str = None,
option_symbol: str = None,
option_symbol_0: str = None,
side_0: str = None,
quantity_0: int = None,
option_symbol_1: str = None,
side_1: str = None,
quantity_1: int = None,
option_symbol_2: str = None,
side_2: str = None,
quantity_2: int = None,
option_symbol_3: str = None,
side_3: str = None,
quantity_3: int = None,
) -> OrderDetails:
"""
Place an order to trade a security.
"""
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/orders"
params = {
"class": order_class,
"symbol": symbol,
"option_symbol": option_symbol,
"side": side,
"quantity": quantity,
"type": order_type,
"duration": duration,
"price": limit_price,
"stop": stop_price,
"tag": tag,
"option_symbol[0]": option_symbol_0,
"side[0]": side_0,
"quantity[0]": quantity_0,
"option_symbol[1]": option_symbol_1,
"side[1]": side_1,
"quantity[1]": quantity_1,
"option_symbol[2]": option_symbol_2,
"side[2]": side_2,
"quantity[2]": quantity_2,
"option_symbol[3]": option_symbol_3,
"side[3]": side_3,
"quantity[3]": quantity_3,
}
params = {k: v for k, v in params.items() if v is not None}
data = self.post(url, params)
res = OrderAPIResponse(**data)
if res.errors:
raise TradierOrderError(res.errors.error_list)
return res.order
def order_equity(
self,
symbol: str,
side: str,
quantity: int,
order_type: str,
duration: str,
limit_price: float = None,
stop_price: float = None,
tag: str = None,
account_id: str = None,
) -> OrderDetails:
"""
Place an order to trade an equity security.
"""
return self.order(
order_class="equity",
symbol=symbol,
side=side,
quantity=quantity,
order_type=order_type,
duration=duration,
limit_price=limit_price,
stop_price=stop_price,
tag=tag,
account_id=account_id,
)
def order_option(
self,
symbol: str,
option_symbol: str,
side: str,
quantity: int,
order_type: str,
duration: str,
limit_price: float = None,
stop_price: float = None,
tag: str = None,
account_id: str = None,
) -> OrderDetails:
"""
Place an order to trade a single option.
"""
return self.order(
order_class="option",
symbol=symbol,
option_symbol=option_symbol,
side=side,
quantity=quantity,
order_type=order_type,
duration=duration,
limit_price=limit_price,
stop_price=stop_price,
tag=tag,
account_id=account_id,
)
def order_multi_leg_option(
self,
symbol: str,
order_type: str,
duration: str,
limit_price: float = None,
tag: str = None,
option_symbol_0: str = None,
side_0: str = None,
quantity_0: int = None,
option_symbol_1: str = None,
side_1: str = None,
quantity_1: int = None,
option_symbol_2: str = None,
side_2: str = None,
quantity_2: int = None,
option_symbol_3: str = None,
side_3: str = None,
quantity_3: int = None,
account_id: str = None,
) -> OrderDetails:
"""
Place an order to trade a single option.
"""
return self.order(
order_class="multileg",
symbol=symbol,
side=None,
quantity=None,
order_type=order_type,
duration=duration,
limit_price=limit_price,
stop_price=None,
tag=tag,
account_id=account_id,
option_symbol_0=option_symbol_0,
side_0=side_0,
quantity_0=quantity_0,
option_symbol_1=option_symbol_1,
side_1=side_1,
quantity_1=quantity_1,
option_symbol_2=option_symbol_2,
side_2=side_2,
quantity_2=quantity_2,
option_symbol_3=option_symbol_3,
side_3=side_3,
quantity_3=quantity_3,
)
def cancel_order(self, order_id, account_id=None) -> OrderDetails:
"""
Cancel and order
"""
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/orders/{order_id}"
data = self.delete(url, {})
res = OrderAPIResponse(**data)
return res.order
def modify_order(
self,
order_id,
order_type: str = None,
duration: str = None,
limit_price: float = None,
stop_price: float = None,
account_id=None,
) -> OrderDetails:
"""
Modify an order. You may change some or all of these parameters. You may not change the session of a pre/post
market session order. Send only the parameters you would like to adjust.
"""
if account_id is None:
account_id = self.default_account_id
url = f"/v1/accounts/{account_id}/orders/{order_id}"
params = {
"type": order_type,
"duration": duration,
"price": limit_price,
"stop": stop_price,
}
params = {k: v for k, v in params.items() if v is not None}
data = self.put(url, params)
res = OrderAPIResponse(**data)
return res.order
def get_quotes(self, symbols: str, greeks: bool = False) -> List[Quote]:
"""
Get a list of symbols using a keyword lookup on the symbols description. Results are in descending order by
average volume of the security. This can be used for simple search functions.
"""
url = "/v1/markets/quotes"
params = {"symbols": symbols, "greeks": greeks}
data = self.get(url, params)
res = MarketsAPIResponse(**ensure_list(data, "quotes"))
return res.quotes.quotes
def get_option_chains(
self, symbol: str, expiration: date, greeks: bool = False
) -> List[Quote]:
"""
Get all quotes in an option chain. Greek and IV data is included courtesy of ORATS. Please check out their APIs
for more in-depth options data.
Greeks/IV data is updated once per hour. This data is calculated using the ORATS APIs and is supplied directly
from them.
"""
url = "/v1/markets/options/chains"
params = {
"symbol": symbol,
"expiration": expiration,
"greeks": greeks,
}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.options.option
def get_option_strikes(self, symbol: str, expiration: date) -> List[float]:
"""
Get an options strike prices for a specified expiration date.
"""
url = "/v1/markets/options/strikes"
params = {"symbol": symbol, "expiration": expiration}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.strikes.strike
def get_option_expirations(
self, symbol: str, include_all_roots: bool = None, strikes: str = None
) -> List[date]:
"""
Get expiration dates for a particular underlying.
Note that some underlying securities use a different symbol for their weekly options (RUT/RUTW, SPX/SPXW). To
make sure you see all expirations, make sure to send the includeAllRoots parameter. This will also ensure any
unique options due to corporate actions (AAPL1) are returned.
"""
url = "/v1/markets/options/expirations"
params = {
"symbol": symbol,
"includeAllRoots": include_all_roots,
"strikes": strikes,
}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.expirations.date
def lookup_option_symbols(self, underlying: str) -> List[Symbol]:
"""
Get all options symbols for the given underlying. This will include additional option roots (ex. SPXW, RUTW) if applicable.
"""
url = "/v1/markets/options/lookup"
params = {"underlying": underlying}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.symbols
def get_historical_quotes(
self, symbol: str, interval: str = None, start: date = None, end: date = None
) -> List[HistoricQuote]:
"""
Get historical pricing for a security. This data will usually cover the entire lifetime of the company if
sending reasonable start/end times. You can fetch historical pricing for options by passing the OCC option symbol
(ex. AAPL220617C00270000) as the symbol.
Notes: Historical data may not be dividend adjusted as this relies on the exchanges to report/adjust it properly.
Historical options data is not available for expired options.
"""
url = "/v1/markets/history"
params = {"symbol": symbol, "interval": interval, "start": start, "end": end}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.history.day
def get_time_and_sales(
self,
symbol: str,
interval: str = None,
start: date = None,
end: date = None,
session_filter: str = None,
) -> List[TimesalesData]:
"""
Time and Sales (timesales) is typically used for charting purposes. It captures pricing across a time slice at
predefined intervals.
Tick data is also available through this endpoint. This results in a very large data set for high-volume
symbols, so the time slice needs to be much smaller to keep downloads time reasonable.
"""
url = "/v1/markets/timesales"
params = {
"symbol": symbol,
"interval": interval,
"start": start,
"end": end,
"session_filter": session_filter,
}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.series.data
def get_etb_list(self) -> List[Security]:
"""
The ETB list contains securities that are able to be sold short with a Tradier Brokerage account. The list is
quite comprehensive and can result in a long download response time.
"""
url = "/v1/markets/etb"
data = self.get(url, {})
res = MarketsAPIResponse(**data)
return res.securities.security
def get_clock(self) -> Clock:
"""
Get the intraday market status. This call will change and return information pertaining to the current day. If
programming logic on whether the market is open/closed – this API call should be used to determine the current
state.
"""
url = "/v1/markets/clock"
data = self.get(url, {})
res = MarketsAPIResponse(**data)
return res.clock
def get_calendar(self, month: int = None, year: int = None) -> List[Hours]:
"""
Get the market calendar for the current or given month. This can be used to plan ahead regarding strategies.
However, the Get Intraday Status should be used to determine the current status of the market.
"""
url = "/v1/markets/calendar"
params = {"month": month, "year": year}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
return res.calendar.days.day
def search_companies(self, query: str, indexes: bool = True) -> List[Security]:
"""
Get a list of symbols using a keyword lookup on the symbols description. Results are in descending order by
average volume of the security. This can be used for simple search functions.
"""
url = "/v1/markets/search"
params = {"q": query, "indexes": indexes}
data = self.get(url, params)
res = MarketsAPIResponse(**data)
if res.securities is not None:
return res.securities.security
else:
return []
def lookup_symbol(
self, query: str, exchanges: str = None, types: str = None
) -> List[Security]:
"""
Get a list of symbols using a keyword lookup on the symbols description. Results are in descending order by
average volume of the security. This can be used for simple search functions.
"""
url = "/v1/markets/lookup"
params = {"q": query, "exchanges": exchanges, "types": types}
data = self.get(url, params)
res = MarketsAPIResponse(**ensure_list(data, "securities", "security"))
if res.securities is not None:
return res.securities.security
else:
return []
@dataclass
class TradierAPIError(Exception):
code: int
message: str
@dataclass
class TradierOrderError(Exception):
errors: List[str]
def ensure_list(data, key1, key2=None):
"""The API is inconsitent in how empty responses are returned. This ensures that we always get an empty list."""
if key2 is None:
key2 = key1[:-1]
if isinstance(data[key1], list):
data[key1] = {}
data[key1][key2] = []
elif data[key1].get(key2) is None:
data[key1][key2] = []
elif not isinstance(data[key1].get(key2), list):
data[key1][key2] = [data[key1][key2]]
return data