PyTradier package¶
Submodules¶
PyTradier.account module¶
-
class
PyTradier.account.Account(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True)¶ Bases:
PyTradier.base.BasePyTradierclass for gathering all account related API calls
-
balances() → dict¶ 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.
see more at https://documentation.tradier.com/brokerage-api/reference/response/balances
- Returns
Balance dict
- Return type
dict
-
gainloss(symbol: Optional[str] = None, page: int = 1, limit: int = 100, sortby: str = 'closedate', sort: str = 'desc', start: Optional[Union[str, datetime.datetime]] = None, end: Optional[Union[str, datetime.datetime]] = None) → dict¶ Get cost basis information for a specific user account. This includes information for all closed positions. Cost basis information is updated through a nightly batch reconciliation process with our clearing firm.
- Parameters
symbol (str, optional) – Filter by security symbol, defaults to None
page (int, optional) – Used for paginated results - Page to start results, defaults to 1
limit (int, optional) – Number of results to return per page, defaults to 100
sortby (str, optional) – Field to sort the results. One of [‘openDate’, ‘closeDate’], defaults to “closedate”
sort (str, optional) – Sort directions, One of [‘asc’, ‘desc’], defaults to “desc”
start (Union[str, datetime], optional) – Start Date, defaults to None
end (Union[str, datetime], optional) – End Date, defaults to None
- Returns
list of positions
- Return type
dict
-
history(page: int = 1, limit: int = 25, activity_type: list = [], start: str = '', end: str = '', symbol: str = '') → list¶ Get historical activity for an account. This data originates with our clearing firm and inherently has a few limitations:
Updated nightly (not intraday) Will not include specific time (hours/minutes) a position or order was created or closed Will not include order numbers
- Parameters
page (int, optional) – Used for paginated results. Page to start results, defaults to 1
limit (int, optional) – Number of results to return per page, defaults to 25
activity_type (list, optional) – Activity type, defaults to []
start (str, optional) – start date, empty string will default to account opening date, defaults to “”
end (str, optional) – end date, empty string will default to end of current day, defaults to “”
symbol (str, optional) – Filter by security symbol, defaults to “”
- Returns
list of events
- Return type
list
-
order(orderId: str, includeTags=False) → dict¶ Get detailed information about a previously placed order.
- Parameters
orderId (str) – OrderId of the order you want more information on
includeTags (bool, optional) – Include order tag on response, defaults to False
- Returns
dict with detailed information
- Return type
dict
-
orders() → list¶ Retrieve orders placed within an account. This API will return orders placed for the market session of the present calendar day.
- Returns
list of Order dictionaries
- Return type
list
-
positions() → list¶ Return the positions of the account
- Returns
list of position objects
- Return type
list
-
profile() → dict¶ returns requested information about a user’s account
- Returns
Information requested, either a string or dict
- Return type
Union[dict, str]
-
PyTradier.base module¶
-
class
PyTradier.base.BasePyTradier(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True)¶ Bases:
object-
create_params(params: dict) → dict¶ Create the parameter dictionary for API calls
- Parameters
params (dict) – The locally defined variables
- Returns
dictionary of values that is not None nor self
- Return type
dict
-
process_response(response: requests.models.Response, dict_args: tuple) → Union[dict, list]¶ Process the response for GET, POST, PUT, DELETE methods
- Parameters
response (requests.Response) – raw response object
dict_args (tuple, optional) – keys to parse successful response object, defaults to ()
- Returns
Processed response, either dict or list of dicts depending on endpoint
- Return type
Union[dict, list]
-
PyTradier.data module¶
-
class
PyTradier.data.MarketData(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True)¶ Bases:
PyTradier.base.BasePyTradierAll Methods currently only support string API calls, no datetime, bools, etc
-
historic_quotes(symbol: str, interval: str = 'daily', start: Optional[str] = None, end: Optional[str] = None) → list¶ 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.
- Parameters
symbol (str) – Symbol to query
interval (str, optional) – Interval of time per timesale. One of: daily, weekly, monthly, defaults to “daily”
start (str, optional) – Start date represented as YYYY-MM-DD, defaults to None
end (str, optional) – End date represented as YYYY-MM-DD, defaults to None
- Returns
[description]
- Return type
list
-
option_chain(symbol: str, expiration: Union[str, datetime.datetime], greeks: Union[str, bool] = 'false') → dict¶ 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.
- Parameters
symbol (str) – Underlying symbol of the chain
expiration (Union[str, datetime]) – Expiration for the chain
greeks (Union[str, bool], optional) – Add greeks and volatility information, defaults to “false”
- Returns
Get all quotes in an option chain
- Return type
dict
-
option_expirations(symbol: str, includeAllRoots: Union[str, bool] = '', strikes: Union[str, bool] = '') → list¶ 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.
- Parameters
symbol (str) – Underlying symbol of the chain
includeAllRoots (Union[str, bool], optional) – Send expirations related to all option roots, defaults to ‘’
strikes (Union[str, bool], optional) – Add strike prices to each expiration, defaults to ‘’
- Returns
list of expiration dates as str %Y-%m-%d
- Return type
list
-
option_lookup(underlying: str) → dict¶ Get all options symbols for the given underlying. This will include additional option roots (ex. SPXW, RUTW) if applicable.
- Parameters
underlying (str) – Underlying symbol of the chain
- Returns
dict {“rootSymbol”: underlying, “options”: [list of option symbols]}
- Return type
dict
-
option_strike(symbol: str, expiration: Union[str, datetime.datetime]) → list¶ Get an options strike prices for a specified expiration date.
- Parameters
symbol (str) – Underlying symbol of the chain
expiration (Union[str, datetime]) – Expiration for the chain
- Returns
[description]
- Return type
list
-
quotes(symbols: Union[str, list], greeks: bool = False) → dict¶ 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
- Parameters
symbols (Union[str, list]) – Comma-delimited list of symbols (equity or option)
greeks (bool, optional) – Add greeks and volatility information (option only), defaults to False
- Returns
quotes for requested symbols
- Return type
dict
-
time_and_sales(symbol: str, start: str, end: str, interval: str = '1min') → list¶ 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.`
- Parameters
symbol (str) – A single security symbol.
start (str) – Start date/time for timesales range represented as YYYY-MM-DD HH:MM
end (str) – Start date/time for timesales range represented as YYYY-MM-DD HH:MM
interval (str, optional) – Interval of time per timesale. One of: tick, 1min, 5min, 15min, defaults to “1min”
- Returns
list of dictionaries containing keys of [‘time’, ‘timestamp’, ‘price’, ‘open’, ‘high’, ‘close’, low’, ‘volume’, ‘vwap’]
- Return type
list
-
PyTradier.exceptions module¶
-
exception
PyTradier.exceptions.AuthError¶ Bases:
ExceptionClass for notifying user that some endpoints are for brokerage accounts only, must use live credentials
-
exception
PyTradier.exceptions.MultiLegKeyWordError¶ Bases:
ExceptionThis class is raised when the dictionar passed to multileg method doesn’t have proper keys or values
-
exception
PyTradier.exceptions.OrderError¶ Bases:
ExceptionThis class is raised when an order is submitted that does not have the proper formatting
-
exception
PyTradier.exceptions.RequestError(message, error_code)¶ Bases:
Exception
-
exception
PyTradier.exceptions.RequiredError¶ Bases:
Exception
-
exception
PyTradier.exceptions.WatchListError¶ Bases:
Exception
PyTradier.fundamental module¶
-
class
PyTradier.fundamental.FundamentalData(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True)¶ Bases:
PyTradier.base.BasePyTradierThis API is presently in Beta. It is only available to Tradier Brokerage account holders and should only be used in production applications with caution
-
company_info(**kwargs)¶
-
corporate_actions(**kwargs)¶
-
corporate_calendar(**kwargs)¶
-
dividends(**kwargs)¶
-
financial_reports(**kwargs)¶
-
price_statistics(**kwargs)¶
-
ratios(**kwargs)¶
-
-
PyTradier.fundamental.paperCheck(func)¶
PyTradier.order module¶
This module is trying to anticipate the more complex orders that will be placed in the future. Any algorithmic trading that occurs with this platform won’t have time to preview each trade. The program ought to evaluate its own trades
-
class
PyTradier.order.LimitOrder(symbol: str, side: str, quantity: int, limit_price: float, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
PyTradier.order.baseOrderA limit order is an order to buy or sell a stock at a specific price or better.
-
class
PyTradier.order.MarketOrder(symbol: str, side: str, quantity: int, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
PyTradier.order.baseOrder
-
class
PyTradier.order.SpecOrder(symbol: str, quantity: int, side, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
PyTradier.order.baseOrder
-
class
PyTradier.order.StopLimitOrder(symbol: str, side: str, quantity: int, stop_price: float, limit_price: float, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
PyTradier.order.baseOrderA stop-limit order is an order to buy or sell a stock that combines the features of a stop order and a limit order
-
class
PyTradier.order.StopOrder(symbol: str, side: str, quantity: int, stop_price: float, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
PyTradier.order.baseOrderA stop order, also referred to as a stop-loss order, is an order to buy or sell a stock once the price of the stock reaches a specified price, known as the stop price.
-
class
PyTradier.order.baseOrder(symbol: str, quantity: int, side, duration: str = '', preview: Union[str, bool] = '', tag: str = '')¶ Bases:
object-
accepted_durations= ['day', 'gtc', 'pre', 'post']¶
-
equity_sides= ['buy', 'buy_to_cover', 'sell', 'sell_short']¶
-
make_legs(index: int, exclude: str = '') → dict¶ [summary]
don’t include duration, tags, preview,
- Parameters
index (int) – index of the order dictionary
exclude (str) – key to be excluded, used with combo/multileg orders
- Returns
dictionary reference for the order
- Return type
dict
-
option_sides= ['buy_to_open', 'buy_to_close', 'sell_to_open', 'sell_to_close']¶
-
params(_class: str) → dict¶ create the order parameter details in a form that Tradier API will understand
- Parameters
_class (str) – the class of the order. Ex equity
- Returns
order details dictionary dictionary
- Return type
dict
-
symbol_process(symbol: str)¶
-
PyTradier.rest module¶
-
class
PyTradier.rest.REST(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True, **kwargs)¶ Bases:
PyTradier.base.BasePyTradierPlace equity and complex option trades including advanced orders. kwarg arguments passed to class initialization will define default values including preview, tag, and durations settings
Order requirements are rather bespoke and I have no found a common pattern to unite them -> self validation is difficult, respond and adjust to error message where they arise
-
all_equity(*args) → bool¶ Returns True if all the orders are Equity orders (no order in args has value in key: “option_symbol”)
- Returns
True or False
- Return type
bool
-
all_option(*args) → bool¶ Returns True if all the orders are Option orders (all orders provided have value in key: “option_symbol”)
- Returns
True or False
- Return type
bool
-
check_types(attr: str, *args, shouldBeDifferent: bool = False) → str¶ confirm all durations are the same, or use default, or use one specified by specific order
- Returns
duration of order
- Return type
str
-
combo_order(*orders, **kwargs)¶ Place a combo order. This is a specialized type of order consisting of one equity leg and one option leg. It can optionally include a second option leg, for some strategies. Pass the type, duration, and price as keywords
- Parameters
orders (limitOrder_stopOrder_stopLimitOrder) – Orders to be placed
type (str) – The type of order, one of [‘market’, ‘debit’, ‘credit’, ‘even’]
duration (str) – duration of order, one of [‘day’, ‘gtc’, ‘pre’, ‘post’]
price (float) – the limit price of the order, required for ‘debit’ and ‘credit’ orders
- Returns
API order response
- Return type
dict
-
create_order_legs(*args, exclude='') → dict¶ create the order legs
- Returns
combined dict from each order’s make_legs() method
- Return type
dict
-
equity(order: Union[PyTradier.order.MarketOrder, PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder]) → dict¶ Place an order to trade an equity security.
- Parameters
order (MarketOrder, LimitOrder, StopOrder, StopLimitOrder) – Order to place
- Returns
Order Response dict
- Return type
dict
-
multileg_order(*orders, **kwargs)¶ Place a multileg order with up to 4 legs. This order type allows for simple and complex option strategies.
-
one_cancels_other(order1: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder], order2: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder], **kwargs)¶ Place a one-cancels-other order. This order type is composed of two separate orders sent simultaneously. The property keys of each order are indexed.
type must be different for both legs. If both orders are equities, the symbol must be the same. If both orders are options, the option_symbol must be the same. If sending duration per leg, both orders must have the same duration.
-
one_trigger_other(index_order: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder], triggered_order: Union[PyTradier.order.MarketOrder, PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder])¶ Place a one-triggers-other order. This order type is composed of two separate orders sent simultaneously. The property keys of each order are indexed.
-
one_triggers_one_cancels_other(index_order: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder], triggered_order: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder], cancelled_order: Union[PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder])¶ Place a one-triggers-one-cancels-other order. This order type is composed of three separate orders sent simultaneously. The property keys of each order are indexed. Duration must be specifed on at least one order
If all equity orders, second and third orders must have the same symbol. If all option orders, second and third orders must have the same option_symbol. Second and third orders must always have a different type. If sending duration per leg, second and third orders must have the same duration.
-
option(order: Union[PyTradier.order.MarketOrder, PyTradier.order.LimitOrder, PyTradier.order.StopOrder, PyTradier.order.StopLimitOrder]) → dict¶ Place an order to trade an option security
- Parameters
order (MarketOrder, LimitOrder, StopOrder, StopLimitOrder) – Order to place
- Returns
order response dict
- Return type
dict
-
place_order(params: dict) → dict¶ base order method for all trades
- Parameters
params (dict) – parameters determining the class, types, sides, symbols etc of the other
- Returns
API response
- Return type
dict
-
PyTradier.utils module¶
-
PyTradier.utils.printer(response: requests.models.Response)¶ Helper function for testing endpoints
- Parameters
response (Response) – the response from API call
PyTradier.watchlist module¶
-
class
PyTradier.watchlist.WatchList(token: str = 'TRADIER_SANDBOX_TOKEN', paper: bool = True)¶ Bases:
PyTradier.base.BasePyTradierCreate and update custom watchlists.
-
add(watchlist_id: str, *args) → dict¶ Add symbols to an existing watchlist. If the symbol exists, it will be over-written.
- Parameters
watchlist_id (str) – A watchlist id
- Returns
[description]
- Return type
dict
-
create(name: str, *args) → dict¶ Create a new watchlist. The new watchlist created will use the specified name and optional symbols upon creation.
- Parameters
name (str) – name of the watchlist to create
- Returns
[description]
- Return type
dict
-
delete(watchlist_id: str) → dict¶ Delete a specific watchlist.
- Parameters
watchlist_id (str) – A watchlist id
- Returns
[description]
- Return type
dict
-
parse_args(*args) → str¶ Most of the methods here allow for multiple symbols be inserted/created/destroyed. this helper function allows user to specify iterable in form of *args or list/tuple args can either be str instances, or a single iterable instance :return: comma delimited string :rtype: str
-
remove(watchlist_id: str, symbol: str) → dict¶ Remove a symbol from a specific watchlist.
- Parameters
watchlist_id (str) – A watchlist id
symbol (str) – Symbol to remove from watchlist
- Returns
[description]
- Return type
dict
-
update(watchlist_id: str, watchlist_name: str, *args) → dict¶ Update an existing watchlist. This request will override the existing watchlist information with the parameters sent in the body.
- Parameters
watchlist_id (str) – A watchlist id
watchlist_name (str) – A watchlist name
- Returns
[description]
- Return type
dict
-