Ticker.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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 https://github.com/mmgen/mmgen-node-tools
  9. # https://gitlab.com/mmgen/mmgen https://gitlab.com/mmgen/mmgen-node-tools
  10. """
  11. mmgen_node_tools.Ticker: Display price information for cryptocurrency and other assets
  12. """
  13. api_host = 'api.coinpaprika.com'
  14. api_url = f'https://{api_host}/v1/ticker'
  15. ratelimit = 240
  16. btc_ratelimit = 10
  17. # We use deprecated coinpaprika ‘ticker’ API for now because it returns ~45% less data.
  18. # Old ‘ticker’ API (/v1/ticker): data['BTC']['price_usd']
  19. # New ‘tickers’ API (/v1/tickers): data['BTC']['quotes']['USD']['price']
  20. # Possible alternatives:
  21. # - https://min-api.cryptocompare.com/data/pricemultifull?fsyms=BTC,LTC&tsyms=USD,EUR
  22. import sys,os,time,json,yaml
  23. from subprocess import run,PIPE,CalledProcessError
  24. from decimal import Decimal
  25. from collections import namedtuple
  26. from mmgen.opts import opt
  27. from mmgen.globalvars import g
  28. from mmgen.color import *
  29. from mmgen.util import die,fmt_list,msg,msg_r,Msg,do_pager,suf,fmt
  30. homedir = os.getenv('HOME')
  31. cachedir = os.path.join(homedir,'.cache','mmgen-node-tools')
  32. cfg_fn = 'ticker-cfg.yaml'
  33. portfolio_fn = 'ticker-portfolio.yaml'
  34. def assets_list_gen(cfg_in):
  35. for k,v in cfg_in.cfg['assets'].items():
  36. yield('')
  37. yield(k.upper())
  38. for e in v:
  39. yield(' {:4s} {}'.format(*e.split('-',1)))
  40. def gen_data(data):
  41. """
  42. Filter the raw data and return it as a dict keyed by the IDs of the assets
  43. we want to display.
  44. Add dummy entry for USD and entry for user-specified asset, if any.
  45. Since symbols in source data are not guaranteed to be unique (e.g. XAG), we
  46. must search the data twice: first for unique IDs, then for symbols while
  47. checking for duplicates.
  48. """
  49. def dup_sym_errmsg(dup_sym):
  50. return (
  51. f'The symbol {dup_sym!r} is shared by the following assets:\n' +
  52. '\n ' + '\n '.join(d['id'] for d in data if d['symbol'] == dup_sym) +
  53. '\n\nPlease specify the asset by one of the full IDs listed above\n' +
  54. f'instead of {dup_sym!r}'
  55. )
  56. def check_assets_found(wants,found,keys=['symbol','id']):
  57. error = False
  58. for k in keys:
  59. missing = wants[k] - found[k]
  60. if missing:
  61. msg(
  62. ('The following IDs were not found in source data:\n{}' if k == 'id' else
  63. 'The following symbols could not be resolved:\n{}').format(
  64. fmt_list(missing,fmt='col',indent=' ')
  65. ))
  66. error = True
  67. if error:
  68. die(1,'Missing data, exiting')
  69. rows_want = {
  70. 'id': {r.id for r in cfg.rows if getattr(r,'id',None)} - {'usd-us-dollar'},
  71. 'symbol': {r.symbol for r in cfg.rows if isinstance(r,tuple) and r.id is None} - {'USD'},
  72. }
  73. usr_rate_assets = tuple(u.rate_asset for u in cfg.usr_rows + cfg.usr_columns if u.rate_asset)
  74. usr_rate_assets_want = {
  75. 'id': {a.id for a in usr_rate_assets if a.id},
  76. 'symbol': {a.symbol for a in usr_rate_assets if not a.id}
  77. }
  78. usr_assets = cfg.usr_rows + cfg.usr_columns + tuple(c for c in (cfg.query or ()) if c)
  79. usr_wants = {
  80. 'id': (
  81. {a.id for a in usr_assets + usr_rate_assets if a.id} -
  82. {a.id for a in usr_assets if a.rate and a.id} - {'usd-us-dollar'} )
  83. ,
  84. 'symbol': (
  85. {a.symbol for a in usr_assets + usr_rate_assets if not a.id} -
  86. {a.symbol for a in usr_assets if a.rate} - {'USD'} ),
  87. }
  88. found = { 'id': set(), 'symbol': set() }
  89. rate_assets = {}
  90. for k in ['id','symbol']:
  91. wants = rows_want[k] | usr_wants[k]
  92. if wants:
  93. for d in data:
  94. if d[k] in wants:
  95. if d[k] in found[k]:
  96. die(1,dup_sym_errmsg(d[k]))
  97. yield (d['id'],d)
  98. found[k].add(d[k])
  99. if d[k] in usr_rate_assets_want[k]:
  100. rate_assets[d['symbol']] = d # NB: using symbol instead of ID
  101. if k == 'id' and len(found[k]) == len(wants):
  102. break
  103. for d in data:
  104. if d['id'] == 'btc-bitcoin':
  105. btcusd = Decimal(d['price_usd'])
  106. break
  107. for asset in (cfg.usr_rows + cfg.usr_columns):
  108. if asset.rate:
  109. """
  110. User-supplied rate overrides rate from source data.
  111. """
  112. _id = asset.id or f'{asset.symbol}-user-asset-{asset.symbol}'.lower()
  113. ra_rate = Decimal(rate_assets[asset.rate_asset.symbol]['price_usd']) if asset.rate_asset else 1
  114. yield ( _id, {
  115. 'symbol': asset.symbol,
  116. 'id': _id,
  117. 'price_usd': str(Decimal(ra_rate/asset.rate)),
  118. 'price_btc': str(Decimal(ra_rate/asset.rate/btcusd)),
  119. 'last_updated': int(now),
  120. })
  121. yield ('usd-us-dollar', {
  122. 'symbol': 'USD',
  123. 'id': 'usd-us-dollar',
  124. 'price_usd': '1.0',
  125. 'price_btc': str(Decimal(1/btcusd)),
  126. 'last_updated': int(now),
  127. })
  128. check_assets_found(usr_wants,found)
  129. def get_src_data(curl_cmd):
  130. tor_captcha_msg = f"""
  131. If you’re using Tor, the API request may have failed due to Captcha protection.
  132. A workaround for this issue is to retrieve the JSON data with a browser from
  133. the following URL:
  134. {api_url}
  135. and save it to:
  136. ‘{cfg.cachedir}/ticker.json’
  137. Then invoke the program with --cached-data and without --btc
  138. """
  139. def rate_limit_errmsg(timeout,elapsed):
  140. return (
  141. f'Rate limit exceeded! Retry in {timeout-elapsed} seconds' +
  142. ('' if cfg.btc_only else ', or use --cached-data or --btc')
  143. )
  144. if not os.path.exists(cachedir):
  145. os.makedirs(cachedir)
  146. if cfg.btc_only:
  147. fn = os.path.join(cfg.cachedir,'ticker-btc.json')
  148. timeout = 5 if g.test_suite else btc_ratelimit
  149. else:
  150. fn = os.path.join(cfg.cachedir,'ticker.json')
  151. timeout = 5 if g.test_suite else ratelimit
  152. fn_rel = os.path.relpath(fn,start=homedir)
  153. if not os.path.exists(fn):
  154. open(fn,'w').write('{}')
  155. if opt.cached_data:
  156. json_text = open(fn).read()
  157. else:
  158. elapsed = int(time.time() - os.stat(fn).st_mtime)
  159. if elapsed >= timeout:
  160. msg_r(f'Fetching data from {api_host}...')
  161. try:
  162. cp = run(curl_cmd,check=True,stdout=PIPE)
  163. except CalledProcessError as e:
  164. msg('')
  165. from .Misc import curl_exit_codes
  166. msg(red(curl_exit_codes[e.returncode]))
  167. msg(red('Command line:\n {}'.format( ' '.join((repr(i) if ' ' in i else i) for i in e.cmd) )))
  168. from mmgen.exception import MMGenCalledProcessError
  169. raise MMGenCalledProcessError(f'Subprocess returned non-zero exit status {e.returncode}')
  170. json_text = cp.stdout.decode()
  171. msg('done')
  172. else:
  173. die(1,rate_limit_errmsg(timeout,elapsed))
  174. try:
  175. data = json.loads(json_text)
  176. except:
  177. msg(json_text[:1024] + '...')
  178. msg(orange(fmt(tor_captcha_msg,strip_char='\t')))
  179. die(2,'Retrieved data is not valid JSON, exiting')
  180. if not data:
  181. if opt.cached_data:
  182. die(1,'No cached data! Run command without --cached-data option to retrieve data from remote host')
  183. else:
  184. die(2,'Remote host returned no data!')
  185. elif 'error' in data:
  186. die(1,data['error'])
  187. if opt.cached_data:
  188. msg(f'Using cached data from ~/{fn_rel}')
  189. else:
  190. open(fn,'w').write(json_text)
  191. msg(f'JSON data cached to ~/{fn_rel}')
  192. return data
  193. def main(cfg_parm,cfg_in_parm):
  194. def update_sample_file(usr_cfg_file):
  195. src_data = files('mmgen_node_tools').joinpath('data',os.path.basename(usr_cfg_file)).read_text()
  196. sample_file = usr_cfg_file + '.sample'
  197. sample_data = open(sample_file).read() if os.path.exists(sample_file) else None
  198. if src_data != sample_data:
  199. os.makedirs(os.path.dirname(sample_file),exist_ok=True)
  200. msg('{} {}'.format(
  201. ('Updating','Creating')[sample_data is None],
  202. sample_file ))
  203. open(sample_file,'w').write(src_data)
  204. def get_curl_cmd():
  205. return ([
  206. 'curl',
  207. '--tr-encoding',
  208. '--compressed', # adds 'Accept-Encoding: gzip'
  209. '--silent',
  210. '--header', 'Accept: application/json',
  211. ] +
  212. (['--proxy', cfg.proxy] if cfg.proxy else []) +
  213. [api_url + ('/btc-bitcoin' if cfg.btc_only else '')]
  214. )
  215. global cfg,cfg_in
  216. cfg = cfg_parm
  217. cfg_in = cfg_in_parm
  218. try:
  219. from importlib.resources import files # Python 3.9
  220. except ImportError:
  221. from importlib_resources import files
  222. update_sample_file(cfg_in.cfg_file)
  223. update_sample_file(cfg_in.portfolio_file)
  224. if opt.portfolio and not cfg_in.portfolio:
  225. die(1,'No portfolio configured!\nTo configure a portfolio, edit the file ~/{}'.format(
  226. os.path.relpath(cfg_in.portfolio_file,start=homedir)))
  227. curl_cmd = get_curl_cmd()
  228. if opt.print_curl:
  229. Msg(curl_cmd + '\n' + ' '.join(curl_cmd))
  230. return
  231. parsed_json = [get_src_data(curl_cmd)] if cfg.btc_only else get_src_data(curl_cmd)
  232. if opt.list_ids:
  233. do_pager('\n'.join(e['id'] for e in parsed_json))
  234. return
  235. global now
  236. now = 1659465400 if g.test_suite else time.time() # 1659524400 1659445900
  237. (do_pager if opt.pager else Msg)(
  238. '\n'.join(getattr(Ticker,cfg.clsname)(dict(gen_data(parsed_json))).gen_output())
  239. )
  240. def make_cfg(cmd_args,cfg_in):
  241. def get_rows_from_cfg(add_data=None):
  242. def gen():
  243. for n,(k,v) in enumerate(cfg_in.cfg['assets'].items()):
  244. yield(k)
  245. if add_data and k in add_data:
  246. v += tuple(add_data[k])
  247. for e in v:
  248. yield parse_asset_id(e,True)
  249. return tuple(gen())
  250. def parse_asset_id(s,require_label=False):
  251. sym,label = (*s.split('-',1),None)[:2]
  252. if require_label and not label:
  253. die(1,f'{s!r}: asset label is missing')
  254. return asset_tuple( sym.upper(), (s.lower() if label else None) )
  255. def parse_usr_asset_arg(s):
  256. """
  257. asset_id[:rate[:rate_asset]]
  258. """
  259. def parse_parm(s):
  260. ss = s.split(':')
  261. assert len(ss) in (1,2,3), f'{s}: malformed argument'
  262. asset_id,rate,rate_asset = (*ss,None,None)[:3]
  263. parsed_id = parse_asset_id(asset_id)
  264. return asset_data(
  265. symbol = parsed_id.symbol,
  266. id = parsed_id.id,
  267. amount = None,
  268. rate = (
  269. None if rate is None else
  270. 1 / Decimal(rate[:-1]) if rate.lower().endswith('r') else
  271. Decimal(rate) ),
  272. rate_asset = parse_asset_id(rate_asset) if rate_asset else None )
  273. return tuple(parse_parm(s2) for s2 in s.split(',')) if s else ()
  274. def parse_query_arg(s):
  275. """
  276. asset_id:amount[:to_asset_id[:to_amount]]
  277. """
  278. def parse_query_asset(asset_id,amount):
  279. parsed_id = parse_asset_id(asset_id)
  280. return asset_data(
  281. symbol = parsed_id.symbol,
  282. id = parsed_id.id,
  283. amount = None if amount is None else Decimal(amount),
  284. rate = None,
  285. rate_asset = None )
  286. ss = s.split(':')
  287. assert len(ss) in (2,3,4), f'{s}: malformed argument'
  288. asset_id,amount,to_asset_id,to_amount = (*ss,None,None)[:4]
  289. return query_tuple(
  290. asset = parse_query_asset(asset_id,amount),
  291. to_asset = parse_query_asset(to_asset_id,to_amount) if to_asset_id else None
  292. )
  293. def gen_uniq(obj_list,key,preload=None):
  294. found = set([getattr(obj,key) for obj in preload if hasattr(obj,key)] if preload else ())
  295. for obj in obj_list:
  296. id = getattr(obj,key)
  297. if id not in found:
  298. yield obj
  299. found.add(id)
  300. def get_usr_assets():
  301. return (
  302. 'user_added',
  303. usr_rows +
  304. (tuple(asset for asset in query if asset) if query else ()) +
  305. usr_columns )
  306. def get_portfolio_assets(ret=()):
  307. if cfg_in.portfolio and opt.portfolio:
  308. ret = (parse_asset_id(e,True) for e in cfg_in.portfolio)
  309. return ( 'portfolio', tuple(e for e in ret if (not opt.btc) or e.symbol == 'BTC') )
  310. def get_portfolio():
  311. return {k:Decimal(v) for k,v in cfg_in.portfolio.items() if (not opt.btc) or k == 'btc-bitcoin'}
  312. def parse_add_precision(s):
  313. if not s:
  314. return 0
  315. if not (s.isdigit() and s.isascii()):
  316. die(1,f'{s}: invalid parameter for --add-precision (not an integer)')
  317. if int(s) > 30:
  318. die(1,f'{s}: invalid parameter for --add-precision (value >30)')
  319. return int(s)
  320. def create_rows():
  321. rows = (
  322. ('trade_pair',) + query if (query and query.to_asset) else
  323. ('bitcoin',parse_asset_id('btc-bitcoin')) if opt.btc else
  324. get_rows_from_cfg( add_data={'fiat':['usd-us-dollar']} if opt.add_columns else None )
  325. )
  326. for hdr,data in (
  327. (get_usr_assets(),) if query else
  328. (get_usr_assets(), get_portfolio_assets())
  329. ):
  330. if data:
  331. uniq_data = tuple(gen_uniq(data,'symbol',preload=rows))
  332. if uniq_data:
  333. rows += (hdr,) + uniq_data
  334. return rows
  335. cfg_tuple = namedtuple('global_cfg',[
  336. 'rows',
  337. 'usr_rows',
  338. 'usr_columns',
  339. 'query',
  340. 'adjust',
  341. 'clsname',
  342. 'btc_only',
  343. 'add_prec',
  344. 'cachedir',
  345. 'proxy',
  346. 'portfolio' ])
  347. query_tuple = namedtuple('query',['asset','to_asset'])
  348. asset_data = namedtuple('asset_data',['symbol','id','amount','rate','rate_asset'])
  349. asset_tuple = namedtuple('asset_tuple',['symbol','id'])
  350. usr_rows = parse_usr_asset_arg(opt.add_rows)
  351. usr_columns = parse_usr_asset_arg(opt.add_columns)
  352. query = parse_query_arg(cmd_args[0]) if cmd_args else None
  353. return cfg_tuple(
  354. rows = create_rows(),
  355. usr_rows = usr_rows,
  356. usr_columns = usr_columns,
  357. query = query,
  358. adjust = ( lambda x: (100 + x) / 100 if x else 1 )( Decimal(opt.adjust or 0) ),
  359. clsname = 'trading' if query else 'overview',
  360. btc_only = opt.btc,
  361. add_prec = parse_add_precision(opt.add_precision),
  362. cachedir = opt.cachedir or cfg_in.cfg.get('cachedir') or cachedir,
  363. proxy = None if opt.proxy == '' else (opt.proxy or cfg_in.cfg.get('proxy')),
  364. portfolio = get_portfolio() if cfg_in.portfolio and opt.portfolio and not query else None
  365. )
  366. def get_cfg_in():
  367. ret = namedtuple('cfg_in_data',['cfg','portfolio','cfg_file','portfolio_file'])
  368. cfg_file,portfolio_file = (
  369. [os.path.join(g.data_dir_root,'node_tools',fn) for fn in (cfg_fn,portfolio_fn)]
  370. )
  371. cfg_data,portfolio_data = (
  372. [yaml.safe_load(open(fn).read()) if os.path.exists(fn) else None for fn in (cfg_file,portfolio_file)]
  373. )
  374. return ret(
  375. cfg = cfg_data or {
  376. 'assets': {
  377. 'coin': [ 'btc-bitcoin', 'eth-ethereum', 'xmr-monero' ],
  378. 'commodity': [ 'xau-gold-spot-token', 'xag-silver-spot-token', 'xbr-brent-crude-oil-spot' ],
  379. 'fiat': [ 'gbp-pound-sterling-token', 'eur-euro-token' ],
  380. 'index': [ 'dj30-dow-jones-30-token', 'spx-sp-500', 'ndx-nasdaq-100-token' ],
  381. },
  382. 'proxy': 'http://vpn-gw:8118'
  383. },
  384. portfolio = portfolio_data,
  385. cfg_file = cfg_file,
  386. portfolio_file = portfolio_file,
  387. )
  388. class Ticker:
  389. class base:
  390. offer = None
  391. to_asset = None
  392. def __init__(self,data):
  393. self.comma = ',' if opt.thousands_comma else ''
  394. self.col1_wid = max(len('TOTAL'),(
  395. max(len(self.create_label(d['id'])) for d in data.values()) if opt.name_labels else
  396. max(len(d['symbol']) for d in data.values())
  397. )) + 1
  398. self.rows = [row._replace(id=self.get_id(row)) if isinstance(row,tuple) else row for row in cfg.rows]
  399. self.col_usd_prices = {k:Decimal(self.data[k]['price_usd']) for k in self.col_ids}
  400. self.prices = {row.id:self.get_row_prices(row.id)
  401. for row in self.rows if isinstance(row,tuple) and row.id in data}
  402. self.prices['usd-us-dollar'] = self.get_row_prices('usd-us-dollar')
  403. def format_last_update_col(self,cross_assets=()):
  404. if opt.elapsed:
  405. from .Util import format_elapsed_hr
  406. fmt_func = format_elapsed_hr
  407. else:
  408. fmt_func = lambda t,now: time.strftime('%F %X',time.gmtime(t)) # ticker API
  409. # t.replace('T',' ').replace('Z','') # tickers API
  410. d = self.data
  411. max_w = 0
  412. min_t = min( (int(d[a.id]['last_updated']) for a in cross_assets), default=None )
  413. for row in self.rows:
  414. if isinstance(row,tuple):
  415. try:
  416. t = int(d[row.id]['last_updated'])
  417. except KeyError:
  418. pass
  419. else:
  420. t_fmt = d[row.id]['last_updated_fmt'] = fmt_func( (min(t,min_t) if min_t else t), now )
  421. max_w = max(len(t_fmt),max_w)
  422. self.upd_w = max_w
  423. def init_prec(self):
  424. exp = [(a.id,Decimal.adjusted(self.prices[a.id]['usd-us-dollar'])) for a in self.usr_col_assets]
  425. self.uprec = { k: max(0,v+4) + cfg.add_prec for k,v in exp }
  426. self.uwid = { k: 12 + max(0, abs(v)-6) + cfg.add_prec for k,v in exp }
  427. def get_id(self,asset):
  428. if asset.id:
  429. return asset.id
  430. else:
  431. for d in self.data.values():
  432. if d['symbol'] == asset.symbol:
  433. return d['id']
  434. def create_label(self,id):
  435. return ' '.join(id.split('-')[1:]).upper()
  436. def gen_output(self):
  437. yield 'Current time: {} UTC'.format(time.strftime('%F %X',time.gmtime(now)))
  438. for asset in self.usr_col_assets:
  439. if asset.symbol != 'USD':
  440. usdprice = Decimal(self.data[asset.id]['price_usd'])
  441. yield '{} ({}) = {:{}.{}f} USD'.format(
  442. asset.symbol,
  443. self.create_label(asset.id),
  444. usdprice,
  445. self.comma,
  446. max(2,int(-usdprice.adjusted())+4) )
  447. if hasattr(self,'subhdr'):
  448. yield self.subhdr
  449. if self.show_adj:
  450. yield (
  451. ('Offered price differs from spot' if self.offer else 'Adjusting prices')
  452. + ' by '
  453. + yellow('{:+.2f}%'.format( (self.adjust-1) * 100 ))
  454. )
  455. yield ''
  456. if cfg.portfolio:
  457. yield blue('PRICES')
  458. if self.table_hdr:
  459. yield self.table_hdr
  460. for row in self.rows:
  461. if isinstance(row,str):
  462. yield ('-' * self.hl_wid)
  463. else:
  464. try:
  465. yield self.fmt_row(self.data[row.id])
  466. except KeyError:
  467. yield gray(f'(no data for {row.id})')
  468. yield '-' * self.hl_wid
  469. if cfg.portfolio:
  470. self.fs_num = self.fs_num2
  471. self.fs_str = self.fs_str2
  472. yield ''
  473. yield blue('PORTFOLIO')
  474. yield self.table_hdr
  475. yield '-' * self.hl_wid
  476. for sym,amt in cfg.portfolio.items():
  477. try:
  478. yield self.fmt_row(self.data[sym],amt=amt)
  479. except KeyError:
  480. yield gray(f'(no data for {sym})')
  481. yield '-' * self.hl_wid
  482. if not cfg.btc_only:
  483. yield self.fs_num.format(
  484. lbl = 'TOTAL', pc1='', pc2='', upd='', amt='',
  485. **{ k.replace('-','_'): v for k,v in self.prices['total'].items() }
  486. )
  487. class overview(base):
  488. def __init__(self,data):
  489. self.data = data
  490. self.adjust = cfg.adjust
  491. self.show_adj = self.adjust != 1
  492. self.usr_col_assets = [asset._replace(id=self.get_id(asset)) for asset in cfg.usr_columns]
  493. self.col_ids = ('usd-us-dollar',) + tuple(a.id for a in self.usr_col_assets) + ('btc-bitcoin',)
  494. super().__init__(data)
  495. self.format_last_update_col()
  496. if cfg.portfolio:
  497. self.prices['total'] = { col_id: sum(self.prices[row.id][col_id] * cfg.portfolio[row.id]
  498. for row in self.rows if isinstance(row,tuple) and row.id in cfg.portfolio and row.id in data)
  499. for col_id in self.col_ids }
  500. self.init_prec()
  501. self.init_fs()
  502. def get_row_prices(self,id):
  503. if id in self.data:
  504. d = self.data[id]
  505. return { k: (
  506. Decimal(d['price_btc']) if k == 'btc-bitcoin' else
  507. Decimal(d['price_usd']) / self.col_usd_prices[k]
  508. ) * self.adjust for k in self.col_ids }
  509. def fmt_row(self,d,amt=None,amt_fmt=None):
  510. def fmt_pct(d):
  511. if d in ('',None):
  512. return gray(' --')
  513. n = Decimal(d)
  514. return (red,green)[n>=0](f'{n:+7.2f}')
  515. p = self.prices[d['id']]
  516. if amt is not None:
  517. amt_fmt = f'{amt:{19+cfg.add_prec}{self.comma}.{8+cfg.add_prec}f}'
  518. if '.' in amt_fmt:
  519. amt_fmt = amt_fmt.rstrip('0').rstrip('.')
  520. return self.fs_num.format(
  521. lbl = (self.create_label(d['id']) if opt.name_labels else d['symbol']),
  522. pc1 = fmt_pct(d.get('percent_change_7d')),
  523. pc2 = fmt_pct(d.get('percent_change_24h')),
  524. upd = d.get('last_updated_fmt'),
  525. amt = amt_fmt,
  526. **{ k.replace('-','_'): v * (1 if amt is None else amt) for k,v in p.items() }
  527. )
  528. def init_fs(self):
  529. col_prec = {'usd-us-dollar':2+cfg.add_prec,'btc-bitcoin':8+cfg.add_prec } # | self.uprec # Python 3.9
  530. col_prec.update(self.uprec)
  531. col_wid = {'usd-us-dollar':8+cfg.add_prec,'btc-bitcoin':12+cfg.add_prec } # """
  532. col_wid.update(self.uwid)
  533. max_row = max(
  534. ( (k,v['btc-bitcoin']) for k,v in self.prices.items() ),
  535. key = lambda a: a[1]
  536. )
  537. widths = { k: len('{:{}.{}f}'.format( self.prices[max_row[0]][k], self.comma, col_prec[k] ))
  538. for k in self.col_ids }
  539. fd = namedtuple('format_str_data',['fs_str','fs_num','wid'])
  540. col_fs_data = {
  541. 'label': fd(f'{{lbl:{self.col1_wid}}}',f'{{lbl:{self.col1_wid}}}',self.col1_wid),
  542. 'pct7d': fd(' {pc1:7}', ' {pc1:7}', 8),
  543. 'pct24h': fd(' {pc2:7}', ' {pc2:7}', 8),
  544. 'update_time': fd(' {upd}', ' {upd}', max((19 if cfg.portfolio else 0),self.upd_w) + 2),
  545. 'amt': fd(' {amt}', ' {amt}', 21),
  546. }
  547. # } | { k: fd( # Python 3.9
  548. col_fs_data.update({ k: fd(
  549. ' {{{}:>{}}}'.format( k.replace('-','_'), widths[k] ),
  550. ' {{{}:{}{}.{}f}}'.format( k.replace('-','_'), widths[k], self.comma, col_prec[k] ),
  551. widths[k]+2
  552. ) for k in self.col_ids
  553. })
  554. cols = (
  555. ['label','usd-us-dollar'] +
  556. [asset.id for asset in self.usr_col_assets] +
  557. [a for a,b in (
  558. ( 'btc-bitcoin', not cfg.btc_only ),
  559. ( 'pct7d', opt.percent_change ),
  560. ( 'pct24h', opt.percent_change ),
  561. ( 'update_time', opt.update_time ),
  562. ) if b]
  563. )
  564. cols2 = list(cols)
  565. if opt.update_time:
  566. cols2.pop()
  567. cols2.append('amt')
  568. self.fs_str = ''.join(col_fs_data[c].fs_str for c in cols)
  569. self.fs_num = ''.join(col_fs_data[c].fs_num for c in cols)
  570. self.hl_wid = sum(col_fs_data[c].wid for c in cols)
  571. self.fs_str2 = ''.join(col_fs_data[c].fs_str for c in cols2)
  572. self.fs_num2 = ''.join(col_fs_data[c].fs_num for c in cols2)
  573. self.hl_wid2 = sum(col_fs_data[c].wid for c in cols2)
  574. @property
  575. def table_hdr(self):
  576. return self.fs_str.format(
  577. lbl = '',
  578. pc1 = ' CHG_7d',
  579. pc2 = 'CHG_24h',
  580. upd = 'UPDATED',
  581. amt = ' AMOUNT',
  582. usd_us_dollar = 'USD',
  583. btc_bitcoin = ' BTC',
  584. **{ a.id.replace('-','_'): a.symbol for a in self.usr_col_assets }
  585. )
  586. class trading(base):
  587. def __init__(self,data):
  588. self.data = data
  589. self.asset = cfg.query.asset._replace(id=self.get_id(cfg.query.asset))
  590. self.to_asset = (
  591. cfg.query.to_asset._replace(id=self.get_id(cfg.query.to_asset))
  592. if cfg.query.to_asset else None )
  593. self.col_ids = [self.asset.id]
  594. self.adjust = cfg.adjust
  595. if self.to_asset:
  596. self.offer = self.to_asset.amount
  597. if self.offer:
  598. real_price = (
  599. self.asset.amount
  600. * Decimal(data[self.asset.id]['price_usd'])
  601. / Decimal(data[self.to_asset.id]['price_usd'])
  602. )
  603. if self.adjust != 1:
  604. die(1,'the --adjust option may not be combined with TO_AMOUNT in the trade specifier')
  605. self.adjust = self.offer / real_price
  606. self.hl_ids = [self.asset.id,self.to_asset.id]
  607. else:
  608. self.hl_ids = [self.asset.id]
  609. self.show_adj = self.adjust != 1 or self.offer
  610. super().__init__(data)
  611. self.usr_col_assets = [self.asset] + ([self.to_asset] if self.to_asset else [])
  612. for a in self.usr_col_assets:
  613. self.prices[a.id]['usd-us-dollar'] = Decimal(data[a.id]['price_usd'])
  614. self.format_last_update_col(cross_assets=self.usr_col_assets)
  615. self.init_prec()
  616. self.init_fs()
  617. def get_row_prices(self,id):
  618. if id in self.data:
  619. d = self.data[id]
  620. return { k: self.col_usd_prices[self.asset.id] / Decimal(d['price_usd']) for k in self.col_ids }
  621. def init_fs(self):
  622. self.max_wid = max(
  623. len('{:{}{}.{}f}'.format(
  624. v[self.asset.id] * self.asset.amount,
  625. 16 + cfg.add_prec,
  626. self.comma,
  627. 8 + cfg.add_prec
  628. ))
  629. for v in self.prices.values()
  630. )
  631. self.fs_str = '{lbl:%s} {p_spot}' % self.col1_wid
  632. self.hl_wid = self.col1_wid + self.max_wid + 1
  633. if self.show_adj:
  634. self.fs_str += ' {p_adj}'
  635. self.hl_wid += self.max_wid + 1
  636. if opt.update_time:
  637. self.fs_str += ' {upd}'
  638. self.hl_wid += self.upd_w + 2
  639. def fmt_row(self,d):
  640. id = d['id']
  641. p = self.prices[id][self.asset.id] * self.asset.amount
  642. p_spot = '{:{}{}.{}f}'.format( p, self.max_wid, self.comma, 8+cfg.add_prec )
  643. p_adj = (
  644. '{:{}{}.{}f}'.format( p*self.adjust, self.max_wid, self.comma, 8+cfg.add_prec )
  645. if self.show_adj else '' )
  646. return self.fs_str.format(
  647. lbl = (self.create_label(id) if opt.name_labels else d['symbol']),
  648. p_spot = green(p_spot) if id in self.hl_ids else p_spot,
  649. p_adj = yellow(p_adj) if id in self.hl_ids else p_adj,
  650. upd = d.get('last_updated_fmt'),
  651. )
  652. @property
  653. def table_hdr(self):
  654. return self.fs_str.format(
  655. lbl = '',
  656. p_spot = '{t:>{w}}'.format(
  657. t = 'SPOT PRICE',
  658. w = self.max_wid ),
  659. p_adj = '{t:>{w}}'.format(
  660. t = ('OFFERED' if self.offer else 'ADJUSTED') + ' PRICE',
  661. w = self.max_wid ),
  662. upd = 'UPDATED'
  663. )
  664. @property
  665. def subhdr(self):
  666. return (
  667. '{a}: {b:{c}} {d}'.format(
  668. a = 'Offer' if self.offer else 'Amount',
  669. b = self.asset.amount,
  670. c = self.comma,
  671. d = self.asset.symbol
  672. ) + (
  673. (
  674. ' =>' +
  675. (' {:{}}'.format(self.offer,self.comma) if self.offer else '') +
  676. ' {} ({})'.format(
  677. self.to_asset.symbol,
  678. self.create_label(self.to_asset.id) )
  679. ) if self.to_asset else '' )
  680. )