Ticker.py 30 KB

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