A crypto market analysis agent LangChain implementation needs two things: reliable market data and an LLM that can reason over it without hallucinating numbers. This tutorial builds a runnable agent that pulls top-asset stats from CoinGecko and uses a tool-calling LangChain agent to spot volatility, correlate moves, and output a structured brief.
Prerequisites
- Python 3.11 or newer
pip install langchain langchain-openai pandas python-dotenv requests- An API key for an OpenAI-compatible LLM endpoint. We’ll point LangChain at n4n.ai’s OpenAI-compatible endpoint so we get automatic fallback across providers and per-token metering.
- No CoinGecko API key; the public endpoint allows ~10–30 calls/min.
Create a .env file:
N4N_API_KEY=sk-your-key-here
Fetching market data
CoinGecko’s /coins/markets returns an array of assets with price, volume, and percentage changes. We trim the payload before sending it to the model—LLMs don’t need 50 fields to reason about outliers.
import json
import requests
def get_raw_markets(limit: int = 10) -> list:
url = "https://api.coingecko.com/api/v3/coins/markets"
params = {
"vs_currency": "usd",
"order": "market_cap_desc",
"per_page": limit,
"page": 1,
"price_change_percentage": "24h"
}
resp = requests.get(url, params=params, timeout=10)
resp.raise_for_status()
return resp.json()
if __name__ == "__main__":
raw = get_raw_markets(5)
print(json.dumps(raw[:1], indent=2))
Expected output (truncated):
[
{
"id": "bitcoin",
"symbol": "btc",
"name": "Bitcoin",
"current_price": 64210,
"market_cap": 1265000000000,
"total_volume": 28000000000,
"price_change_percentage_24h": 1.24
}
]
Defining the LangChain tool
Wrap the fetch in a LangChain tool so the agent can call it. Return a compact JSON string; the agent parses it internally.
from langchain_core.tools import tool
@tool
def fetch_market_data(limit: int = 10) -> str:
"""Fetch top crypto assets by market cap with 24h price change and volume.
Input: number of assets to return (default 10)."""
raw = get_raw_markets(limit)
slim = [{
"symbol": d["symbol"],
"name": d["name"],
"price": d["current_price"],
"mcap": d["market_cap"],
"vol": d["total_volume"],
"change_24h": d["price_change_percentage_24h"]
} for d in raw]
return json.dumps(slim)
Wiring the chat model
Use ChatOpenAI with the compatible base URL. Temperature 0 keeps the analysis deterministic.
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
load_dotenv()
llm = ChatOpenAI(
model="gpt-4o-mini",
api_key=os.getenv("N4N_API_KEY"),
base_url="https://api.n4n.ai/v1",
temperature=0
)
Building the agent
We use create_tool_calling_agent and AgentExecutor. The system prompt forbids the model from inventing numbers—it must use the tool.
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
prompt = ChatPromptTemplate.from_messages([
("system", "You are a crypto market analyst. Use the fetch_market_data tool for all numeric claims. "
"Never estimate prices. Output a concise bullet list with symbols, percentages, and volume."),
("human", "{input}"),
MessagesPlaceholder("agent_scratchpad")
])
agent = create_tool_calling_agent(llm, [fetch_market_data], prompt)
executor = AgentExecutor(
agent=agent,
tools=[fetch_market_data],
verbose=False,
max_iterations=3
)
Running the crypto market analysis agent LangChain
Invoke with a specific analytical question:
query = "List the top 3 gainers by 24h change among the top 20 assets. Flag any with volume > $1B."
result = executor.invoke({"input": query})
print(result["output"])
Sample output:
- WIF (dogwifhat): +14.2% in 24h, volume $1.34B
- PEPE: +9.8% in 24h, volume $0.92B
- BONK: +7.1% in 24h, volume $0.61B
Only WIF exceeds $1B volume. The move aligns with broader memcoin rotation; Bitcoin unchanged.
The agent called the tool with limit=20, parsed the JSON, sorted by change_24h, and applied the volume filter. No numbers came from the model’s weights.
Adding structured output for downstream use
If you need to feed the brief into a dashboard, add a second chain that parses the agent text into a schema. Use with_structured_output on the same LLM.
from pydantic import BaseModel, Field
class AssetMove(BaseModel):
symbol: str
change_24h: float
volume_usd: float
note: str
class MarketBrief(BaseModel):
movers: list[AssetMove] = Field(description="Top gainers identified")
commentary: str
structured_llm = llm.with_structured_output(MarketBrief)
brief = structured_llm.invoke(result["output"])
print(brief.model_dump_json(indent=2))
This yields JSON your backend can store without regex scraping.
Operational notes
Tool calls over public CoinGecko can hit rate limits. Wrap get_raw_markets in a simple retry with exponential backoff. When you route through n4n.ai, it forwards provider cache-control hints and meters per token, so you can attribute cost to each agent loop iteration rather than guessing.
Keep the agent’s max_iterations low. A crypto market analysis agent LangChain loop that calls the tool twice and then answers is cheap; one that spirals for ten steps wastes tokens reconciling the same JSON.
For production, cache the CoinGecko response for 60 seconds at the API layer. Market data is inherently laggy; there is no edge in fetching every second, and you’ll just get IP-banned.
Extending the agent
Swap the tool for a WebSocket feed if you need tick-level data, or add a second tool that pulls on-chain metrics from a paid API. The agent code stays identical—only the @tool function changes. That separation is the real win: the LLM handles reasoning, the tool handles ground truth.