Introduction
In the volatile world of cryptocurrency, real-time data can mean the difference between a profitable trade and a missed opportunity. Building automated tools that fetch, analyze, and act on market data has become essential for developers, traders, and enthusiasts alike. In this hands-on guide, we'll walk through building a real-time crypto intelligence agent by combining the CoinGecko API with Anthropic's Claude AI.
Why CoinGecko + Claude?
The CoinGecko API is one of the most widely used free APIs for cryptocurrency data — offering real-time prices, market caps, volumes, historical data, and more across thousands of coins. Claude, on the other hand, excels at reasoning, summarization, and tool use. Together, they let you build an agent that doesn't just display numbers — it interprets, explains, and recommends.
Key Use Cases
| Use Case | Description |
|---|---|
| Real-time Market Summaries | "Summarize today's top movers and why they're surging" |
| Portfolio Alerts | "Alert me if BTC drops below $60K and suggest a hedge" |
| Trading Signal Generation | "Based on the last hour's price action, should I buy or sell?" |
| Automated Reports | Generate daily crypto intelligence digests |
Prerequisites
- Python 3.8+
- Anthropic API key (console.anthropic.com)
- CoinGecko API key (optional; free tier: 50 calls/min)
-
requests,anthropic,python-dotenv
Step 1: Fetching Live Data from CoinGecko
CoinGecko's /simple/price endpoint is the workhorse. Here's a clean wrapper:
import requests
def get_crypto_price(crypto_id='bitcoin', vs_currency='usd'):
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
'ids': crypto_id,
'vs_currencies': vs_currency,
'include_market_cap': 'true',
'include_24hr_vol': 'true',
'include_24hr_change': 'true'
}
headers = {'accept': 'application/json'}
if COINGECKO_API_KEY:
headers['x-cg-demo-api-key'] = COINGECKO_API_KEY
resp = requests.get(url, params=params, headers=headers)
return resp.json() if resp.status_code == 200 else None
# Usage
btc = get_crypto_price('bitcoin')
print(f"BTC: ${btc['bitcoin']['usd']}")
Response structure:
{
"bitcoin": {
"usd": 67300,
"usd_market_cap": 1320000000000,
"usd_24h_vol": 28000000000,
"usd_24h_change": 2.35
}
}
Step 2: Giving Claude the Power to Fetch Prices (Tool Use)
Claude's tool use (function calling) feature lets it decide when to call an external API. We define a tool schema and let Claude orchestrate the call:
import anthropic
client = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)
price_tool = {
"name": "get_crypto_price",
"description": "Get live price, market cap, 24h volume and change for any crypto",
"input_schema": {
"type": "object",
"properties": {
"crypto_id": {
"type": "string",
"description": "CoinGecko ID, e.g. 'bitcoin', 'ethereum', 'solana'"
},
"currency": {
"type": "string",
"description": "Fiat currency, default 'usd'"
}
},
"required": ["crypto_id"]
}
}
The Agent Loop
def chat_with_crypto_agent(user_message):
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=messages,
tools=[price_tool]
)
if response.stop_reason == "tool_use":
# Claude wants to call our tool
block = next(b for b in response.content if b.type == "tool_use")
if block.name == "get_crypto_price":
data = get_crypto_price(
block.input["crypto_id"],
block.input.get("currency", "usd")
)
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": block.id,
"content": str(data)
}]
})
else:
return response.content[0].text
Try it:
print(chat_with_crypto_agent(
"What's Ethereum at right now, and how's it performing vs yesterday?"
))
Claude will detect the intent, call get_crypto_price('ethereum'), receive the data, and produce a natural-language response like:
"Ethereum is currently at $3,450, up 4.1% in the last 24 hours. Its market cap sits at $414 billion with $22 billion in 24h trading volume. That's a strong green day — the 4.1% gain suggests positive momentum, possibly driven by..."
Step 3: Building a Real-Time Price Cache
Hitting the API on every request wastes rate limits. Let's build a background price cache that refreshes every 30 seconds:
import threading, time
price_cache = {}
cache_lock = threading.Lock()
def fetch_prices_for_coins(coin_ids=['bitcoin','ethereum','solana']):
url = "https://api.coingecko.com/api/v3/simple/price"
params = {
'ids': ','.join(coin_ids),
'vs_currencies': 'usd',
'include_market_cap': 'true',
'include_24hr_vol': 'true',
'include_24hr_change': 'true'
}
headers = {'accept': 'application/json'}
if COINGECKO_API_KEY:
headers['x-cg-demo-api-key'] = COINGECKO_API_KEY
try:
resp = requests.get(url, params=params, headers=headers)
if resp.status_code == 200:
with cache_lock:
price_cache.clear()
price_cache.update(resp.json())
except Exception as e:
print(f"Cache update error: {e}")
def start_price_refresh(interval=30):
def loop():
while True:
fetch_prices_for_coins()
time.sleep(interval)
t = threading.Thread(target=loop, daemon=True)
t.start()
Now your agent responds in milliseconds — no API wait time.
Step 4: Adding Trending Coins & Market Breadth
CoinGecko's /search/trending endpoint reveals what's hot right now:
def get_trending():
url = "https://api.coingecko.com/api/v3/search/trending"
resp = requests.get(url, headers={'accept': 'application/json'})
coins = resp.json()['coins']
return [{
'name': c['item']['name'],
'symbol': c['item']['symbol'],
'market_cap_rank': c['item']['market_cap_rank'],
'score': c['item']['score']
} for c in coins[:7]]
Add this as a second tool in your Claude agent, and you can ask questions like:
"What are the top trending coins today? Give me a quick market pulse."
Step 5: Putting It All Together — A Production-Ready Agent
Here's the complete architecture:
┌─────────────┐ ┌─────────────────┐ ┌──────────────┐
│ User │────▶│ Claude Agent │────▶│ CoinGecko │
│ Question │ │ (Tool Router) │ │ API + Cache │
└─────────────┘ └─────────────────┘ └──────────────┘
│
┌───────▼───────┐
│ Natural │
│ Language │
│ Response │
└───────────────┘
Full code is ~150 lines. The agent can:
- Fetch live prices for any coin
- Report 24h changes, volume, market cap
- Surface trending coins
- Answer natural-language questions about the market
- Run with a background cache for sub-second responses
Beyond the Basics: Ideas to Extend
| Idea | Difficulty | Impact |
|---|---|---|
Add historical price charts via /market_chart
|
Medium | High |
| Implement price alerts ("ping me if SOL drops 5%") | Easy | High |
| Track your portfolio with P&L calculations | Medium | High |
| Add on-chain data via Etherscan/Solscan APIs | Hard | Very High |
| Auto-post market summaries to Twitter/Telegram | Easy | Medium |
| Multi-agent setup: one for data, one for analysis | Hard | Very High |
Conclusion
Combining CoinGecko's rich market data with Claude's reasoning capabilities creates a genuinely useful crypto intelligence agent in under 200 lines of Python. The free tiers of both services are generous enough for personal projects and prototyping.
The real power comes from Claude's tool-use — it knows when to fetch data and how to interpret it, so you don't need to build complex rule engines. This pattern (LLM + live data APIs) extends far beyond crypto: stock markets, weather, news, sports scores — anywhere real-time data meets natural language.
Start building:
What will you build with this pattern? Drop a comment below! 🚀
Top comments (0)