How to Pull DefiLlama TVL Data via API and Build Custom Dashboards
Step‑by‑step tutorial on accessing DefiLlama’s API, parsing TVL data, and visualizing it with popular dashboard tools.
How to Pull DeFiLlama TVL Data via API and Build Custom Dashboards
By a senior crypto‑finance analyst
---
Table of Contents
1. [Why TVL Matters in DeFi](#why-tvl-matters-in-defi)
2. [Getting Started with the DeFiLlama API](#getting-started-with-the-defillama-api)
3. [Parsing TVL Data in Python (or JavaScript)](#parsing-tvl-data-in-python-or-javascript)
4. [Choosing a Dashboard Tool: From Grafana to Power BI](#choosing-a-dashboard-tool-from-grafana-to-power‑bi)
5. [Building a Real‑Time TVL Dashboard](#building-a-real‑time-tvl-dashboard)
6. [Advanced Visualizations and Alerts](#advanced-visualizations-and-alerts)
7. [Putting It All Together: A Sample End‑to‑End Workflow](#putting-it-all-together-a-sample-end‑to‑end-workflow)
8. [FAQ](#faq)
---
Why TVL Matters in DeFi
Total Value Locked (TVL) is the most widely quoted metric for measuring the health of a decentralized finance (DeFi) protocol. TVL aggregates the market value of all assets deposited into a set of smart contracts. A higher TVL typically indicates greater user confidence, deeper liquidity, and more robust security incentives.
- Market Benchmark: As of Q2 2026, the global DeFi TVL reported by major aggregators hovers around $210 billion, a 7 % increase year‑over‑year.
- Risk Management: Institutional traders use TVL trends to gauge protocol exposure and adjust risk‑adjusted capital allocations.
- Competitive Analysis: Investors compare TVL growth rates across chains (Ethereum, BNB Smart Chain, Avalanche, etc.) to spot emerging opportunities.
Because TVL is a dynamic, high‑frequency data point, analysts need reliable, low‑latency access to the underlying numbers. DeFiLlama offers a public RESTful API that delivers TVL data in JSON format, making it ideal for automated pipelines and custom dashboards.
---
Getting Started with the DeFiLlama API
1. API Overview
DeFiLlama’s API is documented at https://api.llama.fi. The endpoint that returns the most current TVL snapshot is:
`
GET https://api.llama.fi/tvl
`
A sample response (truncated for brevity) looks like this:
`json
{
"totalLiquidityUSD": 212345678901,
"totalLiquidityUSD24hChange": "-1.23",
"chains": [
{
"chain": "Ethereum",
"tvl": 135000000000,
"tvlChange24h": "-0.56"
},
{
"chain": "BSC",
"tvl": 27000000000,
"tvlChange24h": "2.14"
}
// …more chains
],
"updatedAt": 1718235600
}
`
Key fields to note:
totalLiquidityUSD– the aggregated TVL across all supported chains, expressed in USD.totalLiquidityUSD24hChange– the percentage change over the prior 24‑hour window.chains– an array of per‑chain TVL data, useful for cross‑chain comparative dashboards.updatedAt– a Unix timestamp indicating the moment the data was refreshed (the API updates every 5 minutes).
2. Rate Limits and Authentication
The API is publicly accessible and does not require an API key for basic usage. However, DeFiLlama enforces a modest rate limit of 60 requests per minute per IP address. For production‑grade monitoring, you should implement a small request‑throttling layer (e.g., using time.sleep(1) between calls in a Python script).
If you need higher throughput—for example, pulling TVL data for every individual protocol—DeFiLlama offers a paid “Enterprise” tier that provides an authenticated endpoint and higher limits. The standard public tier is sufficient for most dashboard projects.
3. Data Reliability
DeFiLlama aggregates on‑chain data directly from block explorers and node providers, using a consensus algorithm that filters out outlier values. According to the 2026 audit by CryptoMetrics, the TVL numbers reported by DeFiLlama exhibit an average deviation of ±0.3 % compared with on‑chain verification tools. This level of accuracy is acceptable for most investment‑grade analytics.
---
Parsing TVL Data in Python (or JavaScript)
Below are two short code snippets that demonstrate how to fetch and parse the TVL payload. Choose the language that best aligns with your existing data pipeline.
1. Python Example (using requests and pandas)
`python
import requests
import pandas as pd
from datetime import datetime
Step 1 – Pull the raw JSON
response = requests.get("https://api.llama.fi/tvl")
response.raise_for_status()
data = response.json()
Step 2 – Extract top‑level fields
total_tvl_usd = data["totalLiquidityUSD"]
tvl_change_24h = float(data["totalLiquidityUSD24hChange"])
updated_ts = data["updatedAt"]
updated_dt = datetime.utcfromtimestamp(updated_ts)
Step 3 – Build a DataFrame for per‑chain TVL
chain_records = []
for chain in data["chains"]:
chain_records.append({
"chain": chain["chain"],
"tvl_usd": chain["tvl"],
"tvl_change_24h": float(chain["tvlChange24h"])
})
df_chains = pd.DataFrame(chain_records)
print(f"Global TVL: ${total_tvl_usd:,.0f} (Δ {tvl_change_24h}% 24h)")
print(f"Data refreshed at {updated_dt} UTC")
print(df_chains.head())
`
Explanation of Key Steps
- Error handling:
raise_for_status()throws an exception if the HTTP status is not 200, preventing silent failures in production. - Data conversion: The Unix timestamp is turned into a human‑readable UTC datetime for logging.
- Tabular format: Converting the
chainsarray into apandasDataFrame lets you perform quick aggregations (e.g., ranking the top‑5 chains by TVL).
2. JavaScript Example (Node.js with axios)
`javascript
const axios = require('axios');
async function fetchTVL() {
try {
const { data } = await axios.get('https://api.llama.fi/tvl');
const totalTVL = data.totalLiquidityUSD;
const change24h = parseFloat(data.totalLiquidityUSD24hChange);
const updated = new Date(data.updatedAt * 1000).toISOString();
console.log(Global TVL: $${totalTVL.toLocaleString()} (Δ ${change24h}% 24h));
console.log(Last updated: ${updated});
const chains = data.chains.map(c => ({
chain: c.chain,
tvl_usd: c.tvl,
tvl_change_24h: parseFloat(c.tvlChange24h)
}));
console.table(chains.slice(0, 5)); // Show top‑5 rows
} catch (err) {
console.error('Error fetching TVL:', err.message);
}
}
fetchTVL();
`
Both snippets return the same data structure, enabling you to plug the parsed output into any downstream visualization tool.
---
Choosing a Dashboard Tool: From Grafana to Power BI
When it comes to displaying real‑time TVL metrics, the choice of dashboard platform depends on three main factors:
1. Data Refresh Rate – Do you need sub‑minute updates (Grafana) or can you tolerate a 5‑minute lag (Power BI)?
2. Team Skill Set – Python‑centric teams may gravitate toward Superset or Redash, whereas business analysts often prefer Power BI or Tableau.
3. Deployment Model – Self‑hosted solutions (Grafana, Superset) give you full control of data privacy, while SaaS offerings (Datadog, Looker) handle scaling for you.
Below is a concise comparison of the most popular options for DeFi TVL dashboards.
| Tool | Licensing | Real‑Time Capability | Learning Curve | Recommended Use‑Case |
|------|-----------|----------------------|----------------|----------------------|
| Grafana | Open‑source (free tier) | Refresh intervals as low as 5 seconds | Moderate (requires Prometheus or InfluxDB) | Crypto traders who need live alerts |
| Power BI | Commercial (per user) | Refreshes via DirectQuery every 5 minutes (Premium) | Low (drag‑and‑drop UI) | Finance teams integrating TVL with traditional KPIs |
| Tableau | Commercial | 15‑minute schedule (Live) | Moderate | Business analysts needing deep drill‑down capabilities |
| Superset | Open‑source | 5‑minute refresh via SQL Lab | High (requires DB + SQL) | Data engineers building pipeline‑first dashboards |
| Datadog | SaaS, paid | 1‑minute metric ingestion | Low | Ops teams wanting unified monitoring of infra and DeFi metrics |
For a start‑up or solo developer, Grafana paired with a lightweight Prometheus exporter is the most straightforward path to a live TVL chart. If you already have a Microsoft ecosystem, Power BI can ingest the JSON payload through its “Web” connector and blend TVL with existing financial datasets.
---
Building a Real‑Time TVL Dashboard
Below we outline a practical workflow that produces a live DeFiLlama TVL dashboard on Grafana. The same principles apply to Power BI, Tableau, or any other platform.
Step 1 – Create a Prometheus Exporter
Prometheus scrapes metrics exposed over HTTP. Write a tiny exporter that queries the DeFiLlama API every 5 minutes and exposes the results as Prometheus metrics.
`python
exporter.py
import time
import requests
from prometheus_client import start_http_server, Gauge
TVL_GAUGE = Gauge('defillama_total_tvl_usd', 'Total TVL across all chains (USD)')
CHAIN_TVL_GAUGE = Gauge('defillama_chain_tvl_usd', 'TVL per chain (USD)', ['chain'])
def fetch_and_set_metrics():
resp = requests.get('https://api.llama.fi/tvl')
data = resp.json()
TVL_GAUGE.set(data['totalLiquidityUSD'])
for chain in data['chains']:
CHAIN_TVL_GAUGE.labels(chain=chain['chain']).set(chain['tvl'])
if __name__ == '__main__':
start_http_server(8000) # Expose metrics at http://localhost:8000/metrics
while True:
fetch_and_set_metrics()
time.sleep(300) # 5‑minute interval
`
Run the exporter in a Docker container or a system service. Prometheus will collect the metrics automatically.
Step 2 – Configure Prometheus
Add a scrape job to your prometheus.yml:
`yaml
scrape_configs:
- job_name: 'defillama_tvl'
static_configs:
- targets: ['localhost:8000']
``
Related guides
- Adding Telegram Alerts to Your Arbitrage Bot: A Complete Setup Guide
- Arbitrage Bot Development Basics for Crypto Traders
- Automated Crypto Arbitrage: Tools and Bots
- Automated Crypto Trading: How to Generate Passive Income with Python and AI
- Crypto Arbitrage App for Automatic Execution
- Crypto Arbitrage Scanner for Beginners
All guides · Coins · Exchanges