Ticker.py 35 KB

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