mcpField
C
coingecko-api

coingecko-api

github.com/agiprolabs数据与数据库456445 次安装8 周前更新
代码仓库

关于 coingecko-api

coingecko-api 是查询 CoinGecko 加密货币市场数据的技能,适用于宏观分析、代币研究和历史行情分析。它提供价格、图表、交易所数据、趋势与分类统计,并说明免费层的频率和数据限制。

主要功能

  1. 01当前价格与市值排名
  2. 02历史价格与 OHLC 数据
  3. 03全球市场统计
  4. 04趋势代币查询
  5. 05交易所与类别数据分析
  6. 06ID 映射及限流参考

适用场景

  1. 01比较交易所成交量和信任评分
  2. 02分析 BTC 主导率与市场总量
  3. 03研究代币历史回报与波动率
  4. 04查看 CoinGecko 近期趋势代币

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/agiprolabs/claude-trading-skills --skill coingecko-api

安装后在 Claude Code 中输入/coingecko-api确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
data_quality.md
endpoints.md
id_mapping.md
scripts/
fetch_market_data.py
historical_analysis.py

详细介绍

CoinGecko API 技能

查询 CoinGecko API,获取全面的加密货币市场数据——价格、历史图表、交易所交易量、热门代币、全球统计数据和类别细分。 免费套餐无需 API 密钥,支持每分钟 30 次调用。

何时使用此技能

  • 宏观分析:全球市值、BTC 主导率、总交易量趋势
  • 历史数据:可追溯多年的每日/每小时 OHLCV 数据(不支持分钟级数据)
  • 跨交易所对比:交易所交易量排名和信任评分
  • 热门趋势/发现:过去 24 小时内 CoinGecko 上的热门代币
  • 类别分析:比较 DeFi、L1 和 meme 币的市值
  • 代币研究:完整元数据,包括链接、描述和社区统计数据

如需 Solana DEX 实时数据、新代币发行,或 Solana 代币的日内数据粒度,请改用 Birdeye 或 DexScreener。

快速开始

获取当前价格
import httpx

# No API key needed for free tier
resp = httpx.get(
    "https://api.coingecko.com/api/v3/simple/price",
    params={"ids": "solana,bitcoin,ethereum", "vs_currencies": "usd",
            "include_24hr_change": "true"},
)
data = resp.json()
for coin, info in data.items():
    print(f"{coin}: ${info['usd']:.2f} ({info['usd_24h_change']:+.1f}%)")
获取市值排名靠前的代币
import httpx

resp = httpx.get(
    "https://api.coingecko.com/api/v3/coins/markets",
    params={"vs_currency": "usd", "order": "market_cap_desc",
            "per_page": 10, "page": 1, "sparkline": "false"},
)
for coin in resp.json():
    print(f"{coin['symbol'].upper():>6}  ${coin['current_price']:>10,.2f}  "
          f"MCap: ${coin['market_cap']/1e9:.1f}B  "
          f"24h: {coin['price_change_percentage_24h']:+.1f}%")
获取历史价格数据
import httpx
import pandas as pd

resp = httpx.get(
    "https://api.coingecko.com/api/v3/coins/solana/market_chart",
    params={"vs_currency": "usd", "days": "90", "interval": "daily"},
)
data = resp.json()
df = pd.DataFrame(data["prices"], columns=["timestamp", "price"])
df["date"] = pd.to_datetime(df["timestamp"], unit="ms")
df = df.set_index("date").drop(columns=["timestamp"])
print(df.describe())
获取 OHLC 蜡烛图数据
import httpx

resp = httpx.get(
    "https://api.coingecko.com/api/v3/coins/solana/ohlc",
    params={"vs_currency": "usd", "days": "30"},
)
# Returns [[timestamp, open, high, low, close], ...]
candles = resp.json()
for c in candles[-5:]:
    print(f"  O={c[1]:.2f}  H={c[2]:.2f}  L={c[3]:.2f}  C={c[4]:.2f}")
