Ticker.py 34 KB

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