🢀 coinmarketcap :: ed9c982


commit ed9c98230356e47ffe8d819481af001d26530c6e
Author: acidvegas <acid.vegas@acid.vegas>
Date:   Fri Jun 28 05:09:59 2019 -0400

    Initial commit

diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..69997e8
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2019, acidvegas <acid.vegas@acid.vegas>
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..173951f
--- /dev/null
+++ b/README.md
@@ -0,0 +1,21 @@
+# coinmarketcap
+> A Python class for the API on CoinMarketCap
+
+###### Requirements
+* [Python](https://www.python.org/downloads/) *(**Note:** This script was developed to be used with the latest version of Python.)*
+
+###### API Documentation
+- [CoinMarketCap API Documentation](https://coinmarketcap.com/api/)
+
+###### Example
+```python
+from coinmarketcap import CoinMarketCap, Cryptocurrency, Exchange, Global, Tools
+CMC = CoinMarketCap(key='API-KEY-HERE')
+print(Cryptocurrency._info('BTC'))
+```
+
+###### Mirrors
+- [acid.vegas](https://acid.vegas/coinmarketcap) *(main)*
+- [SuperNETs](https://git.supernets.org/pumpcoin/coinmarketcap)
+- [GitHub](https://github.com/pumpcoin/coinmarketcap)
+- [GitLab](https://gitlab.com/pumpcoin/coinmarketcap)
diff --git a/coinmarketcap/coinmarketcap.py b/coinmarketcap/coinmarketcap.py
new file mode 100644
index 0000000..eeb9973
--- /dev/null
+++ b/coinmarketcap/coinmarketcap.py
@@ -0,0 +1,144 @@
+#!/usr/bin/env python
+# CoinMarketCap API Class - Developed by acidvegas in Python (https://acid.vegas/coinmarketcap)
+
+'''
+API Documentation:
+	https://coinmarketcap.com/api/
+'''
+
+import datetime
+import http.client
+import json
+import time
+
+CMC = CoinMarketCap()
+
+class CoinMarketCap(object):
+	def __init__(self):
+		self.cache    = {'global':{'last_updated':0},'ticker':{'BTC':{'last_updated':0}}}
+		self.last     = time.time()
+		self.requests = 0
+
+	def api(self, sub, data):
+		conn = http.client.HTTPSConnection(sub + '.coinmarketcap.com', timeout=15)
+		conn.request('GET', data)
+		response = json.loads(conn.getresponse().read())
+		conn.close()
+		self.requests += 1
+		return response
+
+class Graph:
+	def _currencies(name, start_time, end_time):
+		return CMC.api('graphs2', f'/currencies/{name}/{start_time}/{end_time}/')
+
+	def _dominance(start_time, end_time):
+		return CMC.api('graphs2', f'/global/dominance/{start_time}/{end_time}/')
+
+	def _market_cap(start_time, end_time):
+		return CMC.api('graphs2', f'/global/marketcap-total/{start_time}/{end_time}/')
+
+	def _market_cap_altcoin(start_time, end_time):
+		return CMC.api('graphs2', f'/global/marketcap-altcoin/{start_time}/{end_time}/')
+
+class Logo:
+	def _currencies(id, size):
+		''' Description: Return a {size}x{size} sized logo image URL for the coin with the {id} id.
+
+			Valid size values are: 16, 32, 64, 128, and 200'''
+		return f'https://s2.coinmarketcap.com/static/img/coins/{size}x{size}/{id}.png'
+
+	def _exchanges(id, size):
+		''' Description: Return a {size}x{size} sized logo image URL for the exchange with the {id} id.
+
+			Valid size values are: 16, 32, 64, 128, and 200'''
+		return f'https://s2.coinmarketcap.com/static/img/exchanges/{size}x{size}/{id}.png'
+
+class Public:
+	def _global(convert='USD'):
+		''' Endpoint   : /global/
+			Method     : GET
+			Description: This endpoint displays the global data found at the top of coinmarketcap.com.
+
+			Optional parameters:
+				* (string) convert - return pricing info in terms of another currency.
+					Valid fiat currency  values are: AUD, BRL, CAD, CHF, CLP, CNY, CZK, DKK, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, NZD, PHP, PKR, PLN, RUB, SEK, SGD, THB, TRY, TWD, ZAR
+					Valid cryptocurrency values are: BCH, BTC, ETH LTC, and XRP '''
+		data = CMC.api('api', '/v2/global/?convert='+convert)['data']
+		return {'cryptocurrencies' : data['active_cryptocurrencies'],
+				'markets'          : data['active_markets'],
+				'btc_dominance'    : int(data['bitcoin_percentage_of_market_cap']),
+				'market_cap'       : int(data['quotes'][convert]['total_market_cap']),
+				'volume'           : int(data['quotes'][convert]['total_volume_24h']),
+				'last_updated'     : int(data['last_updated'])}
+
+	def _listings():
+		''' Endpoint   : /listings/
+			Method     : GET
+			Description: This endpoint displays all active cryptocurrency listings in one call. Use the "id" field on the Ticker endpoint to query more information on a specific cryptocurrency. '''
+		return CMC.api('api', '/v2/listings/')
+
+	def _ticker(start=1, limit=100, sort='rank', structure='dictionary', convert='USD'):
+		''' Endpoint   : /ticker/
+			Method     : GET
+			Description: This endpoint displays cryptocurrency ticker data in order of rank. The maximum number of results per call is 100. Pagination is possible by using the start and limit parameters.
+
+			Optional parameters:
+				* (int) start        - return results from rank [start] and above (default is 1)
+				* (int) limit        - return a maximum of [limit] results (default is 100; max is 100)
+				* (string) sort      - return results sorted by [sort] . Possible values are id, rank, volume_24h, and percent_change_24h (default is rank).
+					Note: It is strongly recommended to use id to sort if paginating through all available results since id is the only sort option guaranteed to return in a consistent order.
+				* (string) structure - specify the structure for the main data field. Possible values are dictionary and array (default is dictionary).
+				* (string) convert   - return pricing info in terms of another currency.
+					Valid fiat currency  values are: AUD, BRL, CAD, CHF, CLP, CNY, CZK, DKK, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, NZD, PHP, PKR, PLN, RUB, SEK, SGD, THB, TRY, TWD, ZAR
+					Valid cryptocurrency values are: BCH, BTC, ETH LTC, and XRP '''
+		data = CMC.api('api', f'/v2/ticker/?start={start}&limit={limit}&sort={sort}&structure={structure}&convert={convert}')['data'] #.replace(b': null', b': "0"'))['data']
+		results = dict()
+		for item in data:
+			del data[item]['id'], data[item]['website_slug'], data[item]['circulating_supply'], data[item]['total_supply'], data[item]['max_supply']
+			results[data[item]['symbol']] = {
+				'name'         : data[item]['name'],
+				'symbol'       : data[item]['symbol'],
+				'rank'         : data[item]['rank'],
+				'price'        : float(data[item]['quotes'][convert]['price']),
+				'volume'       : int(data[item]['quotes'][convert]['volume_24h']),
+				'market_cap'   : int(data[item]['quotes'][convert]['market_cap']),
+				'percent'      : {'1h':float(data[item]['quotes'][convert]['percent_change_1h']),'24h':float(data[item]['quotes'][convert]['percent_change_24h']),'7d':float(data[item]['quotes'][convert]['percent_change_7d'])},
+				'last_updated' : int(data[item]['last_updated'])
+			}
+			data[item] = None
+		return results
+
+	def _ticker_specific(id, structure='dictionary', convert='USD'):
+		''' Endpoint   : /ticker/{id}/
+			Method     : GET
+			Description: This endpoint displays ticker data for a specific cryptocurrency. Use the "id" field from the Listings endpoint in the URL.
+
+			Optional parameters:
+	        	* (string) structure - specify the structure for the main data field. Possible values are dictionary and array (default is dictionary).
+    	    	* (string) convert   - return pricing info in terms of another currency.
+        			Valid fiat currency  values are: AUD, BRL, CAD, CHF, CLP, CNY, CZK, DKK, EUR, GBP, HKD, HUF, IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, NZD, PHP, PKR, PLN, RUB, SEK, SGD, THB, TRY, TWD, ZAR
+					Valid cryptocurrency values are: BCH, BTC, ETH LTC, and XRP '''
+		data = CMC.api('api', f'/v2/ticker/{id}/?structure={structure}&convert={convert}') # replace(b': null', b': "0"'))
+		return {'name'         : data['name'],
+				'symbol'       : data['symbol'],
+				'rank'         : data['rank'],
+				'price'        : float(data['quotes'][convert]['price']),
+				'volume'       : int(data['quotes'][convert]['volume_24h']),
+				'market_cap'   : int(data['quotes'][convert]['market_cap']),
+				'percent'      : {'1h':float(data['quotes'][convert]['percent_change_1h']),'24h':float(data['quotes'][convert]['percent_change_24h']),'7d':float(data['quotes'][convert]['percent_change_7d'])},
+				'last_updated' : int(data['last_updated'])}
+
+class Search:
+	def _cryptocurrencies():
+		data = CMC.api('s2', '/generated/search/quick_search.json')
+		results = dict()
+		for item in data:
+			results[item['symbol']] = {'id':name['id'],'name':item['name'],'rank':item['rank'],'slug':item['slug']}
+		return results
+
+	def _markets():
+		data = CMC.api('s2', '/generated/search/quick_search_exchanges.json')
+		results = dict()
+		for item in data:
+			results[item['slug']] = {'id':item['id'],'name':item['name'],'rank':item['rank']}
+		return results
diff --git a/coinmarketcap/pro-coinmarketcap.py b/coinmarketcap/pro-coinmarketcap.py
new file mode 100644
index 0000000..b6bf32c
--- /dev/null
+++ b/coinmarketcap/pro-coinmarketcap.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python
+# CoinMarketCap API Class - Developed by acidvegas in Python (https://acid.vegas/coinmarketcap)
+
+'''
+API Documentation:
+	https://coinmarketcap.com/api/
+'''
+
+import datetime
+import http.client
+import json
+import time
+import urllib.parse
+import zlib
+
+def clean_params(params):
+	params = {k: v for k, v in params.items() if v is not None}
+	return '?' + urllib.parse.urlencode(params) if params else ''
+
+class CoinMarketCap(object):
+	def __init__(self, key):
+		self.cache = {}
+		self.key = key
+		self.last = time.time()
+
+	def api(self, endpoint):
+		headers = {'Accept':'application/json', 'Accept-Encoding':'deflate, gzip', 'X-CMC_PRO_API_KEY':self.key}
+		conn = http.client.HTTPSConnection('pro-api.coinmarketcap.com', timeout=15)
+		conn.request('GET', '/v1/' + endpoint, headers=headers)
+		response = json.loads(zlib.decompress(conn.getresponse().read(), 16+zlib.MAX_WBITS))
+		conn.close()
+		return response
+
+class Cryptocurrency:
+	def info(id=None, symbol=None):
+		params = clean_params({'id':id, 'symbol':symbol})
+		return CMC.api('cryptocurrency/info' + params)
+
+	def map(listing_status='active', start=1, limit=None, symbol=None):
+		params = clean_params({'listing_status':listing_status, 'start':start, 'limit':limit, 'symbol':symbol})
+		return CMC.api('cryptocurrency/map' + params)
+
+	def listings_historical(timestamp=None, start=1, limit=100, convert=None, sort='market_cap', sort_dir='desc', cryptocurrency_type='all'):
+		params = clean_params({'timestamp':timestamp, 'start':start, 'limit':limit, 'convert':convert, 'sort':sort, 'sort_dir':sort_dir, 'cryptocurrency_type':cryptocurrency_type})
+		return CMC.api('cryptocurrency/listings/historical' + params)
+
+	def listings_latest(start=1, limit=100, convert='USD', sort='market_cap', sort_dir='desc', cryptocurrency_type='all'):
+		params = clean_params({'start':start, 'limit':limit, 'convert':convert, 'sort':sort, 'sort_dir':sort_dir, 'cryptocurrency_type':cryptocurrency_type})
+		return CMC.api('cryptocurrency/listings/latest' + params)
+
+	def market_pairs_latest(id=None, symbol=None, start=1, limit=100, convert='USD'):
+		params = clean_params({'id':id, 'symbol':symbol, 'start':start, 'limit':limit, 'convert':convert})
+		return CMC.api('cryptocurrency/market-pairs/latest' + params)
+
+	def ohlcv_historical(id=None, symbol=None, time_period='daily', time_start=None, time_end=None, count=10, interval='daily', convert='USD'):
+		params = clean_params({'id':id, 'symbol':symbol, 'time_period':time_period, 'time_start':time_start, 'time_end':time_end, 'count':count, 'interval':interval, 'convert':convert})
+		return CMC.api('cryptocurrency/ohlcv/historical' + params)
+
+	def ohlcv_latest(id=None, symbol=None, convert=None):
+		params = clean_params({'id':id, 'symbol':symbol, 'convert':convert)
+		return CMC.api('cryptocurrency/ohlcv/latest' + params)
+
+	def quotes_historical(id=None, symbol=None, time_period='dailey', time_start=None, time_end=None, count=10, interval='daily', convert='USD'):
+		params = clean_params({'id':id, 'symbol':symbol, 'time_period':time_period, 'time_start':time_start, 'time_end':time_end, 'count':count, 'interval':interval, 'convert':convert})
+		return CMC.api('cryptocurrency/ohlcv/historical' + params)
+
+	def quotes_latest():
+		params = clean_params({'id':id, 'symbol':symbol, 'convert':convert})
+		return CMC.api('cryptocurrency/ohlcv/latest' + params)
+
+class Exchange:
+	def info(id=None, slug=None):
+	def map():
+	def historical():
+	def latest():
+	def market_pairs():
+	def quotes():
+
+class Global:
+	def historical():
+	def latest():
+
+class Tools:
+	def price_conversion():
\ No newline at end of file