Skip to main content

Analytics Dashboard

Learn how to build powerful DeFi analytics dashboards using the Hoops Finance API. This guide shows you how to fetch platform metrics, pair statistics, and create visualizations for key DeFi insights.

Overview

This page covers:

  • Fetching platform-wide metrics (TVL, volume, fees)
  • Getting detailed pair statistics
  • Sorting and filtering data for dashboards
  • Basic visualization examples

Platform Metrics

Get Total TVL and Platform Fees

The /getmetrics endpoint provides comprehensive platform-wide data.

import requests
import json

def get_platform_metrics(period="24h"):
"""Fetch platform metrics for specified period"""
url = f"https://api.hoops.finance/getmetrics?period={period}"
response = requests.get(url)
response.raise_for_status()
return response.json()

# Usage
metrics = get_platform_metrics("24h")
print(f"Total TVL: ${metrics['tvl']:,.2f}")
print(f"24h Volume: ${metrics['volume24h']:,.2f}")
print(f"Total Fees: ${metrics['fees24h']:,.2f}")
print(f"Active Pairs: {metrics['activePairs']}")
Use Case

Great for: Dashboard overview cards, portfolio tracking, and platform health monitoring

Response Fields Explained

FieldDescriptionExample
tvlTotal Value Locked across all pools1234567.89
volume24h24-hour trading volume987654.32
fees24h24-hour fee revenue1234.56
activePairsNumber of active liquidity pairs150
totalPairsTotal number of pairs200

Pair Statistics

Get All Pairs with Statistics

def get_all_pairs_with_stats():
"""Fetch all pairs with their statistics"""
url = "https://api.hoops.finance/pairs"
response = requests.get(url)
response.raise_for_status()
return response.json()

def sort_pairs_by_volume(pairs, limit=10):
"""Sort pairs by 24h volume and return top pairs"""
sorted_pairs = sorted(pairs['pairs'],
key=lambda x: float(x.get('volume24h', 0)),
reverse=True)
return sorted_pairs[:limit]

# Usage
pairs = get_all_pairs_with_stats()
top_volume_pairs = sort_pairs_by_volume(pairs, 5)

for pair in top_volume_pairs:
print(f"{pair['token0Symbol']}/{pair['token1Symbol']}: "
f"${float(pair['volume24h']):,.2f} (24h volume)")
Use Case

Great for: Trading dashboards, volume analysis, and identifying trending pairs

Detailed Pair Statistics

Get Specific Pair Details

def get_pair_details(pair_contract):
"""Fetch detailed information for a specific pair"""
url = f"https://api.hoops.finance/pairs/{pair_contract}"
response = requests.get(url)
response.raise_for_status()
return response.json()

def get_pair_statistics(pair_contract):
"""Fetch statistics for a specific pair"""
url = f"https://api.hoops.finance/getstatistics?pairContract={pair_contract}"
response = requests.get(url)
response.raise_for_status()
return response.json()

# Usage
pair_address = "CAB6MICC2WKRT372U3FRPKGGVB5R3FDJSMWJL5XK6R3XWMJUCA4RJMXU"
pair_details = get_pair_details(pair_address)
pair_stats = get_pair_statistics(pair_address)

print(f"Pair: {pair_details['token0Symbol']}/{pair_details['token1Symbol']}")
print(f"TVL: ${float(pair_details['tvl']):,.2f}")
print(f"Fee: {pair_details['fee']}%")
print(f"24h Volume: ${float(pair_details['volume24h']):,.2f}")
Use Case

Great for: Individual pair analysis, detailed trading views, and portfolio tracking

Building a Complete Dashboard

Python Dashboard Example

import requests
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

class HoopsDashboard:
def __init__(self):
self.base_url = "https://api.hoops.finance"

def get_dashboard_data(self):
"""Fetch all data needed for dashboard"""
# Get platform metrics
metrics = requests.get(f"{self.base_url}/getmetrics?period=24h").json()

# Get all pairs
pairs = requests.get(f"{self.base_url}/pairs").json()

return {
'metrics': metrics,
'pairs': pairs['pairs']
}

def create_volume_chart(self, pairs, top_n=10):
"""Create a bar chart of top volume pairs"""
# Sort by volume and get top pairs
top_pairs = sorted(pairs, key=lambda x: float(x.get('volume24h', 0)), reverse=True)[:top_n]