全球市场统计数据
import httpx

resp = httpx.get("https://api.coingecko.com/api/v3/global")
g = resp.json()["data"]
print(f"Total Market Cap:  ${g['total_market_cap']['usd']/1e12:.2f}T")
print(f"24h Volume:        ${g['total_volume']['usd']/1e9:.0f}B")
print(f"BTC Dominance:     {g['market_cap_percentage']['btc']:.1f}%")
print(f"Active Coins:      {g['active_cryptocurrencies']:,}")
热门代币
import httpx

resp = httpx.get("https://api.coingecko.com/api/v3/search/trending")
for item in resp.json()["coins"]:
    coin = item["item"]
    print(f"#{coin['market_cap_rank'] or '?':>4}  {coin['name']} ({coin['symbol']})")

身份验证

免费套餐无需 API 密钥(每分钟 30 次调用)。如需更高限额,请从 https://www.coingecko.com/en/api/pricing 获取 Pro 密钥并设置:

export COINGECKO_API_KEY="CG-xxxxxxxxxxxxxxxxxxxx"

Pro 请求使用不同的基础 URL 和标头:

import os, httpx

API_KEY = os.getenv("COINGECKO_API_KEY", "")
if API_KEY:
    BASE_URL = "https://pro-api.coingecko.com/api/v3"
    HEADERS = {"x-cg-pro-api-key": API_KEY}
else:
    BASE_URL = "https://api.coingecko.com/api/v3"
    HEADERS = {}

速率限制

免费套餐:每分钟 30 次请求。收到 429 响应时请实施退避机制:

import time, httpx

def cg_get(url: str, params: dict, max_retries: int = 3) -> dict:
    """GET with retry on rate limit."""
    for attempt in range(max_retries):
        resp = httpx.get(url, params=params, headers=HEADERS, timeout=15.0)
        if resp.status_code == 429:
            wait = 2 ** attempt * 10
            print(f"Rate limited, waiting {wait}s...")
            time.sleep(wait)
            continue
        resp.raise_for_status()
        return resp.json()
    raise RuntimeError("Max retries exceeded")

查找 CoinGecko 代币 ID

CoinGecko 使用 slug 风格的 ID(例如 solana、bitcoin、usd-coin)。如需通过合约地址或名称查找 ID,请参阅 references/id_mapping.md。

通过合约地址快速查询(适用于 Solana 代币):

import httpx

# Look up by Solana contract address
contract = "So11111111111111111111111111111111111111112"
resp = httpx.get(
    "https://api.coingecko.com/api/v3/coins/solana/contract/"
    + contract
)
coin = resp.json()
print(f"ID: {coin['id']}, Name: {coin['name']}")

主要限制

  • 非实时数据:免费套餐的价格每 1-2 分钟更新一次
  • Solana 覆盖有限:许多较新的 Solana 代币尚未收录
  • OHLC 粒度:仅支持 1/7/14/30/90/180/365 天的时间窗口;蜡烛图大小取决于时间窗口(参见 references/endpoints.md)
  • 历史数据缺失:部分代币在早期时段缺少数据
  • 免费套餐限流:每分钟 30 次请求,因此批量操作需要谨慎安排请求间隔

有关数据缺失和套餐差异的详细说明,请参阅 references/data_quality.md。

文件

参考文档
  • references/endpoints.md — 完整的端点参考,包含参数、响应架构和速率限制
  • references/id_mapping.md — 如何查找代币的 CoinGecko ID、合约地址映射和搜索技巧
  • references/data_quality.md — 数据质量说明、历史数据缺失情况以及免费与 Pro 套餐的差异
脚本
  • scripts/fetch_market_data.py — 获取市值排名靠前的代币、热门代币和全球统计数据(支持 --demo 模式)
  • scripts/historical_analysis.py — 获取历史 OHLCV 数据并计算收益率、波动率和回撤(支持 --demo 模式)

评论

支持 Markdown