Ticker.py 34 KB

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