Cryptocurrency & DeFi Research Agent

Superhighway guides

Cryptocurrency and DeFi research is fragmented across dozens of sources — CoinGecko and CoinMarketCap for prices and market cap, Messari for asset profiles, DeFiLlama for Total Value Locked (TVL) and protocol revenue, Dune Analytics for on-chain dashboards, GitHub for developer activity, and a firehose of news for upgrades, governance votes, and security incidents. This guide builds a Python agent that pulls those public sources together and assembles a structured research briefing on any token, protocol, chain, or DeFi sector. It chains all four Superhighway endpoints — /research for deep synthesis of protocol mechanics and tokenomics, /search for market data and on-chain metrics, /scrape for a specific asset or protocol page, and /news for the last week of price moves, upgrades, and incidents — then hands everything to an LLM that emits a structured briefing as JSON.

This guide is for educational and research purposes only. It is not financial advice or investment advice. Cryptocurrency and DeFi markets are highly volatile, speculative, and largely unregulated. Always conduct your own research (DYOR) and consult a qualified financial advisor before making any investment decisions.

1. What you'll build

A Python agent that takes a crypto asset, protocol, chain, or DeFi sector and produces a structured research briefing:

2. Setup

pip install openai requests python-dotenv

Create a .env file with your two keys:

SUPERHIGHWAY_API_KEY=your_key_here
OPENAI_API_KEY=your_key_here

3. Research the asset or protocol

Start with /research, which pulls multi-source background into one synthesis — protocol mechanics, the consensus model, tokenomics and emission schedule, on-chain metrics, and ecosystem analysis. This is the grounding context for every later step.

import requests, os, json

SUPERHIGHWAY_KEY = os.getenv("SUPERHIGHWAY_API_KEY")
BASE = "https://superhighway.walls.sh"
HEADERS = {"Authorization": f"Bearer {SUPERHIGHWAY_KEY}"}

def research_asset(query: str) -> str:
    """Deep synthesis: protocol mechanics, tokenomics, on-chain metrics, ecosystem."""
    r = requests.get(
        f"{BASE}/research",
        params={"q": f"{query} cryptocurrency protocol tokenomics on-chain metrics ecosystem analysis"},
        headers=HEADERS,
    )
    data = r.json()
    return data.get("summary", "")[:3000]

4. Find market data and on-chain metrics

Two /search calls do the legwork. The first targets market data — price, market cap, volume, and circulating supply from CoinGecko, CoinMarketCap, and Messari. The second, scoped to the last week, targets on-chain metrics — TVL, protocol revenue, governance, and developer activity from DeFiLlama, Dune Analytics, and DefiPulse.

def find_market_data(query: str) -> list[dict]:
    """Market data: price, market cap, volume, circulating supply."""
    r = requests.get(
        f"{BASE}/search",
        params={
            "q": f"{query} cryptocurrency market data price market cap volume "
                 f"site:coingecko.com OR site:coinmarketcap.com OR site:messari.io",
        },
        headers=HEADERS,
    )
    return r.json().get("results", [])

def find_onchain_metrics(query: str) -> list[dict]:
    """On-chain metrics: TVL, protocol revenue, governance, developer activity."""
    r = requests.get(
        f"{BASE}/search",
        params={
            "q": f"{query} DeFi protocol TVL developer activity governance",
            "time": "week",
        },
        headers=HEADERS,
    )
    return r.json().get("results", [])

5. Scrape an asset or protocol page

/scrape turns one candidate URL into clean, LLM-ready markdown — a CoinGecko asset page, a DeFiLlama protocol page, or a Messari profile. This is where the agent pulls actual price tables, supply figures, and TVL numbers out of the page.

def scrape_page(url: str) -> dict:
    """Scrape an asset or protocol page for specific market and on-chain figures."""
    r = requests.post(
        f"{BASE}/scrape",
        json={"url": url, "mode": "markdown"},
        headers=HEADERS,
    )
    data = r.json()
    return {
        "url": url,
        "title": data.get("title", ""),
        "content": data.get("markdown", data.get("text", ""))[:2500],
    }

