qtrade package

Submodules

Core module for Questrade API wrapper.

class qtrade.questrade.Questrade(access_code: str | None = None, token_yaml: str | None = None, save_yaml: bool = True)[source]

Bases: object

Questrade baseclass.

This class holds the methods to get access tokens, refresh access tokens as well as get stock quotes and portfolio overview. An instance of the class needs to be either initialized with an access_code or the path of a access token yaml file.

Parameters:
  • access_code (str, optional) – Access code from Questrade

  • token_yaml (str, optional) – Path of the yaml-file holding the token payload

  • save_yaml (bool, optional) – Boolean to indicate if the token payload will be saved in a yaml-file. Default True.

get_account_activities(account_id: int, start_date: str, end_date: str) List[Dict][source]

Get account activities.

This method will get the account activities for a given account ID in a given time interval.

This method will in general return a list of dictionaries, where each dictionary represents one trade/account activity. Each dictionary is of the form

{'action': 'Buy',
'commission': -5.01,
'currency': 'CAD',
'description': 'description text',
'grossAmount': -1000,
'netAmount': -1005.01,
'price': 10,
'quantity': 100,
'settlementDate': '2018-08-09T00:00:00.000000-04:00',
'symbol': 'XYZ.TO',
'symbolId': 1234567,
'tradeDate': '2018-08-07T00:00:00.000000-04:00',
'transactionDate': '2018-08-09T00:00:00.000000-04:00',
'type': 'Trades'}
Parameters:
  • account_id (int) – Accound ID for which the activities will be returned.

  • start_date (str) – Start date of time period, format YYYY-MM-DD

  • end_date (str) – End date of time period, format YYYY-MM-DD

Returns:

List of dictionaries, where each list entry is a dictionary with basic order & dividend information.

Return type:

list

get_account_balances(account_id: int) Dict[source]

Get account balances.

This method will get the account balance for a given account ID.

Parameters:

account_id (int) – Accound ID for which the activities will be returned.

Returns:

Dictionary holding balance information

Return type:

dict

get_account_executions(account_id: int, start_date: str, end_date: str) List[Dict][source]

Get account executions.

This method will get the account executionss for a given account ID in a given time interval.

This method will in general return a list of dictionaries, where each dictionary represents one account execution. Each dictionary is of the form

 {"symbol": "AAPL",
 "symbolId": 8049,
 "quantity":   10,
 "side":  "Buy",
 "price": 536.87,
 "id": 53817310,
 "orderId": 177106005,
 "orderChainId": 17710600,
 "exchangeExecId": "XS1771060050147",
 "timestam":  2014-03-31T13:38:29.000000-04:00,
 "notes":  "",
 "venue":  "LAMP",
 "totalCost":   5368.7,
 "orderPlacementCommission": 0,
 "commission":    4.95,
 "executionFee": 0,
 "secFee": 0,
 "canadianExecutionFee": 0,
 "parentId": 0,
}
Parameters:
  • account_id (int) – Accound ID for which the executionss will be returned.

  • start_date (str) – Start date of time period, format YYYY-MM-DD

  • end_date (str) – End date of time period, format YYYY-MM-DD

Returns:

List of dictionaries, where each list entry is a dictionary with execution information.

Return type:

list

get_account_id() List[int][source]

Get account ID.

This method gets the accounts ID connected to the token.

Returns:

List of account IDs.

Return type:

list

get_account_positions(account_id: int) List[Dict][source]

Get account positions.

This method will get the positions for the account ID connected to the token.

The returned data is a list where for each position, a dictionary with the following data will be returned:

{'averageEntryPrice': 1000,
'closedPnl': 0,
'closedQuantity': 0,
'currentMarketValue': 3120,
'currentPrice': 1040,
'isRealTime': False,
'isUnderReorg': False,
'openPnl': 120,
'openQuantity': 3,
'symbol': 'XYZ',
'symbolId': 1234567,
'totalCost': 3000}
Parameters:

account_id (int) – Account ID for which the positions will be returned.

Returns:

List of dictionaries, where each list entry is a dictionary with basic position information.

Return type:

list

get_historical_data(ticker: str, start_date: str, end_date: str, interval: str) List[source]

Get historical ticker data.

This method get gets historical data for a time interval and a defined time frequency.

Parameters:
  • ticker (str) – Ticker Symbol

  • start_date (str) – Date in the format YYYY-MM-DD

  • end_date (str) – Date in the format YYYY-MM-DD

  • interval (str) – Time frequency, i.e. OneDay.

Returns:

list of historical data for each interval. The list is ordered by date.

Return type:

list

get_option_chain(ticker: str) Dict[source]

Retrieve an option chain for a particular underlying symbol.

https://www.questrade.com/api/documentation/rest-operations/market-calls/symbols-id-options

This method will return a dictionary of the form

{
    "options": [
    {
      "expiryDate": "2015-01-17T00:00:00.000000-05:00",
      "description": "BANK OF MONTREAL",
      "listingExchange": "MX",
      "optionExerciseType": "American",
      "chainPerRoot": [
      {
        "root": "BMO",
        "chainPerStrikePrice": [
        {
          "strikePrice": 60,
          "callSymbolId": 6101993,
          "putSymbolId": 6102009
        },
        {
          "strikePrice": 62,
          "callSymbolId": 6101994,
          "putSymbolId": 6102010
        },
        {
          "strikePrice": 64,
          "callSymbolId": 6101995,
          "putSymbolId": 6102011
        }],
        "multiplier": 100
      }]
    }]
}
Parameters:

