Ticker.py 29 KB

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