Ticker.py 29 KB

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