ticker (str) – Ticker symbol

Returns:

Dictionary of option chain information for a particular symbol.

Return type:

dict

get_option_quotes(filters: List[Dict], option_ids: List[int]) Dict[source]

Retrieve a single Level 1 market quote and Greek data for one or more option symbols.

www.questrade.com/api/documentation/rest-operations/market-calls/markets-quotes-options

This method will return a dictionary of the form

{"optionQuotes": [
        {
            "underlying": "MSFT",
            "underlyingId": 27426,
            "symbol": "MSFT20Jan17C70.00",
            "symbolId": 7413503,
            "bidPrice": 4.90,
            "bidSize": 0,
            "askPrice": 4.95,
            "askSize": 0,
            "lastTradePriceTrHrs": 4.93,
            "lastTradePrice": 4.93,
            "lastTradeSize": 0,
            "lastTradeTick": "Equal",
            "lastTradeTime": "2015-08-17T00:00:00.000000-04:00",
            "volume": 0,
            "openPrice": 0,
            "highPricehighPrice": 4.93,
            "lowPrice": 0,
            "volatility": 52.374257,
            "delta": 0.06985,
            "gamma": 0.01038,
            "theta": -0.001406,
            "vega": 0.074554,
            "rho": 0.04153,
            "openInterest": 2292,
            "delay": 0,
            "isHalted": False,
            "VWAP": 0,
        }
    ]
}
Parameters:

filters (List of dictionaries) – List of filters. For example

[
    {
     "optionType": "Call",
     "underlyingId": 27426,
     "expiryDate": "2017-01-20T00:00:00.000000-05:00",
     "minstrikePrice": 70,
     "maxstrikePrice": 80
     }
 ]
option_ids: [int]

List of option IDs

Returns:

Dictionary of option quotes.

Return type:

dict

get_quote(tickers: List[str]) Dict | List[Dict][source]

Get quote.

This function gets information such as a quote for a single ticker or a list of tickers.

Parameters:

tickers ([str]) – List of tickers

Returns:

Dictionary with quotes or list of dictionaries with quotes

Return type:

dict or [dict]

refresh_access_token(from_yaml: bool = False, yaml_path: str = 'access_token.yml') TokenDict[source]

Refresh access token.

This method refreshes the access token. This only works if the overall access has not yet expired. By default it will look for the yaml-file, but it could also look for the internal state

Parameters:
  • from_yaml (bool, optional [False]) – This parameter controls if the refresh token is sourced from a yaml file or if the attribute access_token is used (default). If True, the yaml-file will be updated.

  • yaml_path (str, optional) – Path of the yaml-file that will be updated. Defaults to access_token.yml

Returns:

Dict with the access token data.

Return type:

dict

save_token_to_yaml(yaml_path: str = 'access_token.yml')[source]

Save the token payload as a yaml-file.

Parameters:

yaml_path (str, optional) – Path of the yaml-file. If the file already exists, it will be overwritten. Defaults to access_token.yml

submit_order(acct_id: int, order_dict: Dict[str, int | bool | str]) Dict[source]

Submit order.

This method submits an order to Questrade. Note that currently only partner apps can submit orders to the Questrade API. The order information is provided in a dictionary of the form

{'accountNumber': 1234567,
'symbolId': 3925293,
'quantity': 1,
'icebergQuantity': 1,
'limitPrice': 57.58,
'isAllOrNone': True,
'isAnonymous': False,
'orderType': 'Limit',
'timeInForce': 'GoodTillCanceled',
'action': 'Buy',
'primaryRoute': 'AUTO',
'secondaryRoute': 'AUTO'}
Parameters:
  • acct_id (int) – Account ID for the account to which the order is to be submitted.

  • order_dict (dict) – Dictionary with the necessary order entries.

Returns:

Dictionary with the API response to the order submission.

Return type:

dict

ticker_information(tickers: str | List[str]) Dict | List[Dict][source]

Get ticker information.

This function gets information such as a quote for a single ticker or a list of tickers.

Parameters:

tickers (str or [str]) – List of tickers or a single ticker

Returns:

Dictionary with ticker information or list of dictionaries with ticker information

Return type:

dict or [dict]

Collection of utility functions.

class qtrade.utility.TokenDict

Bases: TypedDict

access_token: str
api_server: str
expires_in: int
refresh_token: str
token_type: str
qtrade.utility.get_access_token_yaml(token_yaml: str) TokenDict[source]

Read in access token yaml.

Parameters:

token_yaml (str) – Path of the token yaml file

Returns:

Dicitonary with the access token parameters

Return type:

dict

qtrade.utility.validate_access_token(access_token: str | None = None, api_server: str | None = None, expires_in: int | None = None, refresh_token: str | None = None, token_type: str | None = None)[source]

Validate access token.

This function validates the access token and ensures that all requiered attributes are provided.

Parameters:
  • access_token (str, optional) – Access token

  • api_server (str, optional) – Api server URL

  • expires_in (int, optional) – Time until token expires

  • refresh_token (str, optional) – Refresh token

  • token_type (str, optional) – Token type

Raises:

Exception – If any of the inputs is None.

Module contents

module init file