Ticker.py 31 KB

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