Ticker.py 37 KB

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