fig = go.Figure(data=[
go.Bar(
x=[f"{p['token0Symbol']}/{p['token1Symbol']}" for p in top_pairs],
y=[float(p['volume24h']) for p in top_pairs],
name='24h Volume'
)
])

fig.update_layout(
title='Top Trading Pairs by Volume',
xaxis_title='Pair',
yaxis_title='Volume (USD)',
height=400
)

return fig

def generate_dashboard(self):
"""Generate complete dashboard"""
data = self.get_dashboard_data()

# Print summary metrics
print("=== HOOP FINANCE DASHBOARD ===")
print(f"Total TVL: ${data['metrics']['tvl']:,.2f}")
print(f"24h Volume: ${data['metrics']['volume24h']:,.2f}")
print(f"Active Pairs: {data['metrics']['activePairs']}")
print(f"Total Fees (24h): ${data['metrics']['fees24h']:,.2f}")

# Create volume chart
volume_chart = self.create_volume_chart(data['pairs'])
volume_chart.show()

# Usage
dashboard = HoopsDashboard()
dashboard.generate_dashboard()

JavaScript Dashboard Example

class HoopsDashboard {
constructor() {
this.baseUrl = 'https://api.hoops.finance';
}

async getDashboardData() {
try {
const [metricsResponse, pairsResponse] = await Promise.all([
fetch(`${this.baseUrl}/getmetrics?period=24h`),
fetch(`${this.baseUrl}/pairs`)
]);

if (!metricsResponse.ok || !pairsResponse.ok) {
throw new Error(`HTTP error! status: ${metricsResponse.status} or ${pairsResponse.status}`);
}

const [metrics, pairs] = await Promise.all([
metricsResponse.json(),
pairsResponse.json()
]);

return {
metrics: metrics,
pairs: pairs.pairs
};
} catch (error) {
console.error('Error fetching dashboard data:', error.message);
throw error;
}
}

generateSummary(data) {
console.log('=== HOOP FINANCE DASHBOARD ===');
console.log(`Total TVL: $${data.metrics.tvl.toLocaleString()}`);
console.log(`24h Volume: $${data.metrics.volume24h.toLocaleString()}`);
console.log(`Active Pairs: ${data.metrics.activePairs}`);
console.log(`Total Fees (24h): $${data.metrics.fees24h.toLocaleString()}`);
}

getTopVolumePairs(pairs, limit = 10) {
return pairs
.sort((a, b) => parseFloat(b.volume24h || 0) - parseFloat(a.volume24h || 0))
.slice(0, limit);
}

async generateDashboard() {
const data = await this.getDashboardData();
this.generateSummary(data);

const topPairs = this.getTopVolumePairs(data.pairs, 5);
console.log('\n=== TOP VOLUME PAIRS ===');
topPairs.forEach((pair, index) => {
console.log(`${index + 1}. ${pair.token0Symbol}/${pair.token1Symbol}: $${parseFloat(pair.volume24h).toLocaleString()}`);
});
}
}

// Usage
const dashboard = new HoopsDashboard();
dashboard.generateDashboard();

Visualization Libraries

Python:

  • Plotly - Interactive charts with web export
  • Matplotlib - Static charts for reports
  • Streamlit - Quick dashboard creation

JavaScript:

  • Chart.js - Simple, responsive charts
  • D3.js - Advanced custom visualizations
  • Recharts - React-based charting

Example: Chart.js Integration

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<canvas id="volumeChart" width="400" height="200"></canvas>

<script>
async function loadChartData() {
const response = await fetch('https://api.hoops.finance/pairs');
const data = await response.json();

const topPairs = data.pairs
.sort((a, b) => parseFloat(b.volume24h || 0) - parseFloat(a.volume24h || 0))
.slice(0, 10);

const ctx = document.getElementById('volumeChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: topPairs.map(p => `${p.token0Symbol}/${p.token1Symbol}`),
datasets: [{
label: '24h Volume (USD)',
data: topPairs.map(p => parseFloat(p.volume24h)),
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
});
}

loadChartData();
</script>
</body>
</html>

Next Steps

Rate Limiting

Remember to implement proper rate limiting in production applications. The API allows 120 requests per minute.