Exemplo n.º 1
0
def repeat_monitor(freq, watchlist, orders=False):
    q = Questrade(grant_type=t, refresh_token=t)
    seconds = freq * 60
    print("Snapping data every %s minutes" % (freq))
    while True:
        now = datetime.now().strftime("%H:%M:%S")
        print("Current time is %s" % (now))
        execute(q, seconds, watchlist, orders)
Exemplo n.º 2
0
def opt_monitor(freq, watchlist, rows=10, date_lim=0):
    q = Questrade(grant_type=t, refresh_token=t)
    seconds = freq*60
    print("Snapping vol data every %s minutes" % freq)
    while True:
        now = datetime.now().strftime("%H:%M:%S")
        print("Current time is %s" % (now))
        execute(q, seconds, watchlist, rows, date_lim)
Exemplo n.º 3
0
def main():
    # If using a new token:
    # q = Questrade(refresh_token=questrade_token)
    # otherwise...
    q = Questrade()

    # First, we need to find the ID of the symbol.
    id = q.symbols_search(prefix="SPY")["symbols"][0]["symbolId"]

    # Then we can get some candles.
    startTime = datetime(year=2020, month=10, day=2, hour=12,
                         minute=0).astimezone().isoformat('T')
    endTime = datetime(year=2020, month=10, day=2, hour=12,
                       minute=10).astimezone().isoformat('T')
    candles = q.markets_candles(id,
                                interval='OneMinute',
                                startTime=startTime,
                                endTime=endTime)
    print("Done!")
Exemplo n.º 4
0
 def __questrade_cache_connect(self):
     if len(Configuration.get_apicache()) == 0:
         return None
     try:
         logging.info(
             'MBOX: Authenticate using cached credentials at {}'.format(
                 Configuration.get_cache_ref()))
         q = Questrade(
             logger=logging.debug,
             storage_adaptor=(lambda: Configuration.get_apicache(),
                              lambda s: Configuration.set_apicache(s)))
         Configuration.set_timestamp(q.time['time'])
     except:
         logging.exception('MBOX: Authenticate using credentials FAILED!!!')
         q = None
     return q
Exemplo n.º 5
0
    def __init__(self, refresh_token=None):
        self.refresh_token = refresh_token

        # First, if a refresh token was past, try to use it
        if refresh_token:
            try:
                self.q = Questrade(refresh_token=refresh_token)
                time = self.q.time

                if 'time' in time:
                    self.validated = True
            except Exception as e:
                print('Exception occurred', e)
            finally:
                if self.validated:
                    print("Questrade API validated")
                    self._read_symbols_ids()
                else:
                    print("Failed to initialize API using token: ",
                          refresh_token)

        # otherwise, we'll try to init the API using any potentially stored refresh tokens (by the library)
        else:
            try:
                self.q = Questrade()
                time = self.q.time

                if 'time' in time:
                    self.validated = True
            except:  #if it failed, then try to manually read the refresh token saved in the local json file. "~/.questrade.json"
                _refresh_token = None

                default_file = os.path.join(os.path.expanduser('~'),
                                            self.default_token_filename)

                if os.path.exists(default_file):
                    with open(default_file) as f:
                        token_json = json.load(f)

                        if 'refresh_token' in token_json:
                            _refresh_token = token_json['refresh_token']

                if _refresh_token:
                    self.q = Questrade(refresh_token=_refresh_token)
                    time = self.q.time

                    if 'time' in time:
                        self.validated = True
            finally:
                if self.validated:
                    print("Questrade API validated")
                    self._read_symbols_ids(
                    )  # attempt to read all symbol ids that we have fetched in the past
                else:
                    print("Not validated!")
Exemplo n.º 6
0
def pilot_monitor(pos_freq,
                  pos_watchlist,
                  opt_freq,
                  opt_watchlist,
                  rows=10,
                  date_lim=4,
                  orders=False):
    q = Questrade(grant_type=t, refresh_token=t)
    pos_seconds = pos_freq * 60
    opt_seconds = opt_freq * 60
    print(
        "Snapping positions data every %s minutes and options data every %s minutes"
        % (pos_freq, opt_freq))
    while True:
        now = datetime.now().strftime("%H")
        print("Current time is %s" % (now))
        execute(q, pos_seconds, pos_watchlist, orders)
        print(int(now))
        if int(now) == 15:
            print('Executing Vols')
            v.execute(q, opt_seconds, opt_watchlist, rows, date_lim)
