CoinMarketCap是一个提供加密货币市场数据的平台,它提供API接口让开发者可以获取实时和历史加密货币数据。使用Python获取这些数据可以帮助你进行加密货币市场分析、价格监控或构建交易策略。
首先需要在CoinMarketCap官网注册账号并申请API密钥(有免费和付费版本)。
pip install requests pandas
import requests
import pandas as pd
def get_cmc_data(api_key, symbol='BTC', convert='USD'):
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
parameters = {
'symbol': symbol,
'convert': convert
}
try:
response = requests.get(url, headers=headers, params=parameters)
data = response.json()
if response.status_code == 200:
return data
else:
print(f"Error: {data['status']['error_message']}")
return None
except Exception as e:
print(f"Error fetching data: {e}")
return None
# 使用示例
api_key = 'your_api_key_here' # 替换为你的API密钥
data = get_cmc_data(api_key, 'BTC,ETH', 'USD')
if data:
# 将数据转换为DataFrame
df = pd.DataFrame.from_dict(data['data'], orient='index')
print(df[['name', 'symbol', 'quote']])
def get_crypto_list(api_key, limit=100):
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
parameters = {
'start': '1',
'limit': str(limit),
'convert': 'USD'
}
response = requests.get(url, headers=headers, params=parameters)
data = response.json()
if response.status_code == 200:
return data['data']
else:
print(f"Error: {data['status']['error_message']}")
return None
# 使用示例
crypto_list = get_crypto_list(api_key, 10)
if crypto_list:
for crypto in crypto_list:
print(f"{crypto['name']} ({crypto['symbol']}): ${crypto['quote']['USD']['price']:.2f}")
问题:免费API有请求次数限制(通常每分钟30次,每天100次) 解决方案:
问题:返回的JSON数据结构复杂 解决方案:
# 示例:提取特定字段
def extract_quote_data(data, symbol):
try:
crypto_data = data['data'][symbol]
quote = crypto_data['quote']['USD']
return {
'name': crypto_data['name'],
'symbol': crypto_data['symbol'],
'price': quote['price'],
'volume_24h': quote['volume_24h'],
'market_cap': quote['market_cap']
}
except KeyError:
print(f"Data for {symbol} not found")
return None
问题:API响应慢或超时 解决方案:
# 设置超时参数
response = requests.get(url, headers=headers, params=parameters, timeout=10)
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
print(f"Received data: {data}")
def on_error(ws, error):
print(f"Error: {error}")
def on_close(ws):
print("WebSocket closed")
def on_open(ws):
print("WebSocket opened")
# 订阅BTC和ETH的价格更新
subscribe_message = {
"method": "subscribe",
"id": "price",
"data": {
"cryptoIds": [1, 1027], # BTC和ETH的ID
"index": None
}
}
ws.send(json.dumps(subscribe_message))
# 使用示例
api_key = 'your_api_key_here'
ws_url = f"wss://stream.coinmarketcap.com/price/latest?CMC_PRO_API_KEY={api_key}"
ws = websocket.WebSocketApp(ws_url,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
def get_historical_data(api_key, symbol, time_start, time_end):
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/historical'
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key,
}
parameters = {
'symbol': symbol,
'time_start': time_start,
'time_end': time_end,
'interval': 'daily'
}
response = requests.get(url, headers=headers, params=parameters)
return response.json()
# 使用示例
historical_data = get_historical_data(api_key, 'BTC', '2023-01-01', '2023-01-31')
通过以上方法,你可以有效地使用Python从CoinMarketCap API获取加密货币数据,并根据需求进行各种分析和应用。