Ticker.py 29 KB

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