Skip to main content
⚠️ DeFi protocols carry smart contract risk and impermanent loss. TVL and yield data are informational only — not investment advice.
Crypto & DeFi · Part 3 of 5

DeFi Protocol Data

Track Total Value Locked, yield rates, and stablecoin health across hundreds of DeFi protocols using DeFiLlama's completely free API.

DeFiLlama API
No Key Required
Generous Rate Limits

DeFiLlama — The Free DeFi Data Standard

DeFiLlama is the gold standard for decentralized finance data aggregation. It tracks over 3,000 DeFi protocols across 100+ blockchain networks, indexing real-time TVL (Total Value Locked), yield opportunities, stablecoin market caps, and governance metrics—all available via a completely free, unauthenticated REST API.

Key advantages: No API key required, generous rate limits, historical data spanning years, and coverage of both established and emerging protocols across every major chain (Ethereum, Arbitrum, Polygon, Solana, Avalanche, and more).

Python: Connecting to DeFiLlama
import requests

LLAMA_BASE = "https://api.llama.fi"
YIELDS_BASE = "https://yields.llama.fi"

def llama_get(path: str, base: str = LLAMA_BASE) -> dict | list:
    """Fetch from DeFiLlama API."""
    resp = requests.get(f"{base}{path}", timeout=15)
    resp.raise_for_status()
    return resp.json()

# Quick test — total DeFi TVL
global_data = llama_get("/v2/charts")
latest = global_data[-1]
from datetime import datetime
dt = datetime.fromtimestamp(latest["date"])
print(f"Total DeFi TVL: ${latest['totalLiquidityUSD']/1e9:.2f}B ({dt.strftime('%Y-%m-%d')})")

Top Protocols by TVL

Explore which DeFi protocols are holding the most user capital. This ranking shifts constantly as yields, security incidents, and new features attract or repel liquidity providers.

Python: Fetch and Rank Top 20 Protocols
def get_top_protocols(limit: int = 20) -> list:
    """Fetch all protocols sorted by TVL."""
    protocols = llama_get("/protocols")
    # Sort by tvl descending
    protocols.sort(key=lambda x: x.get("tvl", 0), reverse=True)
    return protocols[:limit]

protocols = get_top_protocols(20)

print(f"{'Rank':<5} {'Protocol':<20} {'Category':<18} {'Chain':<12} {'TVL (USD)':>14}")
print("-" * 72)
for i, p in enumerate(protocols, 1):
    name = p["name"][:19]
    cat = p.get("category", "Unknown")[:17]
    chain = p.get("chain", "Multi")[:11]
    tvl = p.get("tvl", 0)
    print(f"{i:<5} {name:<20} {cat:<18} {chain:<12} ${tvl/1e9:>12.2f}B")

Output interpretation: Each protocol shows its current TVL in billions of USD. Decentralized exchanges (DEXs) like Uniswap and Aave dominate rankings, but lending, derivatives, and liquid staking protocols vary by season.

TVL History for a Specific Protocol

Monitor how a protocol's total value locked evolves over time. Track recovery from hacks, reaction to governance changes, or competition from new entrants.

Python: Historical TVL Trends
import pandas as pd

def get_protocol_tvl_history(protocol_slug: str) -> pd.DataFrame:
    """
    Fetch historical TVL for a protocol.
    Slug = lowercase name with hyphens (e.g., 'uniswap', 'aave', 'lido')
    """
    data = llama_get(f"/protocol/{protocol_slug}")
    tvl_data = data.get("tvl", [])

    df = pd.DataFrame(tvl_data)
    df["date"] = pd.to_datetime(df["date"], unit="s")
    df = df.rename(columns={"totalLiquidityUSD": "tvl_usd"})
    df = df[["date", "tvl_usd"]].sort_values("date")
    return df

