2018-03-20 17:26:12 +00:00
|
|
|
"""
|
|
|
|
Robinhood API backend.
|
|
|
|
"""
|
2018-03-21 14:30:43 +00:00
|
|
|
from functools import partial
|
|
|
|
|
2018-03-20 17:26:12 +00:00
|
|
|
from async_generator import asynccontextmanager
|
2018-03-27 20:24:45 +00:00
|
|
|
# TODO: move to urllib3/requests once supported
|
2018-03-21 01:01:55 +00:00
|
|
|
import asks
|
2018-03-20 17:26:12 +00:00
|
|
|
|
|
|
|
from ..log import get_logger
|
2018-05-09 03:52:35 +00:00
|
|
|
from ._util import resproc, BrokerError
|
2018-03-21 14:30:43 +00:00
|
|
|
from ..calc import percent_change
|
2018-03-20 17:26:12 +00:00
|
|
|
|
2018-03-27 20:24:45 +00:00
|
|
|
asks.init('trio')
|
|
|
|
log = get_logger(__name__)
|
2018-03-20 17:26:12 +00:00
|
|
|
_service_ep = 'https://api.robinhood.com'
|
|
|
|
|
|
|
|
|
|
|
|
class _API:
|
|
|
|
"""Robinhood API endpoints exposed as methods and wrapped with an
|
|
|
|
http session.
|
|
|
|
"""
|
|
|
|
def __init__(self, session: asks.Session):
|
|
|
|
self._sess = session
|
|
|
|
|
|
|
|
async def _request(self, path: str, params=None) -> dict:
|
|
|
|
resp = await self._sess.get(path=f'/{path}', params=params)
|
|
|
|
return resproc(resp, log)
|
|
|
|
|
|
|
|
async def quotes(self, symbols: str) -> dict:
|
|
|
|
return await self._request('quotes/', params={'symbols': symbols})
|
|
|
|
|
|
|
|
async def fundamentals(self, symbols: str) -> dict:
|
2018-03-21 01:01:55 +00:00
|
|
|
return await self._request(
|
|
|
|
'fundamentals/', params={'symbols': symbols})
|
2018-03-20 17:26:12 +00:00
|
|
|
|
|
|
|
|
|
|
|
class Client:
|
|
|
|
"""API client suitable for use as a long running broker daemon or
|
|
|
|
single api requests.
|
|
|
|
"""
|
|
|
|
def __init__(self):
|
|
|
|
self._sess = asks.Session()
|
|
|
|
self._sess.base_location = _service_ep
|
|
|
|
self.api = _API(self._sess)
|
|
|
|
|
2018-03-27 20:24:45 +00:00
|
|
|
def _zip_in_order(self, symbols: [str], results_dict: dict):
|
|
|
|
return {quote.get('symbol', sym) if quote else sym: quote
|
|
|
|
for sym, quote in zip(symbols, results_dict)}
|
|
|
|
|
2018-03-20 17:26:12 +00:00
|
|
|
async def quote(self, symbols: [str]):
|
2018-03-27 20:24:45 +00:00
|
|
|
"""Retrieve quotes for a list of ``symbols``.
|
|
|
|
"""
|
2018-05-09 03:52:35 +00:00
|
|
|
try:
|
|
|
|
resp = await self.api.quotes(','.join(symbols))
|
|
|
|
except BrokerError:
|
|
|
|
resp = {'results': [None] * len(symbols)}
|
|
|
|
|
|
|
|
return self._zip_in_order(symbols, resp['results'])
|
2018-03-20 17:26:12 +00:00
|
|
|
|
2018-03-27 20:24:45 +00:00
|
|
|
async def symbol_data(self, symbols: [str]):
|
|
|
|
"""Retrieve symbol data via the ``fundmentals`` endpoint.
|
2018-03-21 14:30:43 +00:00
|
|
|
"""
|
2018-03-27 20:24:45 +00:00
|
|
|
return self._zip_in_order(
|
|
|
|
symbols,
|
|
|
|
(await self.api.fundamentals(','.join(symbols)))['results']
|
|
|
|
)
|
2018-03-21 14:30:43 +00:00
|
|
|
|
2018-03-20 17:26:12 +00:00
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
async def get_client() -> Client:
|
|
|
|
"""Spawn a RH broker client.
|
|
|
|
"""
|
|
|
|
yield Client()
|
2018-03-21 14:30:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def quoter(client: Client, tickers: [str]):
|
|
|
|
"""Quoter context.
|
|
|
|
"""
|
2018-04-18 05:29:33 +00:00
|
|
|
return client.quote
|
2018-03-21 14:30:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
# Robinhood key conversion / column order
|
|
|
|
_rh_keys = {
|
|
|
|
'symbol': 'symbol', # done manually in qtconvert
|
|
|
|
'%': '%',
|
|
|
|
'last_trade_price': ('last', partial(round, ndigits=3)),
|
|
|
|
'last_extended_hours_trade_price': 'last pre-mkt',
|
|
|
|
'ask_price': ('ask', partial(round, ndigits=3)),
|
|
|
|
'bid_price': ('bid', partial(round, ndigits=3)),
|
|
|
|
# 'lastTradeSize': 'size', # not available?
|
|
|
|
'bid_size': 'bsize',
|
|
|
|
'ask_size': 'asize',
|
|
|
|
# 'VWAP': ('VWAP', partial(round, ndigits=3)),
|
|
|
|
# 'mktcap': ('mktcap', humanize),
|
|
|
|
# '$ vol': ('$ vol', humanize),
|
|
|
|
# 'volume': ('vol', humanize),
|
|
|
|
'previous_close': 'close',
|
|
|
|
'adjusted_previous_close': 'adj close',
|
|
|
|
# 'trading_halted': 'halted',
|
|
|
|
|
|
|
|
# example fields
|
|
|
|
# "adjusted_previous_close": "8.1900",
|
|
|
|
# "ask_price": "8.2800",
|
|
|
|
# "ask_size": 1200,
|
|
|
|
# "bid_price": "8.2500",
|
|
|
|
# "bid_size": 1800,
|
|
|
|
# "has_traded": true,
|
|
|
|
# "last_extended_hours_trade_price": null,
|
|
|
|
# "last_trade_price": "8.2350",
|
|
|
|
# "last_trade_price_source": "nls",
|
|
|
|
# "previous_close": "8.1900",
|
|
|
|
# "previous_close_date": "2018-03-20",
|
|
|
|
# "symbol": "CRON",
|
|
|
|
# "trading_halted": false,
|
|
|
|
# "updated_at": "2018-03-21T13:46:05Z"
|
|
|
|
}
|
|
|
|
|
|
|
|
_bidasks = {
|
|
|
|
'last': ['bid', 'ask'],
|
|
|
|
# 'size': ['bsize', 'asize'],
|
|
|
|
# 'VWAP': ['low', 'high'],
|
|
|
|
# 'last pre-mkt': ['close', 'adj close'],
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def format_quote(
|
|
|
|
quote: dict, symbol_data: dict,
|
|
|
|
keymap: dict = _rh_keys,
|
|
|
|
) -> (dict, dict):
|
|
|
|
"""remap a list of quote dicts ``quotes`` using the mapping of old keys
|
|
|
|
-> new keys ``keymap`` returning 2 dicts: one with raw data and the other
|
|
|
|
for display.
|
|
|
|
|
|
|
|
returns 2 dicts: first is the original values mapped by new keys,
|
|
|
|
and the second is the same but with all values converted to a
|
|
|
|
"display-friendly" string format.
|
|
|
|
"""
|
|
|
|
last = quote['last_trade_price']
|
|
|
|
# symbol = quote['symbol']
|
|
|
|
previous = quote['previous_close']
|
|
|
|
change = percent_change(float(previous), float(last))
|
|
|
|
# share_count = symbol_data[symbol].get('outstandingshares', none)
|
|
|
|
# mktcap = share_count * last if share_count else 'na'
|
|
|
|
computed = {
|
|
|
|
'symbol': quote['symbol'],
|
|
|
|
'%': round(change, 3),
|
|
|
|
'ask_price': float(quote['ask_price']),
|
|
|
|
'bid_price': float(quote['bid_price']),
|
|
|
|
'last_trade_price': float(quote['last_trade_price']),
|
|
|
|
# 'mktcap': mktcap,
|
|
|
|
# '$ vol': round(quote['vwap'] * quote['volume'], 3),
|
|
|
|
'close': previous,
|
|
|
|
}
|
|
|
|
new = {}
|
|
|
|
displayable = {}
|
|
|
|
|
|
|
|
for key, new_key in keymap.items():
|
|
|
|
display_value = value = computed.get(key) or quote.get(key)
|
|
|
|
|
|
|
|
# api servers can return `None` vals when markets are closed (weekend)
|
|
|
|
value = 0 if value is None else value
|
|
|
|
|
|
|
|
# convert values to a displayble format using available formatting func
|
|
|
|
if isinstance(new_key, tuple):
|
|
|
|
new_key, func = new_key
|
|
|
|
display_value = func(value)
|
|
|
|
|
|
|
|
new[new_key] = value
|
|
|
|
displayable[new_key] = display_value
|
|
|
|
|
|
|
|
return new, displayable
|