Perfect for data teams, researchers, and analysts who need to programmatically analyze onchain data, build custom reports, and create automated analytics pipelines.
Let’s start by executing a query to analyze recent DEX trading volume:
from dune_client.client import DuneClientimport pandas as pd# Initialize clientdune = DuneClient(api_key="YOUR_API_KEY")# Execute SQL querysql = """SELECT blockchain, DATE_TRUNC('hour', block_time) as hour, SUM(amount_usd) as volume_usd, COUNT(*) as trade_countFROM dex.tradesWHERE block_time > now() - interval '24' hourGROUP BY 1, 2ORDER BY 2 DESC"""results = dune.run_sql(query_sql=sql)# Convert to pandas DataFrame for analysisdf = pd.DataFrame(results.result.rows)print(df.head())
# Step 1: Execute querycurl -X POST "https://api.dune.com/api/v1/sql/execute" \ -H "Content-Type: application/json" \ -H "X-Dune-Api-Key: YOUR_API_KEY" \ -d '{ "sql": "SELECT blockchain, DATE_TRUNC('\''hour'\'', block_time) as hour, SUM(amount_usd) as volume_usd, COUNT(*) as trade_count FROM dex.trades WHERE block_time > now() - interval '\''24'\'' hour GROUP BY 1, 2 ORDER BY 2 DESC", "performance": "medium" }'# Response includes execution_id# {"execution_id":"01JA...","state":"QUERY_STATE_EXECUTING"}# Step 2: Get results (after query completes)curl "https://api.dune.com/api/v1/execution/{execution_id}/results" \ -H "X-Dune-Api-Key: YOUR_API_KEY"
The run_sql() function in our Python SDK automatically handles query execution and polling for completion. With cURL, you’ll need to poll the execution status endpoint and then fetch results manually.
Server-side filtering with Dune’s SQL-like WHERE clause syntax is unique to Dune’s API! It saves bandwidth and processing time compared to filtering client-side.
Run analytics on a schedule (e.g., with cron, Airflow, or cloud scheduler):
import scheduleimport timefrom dune_client.client import DuneClientdune = DuneClient(api_key="YOUR_API_KEY")def hourly_report(): """Generate hourly DEX report""" sql = """ SELECT project, SUM(amount_usd) as hourly_volume FROM dex.trades WHERE block_time > now() - interval '1' hour GROUP BY 1 ORDER BY 2 DESC """ results = dune.run_sql(query_sql=sql) # Send to your dashboard/database/Slack send_to_dashboard(results.result.rows)# Run every hourschedule.every().hour.at(":00").do(hourly_report)while True: schedule.run_pending() time.sleep(60)
from dune_client.client import DuneClientimport timedune = DuneClient(api_key="YOUR_API_KEY")def monitor_large_trades(threshold=1000000): """Alert on large trades""" sql = f""" SELECT * FROM dex.trades WHERE block_time > now() - interval '5' minute AND amount_usd > {threshold} ORDER BY block_time DESC """ results = dune.run_sql(query_sql=sql) if results.result.rows: for trade in results.result.rows: send_alert(f"Large trade: ${trade['amount_usd']:,.2f} on {trade['blockchain']}")# Run continuouslywhile True: monitor_large_trades() time.sleep(300) # Check every 5 minutes