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:
Copy
Ask AI
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())
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.
from dune_client.client import DuneClientdune = DuneClient(api_key="YOUR_API_KEY")# Execute query with SQL-based filteringsql = """SELECT blockchain, project, SUM(amount_usd) as volume_usdFROM dex.tradesWHERE block_time > now() - interval '24' hour AND blockchain = 'ethereum' AND amount_usd > 1000000GROUP BY 1, 2ORDER BY 3 DESC"""results = dune.run_sql(query_sql=sql)# Results are already filtered server-sidefor row in results.result.rows: print(row)
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):
Copy
Ask AI
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