# Compare Aave vs Uniswap TVL trend (last 30 days)
for protocol in ["aave", "uniswap"]:
    df = get_protocol_tvl_history(protocol)
    recent = df.tail(30)
    change = (recent.iloc[-1]["tvl_usd"] - recent.iloc[0]["tvl_usd"]) / recent.iloc[0]["tvl_usd"] * 100
    current_tvl = recent.iloc[-1]["tvl_usd"]
    print(f"{protocol.title():<12} TVL: ${current_tvl/1e9:.2f}B  | 30d change: {change:+.1f}%")

Real-world use: TVL trends reveal market confidence. A sudden drop often signals a security issue, governance crisis, or migration to competing protocols. Sustained growth indicates product-market fit and user trust.

Yield Rate Monitor

DeFiLlama's yields API surfaces the highest-yield liquidity pools across DeFi. Filter by TVL to avoid "rug pull" honeypots, and track impermanent loss (IL) risk for LP positions.

Python: Top-Yield Pools with TVL Filter
def get_top_yields(min_tvl_usd: float = 10_000_000, limit: int = 20) -> pd.DataFrame:
    """
    Find highest-yield pools with meaningful TVL.
    Filters out tiny/illiquid pools.
    """
    data = llama_get("/pools", base=YIELDS_BASE)
    pools = data["data"]

    # Filter and sort
    filtered = [
        p for p in pools
        if (p.get("tvlUsd", 0) >= min_tvl_usd
            and p.get("apy") is not None
            and p.get("apy", 0) > 0)
    ]
    filtered.sort(key=lambda x: x["apy"], reverse=True)

    rows = []
    for p in filtered[:limit]:
        rows.append({
            "protocol": p.get("project", ""),
            "pool":     p.get("symbol", ""),
            "chain":    p.get("chain", ""),
            "apy":      p.get("apy", 0),
            "apy_base": p.get("apyBase", 0) or 0,
            "apy_reward": p.get("apyReward") or 0,
            "tvl_m":    p.get("tvlUsd", 0) / 1e6,
            "il_risk":  p.get("ilRisk", "none"),
        })

    return pd.DataFrame(rows)

df = get_top_yields(min_tvl_usd=50_000_000)
print(df[["protocol","pool","chain","apy","tvl_m","il_risk"]].to_string(index=False))

Critical interpretation: APY includes base yields (from fees) and reward yields (from incentive tokens). High reward APY often signals unsustainable incentive programs. Always cross-check IL risk—impermanent loss can wipe out gains on volatile pairs.

Stablecoin Depeg Alert System

Monitor stablecoin prices in real time. When DAI, USDC, or USDT drift beyond their $1.00 peg, it signals market stress, liquidity shortages, or exchange rate imbalances that can cascade across DeFi.

Python: Depeg Detection & Alerts
def get_stablecoin_prices() -> list:
    """Fetch current prices for major stablecoins."""
    # DeFiLlama stablecoins endpoint
    data = llama_get("/stablecoins?includePrices=true")
    return data.get("peggedAssets", [])

def check_depeg(peg_tolerance: float = 0.005):  # 0.5% tolerance
    """Alert if any stablecoin depegs beyond tolerance."""
    stables = get_stablecoin_prices()
    alerts = []

    for stable in stables:
        name = stable.get("name", "")
        peg_type = stable.get("pegType", "")
        if "usd" not in peg_type.lower():
            continue  # Only check USD pegs

        # Current price (can be None if not available)
        price_data = stable.get("price")
        if price_data is None:
            continue

        # Price deviation from $1.00
        deviation = abs(price_data - 1.0)
        if deviation > peg_tolerance:
            direction = "ABOVE" if price_data > 1.0 else "BELOW"
            alerts.append({
                "name": name,
                "price": price_data,
                "deviation_pct": deviation * 100,
                "direction": direction,
            })
            print(f"🚨 DEPEG: {name} trading at ${price_data:.4f} "
                  f"({direction} peg by {deviation*100:.2f}%)")

    if not alerts:
        print(f"✅ All stablecoins within {peg_tolerance*100:.1f}% of peg")

    return alerts

# Run every 10 minutes
import time
while True:
    check_depeg(peg_tolerance=0.01)
    time.sleep(600)

