Ticker.py 30 KB

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