main_ticker.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. mmnode-ticker: Display price information for cryptocurrency and other assets
  12. """
  13. opts_data = {
  14. 'sets': [
  15. ('widest', True, 'percent_cols', 'd,w,m,y'),
  16. ('widest', True, 'name_labels', True),
  17. ('widest', True, 'thousands_comma', True),
  18. ('widest', True, 'update_time', True),
  19. ('wide', True, 'percent_cols', 'd,w'),
  20. ('wide', True, 'name_labels', True),
  21. ('wide', True, 'thousands_comma', True),
  22. ('wide', True, 'update_time', True),
  23. ],
  24. 'text': {
  25. 'desc': 'Display prices for cryptocurrency and other assets',
  26. 'usage': '[opts] [TRADE_SPECIFIER | ASSET_RANGE]',
  27. 'options': """
  28. -h, --help Print this help message
  29. --, --longhelp Print help message for long options (common options)
  30. -a, --asset-limit=N Retrieve data for top ‘N’ cryptocurrencies by market
  31. cap (default: {al}). To retrieve all available data,
  32. specify a value of zero.
  33. -A, --adjust=P Adjust prices by percentage ‘P’. In ‘trading’ mode,
  34. spot and adjusted prices are shown in separate columns.
  35. -b, --btc Fetch and display data for Bitcoin only
  36. -c, --add-columns=LIST Add columns for asset specifiers in LIST (comma-
  37. separated, see ASSET SPECIFIERS below). Can also be
  38. used to supply a USD exchange rate for missing assets.
  39. -C, --cached-data Use cached data from previous network query instead of
  40. live data from server
  41. -d, --download=D Retrieve and cache asset data ‘D’ from network (valid
  42. options: {ds})
  43. -D, --cachedir=D Read and write cached JSON data to directory ‘D’
  44. instead of ‘~/{dfl_cachedir}’
  45. -e, --add-precision=N Add ‘N’ digits of precision to columns
  46. -E, --elapsed Show elapsed time in UPDATED column (see --update-time)
  47. -F, --portfolio Display portfolio data
  48. -l, --list-ids List IDs of all available assets
  49. -n, --name-labels Label rows with asset names rather than symbols
  50. -p, --percent-cols=C Add daily, weekly, monthly, or yearly percentage change
  51. columns ‘C’ (specify with comma-separated letters
  52. {pc})
  53. -P, --pager Pipe the output to a pager
  54. -q, --quiet Produce quieter output
  55. -r, --add-rows=LIST Add rows for asset specifiers in LIST (comma-separated,
  56. see ASSET SPECIFIERS below). Can also be used to supply
  57. a USD exchange rate for missing assets.
  58. -s, --sort=P Sort output according to parameter P. Valid parameters
  59. are {sp_codes}. See SORT PARAMETERS below.
  60. To reverse the sort, prefix the parameter with ‘r’.
  61. -t, --testing Print command(s) to be executed to stdout and exit
  62. -T, --thousands-comma Use comma as a thousands separator
  63. -u, --update-time Include UPDATED (last update time) column
  64. -v, --verbose Be more verbose
  65. -w, --wide Display most optional columns (same as -unT -p d,w)
  66. -W, --widest Display all optional columns (same as -unT -p d,w,m,y)
  67. -x, --proxy=P Connect via proxy ‘P’. Set to the empty string to
  68. completely disable or ‘none’ to allow override from
  69. environment. Consult the curl manpage for --proxy usage.
  70. -X, --proxy2=P Alternate proxy for non-crypto financial data. Defaults
  71. to value of --proxy
  72. """,
  73. 'notes': """
  74. The script has three display modes: ‘overview’, enabled when no arguments are
  75. given on the command line; ‘trading’, when a TRADE_SPECIFIER argument (see
  76. below) is given; and ‘market cap’, when an ASSET_RANGE (see below) is given.
  77. Overview mode displays prices of all configured assets, and optionally the
  78. user’s portfolio; trading mode displays the price of a given quantity of an
  79. asset in relation to other assets, optionally comparing an offered price to
  80. the spot price; and market cap mode lists a range of crypto assets selected
  81. by current market cap.
  82. The ASSET_RANGE argument can be either an integer N, in which case the top
  83. N assets by market cap will be displayed, or a hyphen-separated range N-M,
  84. in which case assets from N to M by market cap will be displayed.
  85. ASSETS consist of either a symbol (e.g. ‘xmr’) or full ID (see --list-ids)
  86. consisting of symbol plus label (e.g. ‘xmr-monero’). In cases where the
  87. symbol is ambiguous, the full ID must be used. For Yahoo Finance assets
  88. the symbol and ID are identical:
  89. Examples:
  90. ltc - specify asset by symbol
  91. ltc-litecoin - same as above, but use full ID instead of symbol
  92. ^dji - Dow Jones Industrial Average (Yahoo)
  93. gc=f - gold futures (Yahoo)
  94. ASSET SPECIFIERS have the following format:
  95. ASSET[:RATE[:RATE_ASSET]]
  96. If the asset referred to by ASSET is not in the source data (see --list-ids),
  97. an arbitrarily chosen label may be used. RATE is the exchange rate of the
  98. asset in relation to RATE_ASSET, if present, otherwise USD. When RATE is
  99. postfixed with the letter ‘r’, its meaning is reversed, i.e. interpreted as
  100. ‘ASSET/RATE_ASSET’ instead of ‘RATE_ASSET/ASSET’. Asset specifier examples:
  101. inr:79.5 - INR is not in the source data, so supply rate of
  102. 79.5 INR to the Dollar (USD/INR)
  103. inr:0.01257r - same as above, but use reverse rate (INR/USD)
  104. inr-indian-rupee:79.5 - same as first example, but add an arbitrary label
  105. omr-omani-rial:2.59r - Omani Rial is pegged to the Dollar at 2.59 USD
  106. bgn-bulgarian-lev:0.5113r:eurusd=x
  107. - Bulgarian Lev is pegged to the Euro at 0.5113 EUR
  108. A TRADE_SPECIFIER is a single argument in the format:
  109. ASSET:AMOUNT[:TO_ASSET[:TO_AMOUNT]]
  110. Examples:
  111. xmr:17.34 - price of 17.34 XMR in all configured assets
  112. xmr-monero:17.34 - same as above, but with full ID
  113. xmr:17.34:eurusd=x - price of 17.34 XMR in EUR only
  114. xmr:17.34:eurusd=x:2800 - commission on an offer of 17.34 XMR for 2800 EUR
  115. TO_AMOUNT, if included, is used to calculate the percentage difference or
  116. commission on an offer compared to the spot price.
  117. If either ASSET or TO_ASSET refer to assets not present in the source data,
  118. a USD rate for the missing asset(s) must be supplied via the --add-columns
  119. or --add-rows options.
  120. SORT PARAMETERS:
  121. {sp_fmt}
  122. PROXY NOTE
  123. The remote server used to obtain the crypto price data, {cc.api_host},
  124. blocks Tor behind a Captcha wall, so a Tor proxy cannot be used directly.
  125. If you’re concerned about privacy, connect via a VPN, or better yet, VPN over
  126. Tor. Then set up an HTTP proxy (e.g. Privoxy) on the VPN’ed host and set the
  127. ‘proxy’ option in the config file or --proxy on the command line accordingly.
  128. Or run the script directly on the VPN’ed host with ’proxy’ or --proxy set to
  129. the null string.
  130. Alternatively, you may download the JSON source data in a Tor-proxied browser
  131. from {cc.api_url}, save it as ‘ticker.json’ in your
  132. configured cache directory and run the script with the --cached-data option.
  133. Financial data is obtained from {fi.desc}, which currently allows Tor.
  134. RATE LIMITING NOTE
  135. To protect user privacy, filtering and processing of cryptocurrency data is
  136. performed client side so that the remote server does not know which assets
  137. are being examined. This is done by fetching data for the top {al} crypto
  138. assets by market cap (configurable via the --asset-limit option) with each
  139. invocation of the script. A rate limit of {cc.ratelimit} seconds between calls is thus
  140. imposed to prevent abuse of the remote server. When the --btc option is in
  141. effect, this limit is reduced to {cc.btc_ratelimit} seconds. To bypass the rate limit
  142. entirely, use --cached-data.
  143. Note that financial data obtained from {fi.api_host} is filtered in the
  144. request, which has privacy implications. The rate limit for financial data
  145. is {fi.ratelimit} seconds.
  146. EXAMPLES
  147. # Basic display in ‘overview’ mode:
  148. $ mmnode-ticker
  149. # Display BTC price only:
  150. $ mmnode-ticker --btc
  151. # Wide display, add EUR and OMR columns, OMR/USD rate, extra precision and
  152. # proxy:
  153. $ mmnode-ticker -w -c eurusd=x,omr-omani-rial:2.59r -e2 -x http://vpnhost:8118
  154. # Wide display, elapsed update time, add EUR, BGN columns and BGN/EUR rate:
  155. $ mmnode-ticker -wE -c eurusd=x,bgn-bulgarian-lev:0.5113r:eurusd=x
  156. # Widest display with all percentage change columns, use cached data from
  157. # previous network query, show portfolio (see above), pipe output to pager,
  158. # add DOGE row:
  159. $ mmnode-ticker -WCFP -r doge
  160. # Display 17.234 XMR priced in all configured assets (‘trading’ mode):
  161. $ mmnode-ticker xmr:17.234
  162. # Same as above, but add INR price at specified USDINR rate:
  163. $ mmnode-ticker -c inr:79.5 xmr:17.234
  164. # Same as above, but view INR price only at specified rate, adding label:
  165. $ mmnode-ticker -c inr-indian-rupee:79.5 xmr:17.234:inr
  166. # Calculate commission on an offer of 2700 USD for 0.123 BTC, compared to
  167. # current spot price:
  168. $ mmnode-ticker usd:2700:btc:0.123
  169. # Calculate commission on an offer of 200000 INR for 0.1 BTC, compared to
  170. # current spot price, at specified USDINR rate:
  171. $ mmnode-ticker -n -c inr-indian-rupee:79.5 inr:200000:btc:0.1
  172. # Display top 20 crypto assets by market cap, adding a Euro column:
  173. $ mmnode-ticker -c eurusd=x 20
  174. # Same as above, specifying assets using a range:
  175. $ mmnode-ticker -c eurusd=x 1-20
  176. CONFIGURED ASSETS:
  177. {assets}
  178. Customize output by editing the file
  179. ~/{cfg}
  180. To add a portfolio, edit the file
  181. ~/{pf_cfg}
  182. """},
  183. 'code': {
  184. 'options': lambda s: s.format(
  185. dfl_cachedir = os.path.relpath(dfl_cachedir, start=homedir),
  186. ds = fmt_dict(DataSource.get_sources(), fmt='equal_compact'),
  187. al = DataSource.coinpaprika.dfl_asset_limit,
  188. sp_codes = fmt_list(sort_params, fmt='fancy'),
  189. pc = fmt_list(Ticker.percent_cols, fmt='fancy')),
  190. 'notes': lambda s: s.format(
  191. assets = fmt_list(assets_list_gen(cfg_in), fmt='col', indent=' '),
  192. cfg = os.path.relpath(cfg_in.cfg_file, start=homedir),
  193. pf_cfg = os.path.relpath(cfg_in.portfolio_file, start=homedir),
  194. al = DataSource.coinpaprika.dfl_asset_limit,
  195. cc = src_cls['cc'](),
  196. sp_fmt = '\n '.join(f'‘{k}’ - {v.desc}' for k, v in sort_params.items()),
  197. fi = src_cls['fi']())
  198. }
  199. }
  200. import os
  201. from mmgen.util import fmt_list, fmt_dict
  202. from mmgen.cfg import Config
  203. from . import Ticker
  204. gcfg = Config(opts_data=opts_data, caller_post_init=True)
  205. src_cls, cfg_in = Ticker.make_cfg(gcfg)
  206. from .Ticker import dfl_cachedir, homedir, DataSource, assets_list_gen, sort_params
  207. gcfg._post_init()
  208. Ticker.main()