6. Get recent crypto news

/news, scoped to the last week, surfaces what just happened — price moves, protocol upgrades, governance votes, security incidents and exploits, exchange listings, funding rounds, and regulatory actions. In crypto this is often the layer that moves markets.

def get_news(query: str) -> list[dict]:
    """Recent price moves, upgrades, governance votes, incidents, listings, funding."""
    r = requests.get(
        f"{BASE}/news",
        params={"q": f"{query} cryptocurrency blockchain", "time": "week"},
        headers=HEADERS,
    )
    return r.json().get("results", [])

7. Generate the briefing with an LLM

Now hand everything to the LLM. The system prompt forbids inventing prices, supply figures, or TVL numbers and bars any investment recommendation — the agent summarizes what's in the sources and flags that figures need real-time verification. The output is structured JSON so it slots straight into a due-diligence memo or a market-monitoring dashboard. The disclaimer field is always populated with the full not-financial-advice text.

from openai import OpenAI

llm = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

DISCLAIMER = (
    "This is not financial advice or investment advice. Cryptocurrency and DeFi "
    "markets are highly volatile and speculative. Conduct your own research and "
    "consult a qualified financial advisor before making any investment decisions."
)

def generate_briefing(query: str, synthesis: str, market: list[dict],
                      onchain: list[dict], page: dict, news: list[dict]) -> dict | None:
    """Generate a structured crypto/DeFi research briefing as JSON."""

    market_text = "\n".join(
        f"- {r.get('title', '')}: {r.get('snippet', '')}" for r in market[:5]
    )
    onchain_text = "\n".join(
        f"- {r.get('title', '')}: {r.get('snippet', '')}" for r in onchain[:5]
    )
    news_text = "\n".join(
        f"- {n.get('title', '')}: {n.get('snippet', '')}" for n in news[:6]
    )
    page_text = f"{page.get('title', '')}: {page.get('content', '')}" if page else "N/A"

    response = llm.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": (
                    "You are a cryptocurrency and DeFi research analyst preparing a "
                    "briefing. Be specific and factual. Only use information from the "
                    "provided sources. Do not invent prices, supply figures, TVL, or "
                    "dates — if a detail isn't in the sources, say 'N/A'. Do NOT make "
                    "investment recommendations; you summarize public information, you "
                    "do not advise. The 'disclaimer' field must always contain the "
                    f"exact text: {DISCLAIMER}"
                ),
            },
            {
                "role": "user",
                "content": f"""Write a crypto/DeFi research briefing for: {query}

Synthesis (/research):
{synthesis[:2000]}

Market Data (CoinGecko / CMC / Messari):
{market_text}

On-Chain Metrics (DeFiLlama / Dune):
{onchain_text}

Scraped Page:
{page_text[:2000]}

Recent News (last 7 days):
{news_text}

Return JSON with exactly these fields (all required):
- asset_or_protocol: name being researched
- asset_type: "token" | "protocol" | "chain" | "defi-sector" | "nft-collection"
- market_overview: price, market cap, trading volume context (e.g. top-10 by market cap, $X bn TVL)
- technology_summary: consensus mechanism, key technical features, what problem it solves
- tokenomics: total supply, circulating supply, emission schedule, vesting cliffs, inflation/deflation mechanisms
- defi_metrics: TVL, protocol revenue, fee revenue, active users — say "N/A" if not a DeFi protocol
- ecosystem_activity: developer activity (commits, active repos), wallet growth, transaction volume trends
- competitive_landscape: key competitors or comparable protocols/assets
- recent_developments: last 7-day significant events — upgrades, partnerships, governance votes, security incidents, exchange listings
- risk_factors: smart contract risk, regulatory risk, liquidity risk, centralization risk, key-person risk
- data_quality: "high" | "medium" | "low" — based on coverage from /research and /search
- disclaimer: always the exact DISCLAIMER text""",
            },
        ],
        response_format={"type": "json_object"},
    )

    try:
        briefing = json.loads(response.choices[0].message.content)
        briefing["disclaimer"] = DISCLAIMER
        return briefing
    except (json.JSONDecodeError, KeyError):
        return None

