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, cyan
  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. class RowDict(dict):
  37. def __iter__(self):
  38. return (e for v in self.values() for e in v)
  39. class DataSource:
  40. source_groups = [
  41. {
  42. 'cc': 'coinpaprika'
  43. }, {
  44. 'fi': 'yahoospot',
  45. 'hi': 'yahoohist',
  46. }]
  47. @classmethod
  48. def get_sources(cls, randomize=False):
  49. g = random.sample(cls.source_groups, k=len(cls.source_groups)) if randomize else cls.source_groups
  50. return {k: v for a in g for k, v in a.items()}
  51. class base:
  52. def fetch_delay(self):
  53. global last_api_host
  54. if not gcfg.testing and last_api_host and last_api_host != self.api_host:
  55. delay = 1 + random.randrange(1, 5000) / 1000
  56. msg_r(f'Waiting {delay:.3f} seconds...')
  57. time.sleep(delay)
  58. msg('')
  59. last_api_host = self.api_host
  60. def get_data_from_network(self):
  61. curl_cmd = list_gen(
  62. ['curl', '--tr-encoding', '--header', 'Accept: application/json', True],
  63. ['--compressed'], # adds 'Accept-Encoding: gzip'
  64. ['--proxy', cfg.proxy, isinstance(cfg.proxy, str)],
  65. ['--silent', not cfg.verbose],
  66. ['--connect-timeout', str(gcfg.http_timeout), gcfg.http_timeout],
  67. [self.api_url])
  68. if gcfg.testing:
  69. Msg(fmt_list(curl_cmd, fmt='bare'))
  70. return
  71. try:
  72. return run(curl_cmd, check=True, stdout=PIPE).stdout.decode()
  73. except CalledProcessError as e:
  74. msg('')
  75. from .Misc import curl_exit_codes
  76. msg(red(curl_exit_codes[e.returncode]))
  77. msg(red('Command line:\n {}'.format(
  78. ' '.join((repr(i) if ' ' in i else i) for i in e.cmd))))
  79. from mmgen.exception import MMGenCalledProcessError
  80. raise MMGenCalledProcessError(
  81. f'Subprocess returned non-zero exit status {e.returncode}')
  82. def get_data(self):
  83. if not os.path.exists(cfg.cachedir):
  84. os.makedirs(cfg.cachedir)
  85. use_cached_data = cfg.cached_data and not gcfg.download
  86. if use_cached_data:
  87. data_type = 'json'
  88. try:
  89. data_in = open(self.json_fn).read()
  90. except FileNotFoundError:
  91. die(1, f'Cannot use cached data, because {self.json_fn_disp} does not exist')
  92. else:
  93. data_type = self.net_data_type
  94. try:
  95. mtime = os.stat(self.json_fn).st_mtime
  96. except FileNotFoundError:
  97. mtime = 0
  98. if (elapsed := int(time.time() - mtime)) >= self.timeout or gcfg.testing:
  99. if gcfg.testing:
  100. msg('')
  101. self.fetch_delay()
  102. msg_r(f'Fetching {self.data_desc} from {self.api_host}...')
  103. if self.has_verbose and cfg.verbose:
  104. msg('')
  105. data_in = self.get_data_from_network()
  106. msg('done')
  107. if gcfg.testing:
  108. return {}
  109. else:
  110. die(1, self.rate_limit_errmsg(elapsed))
  111. match data_type:
  112. case 'json':
  113. try:
  114. data = json.loads(data_in)
  115. except:
  116. self.json_data_error_msg(data_in)
  117. die(2, 'Retrieved data is not valid JSON, exiting')
  118. json_text = data_in
  119. case 'python':
  120. data = data_in
  121. json_text = json.dumps(data_in)
  122. if not data:
  123. if use_cached_data:
  124. die(1,
  125. f'No cached {self.data_desc}! Run command without the --cached-data option, '
  126. 'or use --download to retrieve data from remote host')
  127. else:
  128. die(2, 'Remote host returned no data!')
  129. elif 'error' in data:
  130. die(1, data['error'])
  131. self.data = self.postprocess_data(data)
  132. if use_cached_data:
  133. self.json_text = None
  134. if not cfg.quiet:
  135. msg(f'Using cached data from {self.json_fn_disp}')
  136. else:
  137. self.json_text = json_text
  138. if cache_data(self, no_overwrite=True):
  139. self.json_text = None
  140. return self
  141. def json_data_error_msg(self, json_text):
  142. pass
  143. def postprocess_data(self, data):
  144. return data
  145. @property
  146. def json_fn_disp(self):
  147. return '~/' + os.path.relpath(self.json_fn, start=homedir)
  148. class coinpaprika(base):
  149. desc = 'CoinPaprika'
  150. data_desc = 'cryptocurrency data'
  151. api_host = 'api.coinpaprika.com'
  152. api_proto = 'https'
  153. ratelimit = 240
  154. btc_ratelimit = 10
  155. net_data_type = 'json'
  156. has_verbose = True
  157. dfl_asset_limit = 2000
  158. max_asset_idx = 1_000_000
  159. def __init__(self):
  160. self.asset_limit = int(cfg.asset_limit) if is_int(cfg.asset_limit) else 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=True):
  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 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=True):
  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. class process_data:
  326. def cc():
  327. nonlocal btcusd
  328. for d in data['cc'].data:
  329. if d['id'] == 'btc-bitcoin':
  330. btcusd = Decimal(str(d['quotes']['USD']['price']))
  331. break
  332. else:
  333. raise ValueError('malformed cryptocurrency data')
  334. for k in ('id', 'symbol'):
  335. for d in data['cc'].data:
  336. if wants[k]:
  337. if d[k] in wants[k]:
  338. if d[k] in found[k]:
  339. die(1, dup_sym_errmsg('cc', d[k]))
  340. if not 'price_usd' in d:
  341. d['price_usd'] = Decimal(str(d['quotes']['USD']['price']))
  342. d['price_btc'] = Decimal(str(d['quotes']['USD']['price'])) / btcusd
  343. d['percent_change_24h'] = d['quotes']['USD']['percent_change_24h']
  344. d['percent_change_7d'] = d['quotes']['USD']['percent_change_7d']
  345. d['percent_change_30d'] = d['quotes']['USD']['percent_change_30d']
  346. d['percent_change_1y'] = d['quotes']['USD']['percent_change_1y']
  347. d['market_cap'] = d['quotes']['USD']['market_cap']
  348. d['last_updated'] = int(datetime.datetime.fromisoformat(
  349. d['last_updated']).timestamp())
  350. yield (d['id'], d)
  351. found[k].add(d[k])
  352. wants[k].remove(d[k])
  353. if d[k] in usr_rate_assets_want[k]:
  354. rate_assets[d['symbol']] = d # NB: using symbol instead of ID for key
  355. else:
  356. break
  357. def fi():
  358. get_id = src_cls['fi'].get_id
  359. conv_func = src_cls['fi'].conv_data
  360. for k, v in data['fi'].data.items():
  361. id = get_id(k, v)
  362. if wants['id']:
  363. if id in wants['id']:
  364. if not isinstance(v, dict):
  365. die(2, str(v))
  366. if id in found['id']:
  367. die(1, dup_sym_errmsg('fi', id))
  368. if hist := hist_close.get(k):
  369. spot = v['regularMarketPrice']['raw']
  370. v['pct_chg_1wk'] = (spot / hist.close_1wk - 1) * 100
  371. v['pct_chg_4wks'] = (spot / hist.close_4wks - 1) * 100 # 4 weeks ≈ 1 month
  372. v['pct_chg_1y'] = (spot / hist.close_1y - 1) * 100
  373. else:
  374. v['pct_chg_1wk'] = v['pct_chg_4wks'] = v['pct_chg_1y'] = None
  375. yield (id, conv_func(id, v, btcusd))
  376. found['id'].add(id)
  377. wants['id'].remove(id)
  378. if id in usr_rate_assets_want['id']: # NB: using symbol instead of ID for key:
  379. rate_assets[k] = conv_func(id, v, btcusd)
  380. else:
  381. break
  382. def hi():
  383. ret = namedtuple('historical_closing_prices', ['close_1wk', 'close_4wks', 'close_1y'])
  384. nonlocal hist_close
  385. for k, v in data['hi'].data.items():
  386. hist = tuple(v.values())
  387. hist_close[k] = ret(hist[-2]['close'], hist[-5]['close'], hist[0]['close'])
  388. return ()
  389. rows_want = {
  390. 'id': {r.id for r in cfg.rows if r.id} - {'usd-us-dollar'},
  391. 'symbol': {r.symbol for r in cfg.rows if r.id is None} - {'USD'}}
  392. usr_rate_assets = tuple(u.rate_asset for u in cfg.usr_rows + cfg.usr_columns if u.rate_asset)
  393. usr_rate_assets_want = {
  394. 'id': {a.id for a in usr_rate_assets if a.id},
  395. 'symbol': {a.symbol for a in usr_rate_assets if not a.id}}
  396. usr_assets = cfg.usr_rows + cfg.usr_columns + tuple(c for c in (cfg.query or ()) if c)
  397. usr_wants = {
  398. 'id': (
  399. {a.id for a in usr_assets + usr_rate_assets if a.id} -
  400. {a.id for a in usr_assets if a.rate and a.id} - {'usd-us-dollar'})
  401. ,
  402. 'symbol': (
  403. {a.symbol for a in usr_assets + usr_rate_assets if not a.id} -
  404. {a.symbol for a in usr_assets if a.rate} - {'USD'})}
  405. found = {'id': set(), 'symbol': set()}
  406. rate_assets = {}
  407. wants = {k: rows_want[k] | usr_wants[k] for k in ('id', 'symbol')}
  408. btcusd = Decimal('1') # dummy
  409. hist_close = {}
  410. parse_fail = False
  411. for data_type in ('cc', 'hi', 'fi'): # 'fi' depends on 'cc' and 'hi' so must go last
  412. if data_type in data:
  413. try:
  414. yield from getattr(process_data, data_type)()
  415. except Exception as e:
  416. rmsg(f'Error in source data {data_type!r}: {e}')
  417. parse_fail = True
  418. else:
  419. cache_data(data[data_type])
  420. if parse_fail:
  421. die(2, 'Invalid data encountered, exiting')
  422. if gcfg.download:
  423. return
  424. check_assets_found(usr_wants, found)
  425. for asset in (cfg.usr_rows + cfg.usr_columns):
  426. if asset.rate:
  427. """
  428. User-supplied rate overrides rate from source data.
  429. """
  430. _id = asset.id or f'{asset.symbol}-user-asset-{asset.symbol}'.lower()
  431. ra_rate = rate_assets[asset.rate_asset.symbol]['price_usd'] if asset.rate_asset else 1
  432. yield (_id, {
  433. 'symbol': asset.symbol,
  434. 'id': _id,
  435. 'name': ' '.join(_id.split('-')[1:]),
  436. 'price_usd': ra_rate / asset.rate,
  437. 'price_btc': ra_rate / asset.rate / btcusd,
  438. 'last_updated': None})
  439. yield ('usd-us-dollar', {
  440. 'symbol': 'USD',
  441. 'id': 'usd-us-dollar',
  442. 'name': 'US Dollar',
  443. 'price_usd': Decimal(1),
  444. 'price_btc': Decimal(1) / btcusd,
  445. 'last_updated': None})
  446. def cache_data(data_src, no_overwrite=False):
  447. if data_src.json_text:
  448. if os.path.exists(data_src.json_fn):
  449. if no_overwrite:
  450. return False
  451. os.rename(data_src.json_fn, data_src.json_fn + '.bak')
  452. with open(data_src.json_fn, 'w') as fh:
  453. fh.write(data_src.json_text)
  454. if not cfg.quiet:
  455. msg(f'JSON data cached to {data_src.json_fn_disp}')
  456. return True
  457. def main():
  458. def update_sample_file(usr_cfg_file):
  459. usr_data = files('mmgen_node_tools').joinpath('data', os.path.basename(usr_cfg_file)).read_text()
  460. sample_file = usr_cfg_file + '.sample'
  461. sample_data = open(sample_file).read() if os.path.exists(sample_file) else None
  462. if usr_data != sample_data:
  463. os.makedirs(os.path.dirname(sample_file), exist_ok=True)
  464. msg('{} {}'.format(
  465. ('Updating', 'Creating')[sample_data is None],
  466. sample_file))
  467. open(sample_file, 'w').write(usr_data)
  468. try:
  469. from importlib.resources import files # Python 3.9
  470. except ImportError:
  471. from importlib_resources import files
  472. update_sample_file(cfg_in.cfg_file)
  473. update_sample_file(cfg_in.portfolio_file)
  474. if gcfg.portfolio and not cfg_in.portfolio:
  475. die(1, 'No portfolio configured!\nTo configure a portfolio, edit the file ~/{}'.format(
  476. os.path.relpath(cfg_in.portfolio_file, start=homedir)))
  477. if gcfg.list_ids:
  478. src_ids = ['cc']
  479. elif gcfg.download:
  480. if not gcfg.download in DataSource.get_sources():
  481. die(1, f'{gcfg.download!r}: invalid data source')
  482. src_ids = [gcfg.download]
  483. else:
  484. src_ids = DataSource.get_sources(randomize=True)
  485. src_data = {k: src_cls[k]().get_data() for k in src_ids}
  486. if gcfg.testing:
  487. return
  488. if gcfg.list_ids:
  489. do_pager('\n'.join(e['id'] for e in src_data['cc'].data))
  490. return
  491. global cfg
  492. if cfg.asset_range:
  493. n, m = cfg.asset_range
  494. cfg = cfg._replace(rows = RowDict({
  495. 'asset_list':
  496. tuple(
  497. asset_tuple(e['symbol'], e['id'], source='cc')
  498. for e in src_data['cc'].data[n-1:m]),
  499. 'extra':
  500. tuple(
  501. [asset_tuple('BTC', 'btc-bitcoin', source='cc')]
  502. + [r for r in cfg.rows if r.source == 'fi'])}))
  503. global now
  504. now = 1659465400 if gcfg.test_suite else time.time() # 1659524400 1659445900
  505. data = dict(gen_data(src_data))
  506. if gcfg.download:
  507. return
  508. (do_pager if cfg.pager else Msg_r)(
  509. '\n'.join(getattr(Ticker, cfg.clsname)(data).gen_output()) + '\n')
  510. def make_cfg(gcfg_arg):
  511. query_tuple = namedtuple('query', ['asset', 'to_asset'])
  512. asset_data = namedtuple('asset_data', ['symbol', 'id', 'amount', 'rate', 'rate_asset', 'source'])
  513. def parse_asset_id(s, require_label=True):
  514. return src_cls['fi' if re.match(fi_pat, s) else 'cc'].parse_asset_id(s, require_label)
  515. def parse_percent_cols(arg):
  516. if arg is None or arg.lower() in ('none', ''):
  517. return []
  518. res = arg.lower().split(',')
  519. for s in res:
  520. if s not in percent_cols:
  521. die(1, '{!r}: invalid --percent-cols parameter (valid letters: {})'.format(
  522. arg,
  523. fmt_list(percent_cols)))
  524. return res
  525. def parse_usr_asset_arg(key, use_cf_file=False):
  526. """
  527. asset_id[:rate[:rate_asset]]
  528. """
  529. def parse_parm(s):
  530. ss = s.split(':')
  531. assert len(ss) in (1, 2, 3), f'{s}: malformed argument'
  532. asset_id, rate, rate_asset = (*ss, None, None)[:3]
  533. parsed_id = parse_asset_id(asset_id, require_label=False)
  534. return asset_data(
  535. symbol = parsed_id.symbol,
  536. id = parsed_id.id,
  537. amount = None,
  538. rate = (
  539. None if rate is None else
  540. 1 / Decimal(rate[:-1]) if rate.lower().endswith('r') else
  541. Decimal(rate)),
  542. rate_asset = parse_asset_id(rate_asset, require_label=False) if rate_asset else None,
  543. source = parsed_id.source)
  544. cl_opt = getattr(gcfg, key)
  545. if cl_opt is None or cl_opt.lower() in ('none', ''):
  546. return ()
  547. cf_opt = cfg_in.cfg.get(key,[]) if use_cf_file else []
  548. return tuple(parse_parm(s) for s in (cl_opt.split(',') if cl_opt else cf_opt))
  549. def parse_asset_range(s):
  550. max_idx = DataSource.coinpaprika.max_asset_idx
  551. match s.split('-'):
  552. case [a, b] if is_int(a) and is_int(b):
  553. n, m = (int(a), int(b))
  554. case [a] if is_int(a):
  555. n, m = (1, int(a))
  556. case _:
  557. return None
  558. if n < 1 or m < 1 or n > m:
  559. raise ValueError(f'‘{s}’: invalid asset range specifier')
  560. if m > max_idx:
  561. raise ValueError(f'‘{s}’: end of range must be <= {max_idx}')
  562. return (n, m)
  563. def parse_query_arg(s):
  564. """
  565. asset_id:amount[:to_asset_id[:to_amount]]
  566. """
  567. def parse_query_asset(asset_id, amount):
  568. parsed_id = parse_asset_id(asset_id, require_label=False)
  569. return asset_data(
  570. symbol = parsed_id.symbol,
  571. id = parsed_id.id,
  572. amount = None if amount is None else Decimal(amount),
  573. rate = None,
  574. rate_asset = None,
  575. source = parsed_id.source)
  576. ss = s.split(':')
  577. assert len(ss) in (2, 3, 4), f'{s}: malformed argument'
  578. asset_id, amount, to_asset_id, to_amount = (*ss, None, None)[:4]
  579. return query_tuple(
  580. asset = parse_query_asset(asset_id, amount),
  581. to_asset = parse_query_asset(to_asset_id, to_amount) if to_asset_id else None)
  582. def gen_uniq(obj_list, key, preload=None):
  583. found = set([getattr(obj, key) for obj in preload if hasattr(obj, key)] if preload else ())
  584. for obj in obj_list:
  585. id = getattr(obj, key)
  586. if id not in found:
  587. yield obj
  588. found.add(id)
  589. def get_usr_assets():
  590. return (
  591. usr_rows
  592. + (tuple(asset for asset in query if asset) if query else ())
  593. + usr_columns)
  594. def get_portfolio_assets():
  595. if cfg_in.portfolio and gcfg.portfolio:
  596. ret = (parse_asset_id(e) for e in cfg_in.portfolio)
  597. return tuple(e for e in ret if (not gcfg.btc) or e.symbol == 'BTC')
  598. else:
  599. return ()
  600. def get_portfolio():
  601. return tuple((k, Decimal(v)) for k, v in cfg_in.portfolio.items()
  602. if (not gcfg.btc) or k == 'btc-bitcoin')
  603. def parse_add_precision(arg):
  604. if not arg:
  605. return 0
  606. s = str(arg)
  607. if not (s.isdigit() and s.isascii()):
  608. die(1, f'{s}: invalid parameter for --add-precision (not an integer)')
  609. if int(s) > 30:
  610. die(1, f'{s}: invalid parameter for --add-precision (value >30)')
  611. return int(s)
  612. def create_rows():
  613. rows = RowDict(
  614. {'trade_pair': query} if (query and query.to_asset) else
  615. {'bitcoin': [parse_asset_id('btc-bitcoin')]} if gcfg.btc else
  616. {k: tuple(parse_asset_id(e) for e in v) for k, v in cfg_in.cfg['assets'].items()})
  617. for hdr, data in (
  618. ('user_uniq', get_usr_assets()),
  619. ('portfolio_uniq', get_portfolio_assets())):
  620. if data:
  621. if uniq_data := tuple(gen_uniq(data, 'symbol', preload=rows)):
  622. rows[hdr] = uniq_data
  623. else:
  624. rows[hdr] = ()
  625. return rows
  626. def get_cfg_var(name):
  627. if name in gcfg._uopts:
  628. return getattr(gcfg, name)
  629. else:
  630. return getattr(gcfg, name) or cfg_in.cfg.get(name)
  631. def get_proxy(name):
  632. proxy = getattr(gcfg, name)
  633. return (
  634. '' if proxy == '' else 'none' if (proxy and proxy.lower() == 'none')
  635. else (proxy or cfg_in.cfg.get(name)))
  636. cfg_tuple = namedtuple('global_cfg',[
  637. 'rows',
  638. 'usr_rows',
  639. 'usr_columns',
  640. 'query',
  641. 'asset_range',
  642. 'adjust',
  643. 'clsname',
  644. 'btc_only',
  645. 'add_prec',
  646. 'cachedir',
  647. 'proxy',
  648. 'proxy2',
  649. 'portfolio',
  650. 'percent_cols',
  651. 'asset_limit',
  652. 'cached_data',
  653. 'elapsed',
  654. 'name_labels',
  655. 'pager',
  656. 'thousands_comma',
  657. 'update_time',
  658. 'quiet',
  659. 'verbose'])
  660. global gcfg, cfg_in, src_cls, cfg
  661. gcfg = gcfg_arg
  662. src_cls = {k: getattr(DataSource, v) for k, v in DataSource.get_sources().items()}
  663. fi_pat = src_cls['fi'].asset_id_pat
  664. cfg_in = get_cfg_in()
  665. if cmd_args := gcfg._args:
  666. if len(cmd_args) > 1:
  667. die(1, 'Only one command-line argument is allowed')
  668. asset_range = parse_asset_range(cmd_args[0])
  669. query = None if asset_range else parse_query_arg(cmd_args[0])
  670. else:
  671. asset_range = None
  672. query = None
  673. usr_rows = parse_usr_asset_arg('add_rows')
  674. usr_columns = parse_usr_asset_arg('add_columns', use_cf_file=True)
  675. proxy = get_proxy('proxy')
  676. proxy = None if proxy == 'none' else proxy
  677. proxy2 = get_proxy('proxy2')
  678. portfolio = (
  679. get_portfolio() if cfg_in.portfolio and get_cfg_var('portfolio') and not query
  680. else None)
  681. if portfolio and asset_range:
  682. die(1, '--portfolio not supported in market cap view')
  683. cfg = cfg_tuple(
  684. rows = create_rows(),
  685. usr_rows = usr_rows,
  686. usr_columns = usr_columns,
  687. query = query,
  688. asset_range = asset_range,
  689. adjust = (lambda x: (100 + x) / 100 if x else 1)(Decimal(gcfg.adjust or 0)),
  690. clsname = 'trading' if query else 'overview',
  691. btc_only = get_cfg_var('btc'),
  692. add_prec = parse_add_precision(get_cfg_var('add_precision')),
  693. cachedir = get_cfg_var('cachedir') or dfl_cachedir,
  694. proxy = proxy,
  695. proxy2 = None if proxy2 == 'none' else '' if proxy2 == '' else (proxy2 or proxy),
  696. portfolio = portfolio,
  697. percent_cols = parse_percent_cols(get_cfg_var('percent_cols')),
  698. asset_limit = get_cfg_var('asset_limit'),
  699. cached_data = get_cfg_var('cached_data'),
  700. elapsed = get_cfg_var('elapsed'),
  701. name_labels = get_cfg_var('name_labels'),
  702. pager = get_cfg_var('pager'),
  703. thousands_comma = get_cfg_var('thousands_comma'),
  704. update_time = get_cfg_var('update_time'),
  705. quiet = get_cfg_var('quiet'),
  706. verbose = get_cfg_var('verbose'))
  707. return (src_cls, cfg_in)
  708. def get_cfg_in():
  709. ret = namedtuple('cfg_in_data', ['cfg', 'portfolio', 'cfg_file', 'portfolio_file'])
  710. cfg_file, portfolio_file = (
  711. [os.path.join(gcfg.data_dir_root, 'node_tools', fn)
  712. for fn in (cfg_fn, portfolio_fn)])
  713. cfg_data, portfolio_data = (
  714. [yaml.safe_load(open(fn).read()) if os.path.exists(fn) else None
  715. for fn in (cfg_file, portfolio_file)])
  716. return ret(
  717. cfg = cfg_data or {
  718. 'assets': {
  719. 'coin': [ 'btc-bitcoin', 'eth-ethereum', 'xmr-monero' ],
  720. # gold futures, silver futures, Brent futures
  721. 'commodity': [ 'gc=f', 'si=f', 'bz=f' ],
  722. # Pound Sterling, Euro, Swiss Franc
  723. 'fiat': [ 'gbpusd=x', 'eurusd=x', 'chfusd=x' ],
  724. # Dow Jones Industrials, Nasdaq 100, S&P 500
  725. 'index': [ '^dji', '^ixic', '^gspc' ]},
  726. 'proxy': 'http://vpn-gw:8118'},
  727. portfolio = portfolio_data,
  728. cfg_file = cfg_file,
  729. portfolio_file = portfolio_file)
  730. class Ticker:
  731. class base:
  732. offer = None
  733. to_asset = None
  734. def __init__(self, data):
  735. self.comma = ',' if cfg.thousands_comma else ''
  736. self.col1_wid = max(len('TOTAL'), (
  737. max(len(self.create_label(d['id'])) for d in data.values()) if cfg.name_labels else
  738. max(len(d['symbol']) for d in data.values())))
  739. self.rows = RowDict(
  740. {k: tuple(row._replace(id=self.get_id(row)) for row in v) for k, v in cfg.rows.items()})
  741. self.col_usd_prices = {k: self.data[k]['price_usd'] for k in self.col_ids}
  742. self.prices = {row.id: self.get_row_prices(row.id) for row in self.rows if row.id in data}
  743. self.prices['usd-us-dollar'] = self.get_row_prices('usd-us-dollar')
  744. def format_last_updated_col(self, cross_assets=()):
  745. if cfg.elapsed:
  746. from mmgen.util2 import format_elapsed_hr
  747. fmt_func = format_elapsed_hr
  748. else:
  749. fmt_func = lambda t, now: time.strftime('%F %X', time.gmtime(t))
  750. d = self.data
  751. max_w = 0
  752. if cross_assets:
  753. last_updated_x = [d[a.id]['last_updated'] for a in cross_assets]
  754. min_t = min((int(n) for n in last_updated_x if isinstance(n, int)), default=None)
  755. else:
  756. min_t = None
  757. for row in self.rows:
  758. try:
  759. t = int(d[row.id]['last_updated'])
  760. except TypeError as e:
  761. d[row.id]['last_updated_fmt'] = gray('--' if 'NoneType' in str(e) else str(e))
  762. except KeyError as e:
  763. msg(str(e))
  764. pass
  765. else:
  766. t_fmt = d[row.id]['last_updated_fmt'] = fmt_func(
  767. (min(t, min_t) if min_t else t),
  768. now = now)
  769. max_w = max(len(t_fmt), max_w)
  770. self.upd_w = max_w
  771. def init_prec(self):
  772. exp = [(a.id, self.prices[a.id]['usd-us-dollar'].adjusted()) for a in self.usr_col_assets]
  773. self.uprec = {k: max(0, v+4) + cfg.add_prec for k, v in exp}
  774. self.uwid = {k: 12 + max(0, abs(v)-6) + cfg.add_prec for k, v in exp}
  775. def get_id(self, asset):
  776. if asset.id:
  777. return asset.id
  778. else:
  779. m = asset.symbol
  780. for d in self.data.values():
  781. if m == d['symbol']:
  782. return d['id']
  783. def create_label(self, id):
  784. return self.data[id]['name'].upper()
  785. def gen_output(self):
  786. yield 'Current time: {}'.format(cyan(time.strftime('%F %X', time.gmtime(now)) + ' UTC'))
  787. for asset in self.usr_col_assets:
  788. if asset.symbol != 'USD':
  789. usdprice = self.data[asset.id]['price_usd']
  790. yield '{} ({}) = {:{}.{}f} USD'.format(
  791. asset.symbol,
  792. self.create_label(asset.id),
  793. usdprice,
  794. self.comma,
  795. max(2, 4-usdprice.adjusted()))
  796. if hasattr(self, 'subhdr'):
  797. yield self.subhdr
  798. if self.show_adj:
  799. yield (
  800. ('Offered price differs from spot' if self.offer else 'Adjusting prices')
  801. + ' by '
  802. + yellow('{:+.2f}%'.format((self.adjust-1) * 100)))
  803. yield ''
  804. if cfg.portfolio:
  805. yield blue('PRICES')
  806. if self.table_hdr:
  807. yield self.table_hdr
  808. if cfg.asset_range:
  809. yield '-' * self.hl_wid
  810. for n, row in enumerate(self.rows['asset_list'], cfg.asset_range[0]):
  811. try:
  812. yield self.fmt_row(self.data[row.id], idx=n)
  813. except KeyError:
  814. yield gray(f'(no data for {row.id})')
  815. else:
  816. for rows in self.rows.values():
  817. if rows:
  818. yield '-' * self.hl_wid
  819. for row in rows:
  820. try:
  821. yield self.fmt_row(self.data[row.id])
  822. except KeyError:
  823. yield gray(f'(no data for {row.id})')
  824. yield '-' * self.hl_wid
  825. if cfg.portfolio:
  826. self.fs_num = self.fs_num2
  827. self.fs_str = self.fs_str2
  828. yield ''
  829. yield blue('PORTFOLIO')
  830. yield self.table_hdr
  831. yield '-' * self.hl_wid
  832. for sym, amt in cfg.portfolio:
  833. try:
  834. yield self.fmt_row(self.data[sym], amt=amt)
  835. except KeyError:
  836. yield gray(f'(no data for {sym})')
  837. yield '-' * self.hl_wid
  838. if not cfg.btc_only:
  839. yield self.fs_num.format(
  840. lbl = 'TOTAL', pc3='', pc4='', pc1='', pc2='', upd='', amt='',
  841. **{k.replace('-', '_'): v for k, v in self.prices['total'].items()})
  842. class overview(base):
  843. def __init__(self, data):
  844. self.data = data
  845. self.adjust = cfg.adjust
  846. self.show_adj = self.adjust != 1
  847. self.usr_col_assets = [asset._replace(id=self.get_id(asset)) for asset in cfg.usr_columns]
  848. self.col_ids = ('usd-us-dollar', 'btc-bitcoin') + tuple(a.id for a in self.usr_col_assets)
  849. super().__init__(data)
  850. self.format_last_updated_col()
  851. if cfg.portfolio:
  852. pf_dict = dict(cfg.portfolio)
  853. self.prices['total'] = {col_id: sum(self.prices[row.id][col_id] * pf_dict[row.id]
  854. for row in self.rows
  855. if row.id in pf_dict 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 ''))