SHARE
TWEET

money.py (edited from first paste, fixed bug)

jcomeau_ictx Apr 8th, 2014 147 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python
  2. 'get amount and dollar value of cryptocurrencies'
  3. import sys, os, pwd, json, glob, urllib2, time
  4. from subprocess import check_output
  5. MINUTES = 60
  6. MARKETS = {
  7.  'cryptsy': {
  8.   'file': '/tmp/cryptsy.dat',
  9.   'url': 'http://pubapi.cryptsy.com/api.php?method=marketdatav2',
  10.  },
  11.  'bitstamp': {
  12.   'file': '/tmp/bitstamp.dat',
  13.   'url': 'https://www.bitstamp.net/api/ticker/',
  14.  },
  15. }
  16. COINS = {  # add to this as necessary
  17.  'americancoind': 'AMC/BTC',
  18.  'argentumcoind': 'ARG/BTC',  # symlink to Argentum
  19.  'dogecoind': 'DOGE/BTC',
  20. }
  21. def money():
  22.  '''
  23. show amount in each currency and dollar amount of each
  24. '''
  25.  cryptsy, bitstamp, bitcoind, daemons = getdata()
  26.  print '%13s  %13s %13s %13s %13s' % (
  27.   'coin', 'value', 'owned', 'BTC value', 'USD value')
  28.  total = bitcoind.get('owned', 0.0)
  29.  dollartotal = total * bitcoind['price']
  30.  print '%13s: %13.6f %13.6f %13.6f %13.5f' % (
  31.   'bitcoind', bitcoind['price'], total, total, dollartotal)
  32.  for daemon in daemons:
  33.   price = lasttradeprice(cryptsy, daemon)
  34.   owned = getbalance(daemon)
  35.   value = owned * price
  36.   dollars = bitcoind['price'] * value
  37.   total, dollartotal = total + value, dollartotal + dollars
  38.   print '%13s: %13.8f %13.6f %13.6f %13.5f' % (
  39.    daemon, price, owned, value, dollars)
  40.  print '%13s: %13s %13s %13.6f %13.5f' % ('total', '', '', total, dollartotal)
  41. def getdata():
  42.  'load necessary data'
  43.  cryptsy, bitstamp = getmarkets()
  44.  os.chdir(os.path.join(pwd.getpwuid(os.geteuid()).pw_dir, 'bin'))
  45.  daemons = glob.glob('*coind')
  46.  bitcoind = {'owned': 'bitcoind' in daemons}
  47.  if bitcoind['owned']:
  48.   daemons.remove('bitcoind')
  49.   bitcoind['owned'] = getbalance('bitcoind')
  50.  bitcoind['price'] = float(bitstamp['last'])
  51.  return cryptsy, bitstamp, bitcoind, daemons
  52. def getbalance(daemon):
  53.  'make RPC call to get balance'
  54.  return float(check_output([daemon, 'getbalance']).strip())
  55. def fetch(url):
  56.  'return contents of URL as an object decoded from JSON data'
  57.  webpage = urllib2.urlopen(url)
  58.  data = webpage.read().strip()
  59.  webpage.close()
  60.  return json.loads(data)
  61. def is_recent(filename):
  62.  '''
  63. boolean indicating if cached data is new enough
  64.  
  65. returns None in special case that file does not exist
  66. '''
  67.  if os.path.exists(filename):
  68.   age = time.time() - os.stat(filename).st_mtime
  69.   debug('age of %s in seconds: %d' % (filename, age))
  70.   return age < 10 * MINUTES
  71. def getmarkets():
  72.  result = []
  73.  for market in MARKETS:
  74.   if is_recent(MARKETS[market]['file']):
  75.    debug('loading %s from file' % market)
  76.    data = json.loads(read(MARKETS[market]['file']))
  77.   else:
  78.    debug('loading %s from URL' % market)
  79.    data = fetch(MARKETS[market]['url'])
  80.    write(MARKETS[market]['file'], json.dumps(data))
  81.   result.append(data)
  82.  return result
  83. def read(filename):
  84.  'read and return contents of file, closing it properly'
  85.  infile = open(filename)
  86.  data = infile.read()
  87.  infile.close()
  88.  return data
  89. def write(filename, data):
  90.  'write data to file, closing it properly'
  91.  outfile = open(filename, 'w')
  92.  outfile.write(data)
  93.  outfile.close()
  94. def lasttradeprice(cryptsy, daemon):
  95.  'fetch last trade price from Cryptsy data'
  96.  market = COINS[daemon]
  97.  return float(cryptsy['return']['markets'][market]['lasttradeprice'])
  98. def debug(message):
  99.  if __debug__:
  100.   print >>sys.stderr, message
  101. if __name__ == '__main__':
  102.  money()
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top