Exemplo n.º 7
0
def _surface_helper(ticker):
    try:
        surface_dif, now_omon, surface_now = vol_comparison(ticker, True,rows=10, date_lim=4)
        pct_chg, cur_price = d.get_bod_pchg(q, ticker)
        print('Vol Surface for %s' % ticker)
        print(surface_now)
        print('Vol Surface Changes for %s' % ticker)
        print(surface_dif)
        print('Price is currently {0}, changing {1} for {2}'.format("{:.2}".format(round(cur_price,2), "{:.2%}".format(pct_chg), ticker)))
        print('Volume monitor for %s' % ticker)
        print(now_omon)
    except Exception as e:
        print(ticker)


def print_surfaces(stock_list):
    with concurrent.futures.ThreadPoolExecutor() as executor:
        f = executor.map(_surface_helper,stock_list)
        for i in f:
            print(i)


if __name__=="__main__":
    t = '32co0bILJKn37TUGv9J2ARfhQv5-m5bt0'
    q = Questrade(grant_type=t, refresh_token=t)
    start = time.perf_counter()
    watchlist = w.opt_list
    print_surfaces(watchlist)
    end = time.perf_counter()
    print(f'Finish in {round(end-start,2)} seconds')
    # opt_monitor(60, w.xlb, date_lim=4)
Exemplo n.º 8
0
######
# Interact with Questrade to get trades and other data

import csv
import sys
import json
import datetime
from rich import print
from questrade_api import Questrade

q = Questrade()


def save_executions(date: str):
    """Save executions to executions.json file
    This is so we can delete unwanted orders until we have proper script to select
    only day trading orders

    Args:
        date (str): date of orders executions
    """
    
    # need to add because questrade accepts ISO format
    start_time = date + 'T00:00:00-05:00'
    end_time = date + 'T23:59:59-05:00'
    response = q.account_executions(id=51779544, startTime=start_time, endTime=end_time)
    orders = response['executions']
    # collect only Executed orders
    # orders: list = [order for order in response['orders'] if order['state'] == 'Executed']
    orders.sort(key=lambda exec: exec['id'])
    
Exemplo n.º 9
0
from questrade_api import Questrade
import numpy as np

token = np.loadtxt('../token.txt')
print(token)
q = Questrade(refresh_token=token)

print(q.markets_quote(34658))
Exemplo n.º 10
0
import os
from questrade_api import Questrade 
from collections import defaultdict

if __name__ == "__main__":

    key = os.environ.get('QUESTRADE_API_KEY')

    if key is None: 
        print('ERROR: Environment variable QUESTRADE_API_KEY not set.')
         
        
    try:
        q = Questrade(refresh_token=key) 
        # After run the first time, can create object without initializing with ref token 
    except Exception as e:
        q = Questrade()
        
    time = q.time['time']

    accounts_raw = q.accounts['accounts']
    accounts = defaultdict(dict)
    for acc in accounts_raw:
        accounts[acc['number']]['type'] = acc['type']
        
    for acc_num in accounts:
        handler = q.account_balances(acc_num)
        accounts[acc_num]['balance_usd'] = handler['perCurrencyBalances'][1]['totalEquity']
        
    if not os.path.isdir('data'):
        os.mkdir('data')
Exemplo n.º 11
0
import preprocess_fun
import urllib
from questrade_api import Questrade
import os

# Ensure working directory path is correct
if os.getcwd()[-3:] == "src":
    os.chdir(os.path.dirname(os.getcwd()))
else:
    pass

# User defined parameters
alphaVan_token = 'U4G0AXZ62E77Z161'
num_days_year = 252
adjusted_daily_save_path = "data/adjusted_daily_closing/"
q = Questrade()

# Initializing Questrade Connection
try:
    current_time = q.time
    print("Questrade API working successfully!")
except urllib.error.HTTPError:
    print(
        "Login key has expired! Need to obtain new refresh token from 'questrade.com'!"
    )
    my_token = str(input("Refresh token from Questrade: "))
    q = Questrade(refresh_token=my_token)
    current_time = q.time
    if not current_time:
        raise Exception("Time should not be empty!")
    else:
