←︎ coinmarketcap :: 9d4eb03


1
commit 9d4eb032737209ed6363f78c16c1ed2fc06849fb
2
Author: acidvegas <acid.vegas@acid.vegas>
3
Date:   Thu Apr 9 20:37:48 2020 -0400
4
5
    Initial commit
6
---
7
 LICENSE          | 15 +++++++++++++++
8
 README.md        | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++
9
 coinmarketcap.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
10
 3 files changed, 121 insertions(+)
11
12
diff --git a/LICENSE b/LICENSE
13
new file mode 100644
14
index 0000000..d521bd0
15
--- /dev/null
16
+++ b/LICENSE
17
@@ -0,0 +1,15 @@
18
+ISC License
19
+
20
+Copyright (c) 2020, acidvegas <acid.vegas@acid.vegas>
21
+
22
+Permission to use, copy, modify, and/or distribute this software for any
23
+purpose with or without fee is hereby granted, provided that the above
24
+copyright notice and this permission notice appear in all copies.
25
+
26
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
27
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
28
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
29
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
30
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
31
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
32
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
33
diff --git a/README.md b/README.md
34
new file mode 100644
35
index 0000000..9344069
36
--- /dev/null
37
+++ b/README.md
38
@@ -0,0 +1,50 @@
39
+# coinmarketcap
40
+> A Python class for the API on [CoinMarketCap](https://coinmarketcap.com)
41
+
42
+## Requirements
43
+* [Python](https://www.python.org/downloads/) *(**Note:** This script was developed to be used with the latest version of Python)*
44
+
45
+## API Documentation
46
+- [CoinMarketCap API Documentation](https://coinmarketcap.com/api/documentation/v1/)
47
+
48
+## Information
49
+In order to use the CoinMarketCap API, you will need an API key which you can sign up for one [here](https://pro.coinmarketcap.com/signup/).
50
+
51
+Data from the API will be cached for 5 minutes at a time (that is how long it takes CoinMarketCap to refresh their data) this way you will not get rate limited.
52
+
53
+The class has only 2 main functions, one for global data and one for ticker data.
54
+
55
+## Example
56
+```python
57
+from coinmarketcap import CoinMarketCap
58
+
59
+CMC  = CoinMarketCap('API_KEY_HERE')
60
+
61
+global_data = CMC._global() # Global data example
62
+print('Cryptocurrencies : ' + str(global_data['cryptocurrencies']))
63
+print('Exchanges        : ' + str(global_data['exchanges']))
64
+print('BTC Dominance    : ' + str(global_data['btc_dominance']))
65
+print('ETH Dominance    : ' + str(global_data['eth_dominance']))
66
+print('Market Cap       : ' + str(global_data['market_cap']))
67
+print('Volume           : ' + str(global_data['volume']))
68
+
69
+ticker_data = CMC._ticker() # Ticker data example
70
+for item in ticker_data:
71
+    print('ID          : ' + item)
72
+    print('Name        : ' + ticker_data[item]['name'])
73
+    print('Symbol      : ' + ticker_data[item]['symbol'])
74
+    print('Slug        : ' + ticker_data[item]['slug'])
75
+    print('Rank        : ' + str(ticker_data[item]['rank']))
76
+    print('Price       : ' + str(ticker_data[item]['price']))
77
+    print('1h  Percent : ' + str(ticker_data[item]['percent']['1h']))
78
+    print('24h Percent : ' + str(ticker_data[item]['percent']['24h']))
79
+    print('7d  Percent : ' + str(ticker_data[item]['percent']['7d']))
80
+    print('Volume      : ' + str(ticker_data[item]['volume']))
81
+    print('Market Cap  : ' + str(ticker_data[item]['market_cap']))
82
+    input('') # Press enter to continue...
83
+```
84
+
85
+## Mirrors
86
+- [acid.vegas](https://acid.vegas/coinmarketcap) *(main)*
87
+- [GitHub](https://github.com/acidvegas/coinmarketcap)
88
+- [GitLab](https://gitlab.com/acidvegas/coinmarketcap)
89
diff --git a/coinmarketcap.py b/coinmarketcap.py
90
new file mode 100644
91
index 0000000..6d8201b
92
--- /dev/null
93
+++ b/coinmarketcap.py
94
@@ -0,0 +1,56 @@
95
+#!/usr/bin/env python
96
+# CoinMarketCap API Class - Developed by acidvegas in Python (https://acid.vegas/coinmarketcap)
97
+
98
+import http.client
99
+import json
100
+import time
101
+import zlib
102
+
103
+class CoinMarketCap(object):
104
+	def __init__(self, api_key):
105
+		self.api_key = api_key
106
+		self.cache   = {'global':dict(), 'ticker':dict()}
107
+		self.last    = {'global':0     , 'ticker':0     }
108
+
109
+	def _api(self, _endpoint):
110
+		conn = http.client.HTTPSConnection('pro-api.coinmarketcap.com', timeout=15)
111
+		conn.request('GET', '/v1/' + _endpoint, headers={'Accept':'application/json', 'Accept-Encoding':'deflate, gzip', 'X-CMC_PRO_API_KEY':self.api_key})
112
+		response = zlib.decompress(conn.getresponse().read(), 16+zlib.MAX_WBITS).decode('utf-8').replace(': null', ': "0"')
113
+		conn.close()
114
+		return json.loads(response)['data']
115
+
116
+	def _global(self):
117
+		if time.time() - self.last['global'] < 300:
118
+			return self.cache['global']
119
+		else:
120
+			data = self._api('global-metrics/quotes/latest')
121
+			self.cache['global'] = {
122
+				'cryptocurrencies' : data['active_cryptocurrencies'],
123
+				'exchanges'        : data['active_exchanges'],
124
+				'btc_dominance'    : int(data['btc_dominance']),
125
+				'eth_dominance'    : int(data['eth_dominance']),
126
+				'market_cap'       : int(data['quote']['USD']['total_market_cap']),
127
+				'volume'           : int(data['quote']['USD']['total_volume_24h'])
128
+			}
129
+			self.last['global'] = time.time()
130
+			return self.cache['global']
131
+
132
+	def _ticker(self):
133
+		if time.time() - self.last['ticker'] < 300:
134
+			return self.cache['ticker']
135
+		else:
136
+			data = self._api('cryptocurrency/listings/latest?limit=5000')
137
+			self.cache['ticker'] = dict()
138
+			for item in data:
139
+				self.cache['ticker'][item['id']] = {
140
+					'name'       : item['name'],
141
+					'symbol'     : item['symbol'],
142
+					'slug'       : item['slug'],
143
+					'rank'       : item['cmc_rank'],
144
+					'price'      : float(item['quote']['USD']['price']),
145
+					'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'])},
146
+					'volume'     : int(float(item['quote']['USD']['volume_24h'])),
147
+					'market_cap' : int(float(item['quote']['USD']['market_cap']))
148
+				}
149
+			self.last['ticker'] = time.time()
150
+			return self.cache['ticker']