coinmarketcap

- python class for the api on coinmarketcap
git clone git://git.acid.vegas/coinmarketcap.git
Log | Files | Refs | Archive | README | LICENSE

coinmarketcap.py (2557B)

      1 #!/usr/bin/env python
      2 # CoinMarketCap API Class - Developed by acidvegas in Python (https://acid.vegas/coinmarketcap)
      3 
      4 import http.client
      5 import json
      6 import time
      7 import zlib
      8 
      9 CACHE_EXPIRY_TIME = 300
     10 
     11 class CoinMarketCap(object):
     12 	def __init__(self, api_key):
     13 		self.api_key = api_key
     14 		self.cache   = {'global':dict(), 'ticker':dict()}
     15 		self.last    = {'global':0     , 'ticker':0     }
     16 
     17 	def _api(self, _endpoint):
     18 		'''Make a request to the CoinMarketCap API.'''
     19 		with http.client.HTTPSConnection('pro-api.coinmarketcap.com', timeout=15) as conn:
     20 			conn.request('GET', f'/v1/{_endpoint}', headers={'Accept':'application/json', 'Accept-Encoding':'deflate, gzip', 'X-CMC_PRO_API_KEY':self.api_key})
     21 			response = conn.getresponse()
     22 			if response.getheader('Content-Encoding') == 'gzip':
     23 				content = zlib.decompress(response.read(), 16+zlib.MAX_WBITS).decode('utf-8')
     24 			else:
     25 				content = response.read().decode('utf-8')
     26 		return json.loads(content.replace(': null', ': "0"'))['data']
     27 
     28 	def _global(self):
     29 		'''Get global market data.'''
     30 		if time.time() - self.last['global'] < CACHE_EXPIRY_TIME:
     31 			return self.cache['global']
     32 		else:
     33 			data = self._api('global-metrics/quotes/latest')
     34 			self.cache['global'] = {
     35 				'cryptocurrencies' : data['active_cryptocurrencies'],
     36 				'exchanges'        : data['active_exchanges'],
     37 				'btc_dominance'    : int(data['btc_dominance']),
     38 				'eth_dominance'    : int(data['eth_dominance']),
     39 				'market_cap'       : int(data['quote']['USD']['total_market_cap']),
     40 				'volume'           : int(data['quote']['USD']['total_volume_24h'])
     41 			}
     42 			self.last['global'] = time.time()
     43 			return self.cache['global']
     44 
     45 	def _ticker(self):
     46 		'''Get ticker data.'''
     47 		if time.time() - self.last['ticker'] < CACHE_EXPIRY_TIME:
     48 			return self.cache['ticker']
     49 		else:
     50 			data = self._api('cryptocurrency/listings/latest?limit=5000')
     51 			self.cache['ticker'] = dict()
     52 			for item in data:
     53 				self.cache['ticker'][item['id']] = {
     54 					'name'       : item['name'],
     55 					'symbol'     : item['symbol'],
     56 					'slug'       : item['slug'],
     57 					'rank'       : item['cmc_rank'],
     58 					'price'      : float(item['quote']['USD']['price']),
     59 					'percent'    : {'1h':float(item['quote']['USD']['percent_change_1h']), '24h':float(item['quote']['USD']['percent_change_24h']), '7d':float(item['quote']['USD']['percent_change_7d'])},
     60 					'volume'     : int(float(item['quote']['USD']['volume_24h'])),
     61 					'market_cap' : int(float(item['quote']['USD']['market_cap']))
     62 				}
     63 			self.last['ticker'] = time.time()
     64 			return self.cache['ticker']