Ticker.py 23 KB

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