Ticker.py 32 KB

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