Exemplo n.º 12
0
class QuestradeApiHandler:

    q = object()
    refresh_token = None  #if this class gets initialized with a refresh token
    validated = False
    symbols_ids_filename = ".questrade_syms.json"  # We'll save all symbol ids that we ever fetched in this file. This will save us time (and api calls). Found under ~/.questrade_syms.json
    symbols_ids = {
    }  #symbol ids will be saved in this dict for quick access (should be identical to the file above...and both will always be auto updated)
    default_token_filename = ".questrade.json"  # the library we're importing stores refresh token info here

    def __init__(self, refresh_token=None):
        self.refresh_token = refresh_token

        # First, if a refresh token was past, try to use it
        if refresh_token:
            try:
                self.q = Questrade(refresh_token=refresh_token)
                time = self.q.time

                if 'time' in time:
                    self.validated = True
            except Exception as e:
                print('Exception occurred', e)
            finally:
                if self.validated:
                    print("Questrade API validated")
                    self._read_symbols_ids()
                else:
                    print("Failed to initialize API using token: ",
                          refresh_token)

        # otherwise, we'll try to init the API using any potentially stored refresh tokens (by the library)
        else:
            try:
                self.q = Questrade()
                time = self.q.time

                if 'time' in time:
                    self.validated = True
            except:  #if it failed, then try to manually read the refresh token saved in the local json file. "~/.questrade.json"
                _refresh_token = None

                default_file = os.path.join(os.path.expanduser('~'),
                                            self.default_token_filename)

                if os.path.exists(default_file):
                    with open(default_file) as f:
                        token_json = json.load(f)

                        if 'refresh_token' in token_json:
                            _refresh_token = token_json['refresh_token']

                if _refresh_token:
                    self.q = Questrade(refresh_token=_refresh_token)
                    time = self.q.time

                    if 'time' in time:
                        self.validated = True
            finally:
                if self.validated:
                    print("Questrade API validated")
                    self._read_symbols_ids(
                    )  # attempt to read all symbol ids that we have fetched in the past
                else:
                    print("Not validated!")

    def _add_symbol_id(self, symbol, id):
        if symbol not in self.symbols_ids:
            self.symbols_ids[symbol] = {}
            self.symbols_ids[symbol]['sym_id'] = id
            self.symbols_ids[symbol][
                'date_retrieved_EST'] = datetime.datetime.now().strftime(
                    '%Y-%m-%d-%H:%M:%S')
            self.symbols_ids[symbol]['date_retrieved_timestamp'] = round(
                time.time())

            # now save to our file
            self._update_symbols_file()

    def _update_symbols_file(self):
        symbols_ids_file = os.path.join(os.path.expanduser('~'),
                                        self.symbols_ids_filename)

        with open(symbols_ids_file, 'w') as json_file:
            json.dump(self.symbols_ids, json_file)

    def _get_sym_id_for_symbol(self, symbol=None):
        sym_id = None

        if self.is_validated() and symbol:
            symbol = symbol.upper()

            if symbol in self.symbols_ids:
                return self.symbols_ids[symbol]['sym_id']

            else:
                results = self.q.symbols_search(prefix=symbol)

                for result in results['symbols']:
                    if result['symbol'].upper() == symbol:
                        sym_id = result['symbolId']
                        self._add_symbol_id(symbol=symbol, id=sym_id)
                        break

        return sym_id

    def is_validated(self):
        return self.validated

    def _read_symbols_ids(self):
        if self.is_validated():
            symbols_ids_file = os.path.join(os.path.expanduser('~'),
                                            self.symbols_ids_filename)

            if os.path.exists(symbols_ids_file):
                with open(symbols_ids_file) as f:
                    self.symbols_ids = json.load(f)

    def get_intraday_candles(self, symbol=None, timeframe="OneMinute"):
        '''
        Returns Last 2000 candles
        Options are: OneMinute, TwoMinutes, ThreeMinutes, FourMinutes, FiveMinutes, TenMinutes, FifteenMinutes, TwentyMinutes, HalfHour, OneHour, TwoHours, ThreeHours, FourHours
        OneDay, OneWeek, OneMonth, OneYear
        '''
        if self.is_validated() and symbol and timeframe:
            sym_id = self._get_sym_id_for_symbol(symbol=symbol)

            if sym_id > 0:
                return self.q.markets_candles(sym_id, interval=timeframe)

        return None

    def get_previous_close(self, symbol):
        """
        Gets the previous closing price of a symbol (1 api call. 2 calls if symbol was never ever retrieved before)
        """
        prev_close = None

        if self.is_validated() and symbol:
            try:
                sym_id = self._get_sym_id_for_symbol(symbol=symbol)

                if sym_id:
                    res = self.q.symbol(sym_id)

                    if 'symbols' in res:
                        prev_close = res['symbols'][0]['prevDayClosePrice']

            except Exception as e:
                print(f"Couldn't get previous close for symbol {symbol}", e)
                prev_close = None

        return prev_close

    def get_last_price(self, symbol, regular_hours_only=False):
        """
        Gets the last traded price for symbol
        If regular_hours_only is set to True, then only get last trading price using regular market hours
        """
        last_price = None
        price_key = "lastTradePriceTrHrs" if regular_hours_only else "lastTradePrice"

        if self.is_validated() and symbol:
            try:
                sym_id = self._get_sym_id_for_symbol(symbol=symbol)

                if sym_id:
                    res = self.q.markets_quote(sym_id)

                    if 'quotes' in res:
                        last_price = res['quotes'][0][price_key]

            except Exception as e:
                print(f"Couldn't get last price for symbol {symbol}", e)
                last_price = None

        return last_price