What triggers depegs: Bank runs on reserve custodians (USDC, 2023), algorithmic design flaws (UST, 2022), or temporary liquidity crunches on smaller exchanges. A 0.5–1% tolerance catches early stress; tighten to 0.1% for precision trading.

Chain TVL Breakdown

Which blockchains dominate DeFi? Ethereum historically leads, but Polygon, Arbitrum, and Solana are rapidly closing the gap. Track market share shifts to identify emerging opportunities.

Python: TVL by Blockchain
def get_chain_tvl() -> pd.DataFrame:
    """Fetch TVL broken down by blockchain."""
    chains = llama_get("/v2/chains")
    chains.sort(key=lambda x: x.get("tvl", 0), reverse=True)

    rows = [{
        "chain": c["name"],
        "tvl_b": c.get("tvl", 0) / 1e9,
        "protocols": c.get("protocols", 0),
    } for c in chains[:15]]

    df = pd.DataFrame(rows)
    total = df["tvl_b"].sum()
    df["share_pct"] = df["tvl_b"] / total * 100

    print(f"{'Chain':<20} {'TVL ($B)':>10} {'Protocols':>12} {'Share':>8}")
    print("-" * 55)
    for _, row in df.iterrows():
        print(f"{row['chain']:<20} {row['tvl_b']:>9.2f}B {row['protocols']:>12} {row['share_pct']:>7.1f}%")
    return df

get_chain_tvl()

Strategic insights: Chains with higher TVL attract developers and users due to network effects. However, emerging chains with lower TVL but growing adoption can offer arbitrage and yield farming opportunities before the market saturates.

DeFiLlama API Endpoints Reference

Complete list of free, rate-limited endpoints for building DeFi data pipelines:

Base URL Endpoint Description
api.llama.fi /protocols All protocols with current TVL, category, chain
api.llama.fi /protocol/{slug} Historical TVL time series for one protocol
api.llama.fi /v2/chains TVL breakdown per blockchain
api.llama.fi /v2/charts Total DeFi TVL history over time
api.llama.fi /stablecoins Stablecoin market caps, supplies, and prices
yields.llama.fi /pools All yield pools with APY, TVL, IL risk, rebalance frequency
Rate Limiting Note: DeFiLlama doesn't publish strict rate limits, but recommend spacing requests 1–2 seconds apart in production. Use caching aggressively—TVL changes slowly, so cache /protocols for 1 hour and /v2/chains for 4 hours.

Building Reliable DeFi Data Pipelines

1. Error Handling & Retry Logic

Network timeouts happen. Implement exponential backoff and retry with a max of 3 attempts:

Python: Robust Requests with Retry
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

def create_session():
    session = requests.Session()
    retry = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503])
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('https://', adapter)
    return session

session = create_session()
resp = session.get("https://api.llama.fi/protocols", timeout=15)
data = resp.json()

2. Caching & Local Snapshots

Cache API responses in JSON files to avoid re-fetching. Timestamp snapshots for backtest-ing historical strategies:

Python: File-Based Caching
import json
from datetime import datetime

def cache_protocols(filename: str = "protocols_cache.json"):
    """Fetch and save protocols locally."""
    data = llama_get("/protocols")
    timestamp = datetime.utcnow().isoformat()
    cached = {"timestamp": timestamp, "data": data}
    with open(filename, "w") as f:
        json.dump(cached, f)
    return data

def load_cached_protocols(filename: str = "protocols_cache.json"):
    """Load from cache if available."""
    try:
        with open(filename) as f:
            cached = json.load(f)
        print(f"Loaded from {cached['timestamp']}")
        return cached["data"]
    except FileNotFoundError:
        return cache_protocols(filename)

3. Monitoring & Alerting

Set up email or webhook alerts for major TVL swings or stablecoin depegs. Combine with your favorite notification service (Discord, PagerDuty, Slack):

Data Quality Disclaimer: DeFiLlama aggregates from public sources and on-chain data. Some protocols may report inaccurate or inflated TVL. Cross-reference with official protocol dashboards and on-chain block explorers for critical decisions.