Ticker.py 25 KB

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