8. The full research pipeline

Wire the steps together: research the asset, find market data and on-chain metrics, scrape the top result, pull news, then generate the briefing.

def research_crypto(query: str) -> dict | None:
    """Run the full crypto/DeFi research pipeline."""
    print(f"Researching: {query}")

    print("Synthesizing protocol and tokenomics...")
    synthesis = research_asset(query)

    print("Finding market data and on-chain metrics...")
    market = find_market_data(query)
    onchain = find_onchain_metrics(query)

    print("Scraping a relevant asset/protocol page...")
    page = {}
    for result in (market + onchain):
        url = result.get("url")
        if not url:
            continue
        page = scrape_page(url)
        if page.get("content"):
            break

    print("Pulling recent crypto news...")
    news = get_news(query)

    print("Generating briefing...")
    return generate_briefing(query, synthesis, market, onchain, page, news)

def print_briefing(b: dict):
    if not b:
        print("Could not generate briefing.")
        return
    print(f"\n{'='*60}")
    print(f"{b.get('asset_or_protocol', '?')}  ({b.get('asset_type', '?')})")
    print(f"Data quality: {b.get('data_quality', '?')}")
    print(f"{'='*60}")
    print(f"\nMarket Overview:\n{b.get('market_overview', '')}")
    print(f"\nTechnology:\n{b.get('technology_summary', '')}")
    print(f"\nTokenomics:\n{b.get('tokenomics', '')}")
    print(f"\nDeFi Metrics:\n{b.get('defi_metrics', '')}")
    print(f"\nEcosystem Activity:\n{b.get('ecosystem_activity', '')}")
    print(f"\nCompetitive Landscape:\n{b.get('competitive_landscape', '')}")
    print(f"\nRecent Developments:\n{b.get('recent_developments', '')}")
    print(f"\nRisk Factors:\n{b.get('risk_factors', '')}")
    print(f"\n{b.get('disclaimer', '')}")

if __name__ == "__main__":
    import sys
    query = sys.argv[1] if len(sys.argv) > 1 else "Uniswap"
    print_briefing(research_crypto(query))

9. Using Anthropic instead of OpenAI

The pipeline is provider-agnostic — only generate_briefing touches the LLM. To use Claude, swap the client. Everything else stays the same.

import anthropic, json

client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

def generate_briefing_claude(query, synthesis, market, onchain, page, news) -> dict | None:
    prompt = f"Write a crypto/DeFi research briefing for: {query}\n... (same content as above)"
    msg = client.messages.create(
        model="claude-sonnet-4-5",
        max_tokens=1500,
        system=(
            "You are a crypto/DeFi research analyst. Only use the provided sources. "
            "Do not invent figures; say 'N/A' when missing. Do NOT advise. "
            "Return ONLY a JSON object with the required fields, including a "
            f"'disclaimer' field set to: {DISCLAIMER}"
        ),
        messages=[{"role": "user", "content": prompt}],
    )
    try:
        briefing = json.loads(msg.content[0].text)
        briefing["disclaimer"] = DISCLAIMER
        return briefing
    except (json.JSONDecodeError, KeyError, IndexError):
        return None

10. Usage examples

11. Next steps

Reminder: this guide is for educational and research purposes only. It is not financial advice or investment advice. Cryptocurrency and DeFi markets are highly volatile, speculative, and largely unregulated. Always conduct your own research (DYOR) and consult a qualified financial advisor before making any investment decisions. Verify all prices, supply figures, and TVL numbers against real-time sources before acting.

12. Getting your API key

Grab a free Superhighway key at /pricing (1,000 calls/month, no credit card). For an agent that provisions its own access, skip the key entirely with x402: it pays $0.002 per call in USDC on Base — no signup, no key management. See the x402 pay-per-call guide for the wallet setup.

See also

The financial research agent applies the same four-endpoint pattern to equities and company fundamentals, and the M&A research agent uses it for deal and transaction due diligence.