Esempio n. 1
0
async def symbol_search(symbol: str, session: TastyAPISession):
    """
    Performs a symbol search using Tastyworks API.

    This returns a list of symbols that are similar to the symbol passed in
    the parameters. This does not provide any details except the related
    symbols and their descriptions.

    Args:
        symbol (string): A base symbol to search for similar symbols

    Returns:
        list (dict): A list of symbols and descriptions that are closely
                     related to the passed symbol parameter
    """

    url = f'{session.API_url}/symbols/search/{symbol}'

    async with aiohttp.request('GET', url, headers=session.get_request_headers()) as resp:
        if resp.status != 200:
            raise Exception(
                f'Failed to query symbols. Response status: {resp.status}; message: {resp.json()["error"]["message"]}'
            )
        data = await resp.json()

    return data['data']['items']
Esempio n. 2
0
 def __init__(self, session: TastyAPISession):
     if not session.is_active():
         raise Exception('TastyWorks API session not active/valid')
     self.tasty_session = session
     self.cometd_client = None
     self.subs = {}
     asyncio.get_event_loop().run_until_complete(self._setup_connection())
 def __init__(self, session: TastyAPISession, timeout=5000):
     if not session.is_active():
         raise Exception('TastyWorks API session not active/valid')
     self.tasty_session = session
     self.timeout = timeout
     self.connection = None
     self.lock = asyncio.Lock()
     asyncio.get_event_loop().run_until_complete(self._setup_connection())
Esempio n. 4
0
    def __init__(self, API_url=None):
        self.logged_in = False
        self.accounts = None

        token_path = os.path.join(os.path.expanduser('~'), _TOKEN_PATH)
        custom_path = os.path.join(os.path.expanduser('~'), _CUSTOM_CONFIG_PATH)
        default_path = os.path.join(sys.prefix, _DEFAULT_CONFIG_PATH)

        # load config
        self.config = ConfigParser()
        if not os.path.exists(custom_path):
            # copy default config to user home dir
            os.makedirs(os.path.dirname(custom_path), exist_ok=True)
            shutil.copyfile(default_path, custom_path)
            self.config.read(default_path)
        self.config.read(custom_path)

        # try to load token
        if os.path.exists(token_path):
            with open(token_path) as f:
                self.session_token = f.read().strip()

            self.API_url = API_url if API_url else 'https://api.tastyworks.com'

            # make sure token hasn't expired
            response = requests.post(f'{self.API_url}/sessions/validate', headers=self.get_request_headers())
            self.logged_in = (response.status_code == 201)

        if not self.logged_in:
            # either the token expired or doesn't exist
            username, password = self._get_credentials()
            TastyAPISession.__init__(self, username, password)

            # write session token to cache
            os.makedirs(os.path.dirname(token_path), exist_ok=True)
            with open(token_path, 'w') as f:
                f.write(self.session_token)
        else:
            LOGGER.debug('Logged in with cached session token.')
Esempio n. 5
0
    async def get_watchlists(cls,
                             session: TastyAPISession,
                             public: bool = True):
        """Get Watchlists

        Class Factory

        Retrieves a watchlist group (either public or private).

        Notes:
            Not all Watchlist's have group names.

        Args:
            session (TastyAPISession): A TastyAPISession object
            public (bool): Retrive public or private watchlists

        Returns:
            WatchlistGroup: Instance of WatchlistGroup()
        """
        url = f'{session.API_url}/public-watchlists' if public else f'{session.API_url}/watchlists'

        async with aiohttp.request(
                'GET', url, headers=session.get_request_headers()) as resp:
            if resp.status != 200:
                raise Exception(
                    f'Failed retrieving watchlists, Response status: {resp.status}; message: {resp.json()["error"]["message"]}'
                )
            data = await resp.json()

        data = data['data']['items']
        inst = cls()
        for entry in data:
            list_data = entry['watchlist-entries']
            wlist = Watchlist.from_list(list_data)
            wlist.name = entry['name']
            try:
                wlist.group_name = entry['group-name']
            except KeyError:
                pass
            inst.watchlists[wlist.name] = wlist

        return inst