Ticker.py 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2022 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet https://github.com/mmgen/mmgen-node-tools
  9. # https://gitlab.com/mmgen/mmgen-wallet https://gitlab.com/mmgen/mmgen-node-tools
  10. """
  11. mmgen_node_tools.Ticker: Display price information for cryptocurrency and other assets
  12. """
  13. # v3.2.dev4: switch to new coinpaprika ‘tickers’ API call (supports ‘limit’ parameter, more historical data)
  14. # Old ‘ticker’ API (/v1/ticker): data['BTC']['price_usd']
  15. # New ‘tickers’ API (/v1/tickers): data['BTC']['quotes']['USD']['price']
  16. # Possible alternatives:
  17. # - https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,LTC&tsyms=USD,EUR
  18. import sys, os, re, time, datetime, json, yaml, random
  19. from subprocess import run, PIPE, CalledProcessError
  20. from decimal import Decimal
  21. from collections import namedtuple
  22. from mmgen.color import red, yellow, green, blue, orange, gray
  23. from mmgen.util import msg, msg_r, Msg, Msg_r, die, fmt, fmt_list, fmt_dict, list_gen, suf
  24. from mmgen.ui import do_pager
  25. homedir = os.getenv('HOME')
  26. dfl_cachedir = os.path.join(homedir, '.cache', 'mmgen-node-tools')
  27. cfg_fn = 'ticker-cfg.yaml'
  28. portfolio_fn = 'ticker-portfolio.yaml'
  29. asset_tuple = namedtuple('asset_tuple', ['symbol', 'id', 'source'])
  30. last_api_host = None
  31. percent_cols = {
  32. 'd': 'day',
  33. 'w': 'week',
  34. 'm': 'month',
  35. 'y': 'year',
  36. }
  37. class DataSource:
  38. source_groups = [
  39. {
  40. 'cc': 'coinpaprika'
  41. }, {
  42. 'fi': 'yahoospot',
  43. 'hi': 'yahoohist',
  44. }]
  45. @classmethod
  46. def get_sources(cls, randomize=False):
  47. g = random.sample(cls.source_groups, k=len(cls.source_groups)) if randomize else cls.source_groups
  48. return {k: v for a in g for k, v in a.items()}
  49. class base:
  50. def fetch_delay(self):
  51. global last_api_host
  52. if not gcfg.testing and last_api_host and last_api_host != self.api_host:
  53. delay = 1 + random.randrange(1, 5000) / 1000
  54. msg_r(f'Waiting {delay:.3f} seconds...')
  55. time.sleep(delay)
  56. msg('')
  57. last_api_host = self.api_host
  58. def get_data_from_network(self):
  59. curl_cmd = list_gen(
  60. ['curl', '--tr-encoding', '--header', 'Accept: application/json', True],
  61. ['--compressed'], # adds 'Accept-Encoding: gzip'
  62. ['--proxy', cfg.proxy, isinstance(cfg.proxy, str)],
  63. ['--silent', not cfg.verbose],
  64. ['--connect-timeout', str(gcfg.http_timeout), gcfg.http_timeout],
  65. [self.api_url])
  66. if gcfg.testing:
  67. Msg(fmt_list(curl_cmd, fmt='bare'))
  68. return
  69. try:
  70. return run(curl_cmd, check=True, stdout=PIPE).stdout.decode()
  71. except CalledProcessError as e:
  72. msg('')
  73. from .Misc import curl_exit_codes
  74. msg(red(curl_exit_codes[e.returncode]))
  75. msg(red('Command line:\n {}'.format(
  76. ' '.join((repr(i) if ' ' in i else i) for i in e.cmd))))
  77. from mmgen.exception import MMGenCalledProcessError
  78. raise MMGenCalledProcessError(
  79. f'Subprocess returned non-zero exit status {e.returncode}')
  80. def get_data(self):
  81. if not os.path.exists(cfg.cachedir):
  82. os.makedirs(cfg.cachedir)
  83. use_cached_data = cfg.cached_data and not gcfg.download
  84. if use_cached_data:
  85. data_type = 'json'
  86. try:
  87. data_in = open(self.json_fn).read()
  88. except FileNotFoundError:
  89. die(1, f'Cannot use cached data, because {self.json_fn_disp} does not exist')
  90. else:
  91. data_type = self.net_data_type
  92. try:
  93. mtime = os.stat(self.json_fn).st_mtime
  94. except FileNotFoundError:
  95. mtime = 0
  96. if (elapsed := int(time.time() - mtime)) >= self.timeout or gcfg.testing:
  97. if gcfg.testing:
  98. msg('')
  99. self.fetch_delay()
  100. msg_r(f'Fetching {self.data_desc} from {self.api_host}...')
  101. if self.has_verbose and cfg.verbose:
  102. msg('')
  103. data_in = self.get_data_from_network()
  104. msg('done')
  105. if gcfg.testing:
  106. return {}
  107. else:
  108. die(1, self.rate_limit_errmsg(elapsed))
  109. match data_type:
  110. case 'json':
  111. try:
  112. data = json.loads(data_in)
  113. except:
  114. self.json_data_error_msg(data_in)
  115. die(2, 'Retrieved data is not valid JSON, exiting')
  116. json_text = data_in
  117. case 'python':
  118. data = data_in
  119. json_text = json.dumps(data_in)
  120. if not data:
  121. if use_cached_data:
  122. die(1,
  123. f'No cached {self.data_desc}! Run command without the --cached-data option, '
  124. 'or use --download to retrieve data from remote host')
  125. else:
  126. die(2, 'Remote host returned no data!')
  127. elif 'error' in data:
  128. die(1, data['error'])
  129. if use_cached_data:
  130. if not cfg.quiet:
  131. msg(f'Using cached data from {self.json_fn_disp}')
  132. else:
  133. if os.path.exists(self.json_fn):
  134. os.rename(self.json_fn, self.json_fn + '.bak')
  135. with open(self.json_fn, 'w') as fh:
  136. fh.write(json_text)
  137. if not cfg.quiet:
  138. msg(f'JSON data cached to {self.json_fn_disp}')
  139. if gcfg.download:
  140. sys.exit(0)
  141. return self.postprocess_data(data)
  142. def json_data_error_msg(self, json_text):
  143. pass
  144. def postprocess_data(self, data):
  145. return data
  146. @property
  147. def json_fn_disp(self):
  148. return '~/' + os.path.relpath(self.json_fn, start=homedir)
  149. class coinpaprika(base):
  150. desc = 'CoinPaprika'
  151. data_desc = 'cryptocurrency data'
  152. api_host = 'api.coinpaprika.com'
  153. api_proto = 'https'
  154. ratelimit = 240
  155. btc_ratelimit = 10
  156. net_data_type = 'json'
  157. has_verbose = True
  158. dfl_asset_limit = 2000
  159. def __init__(self):
  160. self.asset_limit = int(cfg.asset_limit or self.dfl_asset_limit)
  161. def rate_limit_errmsg(self, elapsed):
  162. rem = self.timeout - elapsed
  163. return (
  164. f'Rate limit exceeded! Retry in {rem} second{suf(rem)}' +
  165. ('' if cfg.btc_only else ', or use --cached-data or --btc'))
  166. @property
  167. def api_url(self):
  168. return (
  169. f'{self.api_proto}://{self.api_host}/v1/tickers/btc-bitcoin'
  170. if cfg.btc_only else
  171. f'{self.api_proto}://{self.api_host}/v1/tickers?limit={self.asset_limit}'
  172. if self.asset_limit else
  173. f'{self.api_proto}://{self.api_host}/v1/tickers')
  174. @property
  175. def json_fn(self):
  176. return os.path.join(
  177. cfg.cachedir,
  178. 'ticker-btc.json' if cfg.btc_only else 'ticker.json')
  179. @property
  180. def timeout(self):
  181. return 0 if gcfg.test_suite else self.btc_ratelimit if cfg.btc_only else self.ratelimit
  182. def json_data_error_msg(self, json_text):
  183. tor_captcha_msg = f"""
  184. If you’re using Tor, the API request may have failed due to Captcha protection.
  185. A workaround for this issue is to retrieve the JSON data with a browser from
  186. the following URL:
  187. {self.api_url}
  188. and save it to:
  189. ‘{cfg.cachedir}/ticker.json’
  190. Then invoke the program with --cached-data and without --btc
  191. """
  192. msg(json_text[:1024] + '...')
  193. msg(orange(fmt(tor_captcha_msg, strip_char='\t')))
  194. def postprocess_data(self, data):
  195. return [data] if cfg.btc_only else data
  196. @staticmethod
  197. def parse_asset_id(s, require_label):
  198. sym, label = (*s.split('-', 1), None)[:2]
  199. if require_label and not label:
  200. die(1, f'{s!r}: asset label is missing')
  201. return asset_tuple(
  202. symbol = sym.upper(),
  203. id = (s.lower() if label else None),
  204. source = 'cc')
  205. class yahoospot(base):
  206. desc = 'Yahoo Finance'
  207. data_desc = 'spot financial data'
  208. api_host = 'finance.yahoo.com'
  209. ratelimit = 30
  210. net_data_type = 'python'
  211. has_verbose = False
  212. asset_id_pat = r'^\^.*|.*=[xf]$'
  213. json_fn_basename = 'ticker-finance.json'
  214. @staticmethod
  215. def get_id(sym, data):
  216. return sym.lower()
  217. @staticmethod
  218. def conv_data(sym, data, btcusd):
  219. price_usd = Decimal(data['regularMarketPrice']['raw'])
  220. return {
  221. 'id': sym,
  222. 'name': data['shortName'],
  223. 'symbol': sym.upper(),
  224. 'price_usd': price_usd,
  225. 'price_btc': price_usd / btcusd,
  226. 'percent_change_1y': data['pct_chg_1y'],
  227. 'percent_change_30d': data['pct_chg_4wks'],
  228. 'percent_change_7d': data['pct_chg_1wk'],
  229. 'percent_change_24h': data['regularMarketChangePercent']['raw'] * 100,
  230. 'last_updated': data['regularMarketTime']}
  231. def rate_limit_errmsg(self, elapsed):
  232. rem = self.timeout - elapsed
  233. return f'Rate limit exceeded! Retry in {rem} second{suf(rem)}, or use --cached-data'
  234. @property
  235. def json_fn(self):
  236. return os.path.join(cfg.cachedir, self.json_fn_basename)
  237. @property
  238. def timeout(self):
  239. return 0 if gcfg.test_suite else self.ratelimit
  240. @property
  241. def symbols(self):
  242. return [r.symbol for r in cfg.rows if isinstance(r, tuple) and r.source == 'fi']
  243. def get_data_from_network(self):
  244. kwargs = {
  245. 'formatted': True,
  246. 'asynchronous': True,
  247. 'proxies': {'https': cfg.proxy2}}
  248. if gcfg.test_suite:
  249. kwargs.update({'timeout': 1, 'retry': 0})
  250. if gcfg.http_timeout:
  251. kwargs.update({'timeout': gcfg.http_timeout})
  252. if gcfg.testing:
  253. Msg('\nyahooquery.Ticker(\n {},\n {}\n)'.format(
  254. self.symbols,
  255. fmt_dict(kwargs, fmt='kwargs')))
  256. return
  257. from yahooquery import Ticker
  258. return self.process_network_data(Ticker(self.symbols,**kwargs))
  259. def process_network_data(self, ticker):
  260. return ticker.price
  261. @staticmethod
  262. def parse_asset_id(s, require_label):
  263. return asset_tuple(
  264. symbol = s.upper(),
  265. id = s.lower(),
  266. source = 'fi')
  267. class yahoohist(yahoospot):
  268. json_fn_basename = 'ticker-finance-history.json'
  269. data_desc = 'historical financial data'
  270. net_data_type = 'json'
  271. period = '1y'
  272. interval = '1wk'
  273. def process_network_data(self, ticker):
  274. return ticker.history(
  275. period = self.period,
  276. interval = self.interval).to_json(orient='index')
  277. def postprocess_data(self, data):
  278. def gen():
  279. keys = set()
  280. d = {}
  281. for key, val in data.items():
  282. if m := re.match(r"\('(.*?)', datetime\.date\((.*)\)\)$", key):
  283. date = '{}-{:>02}-{:>02}'.format(*m[2].split(', '))
  284. if (sym := m[1]) in keys:
  285. d[date] = val
  286. else:
  287. keys.add(sym)
  288. d = {date: val}
  289. yield (sym, d)
  290. return dict(gen())
  291. def assets_list_gen(cfg_in):
  292. for k, v in cfg_in.cfg['assets'].items():
  293. yield ''
  294. yield k.upper()
  295. for e in v:
  296. out = e.split('-', 1)
  297. yield ' {:5s} {}'.format(out[0], out[1] if len(out) == 2 else '')
  298. def gen_data(data):
  299. """
  300. Filter the raw data and return it as a dict keyed by the IDs of the assets
  301. we want to display.
  302. Add dummy entry for USD and entry for user-specified asset, if any.
  303. Since symbols in source data are not guaranteed to be unique (e.g. XAG), we
  304. must search the data twice: first for unique IDs, then for symbols while
  305. checking for duplicates.
  306. """
  307. def dup_sym_errmsg(data_type, dup_sym):
  308. return (
  309. f'The symbol {dup_sym!r} is shared by the following assets:\n' +
  310. '\n ' + '\n '.join(d['id'] for d in data[data_type].data if d['symbol'] == dup_sym) +
  311. '\n\nPlease specify the asset by one of the full IDs listed above\n' +
  312. f'instead of {dup_sym!r}')
  313. def check_assets_found(wants, found, keys=['symbol', 'id']):
  314. error = False
  315. for k in keys:
  316. missing = wants[k] - found[k]
  317. if missing:
  318. msg(
  319. ('The following IDs were not found in source data:\n{}' if k == 'id' else
  320. 'The following symbols could not be resolved:\n{}').format(
  321. fmt_list(missing, fmt='col', indent=' ')))
  322. error = True
  323. if error:
  324. die(1, 'Missing data, exiting')
  325. rows_want = {
  326. 'id': {r.id for r in cfg.rows if isinstance(r, tuple) and r.id} - {'usd-us-dollar'},
  327. 'symbol': {r.symbol for r in cfg.rows if isinstance(r, tuple) and r.id is None} - {'USD'}}
  328. usr_rate_assets = tuple(u.rate_asset for u in cfg.usr_rows + cfg.usr_columns if u.rate_asset)
  329. usr_rate_assets_want = {
  330. 'id': {a.id for a in usr_rate_assets if a.id},
  331. 'symbol': {a.symbol for a in usr_rate_assets if not a.id}}
  332. usr_assets = cfg.usr_rows + cfg.usr_columns + tuple(c for c in (cfg.query or ()) if c)
  333. usr_wants = {
  334. 'id': (
  335. {a.id for a in usr_assets + usr_rate_assets if a.id} -
  336. {a.id for a in usr_assets if a.rate and a.id} - {'usd-us-dollar'})
  337. ,
  338. 'symbol': (
  339. {a.symbol for a in usr_assets + usr_rate_assets if not a.id} -
  340. {a.symbol for a in usr_assets if a.rate} - {'USD'})}
  341. found = {'id': set(), 'symbol': set()}
  342. rate_assets = {}
  343. wants = {k: rows_want[k] | usr_wants[k] for k in ('id', 'symbol')}
  344. for d in data['cc']:
  345. if d['id'] == 'btc-bitcoin':
  346. btcusd = Decimal(str(d['quotes']['USD']['price']))
  347. break
  348. get_id = src_cls['fi'].get_id
  349. conv_func = src_cls['fi'].conv_data
  350. for k, v in data['fi'].items():
  351. id = get_id(k, v)
  352. if wants['id']:
  353. if id in wants['id']:
  354. if not isinstance(v, dict):
  355. die(2, str(v))
  356. if id in found['id']:
  357. die(1, dup_sym_errmsg('fi', id))
  358. if m := data['hi'].get(k):
  359. spot = v['regularMarketPrice']['raw']
  360. hist = tuple(m.values())
  361. v['pct_chg_1wk'], v['pct_chg_4wks'], v['pct_chg_1y'] = (
  362. (spot / hist[-2]['close'] - 1) * 100,
  363. (spot / hist[-5]['close'] - 1) * 100, # 4 weeks ≈ 1 month
  364. (spot / hist[0]['close'] - 1) * 100)
  365. else:
  366. v['pct_chg_1wk'] = v['pct_chg_4wks'] = v['pct_chg_1y'] = None
  367. yield (id, conv_func(id, v, btcusd))
  368. found['id'].add(id)
  369. wants['id'].remove(id)
  370. if id in usr_rate_assets_want['id']:
  371. rate_assets[k] = conv_func(id, v, btcusd) # NB: using symbol instead of ID for key
  372. else:
  373. break
  374. for k in ('id', 'symbol'):
  375. for d in data['cc']:
  376. if wants[k]:
  377. if d[k] in wants[k]:
  378. if d[k] in found[k]:
  379. die(1, dup_sym_errmsg('cc', d[k]))
  380. if not 'price_usd' in d:
  381. d['price_usd'] = Decimal(str(d['quotes']['USD']['price']))
  382. d['price_btc'] = Decimal(str(d['quotes']['USD']['price'])) / btcusd
  383. d['percent_change_24h'] = d['quotes']['USD']['percent_change_24h']
  384. d['percent_change_7d'] = d['quotes']['USD']['percent_change_7d']
  385. d['percent_change_30d'] = d['quotes']['USD']['percent_change_30d']
  386. d['percent_change_1y'] = d['quotes']['USD']['percent_change_1y']
  387. # .replace('Z','+00:00') -- Python 3.9 backport
  388. d['last_updated'] = int(datetime.datetime.fromisoformat(
  389. d['last_updated'].replace('Z', '+00:00')).timestamp())
  390. yield (d['id'], d)
  391. found[k].add(d[k])
  392. wants[k].remove(d[k])
  393. if d[k] in usr_rate_assets_want[k]:
  394. rate_assets[d['symbol']] = d # NB: using symbol instead of ID for key
  395. else:
  396. break
  397. check_assets_found(usr_wants, found)
  398. for asset in (cfg.usr_rows + cfg.usr_columns):
  399. if asset.rate:
  400. """
  401. User-supplied rate overrides rate from source data.
  402. """
  403. _id = asset.id or f'{asset.symbol}-user-asset-{asset.symbol}'.lower()
  404. ra_rate = rate_assets[asset.rate_asset.symbol]['price_usd'] if asset.rate_asset else 1
  405. yield (_id, {
  406. 'symbol': asset.symbol,
  407. 'id': _id,
  408. 'name': ' '.join(_id.split('-')[1:]),
  409. 'price_usd': ra_rate / asset.rate,
  410. 'price_btc': ra_rate / asset.rate / btcusd,
  411. 'last_updated': None})
  412. yield ('usd-us-dollar', {
  413. 'symbol': 'USD',
  414. 'id': 'usd-us-dollar',
  415. 'name': 'US Dollar',
  416. 'price_usd': Decimal(1),
  417. 'price_btc': Decimal(1) / btcusd,
  418. 'last_updated': None})
  419. def main():
  420. def update_sample_file(usr_cfg_file):
  421. usr_data = files('mmgen_node_tools').joinpath('data', os.path.basename(usr_cfg_file)).read_text()
  422. sample_file = usr_cfg_file + '.sample'
  423. sample_data = open(sample_file).read() if os.path.exists(sample_file) else None
  424. if usr_data != sample_data:
  425. os.makedirs(os.path.dirname(sample_file), exist_ok=True)
  426. msg('{} {}'.format(
  427. ('Updating', 'Creating')[sample_data is None],
  428. sample_file))
  429. open(sample_file, 'w').write(usr_data)
  430. try:
  431. from importlib.resources import files # Python 3.9
  432. except ImportError:
  433. from importlib_resources import files
  434. update_sample_file(cfg_in.cfg_file)
  435. update_sample_file(cfg_in.portfolio_file)
  436. if gcfg.portfolio and not cfg_in.portfolio:
  437. die(1, 'No portfolio configured!\nTo configure a portfolio, edit the file ~/{}'.format(
  438. os.path.relpath(cfg_in.portfolio_file, start=homedir)))
  439. if gcfg.list_ids:
  440. src_ids = ['cc']
  441. elif gcfg.download:
  442. if not gcfg.download in DataSource.get_sources():
  443. die(1, f'{gcfg.download!r}: invalid data source')
  444. src_ids = [gcfg.download]
  445. else:
  446. src_ids = DataSource.get_sources(randomize=True)
  447. src_data = {k: src_cls[k]().get_data() for k in src_ids}
  448. if gcfg.testing:
  449. return
  450. if gcfg.list_ids:
  451. do_pager('\n'.join(e['id'] for e in src_data['cc']))
  452. return
  453. global now
  454. now = 1659465400 if gcfg.test_suite else time.time() # 1659524400 1659445900
  455. data = dict(gen_data(src_data))
  456. (do_pager if cfg.pager else Msg_r)(
  457. '\n'.join(getattr(Ticker, cfg.clsname)(data).gen_output()) + '\n')
  458. def make_cfg(gcfg_arg):
  459. query_tuple = namedtuple('query', ['asset', 'to_asset'])
  460. asset_data = namedtuple('asset_data', ['symbol', 'id', 'amount', 'rate', 'rate_asset', 'source'])
  461. def parse_asset_id(s, require_label=False):
  462. return src_cls['fi' if re.match(fi_pat, s) else 'cc'].parse_asset_id(s, require_label)
  463. def get_rows_from_cfg(add_data=None):
  464. def gen():
  465. for n, (k, v) in enumerate(cfg_in.cfg['assets'].items()):
  466. yield k
  467. if add_data and k in add_data:
  468. v += tuple(add_data[k])
  469. for e in v:
  470. yield parse_asset_id(e, require_label=True)
  471. return tuple(gen())
  472. def parse_percent_cols(arg):
  473. if arg is None:
  474. return []
  475. res = arg.lower().split(',')
  476. for s in res:
  477. if s not in percent_cols:
  478. die(1, '{!r}: invalid --percent-cols parameter (valid letters: {})'.format(
  479. arg,
  480. fmt_list(percent_cols)))
  481. return res
  482. def parse_usr_asset_arg(key, use_cf_file=False):
  483. """
  484. asset_id[:rate[:rate_asset]]
  485. """
  486. def parse_parm(s):
  487. ss = s.split(':')
  488. assert len(ss) in (1, 2, 3), f'{s}: malformed argument'
  489. asset_id, rate, rate_asset = (*ss, None, None)[:3]
  490. parsed_id = parse_asset_id(asset_id)
  491. return asset_data(
  492. symbol = parsed_id.symbol,
  493. id = parsed_id.id,
  494. amount = None,
  495. rate = (
  496. None if rate is None else
  497. 1 / Decimal(rate[:-1]) if rate.lower().endswith('r') else
  498. Decimal(rate)),
  499. rate_asset = parse_asset_id(rate_asset) if rate_asset else None,
  500. source = parsed_id.source)
  501. cl_opt = getattr(gcfg, key)
  502. cf_opt = cfg_in.cfg.get(key,[]) if use_cf_file else []
  503. return tuple(parse_parm(s) for s in (cl_opt.split(',') if cl_opt else cf_opt))
  504. def parse_query_arg(s):
  505. """
  506. asset_id:amount[:to_asset_id[:to_amount]]
  507. """
  508. def parse_query_asset(asset_id, amount):
  509. parsed_id = parse_asset_id(asset_id)
  510. return asset_data(
  511. symbol = parsed_id.symbol,
  512. id = parsed_id.id,
  513. amount = None if amount is None else Decimal(amount),
  514. rate = None,
  515. rate_asset = None,
  516. source = parsed_id.source)
  517. ss = s.split(':')
  518. assert len(ss) in (2, 3, 4), f'{s}: malformed argument'
  519. asset_id, amount, to_asset_id, to_amount = (*ss, None, None)[:4]
  520. return query_tuple(
  521. asset = parse_query_asset(asset_id, amount),
  522. to_asset = parse_query_asset(to_asset_id, to_amount) if to_asset_id else None)
  523. def gen_uniq(obj_list, key, preload=None):
  524. found = set([getattr(obj, key) for obj in preload if hasattr(obj, key)] if preload else ())
  525. for obj in obj_list:
  526. id = getattr(obj, key)
  527. if id not in found:
  528. yield obj
  529. found.add(id)
  530. def get_usr_assets():
  531. return (
  532. 'user_added',
  533. usr_rows +
  534. (tuple(asset for asset in query if asset) if query else ()) +
  535. usr_columns)
  536. def get_portfolio_assets(ret=()):
  537. if cfg_in.portfolio and gcfg.portfolio:
  538. ret = (parse_asset_id(e, require_label=True) for e in cfg_in.portfolio)
  539. return ('portfolio', tuple(e for e in ret if (not gcfg.btc) or e.symbol == 'BTC'))
  540. def get_portfolio():
  541. return {k: Decimal(v) for k, v in cfg_in.portfolio.items()
  542. if (not gcfg.btc) or k == 'btc-bitcoin'}
  543. def parse_add_precision(arg):
  544. if not arg:
  545. return 0
  546. s = str(arg)
  547. if not (s.isdigit() and s.isascii()):
  548. die(1, f'{s}: invalid parameter for --add-precision (not an integer)')
  549. if int(s) > 30:
  550. die(1, f'{s}: invalid parameter for --add-precision (value >30)')
  551. return int(s)
  552. def create_rows():
  553. rows = (
  554. ('trade_pair',) + query if (query and query.to_asset) else
  555. ('bitcoin', parse_asset_id('btc-bitcoin')) if gcfg.btc else
  556. get_rows_from_cfg(add_data={'fiat':['usd-us-dollar']} if gcfg.add_columns else None))
  557. for hdr, data in (
  558. (get_usr_assets(),) if query else
  559. (get_usr_assets(), get_portfolio_assets())):
  560. if data:
  561. uniq_data = tuple(gen_uniq(data, 'symbol', preload=rows))
  562. if uniq_data:
  563. rows += (hdr,) + uniq_data
  564. return rows
  565. cfg_tuple = namedtuple('global_cfg',[
  566. 'rows',
  567. 'usr_rows',
  568. 'usr_columns',
  569. 'query',
  570. 'adjust',
  571. 'clsname',
  572. 'btc_only',
  573. 'add_prec',
  574. 'cachedir',
  575. 'proxy',
  576. 'proxy2',
  577. 'portfolio',
  578. 'percent_cols',
  579. 'asset_limit',
  580. 'cached_data',
  581. 'elapsed',
  582. 'name_labels',
  583. 'pager',
  584. 'thousands_comma',
  585. 'update_time',
  586. 'quiet',
  587. 'verbose'])
  588. global gcfg, cfg_in, src_cls, cfg
  589. gcfg = gcfg_arg
  590. src_cls = {k: getattr(DataSource, v) for k, v in DataSource.get_sources().items()}
  591. fi_pat = src_cls['fi'].asset_id_pat
  592. cmd_args = gcfg._args
  593. cfg_in = get_cfg_in()
  594. if gcfg.test_suite: # required for testing with overlay
  595. from . import Ticker as this_mod
  596. this_mod.src_cls = src_cls
  597. this_mod.cfg_in = cfg_in
  598. usr_rows = parse_usr_asset_arg('add_rows')
  599. usr_columns = parse_usr_asset_arg('add_columns', use_cf_file=True)
  600. query = parse_query_arg(cmd_args[0]) if cmd_args else None
  601. def get_proxy(name):
  602. proxy = getattr(gcfg, name)
  603. return (
  604. '' if proxy == '' else 'none' if (proxy and proxy.lower() == 'none')
  605. else (proxy or cfg_in.cfg.get(name)))
  606. proxy = get_proxy('proxy')
  607. proxy = None if proxy == 'none' else proxy
  608. proxy2 = get_proxy('proxy2')
  609. cfg = cfg_tuple(
  610. rows = create_rows(),
  611. usr_rows = usr_rows,
  612. usr_columns = usr_columns,
  613. query = query,
  614. adjust = (lambda x: (100 + x) / 100 if x else 1)(Decimal(gcfg.adjust or 0)),
  615. clsname = 'trading' if query else 'overview',
  616. btc_only = gcfg.btc or cfg_in.cfg.get('btc'),
  617. add_prec = parse_add_precision(gcfg.add_precision or cfg_in.cfg.get('add_precision')),
  618. cachedir = gcfg.cachedir or cfg_in.cfg.get('cachedir') or dfl_cachedir,
  619. proxy = proxy,
  620. proxy2 = None if proxy2 == 'none' else '' if proxy2 == '' else (proxy2 or proxy),
  621. portfolio =
  622. get_portfolio()
  623. if cfg_in.portfolio
  624. and (gcfg.portfolio or cfg_in.cfg.get('portfolio'))
  625. and not query
  626. else None,
  627. percent_cols = parse_percent_cols(gcfg.percent_cols or cfg_in.cfg.get('percent_cols')),
  628. asset_limit = gcfg.asset_limit or cfg_in.cfg.get('asset_limit'),
  629. cached_data = gcfg.cached_data or cfg_in.cfg.get('cached_data'),
  630. elapsed = gcfg.elapsed or cfg_in.cfg.get('elapsed'),
  631. name_labels = gcfg.name_labels or cfg_in.cfg.get('name_labels'),
  632. pager = gcfg.pager or cfg_in.cfg.get('pager'),
  633. thousands_comma = gcfg.thousands_comma or cfg_in.cfg.get('thousands_comma'),
  634. update_time = gcfg.update_time or cfg_in.cfg.get('update_time'),
  635. quiet = gcfg.quiet or cfg_in.cfg.get('quiet'),
  636. verbose = gcfg.verbose or cfg_in.cfg.get('verbose'))
  637. def get_cfg_in():
  638. ret = namedtuple('cfg_in_data', ['cfg', 'portfolio', 'cfg_file', 'portfolio_file'])
  639. cfg_file, portfolio_file = (
  640. [os.path.join(gcfg.data_dir_root, 'node_tools', fn)
  641. for fn in (cfg_fn, portfolio_fn)])
  642. cfg_data, portfolio_data = (
  643. [yaml.safe_load(open(fn).read()) if os.path.exists(fn) else None
  644. for fn in (cfg_file, portfolio_file)])
  645. return ret(
  646. cfg = cfg_data or {
  647. 'assets': {
  648. 'coin': [ 'btc-bitcoin', 'eth-ethereum', 'xmr-monero' ],
  649. # gold futures, silver futures, Brent futures
  650. 'commodity': [ 'gc=f', 'si=f', 'bz=f' ],
  651. # Pound Sterling, Euro, Swiss Franc
  652. 'fiat': [ 'gbpusd=x', 'eurusd=x', 'chfusd=x' ],
  653. # Dow Jones Industrials, Nasdaq 100, S&P 500
  654. 'index': [ '^dji', '^ixic', '^gspc' ]},
  655. 'proxy': 'http://vpn-gw:8118'},
  656. portfolio = portfolio_data,
  657. cfg_file = cfg_file,
  658. portfolio_file = portfolio_file)
  659. class Ticker:
  660. class base:
  661. offer = None
  662. to_asset = None
  663. def __init__(self, data):
  664. self.comma = ',' if cfg.thousands_comma else ''
  665. self.col1_wid = max(len('TOTAL'), (
  666. max(len(self.create_label(d['id'])) for d in data.values()) if cfg.name_labels else
  667. max(len(d['symbol']) for d in data.values()))) + 1
  668. self.rows = [row._replace(id=self.get_id(row)) if isinstance(row, tuple) else row
  669. for row in cfg.rows]
  670. self.col_usd_prices = {k: self.data[k]['price_usd'] for k in self.col_ids}
  671. self.prices = {row.id: self.get_row_prices(row.id)
  672. for row in self.rows if isinstance(row, tuple) and row.id in data}
  673. self.prices['usd-us-dollar'] = self.get_row_prices('usd-us-dollar')
  674. def format_last_update_col(self, cross_assets=()):
  675. if cfg.elapsed:
  676. from mmgen.util2 import format_elapsed_hr
  677. fmt_func = format_elapsed_hr
  678. else:
  679. fmt_func = lambda t, now: time.strftime('%F %X', time.gmtime(t))
  680. d = self.data
  681. max_w = 0
  682. if cross_assets:
  683. last_updated_x = [d[a.id]['last_updated'] for a in cross_assets]
  684. min_t = min((int(n) for n in last_updated_x if isinstance(n, int)), default=None)
  685. else:
  686. min_t = None
  687. for row in self.rows:
  688. if isinstance(row, tuple):
  689. try:
  690. t = int(d[row.id]['last_updated'])
  691. except TypeError as e:
  692. d[row.id]['last_updated_fmt'] = gray('--' if 'NoneType' in str(e) else str(e))
  693. except KeyError as e:
  694. msg(str(e))
  695. pass
  696. else:
  697. t_fmt = d[row.id]['last_updated_fmt'] = fmt_func(
  698. (min(t, min_t) if min_t else t),
  699. now = now)
  700. max_w = max(len(t_fmt), max_w)
  701. self.upd_w = max_w
  702. def init_prec(self):
  703. exp = [(a.id, self.prices[a.id]['usd-us-dollar'].adjusted()) for a in self.usr_col_assets]
  704. self.uprec = {k: max(0, v+4) + cfg.add_prec for k, v in exp}
  705. self.uwid = {k: 12 + max(0, abs(v)-6) + cfg.add_prec for k, v in exp}
  706. def get_id(self, asset):
  707. if asset.id:
  708. return asset.id
  709. else:
  710. for d in self.data.values():
  711. if d['symbol'] == asset.symbol:
  712. return d['id']
  713. def create_label(self, id):
  714. return self.data[id]['name'].upper()
  715. def gen_output(self):
  716. yield 'Current time: {} UTC'.format(time.strftime('%F %X', time.gmtime(now)))
  717. for asset in self.usr_col_assets:
  718. if asset.symbol != 'USD':
  719. usdprice = self.data[asset.id]['price_usd']
  720. yield '{} ({}) = {:{}.{}f} USD'.format(
  721. asset.symbol,
  722. self.create_label(asset.id),
  723. usdprice,
  724. self.comma,
  725. max(2, 4-usdprice.adjusted()))
  726. if hasattr(self, 'subhdr'):
  727. yield self.subhdr
  728. if self.show_adj:
  729. yield (
  730. ('Offered price differs from spot' if self.offer else 'Adjusting prices')
  731. + ' by '
  732. + yellow('{:+.2f}%'.format((self.adjust-1) * 100)))
  733. yield ''
  734. if cfg.portfolio:
  735. yield blue('PRICES')
  736. if self.table_hdr:
  737. yield self.table_hdr
  738. for row in self.rows:
  739. if isinstance(row, str):
  740. yield ('-' * self.hl_wid)
  741. else:
  742. try:
  743. yield self.fmt_row(self.data[row.id])
  744. except KeyError:
  745. yield gray(f'(no data for {row.id})')
  746. yield '-' * self.hl_wid
  747. if cfg.portfolio:
  748. self.fs_num = self.fs_num2
  749. self.fs_str = self.fs_str2
  750. yield ''
  751. yield blue('PORTFOLIO')
  752. yield self.table_hdr
  753. yield '-' * self.hl_wid
  754. for sym, amt in cfg.portfolio.items():
  755. try:
  756. yield self.fmt_row(self.data[sym], amt=amt)
  757. except KeyError:
  758. yield gray(f'(no data for {sym})')
  759. yield '-' * self.hl_wid
  760. if not cfg.btc_only:
  761. yield self.fs_num.format(
  762. lbl = 'TOTAL', pc3='', pc4='', pc1='', pc2='', upd='', amt='',
  763. **{k.replace('-', '_'): v for k, v in self.prices['total'].items()})
  764. class overview(base):
  765. def __init__(self, data):
  766. self.data = data
  767. self.adjust = cfg.adjust
  768. self.show_adj = self.adjust != 1
  769. self.usr_col_assets = [asset._replace(id=self.get_id(asset)) for asset in cfg.usr_columns]
  770. self.col_ids = ('usd-us-dollar',) + tuple(a.id for a in self.usr_col_assets) + ('btc-bitcoin',)
  771. super().__init__(data)
  772. self.format_last_update_col()
  773. if cfg.portfolio:
  774. self.prices['total'] = {col_id: sum(self.prices[row.id][col_id] * cfg.portfolio[row.id]
  775. for row in self.rows
  776. if isinstance(row, tuple) and row.id in cfg.portfolio and row.id in data)
  777. for col_id in self.col_ids}
  778. self.init_prec()
  779. self.init_fs()
  780. def get_row_prices(self, id):
  781. if id in self.data:
  782. d = self.data[id]
  783. return {k: (
  784. d['price_btc'] if k == 'btc-bitcoin' else
  785. d['price_usd'] / self.col_usd_prices[k]
  786. ) * self.adjust for k in self.col_ids}
  787. def fmt_row(self, d, amt=None, amt_fmt=None):
  788. def fmt_pct(n):
  789. return gray(' --') if n is None else (red, green)[n>=0](f'{n:+7.2f}')
  790. p = self.prices[d['id']]
  791. if amt is not None:
  792. amt_fmt = f'{amt:{19+cfg.add_prec}{self.comma}.{8+cfg.add_prec}f}'
  793. if '.' in amt_fmt:
  794. amt_fmt = amt_fmt.rstrip('0').rstrip('.')
  795. return self.fs_num.format(
  796. lbl = self.create_label(d['id']) if cfg.name_labels else d['symbol'],
  797. pc1 = fmt_pct(d.get('percent_change_7d')),
  798. pc2 = fmt_pct(d.get('percent_change_24h')),
  799. pc3 = fmt_pct(d.get('percent_change_1y')),
  800. pc4 = fmt_pct(d.get('percent_change_30d')),
  801. upd = d.get('last_updated_fmt'),
  802. amt = amt_fmt,
  803. **{k.replace('-', '_'): v * (1 if amt is None else amt) for k, v in p.items()})
  804. def init_fs(self):
  805. col_prec = {'usd-us-dollar': 2+cfg.add_prec, 'btc-bitcoin': 8+cfg.add_prec} | self.uprec
  806. max_row = max(
  807. ((k, v['btc-bitcoin']) for k, v in self.prices.items()),
  808. key = lambda a: a[1])
  809. widths = {k: len('{:{}.{}f}'.format(self.prices[max_row[0]][k], self.comma, col_prec[k]))
  810. for k in self.col_ids}
  811. fd = namedtuple('format_str_data', ['fs_str', 'fs_num', 'wid'])
  812. col_fs_data = {
  813. 'label': fd(f'{{lbl:{self.col1_wid}}}', f'{{lbl:{self.col1_wid}}}', self.col1_wid),
  814. 'pct1y': fd(' {pc3:7}', ' {pc3:7}', 8),
  815. 'pct1m': fd(' {pc4:7}', ' {pc4:7}', 8),
  816. 'pct1w': fd(' {pc1:7}', ' {pc1:7}', 8),
  817. 'pct1d': fd(' {pc2:7}', ' {pc2:7}', 8),
  818. 'update_time': fd(' {upd}', ' {upd}',
  819. max((19 if cfg.portfolio else 0), self.upd_w) + 2),
  820. 'amt': fd(' {amt}', ' {amt}', 21)
  821. } | {k: fd(
  822. ' {{{}:>{}}}'.format(k.replace('-', '_'), widths[k]),
  823. ' {{{}:{}{}.{}f}}'.format(k.replace('-', '_'), widths[k], self.comma, col_prec[k]),
  824. widths[k] + 2
  825. ) for k in self.col_ids}
  826. cols = (
  827. ['label', 'usd-us-dollar'] +
  828. [asset.id for asset in self.usr_col_assets] +
  829. [a for a, b in (
  830. ('btc-bitcoin', not cfg.btc_only),
  831. ('pct1y', 'y' in cfg.percent_cols),
  832. ('pct1m', 'm' in cfg.percent_cols),
  833. ('pct1w', 'w' in cfg.percent_cols),
  834. ('pct1d', 'd' in cfg.percent_cols),
  835. ('update_time', cfg.update_time))
  836. if b])
  837. cols2 = list(cols)
  838. if cfg.update_time:
  839. cols2.pop()
  840. cols2.append('amt')
  841. self.fs_str = ''.join(col_fs_data[c].fs_str for c in cols)
  842. self.fs_num = ''.join(col_fs_data[c].fs_num for c in cols)
  843. self.hl_wid = sum(col_fs_data[c].wid for c in cols)
  844. self.fs_str2 = ''.join(col_fs_data[c].fs_str for c in cols2)
  845. self.fs_num2 = ''.join(col_fs_data[c].fs_num for c in cols2)
  846. self.hl_wid2 = sum(col_fs_data[c].wid for c in cols2)
  847. @property
  848. def table_hdr(self):
  849. return self.fs_str.format(
  850. lbl = '',
  851. pc1 = ' CHG_7d',
  852. pc2 = 'CHG_24h',
  853. pc3 = 'CHG_1y',
  854. pc4 = 'CHG_30d',
  855. upd = 'UPDATED',
  856. amt = ' AMOUNT',
  857. usd_us_dollar = 'USD',
  858. btc_bitcoin = ' BTC',
  859. **{a.id.replace('-', '_'): a.symbol for a in self.usr_col_assets})
  860. class trading(base):
  861. def __init__(self, data):
  862. self.data = data
  863. self.asset = cfg.query.asset._replace(id=self.get_id(cfg.query.asset))
  864. self.to_asset = (
  865. cfg.query.to_asset._replace(id=self.get_id(cfg.query.to_asset))
  866. if cfg.query.to_asset else None)
  867. self.col_ids = [self.asset.id]
  868. self.adjust = cfg.adjust
  869. if self.to_asset:
  870. self.offer = self.to_asset.amount
  871. if self.offer:
  872. real_price = (
  873. self.asset.amount
  874. * data[self.asset.id]['price_usd']
  875. / data[self.to_asset.id]['price_usd'])
  876. if self.adjust != 1:
  877. die(1,
  878. 'the --adjust option may not be combined with TO_AMOUNT '
  879. 'in the trade specifier')
  880. self.adjust = self.offer / real_price
  881. self.hl_ids = [self.asset.id, self.to_asset.id]
  882. else:
  883. self.hl_ids = [self.asset.id]
  884. self.show_adj = self.adjust != 1 or self.offer
  885. super().__init__(data)
  886. self.usr_col_assets = [self.asset] + ([self.to_asset] if self.to_asset else [])
  887. for a in self.usr_col_assets:
  888. self.prices[a.id]['usd-us-dollar'] = data[a.id]['price_usd']
  889. self.format_last_update_col(cross_assets=self.usr_col_assets)
  890. self.init_prec()
  891. self.init_fs()
  892. def get_row_prices(self, id):
  893. if id in self.data:
  894. d = self.data[id]
  895. return {k: self.col_usd_prices[self.asset.id] / d['price_usd'] for k in self.col_ids}
  896. def init_fs(self):
  897. self.max_wid = max(
  898. len('{:{}{}.{}f}'.format(
  899. v[self.asset.id] * self.asset.amount,
  900. 16 + cfg.add_prec,
  901. self.comma,
  902. 8 + cfg.add_prec))
  903. for v in self.prices.values())
  904. self.fs_str = '{lbl:%s} {p_spot}' % self.col1_wid
  905. self.hl_wid = self.col1_wid + self.max_wid + 1
  906. if self.show_adj:
  907. self.fs_str += ' {p_adj}'
  908. self.hl_wid += self.max_wid + 1
  909. if cfg.update_time:
  910. self.fs_str += ' {upd}'
  911. self.hl_wid += self.upd_w + 2
  912. def fmt_row(self, d):
  913. id = d['id']
  914. p = self.prices[id][self.asset.id] * self.asset.amount
  915. p_spot = '{:{}{}.{}f}'.format(p, self.max_wid, self.comma, 8+cfg.add_prec)
  916. p_adj = (
  917. '{:{}{}.{}f}'.format(p*self.adjust, self.max_wid, self.comma, 8+cfg.add_prec)
  918. if self.show_adj else '')
  919. return self.fs_str.format(
  920. lbl = self.create_label(id) if cfg.name_labels else d['symbol'],
  921. p_spot = green(p_spot) if id in self.hl_ids else p_spot,
  922. p_adj = yellow(p_adj) if id in self.hl_ids else p_adj,
  923. upd = d.get('last_updated_fmt'))
  924. @property
  925. def table_hdr(self):
  926. return self.fs_str.format(
  927. lbl = '',
  928. p_spot = '{t:>{w}}'.format(
  929. t = 'SPOT PRICE',
  930. w = self.max_wid),
  931. p_adj = '{t:>{w}}'.format(
  932. t = ('OFFERED' if self.offer else 'ADJUSTED') + ' PRICE',
  933. w = self.max_wid),
  934. upd = 'UPDATED')
  935. @property
  936. def subhdr(self):
  937. return (
  938. '{a}: {b:{c}} {d}'.format(
  939. a = 'Offer' if self.offer else 'Amount',
  940. b = self.asset.amount,
  941. c = self.comma,
  942. d = self.asset.symbol
  943. ) + (
  944. (
  945. ' =>' +
  946. (' {:{}}'.format(self.offer, self.comma) if self.offer else '') +
  947. ' {} ({})'.format(
  948. self.to_asset.symbol,
  949. self.create_label(self.to_asset.id))
  950. ) if self.to_asset else ''))