0
# CoinMarketCap
1
2
Python wrapper around the coinmarketcap.com API (Version 2), enabling developers to easily retrieve cryptocurrency market data including listings, ticker information, and global market statistics. The library features built-in caching (120-second cache), support for multiple fiat and cryptocurrency conversions, and a clean object-oriented interface through the Market class.
3
4
## Package Information
5
6
- **Package Name**: coinmarketcap
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install coinmarketcap`
10
11
## Core Imports
12
13
```python
14
from coinmarketcap import Market
15
```
16
17
## Basic Usage
18
19
```python
20
from coinmarketcap import Market
21
22
# Initialize the market client with default settings
23
coinmarketcap = Market()
24
25
# Get all active cryptocurrency listings
26
listings = coinmarketcap.listings()
27
print(f"Found {len(listings['data'])} cryptocurrencies")
28
29
# Get top 10 cryptocurrencies by rank
30
top_10 = coinmarketcap.ticker(limit=10)
31
for crypto_id, data in top_10['data'].items():
32
print(f"{data['name']} ({data['symbol']}) - Rank: {data['rank']}")
33
34
# Get specific cryptocurrency by ID (Bitcoin = 1)
35
bitcoin = coinmarketcap.ticker(1)
36
btc_price = bitcoin['data']['quotes']['USD']['price']
37
print(f"Bitcoin price: ${btc_price}")
38
39
# Get global market statistics
40
stats = coinmarketcap.stats()
41
total_market_cap = stats['data']['quotes']['USD']['total_market_cap']
42
print(f"Total market cap: ${total_market_cap:,.0f}")
43
```
44
45
## Architecture
46
47
The package uses a caching strategy with SQLite backend through `requests_cache` to optimize API usage:
48
49
- **120-second cache expiry**: All API responses are cached for 2 minutes
50
- **Automatic cache management**: Cache files stored in temp directory by default
51
- **Session reuse**: Single HTTP session with proper headers for all requests
52
- **Error handling**: Graceful exception handling for network and parsing errors
53
54
## Capabilities
55
56
### Market Client
57
58
The main interface for accessing CoinMarketCap API endpoints with built-in request caching and error handling.
59
60
```python { .api }
61
class Market:
62
def __init__(
63
self,
64
base_url: str = "https://api.coinmarketcap.com/v2/",
65
request_timeout: int = 30,
66
tempdir_cache: bool = True
67
):
68
"""
69
Initialize Market client with API configuration.
70
71
Parameters:
72
- base_url (str): CoinMarketCap API base URL (default: v2 API)
73
- request_timeout (int): HTTP request timeout in seconds (default: 30)
74
- tempdir_cache (bool): Use system temp directory for cache (default: True)
75
"""
76
```
77
78
### Cryptocurrency Listings
79
80
Retrieve all active cryptocurrency listings with basic information for further querying.
81
82
```python { .api }
83
def listings(self) -> dict:
84
"""
85
Get all active cryptocurrency listings.
86
87
Returns:
88
dict: Response containing list of cryptocurrencies with id, name, symbol, website_slug
89
Exception: Returns Exception object on network or parsing errors
90
91
Note: Response includes 'cached' field indicating if data came from cache
92
"""
93
```
94
95
### Ticker Data
96
97
Retrieve cryptocurrency ticker data with pagination, sorting, and currency conversion options.
98
99
```python { .api }
100
def ticker(self, currency: str = "", **kwargs) -> dict:
101
"""
102
Get cryptocurrency ticker data with optional filtering and conversion.
103
104
Parameters:
105
- currency (str): Specific cryptocurrency ID to query (empty for all)
106
- start (int): Return results from rank [start] and above (default: 1)
107
- limit (int): Maximum results to return (default: 100, max: 100)
108
- convert (str): Currency conversion code
109
Fiat: AUD, BRL, CAD, CHF, CLP, CNY, CZK, DKK, EUR, GBP, HKD, HUF,
110
IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, NZD, PHP, PKR, PLN,
111
RUB, SEK, SGD, THB, TRY, TWD, ZAR
112
Crypto: BTC, ETH, XRP, LTC, BCH
113
- sort (str): Sort order - "id", "rank", "volume_24h", "percent_change_24h" (default: rank)
114
Note: "id" is recommended for pagination as it provides consistent ordering
115
- structure (str): Response structure format - "dictionary" or "array" (default: dictionary)
116
117
Returns:
118
dict: Response containing ticker data with pricing, market cap, volume info
119
Exception: Returns Exception object on network or parsing errors
120
121
Note: Response includes 'cached' field indicating if data came from cache
122
"""
123
```
124
125
### Global Market Statistics
126
127
Retrieve global cryptocurrency market data and statistics.
128
129
```python { .api }
130
def stats(self, **kwargs) -> dict:
131
"""
132
Get global cryptocurrency market statistics.
133
134
Parameters:
135
- convert (str): Currency conversion code (same options as ticker method)
136
137
Returns:
138
dict: Response containing global market data with total market cap, volume,
139
active cryptocurrencies count, Bitcoin dominance
140
Exception: Returns Exception object on network or parsing errors
141
142
Note: Response includes 'cached' field indicating if data came from cache
143
"""
144
```
145
146
## Usage Examples
147
148
### Currency Conversion
149
150
```python
151
# Get Bitcoin price in EUR
152
bitcoin_eur = coinmarketcap.ticker(1, convert='EUR')
153
eur_price = bitcoin_eur['data']['quotes']['EUR']['price']
154
print(f"Bitcoin price: €{eur_price:.2f}")
155
156
# Get global stats in multiple currencies
157
global_btc = coinmarketcap.stats(convert='BTC')
158
btc_market_cap = global_btc['data']['quotes']['BTC']['total_market_cap']
159
print(f"Total market cap: {btc_market_cap:.2f} BTC")
160
```
161
162
### Pagination and Sorting
163
164
```python
165
# Get cryptocurrencies ranked 11-20, sorted by 24h volume
166
page_2 = coinmarketcap.ticker(start=11, limit=10, sort='volume_24h')
167
168
# Get top 5 by 24h percentage change
169
top_gainers = coinmarketcap.ticker(limit=5, sort='percent_change_24h')
170
171
# Get data in array format instead of dictionary
172
array_data = coinmarketcap.ticker(limit=10, structure='array')
173
174
# Use ID sorting for consistent pagination (recommended)
175
consistent_page = coinmarketcap.ticker(start=1, limit=10, sort='id')
176
```
177
178
### Error Handling
179
180
```python
181
# The API methods can return Exception objects on error
182
try:
183
data = coinmarketcap.ticker(99999) # Invalid ID
184
if isinstance(data, Exception):
185
print(f"API error: {data}")
186
else:
187
print("Success:", data)
188
except Exception as e:
189
print(f"Network error: {e}")
190
191
# Alternative: Check for successful response structure
192
response = coinmarketcap.listings()
193
if not isinstance(response, Exception) and 'data' in response:
194
print(f"Found {len(response['data'])} cryptocurrencies")
195
else:
196
print("API call failed")
197
```