Ticker.py 33 KB

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