# About us & media kit
Source: https://docs.dexpaprika.com/about
Learn what DexPaprika does, our connection to CoinPaprika, and download our media kit with logos and icons.
## What we do
DexPaprika gives you clear, reliable DEX data -- in real time and historically -- so you can build with confidence. We bring together on-chain markets across major networks to power dashboards, trading systems, research, and AI agents.
* We're a team based in Poznań, Poland, with years of crypto data experience
* Our API gives fast access to tokens, pools, and DEX activity
* Developer-first docs, SDKs, and examples
* Consistent schema across supported blockchains
## Backed by CoinPaprika
DexPaprika is built by the team behind CoinPaprika -- a crypto data platform trusted since 2018. We started DexPaprika to offer a lightweight, purpose-built layer for DEX markets, backed by CoinPaprika’s reliability and uptime.
* Our parent company: [CoinPaprika](https://coinpaprika.com)
## Media kit
Download our branding kit with logos and icons for press and integration use.
* **Media pack**: [Download media\_pack.zip](https://dexpaprika.com/media_pack_dexpaprika.zip)
### FAQs
Yes. Our API is public--no API keys or registration required.
DexPaprika is built by the CoinPaprika team to focus specifically on on‑chain DEX markets.
Use the media pack above; it contains logos and icons for press/integrations.
# ChatGPT Actions integration
Source: https://docs.dexpaprika.com/ai-integration/chatgpt-actions
Integrate DexPaprika data with ChatGPT using OpenAPI actions for real-time crypto and DeFi data access directly in your conversations.
## Integration overview
Add DexPaprika’s OpenAPI as a ChatGPT Action to query networks, pools, tokens, and search within chats.
## What are ChatGPT Actions?
ChatGPT Actions allow you to connect ChatGPT to external APIs, enabling it to retrieve real-time data and perform actions beyond its training data. With DexPaprika's ChatGPT Actions integration, you can access live cryptocurrency and DeFi data directly within your ChatGPT conversations.
**Ready-to-use OpenAPI URL:** Visit [mcp.dexpaprika.com/openapi](https://mcp.dexpaprika.com/openapi) to get the pre-configured OpenAPI specification URL for immediate use with ChatGPT Actions.
## Prerequisites
* **ChatGPT Plus or Enterprise subscription** - Actions are only available for paid ChatGPT users
* Access to **ChatGPT's custom GPT creation** interface
* Basic understanding of API integrations (helpful but not required)
***
## Step-by-Step setup guide
### Step 1: Create a new Custom GPT
1. **Log in to ChatGPT** and navigate to your dashboard
2. **Click "Explore"** in the sidebar
3. **Select "Create a GPT"** from the top of the page
4. **Choose "Configure"** tab for manual setup
### Step 2: Configure your GPT
Fill in the basic information for your custom GPT:
* **Name**: `DexPaprika Crypto Assistant`
* **Description**: `Get real-time cryptocurrency and DeFi data across 33 blockchain networks`
* **Instructions**:
```
You are a cryptocurrency and DeFi data assistant powered by DexPaprika. You can access real-time data about:
- Blockchain networks and their supported DEXes
- Liquidity pools and their metrics (TVL, volume, fees)
- Token prices and market data
- DEX trading activity and analytics
- Cross-chain comparisons and analysis
Always provide accurate, up-to-date information and explain complex DeFi concepts clearly. When showing pool data, include relevant metrics like TVL, 24h volume, and fee tiers when available.
```
### Step 3: Add the DexPaprika Action
1. **Scroll down to the "Actions" section**
2. **Click "Create new action"**
3. **Get the OpenAPI URL** from [mcp.dexpaprika.com/openapi](https://mcp.dexpaprika.com/openapi)
4. **Import the schema**:
* Select **"Import from URL"**
* Paste the OpenAPI URL: `https://mcp.dexpaprika.com/openapi`
* Click **"Import"**
The OpenAPI specification will automatically configure all available DexPaprika endpoints, including networks, pools, tokens, and search functionality.
### Step 4: Configure action settings
1. **Authentication**: Select "None" (DexPaprika API is publicly accessible)
2. **Privacy policy**: Add `https://dexpaprika.com/terms/` if required
3. **Action description**: The description will be auto-filled from the OpenAPI spec
### Step 5: Test and Publish
1. **Click "Test"** to verify the integration works
2. **Try a sample query**: "What are the top 5 liquidity pools on Ethereum?"
3. **Click "Save"** when everything works correctly
4. **Choose visibility**: Keep private or share with others
***
## Usage examples
Once your ChatGPT Action is set up, you can ask questions like:
### Network and DEX queries
* "Which blockchain networks does DexPaprika support?"
* "What are the top DEXes on Solana by trading volume?"
* "Show me all available DEXes on Arbitrum"
### Pool analysis
* "What are the most liquid USDC/ETH pools across all networks?"
* "Find the highest volume pools on Uniswap V3"
* "Compare fees between different USDT/USDC pools"
### Token information
* "What's the current price of SOL across different DEXes?"
* "Show me all pools containing PEPE token"
* "Get detailed information about Chainlink token on Ethereum"
### Market research
* "Find newly created pools with high trading volume"
* "What's the total trading volume on PancakeSwap today?"
* "Compare liquidity between Ethereum and Polygon networks"
### Advanced analytics
* "Analyze arbitrage opportunities between Uniswap and SushiSwap"
* "Show me pools with unusual price movements in the last 24 hours"
* "Find the most profitable liquidity provision opportunities"
**Want to explore more?** Visit [mcp.dexpaprika.com](https://mcp.dexpaprika.com) to test the interface, check out our [tutorials](/tutorials/tutorial_intro) for step-by-step guides, or browse the [API documentation](/api-reference/introduction) for technical details.
***
## Troubleshooting
**Solutions**:
1. Verify the OpenAPI URL is correctly imported: `https://mcp.dexpaprika.com/openapi`
2. Check that your ChatGPT subscription includes Actions (Plus or Enterprise)
3. Try recreating the Action if import failed
4. Ensure no typos in the OpenAPI URL
**Solutions**:
1. Be more specific in your queries (include network names, token symbols)
2. Try different phrasings for your questions
3. Check if the requested data exists (some networks/tokens may have limited pools)
**Solutions**:
1. Break complex queries into smaller, focused questions
2. Ask for specific data rather than broad overviews
3. Be patient - real-time data fetching may take a few seconds
***
## What's next?
Explore all available endpoints and their capabilities
Try our Model Context Protocol integration for Claude
Zero-setup MCP integration for Claude and Cursor
Learn how to discover newly created liquidity pools
## Need Help?
Connect with our community for real-time support
Contact our team for technical assistance
**Custom integrations needed?** Our team can help you build advanced ChatGPT Actions tailored to your specific use cases. [Contact us](mailto:support@coinpaprika.com) to discuss your requirements.
### FAQs
No. Set authentication to None; DexPaprika API is public.
Use “Import from URL” with `https://mcp.dexpaprika.com/openapi` so endpoints stay in sync.
Include the `network` and, when relevant, a `token` or `pool_address` to reduce ambiguity.
# Integrating Documentation with Cursor IDE
Source: https://docs.dexpaprika.com/ai-integration/cursor-ide-integration
Learn how to integrate DexPaprika documentation and MCP server directly into Cursor IDE for enhanced development workflows with real-time crypto data access.
## Integration overview
Connect Cursor IDE to DexPaprika via the hosted MCP server and add docs for rich AI context.
## What is Cursor IDE?
Cursor is a powerful AI-first code editor built on top of VS Code that provides advanced AI assistance for developers. With its built-in Claude integration and MCP (Model Context Protocol) support, Cursor can access external data sources and documentation to provide more intelligent coding assistance.
## Why integrate DexPaprika with Cursor?
Integrating DexPaprika documentation and data with Cursor IDE provides several powerful benefits:
* **Real-time crypto data access** - Get live market data, pool information, and token prices while coding
* **Enhanced AI assistance** - Cursor's AI can reference DexPaprika documentation and data for better code suggestions
* **DeFi development workflow** - Build DeFi applications with direct access to comprehensive blockchain data
* **Documentation context** - AI can reference our API docs, tutorials, and examples while helping you code
***
## Step 1: Install MCP server with one click
The easiest way to get started is using our "Connect to Cursor" button that opens Cursor IDE for MCP server installation.
1. Look for the **"Connect to Cursor"** button in our documentation
2. This button is available on relevant pages throughout our docs
3. Click the button to open Cursor IDE
1. The button will open Cursor IDE (if not already open)
2. In the MCP server configuration dialog, enter the DexPaprika MCP server URL:
```
https://mcp.dexpaprika.com/sse
```
3. Click "Install" to complete the setup
4. Restart Cursor if prompted to complete the setup
1. Open a new chat with Claude in Cursor (Cmd/Ctrl + L)
2. Ask a question like: "What are the top liquidity pools on Ethereum?"
3. You should see DexPaprika data being retrieved and displayed
4. Try asking about specific networks, tokens, or pools to test the integration
**Can't find the button?** The "Connect to Cursor" button appears on pages where MCP integration is relevant. If you don't see it, you can also manually configure the MCP server using the method below.
## Step 2: Add documentation context
Once you have the MCP server installed, enhance your development experience by adding our documentation to your Cursor workspace for full API reference indexing.
1. In Cursor, go to **Settings** (Cmd/Ctrl + ,)
2. Navigate to **Indexing & Docs** in the left sidebar
3. This section allows you to add custom documentation for AI context
1. In the **Docs** section, click **"+ Add Doc"**
2. Fill out the documentation details:
* **Name**: "DexPaprika API Reference"
* **URL**: `https://docs.dexpaprika.com/api-reference/introduction`
3. Click **"Add"** to complete the setup
4. This will index our full API reference for AI context
**Pro tip:** Using the URL `https://docs.dexpaprika.com/api-reference/introduction` ensures Cursor indexes our complete API reference, giving you access to all endpoints, parameters, and examples in your AI conversations.
## Manual MCP server configuration
If you can't find the "Connect to Cursor" button or prefer manual setup, you can configure the MCP server manually by following our [hosted MCP server guide](/ai-integration/hosted-mcp-server).
**Need help with manual setup?** Our hosted MCP server guide provides detailed instructions for configuring the DexPaprika MCP server in Cursor, Claude Desktop, and other MCP-compatible tools.
***
## Available features
Once integrated, you can access comprehensive DexPaprika functionality within Cursor:
### Real-time data access
* **Network information** - Get details about supported blockchain networks
* **DEX data** - Access decentralized exchange information and metrics
* **Pool analytics** - Real-time liquidity pool data, volumes, and fees
* **Token information** - Current prices, market data, and token details
* **Search functionality** - Find tokens, pools, and DEXes across networks
### Documentation context
* **API reference** - Complete endpoint documentation and examples
* **SDK guides** - Language-specific integration tutorials
* **Best practices** - Coding patterns and optimization tips
* **Troubleshooting** - Common issues and solutions
***
## Usage examples
### Example 1: Building a DeFi dashboard
Ask Cursor to help you build a DeFi dashboard with real-time data:
```
"Help me create a React component that displays the top 5 liquidity pools
on Ethereum using the DexPaprika API. Include volume, TVL, and price data."
```
Cursor can now:
* Reference our API documentation for correct endpoint usage
* Provide real-time pool data for testing
* Suggest optimal data fetching patterns
* Help with error handling and loading states
### Example 2: Token price monitoring
Create a price monitoring application:
```
"Build a Python script that monitors SOL token prices across different
DEXes and alerts when there are significant price differences."
```
Cursor can:
* Access real-time SOL price data from multiple DEXes
* Reference our historical data tutorials
* Suggest efficient polling strategies
* Help implement price comparison logic
### Example 3: Pool discovery bot
Develop a new pool discovery system:
```
"Create a Node.js application that finds newly created liquidity pools
with high trading volume and sends notifications."
```
Cursor can:
* Use our pool discovery endpoints
* Reference our "Find New Pools" tutorial
* Provide real-time pool data for testing
* Help with notification system implementation
***
***
## Troubleshooting
**Symptoms**: Cursor shows connection errors or timeouts.
**Solutions**:
1. Verify internet connection is stable
2. Check that the MCP server URL is correct: `https://mcp.dexpaprika.com/sse`
3. Restart Cursor completely
4. Try removing and re-adding the MCP server configuration
5. Check Cursor's console for detailed error messages
**Symptoms**: Cursor's AI doesn't reference DexPaprika documentation.
**Solutions**:
1. Ensure documentation files are in your workspace
2. Enable "Use workspace files as context" in AI settings
3. Try asking more specific questions about our API
4. Restart Cursor to refresh context
**Symptoms**: Cursor takes a long time to respond with DexPaprika data.
**Solutions**:
1. Check your internet connection speed
2. Try breaking complex queries into smaller parts
3. Use specific network/token names in your queries
4. Consider using the hosted MCP server for better performance
**Symptoms**: Getting authentication or permission errors.
**Solutions**:
1. DexPaprika API is publicly accessible - no authentication required
2. Check if your network has firewall restrictions
3. Try using the hosted MCP server instead of local installation
4. Contact support if issues persist
***
## Best practices
### For optimal performance
1. **Use specific queries** - Instead of "show me all pools", ask for "top 5 USDC/ETH pools on Ethereum"
2. **Cache frequently used data** - Store common queries locally to reduce API calls
3. **Handle errors gracefully** - Implement proper error handling for network issues
4. **Monitor rate limits** - Be mindful of API usage patterns
### For better AI assistance
1. **Provide context** - Tell Cursor what you're building and your goals
2. **Reference documentation** - Ask Cursor to explain concepts from our docs
3. **Iterate on solutions** - Ask follow-up questions to refine the code
4. **Test with real data** - Use actual DexPaprika data in your development
***
## What's next?
Explore all available endpoints and their capabilities
Learn how to use our official SDKs in your projects
Discover newly created liquidity pools and tokens
Access and analyze historical price and volume data
Zero-setup MCP integration for instant access
Integrate DexPaprika data with ChatGPT
## Need Help?
Connect with our community for real-time support and discussions
Contact our team for technical assistance and custom integrations
**Building something amazing?** Share your Cursor + DexPaprika integrations with our community! We love seeing what developers build with our tools. [Reach out](mailto:support@coinpaprika.com) to showcase your work.
### FAQs
Manually add `https://mcp.dexpaprika.com/sse` via Cursor settings → Tools & Integrations → New MCP server.
Add `https://docs.dexpaprika.com/api-reference/introduction` under Indexing & Docs and enable workspace context.
Restart Cursor, re‑add the server, and verify the URL; check the developer console for detailed errors.
# DexPaprika Hosted MCP Server
Source: https://docs.dexpaprika.com/ai-integration/hosted-mcp-server
Access real-time DeFi data in Claude, Cursor, and other MCP-compatible tools without any installation or setup. Our hosted MCP server provides instant access to comprehensive DEX data across 33 blockchains.
## Integration overview
Use the hosted MCP server URL to enable streaming DeFi data in Claude, Cursor, and other MCP clients.
Having trouble connecting? We're here to help - [reach out](mailto:support@coinpaprika.com) and we'll get you up and running.
## Why use our hosted MCP server?
Skip the installation hassle and get instant access to comprehensive DeFi data. Our hosted MCP server eliminates setup complexity while providing enterprise-grade reliability and performance.
**What you get instantly:**
* **Zero setup required** - just add the URL to your config
* **Multiple transport options** - SSE, streamable HTTP, and JSON-RPC support
* **Always up-to-date** - we handle updates and maintenance
* **Enterprise reliability** - High availability and performance
* **Real-time data** - live prices, volumes, and pool information
* **33 blockchain networks** - Ethereum, Solana, Base, Arbitrum, and more
Visit [mcp.dexpaprika.com](https://mcp.dexpaprika.com) to explore our hosted MCP server interface and see the available data before integrating.
***
## Quick integration guide
### Claude desktop setup
Add our hosted MCP server to Claude Desktop in just 2 steps:
Find your Claude Desktop configuration file:
* **macOS**: `~/Library/Application\ Support/Claude/claude_desktop_config.json`
* **Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
* **Linux**: `~/.config/Claude/claude_desktop_config.json`
If the file doesn't exist, create it with this content:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"url": "https://mcp.dexpaprika.com/sse"
}
}
}
```
If the file already exists, add our server to the existing `mcpServers` object:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"url": "https://mcp.dexpaprika.com/sse"
}
}
}
```
Save the file and restart Claude Desktop. You're ready to go!
### Cursor setup
1. Open Cursor IDE
2. Go to **Settings** (Cmd/Ctrl + ,)
3. Navigate to **Tools & Integrations**
4. Click **New MCP server**
This will open the `mcp.json` file. Add the DexPaprika server configuration:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"url": "https://mcp.dexpaprika.com/sse"
}
}
}
```
Save the file and restart Cursor if needed.
### ChatGPT integration
Want to use DexPaprika data in ChatGPT? You can integrate our API directly into ChatGPT using Actions:
1. **Create a custom GPT** in ChatGPT (requires Plus or Enterprise subscription)
2. **Add our OpenAPI specification** from [mcp.dexpaprika.com/openapi](https://mcp.dexpaprika.com/openapi)
3. **Start asking crypto questions** directly in your ChatGPT conversations
**Ready to set up ChatGPT?** Follow our complete [ChatGPT Actions integration guide](/ai-integration/chatgpt-actions) for step-by-step instructions.
***
## Connection options
Our hosted MCP server supports multiple transport protocols to ensure compatibility with different clients and use cases:
**Endpoint:** `https://mcp.dexpaprika.com/sse`
**Best for:** Claude Desktop, Cursor, and most MCP clients\
**Benefits:** Real-time streaming updates, excellent browser compatibility, automatic reconnection\
**Use cases:** Live price monitoring, real-time pool updates, continuous market data feeds
This is the recommended option for most users as it provides the smoothest experience with popular AI tools.
**Endpoint:** `https://mcp.dexpaprika.com/streamable-http`
**Best for:** Custom applications, web services, and clients that prefer HTTP streaming\
**Benefits:** Standard HTTP protocol, works well with firewalls, easier debugging\
**Use cases:** Integration with existing web infrastructure, corporate environments with strict network policies
Perfect for developers building custom integrations or working in environments where SSE might be restricted.
**Endpoint:** `https://mcp.dexpaprika.com/json-rpc`
**Best for:** Traditional API integrations, batch processing, simple request-response patterns\
**Benefits:** Familiar REST-like interface, stateless communication, easy to cache\
**Use cases:** Periodic data fetching, batch analysis, integration with existing JSON-RPC systems
Ideal for applications that don't need real-time updates and prefer traditional API communication patterns.
**Getting started?** Use the SSE endpoint (`https://mcp.dexpaprika.com/sse`) for the best experience with Claude Desktop and Cursor. You can always switch protocols later based on your specific needs.
**Need help choosing?** Visit [mcp.dexpaprika.com](https://mcp.dexpaprika.com) to test different connection methods and see which works best for your setup.
***
## Available features
Our hosted MCP server provides comprehensive access to DeFi data:
### Core data access
* **Multi-chain support** - 33 blockchain networks including Ethereum, Solana, Base, Arbitrum, Polygon, and more
* **Real-time prices** - Live token prices and market data
* **Liquidity pools** - Detailed pool information, volumes, and fees
* **DEX analytics** - Trading data across major decentralized exchanges
* **Search functionality** - Find tokens, pools, and DEXes across all networks
New: Batch token pricing via [`GET /networks/{network}/multi/prices`](/api-reference/tokens/get-batched-token-prices-on-a-network) for efficient multi‑token lookups (up to 10 tokens per request).
### Advanced analytics
* **Historical data** - Price history and trading volumes over time
* **Pool monitoring** - Track new pool creation and liquidity changes
* **Cross-chain comparisons** - Compare prices and liquidity across different networks
* **Volume analysis** - Trading volume trends and patterns
***
## Usage examples
Once configured, you can ask Claude or Cursor powerful questions about DeFi data:
### Example queries you can make
| Category | Example Query |
| --------------------------- | ------------------------------------------------------------------------------------------- |
| **Basic market data** | "What are the top 5 liquidity pools by volume today?" |
| **Network information** | "Which blockchain networks does DexPaprika support?" |
| **Token prices** | "What's the current price of SOL across different DEXes?" |
| **Pool analysis** | "Show me the most liquid USDC/ETH pools across all networks and compare their trading fees" |
| **New opportunities** | "Find newly created liquidity pools in the last 24 hours with volume over \$100k" |
| **Cross-chain comparison** | "Compare ETH prices between Ethereum mainnet and Layer 2 solutions like Arbitrum and Base" |
| **DEX performance** | "Which DEX has the highest trading volume on Solana today?" |
| **Token discovery** | "Search for meme tokens with high trading volume in the last hour" |
| **Arbitrage opportunities** | "Find price differences for USDC across different DEXes on Ethereum" |
**Want to explore more?** Visit [mcp.dexpaprika.com](https://mcp.dexpaprika.com) to test the interface, check out our [tutorials](/tutorials/tutorial_intro) for step-by-step guides, or browse the [API documentation](/api-reference/introduction) for technical details.
***
## Benefits over self-hosted solutions
| Feature | Hosted MCP | Self-Hosted MCP |
| --------------- | -------------------- | ------------------------------ |
| **Setup time** | \< 2 minutes | 15-30 minutes |
| **Maintenance** | Zero - we handle it | Regular updates required |
| **Reliability** | High availability | Depends on your infrastructure |
| **Performance** | Optimized hosting | Limited by your server |
| **Updates** | Automatic | Manual intervention |
| **Support** | Professional support | Community only |
***
## Troubleshooting
### Common issues and solutions
**Symptoms**: Claude shows connection errors or timeouts when making requests.
**Solutions**:
1. Check your internet connection
2. Restart Claude Desktop/Cursor
3. Verify the configuration syntax in your config file
4. Try removing and re-adding the server configuration
**Symptoms**: Can't locate the Claude Desktop configuration file.
**Solutions**:
1. Create the directories if they don't exist:
* **macOS**: `mkdir -p ~/Library/Application\ Support/Claude/`
* **Windows**: Create the `Claude` folder in your `%APPDATA%` directory
2. Create the `claude_desktop_config.json` file manually
3. Ensure proper JSON syntax
**Symptoms**: The DexPaprika server doesn't appear in Claude's available tools.
**Solutions**:
1. Verify JSON syntax in your configuration file
2. Restart Claude Desktop completely
3. Check that the server URL is correct: `https://mcp.dexpaprika.com/sse`
4. Try removing and re-adding the server configuration
**Symptoms**: Getting rate limit errors or API failures.
**Solutions**:
1. Our hosted service includes built-in rate limiting protection
2. If you're hitting limits, contact support for assistance
3. Try spacing out your requests if making many in quick succession
***
## API coverage
Our hosted MCP server provides access to all DexPaprika API endpoints:
Access all supported blockchain networks and their available decentralized exchanges
Comprehensive pool data including TVL, volume, fees, and token pairs
Real-time token prices, market data, and detailed token information
Price history, volume trends, and historical pool performance
Powerful search across tokens, pools, and DEXes with filtering options
Live data feeds with the latest market information and trading activity
***
## What's next?
Explore all available data endpoints and their capabilities
Learn how to discover newly created liquidity pools and tokens
Want to run your own MCP server? Check out our self-hosted guide
Access and analyze historical price and volume data
## Need help?
Connect with our community and get real-time support from other builders
Reach out directly for technical support or feature requests
**Looking for custom integrations?** Our team can help you integrate DexPaprika data into any application or workflow. [Contact us](mailto:support@coinpaprika.com) to discuss your specific needs.
### FAQs
No. The service uses the public DexPaprika API; simply add the hosted URL to your client config.
Start with SSE for streaming and broad compatibility. Use streamable HTTP or JSON‑RPC if your environment restricts SSE.
Confirm the URL, restart the client, and test the endpoint in a browser. If using desktop apps, ensure your config JSON is valid.
Light protective limits are in place. Space out high‑frequency requests or contact support for higher throughput.
# DexPaprika for AI agents and AI-assisted development
Source: https://docs.dexpaprika.com/ai-integration/index
Connect AI tools to real-time DEX data across 33 blockchains. Choose from Claude Code plugin, hosted MCP server, IDE integrations, ChatGPT Actions, or direct REST API access -- no API key needed.
## Why DexPaprika + AI?
DexPaprika provides free, real-time on-chain DEX data covering 33 blockchains, 26M+ tokens, and 28M+ pools. No API key. No authentication. AI agents and AI-assisted IDEs can query token prices, pool data, historical OHLCV, swap transactions, and more -- either through MCP (Model Context Protocol) or direct REST API calls.
This page helps you pick the right integration for your setup.
***
## Choose your integration
One install command. Query pools, tokens, prices, and stream live data from the terminal.
Two commands. Zero config. Built-in MCP server access inside Claude Code.
Add a URL to Claude Desktop, Cursor, or VS Code. No installation needed.
Run the MCP server locally via npm/npx for full control.
One command. Full API knowledge for Claude Code, Cursor, Cline, and 40+ agents.
Call the API directly from any agent framework or custom application.
***
## Comparison table
| | Agent Skills | CLI | Claude Code Plugin | Hosted MCP | Self-hosted MCP | REST API |
| -------------------- | ------------------------------------------- | ------------------------------------- | --------------------------------------------- | ------------------------------- | --------------------------- | ------------------------------------------------ |
| **Setup time** | 10 seconds | 10 seconds | 30 seconds | 1-2 minutes | 10-15 minutes | 0 (just call endpoints) |
| **Install** | `npx skills add` | One curl command | Plugin marketplace | Add URL to config | npm/npx | No install |
| **Works with** | Claude Code, Cursor, Cline, 40+ agents | Any terminal, any agent | Claude Code | Claude Desktop, Cursor, VS Code | Claude Desktop, Cursor | Any HTTP client or agent |
| **How it works** | Agent reads API docs and makes calls itself | Direct CLI commands | MCP tools called by agent | MCP tools called by agent | MCP tools called by agent | Direct HTTP calls |
| **Streaming prices** | Agent can use REST streaming | Built-in `stream` command | No (use REST streaming) | No (use REST streaming) | No (use REST streaming) | Yes via [SSE streaming](/streaming/introduction) |
| **Works offline** | Yes (local files) | Yes (local binary) | No | No | Yes (local server) | No |
| **Best for** | Any agent that can make HTTP/CLI calls | Terminal agents, scripting, pipelines | Claude Code users who want everything bundled | Quick AI IDE setup | Custom/private environments | Agent frameworks, custom apps |
***
## Integration details
### CLI
Install in one line and start querying:
```bash theme={null}
curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh | sh
```
Works on macOS and Linux. Windows binaries available on [GitHub releases](https://github.com/coinpaprika/dexpaprika-cli/releases).
```bash theme={null}
# Get a token price
dexpaprika-cli token solana So11111111111111111111111111111111111111112
# Search for anything
dexpaprika-cli search uniswap
# Stream live prices
dexpaprika-cli stream ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
# JSON output for scripting and piping
dexpaprika-cli --output json --raw pools ethereum | jq '.[0]'
```
AI agents running in terminals can install the CLI and use `--output json --raw` for machine-readable output. The CLI covers every REST API endpoint plus live SSE streaming.
[Full CLI guide -->](/tutorials/cli)
***
### Claude Code Plugin
The fastest path if you use Claude Code. Two commands and you're done:
```bash theme={null}
/plugin marketplace add coinpaprika/claude-marketplace
/plugin install dexpaprika
```
The plugin bundles an MCP server -- no separate configuration needed. Ask Claude about token prices, pool data, or DEX analytics and it uses the plugin automatically.
[Full setup guide →](/tutorials/claude-code-plugin-guide)
***
### Hosted MCP Server
Add one URL to your AI tool's config. Works with Claude Desktop, Cursor, and VS Code.
**SSE endpoint (recommended):** `https://mcp.dexpaprika.com/sse`
Add to `claude_desktop_config.json`:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"url": "https://mcp.dexpaprika.com/sse"
}
}
}
```
Go to Settings → Tools & Integrations → New MCP server, then add:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"url": "https://mcp.dexpaprika.com/sse"
}
}
}
```
Or use the one-click install button in our docs.
Use the one-click install button in our docs, or manually configure the MCP server in Copilot Chat settings.
[Full hosted MCP guide →](/ai-integration/hosted-mcp-server)
***
### Self-hosted MCP Server
Run the MCP server on your own machine:
```bash theme={null}
npm install -g dexpaprika-mcp
```
Or run without installing:
```bash theme={null}
npx dexpaprika-mcp
```
Then configure your AI tool to use the `dexpaprika-mcp` command.
[Full self-hosted MCP guide →](/ai-integration/mcp)
***
### Agent Skills
Give your AI agent full knowledge of the DexPaprika API, CLI, and streaming service:
```bash theme={null}
npx skills add github.com/coinpaprika/skills/ --skill dexpaprika-api
```
Works with Claude Code, Cursor, Cline, and [40+ other agents](https://github.com/vercel-labs/skills). The agent reads the skill files locally and makes API calls directly -- no MCP server needed.
[Full skills guide -->](/ai-integration/skills)
***
### REST API
Any AI agent or framework can call the DexPaprika REST API directly. Base URL: `https://api.dexpaprika.com`
See the [REST API reference](/api-reference/introduction) and the [common patterns guide](/knowledge-base/common-patterns) for standard workflows like price lookups, pool discovery, and historical data retrieval.
***
### ChatGPT Actions
Create a custom GPT with DexPaprika data access using our OpenAPI spec:
1. Create a custom GPT in ChatGPT
2. Add an Action with the schema URL: `https://mcp.dexpaprika.com/openapi`
3. Start asking crypto questions
[Full ChatGPT Actions guide →](/ai-integration/chatgpt-actions)
***
### IDE integrations
One-click MCP install + docs indexing for Cursor
Copilot Chat MCP integration for VS Code
***
## What data can AI agents access?
All DexPaprika data is available through every integration method:
| Capability | Description |
| ------------------ | ------------------------------------------------------------------- |
| **Token prices** | Real-time USD prices for any token on any supported network |
| **Batch prices** | Up to 10 token prices in a single request |
| **Pool data** | Liquidity, volume, fees, token pairs for any pool |
| **Pool filtering** | Find pools by volume range, transaction count, or creation date |
| **OHLCV history** | Historical candlestick data with 9 interval options (1m to 24h) |
| **Transactions** | Recent swaps, adds, and removes for any pool |
| **DEX listings** | All DEXes on a network with pool counts |
| **Search** | Find tokens, pools, and DEXes by name, symbol, or address |
| **Network info** | All 33 supported blockchain networks |
| **Live streaming** | Real-time price updates via SSE (REST API only, up to 2,000 tokens) |
***
## Example: what you can ask an AI with DexPaprika access
Once connected, try prompts like:
* "What's the current price of SOL?"
* "Show me the top 10 pools on Ethereum by volume"
* "Find newly created pools on Base with over \$50k daily volume"
* "Get 30-day OHLCV data for the USDC/ETH pool on Uniswap V3"
* "Compare WETH prices across Ethereum, Arbitrum, and Base"
* "Which DEX has the most pools on Solana?"
* "Stream live prices for WETH and WBTC on Ethereum"
***
## Next steps
Learn core concepts: pools, DEXes, OHLCV, and how DexPaprika data works
Step-by-step guides for common tasks
Complete endpoint documentation with interactive playground
Real-time price updates via Server-Sent Events
### FAQs
For terminal-based work and scripting, start with the CLI. If you use Claude Code, the plugin is the fastest path. For Claude Desktop, Cursor, or VS Code, use the hosted MCP server. For custom agents and applications, use the REST API directly.
No. DexPaprika is completely free and public. No API key, no registration, no authentication needed for any integration method.
Yes. For example, you can use the MCP server in Cursor for interactive development and call the REST API from your application code.
The free API allows 10,000 requests per day. For unlimited access, see the [Pro API](/api-pro/introduction).
# Installing MCP Server for DexPaprika
Source: https://docs.dexpaprika.com/ai-integration/mcp
Integrating DexPaprika data with Claude.ai using Model Context Protocol (MCP)
## Integration overview
Install and configure the DexPaprika MCP server so AI tools can query networks, DEXes, pools, tokens, and search.
## What is MCP?
MCP (Model Context Protocol) is an [open protocol standard customized by Claude](https://modelcontextprotocol.io/introduction) for establishing unified context interaction between AI models and development environments, enabling AI to better understand and process code. The DexPaprika MCP server leverages this protocol to provide AI assistants like Claude with access to real-time crypto and DeFi market data, enabling advanced conversations about blockchain networks, decentralized exchanges (DEXes), liquidity pools, and tokens across the DeFi ecosystem.
**Looking for an easier setup?** If you prefer not to install anything locally, check out our [DexPaprika Hosted MCP Server](/ai-integration/hosted-mcp-server) for instant access with zero installation required.
## Installation Guide
### Prerequisites
Before installing the DexPaprika MCP server, ensure you have:
* [Node.js](https://nodejs.org/) (v16 or higher) installed on your system
* [npm](https://www.npmjs.com/) (comes with Node.js) or [yarn](https://yarnpkg.com/) package manager
* [Claude Desktop](https://claude.ai/desktop) or [Cursor](https://cursor.sh/) installed if you want to use the MCP server with these applications
### Installation Options
#### Option 1: Global Installation (Recommended)
Installing the DexPaprika MCP server globally makes it available throughout your system:
```bash theme={null}
npm install -g dexpaprika-mcp
```
After installation, you can start the server by running:
```bash theme={null}
dexpaprika-mcp
```
#### Option 2: Use with npx (No Installation)
Alternatively, you can run the server directly without installation using npx:
```bash theme={null}
npx dexpaprika-mcp
```
This is useful for trying out the server without permanently installing it.
### Verification
To verify that your installation was successful, run:
```bash theme={null}
dexpaprika-mcp --version
```
You should see the current version number of the DexPaprika MCP server.
## Configuration
### Claude Desktop Configuration
To use the DexPaprika MCP server with Claude Desktop:
1. Download and install [Claude Desktop](https://claude.ai/desktop) if you haven't already
2. Locate your Claude Desktop configuration file:
* **macOS**: `~/Library/Application\ Support/Claude/claude_desktop_config.json`
* **Windows**: `%APPDATA%/Claude/claude_desktop_config.json`
3. If the file doesn't exist, create it with the following content:
```json theme={null}
{
"mcpServers": {
"dexpaprika": {
"command": "dexpaprika-mcp"
}
}
}
```
4. If the file already exists, add the DexPaprika configuration to the existing `mcpServers` object:
```json theme={null}
"dexpaprika": {
"command": "dexpaprika-mcp"
}
```
5. Save the file and restart Claude Desktop.
6. To verify the configuration, open Claude Desktop and try asking a question about cryptocurrency data, such as "What are the top liquidity pools on Ethereum?"
Make sure you have the latest version of our package by running `npm update -g dexpaprika-mcp`
### Cursor Configuration
If you're using Cursor IDE with Claude:
1. Download and install [Cursor](https://cursor.sh/) if you haven't already
2. Open Cursor and click on the Claude button in the sidebar
3. Click on the settings icon (⚙️) and select "Add MCP Server"
4. Fill in the following information:
* **Server name**: `dexpaprika`
* **Type**: `command` (select from dropdown)
* **Command to run**: `npx dexpaprika-mcp`
5. Click "Add" to save the configuration
6. Alternatively, Cursor will automatically use any MCP servers configured in Claude Desktop
## Troubleshooting
If you encounter issues with the DexPaprika MCP server:
1. **Server not found errors**:
* Ensure the server is installed correctly using `npm list -g dexpaprika-mcp`
* Try reinstalling with `npm install -g dexpaprika-mcp`
2. **Connection errors**:
* Check that your internet connection is active
* Verify that no firewall is blocking the connection
3. **Configuration errors**:
* Double-check your configuration file syntax
* Ensure the path to the configuration file is correct for your OS
4. **Command not found errors**:
* Ensure Node.js is installed and in your PATH
* Try using the full path to the npm or npx executables
## Features
The DexPaprika MCP server provides access to:
* Blockchain network information across multiple chains
* Decentralized exchange (DEX) data
* Liquidity pool details and metrics
* Token information and market data
* Price and volume analytics for tokens and pools
* Comprehensive search capabilities across DeFi entities
## Available Tools
The DexPaprika MCP server provides the following tools to Claude:
1. **getNetworks** - Retrieve a list of all 33 supported blockchain networks and their metadata
2. **getNetworkDexes** - Get a list of available decentralized exchanges on a specific network
3. **getNetworkPools** - Get top liquidity pools on a specific network, sorted by volume, price, transactions, or creation date
4. **getDexPools** - Get top pools on a specific DEX within a network
5. **getPoolDetails** - Get detailed information about a specific pool including liquidity, reserves, and pricing
6. **getPoolOHLCV** - Get historical OHLCV (candlestick) data for a pool with configurable intervals (1m to 24h)
7. **getPoolTransactions** - Get recent swap transactions, liquidity adds, and removes for a pool
8. **getTokenDetails** - Get detailed token information including price, volume, and liquidity across time windows
9. **getTokenPools** - Find all liquidity pools containing a specific token
10. **getTokenMultiPrices** - Fetch USD prices for up to 10 tokens in a single request
11. **search** - Search for tokens, pools, and DEXes by name, symbol, or address across all networks
12. **getStats** - Get high-level statistics about the DexPaprika ecosystem (chains, DEXes, pools, tokens)
## Usage Examples
Once configured, you can ask Claude questions about DeFi data. Here are some example prompts:
### General Market Data
* "What are the top 5 liquidity pools across all networks by volume?"
### Network-Specific Queries
* "Which blockchain networks are supported by DexPaprika?"
* "What are the top DEXes on the Solana network?"
* "Show me the top 10 liquidity pools on Ethereum, ordered by volume."
### DEX and Pool Analysis
* "What are the most active pools on Uniswap V3?"
* "Show me details about the USDC/ETH pool on Uniswap V3."
* "Compare the trading volume between PancakeSwap and Uniswap."
### Token Information
* "What's the current price of SOL in the Raydium pool on Solana?"
* "Find all pools that include the SHIB token."
### Search Functionality
* "Search for pools related to 'Bitcoin'"
* "Find tokens with 'Pepe' in their name"
## Advanced Queries
You can also ask Claude to perform more complex analysis:
* "Compare the liquidity and volume of the top 3 DEXes on Ethereum"
* "What's the price difference of ETH between Uniswap and SushiSwap?"
* "Show me the tokens with the highest price volatility in the last 24 hours"
* "Analyze the trading volume trends for BNB on PancakeSwap"
## Support
If you need further assistance, you can:
* Contact DexPaprika support by [email](support@coinpaprika.com)
* Join the [Discord community](https://discord.gg/DhJge5TUGM)
### FAQs
No. The underlying DexPaprika API is public; the MCP server proxies public endpoints.
Claude Desktop reads `claude_desktop_config.json`; Cursor can add the same server via “Add MCP Server” or inherit Claude’s config.
Use absolute paths to `uvx`/`npx` in the config; many desktop apps don’t inherit shell `PATH`.
Yes--most integrations should run read‑only; the examples show `--readonly`.
# Install DexPaprika agent skills
Source: https://docs.dexpaprika.com/ai-integration/skills
Add the DexPaprika skill to Claude Code, Cursor, or any compatible AI agent with one command. Gives your agent full knowledge of the DexPaprika REST API, CLI, and streaming service.
## What are agent skills?
Agent skills are reusable instruction files that teach AI agents how to use a specific tool or API. When you install the DexPaprika skill, your AI agent gets a complete reference of every endpoint, CLI command, streaming parameter, and common workflow -- so it can make correct API calls without guessing.
Skills work with Claude Code, Cursor, Cline, OpenCode, and [many other AI agents](https://github.com/vercel-labs/skills). One install command. No API key needed.
***
## What's included
The DexPaprika skill installs the following files into your project:
| File | What it provides |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SKILL.md` | Full API reference: all REST endpoints, CLI commands, MCP setup, streaming API, SDKs, common workflows, token addresses, pagination, error handling |
| `references/openapi.yml` | Complete OpenAPI 3.1 specification with all schemas, parameters, and response types |
| `references/cli-reference.md` | Every `dexpaprika-cli` command with flags, examples, and output formats |
| `references/streaming-api.md` | SSE streaming documentation: GET/POST endpoints, response fields, connection handling |
Your AI agent reads `SKILL.md` automatically. The reference files are loaded on demand when the agent needs deeper detail (like exact response schemas or CLI flag options).
***
## Install
### One command
```bash theme={null}
npx skills add github.com/coinpaprika/skills/ --skill dexpaprika-api
```
This copies the skill files into `.claude/skills/dexpaprika-api/` in your current project.
To install both CoinPaprika and DexPaprika skills at once, drop the `--skill` flag:
```bash theme={null}
npx skills add github.com/coinpaprika/skills/
```
### What happens
1. The `skills` CLI (by [Vercel Labs](https://github.com/vercel-labs/skills)) fetches the skill from GitHub
2. Files are copied to `.claude/skills/dexpaprika-api/`
3. On next startup, your AI agent auto-discovers and loads the skill
Your project directory should now look like this:
```
.claude/skills/
dexpaprika-api/
SKILL.md
references/
openapi.yml
cli-reference.md
streaming-api.md
```
### Restart your agent
After installing, restart Claude Code (or your AI tool) so it picks up the new skill files.
***
## Verify it works
After restarting, ask your AI agent a DexPaprika question:
```
What blockchain networks does DexPaprika support?
```
The agent should return a list of supported networks (Ethereum, Solana, Base, Arbitrum, Polygon, and more). If it does, the skill is loaded and working.
Try a more specific query:
```
Get the current price of WETH on Ethereum using DexPaprika
```
The agent should call `https://api.dexpaprika.com/networks/ethereum/tokens/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` and return the price.
***
## Example queries
Once the skill is loaded, your agent knows how to use the full DexPaprika stack. Here are some things you can ask:
### REST API queries
```
Show me the top 5 pools on Ethereum by 24h volume
```
```
Get 30-day OHLCV data for the USDC/ETH pool on Uniswap V3
```
```
Search for PEPE token across all chains
```
### CLI commands
The skill teaches your agent to use `dexpaprika-cli` if it's installed:
```
Use dexpaprika-cli to stream live prices for WETH on Ethereum
```
```
Run dexpaprika-cli to find newly created pools on Solana
```
### Batch pricing
```
Get prices for WETH, USDC, and DAI on Ethereum in a single request
```
### Streaming
```
Write a Python script that streams real-time WETH prices using DexPaprika's SSE endpoint
```
***
## Skills vs MCP server vs Claude Code plugin
| | Agent Skills | Hosted MCP Server | Claude Code Plugin |
| --------------------------- | ----------------------------------------------------------------- | ------------------------------------- | --------------------------------------------- |
| **Install** | `npx skills add` | Add URL to config | `/plugin install` |
| **What it gives the agent** | Full API knowledge (endpoints, CLI, streaming docs) | Live tool calls (14 MCP tools) | MCP tools + agents + skills |
| **Agent makes API calls** | Yes, directly via REST or CLI | No, MCP server handles calls | MCP server handles calls |
| **Works offline** | Yes (skill files are local) | No (needs mcp.dexpaprika.com) | No (needs MCP server) |
| **Works with** | Claude Code (default), Cursor, Cline, and more via `--agent` flag | Claude Desktop, Cursor, VS Code | Claude Code only |
| **Best for** | Any agent that can make HTTP calls or run CLI commands | Quick AI IDE setup with managed tools | Claude Code users who want everything bundled |
You can combine approaches. Install the skill for API knowledge **and** connect the MCP server for tool-based access. They complement each other.
***
## Manage skills
### List installed skills
```bash theme={null}
npx skills list
```
### Remove the skill
```bash theme={null}
npx skills remove dexpaprika-api
```
### Update to latest version
```bash theme={null}
npx skills update
```
***
## Troubleshooting
Restart your AI agent (Claude Code, Cursor, etc.). Skills are discovered at startup. If it still doesn't load, check that the files are in the right location:
```bash theme={null}
ls .claude/skills/dexpaprika-api/
```
You should see `SKILL.md` and a `references/` directory.
The `skills` CLI requires Node.js. Make sure you have Node.js 16+ installed:
```bash theme={null}
node --version
```
If Node.js is installed and it still fails, try running with a fresh npx cache:
```bash theme={null}
npx --yes skills add github.com/coinpaprika/skills/ --skill dexpaprika-api
```
Be specific in your prompt. Instead of "What's the price of ETH?", try "Using the DexPaprika API, get the price of WETH on Ethereum." The agent should recognize the skill context and use the correct endpoints.
Skills must be direct children of `.claude/skills/`. If the files ended up nested differently (e.g., `.claude/skills/skills/dexpaprika-api/`), move the `dexpaprika-api` folder so it sits directly inside `.claude/skills/`. See the directory tree in the [Install](#install) section for the expected layout.
***
## Next steps
Install dexpaprika-cli for direct terminal access to all endpoints
Add MCP server access to Claude Desktop, Cursor, or VS Code
Get the full plugin bundle with MCP tools, agents, and skills
Complete endpoint documentation with interactive playground
***
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve.
### FAQs
No. The DexPaprika API is public and free. No keys, no registration. The skill teaches your agent to call the free API directly.
Skills give your agent knowledge (API docs, CLI commands, common patterns). MCP gives your agent tools (callable functions that return live data). Skills make your agent smarter about the API; MCP does the calling for it.
Claude Code, Cursor, Cline, OpenCode, Aider, and many others. The `skills` CLI auto-detects your agent, or you can target one explicitly with the `--agent` flag. See the [full list of supported agents](https://github.com/vercel-labs/skills).
Yes. Install the skill for deep API knowledge and connect the MCP server for tool-based access. They complement each other well.
No. The skill files are static reference documents stored locally in your project. Your agent reads them locally. API calls only happen when your agent decides to query the DexPaprika API based on what it learned from the skill.
# Integrating Documentation with VS Code
Source: https://docs.dexpaprika.com/ai-integration/vscode-ide-integration
Learn how to integrate DexPaprika documentation and the hosted MCP server directly into VS Code for enhanced AI-assisted workflows.
## Integration overview
Add the hosted MCP server to VS Code’s Copilot Chat and index docs for better AI assistance.
## What is VS Code?
Visual Studio Code is a popular open-source editor with rich AI and extension capabilities. With MCP (Model Context Protocol) support in Copilot Chat, VS Code can access external data sources and documentation to provide more intelligent coding assistance.
## Why integrate DexPaprika with VS Code?
* **Real-time crypto data access** - Live market data, pool information, and token prices while coding
* **Enhanced AI assistance** - Copilot Chat can reference DexPaprika data for better suggestions
* **DeFi development workflow** - Build faster with comprehensive blockchain data
* **Documentation context** - Quickly reference our API docs and tutorials while you work
***
## Step 1: Install MCP server with one click
Use the "Connect to VS Code" button in our docs to open VS Code and add the DexPaprika MCP server.
1. Look for the **"Connect to VS Code"** button in our documentation
2. Click the button to open VS Code and start MCP installation
1. The install dialog pre-fills the DexPaprika hosted MCP SSE URL:
```
https://mcp.dexpaprika.com/sse
```
2. Click **Install** to complete the setup
3. Restart VS Code if prompted
1. Open **Copilot Chat** in VS Code
2. Ask: "What are the top liquidity pools on Ethereum?"
3. You should see DexPaprika data being retrieved and displayed
4. Ask about specific networks, tokens, or pools to test further
If the button is not visible, copy this URL into the prompt when VS Code asks for the server address: `https://mcp.dexpaprika.com/sse`.
## Available features
Once integrated, you can access comprehensive DexPaprika functionality in Copilot Chat:
### Real-time data access
* **Network information** - Supported blockchain networks
* **DEX data** - Decentralized exchange information and metrics
* **Pool analytics** - Real-time liquidity pool data, volumes, and fees
* **Token information** - Current prices, market data, and token details
* **Search functionality** - Find tokens, pools, and DEXes across networks
### Documentation context
* **API reference** - Complete endpoint docs and examples
* **SDK guides** - Language-specific integration tutorials
* **Best practices** - Coding patterns and optimization tips
* **Troubleshooting** - Common issues and solutions
***
## Usage examples
### Example 1: Building a DeFi dashboard
```
"Help me create a React component that displays the top 5 liquidity pools
on Ethereum using the DexPaprika API. Include volume, TVL, and price data."
```
### Example 2: Token price monitoring
```
"Build a Python script that monitors SOL token prices across different
DEXes and alerts when there are significant price differences."
```
### Example 3: Pool discovery bot
```
"Create a Node.js application that finds newly created liquidity pools
with high trading volume and sends notifications."
```
***
## Troubleshooting
**Symptoms**: Errors or timeouts when connecting.
**Solutions**:
1. Verify internet connection is stable
2. Check the server URL is exactly: `https://mcp.dexpaprika.com/sse`
3. Restart VS Code completely
4. Remove and re-add the MCP configuration
5. Check VS Code output/logs for MCP-related errors
**Symptoms**: DexPaprika tools do not appear or responses lack data.
**Solutions**:
1. Ensure the server is added and enabled in MCP settings
2. Try re-adding via the **Connect to VS Code** button
3. Ask more specific questions (e.g., network or token names)
4. Restart VS Code
**Symptoms**: Slow responses.
**Solutions**:
1. Check network speed
2. Break complex queries into smaller parts
3. Use specific network/token names in queries
***
## Need Help?
Connect with our community for real-time support and discussions
Contact our team for technical assistance and custom integrations
Share your VS Code + DexPaprika integrations with our community! We love seeing what developers build. [Reach out](mailto:support@coinpaprika.com) to showcase your work.
### FAQs
In the MCP prompt, paste `https://mcp.dexpaprika.com/sse`, confirm, and restart VS Code if needed.
Re‑add the server and retry a scoped prompt (include network or token) to ensure the tools activate.
Check the Output/Logs panel for MCP errors, verify the URL, and restart VS Code; re‑add the server if necessary.
# DexPaprika Pro API - Enterprise REST API
Source: https://docs.dexpaprika.com/api-pro/introduction
Enterprise-grade DEX and on-chain data with dedicated infrastructure, no rate limits, and priority support. Secure access via API key authentication.
**Are you using the free API?** The standard DexPaprika API at `api.dexpaprika.com` is available for everyone. This Pro API is for enterprise customers who need higher performance, no rate limits, and dedicated support.
## What is the Pro API?
The DexPaprika Pro API provides the same comprehensive DEX and on-chain data as our free API, but with enterprise-grade infrastructure and benefits:
Unlimited requests to support high-volume applications and data pipelines
Separate infrastructure ensuring consistent performance and availability
Direct access to our engineering team for technical assistance
Secure access control and usage tracking for your organization
***
## Getting started
### 1. Get your API key
Pro API access requires an enterprise subscription. [Contact our team](mailto:support@coinpaprika.com) to get started.
To obtain a Pro API key:
Email [support@coinpaprika.com](mailto:support@coinpaprika.com) to discuss enterprise options and receive your API key
### 2. Authentication
All Pro API requests require authentication via the `Authorization` header:
```bash cURL theme={null}
curl -X GET "https://api-pro.dexpaprika.com/networks/ethereum/pools" \
-H "Content-Type: application/json" \
-H "Authorization: api_YOUR_API_KEY_HERE"
```
```python Python theme={null}
import requests
headers = {
"Content-Type": "application/json",
"Authorization": "api_YOUR_API_KEY_HERE"
}
response = requests.get(
"https://api-pro.dexpaprika.com/networks/ethereum/pools",
headers=headers
)
print(response.json())
```
```javascript JavaScript theme={null}
const headers = {
'Content-Type': 'application/json',
'Authorization': 'api_YOUR_API_KEY_HERE'
};
fetch('https://api-pro.dexpaprika.com/networks/ethereum/pools', {
headers: headers
})
.then(response => response.json())
.then(data => console.log(data));
```
```go Go theme={null}
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
req, _ := http.NewRequest("GET", "https://api-pro.dexpaprika.com/networks/ethereum/pools", nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "api_YOUR_API_KEY_HERE")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
```
### 3. API key format
Your API key will follow this format:
```
api_your_personal_api_key
```
Always prefix your key with `api_` when using it in the Authorization header.
***
## Differences from Free API
| Feature | Free API | Pro API |
| ------------------ | ---------------------------- | -------------------------------- |
| **Base URL** | `https://api.dexpaprika.com` | `https://api-pro.dexpaprika.com` |
| **Authentication** | None required | API key required |
| **Rate Limits** | 10,000 requests/day | No limits |
| **Infrastructure** | Shared | Dedicated |
| **Support** | Community | Priority enterprise support |
| **Endpoints** | All endpoints | All endpoints |
All endpoints available in the free API are also available in the Pro API. Simply replace the base URL and add authentication.
***
## Quick start example
Let's fetch Solana SOL token data using the Pro API:
Replace `YOUR_API_KEY_HERE` with your actual API key:
```bash theme={null}
curl -X GET "https://api-pro.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112" \
-H "Content-Type: application/json" \
-H "Authorization: api_YOUR_API_KEY_HERE"
```
You'll get the same comprehensive data as the free API:
```json Response [expandable] theme={null}
{
"id": "So11111111111111111111111111111111111111112",
"name": "Wrapped SOL",
"symbol": "SOL",
"chain": "solana",
"decimals": 9,
"total_supply": 0,
"has_image": true,
"summary": {
"price_usd": 165.0363416231933,
"fdv": 21277129298.9034355594499,
"liquidity_usd": 21277129298.9034355594499,
"pools": 12543,
"24h": {
"volume": 18207227.90283451,
"volume_usd": 3172926820.723157,
"sells": 11953376,
"buys": 8641848,
"txns": 20595327,
"buy_usd": 1586463410.3615785,
"sell_usd": 1586463410.3615785,
"last_price_usd_change": 2.5
}
}
}
```
***
## Error handling
### Authentication errors
**Error response:**
```json theme={null}
{
"message": "Forbidden"
}
```
**Solution:** Ensure you're including the `Authorization` header with a valid API key in the format `api_YOUR_KEY`.
**Error response:**
```json theme={null}
{
"message": "Unauthorized"
}
```
**Solution:** Check that your API key follows the correct format: `api_` prefix followed by your key string.
### Other errors
All other error codes match the [standard DexPaprika API](/api-reference/introduction):
* `400 Bad Request` - Invalid parameters
* `404 Not Found` - Resource not found
* `500 Internal Server Error` - Server error
***
## Available endpoints
The Pro API provides access to all DexPaprika endpoints:
Get detailed token information including price, liquidity, and trading volume
Access liquidity pool data and trading statistics
List all supported blockchain networks
Query swap transactions, adds, and removes
Search across tokens, pools, and DEXes
Retrieve multiple token prices in a single request
View complete API documentation in the [REST API Reference](/api-reference/introduction) section. All examples use the free API URL - simply replace with `api-pro.dexpaprika.com` and add authentication.
***
## Migration guide
Migrating from the free API to Pro API is straightforward:
Replace all instances of:
```
https://api.dexpaprika.com
```
With:
```
https://api-pro.dexpaprika.com
```
Add the `Authorization` header to every request:
```javascript theme={null}
headers: {
'Authorization': 'api_YOUR_API_KEY_HERE'
}
```
Since Pro API has no rate limits, you can remove any throttling or rate limiting code from your application.
Make test requests to verify your API key works correctly and you're receiving expected responses.
***
## Best practices
**Never expose your API key in client-side code or public repositories.**
* Store API keys in environment variables or secure vaults (e.g., AWS Secrets Manager, HashiCorp Vault)
* Use `.env` files locally and add them to `.gitignore`
* Rotate keys periodically as part of security best practices
* Never hardcode keys in your application source code
```bash Example .env file theme={null}
DEXPAPRIKA_PRO_API_KEY=api_your_personal_api_key
```
**Track your API usage to optimize performance and identify issues early.**
* Log all API requests and responses for debugging
* Set up monitoring dashboards to track request volumes
* Monitor response times and error rates
* Alert on unusual patterns or spikes in traffic
* Review usage patterns to optimize your integration
**Always handle authentication errors gracefully and implement retry logic.**
* Catch and handle 403/401 errors separately from other errors
* Implement exponential backoff for transient failures
* Don't retry on authentication errors - fix the key instead
* Log errors with context for easier troubleshooting
* Provide meaningful error messages to end users
```javascript Example error handling theme={null}
try {
const response = await fetch(url, { headers });
if (response.status === 403) {
console.error('Invalid API key - check your credentials');
// Don't retry - fix the key
return;
}
// Handle other errors with retry logic
} catch (error) {
console.error('Request failed:', error);
}
```
**Reuse HTTP connections to reduce latency and improve throughput.**
* Configure HTTP clients to reuse connections
* Set appropriate connection pool sizes (e.g., 10-50 connections)
* Enable keep-alive headers
* Use persistent connections for high-volume applications
* Monitor connection pool metrics
```python Example with Python requests theme={null}
import requests
from requests.adapters import HTTPAdapter
session = requests.Session()
adapter = HTTPAdapter(pool_connections=20, pool_maxsize=20)
session.mount('https://', adapter)
# Reuse session for all requests
response = session.get(url, headers=headers)
```
***
## Next steps
Explore all available endpoints and their parameters
Real-time token price updates via Server-Sent Events
Learn how to build applications with DexPaprika
Check which tokens and pools are available in our database
***
## Get support
Get priority technical support from our engineering team
Connect with our community for general questions
***
## FAQs
Contact our enterprise sales team at [support@coinpaprika.com](mailto:support@coinpaprika.com) to discuss subscription options and receive your API key.
Yes, you can use both APIs in the same application. The free API requires no authentication, while the Pro API requires your API key.
Correct. The Pro API has no rate limits, allowing you to make as many requests as needed for your application.
Contact [support@coinpaprika.com](mailto:support@coinpaprika.com) immediately to revoke your current key and receive a new one.
Yes, we can provide custom infrastructure solutions for enterprise customers. Contact our sales team to discuss your specific requirements.
Yes, both APIs provide access to the same comprehensive DEX and on-chain data. The Pro API offers better performance and no rate limits.
# Get a list of available dexes on a network.
Source: https://docs.dexpaprika.com/api-reference/dexes/get-a-list-of-available-dexes-on-a-network
get /networks/{network}/dexes
List all decentralized exchanges available on a specific blockchain network
## Endpoint overview
List decentralized exchanges available on a specific network.
See also: [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools by DEX](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
### FAQs
Identifier, display name, and often counts/metrics used to navigate to pools.
Call the DEX pools endpoint with the same `network` and `dex` id.
Yes; ids are stable across requests and are used throughout the API.
# DexPaprika DEX & on‑chain API - REST reference
Source: https://docs.dexpaprika.com/api-reference/introduction
REST API reference for querying tokens, liquidity pools, swaps, and DEX data across 33 blockchain networks
**Need unlimited requests and dedicated infrastructure?** Check out the [Pro API](/api-pro/introduction) for enterprise-grade access with no rate limits and priority support.
The DexPaprika DEX API provides near real-time data about tokens, liquidity pools, and decentralized exchanges on 33 blockchains. Below you can find the most popular endpoints that you can use to build your own applications:
See also: [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Liquidity pool endpoint](/api-reference/pools/get-a-pool-on-a-network),
[Swap transactions](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages),
[Token data](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
New:Advanced pool filtering -- filter pools by volume, transactions, and creation date. Plus batch token prices in a single request.
### Popular endpoints
Get detailed information about any token on a given network like latest price, liquidity, and trading volume
Access liquidity pool data and trading statistics for a given pool address
List supported networks
Fetch swaps/adds/removes
## Quick start
We will make a GET request to the [Token](/api-reference/tokens/get-a-tokens-latest-data-on-a-network) endpoint in order to get the latest price in USD of TRUMP. All we need is the [network ID](/api-reference/networks/get-a-list-of-available-blockchain-networks) and the token address.
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/solana/tokens/6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN"
```
This will return latest data about TRUMP (TRUMP) on Solana:
```json Response [expandable] theme={null}
{
"id": "6p6xgHyF7AeE6TZkSmFsko444wqoP15icUSqi2jfGiPN",
"name": "OFFICIAL TRUMP",
"symbol": "TRUMP",
"chain": "solana",
"decimals": 6,
"total_supply": 1000000000000000,
"description": "",
"website": "",
"explorer": "",
"added_at": "2025-01-17T23:26:21Z",
"summary": {
"price_usd": 13.14091959123721,
"fdv": 13140919591.23721,
"liquidity_usd": 149423162.71562782,
"24h": {
"volume": 21068441.593753017,
"volume_usd": 281073979.6428536,
"sell": 64806,
"buy": 69661,
"txns": 134467
},
"6h": {
"volume": 3947009.6413350017,
"volume_usd": 51291873.69781224,
"sell": 15636,
"buy": 16434,
"txns": 32070
},
"1h": {
"volume": 412765.81969400006,
"volume_usd": 5443526.242503976,
"sell": 1965,
"buy": 1934,
"txns": 3899
},
"30m": {
"volume": 138223.89740200003,
"volume_usd": 1826042.0489568561,
"sell": 666,
"buy": 942,
"txns": 1608
},
"15m": {
"volume": 102904.73769500002,
"volume_usd": 1356865.0163336615,
"sell": 499,
"buy": 634,
"txns": 1133
},
"5m": {
"volume": 16003.968976,
"volume_usd": 210782.49285099082,
"sell": 77,
"buy": 155,
"txns": 232
}
},
"last_updated": "2025-02-25T13:42:32.093353071Z"
}
```
## Base URL
All API endpoints use the following base URL:
```
https://api.dexpaprika.com/
```
## Common use cases
Here are some popular ways to use our API:
```bash theme={null}
# Get USDC price and trading data
curl -X GET "https://api.dexpaprika.com/networks/solana/tokens/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
```
```bash theme={null}
# Get all pools where SOL is traded
curl -X GET "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112/pools"
```
```bash theme={null}
# Search for "Jupiter" token across all networks
curl -X GET "https://api.dexpaprika.com/search?query=jupiter"
```
### FAQs
No. The DexPaprika API is public; no API keys or registration required.
Liquidity pools, swap transactions, token metrics/prices, and network coverage across multiple chains.
Use the Coverage Checker tool or the Networks/Token endpoints to locate addresses.
Collection is near real‑time; responses reflect the latest indexed blocks and events.
## Rate limits
The API is free to use with a rate limit of:
* 10,000 requests per day
Need higher limits? [Contact us](mailto:support@coinpaprika.com) to discuss enterprise options.
# Get a list of available blockchain networks.
Source: https://docs.dexpaprika.com/api-reference/networks/get-a-list-of-available-blockchain-networks
get /networks
List all supported blockchain networks and their canonical IDs for use in API requests
## Endpoint overview
Enumerate supported blockchain networks and canonical ids for requests.
See also: [DEXes on a network](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network),
[Tokens](/api-reference/tokens/get-a-tokens-latest-data-on-a-network),
[Pools](/api-reference/pools/get-a-pool-on-a-network)
### FAQs
An `id` used in all endpoints plus display metadata and, where available, counts of related entities.
Prefer lowercase canonical ids like `ethereum`, `solana`. Use this list as the source of truth.
Call the network DEXes endpoint and then drill into pools for each DEX.
# Advanced pool filtering on a specific network.
Source: https://docs.dexpaprika.com/api-reference/pools/advanced-pool-filtering-on-a-network
get /networks/{network}/pools/filter
Filter and search liquidity pools by volume, transaction count, and creation date with sorting and pagination
## Endpoint overview
Filter and search pools on a specific network by volume, transaction count, liquidity, and creation date. Supports sorting and pagination for building screeners, dashboards, and analytics tools.
See also: [Top pools on a network](/api-reference/pools/get-top-x-pools-on-a-network),
[Pools by DEX](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
The `volume_30d_min` and `volume_30d_max` parameters are documented but **not yet functional**. Using them will return empty or zero-value results. These will be enabled in a future update.
### FAQs
The regular `/networks/{network}/pools` endpoint lists top pools with basic sorting. This endpoint adds range filters (min/max volume, transaction count thresholds, creation date windows) so you can build advanced screeners without client-side filtering.
You can sort by `volume_24h` (default), `volume_7d`, `volume_30d`, `liquidity`, `txns_24h`, or `created_at`. Combine with `sort_dir` (`asc` or `desc`).
Pages are 1-indexed. Set `limit` (1-100, default 50) and increment `page`. The response includes `page_info` with `total_items` and `total_pages` so you know when to stop.
Yes. All filter parameters are combined with AND logic. For example, `volume_24h_min=100000&txns_24h_min=50&created_after=1709251200` returns only pools matching all three conditions.
# Advanced pool filtering on a specific network.
Source: https://docs.dexpaprika.com/api-reference/pools/advanced-pool-filtering-on-a-specific-network
/api-reference/openapi.yml get /networks/{network}/pools/filter
Retrieves a paginated list of pools matching the advanced search criteria,
such as 24-hour volume, transaction counts, and creation timestamps.
# Get a pool on a network.
Source: https://docs.dexpaprika.com/api-reference/pools/get-a-pool-on-a-network
get /networks/{network}/pools/{pool_address}
Get detailed liquidity, reserves, pricing, and metadata for a specific pool on a blockchain network
## Endpoint overview
Get detailed liquidity, reserves, pricing, and metadata for a specific pool.
See also: [Pool transactions](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages),
[Token data](/api-reference/tokens/get-a-tokens-latest-data-on-a-network),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks)
### FAQs
Provide both `network` (e.g., `ethereum`, `solana`) and `pool_address` (on‑chain pool address). Optional: `inversed` to flip the price ratio.
It returns prices and ratios from the opposite pair perspective (token1/token0). Leave it `false` for the default token0/token1 view.
Use the Coverage Checker tool or list a token’s pools from the token endpoint, then copy the desired pool’s address.
Prices are in USD where available; liquidity and volumes include USD fields. Raw token amounts are returned in token units.
Collection is near real‑time; responses reflect the latest indexed blocks/events per network.
# Get OHLCV data for a pool pair.
Source: https://docs.dexpaprika.com/api-reference/pools/get-ohlcv-data-for-a-pool-pair
get /networks/{network}/pools/{pool_address}/ohlcv
Retrieve historical OHLCV candlestick data for a pool at intervals from 1 minute to 24 hours
## Endpoint overview
Retrieve historical OHLCV for a pool at granular intervals.
See also: [Pool details](/api-reference/pools/get-a-pool-on-a-network),
[Pool transactions](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages)
### FAQs
`1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h` with a max of 366 points per request.
Provide `start` (ISO or Unix). Optional `end` up to one year from the start.
It flips the price ratio so the series reflects token1/token0 instead of token0/token1.
# Get top X pools. (DEPRECATED)
Source: https://docs.dexpaprika.com/api-reference/pools/get-top-x-pools
get /pools
Deprecated global pools endpoint -- use network-scoped /networks/{network}/pools instead
## Endpoint overview
List top pools across networks; prefer network-scoped endpoints for focused results.
See also: [Pools by network](/api-reference/pools/get-top-x-pools-on-a-network),
[Pools by DEX](/api-reference/pools/get-top-x-pools-on-a-networks-dex),
[OHLCV](/api-reference/pools/get-ohlcv-data-for-a-pool-pair)
### FAQs
A paginated list of top pools across all networks ordered by the chosen field, typically `volume_usd`.
Use `order_by` (e.g., `volume_usd`, `price_usd`) and `sort` (`asc` or `desc`).
Prefer the network‑scoped endpoint to avoid mixing pools from different chains.
**This endpoint has been deprecated and will return a `410 Gone` error.**
Please use [`/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network) instead to get top pools for each specific blockchain network.
### Migration Examples:
Instead of:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/pools"
```
Use network-specific endpoints:
```bash theme={null}
# Get top pools on Ethereum
curl -X GET "https://api.dexpaprika.com/networks/ethereum/pools"
# Get top pools on Solana
curl -X GET "https://api.dexpaprika.com/networks/solana/pools"
# Get top pools on Fantom
curl -X GET "https://api.dexpaprika.com/networks/fantom/pools"
```
This change provides better performance and more relevant, network-specific results.
# Get top X pools. (DEPRECATED)
Source: https://docs.dexpaprika.com/api-reference/pools/get-top-x-pools-deprecated
/api-reference/openapi.yml get /pools
**THIS ENDPOINT HAS BEEN DEPRECATED AND WILL BE REMOVED.**
It now returns a 410 Gone status. Please refer to our API documentation for alternatives.
---
*Original Description (for historical reference):*
Retrieves a paginated list of top pools from all (or specific) networks.
Allows sorting and ordering, providing aggregated volume, price data,
and token details for each pool.
# Get top X pools on a network.
Source: https://docs.dexpaprika.com/api-reference/pools/get-top-x-pools-on-a-network
get /networks/{network}/pools
List top liquidity pools on a specific blockchain network with sorting and pagination
## Endpoint overview
List top liquidity pools on a specific network with sorting and paging.
See also: [Pools across all networks](/api-reference/pools/get-top-x-pools),
[Pools by DEX](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
### FAQs
Provide the `network` id (e.g., `ethereum`, `solana`) path parameter.
Common values are `volume_usd`, `price_usd`, and `liquidity_usd` depending on the dataset.
Start with `page=0`, set `limit` (up to 100), and increment `page` while results are returned.
# Get top X pools on a network's DEX.
Source: https://docs.dexpaprika.com/api-reference/pools/get-top-x-pools-on-a-networks-dex
get /networks/{network}/dexes/{dex}/pools
List top liquidity pools for a specific DEX on a blockchain network with sorting and pagination
## Endpoint overview
List top pools for a specific DEX within a given network.
See also: [Pools by network](/api-reference/pools/get-top-x-pools-on-a-network),
[Pool details](/api-reference/pools/get-a-pool-on-a-network)
### FAQs
First list DEXes for the network and copy the `dex` id (e.g., `uniswap_v2`).
Yes. Use `order_by=volume_usd` with `sort=desc` to get the busiest pools first.
No. It is scoped to one `network` and one `dex` at a time.
# Get transactions of a pool on a network. Paging can be used up to 100 pages.
Source: https://docs.dexpaprika.com/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages
get /networks/{network}/pools/{pool_address}/transactions
List recent swaps, liquidity adds, and removes for a pool with page or cursor-based pagination
## Endpoint overview
List recent swaps, adds, and removes for a pool with paging.
See also: [Pool details](/api-reference/pools/get-a-pool-on-a-network),
[Token data](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
### FAQs
Use `page`/`limit` or the `cursor` for deep pagination. `cursor` points to a specific transaction id for resume.
Swaps, liquidity adds, and removes with token amounts, USD values when available, and timestamps.
Request with `limit` (e.g., 20–100) and without `page` to get the latest batch; poll periodically for new entries.
Results are returned in reverse chronological order (most recent first) per pool.
# Search for tokens, pools, and DEXes
Source: https://docs.dexpaprika.com/api-reference/search/search-for-tokens-pools-and-dexes
get /search
Search for tokens, liquidity pools, and DEXes by name, symbol, or contract address
See also: [Tokens](/api-reference/tokens/get-a-tokens-latest-data-on-a-network),
[Pools](/api-reference/pools/get-a-pool-on-a-network),
[DEXes on a network](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network)
### FAQs
Tokens, pools, and DEXes by name, symbol, or address/identifier depending on the network.
No; queries are normalized internally.
Copy the `network` and `id`/`address` from the result and pass them to the corresponding endpoints.
# Advanced token filtering on a specific network.
Source: https://docs.dexpaprika.com/api-reference/tokens/advanced-token-filtering-on-a-specific-network
/api-reference/openapi.yml get /networks/{network}/tokens/filter
Retrieves a paginated list of tokens matching the advanced search criteria,
such as 24-hour volume, transaction counts, liquidity, FDV, and creation timestamps.
# Get a token's latest data on a network.
Source: https://docs.dexpaprika.com/api-reference/tokens/get-a-tokens-latest-data-on-a-network
get /networks/{network}/tokens/{token_address}
Retrieves detailed information about a specific token on the given network,
including latest price, metadata, status, and recent summary metrics such as price changes
and volumes over multiple timeframes. The `token_supply` is a raw integer. To get the actual supply, move the decimal point left by the `decimals` value. Example: supply = `raw_supply` / 10^`decimals`
## Endpoint overview
Fetch token metadata, price, FDV, liquidity summary, and recent metrics.
See also: [Token pools](/api-reference/tokens/get-top-x-pools-for-a-token),
[Pool details](/api-reference/pools/get-a-pool-on-a-network),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks)
### FAQs
Provide `token_address` (contract or canonical address) and `network` (e.g., `ethereum`, `solana`).
`total_supply` is raw; divide by 10^`decimals` to get human‑readable supply.
Use the token pools endpoint to list all pools including this token, optionally filtered by a pair address.
Aggregated metrics for 24h, 6h, 1h, 30m, 15m, and 5m where available.
# Get batched prices for multiple tokens on a network.
Source: https://docs.dexpaprika.com/api-reference/tokens/get-batched-prices-for-multiple-tokens-on-a-network
/api-reference/openapi.yml get /networks/{network}/multi/prices
Retrieves the current USD price for a list of specified token addresses
in a single API call. This is more efficient than making multiple requests
to the single-token detail endpoint when you only need pricing information.
# Get batched prices for multiple tokens on a network.
Source: https://docs.dexpaprika.com/api-reference/tokens/get-batched-token-prices-on-a-network
get /networks/{network}/multi/prices
Fetch current USD prices for up to 10 token addresses in a single request
## Endpoint overview
Fetch current USD prices for multiple token addresses in a single request.
See also: [Token details](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
### Usage
Pass the `network` path parameter and provide a comma-separated list in the `tokens` query parameter.
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xdac17f958d2ee523a2206206994597c13d831ec7" | jq
```
Notes:
* Only tokens with available prices are returned (unknown/unpriced tokens are omitted).
* The order of results is not guaranteed.
* If all provided tokens are invalid or unpriced, the response is an empty array with HTTP 200.
* Duplicate input addresses may produce duplicate entries; dedupe client-side if needed.
* Provide tokens as a comma-separated list in a single `tokens` parameter (explode=false).
* Maximum 10 `tokens` per request. More than 10 will return HTTP 400.
### Response example
```json Response theme={null}
[
{
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"chain": "ethereum",
"price_usd": 4400.5697112921535
},
{
"id": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"chain": "ethereum",
"price_usd": 1.0002529851244053
}
]
```
### FAQs
Repeat the `tokens` query parameter for each address (e.g., `?tokens=0x...&tokens=0x...`).
They are ignored and omitted from the response.
No. Do not rely on response order.
The endpoint returns HTTP 200 with an empty array.
No. Duplicate inputs may yield duplicate entries; dedupe client-side if required.
Yes. Provide a single `tokens` parameter with comma-separated addresses.
Up to 10. Requests with more than 10 tokens return HTTP 400.
# Get top tokens on a network.
Source: https://docs.dexpaprika.com/api-reference/tokens/get-top-tokens-on-a-network
/api-reference/openapi.yml get /networks/{network}/tokens/top
Retrieves a paginated list of top-ranked tokens for a specified network.
The results are ordered based on the criteria provided in the query (e.g., volume, liquidity)
and enriched with short-term transaction data and token metadata.
# Get top X pools for a token.
Source: https://docs.dexpaprika.com/api-reference/tokens/get-top-x-pools-for-a-token
get /networks/{network}/tokens/{token_address}/pools
List liquidity pools containing a specific token with optional pair filtering and sorting
## Endpoint overview
List pools that include a given token; optional pairing filter available.
See also: [Token details](/api-reference/tokens/get-a-tokens-latest-data-on-a-network),
[Pools by network](/api-reference/pools/get-top-x-pools-on-a-network)
### FAQs
Provide the second token address via the `address` (or `pairWith`) parameter to restrict results to that pairing.
Use `order_by` such as `volume_usd` or `liquidity_usd` with `sort` direction.
Up to 100 items depending on `limit`.
# Retrieve high-level asset statistics
Source: https://docs.dexpaprika.com/api-reference/utils/retrieve-high-level-asset-statistics
get /stats
Get high-level platform statistics including total networks, DEXes, pools, and tokens
## Endpoint overview
Get high-level counts and coverage information across the platform.
See also: [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools](/api-reference/pools/get-top-x-pools)
### FAQs
High‑level counts for networks, DEXes, pools, and tokens available on DexPaprika.
Stats are rebuilt periodically; values reflect the latest successful aggregation.
Yes. Many users poll it to confirm platform availability and catalog growth.
# Changelog
Source: https://docs.dexpaprika.com/changelog/changelog
Track all updates and changes to DexPaprika API
This page contains all significant updates, improvements, and bug fixes for the DexPaprika API. We're committed to making our product better with each release. Check our [API reference](/api-reference) for the latest version.
## Added
* `GET /networks/{network}/pools/{pool_address}/transactions`: new optional `from` and `to` query parameters (UNIX timestamps, int64) to filter transactions by time range.
* `from` is inclusive, `to` is exclusive. Results are always capped to the last 7 days.
* Token schema: new `telegram` and `twitter` string fields for official social links.
## Added
* New endpoint: `GET /networks/{network}/tokens/filter` for [advanced token filtering](/api-reference/tokens/advanced-token-filtering-on-a-network).
* Filter tokens by volume (`volume_24h`, `volume_7d`, `volume_30d`), liquidity (`liquidity_usd`), FDV (`fdv_min`, `fdv_max`), transaction count (`txns_24h_min`), and creation date (`created_after`, `created_before`).
* Sort by `volume_24h`, `volume_7d`, `volume_30d`, `liquidity_usd`, `txns_24h`, `created_at`, or `fdv`.
* Paginated response with `page_info`.
* New endpoint: `GET /networks/{network}/tokens/top` for [top tokens on a network](/api-reference/tokens/get-top-tokens-on-a-network).
* Ranked token list with enriched metadata and multi-timeframe metrics (24h, 1h, 5m).
* Order by `volume_24h`, `price_usd`, `liquidity_usd`, `txns`, or `price_change`.
* Each token includes buy/sell counts, volume, and price change per interval.
* New schemas: `TokenFilterResponse`, `TokenSearchResult`, `TopTokenResponse`, `TopTokenItem`, `TopTokenTimeData`.
## Changed
* `GET /networks` response schema updated from `Network` to `NetworkMetrics` with new fields: `volume_usd_24h`, `txns_24h`, `pools_count`.
* `GET /networks/{network}/dexes` response enriched with `dex_id`, `volume_usd_24h`, `txns_24h`, `pools_count` per DEX.
* `GET /networks/{network}/pools/filter`: `PoolSearchResult` now extends `PoolWithPrices` via `allOf`, adding `volume_usd_7d` and `liquidity_usd`.
* Pool filter parameters `volume_7d_min`, `liquidity_usd_min`, and `liquidity_usd_max` are now functional.
* New pool filter parameters: `volume_7d_max`, `volume_30d_max`.
## Known limitations
* `volume_30d_min` and `volume_30d_max` parameters on pool and token filter endpoints are documented but not yet functional.
## Added
* New endpoint: `GET /networks/{network}/pools/filter` for [advanced pool filtering](/api-reference/pools/advanced-pool-filtering-on-a-network).
* Filter pools by 24h volume range (`volume_24h_min`, `volume_24h_max`), transaction count (`txns_24h_min`), and creation date (`created_after`, `created_before`).
* Sort by `volume_24h`, `volume_7d`, `volume_30d`, `liquidity`, `txns_24h`, or `created_at` with `asc`/`desc` direction.
* Paginated response with `page_info` including `total_items` and `total_pages`.
* New schemas: `PoolFilterResponse` and `PoolSearchResult`.
## Known limitations
* `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, and `liquidity_usd_max` parameters are documented but not yet functional. These will be enabled in a future update.
## Changed
* `GET /networks/{network}/multi/prices`: requests are now limited to a maximum of 10 `tokens` per call.
* Parameter encoding updated to a single comma-separated `tokens` list (`explode=false`).
## Error handling
* Requests with more than 10 tokens return `400 Bad Request`.
* Requests with zero tokens still return `400 Bad Request` (unchanged).
## Docs
* Updated API reference, tutorial, and MCP notes to reflect the cap, edge-case behavior, and comma-separated encoding.
## Added
* New endpoint: `GET /networks/{network}/multi/prices` for batch token price retrieval on a network.
* Request: repeatable `tokens` query parameter (e.g., `?tokens=0x...&tokens=0x...`).
* Response: array of `{ id, chain, price_usd }` objects for tokens with available prices; unknown/unpriced tokens are omitted.
## Changed
* `AssetPrice` schema added and documented in OpenAPI.
* Internals: performance optimization to fetch token summaries conditionally.
## Compatibility
* Certain price-related fields now use `omitempty` semantics in responses. If you previously relied on nulls for absent values, note these keys may now be omitted when data is unavailable.
## Docs
* New API page: [Get batched token prices on a network](/api-reference/tokens/get-batched-token-prices-on-a-network).
* Updated tutorials and references to include batch pricing guidance.
## Enhanced
* **Transaction Schema:**
* Added `token_0_symbol` and `token_1_symbol` fields to transaction objects for explicit token symbol tracking.
* Added `price_0`, `price_1`, `price_0_usd`, and `price_1_usd` fields to transaction objects for detailed price reporting.
* Added `created_at` field to transaction objects for precise transaction timestamping.
## Migration/Compatibility
* No breaking changes to existing endpoints, but clients parsing transaction objects should update their models to support the new fields for full compatibility.
### FAQs
We ship changes continuously. Breaking changes are called out explicitly with migration guidance.
Each breaking change section includes steps and replacement endpoints when applicable.
Watch this changelog and our Discord announcements; major updates are posted there.
## Deprecated
* **BREAKING**: The [`/pools`](/api-reference/pools/get-top-x-pools) endpoint has been permanently deprecated and now returns `410 Gone`
* Users should migrate to [`/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network) to get top pools for each specific network
## Changed
* Enhanced deprecation messaging with clear migration paths for affected endpoints
## Migration guide
Instead of using the deprecated global pools endpoint:
```
GET /pools
```
Use the network-specific pools endpoint for each blockchain:
```
GET /networks/ethereum/pools
GET /networks/solana/pools
GET /networks/fantom/pools
```
This change provides better performance and more relevant results by focusing on network-specific data.
## Added
* Introduced the optional `reorder` query parameter to the [`/networks/{network}/tokens/{token_address}/pools`](/api-reference/tokens/get-top-x-pools-for-a-token) endpoint. This allows clients to reorder pool data so the specified token becomes the primary token for all metrics and calculations.
## Added
* Added operation IDs to all endpoints for better client code generation
* Added fully diluted valuation (`fdv`) field to token responses
* Added detailed license information and contact details in API specification
* Added `buy_usd` and `sell_usd` fields to provide monetary values for trades
* Added `last_price_usd_change` field to all time intervals (24h, 6h, 1h, 30m, 15m, 5m, 1m)
* Added organized API tags with descriptions for better navigation
## Changed
* Updated OpenAPI specification from 3.0.3 to 3.1.0 for improved documentation
* Changed [OHLCV endpoint](/api-reference/pools/get-ohlcv-data-for-a-pool-pair) response format from wrapped object to direct array of records (Breaking Change)
* Renamed `buy`/`sell` fields to `buys`/`sells` for consistency (Breaking Change)
* Changed [network](/api-reference/networks) response format from object to array for cleaner consumption
* Updated network schema with improved field naming (`display_name` instead of just `name`)
* Standardized ID field in Network schema to use string identifiers instead of numeric IDs
* Enhanced token schema with additional fields: chain, total\_supply, added\_at, last\_updated
* Improved parameter documentation with examples and clearer descriptions
## Fixed
* Improved consistency in representing null values in responses
* Updated example responses to more accurately reflect actual API behavior
* Fixed formatting inconsistencies in API documentation
## Improved
* Enhanced OHLCV schema with time\_open and time\_close fields to clearly define candlestick periods
* Improved validation for time intervals and limits in OHLCV endpoint
* Added explicit error response documentation for the /stats endpoint
* Enhanced descriptions for all endpoints and parameters
## Added
* Support for buy/sell volume metrics across all time intervals
* Added transaction counts to pool details
* Added initial support for price tracking
## Changed
* Improved error messaging with more specific error codes
* Enhanced documentation with more descriptive examples
## Fixed
* Corrected timestamp format inconsistencies across endpoints
* Fixed incorrect price calculations in some edge cases
## Added
* Initial public beta release
* Support for Solana network
* Basic endpoints for [networks](/api-reference/networks), [DEXes](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network), [pools](/api-reference/pools/get-top-x-pools), and [tokens](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
* [Search functionality](/api-reference/search/search-for-tokens-pools-and-dexes) across tokens, pools, and DEXes
* OHLCV data for historical price tracking
* Transaction history for pools
## Added
* Pool and token details endpoints
* Initial version of search functionality
## Changed
* Improved error handling and response formats
* Enhanced documentation with examples
## Added
* Initial development release
* Preliminary endpoints for pools and DEXes
# Dexpaprika api reference verified
Source: https://docs.dexpaprika.com/dexpaprika-api-reference-verified
# DexPaprika API -- Verified Reference (2026-03-02)
Every claim in this document was verified against the live API with 72 tests, 72 pass, 0 failures.
***
## Base URLs
| Service | URL | Notes |
| -------------- | ---------------------------------------------------- | ---------------------------------------------------------------------------- |
| REST API | `https://api.dexpaprika.com` | JSON responses, no auth |
| Streaming API | `https://streaming.dexpaprika.com` | SSE only on `/stream` path. Bare URL returns `{"message":"Not Found"}` (404) |
| Streaming docs | `https://docs.dexpaprika.com/streaming/introduction` | Human-readable docs |
***
## Pagination (applies to ALL list endpoints)
* Pages are **1-indexed**. `page=0` is silently treated as `page=1`.
* Max `limit` is **100**. Values >100 return HTTP 400 (rejected, not capped).
* Exception: `/pools/filter` uses wrapper key `results` instead of `pools`.
All paginated responses include:
```json theme={null}
"page_info": {
"limit": 10,
"page": 1,
"total_items": 7838,
"total_pages": 784
}
```
***
## Endpoints
### GET /networks
**Response:** Flat array (no wrapper, no page\_info).
```json theme={null}
[
{"id": "ethereum", "display_name": "Ethereum"},
{"id": "solana", "display_name": "Solana"}
]
```
* **33 networks** as of 2026-03-02
* Each item: 2 keys -- `id` (string), `display_name` (string)
* Common IDs: `ethereum`, `solana`, `bsc`, `arbitrum`, `base`, `polygon`, `optimism`, `avalanche`
***
### GET /stats
**Response:** Flat object (no wrapper).
```json theme={null}
{
"chains": 33,
"factories": 205,
"pools": 28185674,
"tokens": 25916463
}
```
* 4 keys: `chains`, `factories`, `pools`, `tokens`
* **Key is `factories`, NOT `dexes`** -- this is the DEX/factory count
***
### GET /search?query=
**Response:** Object with 3 array keys.
```json theme={null}
{
"tokens": [...],
"pools": [...],
"dexes": [...]
}
```
* Case-insensitive
* Empty query → 400
* Token result shape (15 keys):
| Key | Type | Notes |
| ------------------ | ------ | ---------------- |
| `id` | string | Contract address |
| `name` | string | |
| `symbol` | string | |
| `chain` | string | Network ID |
| `type` | string | Often empty |
| `status` | string | e.g. `"visible"` |
| `decimals` | number | |
| `total_supply` | number | |
| `description` | string | |
| `website` | string | |
| `explorer` | string | |
| `price_usd` | number | |
| `liquidity_usd` | number | |
| `volume_usd` | number | |
| `price_usd_change` | number | |
* Pool result shape includes: `id`, `dex_id`, `dex_name`, `chain`, `created_at_block_number`, `created_at`, `volume_usd`, `transactions`, `price_usd`, `last_price_change_usd_5m` (nullable), `last_price_change_usd_1h` (nullable), `last_price_change_usd_24h` (nullable), `tokens` (array)
**NOTE:** Search token shape is DIFFERENT from token details shape. Search tokens do NOT have `has_image`, `added_at`, `price_stats`, `summary`, or `last_updated`.
***
### GET /networks//tokens/
**Response:** Flat object (no wrapper).
Top-level keys (13 total):
| Key | Type | Notes |
| -------------- | ------- | ---------------- |
| `id` | string | Contract address |
| `name` | string | |
| `symbol` | string | |
| `chain` | string | |
| `decimals` | number | |
| `total_supply` | number | |
| `description` | string | |
| `website` | string | |
| `has_image` | boolean | |
| `added_at` | string | ISO 8601 |
| `price_stats` | object | See below |
| `summary` | object | See below |
| `last_updated` | string | ISO 8601 |
**`price_stats`** (4 keys):
| Key | Type |
| ---------- | ------ |
| `high_24h` | number |
| `low_24h` | number |
| `ath` | number |
| `ath_date` | string |
**`summary`** (13 keys):
| Key | Type |
| --------------- | ------ |
| `chain` | string |
| `id` | string |
| `price_usd` | number |
| `fdv` | number |
| `liquidity_usd` | number |
| `pools` | number |
| `24h` | object |
| `6h` | object |
| `1h` | object |
| `30m` | object |
| `15m` | object |
| `5m` | object |
| `1m` | object |
**Price is at:** `response.summary.price_usd`
**`summary.main_pool` does NOT exist.** There is no main\_pool field anywhere in this response.
**Each time window object** (8 keys, same shape for all intervals):
| Key | Type | Notes |
| ----------------------- | ------ | --------------------- |
| `volume` | number | Volume in token units |
| `volume_usd` | number | Volume in USD |
| `sells` | number | **Plural with 's'** |
| `buys` | number | **Plural with 's'** |
| `txns` | number | Total transactions |
| `buy_usd` | number | |
| `sell_usd` | number | |
| `last_price_usd_change` | number | Percentage |
**CRITICAL:** Fields are `sells` and `buys` (plural). NOT `sell`/`buy` (singular). The singular forms do not exist.
***
### GET /networks//multi/prices?tokens=,
**Response:** Flat array (no wrapper, no page\_info).
```json theme={null}
[
{"chain": "ethereum", "id": "0xc02a...", "price_usd": 1975.75},
{"chain": "ethereum", "id": "0xa0b8...", "price_usd": 1.0001}
]
```
* Each item: 3 keys -- `chain`, `id`, `price_usd`
* Order is NOT guaranteed
* Max **10 tokens**. 11+ returns 400 with `{"message":"max 10 tokens allowed."}`
* Invalid/unknown tokens are silently omitted (not an error)
* All-invalid tokens → HTTP 200 with empty array `[]`
* Comma-separated addresses in a single `tokens` param
***
### GET /networks//pools
**Response:** `{pools: [...], page_info: {...}}`
**Parameters:**
| Param | Values | Default |
| ---------- | ------------------------------------------------------------------------------------ | ------------ |
| `page` | 1-indexed integer | 1 |
| `limit` | 1-100 | 10 |
| `order_by` | `volume_usd`, `price_usd`, `transactions`, `last_price_change_usd_24h`, `created_at` | `volume_usd` |
| `sort` | `asc`, `desc` | `desc` |
**Pool item keys** (14 total):
| Key | Type | Notes |
| --------------------------- | ----------- | --------------------- |
| `id` | string | Pool contract address |
| `chain` | string | |
| `dex_id` | string | |
| `dex_name` | string | |
| `fee` | number | |
| `created_at` | string | ISO 8601 |
| `created_at_block_number` | number | |
| `volume_usd` | number | |
| `transactions` | number | |
| `price_usd` | number | |
| `last_price_change_usd_5m` | number/null | Can be null |
| `last_price_change_usd_1h` | number/null | Can be null |
| `last_price_change_usd_24h` | number/null | Can be null |
| `tokens` | array | Token summary objects |
***
### GET /networks//pools/filter
**Response:** `{results: [...], page_info: {...}}`
Note: wrapper key is **`results`**, not `pools`.
**Parameters:**
| Param | Type | Description | Default |
| ---------------- | ------- | -------------------------------------- | ------------ |
| `page` | integer | **1-indexed** | 1 |
| `limit` | integer | 1-100 | 50 |
| `volume_24h_min` | number | Min 24h volume USD | -- |
| `volume_24h_max` | number | Max 24h volume USD | -- |
| `txns_24h_min` | integer | Min transactions 24h | -- |
| `created_after` | integer | UNIX timestamp | -- |
| `created_before` | integer | UNIX timestamp | -- |
| `sort_by` | string | `volume_24h`, `txns_24h`, `created_at` | `volume_24h` |
| `sort_dir` | string | `asc`, `desc` | `desc` |
**Non-functional params** (accepted but return 0 results): `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, `liquidity_usd_max`
All filters combine with **AND** logic.
**Filter result item keys** (7 total):
| Key | Type | Notes |
| ---------------- | ------ | ------------------------------------------- |
| `address` | string | **Not `id`** -- different from pool listing |
| `chain` | string | |
| `dex_id` | string | |
| `volume_usd_24h` | number | **Not `volume_usd`** -- different name |
| `liquidity_usd` | number | |
| `txns_24h` | number | **Not `transactions`** -- different name |
| `created_at` | string | ISO 8601 |
**IMPORTANT field name differences from `/pools` listing:**
| `/pools` listing | `/pools/filter` results |
| ---------------- | ----------------------- |
| `id` | `address` |
| `volume_usd` | `volume_usd_24h` |
| `transactions` | `txns_24h` |
***
### GET /networks//pools/
**Response:** Flat object (no wrapper).
**Parameters:** `inversed` (boolean, default: false) -- flips the token pair price ratio.
**Top-level keys** (20 total):
| Key | Type |
| ------------------------- | ------ |
| `id` | string |
| `chain` | string |
| `dex_id` | string |
| `dex_name` | string |
| `factory_id` | string |
| `fee` | number |
| `created_at` | string |
| `created_at_block_number` | number |
| `last_price` | number |
| `last_price_usd` | number |
| `price_time` | string |
| `price_stats` | object |
| `token_reserves` | object |
| `tokens` | array |
| `24h` | object |
| `6h` | object |
| `1h` | object |
| `30m` | object |
| `15m` | object |
| `5m` | object |
***
### GET /networks//pools//ohlcv
**Response:** Flat array (no wrapper).
**Parameters:**
| Param | Type | Required | Notes |
| ---------- | ------- | -------- | --------------------------------------------------------- |
| `start` | string | **Yes** | ISO 8601 or UNIX timestamp |
| `end` | string | No | Max 1 year from start |
| `limit` | integer | No | Max **366**. Values >366 return 400. |
| `interval` | string | No | `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h` |
| `inversed` | boolean | No | Flip price ratio |
Missing `start` → 400.
**Candle keys** (7 total):
| Key | Type |
| ------------ | ------ |
| `time_open` | string |
| `time_close` | string |
| `open` | number |
| `high` | number |
| `low` | number |
| `close` | number |
| `volume` | number |
***
### GET /networks//pools//transactions
**Response:** `{transactions: [...], page_info: {...}}`
**Parameters:**
| Param | Default | Notes |
| -------- | ------- | ---------------------------------- |
| `page` | 1 | 1-indexed |
| `limit` | 20 | Max 100 |
| `cursor` | -- | Transaction ID for deep pagination |
Max 100 pages via page param. Use `cursor` for deeper.
**Transaction item keys** (24 total):
| Key | Type |
| ------------------------- | ------ |
| `id` | string |
| `log_index` | number |
| `transaction_index` | number |
| `factory_id` | string |
| `pool_id` | string |
| `chain` | string |
| `canonical_chain` | string |
| `sender` | string |
| `recipient` | string |
| `token_0` | string |
| `token_0_symbol` | string |
| `token_1` | string |
| `token_1_symbol` | string |
| `amount_0` | number |
| `amount_1` | number |
| `volume_0` | number |
| `volume_1` | number |
| `price_0` | number |
| `price_0_usd` | number |
| `price_1` | number |
| `price_1_usd` | number |
| `created_at_block_number` | number |
| `created_at_block_hash` | string |
| `created_at` | string |
***
### GET /networks//tokens//pools
**Response:** `{pools: [...], page_info: {...}}`
**Parameters:**
| Param | Default | Notes |
| ---------- | ------------ | --------------------------------------------- |
| `page` | 1 | 1-indexed |
| `limit` | 10 | |
| `order_by` | `volume_usd` | Same options as pool listing |
| `sort` | `desc` | |
| `address` | -- | Filter to pools paired with this second token |
| `reorder` | false | Make queried token primary in all metrics |
***
### GET /networks//dexes
**Response:** `{dexes: [...], page_info: {...}}`
Note: `page_info` exists but may show `total_items: 0` (appears buggy). The `limit` param may be ignored -- all DEXes are returned.
**DEX item keys** (4 total):
| Key | Type |
| ---------- | ------ |
| `dex_id` | string |
| `dex_name` | string |
| `chain` | string |
| `protocol` | string |
***
### GET /networks//dexes//pools
**Response:** `{pools: [...], page_info: {...}}`
Same pool item shape as `/networks/{network}/pools`.
***
## Streaming API
### GET /stream (single token)
```
GET https://streaming.dexpaprika.com/stream?method=t_p&chain={network}&address={token_address}
```
### POST /stream (multiple tokens, up to 2,000)
```
POST https://streaming.dexpaprika.com/stream
Content-Type: application/json
Accept: text/event-stream
[
{"chain": "ethereum", "address": "0xc02a...", "method": "t_p"},
{"chain": "solana", "address": "So111...", "method": "t_p"}
]
```
### SSE event format
```
data: {"a":"0xc02a...","c":"ethereum","p":"2060.04","t":1772466306,"t_p":1772466304}
event: t_p
```
Note: `data:` line comes BEFORE `event:` line.
| Field | Type | Description |
| ----- | ---------- | ------------------------------------------------------- |
| `a` | string | Token address |
| `c` | string | Chain ID |
| `p` | **string** | Price in USD. **String, not number.** Parse as decimal. |
| `t` | integer | Server send timestamp (UNIX seconds) |
| `t_p` | integer | Price data timestamp (UNIX seconds) |
### Streaming constraints
* Max **2,000** assets per POST
* **All assets must be valid** -- one invalid asset cancels entire stream with 400
* Global limit: 10,000 concurrent streams per server
* First events may take **10-20 seconds** to arrive
* Events arrive \~1/second after initial connection
### Streaming errors
| Status | Cause | Message |
| ------ | ---------------------- | ----------------------------------------------------------- |
| 200 | Connected | Stream begins |
| 400 | Bad chain | `{"message":"unsupported chain"}` |
| 400 | Bad address | `{"message":"asset not found"}` |
| 400 | Invalid asset in batch | `{"message":"unsupported chain"}` (entire stream cancelled) |
| 404 | Bare URL / wrong path | `{"message":"Not Found"}` |
| 429 | Global limit | Retry with backoff |
In-stream errors arrive as SSE: `event: error` + `data: {"message": "..."}`
***
## Error handling (REST)
| Status | Cause | Example |
| ------ | -------------- | ---------------------------------------------------------------------------------------------- |
| 200 | Success | Normal response |
| 400 | Invalid params | Bad `order_by`, `sort`, `sort_by`, empty query, limit >100, OHLCV limit >366, >10 batch tokens |
| 404 | Not found | Invalid network, token, or pool address |
| 410 | Deprecated | `GET /pools` (use `/networks/{network}/pools`) |
| 429 | Rate limit | 10,000 req/day exceeded |
| 500 | Server error | Retry with backoff |
***
## Constraints summary
| Constraint | Value | Enforcement |
| ---------------------------- | ------------------- | ------------------------ |
| Rate limit | 10,000 requests/day | |
| Pagination max per page | 100 | 400 if exceeded |
| Pagination indexing | 1-indexed | page=0 treated as page=1 |
| Batch prices max tokens | 10 | 400 if exceeded |
| OHLCV max data points | 366 | 400 if exceeded |
| OHLCV max range | 1 year | |
| Transaction max pages | 100 | Use cursor for deeper |
| Streaming max assets/request | 2,000 | |
| Streaming global concurrent | 10,000 per server | |
***
## Common token addresses
| Token | Chain | Address |
| ----- | -------- | --------------------------------------------- |
| WETH | ethereum | `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` |
| USDC | ethereum | `0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48` |
| USDT | ethereum | `0xdac17f958d2ee523a2206206994597c13d831ec7` |
| USDC | polygon | `0x2791bca1f2de4661ed88a30c99a7a9449aa84174` |
| SOL | solana | `So11111111111111111111111111111111111111112` |
***
## Key gotchas for implementers
1. **`sells`/`buys` not `sell`/`buy`** -- plural forms only in token summary time windows
2. **`summary.main_pool` does not exist** -- to find a token's best pool, query `/tokens/{address}/pools?order_by=volume_usd&sort=desc&limit=1`
3. **Filter uses different field names** than pool listing: `address` not `id`, `volume_usd_24h` not `volume_usd`, `txns_24h` not `transactions`
4. **Filter wrapper key is `results`**, not `pools`
5. **Stats key is `factories`**, not `dexes`
6. **Pages are 1-indexed everywhere** -- page=0 is silently normalized to page=1
7. **Limits are enforced, not capped** -- limit=200 returns 400, not 100 results
8. **Streaming `p` is a string** -- parse as decimal for precision, do not treat as JSON number
9. **Streaming bare URL is 404** -- only `/stream` path works
10. **Search token shape ≠ token details shape** -- different fields at top level
11. **OHLCV is the only flat-array list response** -- all other list endpoints wrap in `{key: [...], page_info: {...}}`
12. **DEXes endpoint `page_info` is buggy** -- may show `total_items: 0` while returning all results
13. **Non-functional filter params** (`volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, `liquidity_usd_max`) are accepted but always return 0 results
14. **First streaming events may take 10-20 seconds** -- don't use short timeouts
# DexPaprika DEX API Go SDK -- On‑chain Liquidity & Swap Data Client
Source: https://docs.dexpaprika.com/get-started/sdk-go
The official Go client library for the DexPaprika API, providing easy access to decentralized exchange data across multiple blockchain networks
See also: [REST intro](/api-reference/introduction),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools](/api-reference/pools/get-a-pool-on-a-network)
## Installation
```bash theme={null}
go get github.com/coinpaprika/dexpaprika-sdk-go
```
## Prerequisites
* Go 1.24 or higher
* Connection to the internet to access the DexPaprika API
* No API key required
## Quick Example: Get Token Price
```go theme={null}
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func main() {
// Create client
client := dexpaprika.NewClient()
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Get WETH token details on Ethereum
token, err := client.Tokens.GetDetails(ctx, "ethereum", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
if err != nil {
log.Fatalf("Error getting token details: %v", err)
}
fmt.Printf("%s: $%.2f\n", token.Name, token.PriceUSD)
// Output: Wrapped Ether: $3245.67
}
```
## API Methods Reference
Parameters marked with an asterisk (\*) are required.
### client.Networks.List(ctx)
**Endpoint:** [GET `/networks`](/api-reference/networks/get-a-list-of-available-blockchain-networks)
Gets all supported blockchain networks including Ethereum, Solana, etc.
**Parameters:**
* `ctx`\* - Context for API request
**Returns:** Network IDs, names, and related information. [Response Structure](/api-reference/networks/get-a-list-of-available-blockchain-networks).
```go theme={null}
networks, err := client.Networks.List(ctx)
```
### client.Networks.ListDexes(ctx, networkId, options)
**Endpoint:** [GET `/networks/{network}/dexes`](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network)
Gets all DEXes on a specific network.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network (e.g., 'ethereum', 'solana')
* `options` - ListOptions containing pagination parameters:
* `Page` - Page number for pagination (starts at 0)
* `Limit` - Number of results per page
**Returns:** DEX IDs, names, pool counts, and volume information. [Response Structure](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network).
```go theme={null}
options := &dexpaprika.ListOptions{
Page: 0,
Limit: 10,
}
dexes, err := client.Networks.ListDexes(ctx, "ethereum", options)
```
### client.Pools.List(ctx, options)
**Endpoint:** [GET `/pools`](/api-reference/pools/get-top-x-pools)
Gets top pools across all networks with pagination.
**Parameters:**
* `ctx`\* - Context for API request
* `options` - ListOptions containing pagination and sorting parameters:
* `Page` - Page number for pagination (starts at 0)
* `Limit` - Number of results per page
* `Sort` - Sort direction ('asc' or 'desc')
* `OrderBy` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
**Returns:** Paginated list of pool objects with pricing data. [Response Structure](/api-reference/pools/get-top-x-pools).
```go theme={null}
options := &dexpaprika.ListOptions{
Limit: 10,
OrderBy: "volume_usd",
Sort: "desc",
}
pools, err := client.Pools.List(ctx, options)
```
***
### client.Pools.ListByNetwork(ctx, networkId, options)
**Endpoint:** [GET `/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network)
Gets pools on a specific network with pagination and sorting options.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `options` - ListOptions containing pagination and sorting parameters
**Returns:** Paginated list of pools for the given network. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-network).
```go theme={null}
options := &dexpaprika.ListOptions{
Limit: 5,
OrderBy: "volume_usd",
Sort: "desc",
}
pools, err := client.Pools.ListByNetwork(ctx, "ethereum", options)
```
***
### client.Pools.ListByDex(ctx, networkId, dexId, options)
**Endpoint:** [GET `/networks/{network}/dexes/{dex}/pools`](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
Gets pools on a specific DEX within a network with pagination.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `dexId`\* - ID of the DEX
* `options` - ListOptions containing pagination and sorting parameters
**Returns:** Paginated list of pools for the specified DEX. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-networks-dex).
```go theme={null}
options := &dexpaprika.ListOptions{
Limit: 10,
OrderBy: "volume_usd",
Sort: "desc",
}
pools, err := client.Pools.ListByDex(ctx, "ethereum", "uniswap_v2", options)
```
***
### client.Pools.GetDetails(ctx, networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}`](/api-reference/pools/get-a-pool-on-a-network)
Gets detailed information about a specific pool.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - PoolDetailOptions containing:
* `Inversed` - Whether to invert the price ratio (boolean)
**Returns:** Detailed pool information including tokens, volumes, liquidity, and more. [Response Structure](/api-reference/pools/get-a-pool-on-a-network).
```go theme={null}
options := &dexpaprika.PoolDetailOptions{
Inversed: false,
}
poolDetails, err := client.Pools.GetDetails(ctx, "ethereum", "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc", options)
```
***
### client.Pools.GetTransactions(ctx, networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/transactions`](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages)
Gets transaction history for a specific pool with pagination.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - ListOptions containing pagination parameters
**Returns:** List of transactions with details about tokens, amounts, and timestamps. [Response Structure](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages).
```go theme={null}
options := &dexpaprika.ListOptions{
Limit: 20,
Page: 0,
}
transactions, err := client.Pools.GetTransactions(ctx, "ethereum", "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc", options)
```
***
### client.Pools.GetOHLCV(ctx, networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/ohlcv`](/api-reference/pools/get-ohlcv-data-for-a-pool-pair)
Gets OHLCV (Open, High, Low, Close, Volume) chart data for a pool.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - OHLCVOptions containing:
* `Start`\* - Start time (time.Time or string ISO format)
* `End` - End time (optional)
* `Limit` - Number of data points to return
* `Interval` - Time interval ('1h', '6h', '24h', etc.)
* `Inversed` - Whether to invert the price ratio (boolean)
**Returns:** Array of OHLCV data points for the specified time range and interval. [Response Structure](/api-reference/pools/get-ohlcv-data-for-a-pool-pair).
```go theme={null}
// Start time 7 days ago
startTime := time.Now().AddDate(0, 0, -7)
options := &dexpaprika.OHLCVOptions{
Start: startTime,
Limit: 100,
Interval: "1h",
Inversed: false,
}
ohlcv, err := client.Pools.GetOHLCV(ctx, "ethereum", "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc", options)
```
### client.Tokens.GetDetails(ctx, networkId, tokenAddress)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}`](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
Gets comprehensive token information.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token contract address
**Returns:** Token details including price, market cap, volume, and metadata. [Response Structure](/api-reference/tokens/get-a-tokens-latest-data-on-a-network).
```go theme={null}
token, err := client.Tokens.GetDetails(ctx, "ethereum", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
```
***
### client.Tokens.GetPools(ctx, networkId, tokenAddress, options, additionalTokenAddress)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}/pools`](/api-reference/tokens/get-top-x-pools-for-a-token)
Gets pools containing a specific token.
**Parameters:**
* `ctx`\* - Context for API request
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token contract address
* `options` - ListOptions containing pagination and sorting parameters
* `additionalTokenAddress` - Optional second token address to filter for pairs with both tokens
**Returns:** List of pools where the queried token is found. [Response Structure](/api-reference/tokens/get-top-x-pools-for-a-token).
```go theme={null}
options := &dexpaprika.ListOptions{
Limit: 10,
Page: 0,
OrderBy: "volume_usd",
Sort: "desc",
}
// Get all WETH-USDC pools
pools, err := client.Tokens.GetPools(
ctx,
"ethereum",
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // WETH
options,
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // USDC
)
```
### client.Search.Search(ctx, query)
**Endpoint:** [GET `/search`](/api-reference/search/search-for-tokens-pools-and-dexes)
Searches across tokens, pools, and DEXes using a query string.
**Parameters:**
* `ctx`\* - Context for API request
* `query`\* - Search query string
**Returns:** Matching entities from all categories (tokens, pools, DEXes). [Response Structure](/api-reference/search/search-for-tokens-pools-and-dexes).
```go theme={null}
results, err := client.Search.Search(ctx, "ethereum")
```
### client.Utils.GetStats(ctx)
**Endpoint:** [GET `/stats`](/api-reference/utils/retrieve-high-level-asset-statistics)
Gets platform-wide statistics.
**Parameters:**
* `ctx`\* - Context for API request
**Returns:** Counts of chains, DEXes, pools, and tokens indexed. [Response Structure](/api-reference/utils/retrieve-high-level-asset-statistics).
```go theme={null}
stats, err := client.Utils.GetStats(ctx)
```
## Complete Example
```go theme={null}
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func main() {
// Initialize client
client := dexpaprika.NewClient()
// Create context with timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Get Ethereum network details
networks, err := client.Networks.List(ctx)
if err != nil {
log.Fatalf("Error fetching networks: %v", err)
}
var ethereum *dexpaprika.Network
for _, network := range networks {
if network.ID == "ethereum" {
ethereum = &network
break
}
}
if ethereum == nil {
log.Fatal("Ethereum network not found")
}
fmt.Printf("Found %s with %d DEXes\n", ethereum.DisplayName, ethereum.DexesCount)
// Get WETH token details
weth, err := client.Tokens.GetDetails(
ctx,
"ethereum",
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
)
if err != nil {
log.Fatalf("Error fetching token details: %v", err)
}
fmt.Printf("%s price: $%.2f\n", weth.Name, weth.PriceUSD)
// Find WETH/USDC pools
options := &dexpaprika.ListOptions{
Limit: 5,
Page: 0,
OrderBy: "volume_usd",
Sort: "desc",
}
pools, err := client.Tokens.GetPools(
ctx,
"ethereum",
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // WETH
options,
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // USDC
)
if err != nil {
log.Fatalf("Error fetching pools: %v", err)
}
// Show top pools
fmt.Println("Top WETH/USDC pools:")
for _, pool := range pools.Pools {
fmt.Printf("%s: $%.2f 24h volume\n", pool.DexName, pool.VolumeUSD)
}
}
```
## Advanced Features
### Error Handling
```go theme={null}
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func handleAPIErrors() {
client := dexpaprika.NewClient()
ctx := context.Background()
// Attempt to get a token with an invalid address
_, err := client.Tokens.GetDetails(ctx, "ethereum", "0xinvalidaddress")
if err != nil {
// Check for specific error types
var apiErr *dexpaprika.APIError
if errors.As(err, &apiErr) {
switch apiErr.StatusCode {
case 404:
fmt.Println("Token not found")
case 429:
fmt.Println("Rate limit exceeded, retry after a delay")
case 500:
fmt.Println("Server error, retry may succeed")
default:
fmt.Printf("API error: %s\n", apiErr.Message)
}
} else {
// Handle non-API errors (like network issues)
fmt.Printf("Non-API error: %v\n", err)
}
// Check if error is retryable
if dexpaprika.IsRetryable(err) {
fmt.Println("This error is retryable")
}
}
}
```
### Caching
```go theme={null}
import (
"context"
"fmt"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func useCaching() {
// Create a regular client
client := dexpaprika.NewClient()
// Create a cached client with 5-minute TTL
cachedClient := dexpaprika.NewCachedClient(client, nil, 5*time.Minute)
// Create context
ctx := context.Background()
// First call - hits the API
startTime := time.Now()
networks, err := cachedClient.GetNetworks(ctx)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("First call (API): %d networks, took %v\n", len(networks), time.Since(startTime))
// Second call - served from cache (much faster)
startTime = time.Now()
networks, err = cachedClient.GetNetworks(ctx)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Second call (cached): %d networks, took %v\n", len(networks), time.Since(startTime))
}
```
### Pagination Helpers
```go theme={null}
import (
"context"
"fmt"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func usePagination() {
client := dexpaprika.NewClient()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Create a paginator for Ethereum pools with 50 items per page
options := &dexpaprika.ListOptions{
Limit: 50,
OrderBy: "volume_usd",
Sort: "desc",
}
paginator := dexpaprika.NewPoolsPaginator(client, options).ForNetwork("ethereum")
// Count total pools processed
totalPools := 0
// Process first 3 pages (or fewer if there aren't that many)
for i := 0; i < 3 && paginator.HasNextPage(); i++ {
// Get next page of results
if err := paginator.GetNextPage(ctx); err != nil {
fmt.Printf("Error getting page: %v\n", err)
break
}
// Process current page
pools := paginator.GetCurrentPage()
totalPools += len(pools)
// Process first few pools in each page
fmt.Printf("=== Page %d ===\n", i+1)
for j, pool := range pools {
if j >= 3 {
fmt.Printf("...and %d more pools\n", len(pools)-3)
break
}
fmt.Printf("%s: $%.2f 24h volume\n", pool.DexName, pool.VolumeUSD)
}
}
fmt.Printf("Processed %d pools total\n", totalPools)
}
```
### Custom Configuration
```go theme={null}
import (
"net/http"
"time"
"github.com/coinpaprika/dexpaprika-sdk-go/dexpaprika"
)
func configureClient() *dexpaprika.Client {
// Create a client with custom configuration
client := dexpaprika.NewClient(
// Custom HTTP client with longer timeout
dexpaprika.WithHTTPClient(&http.Client{
Timeout: 60 * time.Second,
}),
// Custom retry configuration (5 retries with backoff)
dexpaprika.WithRetryConfig(5, 2*time.Second, 30*time.Second),
// Rate limiting to 3 requests per second
dexpaprika.WithRateLimit(3.0),
// Custom user agent
dexpaprika.WithUserAgent("MyApp/1.0 DexPaprikaClient"),
)
return client
}
```
## Resources
* [GitHub Repository](https://github.com/coinpaprika/dexpaprika-sdk-go)
* [DexPaprika Website](https://dexpaprika.com)
* [API Reference](/api-reference/introduction)
## API Status
The DexPaprika API provides consistent data with stable endpoints. No API key is currently required to access the service. We aim to maintain backward compatibility and provide notice of any significant changes.
### FAQs
No. The API is public; no keys or registration required.
Use Coverage Checker or list Networks and query Tokens/Pools to discover addresses.
Use pools/transactions endpoints with `pool_address`, `network`, and time/paging params as documented.
Handle retries for transient HTTP errors and keep calls reasonable for public endpoints.
# DexPaprika DEX API PHP SDK -- On‑chain Liquidity & Swap Data Client
Source: https://docs.dexpaprika.com/get-started/sdk-php
The official PHP client library for the DexPaprika API, providing easy access to decentralized exchange data across multiple blockchain networks
See also: [REST intro](/api-reference/introduction),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools](/api-reference/pools/get-a-pool-on-a-network)
## Installation
```bash theme={null}
# Using Composer
composer require coinpaprika/dexpaprika-sdk-php
# From source
git clone https://github.com/coinpaprika/dexpaprika-sdk-php.git
cd dexpaprika-sdk-php
composer install
```
## Prerequisites
* PHP 7.4 or higher
* [Composer](https://getcomposer.org/)
* `ext-json` PHP extension
* Connection to the internet to access the DexPaprika API
* No API key required
## PHP SDK Quickstart
```php theme={null}
tokens->getTokenDetails('ethereum', '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2');
echo "{$weth['name']}: \${$weth['price_usd']}";
// Output: Wrapped Ether: $3245.67
```
## API Methods Reference
Parameters marked with an asterisk (\*) are required.
### client->networks->getNetworks()
**Endpoint:** [GET `/networks`](/api-reference/networks/get-a-list-of-available-blockchain-networks)
Gets all supported blockchain networks including Ethereum, Solana, etc.
**Parameters:** None
**Returns:** Network IDs, names, and related information. [Response Structure](/api-reference/networks/get-a-list-of-available-blockchain-networks).
```php theme={null}
// Get all networks
$networks = $client->networks->getNetworks();
echo "Found {$networks['networks']} networks";
```
### client->networks->findNetwork(networkId)
Gets a network by its ID.
**Parameters:**
* `networkId`\* - ID of the network to find (e.g., 'ethereum')
**Returns:** The network information or null if not found.
```php theme={null}
// Find Ethereum network
$ethereum = $client->networks->findNetwork('ethereum');
if ($ethereum) {
echo "Found network: {$ethereum['display_name']}";
}
```
### client->networks->getNetworkDexes(networkId, options)
**Endpoint:** [GET `/networks/{network}/dexes`](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network)
Gets all DEXes on a specific network.
**Parameters:**
* `networkId`\* - ID of the network (e.g., 'ethereum', 'solana')
* `options` - Additional options:
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
**Returns:** DEX IDs, names, pool counts, and volume information. [Response Structure](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network).
```php theme={null}
// Get all DEXes on Ethereum
$dexes = $client->networks->getNetworkDexes('ethereum', ['limit' => 10]);
echo "Found {$dexes['dexes']} DEXes on Ethereum";
```
### client->networks->findDex(networkId, dexId)
Finds a specific DEX on a network by its ID.
**Parameters:**
* `networkId`\* - ID of the network
* `dexId`\* - ID of the DEX to find
**Returns:** The DEX information or null if not found.
```php theme={null}
// Find Uniswap V3 on Ethereum
$dex = $client->networks->findDex('ethereum', 'uniswap-v3');
if ($dex) {
echo "Found DEX: {$dex['name']}";
}
```
### client->pools->getTopPools(options)
**Endpoint:** [GET `/pools`](/api-reference/pools/get-top-x-pools)
Gets top pools across all networks with pagination.
**Parameters:**
* `options` - Additional options:
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `orderBy` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
* `sort` - Sort direction ('asc' or 'desc')
**Returns:** Paginated list of pool objects with pricing data. [Response Structure](/api-reference/pools/get-top-x-pools).
```php theme={null}
// Get top 10 pools by volume
$topPools = $client->pools->getTopPools([
'limit' => 10,
'orderBy' => 'volume_usd',
'sort' => 'desc'
]);
echo "Top pool: {$topPools['pools'][0]['dex_name']}";
```
### client->pools->getNetworkPools(networkId, options)
**Endpoint:** [GET `/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network)
Gets pools on a specific network with pagination and sorting options.
**Parameters:**
* `networkId`\* - ID of the network
* `options` - Additional options:
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `orderBy` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
* `sort` - Sort direction ('asc' or 'desc')
**Returns:** Paginated list of pools for the given network. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-network).
```php theme={null}
// Get top 5 pools on Ethereum by volume
$pools = $client->pools->getNetworkPools('ethereum', [
'limit' => 5,
'orderBy' => 'volume_usd',
'sort' => 'desc'
]);
echo "Found {$pools['pools']} pools on Ethereum";
```
### client->pools->getDexPools(networkId, dexId, options)
**Endpoint:** [GET `/networks/{network}/dexes/{dex}/pools`](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
Gets pools on a specific DEX within a network with pagination.
**Parameters:**
* `networkId`\* - ID of the network
* `dexId`\* - ID of the DEX
* `options` - Additional options:
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `orderBy` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
* `sort` - Sort direction ('asc' or 'desc')
**Returns:** Paginated list of pools for the specified DEX. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-networks-dex).
```php theme={null}
// Get top 10 Uniswap V3 pools on Ethereum
$uniswapPools = $client->pools->getDexPools('ethereum', 'uniswap-v3', [
'limit' => 10,
'orderBy' => 'volume_usd',
'sort' => 'desc'
]);
echo "Found {$uniswapPools['pools']} Uniswap V3 pools";
```
### client->pools->getPoolDetails(networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}`](/api-reference/pools/get-a-pool-on-a-network)
Gets detailed information about a specific pool.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - Additional options:
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Detailed pool information including tokens, volumes, liquidity, and more. [Response Structure](/api-reference/pools/get-a-pool-on-a-network).
```php theme={null}
// Get details for a specific pool (WETH/USDC on Uniswap V2)
$pool = $client->pools->getPoolDetails(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
['inversed' => false]
);
echo "Pool: {$pool['tokens'][0]['symbol']}/{$pool['tokens'][1]['symbol']}";
```
### client->pools->getPoolTransactions(networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/transactions`](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages)
Gets transaction history for a specific pool with pagination.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - Additional options:
* `page` - Page number for pagination
* `limit` - Number of transactions per page
* `cursor` - Transaction ID used for cursor-based pagination
**Returns:** List of transactions with details about tokens, amounts, and timestamps. [Response Structure](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages).
```php theme={null}
// Get the latest 20 transactions for a pool
$transactions = $client->pools->getPoolTransactions(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
['limit' => 20]
);
$latestTxTime = date('Y-m-d H:i:s', $transactions['transactions'][0]['block_timestamp']);
echo "Latest transaction: {$latestTxTime}";
```
### client->pools->getPoolOHLCV(networkId, poolAddress, start, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/ohlcv`](/api-reference/pools/get-ohlcv-data-for-a-pool-pair)
Gets OHLCV (Open, High, Low, Close, Volume) chart data for a pool.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `start`\* - Start time (ISO date string, YYYY-MM-DD, or Unix timestamp)
* `options` - Additional options:
* `end` - End time (optional)
* `limit` - Number of data points to return
* `interval` - Time interval ('1m', '5m', '15m', '30m', '1h', '6h', '12h', '24h')
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Array of OHLCV data points for the specified time range and interval. [Response Structure](/api-reference/pools/get-ohlcv-data-for-a-pool-pair).
```php theme={null}
// Get OHLCV data for the past 7 days with 1-hour intervals
$endDate = date('Y-m-d');
$startDate = date('Y-m-d', strtotime('-7 days'));
$ohlcv = $client->pools->getPoolOHLCV(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
$startDate,
[
'end' => $endDate,
'interval' => '1h',
'limit' => 168 // 24 * 7 hours
]
);
echo "Received {$ohlcv} OHLCV data points";
```
### client->tokens->getTokenDetails(networkId, tokenAddress)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}`](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
Gets comprehensive token information.
**Parameters:**
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token contract address
**Returns:** Token details including price, market cap, volume, and metadata. [Response Structure](/api-reference/tokens/get-a-tokens-latest-data-on-a-network).
```php theme={null}
// Get WETH token details
$weth = $client->tokens->getTokenDetails(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
);
echo "{$weth['name']} price: \${$weth['price_usd']}";
```
### client->tokens->getTokenPools(networkId, tokenAddress, options)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}/pools`](/api-reference/tokens/get-top-x-pools-for-a-token)
Gets pools containing a specific token.
**Parameters:**
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token contract address
* `options` - Additional options:
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `sort` - Sort direction ('asc' or 'desc')
* `orderBy` - Field to sort by ('volume\_usd', 'price\_usd', etc.)
* `address` - Optional second token address to filter for pairs with both tokens
**Returns:** List of pools where the queried token is found. [Response Structure](/api-reference/tokens/get-top-x-pools-for-a-token).
```php theme={null}
// Get WETH/USDC pools
$pools = $client->tokens->getTokenPools(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH
[
'limit' => 5,
'orderBy' => 'volume_usd',
'sort' => 'desc',
'address' => '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' // USDC
]
);
foreach ($pools['pools'] as $pool) {
echo "{$pool['dex_name']}: $" . number_format($pool['volume_usd'], 2) . " 24h volume\n";
}
```
### client->tokens->findToken(networkId, tokenSymbol)
Attempts to find a token by its symbol.
**Parameters:**
* `networkId`\* - ID of the network
* `tokenSymbol`\* - Token symbol to search for
**Returns:** Token details if found.
```php theme={null}
// Find WETH token by symbol
try {
$token = $client->tokens->findToken('ethereum', 'WETH');
echo "Found token {$token['name']} at {$token['address']}";
} catch (Exception $e) {
echo "Token not found";
}
```
### client->search->search(query)
**Endpoint:** [GET `/search`](/api-reference/search/search-for-tokens-pools-and-dexes)
Searches across tokens, pools, and DEXes using a query string.
**Parameters:**
* `query`\* - Search query string
**Returns:** Matching entities from all categories (tokens, pools, DEXes). [Response Structure](/api-reference/search/search-for-tokens-pools-and-dexes).
```php theme={null}
// Search for "ethereum" across all entities
$results = $client->search->search("ethereum");
echo "Found {$results['summary']['total_tokens']} tokens\n";
echo "Found {$results['summary']['total_pools']} pools\n";
echo "Found {$results['summary']['total_dexes']} dexes\n";
```
### client->stats->getStats()
**Endpoint:** [GET `/stats`](/api-reference/utils/retrieve-high-level-asset-statistics)
Gets platform-wide statistics.
**Parameters:** None
**Returns:** Counts of chains, DEXes, pools, and tokens indexed. [Response Structure](/api-reference/utils/retrieve-high-level-asset-statistics).
```php theme={null}
// Get platform statistics
$stats = $client->stats->getStats();
echo "Total chains: {$stats['chains']}\n";
echo "Total DEXes: {$stats['dexes']}\n";
echo "Total pools: {$stats['pools']}\n";
echo "Total tokens: {$stats['tokens']}\n";
```
## Complete Example
```php theme={null}
networks->getNetworks();
$ethereum = null;
foreach ($networks['networks'] as $network) {
if ($network['id'] === 'ethereum') {
$ethereum = $network;
break;
}
}
echo "Found {$ethereum['display_name']} with {$ethereum['dexes_count']} DEXes\n";
// Get WETH token details
$weth = $client->tokens->getTokenDetails(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
);
echo "{$weth['name']} price: \${$weth['price_usd']}\n";
// Find WETH/USDC pools
$pools = $client->tokens->getTokenPools(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH
[
'limit' => 5,
'orderBy' => 'volume_usd',
'sort' => 'desc',
'address' => '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' // USDC
]
);
// Show top pools
echo "Top WETH/USDC pools:\n";
foreach ($pools['pools'] as $pool) {
echo "{$pool['dex_name']}: $" . number_format($pool['volume_usd'], 2) . " 24h volume\n";
}
} catch (DexPaprikaApiException $e) {
echo "API Error: {$e->getMessage()}\n";
} catch (Exception $e) {
echo "Error: {$e->getMessage()}\n";
}
}
main();
```
## Advanced Features
### Error Handling
```php theme={null}
tokens->getTokenDetails('ethereum', '0xinvalidaddress');
} catch (NotFoundException $e) {
echo "Token not found: {$e->getMessage()}\n";
} catch (RateLimitException $e) {
echo "Rate limit exceeded. Try again in: {$e->getRetryAfter()} seconds\n";
} catch (ServerException $e) {
echo "Server error occurred: {$e->getMessage()}\n";
} catch (NetworkException $e) {
echo "Network error: {$e->getMessage()}\n";
} catch (DexPaprikaApiException $e) {
echo "API error: {$e->getMessage()} (Code: {$e->getCode()})\n";
} catch (Exception $e) {
echo "General error: {$e->getMessage()}\n";
}
// The SDK automatically retries on these status codes:
// 408 (Request Timeout), 429 (Too Many Requests),
// 500, 502, 503, 504 (Server Errors)
// Custom retry configuration
use DexPaprika\Config;
$config = new Config();
$config->setMaxRetries(4); // Number of retry attempts (default: 3)
$config->setRetryDelays([100, 500, 1000, 5000]); // Delay in milliseconds
$client = new Client(null, null, false, $config);
// All API requests will now use these retry settings
try {
$networks = $client->networks->getNetworks();
} catch (Exception $e) {
echo "Failed after multiple retries: {$e->getMessage()}\n";
}
```
### Caching System
```php theme={null}
setupCache();
// First call - hits the API
$startTime = microtime(true);
$networks = $client->networks->getNetworks();
$firstCallTime = microtime(true) - $startTime;
echo "First call (API): {$networks['networks']} networks, took {$firstCallTime} s\n";
// Second call - served from cache (much faster)
$startTime = microtime(true);
$networks = $client->networks->getNetworks();
$secondCallTime = microtime(true) - $startTime;
echo "Second call (cached): {$networks['networks']} networks, took {$secondCallTime} s\n";
echo "Cache speedup: {$firstCallTime / $secondCallTime} x\n";
// You can skip the cache when you need fresh data
$client->getConfig()->setCacheEnabled(false);
$freshNetworks = $client->networks->getNetworks();
$client->getConfig()->setCacheEnabled(true);
// Custom cache configuration
$cache = new FilesystemCache('/path/to/custom/cache');
$client->setupCache($cache, 300); // 5 minutes TTL
// Clear the entire cache
$client->getConfig()->getCache()->clear();
```
### Pagination Helper
```php theme={null}
pools->getNetworkPools(
$networkId,
[
'page' => $page,
'limit' => $limit,
'sort' => 'desc',
'orderBy' => 'volume_usd'
]
);
$allPools = array_merge($allPools, $response['pools']);
// Check if there are more pages
$hasMore = count($response['pools']) == $limit;
$page++;
// Adding a small delay to avoid hitting rate limits
usleep(100000); // 100ms
}
echo "Fetched a total of {$allPools} pools on {$networkId}\n";
return $allPools;
}
// Alternative approach using built-in paginator
function fetchAllPoolsWithPaginator($networkId) {
$client = new Client();
$allPools = [];
// Create a paginator for network pools
$paginator = $client->createPaginator(
$client->pools,
'getNetworkPools',
[
$networkId,
[
'limit' => 50,
'orderBy' => 'volume_usd',
'sort' => 'desc'
]
]
);
// Iterate through all pages (or up to a maximum)
$paginator->setMaxPages(10); // Optional: limit to 10 pages
foreach ($paginator as $page => $response) {
$allPools = array_merge($allPools, $response['pools']);
echo "Processed page {$page}, got {$response['pools']} pools\n";
}
echo "Fetched a total of {$allPools} pools on {$networkId}\n";
return $allPools;
}
// Usage example
$ethereumPools = fetchAllPools('ethereum');
// or
$ethereumPools = fetchAllPoolsWithPaginator('ethereum');
```
### Working with Objects
```php theme={null}
setResponseFormat('object');
$client = new Client(null, null, true, $config);
// Get pool details
$pool = $client->pools->getPoolDetails(
'ethereum',
'0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640' // USDC/WETH Uniswap v3 pool
);
// Access pool properties as object properties
echo "Pool: {$pool->tokens[0]->symbol}/{$pool->tokens[1]->symbol}\n";
echo "Volume (24h): \${$pool->day->volume_usd}\n";
echo "Transactions (24h): {$pool->day->txns}\n";
echo "Price: \${$pool->last_price_usd}\n";
// Time interval data is available for multiple timeframes
echo "1h price change: {$pool->hour1->last_price_usd_change}%\n";
echo "24h price change: {$pool->day->last_price_usd_change}%\n";
// Combining with array-based response for specific API calls
$client->getConfig()->setResponseFormat('array');
$networks = $client->networks->getNetworks();
// Back to object mode
$client->getConfig()->setResponseFormat('object');
$token = $client->tokens->getTokenDetails('ethereum', '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2');
echo "{$token->name} price: \${$token->price_usd}\n";
```
## Resources
* [GitHub Repository](https://github.com/coinpaprika/dexpaprika-sdk-php)
* [DexPaprika Website](https://dexpaprika.com)
* [API Reference](/api-reference/introduction)
* [Discord Community](https://discord.gg/DhJge5TUGM)
## API Status
The DexPaprika API provides consistent data with stable endpoints. No API key is currently required to access the service. We aim to maintain backward compatibility and provide notice of any significant changes.
### FAQs
No. The API is public; no keys or registration required.
Use Coverage Checker or list Networks and query Tokens/Pools to discover addresses.
Use pools/transactions endpoints with `pool_address`, `network`, and time/paging params as documented.
Handle retries for transient HTTP errors and keep calls reasonable for public endpoints.
# DexPaprika DEX API Python SDK -- On‑chain Liquidity & Swap Data Client
Source: https://docs.dexpaprika.com/get-started/sdk-python
The official Python client library for the DexPaprika API, providing easy access to decentralized exchange data across multiple blockchain networks
See also: [REST intro](/api-reference/introduction),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools](/api-reference/pools/get-a-pool-on-a-network)
## Installation
```bash theme={null}
# Using pip
pip install dexpaprika-sdk
# Using poetry
poetry add dexpaprika-sdk
# From source
git clone https://github.com/coinpaprika/dexpaprika-sdk-python.git
cd dexpaprika-sdk-python
pip install -e .
```
## Prerequisites
* Python 3.8 or higher
* Connection to the internet to access the DexPaprika API
* No API key required
## Quick Example: Get Token Price
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
from dexpaprika_sdk.models import TokenDetails # Type hint example
# Create client and get WETH price on Ethereum
client = DexPaprikaClient()
token: TokenDetails = client.tokens.get_details("ethereum", "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
print(f"{token.name}: ${token.price_usd}")
# Output: Wrapped Ether: $3245.67
```
## API Methods Reference
Parameters marked with an asterisk (\*) are required.
### client.networks.list()
**Endpoint:** [GET `/networks`](/api-reference/networks/get-a-list-of-available-blockchain-networks)
Gets all supported blockchain networks including Ethereum, Solana, etc.
**Parameters:** None
**Returns:** Network IDs, names, and related information. [Response Structure](/api-reference/networks/get-a-list-of-available-blockchain-networks).
```python theme={null}
# Get all networks
networks = client.networks.list()
print(f"Found {len(networks)} networks")
```
### client.dexes.list\_by\_network(network\_id, page, limit)
**Endpoint:** [GET `/networks/{network}/dexes`](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network)
Gets all DEXes on a specific network.
**Parameters:**
* `network_id`\* - ID of the network (e.g., 'ethereum', 'solana')
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
**Returns:** DEX IDs, names, pool counts, and volume information. [Response Structure](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network).
```python theme={null}
# Get all DEXes on Ethereum
dexes = client.dexes.list_by_network("ethereum")
print(f"Found {len(dexes.dexes)} DEXes on Ethereum")
```
### client.pools.list(page, limit, sort, order\_by)
**Endpoint:** [GET `/pools`](/api-reference/pools/get-top-x-pools)
Gets top pools across all networks with pagination.
**Parameters:**
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `sort` - Sort direction ('asc' or 'desc')
* `order_by` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
**Returns:** Paginated list of pool objects with pricing data. [Response Structure](/api-reference/pools/get-top-x-pools).
```python theme={null}
# Get top 10 pools by volume
top_pools = client.pools.list(limit=10, order_by="volume_usd", sort="desc")
print(f"Top pool: {top_pools.pools[0].dex_name}")
```
***
### client.pools.list\_by\_network(network\_id, page, limit, sort, order\_by)
**Endpoint:** [GET `/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network)
Gets pools on a specific network with pagination and sorting options.
**Parameters:**
* `network_id`\* - ID of the network
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `sort` - Sort direction ('asc' or 'desc')
* `order_by` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
**Returns:** Paginated list of pools for the given network. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-network).
```python theme={null}
# Get top 5 pools on Ethereum by volume
pools = client.pools.list_by_network(
network_id="ethereum",
limit=5,
order_by="volume_usd",
sort="desc"
)
print(f"Found {len(pools.pools)} pools on Ethereum")
```
***
### client.pools.list\_by\_dex(network\_id, dex\_id, page, limit, sort, order\_by)
**Endpoint:** [GET `/networks/{network}/dexes/{dex}/pools`](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
Gets pools on a specific DEX within a network with pagination.
**Parameters:**
* `network_id`\* - ID of the network
* `dex_id`\* - ID of the DEX
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `sort` - Sort direction ('asc' or 'desc')
* `order_by` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
**Returns:** Paginated list of pools for the specified DEX. [Response Structure](/api-reference/pools/get-top-x-pools-on-a-networks-dex).
```python theme={null}
# Get top 10 Uniswap V2 pools on Ethereum
uniswap_pools = client.pools.list_by_dex(
network_id="ethereum",
dex_id="uniswap_v2",
limit=10,
order_by="volume_usd",
sort="desc"
)
print(f"Found {len(uniswap_pools.pools)} Uniswap V2 pools")
```
***
### client.pools.get\_details(network\_id, pool\_address, inversed)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}`](/api-reference/pools/get-a-pool-on-a-network)
Gets detailed information about a specific pool.
**Parameters:**
* `network_id`\* - ID of the network
* `pool_address`\* - On-chain address of the pool
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Detailed pool information including tokens, volumes, liquidity, and more. [Response Structure](/api-reference/pools/get-a-pool-on-a-network).
```python theme={null}
from dexpaprika_sdk.models import PoolDetails # Type hint example
# Get details for a specific pool (WETH/USDC on Uniswap V2)
pool: PoolDetails = client.pools.get_details(
network_id="ethereum",
pool_address="0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc",
inversed=False
)
print(f"Pool: {pool.tokens[0].symbol}/{pool.tokens[1].symbol}")
```
***
### client.pools.get\_transactions(network\_id, pool\_address, page, limit)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/transactions`](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages)
Gets transaction history for a specific pool with pagination.
**Parameters:**
* `network_id`\* - ID of the network
* `pool_address`\* - On-chain address of the pool
* `page` - Page number for pagination
* `limit` - Number of transactions per page
**Returns:** List of transactions with details about tokens, amounts, and timestamps. [Response Structure](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages).
```python theme={null}
# Get the latest 20 transactions for a pool
transactions = client.pools.get_transactions(
network_id="ethereum",
pool_address="0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc",
limit=20
)
from datetime import datetime
latest_tx_time = datetime.fromtimestamp(transactions.transactions[0].block_timestamp).strftime('%Y-%m-%d %H:%M:%S')
print(f"Latest transaction: {latest_tx_time}")
```
***
### client.pools.get\_ohlcv(network\_id, pool\_address, start, end, limit, interval, inversed)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/ohlcv`](/api-reference/pools/get-ohlcv-data-for-a-pool-pair)
Gets OHLCV (Open, High, Low, Close, Volume) chart data for a pool.
**Parameters:**
* `network_id`\* - ID of the network
* `pool_address`\* - On-chain address of the pool
* `start`\* - Start time (ISO date string, YYYY-MM-DD, or Unix timestamp)
* `end` - End time (optional)
* `limit` - Number of data points to return
* `interval` - Time interval ('1m', '5m', '15m', '30m', '1h', '6h', '12h', '24h')
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Array of OHLCV data points for the specified time range and interval. [Response Structure](/api-reference/pools/get-ohlcv-data-for-a-pool-pair).
```python theme={null}
from datetime import datetime, timedelta
# Get OHLCV data for the past 7 days with 1-hour intervals
end_date = datetime.now()
start_date = end_date - timedelta(days=7)
ohlcv = client.pools.get_ohlcv(
network_id="ethereum",
pool_address="0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc",
start=start_date.strftime("%Y-%m-%d"),
end=end_date.strftime("%Y-%m-%d"),
interval="1h",
limit=168 # 24 * 7 hours
)
print(f"Received {len(ohlcv)} OHLCV data points")
```
### client.tokens.get\_details(network\_id, token\_address)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}`](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
Gets comprehensive token information.
**Parameters:**
* `network_id`\* - ID of the network
* `token_address`\* - Token contract address
**Returns:** Token details including price, market cap, volume, and metadata. [Response Structure](/api-reference/tokens/get-a-tokens-latest-data-on-a-network).
```python theme={null}
# Get WETH token details
weth = client.tokens.get_details(
network_id="ethereum",
token_address="0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
)
print(f"{weth.name} price: ${weth.price_usd}")
```
***
### client.tokens.get\_pools(network\_id, token\_address, page, limit, sort, order\_by, address)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}/pools`](/api-reference/tokens/get-top-x-pools-for-a-token)
Gets pools containing a specific token.
**Parameters:**
* `network_id`\* - ID of the network
* `token_address`\* - Token contract address
* `page` - Page number for pagination (starts at 0)
* `limit` - Number of results per page
* `sort` - Sort direction ('asc' or 'desc')
* `order_by` - Field to sort by ('volume\_usd', 'price\_usd', etc.)
* `address` - Optional second token address to filter for pairs with both tokens
**Returns:** List of pools where the queried token is found. [Response Structure](/api-reference/tokens/get-top-x-pools-for-a-token).
```python theme={null}
# Get WETH/USDC pools
pools = client.tokens.get_pools(
network_id="ethereum",
token_address="0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", # WETH
limit=5,
order_by="volume_usd",
sort="desc",
address="0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" # USDC
)
for pool in pools.pools:
print(f"{pool.dex_name}: ${pool.volume_usd:,.2f} 24h volume")
```
### client.search.search(query)
**Endpoint:** [GET `/search`](/api-reference/search/search-for-tokens-pools-and-dexes)
Searches across tokens, pools, and DEXes using a query string.
**Parameters:**
* `query`\* - Search query string
**Returns:** Matching entities from all categories (tokens, pools, DEXes). [Response Structure](/api-reference/search/search-for-tokens-pools-and-dexes).
```python theme={null}
# Search for "ethereum" across all entities
results = client.search.search("ethereum")
print(f"Found {len(results.tokens)} tokens")
print(f"Found {len(results.pools)} pools")
print(f"Found {len(results.dexes)} dexes")
```
### client.utils.get\_stats()
**Endpoint:** [GET `/stats`](/api-reference/utils/retrieve-high-level-asset-statistics)
Gets platform-wide statistics.
**Parameters:** None
**Returns:** Counts of chains, DEXes, pools, and tokens indexed. [Response Structure](/api-reference/utils/retrieve-high-level-asset-statistics).
```python theme={null}
# Get platform statistics
stats = client.utils.get_stats()
print(f"Total chains: {stats.chains}")
print(f"Total DEXes: {stats.dexes}")
print(f"Total pools: {stats.pools}")
print(f"Total tokens: {stats.tokens}")
```
## Complete Example
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
def main():
# Initialize client
client = DexPaprikaClient()
# Get Ethereum network details
networks = client.networks.list()
ethereum = next((n for n in networks if n.id == "ethereum"), None)
print(f"Found {ethereum.display_name} with {ethereum.dexes_count} DEXes")
# Get WETH token details
weth = client.tokens.get_details(
network_id="ethereum",
token_address="0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
)
print(f"{weth.name} price: ${weth.price_usd}")
# Find WETH/USDC pools
pools = client.tokens.get_pools(
network_id="ethereum",
token_address="0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", # WETH
limit=5,
order_by="volume_usd",
sort="desc",
address="0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" # USDC
)
# Show top pools
print('Top WETH/USDC pools:')
for pool in pools.pools:
print(f"{pool.dex_name}: ${pool.volume_usd:,.2f} 24h volume")
if __name__ == "__main__":
main()
```
## Advanced Features
### Error Handling
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
import requests
# Basic error handling
try:
client = DexPaprikaClient()
token = client.tokens.get_details("ethereum", "0xinvalidaddress")
except Exception as e:
if "404" in str(e):
print("Token not found")
elif "429" in str(e):
print("Rate limit exceeded")
else:
print(f"An error occurred: {e}")
# The SDK automatically retries on these status codes:
# 408 (Request Timeout), 429 (Too Many Requests),
# 500, 502, 503, 504 (Server Errors)
# Custom retry configuration
client = DexPaprikaClient(
max_retries=4, # Number of retry attempts (default: 4)
backoff_times=[0.1, 0.5, 1.0, 5.0] # Backoff times in seconds
)
# All API requests will now use these retry settings
try:
networks = client.networks.list()
except requests.exceptions.RetryError as e:
print(f"Failed after multiple retries: {e}")
```
### Caching System
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
import time
# The SDK includes built-in caching by default
# Demonstration of cache behavior
# Create a regular client with default cache (5 minutes TTL)
client = DexPaprikaClient()
# First call - hits the API
start_time = time.time()
networks = client.networks.list()
first_call_time = time.time() - start_time
print(f"First call (API): {len(networks)} networks, took {first_call_time:.4f}s")
# Second call - served from cache (much faster)
start_time = time.time()
networks = client.networks.list()
second_call_time = time.time() - start_time
print(f"Second call (cached): {len(networks)} networks, took {second_call_time:.4f}s")
print(f"Cache speedup: {first_call_time / second_call_time:.1f}x")
# You can skip the cache when you need fresh data
fresh_networks = client.networks._get("/networks", skip_cache=True)
# Clear the entire cache
client.clear_cache()
# Clear cache only for specific endpoints
client.clear_cache(endpoint_prefix="/networks")
# Different types of data have different cache durations:
# - Network data: 24 hours
# - Pool data: 5 minutes
# - Token data: 10 minutes
# - Statistics: 15 minutes
# - Other data: 5 minutes (default)
```
### Pagination Helper
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
import time
def fetch_all_pools(network_id):
client = DexPaprikaClient()
all_pools = []
page = 0
limit = 50
has_more = True
while has_more:
response = client.pools.list_by_network(
network_id=network_id,
page=page,
limit=limit,
sort="desc",
order_by="volume_usd"
)
all_pools.extend(response.pools)
# Check if there are more pages
has_more = len(response.pools) == limit
page += 1
# Adding a small delay to avoid hitting rate limits
time.sleep(0.1)
print(f"Fetched a total of {len(all_pools)} pools on {network_id}")
return all_pools
# Usage example
ethereum_pools = fetch_all_pools("ethereum")
```
### Parameter Validation
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
# The SDK automatically validates parameters before making API requests
client = DexPaprikaClient()
# Invalid parameter examples will raise helpful error messages
try:
# Invalid network ID
client.pools.list_by_network(network_id="", limit=5)
except ValueError as e:
print(e) # "network_id is required"
try:
# Invalid sort parameter
client.pools.list(sort="invalid_sort")
except ValueError as e:
print(e) # "sort must be one of: asc, desc"
try:
# Invalid limit parameter
client.pools.list(limit=500)
except ValueError as e:
print(e) # "limit must be at most 100"
```
### Working with Models
```python theme={null}
from dexpaprika_sdk import DexPaprikaClient
from dexpaprika_sdk.models import PoolDetails # Type hint example
client = DexPaprikaClient()
# Get pool details
pool: PoolDetails = client.pools.get_details(
network_id="ethereum",
pool_address="0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" # USDC/WETH Uniswap v3 pool
)
# Access pool properties with type checking and auto-completion
print(f"Pool: {pool.tokens[0].symbol}/{pool.tokens[1].symbol}")
print(f"Volume (24h): ${pool.day.volume_usd:.2f}")
print(f"Transactions (24h): {pool.day.txns}")
print(f"Price: ${pool.last_price_usd:.4f}")
# Time interval data is available for multiple timeframes
print(f"1h price change: {pool.hour1.last_price_usd_change:.2f}%")
print(f"24h price change: {pool.day.last_price_usd_change:.2f}%")
# All API responses are converted to typed Pydantic models
# This provides automatic validation, serialization/deserialization,
# and IDE auto-completion support through Python type hints
```
## Resources
* [GitHub Repository](https://github.com/coinpaprika/dexpaprika-sdk-python)
* [DexPaprika Website](https://dexpaprika.com)
* [API Reference](/api-reference/introduction)
* [Discord Community](https://discord.gg/DhJge5TUGM)
## API Status
The DexPaprika API provides consistent data with stable endpoints. No API key is currently required to access the service. We aim to maintain backward compatibility and provide notice of any significant changes.
### FAQs
No. The API is public; no keys or registration required.
Use Coverage Checker or list Networks and query Tokens/Pools to discover addresses.
Use pools/transactions endpoints with `pool_address`, `network`, and time/paging params as documented.
Handle retries for transient HTTP errors and keep calls reasonable for public endpoints.
# DexPaprika DEX API TypeScript SDK -- On‑chain Liquidity & Swap Data Client
Source: https://docs.dexpaprika.com/get-started/sdk-ts
JavaScript client library for accessing decentralized exchange data across multiple blockchain networks
See also: [REST intro](/api-reference/introduction),
[Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Pools](/api-reference/pools/get-a-pool-on-a-network)
## Prerequisites
* Node.js 14.0.0 or higher
* Connection to the internet to access the DexPaprika API
* No API key required
## Installation
Install the DexPaprika SDK using your preferred package manager:
```bash theme={null}
# using npm
npm install @dexpaprika/sdk
# using yarn
yarn add @dexpaprika/sdk
# using pnpm
pnpm add @dexpaprika/sdk
```
## Quick Example
```javascript theme={null}
import { DexPaprikaClient } from '@dexpaprika/sdk';
// Initialize the client
const client = new DexPaprikaClient();
// Get the price of Wrapped Ether (WETH) on Ethereum
async function getWethPrice() {
const wethAddress = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
const token = await client.tokens.getDetails('ethereum', wethAddress);
console.log(`Current WETH price: $${token.price_usd}`);
}
getWethPrice();
```
## API Methods Reference
All API methods in the DexPaprika SDK follow a consistent pattern, accepting required parameters first, followed by an optional `options` object for additional configuration. This options pattern provides flexibility while keeping the API clean and easy to use.
For example, most listing methods accept pagination and sorting options:
```javascript theme={null}
// Get pools with custom pagination and sorting
const pools = await client.pools.listByNetwork('ethereum', {
page: 0, // start at first page
limit: 20, // get 20 results
sort: 'desc', // sort descending
orderBy: 'volume_usd' // sort by volume
});
```
### client.networks.list()
**Endpoint:** [GET `/networks`](/api-reference/networks/get-networks)
Retrieves all supported blockchain networks and their metadata.
**Parameters:** None
**Returns:** Array of network objects containing network ID, name, and other information.
```javascript theme={null}
const networks = await client.networks.list();
console.log(`Supported networks: ${networks.length}`);
```
***
### client.networks.getDexes(networkId, options)
**Endpoint:** [GET `/networks/{network}/dexes`](/api-reference/networks/get-dexes-of-a-network)
Retrieves all DEXes on a specific network.
**Parameters:**
* `networkId`\* - Network ID (e.g., "ethereum", "solana")
* `options` - Optional configuration:
* `page` - Page number for pagination
* `limit` - Number of DEXes per page
**Returns:** Paginated list of DEX objects with name, ID, and metadata.
```javascript theme={null}
const dexes = await client.networks.getDexes('ethereum', { limit: 20 });
dexes.data.forEach(dex => console.log(dex.name));
```
### client.dexes.get(networkId, dexId)
**Endpoint:** [GET `/networks/{network}/dexes/{dex}`](/api-reference/dexes/get-a-dex-on-a-network)
Gets information about a specific DEX on a network.
**Parameters:**
* `networkId`\* - Network ID (e.g., "ethereum", "solana")
* `dexId`\* - DEX identifier (e.g., "uniswap\_v2")
**Returns:** DEX details including name, website, API endpoints if available, and statistics.
```javascript theme={null}
const dex = await client.dexes.get('ethereum', 'uniswap_v2');
console.log(`${dex.name} stats: Volume $${dex.volume_usd_24h}, Pools: ${dex.pool_count}`);
```
### client.pools.list(options)
**Endpoint:** [GET `/pools`](/api-reference/pools/get-top-x-pools)
Gets top pools across all networks with pagination.
**Parameters:**
* `options` - Options object for pagination and sorting:
* `page` - Page number for pagination
* `limit` - Number of pools per page
* `sort` - Sort direction ('asc' or 'desc')
* `orderBy` - Field to sort by ('volume\_usd', 'price\_usd', etc.)
**Returns:** Paginated list of pool objects with pricing data.
```javascript theme={null}
const pools = await client.pools.list({
limit: 10,
orderBy: 'volume_usd',
sort: 'desc'
});
console.log(`Top pool: ${pools.data[0].token0.symbol}/${pools.data[0].token1.symbol}`);
```
***
### client.pools.listByNetwork(networkId, options)
**Endpoint:** [GET `/networks/{network}/pools`](/api-reference/pools/get-top-x-pools-on-a-network)
Gets pools on a specific network with pagination and sorting options.
**Parameters:**
* `networkId`\* - ID of the network
* `options` - Options object for pagination and sorting:
* `page` - Page number for pagination
* `limit` - Number of pools per page
* `sort` - Sort direction ('asc' or 'desc')
* `orderBy` - Field to sort by ('volume\_usd', 'price\_usd', etc.)
**Returns:** Paginated list of pools for the given network.
```javascript theme={null}
const ethereumPools = await client.pools.listByNetwork('ethereum', {
limit: 5,
orderBy: 'volume_usd',
sort: 'desc'
});
console.log(`Found ${ethereumPools.meta.total} pools on Ethereum`);
```
***
### client.pools.listByDex(networkId, dexId, options)
**Endpoint:** [GET `/networks/{network}/dexes/{dex}/pools`](/api-reference/pools/get-top-x-pools-on-a-networks-dex)
Gets pools on a specific DEX within a network with pagination.
**Parameters:**
* `networkId`\* - ID of the network
* `dexId`\* - ID of the DEX
* `options` - Options object for pagination and sorting:
* `page` - Page number for pagination
* `limit` - Number of pools per page
* `sort` - Sort direction ('asc' or 'desc')
* `orderBy` - Field to sort by ('volume\_usd', 'price\_usd', etc.)
**Returns:** Paginated list of pools for the specified DEX.
```javascript theme={null}
const uniswapPools = await client.pools.listByDex('ethereum', 'uniswap_v2', {
limit: 10,
orderBy: 'volume_usd',
sort: 'desc'
});
console.log(`Top Uniswap V2 pool: ${uniswapPools.data[0].token0.symbol}/${uniswapPools.data[0].token1.symbol}`);
```
***
### client.pools.getDetails(networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}`](/api-reference/pools/get-a-pool-on-a-network)
Gets detailed information about a specific pool.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - Options object:
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Detailed pool information including tokens, volumes, liquidity, and more.
```javascript theme={null}
// Get details for a specific pool (WETH/USDC on Uniswap V2)
const pool = await client.pools.getDetails(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
{ inversed: false }
);
console.log(`Pool: ${pool.token0.symbol}/${pool.token1.symbol}`);
```
***
### client.pools.getTransactions(networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/transactions`](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages)
Gets transaction history for a specific pool with pagination.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options` - Options object for pagination:
* `page` - Page number for pagination
* `limit` - Number of transactions per page
* `cursor` - Transaction ID for cursor-based pagination
**Returns:** List of transactions with details about tokens, amounts, and timestamps.
```javascript theme={null}
// Get the latest 20 transactions for a pool
const transactions = await client.pools.getTransactions(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
{ limit: 20 }
);
console.log(`Latest transaction: ${transactions.data[0].hash}`);
```
***
### client.pools.getOHLCV(networkId, poolAddress, options)
**Endpoint:** [GET `/networks/{network}/pools/{pool_address}/ohlcv`](/api-reference/pools/get-ohlcv-data-for-a-pool-pair)
Gets OHLCV (Open, High, Low, Close, Volume) chart data for a pool.
**Parameters:**
* `networkId`\* - ID of the network
* `poolAddress`\* - On-chain address of the pool
* `options`\* - OHLCV options object:
* `start`\* - Start time (ISO date string or timestamp)
* `end` - End time (optional)
* `limit` - Number of data points to return
* `interval` - Time interval ('1h', '6h', '24h', etc.)
* `inversed` - Whether to invert the price ratio (boolean)
**Returns:** Array of OHLCV data points for the specified time range and interval.
```javascript theme={null}
// Get hourly price data for the past week
const startDate = new Date();
startDate.setDate(startDate.getDate() - 7);
const ohlcvData = await client.pools.getOHLCV(
'ethereum',
'0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc',
{
start: startDate.toISOString(),
interval: '1h',
limit: 168 // 7 days * 24 hours
}
);
console.log(`Data points: ${ohlcvData.length}`);
console.log(`Current price: ${ohlcvData[ohlcvData.length-1].close}`);
```
### client.tokens.getDetails(networkId, tokenAddress)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}`](/api-reference/tokens/get-a-token-on-a-network)
Gets detailed information about a specific token on a network.
**Parameters:**
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token address or identifier
**Returns:** Detailed token information including price, volume, and metadata.
```javascript theme={null}
// Get details for WETH on Ethereum
const weth = await client.tokens.getDetails(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
);
console.log(`${weth.name} (${weth.symbol}): $${weth.price_usd}`);
```
***
### client.tokens.getPools(networkId, tokenAddress, options)
**Endpoint:** [GET `/networks/{network}/tokens/{token_address}/pools`](/api-reference/tokens/get-token-pools-on-a-network)
Gets a list of liquidity pools that include the specified token.
**Parameters:**
* `networkId`\* - ID of the network
* `tokenAddress`\* - Token address or identifier
* `options` - Options object for filtering, pagination and sorting:
* `page` - Page number for pagination
* `limit` - Number of pools per page
* `sort` - Sort direction ('asc' or 'desc')
* `orderBy` - Field to sort by ('volume\_usd', 'liquidity\_usd', etc.)
* `pairWith` - Optional second token address to filter for specific pairs
**Returns:** Paginated list of pools containing the specified token.
```javascript theme={null}
// Find WETH/USDC pools on Ethereum
const wethAddress = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
const usdcAddress = '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';
const pools = await client.tokens.getPools(
'ethereum',
wethAddress,
{
limit: 5,
orderBy: 'volume_usd',
sort: 'desc',
pairWith: usdcAddress
}
);
pools.data.forEach(pool => {
console.log(`${pool.dex.name}: $${pool.volume_usd_24h} 24h volume`);
});
```
### client.search.search(query)
**Endpoint:** [GET `/search`](/api-reference/search/search-for-tokens-pools-and-dexes)
Searches for tokens, pools, and DEXes by name or identifier.
**Parameters:**
* `query`\* - Search term (e.g., "uniswap", "bitcoin", or a token address)
**Returns:** Search results organized by category (tokens, pools, DEXes).
```javascript theme={null}
// Search for "ethereum"
const results = await client.search.search('ethereum');
console.log(`Found ${results.tokens.length} tokens`);
console.log(`Found ${results.pools.length} pools`);
console.log(`Found ${results.dexes.length} DEXes`);
```
### client.utils.getStats()
**Endpoint:** [GET `/stats`](/api-reference/utils/get-stats)
Gets high-level statistics about the DexPaprika ecosystem.
**Parameters:** None
**Returns:** Statistics about chains, DEXes, pools, and tokens.
```javascript theme={null}
const stats = await client.utils.getStats();
console.log(`Networks: ${stats.networks}`);
console.log(`DEXes: ${stats.dexes}`);
console.log(`Pools: ${stats.pools}`);
console.log(`Tokens: ${stats.tokens}`);
```
## Complete Example
```javascript theme={null}
import { DexPaprikaClient } from '@dexpaprika/sdk';
async function main() {
// Initialize client
const client = new DexPaprikaClient();
// Get Ethereum network details
const networks = await client.networks.list();
const ethereum = networks.find(n => n.id === 'ethereum');
console.log(`Found ${ethereum.name} with ${ethereum.dexes_count} DEXes`);
// Get WETH token details
const weth = await client.tokens.getDetails(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2'
);
console.log(`${weth.name} price: $${weth.price_usd}`);
// Find WETH/USDC pools
const pools = await client.tokens.getPools(
'ethereum',
'0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', // WETH
{
limit: 5,
sort: 'desc',
orderBy: 'volume_usd',
pairWith: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' // USDC
}
);
// Show top pools
console.log('Top WETH/USDC pools:');
pools.data.forEach(pool => {
console.log(`${pool.dex.name}: $${pool.volume_usd_24h.toLocaleString()} 24h volume`);
});
}
main().catch(console.error);
```
## Advanced Features
### Error Handling
```javascript theme={null}
import { DexPaprikaClient, parseError } from '@dexpaprika/sdk';
// Basic error handling
try {
const client = new DexPaprikaClient();
const token = await client.tokens.getDetails('ethereum', '0xinvalidaddress');
} catch (error) {
// Using the helper to extract the most relevant error message
console.error('Error:', parseError(error));
// Or handle specific error cases manually
if (error.response?.status === 404) {
console.error('Resource not found');
} else if (error.response?.status === 429) {
console.error('Rate limit exceeded');
}
}
// The SDK automatically retries on these status codes:
// 408 (Request Timeout), 429 (Too Many Requests),
// 500, 502, 503, 504 (Server Errors)
// Custom retry configuration
const client = new DexPaprikaClient('https://api.dexpaprika.com', {}, {
retry: {
maxRetries: 3,
delaySequenceMs: [200, 500, 1000],
retryableStatuses: [429, 500, 503]
}
});
```
### Caching
```javascript theme={null}
import { DexPaprikaClient, Cache } from '@dexpaprika/sdk';
// The SDK includes built-in caching by default
// This example shows how to configure it
// Configure caching with custom settings
const client = new DexPaprikaClient('https://api.dexpaprika.com', {}, {
cache: {
ttl: 60 * 1000, // 1 minute cache TTL (default is 5 minutes)
maxSize: 100, // Store up to 100 responses (default is 1000)
enabled: true // Enable caching (enabled by default)
}
});
// Demonstration of cache behavior
async function demonstrateCaching() {
console.time('First call');
await client.networks.list(); // Makes an API request
console.timeEnd('First call');
console.time('Second call');
await client.networks.list(); // Returns cached result
console.timeEnd('Second call');
// You can also manage the cache manually
client.clearCache(); // Clear all cached data
console.log(client.cacheSize); // Get current cache size
client.setCacheEnabled(false); // Disable caching
}
// Using the Cache class directly
const manualCache = new Cache({
ttl: 30 * 1000, // 30 second TTL
maxSize: 50 // Store maximum 50 items
});
manualCache.set('myKey', { data: 'example data' });
const data = manualCache.get('myKey');
manualCache.delete('myKey');
manualCache.clear();
```
### Pagination Helper
```javascript theme={null}
import { DexPaprikaClient } from '@dexpaprika/sdk';
async function fetchAllPools(networkId) {
const client = new DexPaprikaClient();
const allPools = [];
let page = 0;
const limit = 50;
let hasMore = true;
while (hasMore) {
const response = await client.pools.listByNetwork(
networkId,
{
page,
limit,
sort: 'desc',
orderBy: 'volume_usd'
}
);
allPools.push(...response.data);
// Check if there are more pages
hasMore = response.data.length === limit;
page++;
// Adding a small delay to avoid hitting rate limits
await new Promise(resolve => setTimeout(resolve, 100));
}
console.log(`Fetched a total of ${allPools.length} pools on ${networkId}`);
return allPools;
}
// Usage example
fetchAllPools('ethereum').catch(console.error);
```
### Custom Configuration
```javascript theme={null}
import { DexPaprikaClient } from '@dexpaprika/sdk';
import axios from 'axios';
// Create a custom axios instance
const axiosInstance = axios.create({
timeout: 60000, // 60 second timeout
headers: {
'User-Agent': 'MyApp/1.0 DexPaprikaSDK'
}
});
// Create client with custom configuration
const client = new DexPaprikaClient(
'https://api.dexpaprika.com', // Base URL (optional)
axiosInstance, // Custom axios instance (optional)
{
// Retry configuration (optional)
retry: {
maxRetries: 5,
delaySequenceMs: [100, 500, 1000, 2000, 5000],
retryableStatuses: [429, 500, 502, 503, 504]
},
// Cache configuration (optional)
cache: {
ttl: 10 * 60 * 1000, // 10 minutes TTL
maxSize: 500, // Store up to 500 responses
enabled: true // Enable caching
}
}
);
// Usage example
async function fetchWithCustomClient() {
try {
const networks = await client.networks.list();
console.log(`Fetched ${networks.length} networks with custom client`);
} catch (err) {
console.error('Error:', err);
}
}
```
## Resources
* [GitHub Repository](https://github.com/coinpaprika/dexpaprika-sdk-js)
* [DexPaprika Website](https://dexpaprika.com)
* [API Reference](/api-reference/introduction)
## API Status
The DexPaprika API provides consistent data with stable endpoints. No API key is currently required to access the service. We aim to maintain backward compatibility and provide notice of any significant changes.
### FAQs
No. The API is public; no keys or registration required.
Use Coverage Checker or list Networks and query Tokens/Pools to discover addresses.
Use pools/transactions endpoints with `pool_address`, `network`, and time/paging params as documented.
Handle retries for transient HTTP errors and keep calls reasonable for public endpoints.
# DexPaprika crypto DEX API - on-chain liquidity & swap data for developers
Source: https://docs.dexpaprika.com/introduction
Real‑time DEX and on‑chain cryptocurrency data: liquidity pools, swaps, token prices, and transactions across 33 blockchain networks via REST API and SSE streaming.
**Enterprise customer?** Use the [Pro API](/api-pro/introduction) for unlimited requests, dedicated infrastructure, and priority support.
See also: [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Liquidity pool endpoint](/api-reference/pools/get-a-pool-on-a-network),
[Swap transactions](/api-reference/pools/get-transactions-of-a-pool-on-a-network-paging-can-be-used-up-to-100-pages),
[Token data](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
Jump straight into the API documentation and start making requests within minutes
Learn step-by-step how to integrate DexPaprika into your applications
## DEX API quickstart
You can also make your first request directly in our API Playground available in the API Reference section. Visit [GET Token](/api-reference/tokens/get-a-tokens-latest-data-on-a-network) to try it out.
In the next steps we will make a GET request to the [Token](/api-reference/tokens/get-a-tokens-latest-data-on-a-network) endpoint in order to get the latest price in USD of SOL. All we need is the network ID and the token address.
* Network ID: `solana`
* Token address: `So11111111111111111111111111111111111111112`
You can find the list of all supported networks in the [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks) endpoint.
Simply make a GET request to the following endpoint in order to fetch latest data about any token. In this case we will use the specified above network ID and token address to populate the endpoint in a format of `https://api.dexpaprika.com/networks/{network_id}/tokens/{address}`.
```bash bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112"
```
```python python.py theme={null}
import requests
response = requests.get("https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112")
print(response.json())
```
```javascript javascript.js theme={null}
fetch("https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112")
.then(response => response.json())
.then(data => console.log(data));
```
This will return quite lengthy response of the latest data about Solana (SOL) that will look similar to this. We send a lot of data in the response, so in the next step we will extract only the price of SOL in USD.
```json Response [expandable] theme={null}
{
"id": "So11111111111111111111111111111111111111112",
"name": "Wrapped SOL",
"symbol": "SOL",
"chain": "solana",
"decimals": 9,
"total_supply": 8765530.584758602,
"description": "",
"website": "",
"has_image": false,
"added_at": "2024-10-04T08:30:05Z",
"price_stats": {
"high_24h": 90.42,
"low_24h": 79.83,
"ath": 2094.38,
"ath_date": "2025-02-18T22:43:00Z"
},
"summary": {
"chain": "solana",
"id": "So11111111111111111111111111111111111111112",
"price_usd": 84.70,
"fdv": 742439936.27,
"liquidity_usd": 720592129.48,
"pools": 68563,
"24h": {
"volume": 107273758.93,
"volume_usd": 9250815075.33,
"sells": 15608060,
"buys": 11886100,
"txns": 27495179,
"buy_usd": 4623901804.94,
"sell_usd": 4626913270.38,
"last_price_usd_change": 1.37
},
"6h": {
"volume": 26773795.06,
"volume_usd": 2287803995.05,
"sells": 3934865,
"buys": 2727726,
"txns": 6662749,
"buy_usd": 1137172848.86,
"sell_usd": 1150631146.19,
"last_price_usd_change": -2.20
},
"1h": {
"volume": 3910905.40,
"volume_usd": 329548955.23,
"sells": 637805,
"buys": 431908,
"txns": 1069763,
"buy_usd": 163705382.93,
"sell_usd": 165843572.30,
"last_price_usd_change": -0.74
},
"30m": {
"volume": 2433489.04,
"volume_usd": 204746406.88,
"sells": 318226,
"buys": 221887,
"txns": 540140,
"buy_usd": 101344488.38,
"sell_usd": 103401918.50,
"last_price_usd_change": -0.34
},
"15m": {
"volume": 850690.44,
"volume_usd": 71384438.53,
"sells": 163924,
"buys": 110052,
"txns": 273982,
"buy_usd": 35058520.01,
"sell_usd": 36325918.52,
"last_price_usd_change": -0.27
},
"5m": {
"volume": 240013.44,
"volume_usd": 20122986.10,
"sells": 48267,
"buys": 33557,
"txns": 81826,
"buy_usd": 9957259.82,
"sell_usd": 10165726.28,
"last_price_usd_change": 0.05
}
},
"last_updated": "2026-03-03T10:19:44.540471814Z"
}
```
As you can see, the response is very rich of data. You can extract only the price of SOL in USD from the full response by navigating to the `summary` object (*or any other object*) and then to the `price_usd` key (*or any other key*) simply by modyfying the previously used GET request:
```bash bash theme={null}
curl -s "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112" | jq '.summary.price_usd'
```
```python python.py theme={null}
import requests
response = requests.get("https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112")
print(response.json()["summary"]["price_usd"])
```
```javascript javascript.js theme={null}
fetch("https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112")
.then(response => response.json())
.then(data => {
const onlyPrice = data.summary.price_usd;
console.log(onlyPrice);
});
```
And as a result you will get the price of SOL in USD:
```json summary.price_usd theme={null}
84.70
```
Congratulations! You just successfully retrieved the latest price of SOL in USD!
New:Advanced pool filtering -- filter pools by volume, transactions, and creation date. Plus batch token prices in a single request.
## Next steps
Jump straight into the API documentation and start making requests within minutes
Learn step-by-step how to integrate DexPaprika into your applications
## Popular use cases
Get real-time and historical price data for any token across 33 blockchains
Access detailed liquidity pool data across major DEXes on any network
Analyze trading volumes, price changes, and market trends
Compare prices and liquidity across different DEXes
## DexPaprika API support
We're here to help you succeed with DexPaprika.
Connect with our community and get real-time support
Share your experience and help us improve
## Explore supported on-chain networks
Browse the full [networks list](/api-reference/networks/get-a-list-of-available-blockchain-networks) to find the correct `network` parameter for your requests.
### FAQs
No. The DexPaprika API is public; no API keys or registration required.
Liquidity pools, swap transactions, token metrics/prices, and network coverage across multiple chains.
Use the Coverage Checker tool or the Networks/Token endpoints to locate addresses.
Collection is near real‑time; responses reflect the latest indexed blocks and events.
**Looking for enterprise solutions?** We offer dedicated support, higher rate limits, and custom features.
[Contact our team](mailto:support@coinpaprika.com) to learn more.
# Common patterns and workflows
Source: https://docs.dexpaprika.com/knowledge-base/common-patterns
Standard workflows for DexPaprika API: looking up token prices, finding pools, getting historical data, filtering pools, batch pricing, and combining REST with streaming for real-time updates.
## Overview
This page covers the most common sequences of API calls for typical tasks. Each pattern shows the exact endpoints, parameters, and response fields you need.
Base URL: `https://api.dexpaprika.com`
***
## Pattern 1: Get a token's price
**When you know the network and token address:**
```bash theme={null}
curl "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112"
```
The price is at `response.summary.price_usd`.
**When you only know the token name or symbol:**
1. Search first:
```bash theme={null}
curl "https://api.dexpaprika.com/search?query=jupiter"
```
2. From the `tokens` array in the response, find the matching token. Note the `chain` and `id` (address) fields.
3. Call the token endpoint:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/{chain}/tokens/{id}"
```
***
## Pattern 2: Compare prices of multiple tokens
Use batch pricing when you need prices for 2–10 tokens on the same network:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
```
Response is an array of `{id, chain, price_usd}` objects. Order is not guaranteed. Tokens without pricing data are silently omitted (not an error).
**Limits:** Max 10 tokens per request. More than 10 returns HTTP 400. Zero tokens also returns HTTP 400.
For tokens across different networks, make separate requests per network.
***
## Pattern 3: Find top pools on a network
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?limit=10&order_by=volume_usd&sort=desc&page=1"
```
**Sorting options for `order_by`:** `volume_usd`, `price_usd`, `transactions`, `last_price_change_usd_24h`, `created_at`
**Pagination:** Pages are 1-indexed. Max 100 items per page.
The response wraps pools in a `pools` array with a `page_info` object.
***
## Pattern 4: Find pools for a specific token
```bash theme={null}
curl "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112/pools?order_by=volume_usd&sort=desc&limit=5"
```
This returns all pools containing that token, sorted by volume. The highest-volume pool is typically the best source for price data and OHLCV history.
**Optional:** Add `reorder=true` to make the queried token the primary token in all metrics. Add `address=` to filter to pools paired with a specific second token.
***
## Pattern 5: Get historical price data (OHLCV)
OHLCV data is per pool, not per token. The workflow is:
1. **Find the best pool** -- the highest-volume pool for the token:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/tokens/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2/pools?order_by=volume_usd&sort=desc&limit=1"
```
2. **Get OHLCV data** for that pool:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/{pool_address}/ohlcv?start=2025-06-01&interval=24h&limit=30"
```
**Intervals:** `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h`
**`start` is required** -- ISO 8601 date or UNIX timestamp. Optional `end` parameter (max 1 year from start). Max 366 data points per request.
Response is a JSON array of candlestick objects with `time_open`, `time_close`, `open`, `high`, `low`, `close`, `volume`.
Use `inversed=true` to flip the pair (e.g., get ETH/USDC instead of USDC/ETH).
***
## Pattern 6: Filter pools by criteria
Use the filter endpoint to find pools matching specific conditions:
```bash theme={null}
# High-volume Ethereum pools
curl "https://api.dexpaprika.com/networks/ethereum/pools/filter?volume_24h_min=100000&sort_by=volume_24h&sort_dir=desc"
# New Solana pools with activity (created after a specific date)
curl "https://api.dexpaprika.com/networks/solana/pools/filter?created_after=1709251200&txns_24h_min=50&sort_by=created_at&sort_dir=desc"
```
**Available filter parameters:**
| Parameter | Type | Description |
| ---------------- | ------- | ------------------------------------------------ |
| `volume_24h_min` | number | Minimum 24h volume in USD |
| `volume_24h_max` | number | Maximum 24h volume in USD |
| `txns_24h_min` | integer | Minimum transactions in last 24h |
| `created_after` | integer | UNIX timestamp -- only pools created after this |
| `created_before` | integer | UNIX timestamp -- only pools created before this |
| `sort_by` | string | `volume_24h` (default), `txns_24h`, `created_at` |
| `sort_dir` | string | `asc` or `desc` (default: `desc`) |
| `page` | integer | 1-indexed (default: 1) |
| `limit` | integer | 1–100 (default: 50) |
All filters combine with AND logic. Response uses `results` array (not `pools`) and includes `page_info` with `total_items` and `total_pages`.
The parameters `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, and `liquidity_usd_max` exist in the spec but are not functional yet -- they return empty results.
***
## Pattern 7: Monitor pool transactions
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/transactions?limit=20&page=1"
```
Transactions are returned in reverse chronological order. Each includes:
* `amount_0`, `amount_1` -- token amounts
* `volume_0`, `volume_1` -- volumes
* `price_0_usd`, `price_1_usd` -- USD prices for each token
* `token_0_symbol`, `token_1_symbol` -- token symbols
* `type` -- `swap`, `add`, or `remove`
* `created_at` -- timestamp
**Pagination:** Max 100 pages. For deep history, use `cursor` parameter (a transaction ID) instead of page numbers.
***
## Pattern 8: Discover DEXes on a network
```bash theme={null}
# List all DEXes on a network
curl "https://api.dexpaprika.com/networks/solana/dexes"
# Get pools for a specific DEX
curl "https://api.dexpaprika.com/networks/solana/dexes/raydium/pools?order_by=volume_usd&sort=desc&limit=10"
```
***
## Pattern 9: Stream live prices
For real-time updates, use the streaming API instead of polling REST.
**Single token (GET):**
```bash theme={null}
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
```
**Multiple tokens (POST) -- up to 2,000:**
```bash theme={null}
curl -N -X POST "https://streaming.dexpaprika.com/stream" \
-H "Accept: text/event-stream" \
-H "Content-Type: application/json" \
-d '[
{"chain": "solana", "address": "So11111111111111111111111111111111111111112", "method": "t_p"},
{"chain": "ethereum", "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "method": "t_p"}
]'
```
Each SSE event:
```
data: {"a":"0xc02a...","c":"ethereum","p":"1952.07","t":1769778188,"t_p":1769778187}
event: t_p
```
The `p` field is a string (not a number) -- parse it as a decimal for precision.
***
## Pattern 10: REST + Streaming combined
The most common production pattern:
1. **REST for discovery** -- use search, token details, and pool listing to find what you want to track
2. **Validate** -- confirm the tokens exist and have pricing data via REST
3. **Stream for live updates** -- open an SSE connection for real-time prices
4. **REST for enrichment** -- periodically call REST for OHLCV history, pool details, or transaction data that streaming doesn't cover
***
## Quick reference: which endpoint for what?
| I want to... | Endpoint |
| ----------------------------------------- | -------------------------------------------------------------------------- |
| Get a token's current price | `GET /networks/{network}/tokens/{address}` → `.summary.price_usd` |
| Get multiple token prices at once | `GET /networks/{network}/multi/prices?tokens=a,b,c` |
| Find a token I don't have the address for | `GET /search?query={name_or_symbol}` |
| See top pools by volume | `GET /networks/{network}/pools?order_by=volume_usd&sort=desc` |
| Find pools for a specific token | `GET /networks/{network}/tokens/{address}/pools` |
| Filter pools by volume/txns/age | `GET /networks/{network}/pools/filter?volume_24h_min=X` |
| Get historical candlestick data | `GET /networks/{network}/pools/{pool}/ohlcv?start=X&interval=24h` |
| See recent swaps on a pool | `GET /networks/{network}/pools/{pool}/transactions` |
| List DEXes on a network | `GET /networks/{network}/dexes` |
| Get pools on a specific DEX | `GET /networks/{network}/dexes/{dex}/pools` |
| Stream live prices | `GET https://streaming.dexpaprika.com/stream?method=t_p&chain=X&address=Y` |
| Get API stats | `GET /stats` |
### FAQs
If all requested tokens are unknown or don't have pricing data, you get HTTP 200 with an empty array -- not an error. Verify the token addresses are correct.
The filter endpoint (`/pools/filter`) uses `address` (not `id`), `volume_usd_24h` (not `volume_usd`), and `txns_24h` (not `transactions`). The response uses a `results` array (not `pools`). These are different schemas optimized for different use cases.
Use the highest-volume pool -- it has the most representative pricing. Find it by calling the token pools endpoint sorted by `volume_usd` descending with `limit=1`.
# Core concepts
Source: https://docs.dexpaprika.com/knowledge-base/concepts
Understand the key concepts behind DexPaprika: blockchain networks, DEXes, liquidity pools, tokens, OHLCV data, and how on-chain data flows from blockchains to the API.
## How DexPaprika works
DexPaprika indexes on-chain activity from 33 blockchain networks in near real-time. It watches smart contract events on decentralized exchanges (DEXes), extracts swap transactions, liquidity changes, and price data, and serves it through a REST API and SSE streaming API.
```
Blockchains → Indexer → DexPaprika API → Your app / AI agent
(33 chains) (near real-time) (REST + Streaming)
```
No API key needed. No registration. Just make HTTP requests.
***
## Networks
A **network** (also called a chain or blockchain) is the underlying blockchain where DEXes operate. Each network has its own token addresses and pool addresses.
DexPaprika currently supports 33 networks including Ethereum, Solana, Base, Arbitrum, Polygon, BSC, Optimism, Avalanche, Fantom, Sui, Aptos, TON, Tron, and more.
Every API call that involves a specific token or pool requires a `network` parameter -- the lowercase identifier like `ethereum`, `solana`, `bsc`, `base`.
```bash theme={null}
# List all supported networks
curl "https://api.dexpaprika.com/networks"
```
The response is a JSON array of objects with `id` and `display_name`.
***
## DEXes (Decentralized Exchanges)
A **DEX** is a decentralized exchange protocol -- a set of smart contracts that allows users to swap tokens without an intermediary. Examples: Uniswap, Raydium, PancakeSwap, Curve.
Each DEX operates on one or more networks. For instance, Uniswap V3 runs on Ethereum, Arbitrum, Base, Polygon, and others.
In DexPaprika, DEXes are identified by a `dex_id` string like `uniswap_v3`, `raydium`, `pancakeswap_v3`.
```bash theme={null}
# List DEXes on Ethereum
curl "https://api.dexpaprika.com/networks/ethereum/dexes"
```
***
## Liquidity pools
A **liquidity pool** is a smart contract that holds reserves of two (or more) tokens. Users swap one token for the other, and the pool's reserves shift accordingly -- that's how prices are determined on a DEX.
Each pool has:
* A **pool address** -- the smart contract address on-chain
* A **token pair** -- the two tokens in the pool (e.g., USDC/WETH)
* **Liquidity** -- the total USD value of tokens held in the pool
* **Volume** -- how much has been traded through the pool in a time period
* **Transactions** -- how many swap/add/remove events happened
* **Price** -- the current exchange rate between the two tokens
Pools are the central data object in DexPaprika. Most queries revolve around finding pools, inspecting them, and tracking their activity.
```bash theme={null}
# Get the top pool on Ethereum by volume
curl "https://api.dexpaprika.com/networks/ethereum/pools?limit=1&order_by=volume_usd&sort=desc"
```
***
## Tokens
A **token** is a digital asset on a blockchain, identified by its contract address. The same token concept (like "USDC") can exist on multiple networks with different addresses.
DexPaprika tracks token data by aggregating activity across all pools that contain that token. The token endpoint returns:
* **Price in USD** -- aggregated from pool data
* **Fully diluted valuation (FDV)**
* **Liquidity** -- total across all pools
* **Volume and transactions** -- across multiple time windows (24h, 6h, 1h, 30m, 15m, 5m, 1m)
* **Buy/sell counts and USD values**
* **Price stats** -- 24h high/low and all-time high
```bash theme={null}
# Get SOL token data on Solana
curl "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112"
```
The price is at `response.summary.price_usd`.
***
## OHLCV data
**OHLCV** stands for Open, High, Low, Close, Volume -- the standard candlestick format used in financial charts.
DexPaprika provides OHLCV data per pool (not per token). To get historical price data for a token, first find its highest-volume pool, then request OHLCV data for that pool.
Available intervals: `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h`
Limits: up to 366 data points per request, max 1 year range.
```bash theme={null}
# 30 days of daily candles for the USDC/WETH pool on Uniswap V3
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&interval=24h&limit=30"
```
***
## Transactions
**Transactions** are individual on-chain events on a pool: swaps, liquidity additions, and removals. Each transaction includes token amounts, USD values, prices, and timestamps.
Transactions are returned in reverse chronological order and are available for any pool.
```bash theme={null}
# Recent transactions for a pool
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/transactions?limit=10"
```
***
## Search
The **search** endpoint lets you find tokens, pools, and DEXes by name, symbol, or address across all networks. Use this when you don't know the exact network or address for something.
```bash theme={null}
# Find "Jupiter" across all networks
curl "https://api.dexpaprika.com/search?query=jupiter"
```
The response includes `tokens`, `pools`, and `dexes` arrays with matching results.
***
## Pool filtering
The **pool filter** endpoint lets you search for pools matching specific criteria: volume range, transaction count, and creation date. This is useful for building pool screeners or finding recently created pools with significant activity.
```bash theme={null}
# Ethereum pools with >$100k daily volume, sorted by volume
curl "https://api.dexpaprika.com/networks/ethereum/pools/filter?volume_24h_min=100000&sort_by=volume_24h&sort_dir=desc"
```
***
## Streaming (real-time prices)
The **streaming API** delivers real-time price updates via Server-Sent Events (SSE). Instead of polling the REST API repeatedly, you open one connection and receive price updates as they happen (roughly every second).
Base URL: `https://streaming.dexpaprika.com`
```bash theme={null}
# Stream WETH price on Ethereum
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
```
Each SSE event contains: token address (`a`), chain (`c`), price as a string (`p`), and timestamps (`t`, `t_p`).
***
## Key things to know
* **No authentication** -- the API is public and free
* **Rate limit** -- 10,000 requests per day on the free tier
* **Pagination** -- all paginated endpoints are 1-indexed (`page=1` is the first page; `page=0` is silently treated as page 1)
* **Max page size** -- 100 items per page across all endpoints
* **Addresses are case-sensitive** -- use the exact on-chain format
* **Prices are numbers** in REST responses but **strings** in streaming SSE events (for decimal precision)
* **OHLCV is per pool, not per token** -- find the highest-volume pool first, then request candles
### FAQs
DexPaprika covers on-chain DEX data (pools, swaps, on-chain token prices). CoinPaprika covers centralized exchange data (market cap rankings, exchange listings, global metrics). They're separate APIs from the same company.
Near real-time. The indexer processes new blocks as they arrive, typically within seconds of on-chain confirmation.
No. DexPaprika is read-only. It provides market data but does not execute trades.
# Error handling and troubleshooting
Source: https://docs.dexpaprika.com/knowledge-base/error-handling
Complete guide to DexPaprika API error codes, common issues, and troubleshooting steps for REST API and Streaming API.
## REST API errors
All REST API errors return a JSON object with a `message` field (and sometimes an `error` field). Here's every status code you can encounter:
### 200 -- Success
Normal response. Parse the JSON body.
One important edge case: **batch pricing** (`GET /networks/{network}/multi/prices`) returns HTTP 200 with an empty array `[]` when none of the requested tokens have pricing data. This is not an error -- it means the tokens were processed but none had prices.
***
### 400 -- Bad Request
The request was malformed or contained invalid parameters.
```json theme={null}
{"message": "invalid query param"}
```
**Common causes:**
* Invalid `order_by` or `sort_by` value (e.g., using `liquidity` when only `volume_usd`, `price_usd`, `transactions`, `last_price_change_usd_24h`, `created_at` are valid)
* Invalid `interval` value for OHLCV (must be one of: `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h`)
* Batch pricing with more than 10 tokens
* Batch pricing with zero tokens (empty `tokens` parameter)
* Invalid UNIX timestamp format in filter parameters
* Missing required parameters (e.g., `start` for OHLCV)
**What to do:** Check the parameter values against the [API reference](/api-reference/introduction) or [common patterns](/knowledge-base/common-patterns).
***
### 404 -- Not Found
The requested resource doesn't exist.
```json theme={null}
{"message": "not found"}
```
**Common causes:**
* Invalid network ID (e.g., `eth` instead of `ethereum`, `sol` instead of `solana`)
* Token address doesn't exist on that network
* Pool address doesn't exist on that network
* Typo in the URL path
**What to do:**
1. Verify the network ID by checking `GET /networks`
2. Use `GET /search?query={name}` to find the correct network and address
3. Check that the address format matches the chain (e.g., `0x...` for EVM chains, base58 for Solana)
***
### 410 -- Gone
The endpoint has been permanently removed.
```json theme={null}
{"error": "Endpoint Removed", "message": "This endpoint has been permanently removed. Please refer to our API documentation for alternatives."}
```
**Currently applies to:**
* `GET /pools` -- the global pools endpoint was deprecated in v1.3.0. Use `GET /networks/{network}/pools` instead.
***
### 429 -- Too Many Requests
Rate limit exceeded.
**Free tier limit:** 10,000 requests per day.
**What to do:**
* Cache responses for data that doesn't change every second (network lists, DEX lists)
* Use batch pricing instead of individual token requests
* Use the streaming API for real-time prices instead of polling
* Consider the [Pro API](/api-pro/introduction) for unlimited requests
***
### 500 -- Internal Server Error
Something went wrong on our side.
**What to do:** Retry with exponential backoff (wait 1s, then 2s, then 4s, etc.). If the error persists, check our [Discord](https://discord.gg/DhJge5TUGM) for status updates or contact support.
***
## Streaming API errors
The streaming API at `https://streaming.dexpaprika.com` can fail in two ways: HTTP errors before the stream starts, or SSE error events during an active stream.
### HTTP errors (before stream starts)
| Status | Meaning |
| ------ | ----------------------------------------------------------------------------------- |
| 200 | Connected successfully, streaming |
| 400 | Bad parameters, unsupported chain, token not found, or one invalid asset in a batch |
| 429 | Global stream limit exceeded (10,000 concurrent streams per server) |
**The 400 behavior is strict:** In a POST request with multiple tokens, if even one token is invalid, the entire request fails. Validate all tokens via the REST API before streaming them.
### SSE errors (during active stream)
If something goes wrong during an active stream, the error arrives as an SSE event:
```
event: error
data: {"message": "..."}
```
**What to do:** Close the connection and reconnect with exponential backoff.
***
## Pagination gotchas
All paginated endpoints in DexPaprika are **1-indexed**:
* `page=1` returns the first page
* `page=0` is silently treated as `page=1` (not an error, but may cause confusion)
Maximum page size is 100 items (via `limit` parameter). Transaction pagination is limited to 100 pages -- for deeper history, use cursor-based pagination with the `cursor` parameter.
***
## Common mistakes and fixes
**Symptom:** `GET /networks/{network}/pools?limit=1` returns `{"pools": [], "page_info": {...}}`
**Cause:** Some combinations of very small limits can return empty results due to internal filtering.
**Fix:** Use `limit=10` or higher. The minimum practical limit is 2–3.
**Symptom:** `GET /search?query=USDC` returns empty arrays.
**Cause:** Search is best-effort and may not match very common/generic terms well. It searches across tokens, pools, and DEXes.
**Fix:** Try more specific queries (e.g., the token address), or use the token endpoint directly if you know the network and address.
**Symptom:** OHLCV request returns `[]`.
**Cause:** The `start` date might be before the pool existed, or the pool may have very low activity in the requested period.
**Fix:** Check the pool's `created_at` field to ensure your date range is valid. Try a broader interval (e.g., `24h` instead of `1h`).
**Symptom:** Code that works with `/pools` breaks when switched to `/pools/filter`.
**Cause:** Different response schemas. Filter uses `address` (not `id`), `volume_usd_24h` (not `volume_usd`), `txns_24h` (not `transactions`), and wraps results in `results` (not `pools`).
**Fix:** Handle each endpoint's response format separately. See [common patterns](/knowledge-base/common-patterns#pattern-6-filter-pools-by-criteria) for the exact filter response structure.
**Symptom:** Streaming connection returns 400 instantly.
**Cause:** One or more assets in the request are invalid (wrong chain ID, non-existent token address).
**Fix:** Validate every token via the REST API before adding it to a streaming request. In a POST batch, all assets must be valid -- one bad asset cancels the entire stream.
### FAQs
The API does not currently return standard rate limit headers (X-RateLimit-\*). Monitor your daily usage on your side.
The daily limit resets on a rolling 24-hour window. After hitting the limit, wait and retry.
No. The 10,000 request/day limit applies across all endpoints combined.
# Rate limits and best practices
Source: https://docs.dexpaprika.com/knowledge-base/rate-limits
DexPaprika API rate limits, pagination rules, caching strategies, and performance optimization tips for building efficient applications.
## Rate limits
| Tier | Limit | Notes |
| ------------ | ----------------------- | -------------------------------------------- |
| **Free API** | 10,000 requests per day | No API key needed |
| **Pro API** | Unlimited | Requires API key and enterprise subscription |
The daily limit resets on a rolling 24-hour window. There is no per-second or per-minute throttle -- only the daily cap. When you exceed the limit, requests return HTTP 429.
Need unlimited access? The [Pro API](/api-pro/introduction) removes all rate limits. Contact [support@coinpaprika.com](mailto:support@coinpaprika.com).
***
## Pagination rules
All paginated endpoints follow the same rules:
| Rule | Value |
| -------------------------- | ---------------------------------------------- |
| **First page** | `page=1` (1-indexed) |
| **Page 0 behavior** | Silently treated as page 1 |
| **Max items per page** | 100 (via `limit` parameter) |
| **Default items per page** | Varies by endpoint (typically 10 or 50) |
| **Transaction pages** | Max 100 pages; use `cursor` for deeper history |
***
## Reduce API calls
### Use batch pricing
Instead of making one request per token:
```
GET /networks/ethereum/tokens/0xc02a.../ → 1 request
GET /networks/ethereum/tokens/0xa0b8.../ → 1 request
GET /networks/ethereum/tokens/0x6b17.../ → 1 request
= 3 requests
```
Use batch pricing for up to 10 tokens at once:
```
GET /networks/ethereum/multi/prices?tokens=0xc02a...,0xa0b8...,0x6b17...
= 1 request
```
That's a 3x reduction -- or up to 10x when you need prices for 10 tokens.
### Use streaming for real-time data
If you need live prices, don't poll the REST API in a loop. Open one streaming connection instead:
```bash theme={null}
# Polling (bad): 60 requests/minute for 1 token
while true; do curl ...; sleep 1; done
# Streaming (good): 1 connection, unlimited updates
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02a..."
```
Streaming supports up to 2,000 tokens on a single connection.
### Cache static data
Some data changes rarely and can be cached:
| Data | Cache for |
| ----------------------------------------- | ---------------------------------------- |
| Network list (`/networks`) | 24 hours |
| DEX list (`/networks/{n}/dexes`) | 1 hour |
| Token metadata (name, symbol, decimals) | 24 hours |
| Pool token pair info | 24 hours |
| OHLCV historical data (completed candles) | Forever (completed candles don't change) |
Data that changes frequently and should be fetched fresh:
* Token prices
* Pool volumes and transaction counts
* Recent transactions
* Current OHLCV candle (incomplete)
### Request only what you need
* Use `limit` to control page size -- don't fetch 100 items if you need 5
* Use `order_by` and `sort` to get the most relevant results first
* Use the filter endpoint for targeted queries instead of fetching all pools and filtering client-side
***
## Handle errors gracefully
### Implement exponential backoff
When requests fail, don't retry immediately in a tight loop:
```python theme={null}
import time
import requests
def fetch_with_backoff(url, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url)
if response.status_code == 200:
return response.json()
if response.status_code == 429:
wait = 2 ** attempt # 1s, 2s, 4s
time.sleep(wait)
continue
if response.status_code >= 500:
wait = 2 ** attempt
time.sleep(wait)
continue
# 400, 404, 410 -- don't retry, fix the request
response.raise_for_status()
raise Exception("Max retries exceeded")
```
### Don't retry client errors
* **400** -- fix the request parameters
* **404** -- verify the network ID and addresses
* **410** -- use the replacement endpoint
Only retry on **429** (rate limit) and **500** (server error).
***
## Streaming best practices
### Validate before streaming
The streaming API rejects the entire request if any asset is invalid. Always verify tokens exist via REST first:
```python theme={null}
# Validate each token before streaming
for token in tokens:
resp = requests.get(f"https://api.dexpaprika.com/networks/{token['chain']}/tokens/{token['address']}")
if resp.status_code != 200:
tokens.remove(token) # Remove invalid tokens
```
### Use batched POST for multiple tokens
Instead of opening multiple GET connections:
```
# Bad: 5 connections for 5 tokens
GET /stream?method=t_p&chain=ethereum&address=0xaaa...
GET /stream?method=t_p&chain=ethereum&address=0xbbb...
GET /stream?method=t_p&chain=ethereum&address=0xccc...
```
Use one POST connection:
```bash theme={null}
# Good: 1 connection for up to 2,000 tokens
POST /stream
[
{"chain": "ethereum", "address": "0xaaa...", "method": "t_p"},
{"chain": "ethereum", "address": "0xbbb...", "method": "t_p"},
{"chain": "ethereum", "address": "0xccc...", "method": "t_p"}
]
```
### Reconnect with backoff
Streaming connections can drop (network issues, server restarts). Always implement auto-reconnection:
```python theme={null}
import time
def stream_with_reconnect(url, payload, max_backoff=60):
backoff = 1
while True:
try:
resp = requests.post(url, json=payload, stream=True,
headers={"Accept": "text/event-stream"})
if resp.status_code != 200:
raise Exception(f"HTTP {resp.status_code}")
backoff = 1 # Reset on successful connection
for line in resp.iter_lines():
if line and line.startswith(b'data:'):
process_event(line)
except Exception as e:
print(f"Disconnected: {e}. Reconnecting in {backoff}s...")
time.sleep(backoff)
backoff = min(backoff * 2, max_backoff)
```
### Parse prices as decimals
The streaming `p` field is a string, not a number. Use decimal parsing to avoid floating-point precision issues:
```python theme={null}
from decimal import Decimal
price = Decimal(data['p']) # Not float(data['p'])
```
***
## Production checklist
* [ ] Cache network and DEX lists
* [ ] Use batch pricing where possible
* [ ] Use streaming instead of polling for live prices
* [ ] Implement exponential backoff for retries
* [ ] Handle all HTTP status codes (200, 400, 404, 410, 429, 500)
* [ ] Parse streaming prices as decimals, not floats
* [ ] Validate tokens before adding to streaming connections
* [ ] Monitor daily request count against the 10,000 limit
* [ ] Consider Pro API if approaching limits
### FAQs
No. Only a daily cap of 10,000 requests. You can burst as fast as you want within that daily budget.
Opening a streaming connection counts as a request. The individual SSE events within the stream do not count.
The free tier is fixed at 10,000/day. For higher limits, use the Pro API.
# Skill
Source: https://docs.dexpaprika.com/skill
Query on-chain DEX data and stream real-time crypto prices using DexPaprika -- token prices, liquidity pools, OHLCV history, swap transactions, advanced pool filtering, and live price streaming via SSE across 33+ blockchains. Use this skill whenever the user wants to fetch crypto token prices, look up pool or DEX data, get historical candlestick data, find new pools, filter pools by volume/transactions/age, stream live prices, build real-time dashboards, or build anything that needs on-chain DEX data. Also use when the user mentions DexPaprika, dexpaprika, streaming crypto prices, or SSE price feeds. REST docs: https://docs.dexpaprika.com -- Streaming docs: https://docs.dexpaprika.com/streaming/introduction
# DexPaprika API
Free API for on-chain DEX data and real-time price streaming. 33+ blockchains, 25M+ tokens, 27M+ pools. No API key, no authentication.
| Service | Base URL | Purpose |
| ------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| REST API | `https://api.dexpaprika.com` | Token data, pools, OHLCV, transactions, search |
| Streaming API | `https://streaming.dexpaprika.com` | Real-time price updates via SSE (\~1s intervals). [Full docs](https://docs.dexpaprika.com/streaming/introduction) |
| CLI | `curl -sSL .../install.sh \| sh` | Terminal tool wrapping the full API. Install: `curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh \| sh` |
All examples use curl, but any HTTP client works. The CLI (`dexpaprika-cli`) wraps every endpoint into simple commands with `--output json --raw` for scripting. REST responses are JSON. Streaming responses are Server-Sent Events.
***
## Core concepts
**Network IDs** are lowercase chain identifiers: `ethereum`, `solana`, `bsc`, `arbitrum`, `base`, `polygon`, `optimism`, `avalanche`, etc. Get the full list from `GET /networks`.
**Token addresses** are the on-chain contract addresses (e.g., `0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` for WETH on Ethereum, `So11111111111111111111111111111111111111112` for SOL on Solana).
**Pool addresses** are the on-chain liquidity pool contract addresses. Find them via token pools or network pools endpoints.
If you don't know the network or address for a token, use search first.
***
## Endpoints
### Search (start here when you don't have addresses)
```
GET /search?query={query}
```
Search tokens, pools, and DEXes by name, symbol, or address. Case-insensitive. Use this to resolve "what's the ETH price" into the actual network + address you need.
**Example:** Find Jupiter token
```bash theme={null}
curl "https://api.dexpaprika.com/search?query=jupiter"
```
***
### Token price and details
```
GET /networks/{network}/tokens/{token_address}
```
Returns name, symbol, chain, decimals, USD price, fully diluted valuation, liquidity, and volume/transaction stats at multiple time windows (24h, 6h, 1h, 30m, 15m, 5m).
**The price is at** `response.summary.price_usd`
**Example:** Get SOL price
```bash theme={null}
curl "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112"
```
Extract just the price:
```bash theme={null}
curl -s "https://api.dexpaprika.com/networks/solana/tokens/So11111111111111111111111111111111111111112" | jq '.summary.price_usd'
```
***
### Batch token prices
```
GET /networks/{network}/multi/prices?tokens={addr1},{addr2},{addr3}
```
Fetch USD prices for multiple tokens in one request. Comma-separated addresses, max 10 per request. Unknown or unpriced tokens are silently omitted from the response.
**Example:** WETH + USDC on Ethereum
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
```
Response is an array of `{id, chain, price_usd}` objects. Order is not guaranteed.
***
### Top pools on a network
```
GET /networks/{network}/pools?page={1}&limit={10}&order_by={volume_usd}&sort={desc}
```
List top liquidity pools. Pages are 1-indexed, max 100 per page. Order by: `volume_usd`, `price_usd`, `transactions`, `last_price_change_usd_24h`, `created_at`.
**Example:** Top 5 Ethereum pools by volume
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?limit=5&order_by=volume_usd&sort=desc"
```
***
### Advanced pool filtering (new)
```
GET /networks/{network}/pools/filter
```
Filter pools with range queries on volume, transactions, and creation date. This is the endpoint to use for building pool screeners, finding high-volume pools, or discovering recently created pools that meet specific criteria.
**Parameters:**
| Parameter | Type | Description |
| ---------------- | ------- | ------------------------------------------------ |
| `page` | integer | Page number, **1-indexed** (default: 1) |
| `limit` | integer | Items per page, 1-100 (default: 50) |
| `volume_24h_min` | number | Min 24h volume in USD |
| `volume_24h_max` | number | Max 24h volume in USD |
| `txns_24h_min` | integer | Min transactions in last 24h |
| `created_after` | integer | UNIX timestamp -- only pools created after this |
| `created_before` | integer | UNIX timestamp -- only pools created before this |
| `sort_by` | string | `volume_24h` (default), `txns_24h`, `created_at` |
| `sort_dir` | string | `asc` or `desc` (default: `desc`) |
Note: `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, `liquidity_usd_max` exist in the spec but are not functional yet -- they return empty results.
All filters combine with AND logic. The response includes `page_info` with `total_items` and `total_pages`.
**Example:** High-volume Ethereum pools (>\$100k daily volume)
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/filter?volume_24h_min=100000&sort_by=volume_24h&sort_dir=desc"
```
**Example:** Recently created Solana pools with activity
```bash theme={null}
curl "https://api.dexpaprika.com/networks/solana/pools/filter?created_after=1709251200&txns_24h_min=50&sort_by=created_at&sort_dir=desc"
```
***
### Pool details
```
GET /networks/{network}/pools/{pool_address}?inversed={false}
```
Returns liquidity, reserves, pricing, token pair info, and DEX metadata for a specific pool. Set `inversed=true` to flip the price ratio (token1/token0 instead of token0/token1).
***
### Pool OHLCV (historical candlesticks)
```
GET /networks/{network}/pools/{pool_address}/ohlcv?start={timestamp}&interval={24h}&limit={30}
```
Historical price candlestick data. `start` is required (ISO 8601 or UNIX timestamp). Optional `end` (max 1 year from start).
**Intervals:** `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `6h`, `12h`, `24h`
**Max data points:** 366 per request
**Example:** Last 30 days of daily candles for a pool
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&interval=24h&limit=30"
```
***
### Pool transactions
```
GET /networks/{network}/pools/{pool_address}/transactions?page={1}&limit={20}
```
Recent swaps, liquidity adds, and removes. Reverse chronological order. Pages 1-indexed, max 100 pages. For deep pagination, use `cursor` parameter (transaction ID) instead of page numbers.
Each transaction includes: token amounts (`amount_0`, `amount_1`), volumes (`volume_0`, `volume_1`), USD prices (`price_0_usd`, `price_1_usd`), token symbols, sender/recipient, and timestamps.
***
### Pools for a token
```
GET /networks/{network}/tokens/{token_address}/pools?order_by={volume_usd}&sort={desc}&limit={10}
```
Find all pools containing a specific token. Optional: add `address` parameter to filter to pools paired with a second specific token. Add `reorder=true` to make the queried token the primary token in all metrics.
***
### DEXes on a network
```
GET /networks/{network}/dexes
```
List all DEXes on a network with their identifiers. Use the `dex` id to filter pools:
```
GET /networks/{network}/dexes/{dex}/pools
```
***
### Networks
```
GET /networks
```
Returns all supported blockchain networks with their IDs. Use these IDs in all other endpoints.
***
### Platform stats
```
GET /stats
```
High-level counts: total networks, DEXes, pools, and tokens. Useful for health checks.
***
## Streaming API -- Real-time prices via SSE
Stream live token prices with \~1 second update intervals. Uses Server-Sent Events (SSE) -- works with any HTTP client that supports streaming. For full streaming docs, guides, and code examples see: [https://docs.dexpaprika.com/streaming/introduction](https://docs.dexpaprika.com/streaming/introduction)
**Base URL:** `https://streaming.dexpaprika.com` (no landing page -- only the `/stream` paths below work)
### Stream a single token (GET)
```bash theme={null}
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
```
### Stream multiple tokens (POST) -- recommended for 2+ tokens
Send a JSON array of assets. Single connection, up to 2,000 tokens.
```bash theme={null}
curl -N -X POST "https://streaming.dexpaprika.com/stream" \
-H "Accept: text/event-stream" \
-H "Content-Type: application/json" \
-d '[
{"chain": "solana", "address": "So11111111111111111111111111111111111111112", "method": "t_p"},
{"chain": "ethereum", "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "method": "t_p"}
]'
```
Each asset object requires `chain` (network ID), `address` (token contract), and `method` (always `t_p` for token price).
### SSE event format
```
data: {"a":"0xc02a...","c":"ethereum","p":"2739.79","t":1769778188,"t_p":1769778187}
event: t_p
```
| Field | Meaning |
| ----- | ------------------------------------------------------- |
| `a` | Token address |
| `c` | Chain ID |
| `p` | Price in USD (string for precision -- parse as decimal) |
| `t` | Server send timestamp (UNIX seconds) |
| `t_p` | Price event timestamp (UNIX seconds) |
Use `now() - t` for network latency, `now() - t_p` for total price data latency.
### Python streaming example
```python theme={null}
import requests, json
assets = [
{"chain": "ethereum", "address": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "method": "t_p"},
{"chain": "solana", "address": "So11111111111111111111111111111111111111112", "method": "t_p"}
]
r = requests.post("https://streaming.dexpaprika.com/stream",
headers={"Accept": "text/event-stream", "Content-Type": "application/json"},
json=assets, stream=True)
for line in r.iter_lines():
if line and line.startswith(b'data:'):
data = json.loads(line[5:])
print(f"{data['c']} {data['a']}: ${data['p']}")
```
### Streaming constraints
* **Max 2,000 assets** per POST request
* **All assets must be valid** -- one invalid asset cancels the entire stream with HTTP 400
* **Global stream limit:** 10,000 concurrent streams per server
* Validate assets via REST `/search` before streaming
* Use multiple smaller requests (100-500 each) rather than one massive request for better load distribution
* Reconnect with exponential backoff on disconnect
### Streaming errors
| Status | Meaning |
| ------ | ----------------------------------------------------------------------------- |
| 200 | Connected, streaming |
| 400 | Bad params, unsupported chain, asset not found, or one invalid asset in batch |
| 429 | Global stream limit exceeded -- retry with backoff |
Errors during an active stream arrive as SSE events: `event: error` + `data: {"message": "..."}`. Handle both HTTP errors (before stream starts) and SSE errors (during streaming).
***
## Constraints and limits
### REST API
* **Rate limit:** 10,000 requests per day
* **Batch prices:** max 10 tokens per request
* **Pagination:** max 100 items per page
* **OHLCV:** max 366 data points per request, max 1 year range
* **Transactions:** max 100 pages of pagination
* **Pagination:** all endpoints are 1-indexed (page=0 is silently treated as page=1)
### Streaming API
* **Max assets per request:** 2,000
* **Global concurrent streams:** 10,000 per server
* **All assets must be valid** or entire stream is cancelled
***
## Error handling
| Status | Meaning | What to do |
| ------ | ------------------------------------------------------------- | --------------------------------------------------------------------- |
| 200 | Success | Parse JSON response |
| 400 | Bad request (invalid params, too many tokens, bad sort field) | Check parameter values and constraints above |
| 404 | Network, token, or pool not found | Verify the network ID and address; use /search to find correct values |
| 410 | Endpoint deprecated (old /pools) | Use `/networks/{network}/pools` instead |
| 429 | Rate limit exceeded | Back off and retry; consider caching responses |
| 500 | Server error | Retry with backoff |
When a batch price request contains only invalid tokens, you get HTTP 200 with an empty array -- not an error.
***
## Common workflows
### "What's the price of X?"
1. `GET /search?query=X` to find the network and token address
2. `GET /networks/{network}/tokens/{address}` to get price at `.summary.price_usd`
### "Show me the top pools on Ethereum"
1. `GET /networks/ethereum/pools?limit=10&order_by=volume_usd&sort=desc`
### "Find new pools with high volume"
1. `GET /networks/{network}/pools/filter?created_after={unix_timestamp}&volume_24h_min=50000&sort_by=created_at&sort_dir=desc`
### "Get historical price data for a token"
1. Find the token's pools via `GET /networks/{network}/tokens/{address}/pools?order_by=volume_usd&sort=desc&limit=1` (the highest-volume pool is the best source)
2. `GET /networks/{network}/pools/{pool_address}/ohlcv?start={date}&interval=24h&limit=30`
### "Compare prices of multiple tokens"
1. `GET /networks/{network}/multi/prices?tokens={addr1},{addr2},{addr3}`
### "Stream live price updates for a token"
1. `GET https://streaming.dexpaprika.com/stream?method=t_p&chain={network}&address={token_address}`
### "Build a real-time dashboard tracking multiple tokens"
1. Validate tokens exist via REST: `GET /search?query={name}` or `GET /networks/{network}/tokens/{address}`
2. `POST https://streaming.dexpaprika.com/stream` with JSON array of `{chain, address, method: "t_p"}` objects
3. Parse SSE events, read price from `p` field (string -- parse as decimal for precision)
### "Monitor a token's price with alerts"
1. Stream the token via GET or POST to `streaming.dexpaprika.com`
2. Compare each incoming `p` value against your threshold
3. Reconnect with exponential backoff on disconnect
***
## What this skill does NOT cover
* **CoinPaprika centralized exchange data** -- that's a different API (`api.coinpaprika.com`)
* **Trading or swapping** -- DexPaprika is read-only; it does not execute trades
***
## Full documentation
* [REST API reference](https://docs.dexpaprika.com/api-reference/introduction)
* [Streaming API docs](https://docs.dexpaprika.com/streaming/introduction)
* [Tutorials](https://docs.dexpaprika.com/tutorials/tutorial_intro)
# React & Next.js Integration
Source: https://docs.dexpaprika.com/streaming/guides/react-integration
Build real-time price components for React and Next.js applications with TypeScript support
**See React integration in production!** Our live dashboard is built with React, TypeScript, and uses the patterns described in this guide. Streams 6 cryptocurrencies using POST /stream with custom hooks, real-time UI updates, and proper error handling. Open the dashboard and inspect the Network tab to see SSE in action! [View Source →](https://crypto-streaming-dashboard-v3.vercel.app/)
## Integration overview
Learn how to integrate DexPaprika's streaming API into React and Next.js applications with:
* Custom React hooks for streaming
* TypeScript support
* Server-side rendering considerations
* Production-ready error handling
***
## Finding Token Addresses
Before streaming, you need token addresses. Use the REST API:
Use the [Search API](/api-reference/search/search-for-tokens-pools-and-dexes) to find tokens by name or symbol
Use the [Networks API](/api-reference/networks/get-a-list-of-available-blockchain-networks) to get supported chains
```bash theme={null}
# Search for USDC tokens
curl "https://api.dexpaprika.com/search?query=USDC"
# Get all supported networks
curl "https://api.dexpaprika.com/networks"
```
***
## Quick Example
```tsx React Hook theme={null}
import { useEffect, useState } from 'react';
function useCryptoPrice(chain: string, address: string) {
const [price, setPrice] = useState(null);
const [status, setStatus] = useState<'connecting' | 'connected' | 'error'>('connecting');
useEffect(() => {
const url = new URL('https://streaming.dexpaprika.com/stream');
url.searchParams.set('method', 't_p');
url.searchParams.set('chain', chain);
url.searchParams.set('address', address);
const eventSource = new EventSource(url.toString());
eventSource.onopen = () => setStatus('connected');
eventSource.addEventListener('t_p', (event) => {
const data = JSON.parse(event.data);
setPrice(parseFloat(data.p));
});
eventSource.onerror = () => setStatus('error');
return () => eventSource.close();
}, [chain, address]);
return { price, status };
}
// Usage
function PriceDisplay() {
const { price, status } = useCryptoPrice('ethereum', '0xc02aa...');
return (
);
}, (prevProps, nextProps) => {
// Only re-render if price changes by more than 0.01%
return Math.abs(prevProps.price - nextProps.price) / prevProps.price < 0.0001;
});
```
***
## Testing
### Unit Testing with Jest
```typescript theme={null}
// __tests__/useCryptoStream.test.ts
import { renderHook, act } from '@testing-library/react-hooks';
import { useCryptoStream } from '../hooks/useCryptoStream';
// Mock EventSource
global.EventSource = jest.fn(() => ({
addEventListener: jest.fn(),
close: jest.fn(),
onopen: jest.fn(),
onerror: jest.fn(),
})) as any;
describe('useCryptoStream', () => {
it('should connect on mount', () => {
const { result } = renderHook(() =>
useCryptoStream({
chain: 'ethereum',
address: '0xtest',
})
);
expect(result.current.status).toBe('connecting');
});
it('should update price on event', () => {
const { result } = renderHook(() =>
useCryptoStream({
chain: 'ethereum',
address: '0xtest',
})
);
act(() => {
// Simulate price update
const event = new MessageEvent('t_p', {
data: JSON.stringify({
a: '0xtest',
c: 'ethereum',
p: '1234.56',
t: Date.now() / 1000,
}),
});
// Trigger event handler
const eventSource = (global.EventSource as jest.Mock).mock.results[0].value;
eventSource.addEventListener.mock.calls[0][1](event);
});
expect(result.current.price).toBe(1234.56);
});
});
```
***
## Production Checklist
Wrap streaming components in error boundaries to handle failures gracefully:
```tsx theme={null}
import { ErrorBoundary } from 'react-error-boundary';
Price unavailable}>
```
Always clean up EventSource connections and timeouts:
```tsx theme={null}
useEffect(() => {
const eventSource = new EventSource(url);
// Cleanup function
return () => {
eventSource.close();
clearTimeout(reconnectTimeout);
};
}, []);
```
Monitor connection status and alert on failures:
```tsx theme={null}
useEffect(() => {
if (status === 'error') {
// Send to error tracking service
Sentry.captureException(new Error('Stream connection failed'));
}
}, [status]);
```
Consider lazy loading streaming components:
```tsx theme={null}
const LivePrices = lazy(() => import('./LivePrices'));
```
***
## Get Support
Get help from other React developers.
Report bugs or request features.
# Real-Time Streaming API
Source: https://docs.dexpaprika.com/streaming/introduction
Stream live cryptocurrency price updates using Server-Sent Events (SSE) for real-time applications
**Live Demo:** Watch our interactive dashboard stream real-time prices for 6 cryptocurrencies across Ethereum, Solana, and BSC. See connection status, latency metrics, and live updates in action. [Open Live Dashboard →](https://crypto-streaming-dashboard-v3.vercel.app/)
## Overview
DexPaprika's Streaming API delivers real-time cryptocurrency price updates via Server-Sent Events (SSE). Build responsive applications with live data feeds. Get price updates every second without polling - no API key required.
Public endpoints with no API keys needed. Start streaming immediately.
Receive price updates approximately every 1 second per asset.
Standard Server-Sent Events for easy integration with any modern platform.
Stream tokens from Ethereum, Solana, BSC, Arbitrum, and more networks.
***
## Why Use Streaming?
### Streaming vs Traditional Polling
```javascript theme={null}
// Efficient: Server pushes updates only when prices change
const url = 'https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
const eventSource = new EventSource(url);
eventSource.addEventListener('t_p', (event) => {
const data = JSON.parse(event.data);
updatePrice(data.p);
});
```
**Benefits:**
* Single persistent connection
* Updates pushed immediately when available
* Minimal bandwidth usage
* No rate limiting concerns
```javascript theme={null}
// Inefficient: Constant requests even when prices don't change
setInterval(async () => {
const response = await fetch('https://api.dexpaprika.com/networks/ethereum/tokens/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2');
const data = await response.json();
updatePrice(data.summary.price_usd);
}, 1000); // 86,400 requests per day per asset!
```
**Drawbacks:**
* High server load from repeated requests
* Wasted bandwidth when prices don't change
* Potential rate limiting issues
* Higher latency for updates
***
## Use Cases
### What You Can Build
Display live prices, volume, and market metrics with sub-second latency. **[See live example →](https://crypto-streaming-dashboard-v3.vercel.app/)**
Show real-time portfolio values and P\&L as prices fluctuate.
Trigger instant notifications when prices hit target levels.
Compare prices across chains for arbitrage opportunities.
Create live price tickers and widgets for websites.
Stream data into time-series databases for real-time analytics.
***
## Available Endpoints
We offer two streaming methods optimized for different use cases:
Stream one token per connection. Simple and straightforward for individual assets.
Stream up to 2,000 tokens in one connection. Optimal for portfolios and dashboards.
### Quick Comparison
| Feature | GET (Single) | POST (Multiple) |
| ---------------------- | ------------------------- | ---------------------- |
| **Assets per request** | 1 | Up to 2,000 |
| **Best for** | Individual price tracking | Portfolios, dashboards |
| **Setup complexity** | Minimal | Moderate |
| **Performance** | Good for 1-10 assets | Optimal for 10+ assets |
| **Load distribution** | Per connection | Automatic balancing |
***
## Quick Start
### 1. Choose Your Method
Stream Ethereum WETH price:
```bash theme={null}
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
```
Stream SOL and USDC prices:
```bash theme={null}
curl -X POST "https://streaming.dexpaprika.com/stream" \
-H "Accept: text/event-stream" \
-H "Content-Type: application/json" \
-d '[
{"chain": "solana", "address": "So11111111111111111111111111111111111111112", "method": "t_p"},
{"chain": "ethereum", "address": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", "method": "t_p"}
]'
```
### 2. Parse the Response
Each price update arrives as a JSON event:
```json theme={null}
{
"a": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // Token address
"c": "ethereum", // Chain
"p": "2739.792547827768", // Price in USD
"t": 1769778188, // Server send timestamp
"t_p": 1769778187 // Price event timestamp
}
```
### 3. Handle in Your Application
```javascript Browser theme={null}
const eventSource = new EventSource(url);
eventSource.addEventListener('t_p', (event) => {
const price = JSON.parse(event.data);
console.log(`${price.c} ${price.a}: $${price.p}`);
});
eventSource.onerror = () => {
// Reconnect logic
eventSource.close();
setTimeout(connectStream, 1000);
};
```
```python Python theme={null}
import requests
import json
response = requests.get(url, stream=True)
for line in response.iter_lines():
if line and line.startswith(b'data:'):
data = json.loads(line[5:])
print(f"{data['c']} {data['a']}: ${data['p']}")
```
```typescript TypeScript theme={null}
interface PriceEvent {
a: string; // address
c: string; // chain
p: string; // price
t: number; // timestamp
}
const stream = new EventSource(url);
stream.addEventListener('t_p', (event: MessageEvent) => {
const price: PriceEvent = JSON.parse(event.data);
updatePrice(price);
});
```
***
## Architecture Overview
```mermaid theme={null}
graph LR
A[Your App] -->|SSE Connection| B[Streaming API]
B --> C[Load Balancer]
C --> D1[Server 1]
C --> D2[Server 2]
C --> D3[Server N]
D1 --> E[Price Feeds]
D2 --> E
D3 --> E
E --> F[Blockchain RPCs]
```
### Key Features
* **Automatic Load Balancing**: Requests distributed across multiple servers
* **Persistent Connections**: Single connection maintained for entire session
* **Efficient Updates**: Only sends data when prices actually change
* **Global Infrastructure**: Low-latency servers in multiple regions
***
## Best Practices
* Implement automatic reconnection with exponential backoff
* Handle both network errors and SSE error events
* Monitor connection health with heartbeat timeouts
* Validate all assets before streaming (invalid assets cancel entire stream)
* Parse both HTTP errors and SSE error events
* Log errors for debugging but don't expose sensitive data
* Use POST method for multiple assets (better than multiple GETs)
* Split large requests across multiple smaller streams
* Parse price strings carefully to maintain precision
* Implement proper logging and monitoring
* Set up alerts for connection drops
* Use connection pooling for multiple streams
* Consider WebSocket bridges for incompatible clients
***
## Supported Networks
Stream tokens from multiple blockchain networks. Use the [Networks API](/api-reference/networks/get-a-list-of-available-blockchain-networks) to get the full list of supported networks:
```bash theme={null}
curl https://api.dexpaprika.com/networks
```
Popular networks include:
* Ethereum (`ethereum`)
* Solana (`solana`)
* Binance Smart Chain (`bsc`)
* Arbitrum (`arbitrum`)
* Polygon (`polygon`)
* Base (`base`)
* Avalanche (`avalanche`)
The `chain` parameter in streaming requests must use the exact `id` value from the [Networks endpoint](/api-reference/networks/get-a-list-of-available-blockchain-networks).
***
## Finding Token Addresses
Before streaming prices, you need the correct token address for your chosen network. Use these REST API endpoints:
### Search for Tokens
Use the [Search API](/api-reference/search/search-for-tokens-pools-and-dexes) to find tokens by name or symbol:
```bash theme={null}
curl "https://api.dexpaprika.com/search?query=USDC"
```
### Get Token Details
Find all pools for a specific token using the [Token Pools API](/api-reference/tokens/get-top-x-pools-for-a-token):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/tokens/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48/pools"
```
### Validate Before Streaming
Use the [Token Prices API](/api-reference/tokens/get-batched-token-prices-on-a-network) to verify your token exists before streaming:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
```
Always verify the token address matches the network you're streaming from. The same token may have different addresses on different chains.
The streaming API will return a `400 Asset not found` error if the token doesn't exist on the specified network. Validate tokens using the REST API first to avoid stream failures.
***
## Next Steps
See the Streaming API in action with our interactive demo. Watch real-time updates across multiple chains.
Build your first streaming application in 5 minutes.
Detailed endpoint documentation and parameters.
Create live price components for React applications.
***
## Get Support
Join our Discord for real-time support and discussions.
Contact our team for technical assistance.
# Stream real-time data for a single asset
Source: https://docs.dexpaprika.com/streaming/stream-real-time-data-for-a-single-asset
get /stream
Establishes an SSE connection to stream updates for a specific token price using query parameters.
**Supported Events:** - `t_p`: Token Price update. Data schema matches `PriceResponse`. - `ping`: Keep-alive event. Data schema matches `PingEvent`. - `error`: Stream error event. Data schema matches `ErrorEvent`.
# Stream real-time reserves for a single asset
Source: https://docs.dexpaprika.com/streaming/stream-real-time-reserves-for-a-single-asset
get /reserves/stream
Establishes an SSE connection to stream updates for pool or token reserves using query parameters.
**Supported Events:** - `reserve_update`: Reserve update event. Data schema matches `ReserveUpdateEnriched`. - `ping`: Keep-alive event. Data schema matches `PingEvent`. - `error`: Stream error event. Data schema matches `ErrorEvent`.
# Subscribe to multiple assets streaming
Source: https://docs.dexpaprika.com/streaming/subscribe-to-multiple-assets-streaming
post /stream
Establishes an SSE connection to stream updates for multiple assets using a JSON request body.
**Supported Events:** - `t_p`: Token Price update. Data schema matches `PriceResponse`. - `ping`: Keep-alive event. Data schema matches `PingEvent`. - `error`: Stream error event. Data schema matches `ErrorEvent`.
# Subscribe to multiple reserves streaming
Source: https://docs.dexpaprika.com/streaming/subscribe-to-multiple-reserves-streaming
post /reserves/stream
Establishes an SSE connection to stream updates for multiple reserves using a JSON request body.
**Supported Events:** - `reserve_update`: Reserve update event. Data schema matches `ReserveUpdateEnriched`. - `ping`: Keep-alive event. Data schema matches `PingEvent`. - `error`: Stream error event. Data schema matches `ErrorEvent`.
# Quick Start: Your First Stream
Source: https://docs.dexpaprika.com/streaming/tutorials/quick-start
Build your first real-time crypto price streaming application in 5 minutes
**See it in action:** Check out our [Live Streaming Dashboard](https://crypto-streaming-dashboard-v3.vercel.app/) to see real-time price updates across multiple chains before you build your own.
## Tutorial overview
In this tutorial, you'll learn how to:
* Connect to the DexPaprika streaming API
* Receive real-time price updates
* Handle connection errors gracefully
* Build a simple price display
**Time to complete**: 5 minutes
**Prerequisites**: Basic JavaScript knowledge
***
## Step 1: Choose Your Asset
For this tutorial, we'll stream the price of Ethereum (WETH).
### Finding Token Addresses
Use the REST API to find token addresses:
1. **Search by name or symbol** using the [Search Endpoint](/api-reference/search/search-for-tokens-pools-and-dexes):
```bash theme={null}
curl "https://api.dexpaprika.com/search?query=WETH"
```
2. **Get network list** using the [Networks Endpoint](/api-reference/networks/get-a-list-of-available-blockchain-networks):
```bash theme={null}
curl "https://api.dexpaprika.com/networks"
```
### Common Token Addresses
Or use these verified addresses for popular tokens:
```
Chain: ethereum
WETH: 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
USDC: 0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
```
```
Chain: solana
SOL: So11111111111111111111111111111111111111112
USDC: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v
```
```
Chain: bsc
BNB: 0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c
USDT: 0x55d398326f99059ff775485246999027b3197955
```
***
## Step 2: Test with cURL
First, let's verify the stream works with a simple cURL command:
```bash theme={null}
curl -N "https://streaming.dexpaprika.com/stream?method=t_p&chain=ethereum&address=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2&limit=3"
```
You should see output like:
```
data: {"a":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","c":"ethereum","p":"3997.5514026436525223","t":1761733397}
event: t_p
data: {"a":"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","c":"ethereum","p":"3998.1234567890123456","t":1761733398}
event: t_p
```
The `limit=3` parameter closes the stream after 3 events - perfect for testing!
***
## Step 3: JavaScript Implementation
Here's how to connect to the streaming API using JavaScript:
```javascript theme={null}
// Connect to streaming API
const url = new URL('https://streaming.dexpaprika.com/stream');
url.searchParams.set('method', 't_p');
url.searchParams.set('chain', 'ethereum');
url.searchParams.set('address', '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2');
const eventSource = new EventSource(url.toString());
// Handle price updates
eventSource.addEventListener('t_p', (event) => {
const data = JSON.parse(event.data);
const price = parseFloat(data.p);
console.log(`WETH Price: $${price.toFixed(2)}`);
});
// Handle errors with reconnection
eventSource.onerror = () => {
console.log('Connection lost, reconnecting...');
eventSource.close();
// Implement reconnection logic here
};
```
**🎯 Live Example:** See this code in action in our [Interactive Streaming Dashboard](https://crypto-streaming-dashboard-v3.vercel.app/) - watch 6 tokens stream live across Ethereum, Solana, and BSC with real-time updates, connection status, and latency monitoring.
***
## Step 4: Customize Your Stream
### Stream Different Tokens
Modify the URL parameters to stream any token:
```javascript theme={null}
// Bitcoin on Ethereum
url.searchParams.set('chain', 'ethereum');
url.searchParams.set('address', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599');
// SOL on Solana
url.searchParams.set('chain', 'solana');
url.searchParams.set('address', 'So11111111111111111111111111111111111111112');
// BNB on BSC
url.searchParams.set('chain', 'bsc');
url.searchParams.set('address', '0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c');
```
### Add Multiple Assets
To stream multiple assets, switch to the POST method:
```javascript theme={null}
async function streamMultipleAssets() {
const assets = [
{ chain: 'ethereum', address: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', method: 't_p' },
{ chain: 'solana', address: 'So11111111111111111111111111111111111111112', method: 't_p' }
];
const response = await fetch('https://streaming.dexpaprika.com/stream', {
method: 'POST',
headers: {
'Accept': 'text/event-stream',
'Content-Type': 'application/json'
},
body: JSON.stringify(assets)
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) break;
const text = decoder.decode(value, { stream: true });
// Parse SSE events from text
console.log(text);
}
}
```
***
## Understanding the Code
### Key Components
The `EventSource` API is the browser's built-in way to handle SSE:
```javascript theme={null}
const eventSource = new EventSource(url);
eventSource.addEventListener('t_p', handler);
```
It automatically handles:
* Persistent connections
* Automatic reconnection
* Event parsing
The `onerror` callback handles disconnections:
```javascript theme={null}
eventSource.onerror = () => {
// Implement exponential backoff
const delay = baseDelay * Math.pow(2, attempts);
setTimeout(reconnect, delay);
};
```
Each event contains:
```javascript theme={null}
{
"a": "address", // Token contract address
"c": "chain", // Blockchain network
"p": "price", // USD price as string
"t": timestamp // Unix timestamp
}
```
***
## Implementation Notes
### Browser Support
* EventSource API works in all modern browsers
* For direct browser connections, you'll need to handle CORS (use a backend proxy)
* No issues when streaming from server-side (Node.js, Python, etc.)
### Best Practices
* Implement exponential backoff for reconnection
* Handle both connection errors and SSE error events
* Parse prices as floats to maintain precision
* Close connections properly on page unload
***
## See It Live
**Experience the API in action!** Our interactive demo streams 6 cryptocurrencies in real-time across Ethereum, Solana, and BSC. Watch live price updates, connection status, latency metrics, and update statistics. Built with React and deployed on Vercel - perfect reference implementation showing POST /stream with multiple assets.
**What you'll see:**
* Real-time price updates every \~1 second
* Multi-chain token streaming (ETH, SOL, BSC)
* Live connection status and latency
* Price change indicators and trends
* Total updates and uptime metrics
***
## Next Steps
Congratulations! You've built your first streaming application. Here's what to explore next:
Create reusable React components for streaming.
Learn POST /stream to efficiently track multiple tokens.
Track your entire portfolio value in real-time.
Learn error handling, monitoring, and scaling.
***
## Get Help
Get help from our community.
Read the complete API documentation.
# Coverage checker
Source: https://docs.dexpaprika.com/tools/coverage-checker
Use this tool to quickly verify whether an asset exists in DexPaprika’s dataset. Enter a contract address, token name, or ticker symbol; we’ll search our coverage and show the closest matches.
See also: [Networks](/api-reference/networks/get-a-list-of-available-blockchain-networks),
[Liquidity pool endpoint](/api-reference/pools/get-a-pool-on-a-network),
[Token data](/api-reference/tokens/get-a-tokens-latest-data-on-a-network)
### FAQs
Copy the token or pool address and pass it to the corresponding REST endpoints along with the network.
Public usage is allowed without keys; be considerate with high‑frequency queries.
Yes. Provide the `network` when calling token/pool endpoints.
### Next steps
Get pool reserves and metricsFetch swaps/adds/removes
# Batch Token Prices Efficiently
Source: https://docs.dexpaprika.com/tutorials/batch-token-prices
Learn how to fetch prices for multiple tokens using the multi-asset endpoint and avoid rate limiting with smart batching strategies.
## Tutorial overview
Efficiently fetch real-time prices for up to 10 tokens in a single API request using the DexPaprika **multi-asset endpoint**. This guide shows you why batching matters and how to implement it effectively.
The multi-asset endpoint is optimized for efficiency. Learn why batching is critical for sustainable API usage and how to structure your requests.
***
## Why batch requests? The math behind it
### Single request vs. batching
Let's say you need to monitor prices for **50 tokens** on Ethereum.
**Scenario 1: Individual Requests (❌ Inefficient)**
```
50 tokens × 1 request per token = 50 API calls
```
**Scenario 2: Using Multi-Asset Endpoint (✅ Efficient)**
```
50 tokens ÷ 10 tokens per batch = 5 API calls
```
**Result: You reduce API calls by 90%** ✅
### Real-world impact
| Use Case | Tokens to Monitor | Individual Requests | Batched Requests | Reduction |
| ------------------------- | ----------------- | ------------------- | ---------------- | --------- |
| Portfolio tracker | 20 tokens | 20 calls | 2 calls | 90% |
| DeFi aggregator | 100 tokens | 100 calls | 10 calls | 90% |
| Trading bot (30s updates) | 50 tokens/day | \~2,880 calls/day | \~288 calls/day | 90% |
| Real-time dashboard | 35 tokens | 35 calls | 4 calls | 88.6% |
**The Key Insight:** Using the multi-asset endpoint instead of individual token calls reduces your request count by up to **90%**. This means you can monitor more tokens, update more frequently, and stay well within rate limits.
***
## Understanding rate limits
The DexPaprika API is **public** with no formal limits currently enforced. Best practices like batching ensure sustainable usage as the service matures.
By batching requests:
* ✅ **Reduce server load** -- Fewer HTTP connections
* ✅ **Improve latency** -- Single network round-trip for multiple tokens
* ✅ **Future-proof your app** -- When rate limits are introduced, you're already optimized
* ✅ **Scale effortlessly** -- Monitor hundreds of tokens without performance degradation
***
## Step 1: Understanding the endpoint
The multi-asset pricing endpoint accepts:
* **Network** (path parameter): e.g., `ethereum`, `solana`, `base`
* **Tokens** (query parameter): Comma-separated list of up to 10 token addresses
* **Constraint:** Maximum 10 tokens per request, 2000 character limit
```bash theme={null}
GET /networks/{network}/multi/prices?tokens={token1},{token2},...,{token10}
```
***
## Step 2: Simple batch request
Fetch prices for 3 tokens on Ethereum in a single request:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xdac17f958d2ee523a2206206994597c13d831ec7,0x6b175474e89094c44da98b954eedeac495271d0f" | jq
```
Response:
```json Response [expandable] theme={null}
[
{
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"chain": "ethereum",
"price_usd": 4400.57
},
{
"id": "0xdac17f958d2ee523a2206206994597c13d831ec7",
"chain": "ethereum",
"price_usd": 1.0003
},
{
"id": "0x6b175474e89094c44da98b954eedeac495271d0f",
"chain": "ethereum",
"price_usd": 1.0001
}
]
```
Duplicate input addresses may produce duplicate entries in the response. Dedupe client-side if required.
***
## Step 3: Batching larger token lists in Node.js
If you need to monitor more than 10 tokens, split them into chunks:
```javascript theme={null}
const https = require('https');
const tokenAddresses = [
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", // WETH
"0xdac17f958d2ee523a2206206994597c13d831ec7", // USDT
"0x6b175474e89094c44da98b954eedeac495271d0f", // DAI
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", // USDC
"0x2260fac5e5542a773aa44fbcff9fafb9a190d659", // WBTC
"0x7fc66500c84a76ad7e9c93437e434122a1b63cad", // AAVE
"0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // UNI
"0x6982508145454ce325ddbe47a25d4ec3d2311933", // PEPE
"0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", // bbb (example)
"0xcccccccccccccccccccccccccccccccccccccccc", // ccc (example)
"0xdddddddddddddddddddddddddddddddddddddddd", // ddd (example)
"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", // eee (example)
];
// Split into chunks of 10
function chunkArray(arr, size) {
const chunks = [];
for (let i = 0; i < arr.length; i += size) {
chunks.push(arr.slice(i, i + size));
}
return chunks;
}
async function fetchPricesInBatches(network, tokens) {
const chunks = chunkArray(tokens, 10);
const allPrices = [];
for (const chunk of chunks) {
const tokensParam = chunk.join(',');
const url = `https://api.dexpaprika.com/networks/${network}/multi/prices?tokens=${tokensParam}`;
try {
const prices = await new Promise((resolve, reject) => {
https.get(url, (res) => {
let data = '';
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
resolve(JSON.parse(data));
});
}).on('error', reject);
});
allPrices.push(...prices);
console.log(`Fetched batch: ${chunk.length} tokens`);
} catch (error) {
console.error(`Error fetching batch:`, error);
}
}
return allPrices;
}
// Usage
(async () => {
const prices = await fetchPricesInBatches('ethereum', tokenAddresses);
console.log(`\nTotal tokens with prices: ${prices.length}`);
prices.forEach(token => {
console.log(`${token.id}: $${token.price_usd}`);
});
})();
```
### Axios variant (node.js)
```javascript theme={null}
import axios from 'axios';
async function fetchBatch(network, addresses) {
const tokensParam = addresses.join(',');
const url = `https://api.dexpaprika.com/networks/${network}/multi/prices`;
const { data } = await axios.get(url, { params: { tokens: tokensParam }, timeout: 5000 });
return data; // [{ id, chain, price_usd }, ...]
}
```
**Key Observation:** 12 tokens require only 2 API calls instead of 12! This is an **83% reduction** in network requests.
***
## Step 4: Python implementation with real-time monitoring
Build a simple price monitor that updates every 30 seconds:
```python theme={null}
import requests
import time
from typing import List, Dict
class TokenPriceMonitor:
def __init__(self, network: str = 'ethereum'):
self.network = network
self.base_url = f"https://api.dexpaprika.com/networks/{network}/multi/prices"
self.batch_size = 10
self.prices_cache = {}
def chunk_tokens(self, tokens: List[str]) -> List[List[str]]:
"""Split tokens into batches of max 10"""
return [tokens[i:i + self.batch_size] for i in range(0, len(tokens), self.batch_size)]
def fetch_prices(self, tokens: List[str]) -> Dict[str, float]:
"""Fetch prices for multiple tokens in batches"""
batches = self.chunk_tokens(tokens)
results = {}
for batch in batches:
tokens_param = ','.join(batch)
try:
response = requests.get(
self.base_url,
params={'tokens': tokens_param},
timeout=5
)
response.raise_for_status()
data = response.json()
for token in data:
results[token['id']] = token['price_usd']
except requests.RequestException as e:
print(f"Error fetching batch: {e}")
# Optional: basic backoff before next batch to avoid tight retry loops
time.sleep(1)
return results
def monitor_prices(self, tokens: List[str], interval: int = 30):
"""Continuously monitor token prices"""
print(f"Monitoring {len(tokens)} tokens on {self.network}")
print(f"Total API calls per update: {len(self.chunk_tokens(tokens))}")
try:
while True:
prices = self.fetch_prices(tokens)
print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] Updated {len(prices)} tokens")
for token, price in list(prices.items())[:5]:
print(f" {token}: ${price:.6f}")
if len(prices) > 5:
print(f" ... and {len(prices) - 5} more tokens")
time.sleep(interval)
except KeyboardInterrupt:
print("\nMonitoring stopped.")
# Example usage
if __name__ == "__main__":
monitor = TokenPriceMonitor(network='ethereum')
tokens_to_watch = [
"0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", # WETH
"0xdac17f958d2ee523a2206206994597c13d831ec7", # USDT
"0x6b175474e89094c44da98b954eedeac495271d0f", # DAI
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48", # USDC
"0x2260fac5e5542a773aa44fbcff9fafb9a190d659", # WBTC
]
monitor.monitor_prices(tokens_to_watch)
```
***
## Step 5: Error handling & edge cases
### Handling Invalid or Unpriced Tokens
Some tokens may not have prices. The endpoint returns only valid tokens:
```bash theme={null}
# Request with some invalid tokens
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xdeaddeaddeaddeaddeaddeaddeaddeaddaddadd" | jq
```
Response (only the priced token is returned):
```json theme={null}
[
{
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"chain": "ethereum",
"price_usd": 4400.57
}
]
```
### Edge-case requests
```bash theme={null}
# 0 tokens (expect 400)
curl -s -o /dev/stderr -w "%{http_code}\n" "https://api.dexpaprika.com/networks/ethereum/multi/prices"
# 11 tokens (expect 400)
curl -s -o /dev/stderr -w "%{http_code}\n" "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8,0x9,0xA,0xB"
```
**Best Practice:** Always validate the response. Check that the number of returned tokens matches your expectations. Handle missing tokens gracefully in your application.
***
## Step 6: Comparison: Single vs. batch requests
### Request 100 tokens for a dashboard
**❌ Without Batching:**
```bash theme={null}
for token in "${token_addresses[@]}"; do
curl -X GET "https://api.dexpaprika.com/networks/ethereum/tokens/$token"
done
# Result: 100 API calls
```
**✅ With Batching:**
```bash theme={null}
# Call 1
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=token1,token2,...,token10"
# Call 2
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=token11,token12,...,token20"
# ... Continue for remaining batches ...
# Result: 10 API calls
```
**Impact:**
* **90% fewer requests** ✅
* **10x faster execution** (single network round-trip per batch vs. 100 individual calls) ✅
* **Lower latency** for your users ✅
* **Future-proof** against rate limits ✅
***
## Performance metrics
**Benchmark: Fetching prices for 50 tokens on Ethereum**
| Metric | Single Requests | Batched (5 calls) |
| ------------------------------------ | --------------- | ----------------- |
| API Calls | 50 | 5 |
| Total Network Round-trips | 50 | 5 |
| Estimated Time (assuming 100ms/call) | 5,000ms | 500ms |
| Bandwidth Used | \~50KB | \~5KB |
| Server Load | High | Low |
**Result:** Batching achieves **10x faster responses** while reducing server load and bandwidth by 90%.
***
## Next steps
Explore the complete multi-asset endpoint documentation.
Learn how to fetch detailed data for individual tokens.
***
## Best practices summary
1. **Always batch** -- Use the multi-asset endpoint instead of individual calls
2. **Chunk large lists** -- Split more than 10 tokens into multiple batches (max 10 per call)
3. **Validate responses** -- Not all requested tokens may have prices; handle missing data
4. **Cache results** -- Store prices and update on a schedule instead of on every request
5. **Handle errors gracefully** -- Network timeouts and invalid tokens are normal; retry with backoff
6. **Monitor performance** -- Track API call counts to measure your optimization improvements
***
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve.
### FAQs
10 tokens per request. Requests with more than 10 tokens will return HTTP 400.
Duplicate inputs may yield duplicate entries in the response. Dedupe client-side if needed.
Tokens without prices are silently omitted from the response. Only priced tokens are returned.
No. The response order is not guaranteed to match your input order. Use the `id` field to identify each token.
No. Each batch must be for a single network. Use separate calls for different networks.
It depends on your use case. For dashboards, every 30-60 seconds is common. For trading bots, every 1-5 seconds. Batching enables frequent updates without excessive API calls.
Yes. The single token endpoint (`GET /networks/{network}/tokens/{token_address}`) provides detailed metadata like liquidity, volume, and holdings. Use it for deep analysis; use multi-asset for just prices.
No. At least one valid token is required. The endpoint returns HTTP 400 if the tokens list is empty.
# DexPaprika Claude Code plugin - Quick setup guide
Source: https://docs.dexpaprika.com/tutorials/claude-code-plugin-guide
Install the DexPaprika Claude Code plugin with two simple commands. Access real-time DEX data, liquidity pools, and token prices directly in Claude Code. Integrated MCP server with zero additional setup required.
## Tutorial overview
Get instant access to real-time DeFi data in Claude Code. The DexPaprika Claude Code plugin provides built-in access to decentralized exchanges, liquidity pools, and token pricing--all with just two commands.
The DexPaprika plugin is a **Claude Code plugin** with built-in MCP server access. Two commands. Zero additional setup. Real-time DEX data ready to use.
***
## What is the DexPaprika Claude Code plugin?
The DexPaprika plugin is a native Claude Code plugin that gives you instant access to real-time decentralized exchange (DEX) data, liquidity pool analytics, and token pricing information across 33 blockchain networks.
**Key features:**
* ✅ Real-time DEX and pool data access
* ✅ Token pricing and market analytics
* ✅ Liquidity pool information
* ✅ Multi-network blockchain support
* ✅ Built-in MCP server (no separate installation needed)
* ✅ Works in Claude Desktop and Cursor IDE
* ✅ No API keys required
***
## Quick installation (2 commands)
### Step 1: Add the CoinPaprika marketplace
```bash theme={null}
/plugin marketplace add coinpaprika/claude-marketplace
```
This adds access to the CoinPaprika marketplace where the DexPaprika plugin is hosted.
### Step 2: Install the DexPaprika plugin
```bash theme={null}
/plugin install dexpaprika
```
Select **"Install now"** when prompted.
### That's it! 🎉
You now have access to real-time DeFi data in Claude Code. No configuration files, no environment setup, no API keys needed.
***
## Using the plugin
Once installed, you can ask Claude about DeFi data naturally:
### Example queries
**Get pool information:**
```
What are the top liquidity pools on Ethereum by volume?
```
**Find token prices:**
```
Show me the current price of USDC and USDT on Ethereum.
```
**Analyze specific pools:**
```
Tell me about the USDC/ETH pool on Uniswap V3.
```
**Discover networks:**
```
What blockchain networks are supported by DexPaprika?
```
**Search for tokens:**
```
Find all pools that include the PEPE token.
```
Claude will automatically use the plugin to fetch real-time data and provide you with current market information.
***
## What's included in the plugin
The DexPaprika plugin gives Claude access to:
### Network information
* List of supported blockchain networks
* Network metadata and specifications
### Decentralized exchanges (DEXes)
* Available DEXes on each network
* DEX volume and activity data
* Protocol information
### Liquidity pools
* Top pools by volume, price, transactions
* Detailed pool metrics and token pairs
* Pool fee structures
* Recent transaction history
### Token data
* Current token prices in USD
* Market data and liquidity information
* Trading volume (5m, 15m, 1h, 6h, 24h)
* Token metadata and explorer links
### Search functionality
* Find tokens, pools, and DEXes across networks
* Search by name, symbol, or address
***
## Verify installation
After installing the plugin, you can check that it's working:
### Check available commands
```
/help
```
You should see the DexPaprika plugin listed among available commands.
### Test with a simple query
```
What networks does DexPaprika support?
```
Claude should return a list of supported blockchain networks (Ethereum, Solana, Base, Arbitrum, Polygon, etc.).
***
## Managing the plugin
### View installed plugins
```
/plugin
```
Select "Manage Plugins" to see all installed plugins and their status.
### Enable/disable the plugin
```
/plugin disable dexpaprika@coinpaprika
```
Disable the plugin if you want to reduce context usage, but keep it installed.
```
/plugin enable dexpaprika@coinpaprika
```
Re-enable the plugin when you need it again.
### Uninstall the plugin
```
/plugin uninstall dexpaprika@coinpaprika
```
Completely remove the plugin if you no longer need it.
### Update the plugin
```
/plugin marketplace update coinpaprika/claude-marketplace
```
Keep the plugin up-to-date with the latest features and improvements.
***
## Practical use cases
### Portfolio monitoring
Ask Claude to track your tokens:
```
Monitor these tokens on Ethereum:
- WETH (0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2)
- USDC (0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48)
- DAI (0x6b175474e89094c44da98b954eedeac495271d0f)
Show their current prices and highest volume pools.
```
### DEX comparison
```
Compare trading volumes on Uniswap and Curve across Ethereum and Polygon.
Which DEX has higher volume? Which pools are most active?
```
### Market research
```
On Solana, what are the top 10 liquidity pools by 24h volume?
For each pool, show token pairs, current price, volume in USD, and liquidity.
```
### Token discovery
```
Find emerging tokens on Base network.
Show the ones created recently with highest trading volume.
```
***
## How it works
The DexPaprika Claude Code plugin:
1. **Installs via the marketplace** -- `/plugin install dexpaprika`
2. **Includes built-in MCP server access** -- No separate MCP configuration needed
3. **Connects to DexPaprika API** -- Fetches real-time DEX and token data
4. **Provides data to Claude** -- Claude uses the data to answer your questions
5. **Returns formatted results** -- Get market analysis, pool data, pricing information
The MCP server is **built into the plugin**, so you don't need to install or configure it separately.
***
## Troubleshooting
### Plugin not showing up
**Problem:** After installing, you don't see the DexPaprika plugin in `/help`
**Solution:**
1. Run `/plugin marketplace update coinpaprika/claude-marketplace`
2. Restart Claude Code
3. Run `/plugin install dexpaprika` again
### Claude not using the plugin
**Problem:** You ask about DEX data but Claude doesn't use the plugin
**Solution:**
* Ask explicitly: "Using DexPaprika, show me..."
* Or phrase questions about pools, tokens, and DEXes specifically
* Claude automatically recognizes plugin-relevant queries
### Plugin commands not working
**Problem:** `/plugin` commands not recognized
**Solution:**
* Ensure you're in Claude Code (not another terminal)
* Check that you're using the correct syntax: `/plugin install dexpaprika`
* Verify marketplace is added: `/plugin marketplace add coinpaprika/claude-marketplace`
### No data returned
**Problem:** Claude can't find data for your query
**Solution:**
* Check the network name (use lowercase: `ethereum`, `solana`, not `Ethereum`)
* Verify token address format for your blockchain
* Some tokens may not have pricing data; try with major tokens (WETH, USDC, DAI)
***
## Integration with CoinPaprika plugin
The same marketplace also hosts the **CoinPaprika plugin** for global cryptocurrency market data.
**Install both for complete crypto coverage:**
```bash theme={null}
/plugin install dexpaprika
/plugin install coinpaprika
```
**What you get:**
* **DexPaprika plugin** -- DEX pools, on-chain liquidity, tokens on specific networks
* **CoinPaprika plugin** -- Global crypto rankings, market cap, exchange data
Use them together to compare DEX prices with exchange prices and find arbitrage opportunities.
***
## Next steps
Explore the complete DexPaprika API documentation for all available data.
Learn how to efficiently fetch prices for multiple tokens.
Step-by-step guide to querying token data via the API.
Learn more about Claude Code plugins and marketplaces.
***
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve the plugin.
### FAQs
Two commands:
1. `/plugin marketplace add coinpaprika/claude-marketplace`
2. `/plugin install dexpaprika`
That's it! No configuration needed.
No. The DexPaprika API is public and free. No authentication required.
Yes. The plugin works in both Claude Desktop and Cursor IDE.
The **Claude Code plugin** is the easy way to get started--just install and use. It includes built-in access to the MCP server. If you need advanced MCP configuration, you can set up the MCP server separately for more control, but the plugin handles this for you automatically.
Yes. Run `/plugin disable dexpaprika@coinpaprika` to turn it off, then `/plugin enable dexpaprika@coinpaprika` to turn it back on.
The plugin receives updates automatically from the marketplace. Run `/plugin marketplace update coinpaprika/claude-marketplace` to check for updates.
33 networks including Ethereum, Solana, Base, Arbitrum, Polygon, Optimism, Fantom, Avalanche, Binance Smart Chain, and more. Ask Claude: "What networks are supported?"
Yes! Install both for comprehensive crypto data:
* `DexPaprika` -- DEX and on-chain pool data
* `CoinPaprika` -- Global market cap and exchange data
Ask explicitly: "Using DexPaprika, show me..." or phrase your question about pools, tokens, and DEXes specifically.
The plugin only makes read-only API calls to public DexPaprika endpoints. No private data is transmitted. All queries are logged per standard Anthropic policy.
# DexPaprika CLI -- DEX data from your terminal
Source: https://docs.dexpaprika.com/tutorials/cli
Install the DexPaprika CLI with one command. Query token prices, pool data, OHLCV history, transactions, and stream live prices from your terminal. Supports macOS, Linux, and Windows.
## What is the DexPaprika CLI?
A fast, standalone command-line tool for querying on-chain DEX data. Written in Rust. Covers the entire DexPaprika API -- token prices, pools, OHLCV, transactions, search, pool filtering, and real-time price streaming via SSE.
No API key. No dependencies. One binary.
**Source:** [github.com/coinpaprika/dexpaprika-cli](https://github.com/coinpaprika/dexpaprika-cli)
***
## Install
### One-line install (macOS, Linux)
```bash theme={null}
curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh | sh
```
Downloads the latest release binary for your platform and puts it in `~/.local/bin`. You can override the install path:
```bash theme={null}
DEXPAPRIKA_INSTALL_DIR=/usr/local/bin curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh | sh
```
### Download from GitHub
Pre-built binaries for every platform are on the [releases page](https://github.com/coinpaprika/dexpaprika-cli/releases):
| Platform | Binary |
| --------------------- | ------------------------------------------------ |
| macOS (Apple Silicon) | `dexpaprika-cli-{version}-darwin-aarch64.tar.gz` |
| macOS (Intel) | `dexpaprika-cli-{version}-darwin-x86_64.tar.gz` |
| Linux (x86\_64) | `dexpaprika-cli-{version}-linux-x86_64.tar.gz` |
| Linux (ARM64) | `dexpaprika-cli-{version}-linux-aarch64.tar.gz` |
| Windows (x86\_64) | `dexpaprika-cli-{version}-windows-x86_64.zip` |
### Build from source
Requires [Rust](https://rustup.rs/):
```bash theme={null}
cargo install --git https://github.com/coinpaprika/dexpaprika-cli
```
### Verify installation
```bash theme={null}
dexpaprika-cli status
```
You should see a health check response confirming the API is reachable.
***
## Commands
Every DexPaprika REST API endpoint has a matching CLI command:
| Command | What it does | Example |
| -------------- | -------------------------------------------------- | --------------------------------------------------------------------------------- |
| `stats` | Ecosystem overview (total networks, pools, tokens) | `dexpaprika-cli stats` |
| `networks` | List all supported chains | `dexpaprika-cli networks` |
| `dexes` | DEXes on a network | `dexpaprika-cli dexes ethereum` |
| `pools` | Top pools on a network | `dexpaprika-cli pools ethereum --limit 5` |
| `pool` | Single pool details | `dexpaprika-cli pool ethereum 0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640` |
| `dex-pools` | Pools on a specific DEX | `dexpaprika-cli dex-pools ethereum uniswap_v3` |
| `transactions` | Recent swaps for a pool | `dexpaprika-cli transactions ethereum 0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640` |
| `pool-ohlcv` | Historical OHLCV candles | `dexpaprika-cli pool-ohlcv ethereum 0x88e6... --start 2025-01-01` |
| `token` | Token price and details | `dexpaprika-cli token ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` |
| `token-pools` | All pools containing a token | `dexpaprika-cli token-pools ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` |
| `prices` | Batch token prices (up to 10) | `dexpaprika-cli prices ethereum --tokens 0xc02a...,0xdac1...` |
| `search` | Search tokens, pools, DEXes | `dexpaprika-cli search uniswap` |
| `stream` | Real-time SSE price stream | `dexpaprika-cli stream ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2` |
| `status` | API health check | `dexpaprika-cli status` |
| `attribution` | License attribution snippets | `dexpaprika-cli attribution` |
| `onboard` | Quick start walkthrough | `dexpaprika-cli onboard` |
| `shell` | Interactive REPL mode | `dexpaprika-cli shell` |
***
## Output formats
The CLI outputs tables by default. Switch to JSON for scripting and piping:
```bash theme={null}
# Table output (default, human-readable)
dexpaprika-cli pools ethereum
# JSON with metadata wrapper
dexpaprika-cli --output json pools ethereum
# Raw JSON (no _meta wrapper, for piping to jq)
dexpaprika-cli --output json --raw pools ethereum
```
Pipe raw JSON into `jq` for filtering:
```bash theme={null}
dexpaprika-cli --output json --raw token ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 | jq '.summary.price_usd'
```
***
## Examples
### Get a token price
```bash theme={null}
dexpaprika-cli token solana So11111111111111111111111111111111111111112
```
### Search for a token you don't know the address of
```bash theme={null}
dexpaprika-cli search jupiter
```
### List top pools by volume
```bash theme={null}
dexpaprika-cli pools ethereum --limit 10
```
### Get OHLCV history for a pool
```bash theme={null}
dexpaprika-cli pool-ohlcv ethereum 0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 --start 2025-01-01
```
### Stream live prices
```bash theme={null}
# Single token -- streams until you hit Ctrl+C
dexpaprika-cli stream ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
# Stop after 50 price updates
dexpaprika-cli stream ethereum 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 --limit 50
# Multiple tokens from a JSON watchlist file
dexpaprika-cli stream --tokens watchlist.json --limit 100
```
### Interactive REPL
```bash theme={null}
dexpaprika-cli shell
```
Opens an interactive session where you can run commands without typing `dexpaprika-cli` each time.
### Batch prices for a portfolio
```bash theme={null}
dexpaprika-cli prices ethereum --tokens 0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48,0x6b175474e89094c44da98b954eedeac495271d0f
```
***
## Use with AI agents
AI agents running in terminals (Claude Code, Aider, etc.) can install and use the CLI as a tool. The one-liner install works in any shell:
```bash theme={null}
curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh | sh
```
Once installed, agents can call `dexpaprika-cli` directly with `--output json --raw` for machine-readable output. This is useful when:
* The agent doesn't have MCP support
* You want the agent to script data pipelines
* You need to pipe output into other tools (`jq`, `csvkit`, scripts)
* You're running headless or in CI/CD
**Example agent workflow:**
```bash theme={null}
# Agent searches for a token
dexpaprika-cli --output json --raw search "pepe" | jq '.tokens[0]'
# Agent gets the price
dexpaprika-cli --output json --raw token ethereum 0x6982508145454ce325ddbe47a25d4ec3d2311933 | jq '.summary.price_usd'
# Agent finds the top pool
dexpaprika-cli --output json --raw token-pools ethereum 0x6982508145454ce325ddbe47a25d4ec3d2311933 | jq '.[0]'
```
***
## Troubleshooting
The installer puts the binary in `~/.local/bin`. If that's not in your PATH, add it:
```bash theme={null}
export PATH="$HOME/.local/bin:$PATH"
```
Add that line to your `~/.bashrc`, `~/.zshrc`, or `~/.profile` to make it permanent.
The installer tries `~/.local/bin` first (no sudo needed). If it falls back to `/usr/local/bin`, it will ask for sudo. You can also set a custom directory:
```bash theme={null}
DEXPAPRIKA_INSTALL_DIR=~/bin curl -sSL https://raw.githubusercontent.com/coinpaprika/dexpaprika-cli/main/install.sh | sh
```
Check the network ID (must be lowercase: `ethereum`, not `Ethereum`) and verify the token address. Use `dexpaprika-cli search ` to find the correct network and address.
SSE streams can drop due to network issues. The `stream` command will show an error. Restart it -- the CLI handles reconnection. For production use, wrap it in a script with retry logic.
***
## Next steps
Full endpoint documentation with interactive playground
Real-time price streaming docs
Standard API workflows
Build projects with AI + DexPaprika
### FAQs
No. The CLI uses the public DexPaprika API. No keys, no registration.
Same as the REST API: 10,000 requests per day. Each CLI command makes one API call (except `stream`, which is a single long-lived SSE connection).
The filter endpoint can be accessed via the REST API directly. Check the [pool filtering tutorial](/tutorials/pool-filtering) for examples.
Yes. Download the Windows binary from the [releases page](https://github.com/coinpaprika/dexpaprika-cli/releases). The install script works on macOS and Linux only.
# Build a crypto price alert bot
Source: https://docs.dexpaprika.com/tutorials/crypto-alert-bot
Learn how to create a real-time cryptocurrency price alert system using DexPaprika API and Telegram
The DexPaprika API provides reliable data access. If you find any issues or have suggestions for improvement, please [contact us](mailto:support@coinpaprika.com).
## Overview
This tutorial guides you through building a **real-time cryptocurrency price alert system** that monitors prices using the **DexPaprika API** and sends notifications to your Telegram when price thresholds are met. Perfect for traders and developers who want to stay updated on market movements without constant manual checking.
The complete code for this tutorial is available on [GitHub](https://github.com/coinpaprika/tutorials/tree/main/crypto-alert-bot).
***
## Features
* Track any cryptocurrency available on DexPaprika API
* Set custom price thresholds for buy/sell opportunities
* Get instant alerts when prices go above or below your targets
* Configure check intervals to match your trading strategy
* Receive notifications directly on Telegram
***
## Prerequisites
* Node.js (v14 or higher)
* npm (Node Package Manager)
* A Telegram account
* A Telegram Bot (created using BotFather)
***
## Step 1: Create your Telegram bot
1. Open Telegram and search for "BotFather" (@BotFather)
2. Start a chat and send the command `/newbot`
3. Follow the instructions to create your bot
4. Save the **bot token** BotFather provides you
***
## Step 2: Get your Telegram chat ID
1. Start a conversation with your new bot
2. Send any message to your bot
3. Visit this URL in your browser (replace with your actual token):
```bash theme={null}
https://api.telegram.org/botYOUR_BOT_TOKEN/getUpdates
```
4. Find the `"chat":{"id":XXXXXXXXX,` value in the response - this is your **chat ID**
***
## Step 3: Set up the project
1. Clone the repository or set up a new project:
```bash theme={null}
git clone https://github.com/coinpaprika/tutorials/tree/main/crypto-alert-bot
# OR
mkdir crypto-alert-bot
cd crypto-alert-bot
npm init -y
```
2. Install required dependencies:
```bash theme={null}
npm install axios dotenv node-telegram-bot-api
```
3. Create the following files in your project directory:
* `.env` (configuration file)
* `index.js` (main application)
***
## Step 4: Configure your settings
Create a `.env` file in the project directory with the following parameters:
```
# Telegram Bot Token (Get this from BotFather on Telegram)
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
# Telegram Chat ID (The chat where alerts will be sent)
TELEGRAM_CHAT_ID=your_telegram_chat_id_here
# Cryptocurrency to track (token address)
CRYPTO_TOKEN_ID=So11111111111111111111111111111111111111112
CRYPTO_NETWORK=solana
# Price threshold for alert (in USD)
TARGET_PRICE=135
# Alert type: "above" or "below" - to trigger when price goes above or below target
ALERT_TYPE=above
# How often to check price (in minutes)
CHECK_INTERVAL=1
```
Make sure to replace placeholder values with your actual configuration details.
***
## Step 5: Create the alert bot
Create an `index.js` file with the following code:
```javascript expandable [expandable] theme={null}
require('dotenv').config();
const axios = require('axios');
const TelegramBot = require('node-telegram-bot-api');
// Configuration from .env file
const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
const CRYPTO_TOKEN_ID = process.env.CRYPTO_TOKEN_ID;
const CRYPTO_NETWORK = process.env.CRYPTO_NETWORK;
const TARGET_PRICE = parseFloat(process.env.TARGET_PRICE);
const ALERT_TYPE = process.env.ALERT_TYPE.toLowerCase();
const CHECK_INTERVAL = parseInt(process.env.CHECK_INTERVAL) * 60 * 1000; // Convert minutes to milliseconds
// Initialize Telegram Bot
const bot = new TelegramBot(TELEGRAM_BOT_TOKEN);
// Validate configuration
if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID || !CRYPTO_TOKEN_ID || !CRYPTO_NETWORK ||
isNaN(TARGET_PRICE) || !ALERT_TYPE || isNaN(CHECK_INTERVAL)) {
console.error('Invalid configuration. Please check your .env file.');
process.exit(1);
}
// Send startup message
bot.sendMessage(TELEGRAM_CHAT_ID,
`🤖 Crypto Alert Bot Started!\n\n` +
`Monitoring: ${CRYPTO_TOKEN_ID} on ${CRYPTO_NETWORK}\n` +
`Alert when price goes ${ALERT_TYPE} $${TARGET_PRICE}\n` +
`Checking every ${CHECK_INTERVAL / 60000} minute(s)`
);
// Variables to track alert state
let alertSent = false;
let lastPrice = 0;
// Main function to check price and send alerts
async function checkPrice() {
try {
// Fetch current price from DexPaprika API
const response = await axios.get(
`https://api.dexpaprika.com/networks/${CRYPTO_NETWORK}/tokens/${CRYPTO_TOKEN_ID}`
);
// Extract price from response
const currentPrice = response.data.summary.price_usd;
lastPrice = currentPrice;
console.log(`Current price of ${CRYPTO_TOKEN_ID}: $${currentPrice}`);
// Check if alert condition is met
let shouldAlert = false;
if (ALERT_TYPE === 'above' && currentPrice > TARGET_PRICE) {
shouldAlert = true;
} else if (ALERT_TYPE === 'below' && currentPrice < TARGET_PRICE) {
shouldAlert = true;
}
// Send alert if condition is met and no alert was sent before
if (shouldAlert && !alertSent) {
const message =
`🚨 PRICE ALERT 🚨\n\n` +
`${response.data.name} (${response.data.symbol})\n` +
`Current Price: $${currentPrice}\n` +
`Target: ${ALERT_TYPE} $${TARGET_PRICE}\n\n` +
`Condition met! 🎯`;
bot.sendMessage(TELEGRAM_CHAT_ID, message);
alertSent = true;
console.log('Alert sent!');
}
// Reset alert flag if price goes back on the other side of the threshold
if ((ALERT_TYPE === 'above' && currentPrice < TARGET_PRICE) ||
(ALERT_TYPE === 'below' && currentPrice > TARGET_PRICE)) {
alertSent = false;
}
} catch (error) {
console.error('Error checking price:', error.message);
// Send error notification if API fails
if (error.response) {
bot.sendMessage(TELEGRAM_CHAT_ID,
`⚠️ Error checking price: ${error.response.status} - ${error.response.statusText}`);
} else {
bot.sendMessage(TELEGRAM_CHAT_ID,
`⚠️ Error checking price: ${error.message}`);
}
}
}
// Run the price check immediately
checkPrice();
// Then set up interval to check regularly
setInterval(checkPrice, CHECK_INTERVAL);
console.log(`Bot is running. Checking ${CRYPTO_TOKEN_ID} every ${CHECK_INTERVAL / 60000} minute(s).`);
```
***
## Step 6: Finding the right token address
Need to track a different token? Use DexPaprika API to find its address:
1. List available networks:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks" | jq
```
2. Search for your token:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/search?query=YOUR_TOKEN_NAME" | jq
```
***
## Step 7: Running the bot
1. Start the bot:
```bash theme={null}
node index.js
```
2. You'll receive a confirmation message on Telegram.
3. The bot will check prices at your specified interval
4. When your price condition is met, you'll get an alert
***
## Running as a background service
### On Linux/Mac:
```bash theme={null}
npm install -g pm2
pm2 start index.js --name crypto-alert
pm2 save
```
### On Windows:
```bash theme={null}
npm install -g forever
forever start index.js
```
***
## How it works
1. The application connects to DexPaprika API to retrieve real-time token prices
2. It compares the current price against your target threshold
3. When the condition is met, it sends an immediate alert via the Telegram Bot API
4. The process repeats based on your configured check interval
***
## Troubleshooting
* Not receiving messages? Double-check your bot token and chat ID
* Ensure your network/token combination is valid in DexPaprika
* Check console output for any error messages
***
## Next steps
Extend the code to monitor multiple tokens or set different thresholds.
Build a visual interface to manage your alerts and view price history.
### FAQs
It reads `summary.price_usd` from the token details endpoint for the specified `network` and `token_address`.
Start with 1–5 minutes depending on volatility; avoid very aggressive intervals to be polite to the public API.
Use the Search endpoint or list networks first, then fetch the token by address to verify.
Yes--query pool details or transactions and set thresholds on `liquidity_usd` or recent `volume_usd`.
**Share Your Extensions!** Built something cool by extending this tutorial? We'd love to see it!
Share your work on our [Discord](https://discord.gg/DhJge5TUGM) - your tutorial might be featured on our website.
Ideas to try: smart trend alerts, multi-token tracking, or historical data analysis.
***
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve.
# Fetching token prices
Source: https://docs.dexpaprika.com/tutorials/fetch-token-price
Learn how to retrieve the price of any token using DexPaprika API with simple curl commands.
## Tutorial overview
Fetch real‑time token prices from the DexPaprika DEX API using a `network` id and `token_address`.
The DexPaprika API provides reliable data access. If you find any issues or have suggestions for improvement, please [contact us](mailto:support@coinpaprika.com).
## Fetching token prices
This tutorial will walk you through retrieving the **latest price of any token** using **DexPaprika API**. We will use simple `cURL` commands to interact with the API.
You can test the API directly in the documentation without writing any code. Visit the [API Reference](/api-reference/introduction) to try it out.
***
## Step 1: Get available networks
To fetch token data, you need the **network ID**. Use this request to get a list of supported blockchain networks:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks" | jq
```
The response will include networks like **Solana, Base, Aptos, Ethereum**, etc. Choose the one you need.
You can find the full list of supported networks in the [Networks API](/api-reference/networks/get-a-list-of-available-blockchain-networks).
***
## Step 2: Find a token address
If you don't have a token address, you can search for it using the API:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/search?query=YOUR_INPUT"
```
Replace `YOUR_INPUT` with the actual phrase you're looking for. The response will return matching token & pools along with their addresses.
***
## Step 3: Fetch the token price
Once you have the **network ID** and **token address**, use the following request to get the token's price:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/{network}/tokens/{token_address}"
```
Replace:
* `{network}` with the network (e.g., `solana`, `base`)
* `{token_address}` with the address found in Step 2
The response will return data like this:
```json Response [expandable] theme={null}
{
"id": "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
"name": "Jupiter",
"symbol": "JUP",
"chain": "solana",
"decimals": 6,
"total_supply": 9999979509174084,
"description": "",
"website": "",
"explorer": "",
"added_at": "2024-09-11T04:37:20Z",
"summary": {
"price_usd": 0.6863252359922881,
"fdv": 6863238296.5519485244070243816004,
"liquidity_usd": 25575125.4495078768612017,
"24h": {
"volume": 80207699.45778705,
"volume_usd": 55796800.523819186,
"sell": 106864,
"buy": 57315,
"txns": 164179
},
"6h": {
"volume": 11540575.177305005,
"volume_usd": 8037337.331943456,
"sell": 17801,
"buy": 9926,
"txns": 27727
},
"1h": {
"volume": 2766848.754695,
"volume_usd": 1900837.0877990713,
"sell": 3484,
"buy": 2082,
"txns": 5566
},
"30m": {
"volume": 1394651.1182109998,
"volume_usd": 954794.8829624434,
"sell": 1907,
"buy": 1198,
"txns": 3105
},
"15m": {
"volume": 373588.37757400004,
"volume_usd": 255759.0367338767,
"sell": 742,
"buy": 316,
"txns": 1058
},
"5m": {
"volume": 109317.68508500002,
"volume_usd": 74963.92390747965,
"sell": 265,
"buy": 86,
"txns": 351
}
},
"last_updated": "2025-02-26T13:11:25.858732857Z"
}
```
***
## Step 4: Extract only the price (single token)
If you only need the **token price in USD**, you can filter the response using `jq`:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/{network}/tokens/{token_address}" | jq '.summary.price_usd'
```
This will return only the price:
```json theme={null}
0.6863252359922881
```
***
## Step 5: Fetch prices for multiple tokens (batch)
If you need prices for multiple tokens at once on the same network, use the batch pricing endpoint:
```bash theme={null}
curl -X GET "https://api.dexpaprika.com/networks/ethereum/multi/prices?tokens=0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2,0xdac17f958d2ee523a2206206994597c13d831ec7" | jq
```
Example response:
```json Response [expandable] theme={null}
[
{ "id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "chain": "ethereum", "price_usd": 4400.5697112921535 },
{ "id": "0xdac17f958d2ee523a2206206994597c13d831ec7", "chain": "ethereum", "price_usd": 1.0002529851244053 }
]
```
Notes:
* Provide a comma-separated list in a single `tokens` parameter.
* Unknown or unpriced tokens are omitted from the array.
* Order is not guaranteed.
* You can pass up to 10 tokens per request; more than 10 returns HTTP 400.
Explore the full endpoint docs: [Get batched token prices on a network](/api-reference/tokens/get-batched-token-prices-on-a-network)
***
## Next steps
Jump straight into the API documentation and start making requests within minutes.
Learn more ways to integrate DexPaprika into your applications.
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve.
### FAQs
The `network` id (e.g., `solana`, `ethereum`) and the on‑chain `token_address`.
`summary.price_usd` returns USD. Other quote currencies may be added later; USD is the canonical quote.
Thin pools can be noisy; prefer higher‑volume pools or the token’s main pool from the token response.
No. The API is public; no keys or registration required.
# Find new crypto pools and token launches
Source: https://docs.dexpaprika.com/tutorials/find-new-pools
Discover newly created liquidity pools across 33 blockchains. Perfect for finding new tokens, arbitrage opportunities, and emerging DeFi projects early.
## Tutorial overview
Discover newly created liquidity pools by sorting pools on each network by `created_at` and applying activity filters.
Hitting any snags? We've got your back - [reach out](mailto:support@coinpaprika.com) and we'll help you get this working.
## Why monitor new pools?
New liquidity pools are where the action happens in DeFi. They signal new token launches, liquidity migrations, and fresh trading opportunities. Being first to spot them can be a serious advantage.
**What you can catch early:**
* **New token launches** before they hit major trackers
* **Arbitrage opportunities** between pools
* **Liquidity migrations** to better DEXes
* **Emerging projects** before they explode
**TL;DR**: Jump to [Step 2](#step-2-get-newest-pools) if you want to start pulling new pools immediately.
***
## Step 1: Pick your networks
First, see what blockchains you want to monitor using the [Networks API](/api-reference/networks/get-a-list-of-available-blockchain-networks):
```bash theme={null}
curl "https://api.dexpaprika.com/networks" | jq '.[] | {id: .id, name: .display_name}'
```
***
## Step 2: Get newest pools
Here's the money shot - getting pools sorted by creation date using the [Network Pools API](/api-reference/pools/get-top-x-pools-on-a-network):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=10" | jq
```
### What these parameters do:
| Parameter | Effect | Pro Tip |
| -------------------- | -------------------------- | --------------------------------------- |
| `orderBy=created_at` | Sort by when pool was made | Only way to find truly new pools |
| `sort=desc` | Newest first | Use `asc` for historical analysis |
| `limit=10` | How many pools back | Max is 100, but 10-20 is usually enough |
| `page=0` | Pagination | Increase for deeper history |
### What you get:
```json theme={null}
{
"pools": [
{
"id": "0x462229e7fc9e6cab0ebbd643cc6dfef2a5261ee9",
"dex_name": "Uniswap V2",
"created_at": "2025-06-09T09:28:35Z",
"volume_usd": 767.17,
"transactions": 5,
"tokens": [
{
"symbol": "🧸TEDDYS",
"name": "🧸TeddySwap",
"fdv": 18769.56
},
{
"symbol": "WETH",
"fdv": 6617036250.33
}
]
}
]
}
```
**Red flags to watch for:**
* Crazy high FDV on new tokens (possible honeypot)
* Zero transactions after hours (might be a test pool)
***
## Focus on specific DEXes
Want to monitor just Uniswap or Raydium? First get the DEX list using the [Network DEXes API](/api-reference/dexes/get-a-list-of-available-dexes-on-a-network):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/dexes" | jq '.[] | {id: .id, name: .name}'
```
Then filter new pools by DEX using the [DEX Pools API](/api-reference/pools/get-top-x-pools-on-a-networks-dex):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/dexes/uniswap_v3/pools?orderBy=created_at&sort=desc&limit=10" | jq
```
***
## Multi-chain monitoring
Real pros monitor multiple chains simultaneously. Here's how:
### Ethereum
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=5" | jq '.pools[] | {chain: "ethereum", pool: .id, created: .created_at, volume: .volume_usd, tokens: [.tokens[].symbol]}'
```
### Solana
```bash theme={null}
curl "https://api.dexpaprika.com/networks/solana/pools?orderBy=created_at&sort=desc&limit=5" | jq '.pools[] | {chain: "solana", pool: .id, created: .created_at, volume: .volume_usd, tokens: [.tokens[].symbol]}'
```
### Base
```bash theme={null}
curl "https://api.dexpaprika.com/networks/base/pools?orderBy=created_at&sort=desc&limit=5" | jq '.pools[] | {chain: "base", pool: .id, created: .created_at, volume: .volume_usd, tokens: [.tokens[].symbol]}'
```
**Pro tip**: Use different limits based on chain activity. Solana might need `limit=20` because of memecoin amounts, while Ethereum `limit=5` catches the important stuff.
***
## Smart filtering strategies
### Only high-activity pools
Skip the dead pools - focus on ones with real trading:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=50" | jq '.pools[] | select(.volume_usd > 1000 and .transactions > 10) | {id: .id, created: .created_at, volume: .volume_usd, txns: .transactions}'
```
### Last 24 hours only
Filter by timestamp to get super fresh pools:
```bash theme={null}
# Get pools from last 24 hours (adjust date as needed)
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=100" | jq --arg yesterday "$(date -d '1 day ago' -Iseconds)" '.pools[] | select(.created_at > $yesterday) | {id: .id, age: .created_at, volume: .volume_usd}'
```
### New token launches
Look for pools where the tokens themselves are brand new:
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=20" | jq '.pools[] | select(.tokens[] | .added_at > "2025-01-25T00:00:00Z") | {pool: .id, pool_age: .created_at, new_tokens: [.tokens[] | select(.added_at > "2025-01-25T00:00:00Z") | .symbol]}'
```
***
## Production monitoring setup
### Simple monitoring script
Here's a bash script that checks for new pools every 5 minutes:
```bash theme={null}
#!/bin/bash
# Monitor new pools across multiple chains
CHAINS=("ethereum" "solana" "base")
MIN_VOLUME=5000
while true; do
echo "🔍 Checking for new pools at $(date)"
for chain in "${CHAINS[@]}"; do
echo "--- $chain ---"
# Get new pools with decent volume
curl -s "https://api.dexpaprika.com/networks/$chain/pools?orderBy=created_at&sort=desc&limit=10" | \
jq --argjson min_vol $MIN_VOLUME '.pools[] | select(.volume_usd > $min_vol) | {
pool_id: .id,
chain: "'$chain'",
created: .created_at,
volume: .volume_usd,
tokens: [.tokens[].symbol]
}'
done
echo "⏰ Sleeping for 5 minutes..."
sleep 300
done
```
### Alert on high-volume new pools
Catch the big moves automatically:
```bash theme={null}
# Check for new pools with serious volume
NEW_POOLS=$(curl -s "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=20" | jq '.pools[] | select(.volume_usd > 50000)')
if [ -n "$NEW_POOLS" ]; then
echo "🚨 HIGH VOLUME NEW POOL DETECTED!"
echo "$NEW_POOLS"
# Add your notification here (Discord webhook, Slack, email, etc.)
# curl -X POST "YOUR_DISCORD_WEBHOOK" -d "{\"content\": \"New high-volume pool: $NEW_POOLS\"}"
fi
```
***
## Troubleshooting common issues
### "No new pools found"
Check if you're looking at the right timeframe:
```bash theme={null}
# See when the last pool was created
curl "https://api.dexpaprika.com/networks/ethereum/pools?orderBy=created_at&sort=desc&limit=1" | jq '.pools[0].created_at'
```
### "Too much spam"
Filter out low-quality pools:
```bash theme={null}
# More restrictive filtering
curl "https://api.dexpaprika.com/networks/solana/pools?orderBy=created_at&sort=desc&limit=50" | jq '.pools[] | select(.transactions > 20 and .volume_usd > 5000 and (.tokens[0].fdv < 100000000 or .tokens[1].fdv < 100000000))'
```
### "Missing opportunities"
You might need to check more frequently or cast a wider net:
```bash theme={null}
# Check multiple DEXes on one chain
for dex in uniswap_v3 uniswap_v2 sushiswap; do
echo "=== $dex ==="
curl -s "https://api.dexpaprika.com/networks/ethereum/dexes/$dex/pools?orderBy=created_at&sort=desc&limit=3" | jq '.pools[0] | {dex: "'$dex'", created: .created_at, tokens: [.tokens[].symbol]}'
done
```
***
## What's next?
Analyze new pools with price history.
Monitor trading activity in real-time.
Get comprehensive pool information and metadata.
Find pools, tokens, and DEXes across all networks.
## Need help?
Share strategies and get help from other builders.
Stuck on something? We'll help you figure it out.
### FAQs
Sort by `created_at` descending and set a reasonable `limit`. Poll periodically and de‑duplicate by pool id.
Combine `volume_usd` and `transactions` thresholds; optionally whitelist DEXes or networks.
Run parallel requests with conservative rate limits and merge results with a timestamp key.
Yes--query newest pools and alert when `volume_usd` exceeds your threshold.
# Local crypto analytics with DuckDB
Source: https://docs.dexpaprika.com/tutorials/local-analytics-with-duckdb
Build a powerful, local crypto analytics database with DuckDB. This tutorial guides you through creating an ETL pipeline for Uniswap v3 data to run complex SQL queries instantly.
## Tutorial overview
Create a local DuckDB analytics database from DEX pools and OHLCV for instant SQL over on‑chain data.
## The local powerhouse: A core pattern for on-chain analysis
Why make thousands of slow, rate-limited API calls when you can run complex SQL queries instantly on your own machine? This tutorial introduces the most effective pattern for crypto data analysis: creating a local, high-performance copy of a complete on-chain dataset. By fetching the data once, you unlock unlimited, high-speed analytical capabilities.
Looking for other analytics solutions? Check out our full list of [API Tutorials](/tutorials/tutorial_intro) for more step-by-step guides.
Our "free tier" isn't about delayed or incomplete data; it's about providing a **full, live, but scope-limited dataset** for you to master. We're giving you the tools, but it's up to you to use them in the way that makes the most sense for your project.
```mermaid theme={null}
graph TD;
subgraph "Step 1: Data Pipeline";
A["Run Python ETL Script"] --> B{"Fetches Pool & OHLCV Data"};
B --> C["DexPaprika API"];
C --> B;
B --> D["Local DuckDB File (uniswap_v3.db)"];
end
subgraph "Step 2 & 3: Analysis";
D --> E{"Query the Database"};
E --> F["Option A: Directly with SQL"];
E --> G["Option B: AI Assistant via MCP"];
end
```
**The goal:**
By the end of this guide, you will have a local `uniswap_v3.db` file containing all pools and their recent trading history from Uniswap v3 on Ethereum. You will be able to:
1. Run a robust, high-performance ETL script that pulls a complete dataset from the DexPaprika API.
2. Perform complex SQL queries on this data instantly, without rate limits.
3. Understand a professional workflow for acquiring and analyzing on-chain data.
**Why this is a foundational skill:**
* **Eliminates Rate Limiting:** Instead of thousands of small, repetitive API calls, you perform one efficient batch download.
* **Unlocks True Analytical Power:** Run complex joins, aggregations, and window functions that are impossible with a simple API.
* **Creates a Foundation:** The skills you learn here can be applied to any data source, preparing you for more advanced, real-time analysis.
Create a Python script to fetch complete Uniswap v3 pool and OHLCV data.
Populate your database and run complex SQL queries to find insights.
Connect your database to an AI assistant for natural language queries.
### FAQs
It’s an embedded analytics database--zero server setup, very fast columnar engine, perfect for local SQL over large datasets.
Depends on pools and history length; tens of millions of rows are feasible on a laptop with DuckDB’s compression.
Append new OHLCV daily or hourly depending on your use case; the pipeline is designed for incremental runs.
Yes--create separate tables per network/DEX and union them or annotate rows with `network`/`dex` columns.
***
## Step 1: Build your local data pipeline
First, let's create a Python script to act as our ETL (Extract, Transform, Load) pipeline. This script will fetch all pool data for **Uniswap v3 on Ethereum** and their recent trading history, then load it into a local DuckDB database file. It leverages two key endpoints: the [Top Pools on a DEX endpoint](/api-reference/pools/get-top-x-pools-on-a-networks-dex) to discover pools, and the [Pool OHLCV Data endpoint](/api-reference/pools/get-ohlcv-data-for-a-pool-pair) to fetch historical price data.
Create a new file named `build_uniswap_db.py`.
```python build_uniswap_db.py [expandable] theme={null}
import duckdb
import pandas as pd
from datetime import datetime, timedelta
import logging
import os
import asyncio
import aiohttp
from typing import List, Dict
# --- Configuration ---
API_BASE_URL = "https://api.dexpaprika.com"
NETWORK = "ethereum"
DEX_ID = "uniswap_v3"
HISTORY_DAYS = 14 # Default days of OHLCV data to fetch
DB_FILE = "dbs/uniswap_v3.db"
INTERVAL = "1h" # 1-hour intervals
OHLCV_API_LIMIT = 100 # Max records per API call
TOP_POOLS_LIMIT = 500 # Focus on top 500 pools by volume
CONCURRENT_REQUESTS = 3 # Number of concurrent API requests
BATCH_SIZE = 15 # Number of pools to process in each batch
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def fetch_with_retry(session: aiohttp.ClientSession, url: str, params: Dict = None, retries=5, backoff_factor=1.0) -> Dict:
"""Generic async fetch function with exponential backoff."""
for attempt in range(retries):
try:
async with session.get(url, params=params, timeout=30) as response:
response.raise_for_status()
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt == retries - 1:
logging.error(f"Final attempt failed for {url}: {e}")
raise
sleep_time = backoff_factor * (2 ** attempt)
logging.warning(f"Request to {url} failed: {e}. Retrying in {sleep_time:.2f}s...")
await asyncio.sleep(sleep_time)
return {}
async def get_top_dex_pools(session: aiohttp.ClientSession, network: str, dex_id: str) -> List[Dict]:
"""Fetches top pools for a given DEX, handling pagination asynchronously."""
logging.info(f"Fetching top {TOP_POOLS_LIMIT} pools for {dex_id} on {network}...")
all_pools = []
page = 1
while len(all_pools) < TOP_POOLS_LIMIT:
url = f"{API_BASE_URL}/networks/{network}/dexes/{dex_id}/pools"
params = {"page": page, "limit": 100, "order_by": "volume_usd", "sort": "desc"}
try:
data = await fetch_with_retry(session, url, params=params)
pools = data.get('pools', [])
if not pools:
break
all_pools.extend(pools)
logging.info(f"Fetched page {page}, got {len(pools)} pools. Total: {len(all_pools)}")
page += 1
if len(all_pools) >= TOP_POOLS_LIMIT:
all_pools = all_pools[:TOP_POOLS_LIMIT]
break
await asyncio.sleep(0.5) # Be respectful to the API
except Exception as e:
logging.error(f"Error fetching page {page} for {dex_id} pools: {e}")
break
logging.info(f"Finished fetching pools. Total found: {len(all_pools)}")
return all_pools
async def get_pool_ohlcv(session: aiohttp.ClientSession, pool_address: str, pool_created_at: str, semaphore: asyncio.Semaphore) -> List[Dict]:
"""
Fetches 1-hour OHLCV data for a pool using an intelligent date range and dynamic windowing.
"""
async with semaphore:
logging.info(f"Fetching OHLCV for pool {pool_address}...")
final_end_time = datetime.utcnow()
# Use the later of: pool creation date or the default history window
start_time = final_end_time - timedelta(days=HISTORY_DAYS)
if pool_created_at:
try:
pool_creation = datetime.strptime(pool_created_at, '%Y-%m-%dT%H:%M:%SZ')
if pool_creation > start_time:
start_time = pool_creation
except (ValueError, TypeError):
logging.warning(f"Could not parse creation date '{pool_created_at}', using default {HISTORY_DAYS} days.")
all_ohlcv = []
current_start_time = start_time
# Calculate how much time each API call can cover
interval_hours = 1 # Based on "1h" interval
time_delta_per_call = timedelta(hours=OHLCV_API_LIMIT * interval_hours)
while current_start_time < final_end_time:
batch_end_time = min(current_start_time + time_delta_per_call, final_end_time)
url = f"{API_BASE_URL}/networks/{NETWORK}/pools/{pool_address}/ohlcv"
params = {
"start": current_start_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"end": batch_end_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"interval": INTERVAL,
"limit": OHLCV_API_LIMIT
}
try:
batch_data = await fetch_with_retry(session, url, params=params)
if batch_data:
for record in batch_data:
record['network'] = NETWORK
record['pool_address'] = pool_address
avg_price = (record.get('open', 0) + record.get('close', 0)) / 2
record['volume_usd'] = record.get('volume', 0) * avg_price if avg_price > 0 else 0
all_ohlcv.extend(batch_data)
except Exception as e:
logging.warning(f"Could not fetch OHLCV batch for {pool_address}: {e}")
current_start_time = batch_end_time
await asyncio.sleep(0.75) # Small delay to be respectful
logging.info(f"Successfully fetched {len(all_ohlcv)} OHLCV records for {pool_address}")
return all_ohlcv
async def main():
"""Main ETL function to build the local DuckDB database."""
os.makedirs("dbs", exist_ok=True)
async with aiohttp.ClientSession() as session:
pools = await get_top_dex_pools(session, NETWORK, DEX_ID)
all_ohlcv_data = []
semaphore = asyncio.Semaphore(CONCURRENT_REQUESTS)
for i in range(0, len(pools), BATCH_SIZE):
batch = pools[i:i+BATCH_SIZE]
tasks = [get_pool_ohlcv(session, p.get('id'), p.get('created_at'), semaphore) for p in batch if p.get('id')]
batch_num = (i // BATCH_SIZE) + 1
total_batches = (len(pools) + BATCH_SIZE - 1) // BATCH_SIZE
logging.info(f"--- Processing batch {batch_num}/{total_batches} ---")
results = await asyncio.gather(*tasks)
for res in results:
all_ohlcv_data.extend(res)
if i + BATCH_SIZE < len(pools):
logging.info(f"--- Finished batch {batch_num}, sleeping for 10 seconds ---")
await asyncio.sleep(10)
logging.info("ETL process finished. Loading data into DuckDB.")
con = duckdb.connect(database=DB_FILE, read_only=False)
if pools:
for pool in pools:
tokens = pool.get('tokens', [])
pool['token0_symbol'] = tokens[0]['symbol'] if len(tokens) > 0 else None
pool['token1_symbol'] = tokens[1]['symbol'] if len(tokens) > 1 else None
pools_df = pd.DataFrame(pools)
pools_df = pools_df[['id', 'dex_name', 'volume_usd', 'created_at', 'token0_symbol', 'token1_symbol']]
pools_df = pools_df.rename(columns={'id': 'address', 'volume_usd': 'volume_24h_usd'})
con.execute("CREATE OR REPLACE TABLE pools AS SELECT * FROM pools_df")
logging.info(f"Loaded {len(pools_df)} records into 'pools' table.")
if all_ohlcv_data:
ohlcv_df = pd.DataFrame(all_ohlcv_data)
ohlcv_df['timestamp'] = pd.to_datetime(ohlcv_df['time_close'])
ohlcv_df = ohlcv_df[['timestamp', 'network', 'pool_address', 'open', 'high', 'low', 'close', 'volume_usd']]
con.execute("CREATE OR REPLACE TABLE pool_ohlcv AS SELECT * FROM ohlcv_df")
logging.info(f"Loaded {len(ohlcv_df)} records into 'pool_ohlcv' table.")
logging.info("Database build complete. Summary:")
print(con.execute("SHOW TABLES").fetchdf())
print("\nPools Sample:")
print(con.execute("SELECT * FROM pools LIMIT 5").fetchdf())
print("\nOHLCV Sample:")
print(con.execute("SELECT * FROM pool_ohlcv ORDER BY timestamp DESC LIMIT 5").fetchdf())
con.close()
if __name__ == "__main__":
# Ensure you have the required libraries:
# pip install requests pandas duckdb aiohttp
asyncio.run(main())
```
A simple, sequential script is great for learning, but real-world data fetching requires a more robust approach. Here is what we've used to make sure it runs reliably:
* **Asynchronous Operations:** By using `asyncio` and `aiohttp`, the script can make many API requests concurrently instead of one by one. This means shorter time for completion.
* **Dynamic Windowing:** The `get_pool_ohlcv` function calculates how much data to request per API call so that it gets all the data for each pool.
* **Concurrency Control & Throttling:** An `asyncio.Semaphore`, combined with carefully tuned `BATCH_SIZE` and `asyncio.sleep()` calls, makes sure we don't hit the rate limit.
* **Resiliency:** The `fetch_with_retry` function automatically retries failed requests with an exponential backoff delay, making the pipeline resilient to temporary network issues.
### **Required libraries**
Before running the script, make sure you have the necessary Python libraries installed.
```bash theme={null}
pip install requests pandas duckdb aiohttp
```
***
## Step 2: Run the pipeline and query with SQL
Now, execute the script from your terminal. It will fetch all Uniswap v3 pool data from Ethereum and their recent trading history, then create a `uniswap_v3.db` file in a new `dbs` directory. This may take several minutes, but it will be significantly faster than a purely sequential script.
```bash theme={null}
python build_uniswap_db.py
```
### **Querying your new database**
Once the script completes, you have a powerful local database at your fingertips. You can now use any SQL client that supports DuckDB, or Python itself, to perform instant, complex analysis. In step 3, we will connect the database to an AI assistant for natural language queries.
If you want to query the database with a Python script, create a new file named `query_duckdb.py` and paste the following code into it.
```python query_duckdb.py [expandable] theme={null}
import duckdb
import pandas as pd
import time
# Connect to the DuckDB database file
con = duckdb.connect(database='dbs/uniswap_v3.db', read_only=True)
print("=== DuckDB Uniswap v3 Analytics ===\n")
# --- Query 1: Database Summary ---
print("--- 1. Database Summary ---")
pool_count = con.execute("SELECT COUNT(*) FROM pools").fetchone()[0]
ohlcv_count = con.execute("SELECT COUNT(*) FROM pool_ohlcv").fetchone()[0]
print(f"Total Pools Loaded: {pool_count}")
print(f"Total OHLCV Records: {ohlcv_count:,}\n")
# --- Query 2: Top 10 Pools by 24h Volume ---
print("--- 2. Top 10 Pools by 24h Volume ---")
start_time = time.time()
top_pools_df = con.execute("""
SELECT
address,
token0_symbol,
token1_symbol,
volume_24h_usd
FROM pools
ORDER BY volume_24h_usd DESC
LIMIT 10
""").fetchdf()
print(top_pools_df)
print(f"Query executed in {time.time() - start_time:.4f} seconds\n")
# --- Query 3: Peak Trading Hours ---
print("--- 3. Peak Trading Hours (UTC) ---")
start_time = time.time()
hourly_volume_df = con.execute("""
SELECT
EXTRACT(hour FROM timestamp) AS hour_of_day,
SUM(volume_usd) AS total_volume_usd
FROM pool_ohlcv
WHERE volume_usd > 0 AND volume_usd < 1000000000 -- Defensive filter against outliers
GROUP BY hour_of_day
ORDER BY total_volume_usd DESC
""").fetchdf()
# Format the volume for better readability
hourly_volume_df['total_volume_usd'] = hourly_volume_df['total_volume_usd'].map('${:,.2f}'.format)
print(hourly_volume_df)
print(f"Query executed in {time.time() - start_time:.4f} seconds\n")
con.close()
```
Now, execute the script from your terminal:
```bash theme={null}
python query_duckdb.py
```
***
## Step 3: AI-powered analysis with an MCP server
While you can use any SQL client to query your database, the real power comes from connecting it to an AI assistant. By using a Model Context Protocol (MCP) server, you can enable your assistant to directly query the `uniswap_v3.db` file you created. This allows you to ask for insights in plain English instead of writing SQL.
For this, we will use `mcp-server-duckdb`, an open-source MCP server for DuckDB.
### **Install the DuckDB MCP server**
You can install the server easily using `npx`:
```bash theme={null}
npx -y @smithery/cli install mcp-server-duckdb --client claude
```
### **Configure your AI assistant**
Next, you need to tell your AI assistant how to run the server. Add the following to your `claude_desktop_config.json` file.
If you see a "Server disconnected" error after restarting your AI assistant, it means the application cannot find the `uvx` or `npx` command. This happens because the application doesn't share the same `PATH` environment variable as your terminal.
**To fix this, you must use the full, absolute path to the command.**
1. Find the absolute path by running `which uvx` or `which npx` in your terminal.
2. Copy the output (e.g., `/Users/yourname/.local/bin/uvx` or `/opt/homebrew/bin/npx`).
3. Use that full path as the `command` value in the JSON configuration below.
The example below uses `uvx`, which is recommended. Make sure to replace `` with the actual absolute path to your project directory.
```json theme={null}
{
"mcpServers": {
"duckdb-crypto": {
"command": "/Users//.local/bin/uvx",
"args": [
"mcp-server-duckdb",
"--db-path",
"/dbs/uniswap_v3.db",
"--readonly"
]
}
}
}
```
Now, when you start your AI assistant, it will have the tools to query your local Uniswap V3 database. You can ask it things like:
* *"Using the duckdb-crypto tool, find the 5 pools with the highest 24-hour volume."*
* *"What was the hourly volatility for the top pool yesterday?"*
***
## What you've built: From API calls to analytics powerhouse
By completing this tutorial, you have successfully transitioned from being a passive data consumer to an active data analyst. You've replaced the slow, restrictive pattern of making individual API calls with a fast, powerful, and scalable local analytics workflow.
**Key achievements:**
* **Built a professional ETL pipeline:** You have a reusable, high-performance Python script that can create a comprehensive local database from any supported DEX and network.
* **Unlocked high-speed SQL:** You can now perform complex analytical queries on a rich dataset in milliseconds, directly on your machine.
* **Mastered a foundational workflow:** This "local-first" data strategy is a cornerstone of professional data analysis. It enables deeper exploration, from high-level market trends down to individual wallet behaviors.
* **Created a Reusable Asset:** Your `uniswap_v3.db` file is a valuable, reusable asset for any future analysis, dashboarding, or AI integration project.
When your project grows and you need to explore other data solutions, check out our full list of [API Tutorials](/tutorials/tutorial_intro) for more advanced guides.
# Filter and screen liquidity pools
Source: https://docs.dexpaprika.com/tutorials/pool-filtering
Use the DexPaprika pool filter endpoint to find pools by volume, transaction count, and creation date. Build pool screeners, find high-activity pools, and discover recently launched tokens.
## What you'll build
A pool screener that finds liquidity pools matching specific criteria -- volume thresholds, transaction counts, and creation dates. This is useful for:
* Finding high-activity pools on any network
* Discovering newly created pools (early token launches)
* Building automated pool monitoring pipelines
* Filtering noise from low-activity pools
***
## The filter endpoint
```
GET /networks/{network}/pools/filter
```
This endpoint lets you combine multiple filters with AND logic. The response includes paginated results with total counts.
### Available parameters
| Parameter | Type | Description |
| ---------------- | ------- | ------------------------------------------------ |
| `volume_24h_min` | number | Minimum 24h volume in USD |
| `volume_24h_max` | number | Maximum 24h volume in USD |
| `txns_24h_min` | integer | Minimum transactions in last 24h |
| `created_after` | integer | UNIX timestamp -- pools created after this date |
| `created_before` | integer | UNIX timestamp -- pools created before this date |
| `sort_by` | string | `volume_24h` (default), `txns_24h`, `created_at` |
| `sort_dir` | string | `asc` or `desc` (default: `desc`) |
| `page` | integer | Page number, 1-indexed (default: 1) |
| `limit` | integer | Items per page, 1–100 (default: 50) |
The parameters `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, and `liquidity_usd_max` exist in the API spec but are not functional yet. Using them returns empty results.
***
## Example 1: High-volume pools on Ethereum
Find Ethereum pools with over \$500,000 in daily volume:
```bash bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/filter?volume_24h_min=500000&sort_by=volume_24h&sort_dir=desc&limit=5"
```
```python python theme={null}
import requests
response = requests.get("https://api.dexpaprika.com/networks/ethereum/pools/filter", params={
"volume_24h_min": 500000,
"sort_by": "volume_24h",
"sort_dir": "desc",
"limit": 5
})
data = response.json()
print(f"Total matching pools: {data['page_info']['total_items']}")
for pool in data["results"]:
print(f" {pool['dex_id']} | {pool['address'][:16]}... | Vol: ${pool['volume_usd_24h']:,.0f} | Txns: {pool['txns_24h']}")
```
```javascript javascript theme={null}
const response = await fetch(
"https://api.dexpaprika.com/networks/ethereum/pools/filter?" +
new URLSearchParams({
volume_24h_min: 500000,
sort_by: "volume_24h",
sort_dir: "desc",
limit: 5
})
);
const data = await response.json();
console.log(`Total matching pools: ${data.page_info.total_items}`);
data.results.forEach(pool => {
console.log(` ${pool.dex_id} | ${pool.address.slice(0, 16)}... | Vol: $${pool.volume_usd_24h.toLocaleString()} | Txns: ${pool.txns_24h}`);
});
```
### Response format
```json theme={null}
{
"results": [
{
"chain": "ethereum",
"address": "0xf6e72db5454dd049d0788e411b06cfaf16853042",
"dex_id": "makerdao",
"volume_usd_24h": 1657645861.93,
"liquidity_usd": 0,
"txns_24h": 4383,
"created_at": "2024-07-11T13:48:47Z"
}
],
"page_info": {
"limit": 5,
"page": 1,
"total_items": 720,
"total_pages": 144
}
}
```
The filter endpoint uses different field names than the pool listing endpoint (`/networks/{network}/pools`). Key differences: `address` instead of `id`, `volume_usd_24h` instead of `volume_usd`, `txns_24h` instead of `transactions`, and results are in a `results` array instead of `pools`.
***
## Example 2: Recently created pools with activity
Find pools created in the last 7 days that have at least 50 transactions:
```bash bash theme={null}
# Calculate UNIX timestamp for 7 days ago
SEVEN_DAYS_AGO=$(python3 -c "import time; print(int(time.time()) - 7*86400)")
curl "https://api.dexpaprika.com/networks/base/pools/filter?created_after=$SEVEN_DAYS_AGO&txns_24h_min=50&sort_by=created_at&sort_dir=desc&limit=10"
```
```python python theme={null}
import requests
import time
seven_days_ago = int(time.time()) - 7 * 86400
response = requests.get("https://api.dexpaprika.com/networks/base/pools/filter", params={
"created_after": seven_days_ago,
"txns_24h_min": 50,
"sort_by": "created_at",
"sort_dir": "desc",
"limit": 10
})
data = response.json()
print(f"New pools with 50+ txns in last 7 days: {data['page_info']['total_items']}")
for pool in data["results"]:
print(f" Created: {pool['created_at']} | DEX: {pool['dex_id']} | Txns: {pool['txns_24h']} | Vol: ${pool['volume_usd_24h']:,.0f}")
```
***
## Example 3: Paginating through all results
When the filter returns many results, paginate through them:
```python theme={null}
import requests
all_pools = []
page = 1
while True:
response = requests.get("https://api.dexpaprika.com/networks/solana/pools/filter", params={
"volume_24h_min": 10000,
"txns_24h_min": 20,
"sort_by": "volume_24h",
"sort_dir": "desc",
"page": page,
"limit": 100
})
data = response.json()
all_pools.extend(data["results"])
total_pages = data["page_info"]["total_pages"]
print(f"Page {page}/{total_pages} -- collected {len(all_pools)} pools so far")
if page >= total_pages:
break
page += 1
print(f"Total pools matching criteria: {len(all_pools)}")
```
***
## Example 4: Combining with pool details
The filter returns summary data. To get full pool details (token pair info, reserves, fees), make a follow-up request:
```python theme={null}
import requests
# Step 1: Find interesting pools
response = requests.get("https://api.dexpaprika.com/networks/ethereum/pools/filter", params={
"volume_24h_min": 100000,
"txns_24h_min": 500,
"limit": 5
})
pools = response.json()["results"]
# Step 2: Get full details for each pool
for pool in pools:
details = requests.get(
f"https://api.dexpaprika.com/networks/{pool['chain']}/pools/{pool['address']}"
).json()
tokens = details.get("tokens", [])
pair = "/".join(t["symbol"] for t in tokens) if tokens else "Unknown"
print(f"{pair} on {pool['dex_id']} -- Vol: ${pool['volume_usd_24h']:,.0f}")
```
***
## Tips
* **Start broad, then narrow:** Begin with just `volume_24h_min` to see how many pools match, then add more filters
* **Use `created_after` for new token discovery:** Combine with `txns_24h_min` to find new pools that actually have trading activity
* **Different networks, different thresholds:** A \$10k volume pool on Ethereum is tiny; on a smaller chain it might be significant. Adjust thresholds per network
* **Check `total_items` in `page_info`:** This tells you how many pools match your criteria before you paginate
***
## Next steps
More techniques for discovering new pools using the standard pool listing endpoint
Get full details for any pool including token pairs and reserves
Standard API workflows including filtering, pricing, and historical data
Full filter endpoint documentation with all parameters
### FAQs
The parameters `volume_7d_min`, `volume_30d_min`, `liquidity_usd_min`, and `liquidity_usd_max` are not yet functional. Stick to `volume_24h_min`, `volume_24h_max`, `txns_24h_min`, `created_after`, and `created_before`.
No. The filter endpoint works per network. Make separate requests for each network you want to check.
The filter can return up to `total_items` results (shown in `page_info`), but you must paginate through them 100 at a time.
# Scalable time-series analytics with InfluxDB
Source: https://docs.dexpaprika.com/tutorials/real-time-analytics-with-influxdb
Harness InfluxDB, a best-in-class time-series database, to build a powerful crypto analytics pipeline that scales from real-time monitoring to large historical datasets.
## Tutorial overview
Stream and analyze pool OHLCV in InfluxDB with hourly/minute intervals and live Grafana dashboards.
## From real-time monitoring to historical analysis
While InfluxDB is a champion of real-time data, its power extends far beyond live dashboards. It provides a highly optimized engine for storing and querying massive time-series datasets, making it a perfect middle-ground between the local analytics of DuckDB and the enterprise scale of ClickHouse.
Looking for other analytics solutions? Check out our full list of [API Tutorials](/tutorials/tutorial_intro) for more step-by-step guides.
This tutorial will guide you through building a production-grade ETL pipeline to populate InfluxDB with a substantial historical dataset, enabling both high-performance queries and real-time visualization.
```mermaid theme={null}
graph TD;
subgraph "Step 1: Infrastructure";
A["Setup InfluxDB & Grafana (Docker)"];
end
subgraph "Step 2: Data Ingestion";
B["Run Python ETL script"];
C["DexPaprika API"];
D["InfluxDB Bucket ('crypto-data')"];
B --"Fetches 14 days of 1h data for 500 pools"--> C;
B --"Writes time-series data"--> D;
end
subgraph "Step 3 & 4: Analysis & Visualization";
E["Option A: Programmatic queries (Python)"];
F["Option B: Live dashboards (Grafana)"];
D --> E;
D --> F;
end
A --> B;
```
**The goal:**
By the end of this guide, you will have a scalable analytics pipeline that can:
1. Ingest 1-hour OHLCV data for the top 500 Uniswap v3 pools over a 14-day period.
2. Run complex time-series analysis using Python and the Flux language.
3. Visualize the data in a live-updating Grafana dashboard.
Get InfluxDB and Grafana running in seconds with Docker.
Create a robust data pipeline for ingesting large time-series datasets.
Analyze your time-series data with InfluxDB's Python client.
Build a real-time dashboard to monitor crypto pools.
***
## Step 1: Setting Up InfluxDB and Grafana
We'll use Docker Compose to spin up both services. First, create a new directory named `INFLUXDB` in your project root. Inside that directory, create a file named `docker-compose.yml` with the following content.
```yml INFLUXDB/docker-compose.yml theme={null}
services:
influxdb:
image: influxdb:2.7
container_name: influxdb
ports:
- "8087:8086"
volumes:
- influxdb-data:/var/lib/influxdb2
environment:
- DOCKER_INFLUXDB_INIT_MODE=setup
- DOCKER_INFLUXDB_INIT_USERNAME=my-user
- DOCKER_INFLUXDB_INIT_PASSWORD=my-password
- DOCKER_INFLUXDB_INIT_ORG=my-org
- DOCKER_INFLUXDB_INIT_BUCKET=crypto-data
- DOCKER_INFLUXDB_INIT_ADMIN_TOKEN=my-super-secret-token
grafana:
image: grafana/grafana:latest
container_name: grafana
ports:
- "3000:3000"
volumes:
- grafana-data:/var/lib/grafana
volumes:
influxdb-data:
grafana-data:
```
Run the following command from the root of the project to start the containers:
```bash theme={null}
docker-compose -f INFLUXDB/docker-compose.yml up -d
```
Once running, you can access:
* **InfluxDB UI:** `http://localhost:8087`
* **Grafana UI:** `http://localhost:3000` (login with `admin`/`admin`)
Use the token `my-super-secret-token` to connect to InfluxDB.
We use port `8087` for InfluxDB to avoid potential conflicts with other services that might be using the default port `8086`.
***
## Step 2: Build the Python ETL Pipeline
Create a new file named `INFLUXDB/build_influxdb_db.py`. This script is built to be robust and efficient, capable of ingesting large volumes of time-series data from the DexPaprika API into your InfluxDB instance. It leverages two key endpoints: the [Top Pools on a DEX endpoint](/api-reference/pools/get-top-x-pools-on-a-networks-dex) to discover pools, and the [Pool OHLCV Data endpoint](/api-reference/pools/get-ohlcv-data-for-a-pool-pair) to fetch historical price data.
```python INFLUXDB/build_influxdb_db.py [expandable] theme={null}
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
import requests
from datetime import datetime, timedelta, timezone
import time
import logging
import asyncio
import aiohttp
from typing import List, Dict
import math
# --- Configuration ---
API_BASE_URL = "https://api.dexpaprika.com"
NETWORK = "ethereum"
DEX_ID = "uniswap_v3"
HISTORY_DAYS = 14 # Fetch 14 days of OHLCV data
TOP_POOLS_LIMIT = 500 # Focus on top 500 pools by volume
BATCH_SIZE = 15 # Process pools in smaller batches
CONCURRENT_REQUESTS = 3 # Concurrent requests for API calls
OHLCV_API_LIMIT = 100 # API limit for OHLCV requests
INTERVAL = "1h" # 1-hour intervals
# InfluxDB Configuration
INFLUX_URL = "http://localhost:8087"
INFLUX_TOKEN = "my-super-secret-token"
INFLUX_ORG = "my-org"
INFLUX_BUCKET = "crypto-data"
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def fetch_with_retry(session: aiohttp.ClientSession, url: str, params: Dict = None, retries=5, backoff_factor=1.0):
"""Generic async fetch function with exponential backoff."""
for attempt in range(retries):
try:
async with session.get(url, params=params, timeout=30) as response:
response.raise_for_status()
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt == retries - 1:
logging.error(f"Final attempt failed for {url}: {e}")
raise
sleep_time = backoff_factor * (2 ** attempt)
logging.warning(f"Request to {url} failed: {e}. Retrying in {sleep_time:.2f}s...")
await asyncio.sleep(sleep_time)
return {}
class InfluxDBETL:
def __init__(self):
self.client = influxdb_client.InfluxDBClient(url=INFLUX_URL, token=INFLUX_TOKEN, org=INFLUX_ORG)
self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
self.api_semaphore = asyncio.Semaphore(CONCURRENT_REQUESTS)
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
"""Checks if the bucket exists and creates it if not."""
logging.info(f"Ensuring bucket '{INFLUX_BUCKET}' exists...")
buckets_api = self.client.buckets_api()
bucket = buckets_api.find_bucket_by_name(INFLUX_BUCKET)
if not bucket:
logging.warning(f"Bucket '{INFLUX_BUCKET}' not found. Creating it...")
buckets_api.create_bucket(bucket_name=INFLUX_BUCKET, org=INFLUX_ORG)
logging.info(f"Bucket '{INFLUX_BUCKET}' created successfully.")
else:
logging.info(f"Bucket '{INFLUX_BUCKET}' already exists.")
def clear_bucket_data(self):
"""Deletes all data from the 'ohlcv' measurement in the bucket."""
logging.info(f"Clearing existing data from measurement 'ohlcv' in bucket '{INFLUX_BUCKET}'...")
try:
delete_api = self.client.delete_api()
start = "1970-01-01T00:00:00Z"
stop = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
delete_api.delete(start, stop, '_measurement="ohlcv"', bucket=INFLUX_BUCKET, org=INFLUX_ORG)
logging.info("Existing data cleared successfully.")
except Exception as e:
logging.error(f"Could not clear data from bucket: {e}")
async def fetch_top_pools(self) -> List[Dict]:
"""Fetch top pools by volume from the specified DEX, handling pagination."""
logging.info(f"Fetching top {TOP_POOLS_LIMIT} pools for {DEX_ID} on {NETWORK}...")
all_pools = []
page = 0
async with aiohttp.ClientSession() as session:
while len(all_pools) < TOP_POOLS_LIMIT:
url = f"{API_BASE_URL}/networks/{NETWORK}/dexes/{DEX_ID}/pools"
params = {"page": page, "limit": 100, "order_by": "volume_usd", "sort": "desc"}
try:
data = await fetch_with_retry(session, url, params=params)
pools = data.get('pools', [])
if not pools:
break
all_pools.extend(pools)
logging.info(f"Fetched page {page}, got {len(pools)} pools. Total: {len(all_pools)}")
page += 1
if len(all_pools) >= TOP_POOLS_LIMIT:
all_pools = all_pools[:TOP_POOLS_LIMIT]
break
await asyncio.sleep(0.5) # Be respectful to the API
except Exception as e:
logging.error(f"Error fetching page {page}: {e}")
break
logging.info(f"Finished fetching pools. Total: {len(all_pools)}")
return all_pools
async def fetch_pool_ohlcv_paginated(self, session: aiohttp.ClientSession, pool_address: str) -> List[Dict]:
"""Fetch complete OHLCV data for a pool using intelligent, dynamic windowing."""
async with self.api_semaphore:
final_end_time = datetime.now(timezone.utc)
current_start_time = final_end_time - timedelta(days=HISTORY_DAYS)
all_ohlcv = []
try:
if 'h' in INTERVAL:
interval_value = int(INTERVAL.replace('h', ''))
time_delta_per_call = timedelta(hours=OHLCV_API_LIMIT * interval_value)
elif 'm' in INTERVAL:
interval_value = int(INTERVAL.replace('m', ''))
time_delta_per_call = timedelta(minutes=OHLCV_API_LIMIT * interval_value)
else:
raise ValueError(f"Unsupported interval format: {INTERVAL}")
except ValueError as e:
logging.error(f"Invalid INTERVAL format: {e}. Defaulting to 1 hour.")
time_delta_per_call = timedelta(hours=OHLCV_API_LIMIT * 1)
total_expected_calls = math.ceil((final_end_time - current_start_time) / time_delta_per_call) if time_delta_per_call.total_seconds() > 0 else 0
call_count = 0
while current_start_time < final_end_time:
call_count += 1
batch_end_time = min(current_start_time + time_delta_per_call, final_end_time)
logging.info(f" [Pool {pool_address}] Fetching window {call_count}/{total_expected_calls}: {current_start_time.date()} to {batch_end_time.date()}")
url = f"{API_BASE_URL}/networks/{NETWORK}/pools/{pool_address}/ohlcv"
params = {
"start": current_start_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"end": batch_end_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"interval": INTERVAL,
"limit": OHLCV_API_LIMIT
}
try:
batch_data = await fetch_with_retry(session, url, params=params)
if batch_data:
for record in batch_data:
record['network'] = NETWORK
record['pool_address'] = pool_address
all_ohlcv.extend(batch_data)
except Exception as e:
logging.warning(f"Could not fetch OHLCV batch for {pool_address}: {e}")
current_start_time = batch_end_time
await asyncio.sleep(0.75) # Crucial delay to prevent rate-limiting
logging.info(f"Pool {pool_address}: collected {len(all_ohlcv)} OHLCV records.")
return all_ohlcv
async def fetch_pool_ohlcv_batch(self, pool_addresses: List[str]) -> List[Dict]:
"""Fetch OHLCV data for multiple pools concurrently."""
logging.info(f"Fetching {INTERVAL} OHLCV for {len(pool_addresses)} pools...")
all_ohlcv = []
async with aiohttp.ClientSession() as session:
tasks = [self.fetch_pool_ohlcv_paginated(session, addr) for addr in pool_addresses]
results = await asyncio.gather(*tasks, return_exceptions=True)
for i, result in enumerate(results):
if isinstance(result, list):
all_ohlcv.extend(result)
elif isinstance(result, Exception):
logging.warning(f"OHLCV fetch failed for pool {pool_addresses[i]}: {result}")
return all_ohlcv
def load_ohlcv_data(self, ohlcv_data: List[Dict], pools_map: Dict):
"""Load OHLCV data into InfluxDB."""
if not ohlcv_data:
logging.warning("No OHLCV data to load.")
return
points = []
for record in ohlcv_data:
pool_id = record.get('pool_address')
pair = pools_map.get(pool_id, "Unknown/Unknown")
point = (
influxdb_client.Point("ohlcv")
.tag("pool_id", pool_id)
.tag("pair", pair)
.field("open", float(record['open']))
.field("high", float(record['high']))
.field("low", float(record['low']))
.field("close", float(record['close']))
.field("volume", float(record.get('volume', 0)))
.time(record['time_close'])
)
points.append(point)
if points:
self.write_api.write(bucket=INFLUX_BUCKET, org=INFLUX_ORG, record=points)
logging.info(f"Wrote {len(points)} data points to InfluxDB.")
async def run_etl(self):
"""Run the complete ETL process."""
self.clear_bucket_data()
logging.info(f"Starting InfluxDB ETL process for top {TOP_POOLS_LIMIT} pools...")
pools = await self.fetch_top_pools()
if pools:
pools_map = {
pool['id']: f"{pool['tokens'][0]['symbol']}/{pool['tokens'][1]['symbol']}"
for pool in pools if len(pool.get('tokens', [])) >= 2
}
pool_addresses = [pool['id'] for pool in pools if pool.get('id')]
for i in range(0, len(pool_addresses), BATCH_SIZE):
batch_addresses = pool_addresses[i:i + BATCH_SIZE]
batch_num = (i // BATCH_SIZE) + 1
total_batches = (len(pool_addresses) + BATCH_SIZE - 1) // BATCH_SIZE
logging.info(f"Processing OHLCV batch {batch_num}/{total_batches} ({len(batch_addresses)} pools)")
ohlcv_data = await self.fetch_pool_ohlcv_batch(batch_addresses)
self.load_ohlcv_data(ohlcv_data, pools_map)
if i + BATCH_SIZE < len(pool_addresses):
logging.info(f"--- Finished batch {batch_num}, sleeping for 10 seconds ---")
await asyncio.sleep(10)
logging.info("ETL process completed!")
async def main():
etl = InfluxDBETL()
await etl.run_etl()
if __name__ == "__main__":
# pip install influxdb-client aiohttp requests pandas
asyncio.run(main())
```
This script is built for performance and reliability, using several best practices common in data pipelines:
* **Asynchronous operations:** By using `asyncio` and `aiohttp`, the script can make many API requests concurrently instead of one by one.
* **Dynamic windowing:** The `fetch_pool_ohlcv_paginated` function calculates how much data to request per API call to ensure complete history is fetched efficiently.
* **Concurrency control & throttling:** An `asyncio.Semaphore`, combined with carefully tuned `BATCH_SIZE` and `asyncio.sleep()` calls, prevents API rate-limiting.
* **Resiliency:** The `fetch_with_retry` function automatically retries failed requests with an exponential backoff delay.
* **Data Integrity:** The script automatically clears old data from the bucket before each run to ensure a clean, consistent dataset.
### **Setup Python Environment**
Before running the ETL script, it's a critical best practice to create an isolated Python environment to manage dependencies.
1. **Create a virtual environment:**
Open your terminal in the project root and run:
```bash theme={null}
python3 -m venv venv
```
2. **Activate the environment:**
* On macOS and Linux:
```bash theme={null}
source venv/bin/activate
```
* On Windows:
```bash theme={null}
.\venv\Scripts\activate
```
Your terminal prompt should now be prefixed with `(venv)`, indicating that the virtual environment is active.
3. **Install required libraries:**
Now, install the necessary Python packages inside the activated environment:
```bash theme={null}
pip install influxdb-client aiohttp requests pandas
```
Run the script to start streaming data into your InfluxDB instance. This may take several minutes.
```bash theme={null}
python INFLUXDB/build_influxdb_db.py
```
***
## Step 3: Programmatic Analysis with Python
While the InfluxDB UI is great for exploration, the real power comes from programmatic access. The `influxdb-client` library for Python allows you to run complex Flux queries and integrate the data into other tools or scripts.
We've created a `query_influxdb.py` script to demonstrate how to connect to your database and perform analysis on the hourly data.
```python INFLUXDB/query_influxdb.py [expandable] theme={null}
import influxdb_client
import pandas as pd
# --- InfluxDB Configuration ---
INFLUX_URL = "http://localhost:8087"
INFLUX_TOKEN = "my-super-secret-token"
INFLUX_ORG = "my-org"
INFLUX_BUCKET = "crypto-data"
def run_flux_query(client: influxdb_client.InfluxDBClient, query: str):
"""Helper function to execute a Flux query and return a pandas DataFrame."""
try:
query_api = client.query_api()
result = query_api.query_data_frame(query, org=INFLUX_ORG)
if isinstance(result, list): # Handle multiple dataframes in result
return pd.concat(result, ignore_index=True) if result else pd.DataFrame()
return result
except Exception as e:
print(f"Error running query: {e}")
return pd.DataFrame()
def main():
"""Connects to InfluxDB and runs sample analytics queries."""
client = influxdb_client.InfluxDBClient(url=INFLUX_URL, token=INFLUX_TOKEN, org=INFLUX_ORG)
print("=== InfluxDB Python Analytics Demo ===\n")
# --- Query 1: Find available trading pairs ---
print("--- 1. Finding available trading pairs ---")
list_pairs_query = f'''
import "influxdata/influxdb/schema"
schema.tagValues(
bucket: "{INFLUX_BUCKET}",
tag: "pair",
start: -14d
)
'''
pairs_df = run_flux_query(client, list_pairs_query)
if not pairs_df.empty:
available_pairs = pairs_df['_value'].tolist()
print(f"Found {len(available_pairs)} pairs. Examples: {available_pairs[:5]}")
# Use the first available pair for subsequent queries
target_pair = available_pairs[0]
else:
print("No pairs found. Please run the ingestion script first.")
print("Using 'WETH/USDC' as a placeholder for query examples.")
target_pair = "WETH/USDC" # Fallback for demo
print(f"\n--- Using pair '{target_pair}' for next queries ---\n")
# --- Query 2: Get raw data for the target pool ---
print(f"--- 2. Raw OHLCV data for {target_pair} ---")
raw_data_query = f'''
from(bucket: "{INFLUX_BUCKET}")
|> range(start: -3d) // Limit to last 3 days for brevity
|> filter(fn: (r) => r._measurement == "ohlcv")
|> filter(fn: (r) => r.pair == "{target_pair}")
|> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")
|> sort(columns: ["_time"], desc: true)
|> limit(n: 10)
'''
raw_df = run_flux_query(client, raw_data_query)
print("Last 10 records:")
if not raw_df.empty and all(c in raw_df.columns for c in ['_time', 'open', 'high', 'low', 'close', 'volume']):
print(raw_df[['_time', 'open', 'high', 'low', 'close', 'volume']])
else:
print("Could not retrieve raw data. Please check if the ingestion was successful.")
print("\n")
# --- Query 3: Calculate 12-hour moving average ---
print(f"--- 3. 12-Hour moving average for {target_pair} close price ---")
moving_avg_query = f'''
from(bucket: "{INFLUX_BUCKET}")
|> range(start: -14d)
|> filter(fn: (r) => r._measurement == "ohlcv" and r._field == "close" and r.pair == "{target_pair}")
|> timedMovingAverage(every: 1h, period: 12h)
|> sort(columns: ["_time"], desc: true)
|> limit(n: 10)
'''
ma_df = run_flux_query(client, moving_avg_query)
print("Last 10 moving average values:")
if not ma_df.empty and all(c in ma_df.columns for c in ['_time', '_value']):
print(ma_df[['_time', '_value']])
else:
print("Could not retrieve moving average data.")
if __name__ == "__main__":
# Ensure you have the required libraries:
# pip install influxdb-client pandas
main()
```
Run the script to see how you can query your data with Python:
```bash theme={null}
python INFLUXDB/query_influxdb.py
```
***
## Step 4: Visualizing Data in Grafana
1. Open Grafana at `http://localhost:3000`.
2. Go to **Connections** > **Add new connection** > **InfluxDB**.
3. Configure the connection:
* **Name**: InfluxDB\_Crypto
* **Query Language**: Flux
* **URL**: `http://influxdb:8086` (use the Docker service name)
* Under **Auth**, toggle **Basic auth** off.
* In the **Custom HTTP Headers** section, add a header:
* **Header**: `Authorization`
* **Value**: `Token my-super-secret-token`
* Enter your InfluxDB **Organization** (`my-org`) and default **Bucket** (`crypto-data`).
4. Click **Save & Test**. You should see a "Bucket found" confirmation.
5. Now, let's create a dashboard. In the left-hand menu, click the **+** icon and select **Dashboard**.
6. Click on the **Add new panel** button.
7. In the new panel view, ensure your `InfluxDB_Crypto` data source is selected at the top.
8. Below the graph, you'll see a query editor. You can switch to the **Script editor** by clicking the pencil icon on the right.
9. Paste the following query into the editor. This query will plot the raw closing price for the `AAVE/USDC` trading pair.
```flux theme={null}
from(bucket: "crypto-data")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r._measurement == "ohlcv" and r._field == "close" and r.pair == "AAVE/USDC")
|> sort(columns: ["_time"], desc: false)
```
**Troubleshooting Tip:** If you initially see "No data," there are two common reasons:
1. **Time Range:** Ensure the time picker at the top right is set to "Last 7 days" or wider, not a shorter period like "Last 6 hours."
2. **Trading Pair:** The default `WETH/USDC` pair used in the original tutorial may not have been in the top 500 pools fetched by the script. The query above uses `AAVE/USDC`, which is more likely to be present. You can find other available pairs by running the `query_influxdb.py` script.
10. At the top right of the dashboard page, set the time range to **Last 7 days** to ensure you see all the historical data you ingested.
11. You should now see the data appear in the panel. You can give the panel a title (e.g., "AAVE/USDC Close Price") in the settings on the right.
12. Click **Apply** to save the panel to your dashboard. You can now add more panels for other queries.
***
## What You've Built
You now have a powerful, scalable analytics pipeline for time-series crypto data. You've combined a production-grade Python ETL script with the industry-standard tools for time-series data storage (InfluxDB) and visualization (Grafana).
**Key achievements:**
* **Built a production-ready ETL pipeline:** You have a reusable, high-performance Python script that can populate a time-series database from any supported DEX.
* **Unlocked programmatic time-series analysis:** You can now perform complex analytical queries on large time-series datasets using Python and Flux.
* **Mastered a scalable analytics workflow:** This pipeline provides a solid foundation for building live dashboards, conducting in-depth market research, and developing sophisticated monitoring or trading algorithms.
* **Enabled live data visualization:** You've connected your database to Grafana, the leading open-source tool for observability and data visualization.
### FAQs
InfluxDB excels at time-series ingestion and dashboards; it’s ideal for hourly/minute data with Grafana visualization.
Keep recent weeks/months for dashboards and archive older data elsewhere; adjust by bucket retention.
`1h` is a sensible default; lower to `15m/5m` for more granularity if needed.
Schedule the ETL to append new windows, and set Grafana panels to auto‑refresh.
# Get token price history and OHLCV data
Source: https://docs.dexpaprika.com/tutorials/retrieve-historical-data
Get historical crypto price data (OHLCV) for any token across 33 blockchains. Perfect for building charts, backtesting strategies, and price analysis.
## Tutorial overview
Pull historical OHLCV from a pool using `start`, `limit`, and `interval`, with tips for smoothing and inverted ratios.
Having trouble with the API? We're here to help - [drop us a line](mailto:support@coinpaprika.com) and we'll get you sorted.
## Why you need historical price data?
Building a crypto app? You'll likely need price charts, volatility analysis, or backtesting data. That's where OHLCV (Open, High, Low, Close, Volume) data comes in - it's the backbone of any serious crypto application.
**Common use cases:**
* **Price charts** in trading apps
* **Backtesting** trading strategies
* **Volatility analysis** for risk management
* **Historical performance** dashboards
* **Market research** and analytics
**Quick Start**: If you know your token already, jump to [Step 2](#step-2-get-price-history-data) to grab the data immediately.
***
## Step 1: Find your token's trading pool
Here's the thing - historical data comes from actual trading pools, not tokens directly. This makes sense because prices happen where people trade.
### Quick search (recommended)
The fastest way to find what you need using the [Search API](/api-reference/search/search-for-tokens-pools-and-dexes):
```bash theme={null}
curl "https://api.dexpaprika.com/search?query=USDC" | jq
```
**Pro tip**: Search returns tokens, pools, and exchanges. Look for pools with high volume - they'll have the most reliable price data.
### If you have the token address
Skip the search and go straight to pools using the [Token Pools API](/api-reference/tokens/get-top-x-pools-for-a-token):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/tokens/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48/pools" | jq
```
Always pick pools with decent volume (>\$10k daily). Low-volume pools can have weird price spikes that don't reflect real market conditions.
***
## Step 2: Get price history data
Now for the good stuff. Here's how to pull historical OHLCV data using the [Pool OHLCV API](/api-reference/pools/get-ohlcv-data-for-a-pool-pair):
```bash theme={null}
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&limit=30&interval=24h&inversed=true" | jq
```
*(Using USDC/ETH pool on Ethereum as example in this tutorial)*
### What these parameters do:
| Parameter | What It Does | Example |
| ---------- | ------------------------------ | ------------------------------ |
| `start` | When to start collecting data | `2025-01-01` or Unix timestamp |
| `limit` | How many data points (max 366) | `30` for 30 days |
| `interval` | Time between each point | `24h`, `1h`, `5m`, etc. |
| `end` | When to stop (optional) | `2025-01-31` |
| `inversed` | Flip the price ratio | `true` for ETH/USDC → USDC/ETH |
### What you get back:
```json theme={null}
[
{
"time_open": "2025-01-30T00:00:00Z",
"time_close": "2025-01-31T00:00:00Z",
"open": 3115.1614508315265,
"high": 3277.717757396331,
"low": 3097.803416632386,
"close": 3250.184016286268,
"volume": 226403988
}
]
```
Each data point gives you everything you need for candlestick charts or analysis.
***
## Time intervals that actually matter
Choose based on what you're building:
**For Trading Apps:**
* `1m`, `5m` - Real-time trading
* `1h`, `4h` - Swing trading
* `24h` - Position trading
**For Analytics Dashboards:**
* `24h` - Daily summaries
* Use daily data and aggregate for weekly/monthly views
**For Research:**
* `24h` with longer date ranges (up to 1 year)
***
## Production tips that'll save you time
### Cache aggressively
Historical data doesn't change - cache it locally:
```bash theme={null}
# Check when pool was created to avoid requesting non-existent data
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" | jq '.created_at'
```
### Handle data gaps
Some pools have quiet periods. Here's how to deal with gaps:
```bash theme={null}
# Filter out low-volume periods that might have unreliable prices
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&limit=30&inversed=true" | jq '.[] | select(.volume > 1000)'
```
### Multi-pool strategy
For major tokens, cross-reference data from multiple pools:
```bash theme={null}
# Get all USDC pools to compare price consistency
curl "https://api.dexpaprika.com/networks/ethereum/tokens/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48/pools?limit=5" | jq '.pools[] | .id'
```
### Rate limiting
Don't hammer the API. We suggest you to batch your requests and cache results:
```javascript theme={null}
// Example: Batch multiple token histories
const tokens = ['USDC', 'WETH', 'USDT'];
const historyPromises = tokens.map(token =>
fetch(`/api/history/${token}`).then(r => r.json())
);
const allHistories = await Promise.all(historyPromises);
```
***
## Troubleshooting common issues
### "Empty response"
Pool might not have data for your date range:
```bash theme={null}
# Check pool age first
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640" | jq '.created_at'
```
### "Weird price spikes"
You hit a low-liquidity period. Switch to shorter intervals or higher-volume pools:
```bash theme={null}
# Use 6h intervals to smooth out anomalies
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&interval=6h&limit=50&inversed=true"
```
### "Upside-down prices"
You need the inverted ratio:
```bash theme={null}
# Flip from TOKEN/ETH to ETH/TOKEN
curl "https://api.dexpaprika.com/networks/ethereum/pools/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640/ohlcv?start=2025-01-01&inversed=true&limit=10"
```
***
## What's next?
Get liquidity, fees, and other pool metrics.
Combine historical data with live prices.
### FAQs
First check the pool’s `created_at`; set `start` to not precede the creation time.
For charts: `1h`/`24h`. For anomaly smoothing: `6h`/`12h`. For near real‑time: `1m`/`5m`.
No trades occurred in that interval; aggregate longer or switch pools with higher activity.
Pass `inversed=true` to flip from token0/token1 to token1/token0.
## Need help?
Ask questions and see what others are building.
Hit a wall? We'll help you debug it.
# Crypto analytics with ClickHouse
Source: https://docs.dexpaprika.com/tutorials/scaling-with-clickhouse
Take your crypto analytics to the next level with ClickHouse. This guide shows you how to build a production-grade data pipeline for massive datasets and lightning-fast queries.
## Tutorial overview
Scale from local to production by ingesting high‑frequency pool OHLCV into ClickHouse for sub‑second analytics.
## From local to production scale
When your analytics needs grow beyond a single machine and you require a database designed for production scale, it's time to consider ClickHouse. ClickHouse is built for handling billions of rows with sub-second query times, making it perfect for production analytics, real-time dashboards, and enterprise-grade data analysis.
Looking for other analytics solutions? Check out our full list of [API Tutorials](/tutorials/tutorial_intro) for more step-by-step guides.
**Why ClickHouse for crypto analytics?**
* **Massive scale:** Built to handle billions of rows and petabytes of data, far beyond the scope of local, in-process databases.
* **Lightning speed:** Optimized columnar storage delivers queries that are 10-100x faster than traditional row-based systems.
* **Real-time ingestion:** Built for continuous data streaming and updates.
* **Production ready:** Used by companies like Uber, Cloudflare, and Spotify for analytics at scale.
```mermaid theme={null}
graph TD;
subgraph "Step 1: Infrastructure";
A["Setup ClickHouse Server"];
end
subgraph "Step 2: Data Ingestion";
B["Run Python ETL script"];
C["DexPaprika API"];
D["ClickHouse database ('crypto_analytics')"];
B --"Fetches pool & OHLCV data"--> C;
B --"Loads millions of rows"--> D;
end
subgraph "Step 3 & 4: Analysis";
E["Option A: Direct SQL queries"];
F["Option B: AI assistant via MCP"];
D --> E;
D --> F;
end
A --> B;
```
**The goal:**
By the end of this guide, you will have a production-grade ClickHouse setup that can:
1. Ingest 15-minute OHLCV data for the top 250 Uniswap v3 pools (7 days of history)
2. Handle real-time data updates via streaming
3. Run complex analytical queries in milliseconds
4. Enable AI-powered analysis through MCP server integration
Install and configure ClickHouse for crypto analytics.
Create a robust data pipeline for high-frequency data ingestion.
Run complex analytics on 15-minute interval data.
Enable AI-powered analysis through MCP server integration.
***
## Step 1: Setting up ClickHouse
### **Option A: Local installation (recommended for learning)**
Install ClickHouse locally for development and testing:
```bash theme={null}
# macOS
brew install clickhouse
```
**macOS specifics: Cask installation**
The `brew install clickhouse` command now installs a Cask, not a standard formula. This provides a single `clickhouse` binary that acts as a multi-tool for both the server and client. Commands that refer to `clickhouse-server` or `brew services` will not work.
Use the following commands instead:
```bash theme={null}
# To start the server on macOS (runs in the foreground):
clickhouse server
# To connect with the client in a new terminal:
clickhouse client
```
```bash theme={null}
# Ubuntu/Debian
sudo apt-get install -y apt-transport-https ca-certificates dirmngr
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 8919F6BD2B48D754
echo "deb https://packages.clickhouse.com/deb stable main" | sudo tee /etc/apt/sources.list.d/clickhouse.list
sudo apt-get update
sudo apt-get install -y clickhouse-server clickhouse-client
# Start the server
sudo systemctl start clickhouse-server
```
### **Option B: ClickHouse Cloud (recommended for production)**
For production workloads, use [ClickHouse Cloud](https://clickhouse.com/cloud):
1. Sign up for a free trial at clickhouse.com/cloud
2. Create a new service
3. Note your connection details (host, port, username, password)
**Moving forward:**
The rest of this tutorial will assume you are using a **local ClickHouse installation (Option A)**. The Python scripts are configured for this by default. If you choose to use ClickHouse Cloud, remember to update the `CLICKHOUSE_HOST`, `CLICKHOUSE_PORT`, `CLICKHOUSE_USER`, and `CLICKHOUSE_PASSWORD` variables in the scripts accordingly.
### **Test your connection**
```bash theme={null}
# Local installation (macOS)
clickhouse client
# Local installation (Linux)
clickhouse-client
# ClickHouse Cloud
clickhouse-client --host your-host.clickhouse.cloud --port 9440 --user default --password your-password --secure
```
***
## Step 2: Build the production ETL pipeline
Create a new file named `build_clickhouse_db.py`. This script efficiently handles high-frequency data from the top 500 pools, incorporating robust error handling and API management strategies. It leverages two key endpoints: the [Top Pools on a DEX endpoint](/api-reference/pools/get-top-x-pools-on-a-networks-dex) to discover pools, and the [Pool OHLCV Data endpoint](/api-reference/pools/get-ohlcv-data-for-a-pool-pair) to fetch historical price data.
```python build_clickhouse_db.py [expandable] theme={null}
import requests
import pandas as pd
import clickhouse_connect
from datetime import datetime, timedelta
import logging
import time
import asyncio
import aiohttp
from typing import List, Dict
import json
import math
# --- Configuration ---
API_BASE_URL = "https://api.dexpaprika.com"
NETWORK = "ethereum"
DEX_ID = "uniswap_v3"
HISTORY_DAYS = 7 # Fetch 7 days of OHLCV data
TOP_POOLS_LIMIT = 250 # Focus on top 250 pools by volume
BATCH_SIZE = 15 # Process pools in smaller batches
CONCURRENT_REQUESTS = 4 # Concurrent requests for API calls
OHLCV_API_LIMIT = 100 # API limit for OHLCV requests
INTERVAL = "15m" # 15-minute intervals
# ClickHouse Configuration
CLICKHOUSE_HOST = "localhost" # or your ClickHouse Cloud host
CLICKHOUSE_PORT = 8123
CLICKHOUSE_USER = "default"
CLICKHOUSE_PASSWORD = "" # Set if using ClickHouse Cloud
CLICKHOUSE_DATABASE = "crypto_analytics"
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def fetch_with_retry(session, url, params=None, retries=5, backoff_factor=0.5):
"""Generic fetch function with exponential backoff."""
for attempt in range(retries):
try:
async with session.get(url, params=params, timeout=30) as response:
response.raise_for_status()
return await response.json()
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
if attempt == retries - 1:
logging.error(f"Final attempt failed for {url}: {e}")
raise
sleep_time = backoff_factor * (2 ** attempt)
logging.warning(f"Request to {url} failed: {e}. Retrying in {sleep_time:.2f}s...")
await asyncio.sleep(sleep_time)
class ClickHouseETL:
def __init__(self):
# Connect without a database first to ensure it exists
with clickhouse_connect.get_client(
host=CLICKHOUSE_HOST,
port=CLICKHOUSE_PORT,
username=CLICKHOUSE_USER,
password=CLICKHOUSE_PASSWORD
) as client:
client.command(f"CREATE DATABASE IF NOT EXISTS {CLICKHOUSE_DATABASE}")
# Now, connect to the specific database for table operations
self.client = clickhouse_connect.get_client(
host=CLICKHOUSE_HOST,
port=CLICKHOUSE_PORT,
username=CLICKHOUSE_USER,
password=CLICKHOUSE_PASSWORD,
database=CLICKHOUSE_DATABASE
)
self.api_semaphore = asyncio.Semaphore(CONCURRENT_REQUESTS)
self.setup_database()
def setup_database(self):
"""Create tables optimized for 15-minute interval data."""
logging.info("Setting up ClickHouse tables...")
# Create pools table with ReplacingMergeTree to handle duplicates
pools_schema = """
CREATE TABLE IF NOT EXISTS pools (
address String,
dex_name String,
volume_24h_usd Float64,
created_at DateTime,
token0_symbol Nullable(String),
token1_symbol Nullable(String),
pair Nullable(String) MATERIALIZED if(isNotNull(token0_symbol) AND isNotNull(token1_symbol), concat(token0_symbol, '-', token1_symbol), NULL),
created_date Date MATERIALIZED toDate(created_at),
volume_rank UInt32
) ENGINE = ReplacingMergeTree(created_at)
ORDER BY (address, volume_24h_usd, created_at)
PARTITION BY toYYYYMM(created_date)
"""
self.client.command(pools_schema)
# Create OHLCV table optimized for time-series analytics
ohlcv_schema = """
CREATE TABLE IF NOT EXISTS pool_ohlcv (
timestamp DateTime,
network String,
pool_address String,
open Float64,
high Float64,
low Float64,
close Float64,
volume_usd Float64,
date Date MATERIALIZED toDate(timestamp),
hour UInt8 MATERIALIZED toHour(timestamp),
minute UInt8 MATERIALIZED toMinute(timestamp),
quarter_hour UInt8 MATERIALIZED intDiv(toMinute(timestamp), 15)
) ENGINE = ReplacingMergeTree(timestamp)
ORDER BY (pool_address, timestamp)
PARTITION BY (date, network)
"""
self.client.command(ohlcv_schema)
logging.info("Database and tables setup complete.")
async def fetch_top_pools(self) -> List[Dict]:
"""Fetch top pools by volume from the specified DEX, handling pagination."""
logging.info(f"Fetching top {TOP_POOLS_LIMIT} pools for {DEX_ID} on {NETWORK}...")
all_pools = []
page = 0
async with aiohttp.ClientSession() as session:
while len(all_pools) < TOP_POOLS_LIMIT:
url = f"{API_BASE_URL}/networks/{NETWORK}/dexes/{DEX_ID}/pools"
params = {"page": page, "limit": 100, "order_by": "volume_usd", "sort": "desc"}
try:
data = await fetch_with_retry(session, url, params=params)
pools = data.get('pools', [])
if not pools:
break
all_pools.extend(pools)
logging.info(f"Fetched page {page}, got {len(pools)} pools. Total: {len(all_pools)}")
page += 1
if len(all_pools) >= TOP_POOLS_LIMIT:
all_pools = all_pools[:TOP_POOLS_LIMIT]
break
await asyncio.sleep(0.5) # Be respectful to the API
except Exception as e:
logging.error(f"Error fetching page {page}: {e}")
break
logging.info(f"Finished fetching pools. Total: {len(all_pools)}")
return all_pools
async def fetch_pool_ohlcv_paginated(self, session: aiohttp.ClientSession, pool_address: str) -> List[Dict]:
"""Fetch complete OHLCV data for a pool using intelligent, dynamic windowing."""
async with self.api_semaphore:
final_end_time = datetime.utcnow()
current_start_time = final_end_time - timedelta(days=HISTORY_DAYS)
all_ohlcv = []
try:
interval_minutes = int(INTERVAL.replace('m', ''))
minutes_per_call = OHLCV_API_LIMIT * interval_minutes
time_delta_per_call = timedelta(minutes=minutes_per_call)
except ValueError:
logging.error(f"Invalid INTERVAL format: {INTERVAL}. Defaulting to 15 minutes.")
interval_minutes = 15
time_delta_per_call = timedelta(minutes=OHLCV_API_LIMIT * 15)
while current_start_time < final_end_time:
batch_end_time = min(current_start_time + time_delta_per_call, final_end_time)
url = f"{API_BASE_URL}/networks/{NETWORK}/pools/{pool_address}/ohlcv"
params = {
"start": current_start_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"end": batch_end_time.strftime('%Y-%m-%dT%H:%M:%SZ'),
"interval": INTERVAL,
"limit": OHLCV_API_LIMIT
}
try:
batch_data = await fetch_with_retry(session, url, params=params)
if batch_data:
for record in batch_data:
record['network'] = NETWORK
record['pool_address'] = pool_address
if 'volume_usd' not in record:
avg_price = (record.get('open', 0) + record.get('close', 0)) / 2
record['volume_usd'] = record.get('volume', 0) * avg_price if avg_price > 0 else 0
all_ohlcv.extend(batch_data)
except Exception as e:
logging.warning(f"Could not fetch OHLCV batch for {pool_address}: {e}")
current_start_time = batch_end_time
await asyncio.sleep(0.75) # Crucial delay to prevent rate-limiting
logging.info(f"Pool {pool_address}: collected {len(all_ohlcv)} OHLCV records.")
return all_ohlcv
async def fetch_pool_ohlcv_batch(self, pool_addresses: List[str]) -> List[Dict]:
"""Fetch OHLCV data for multiple pools concurrently."""
logging.info(f"Fetching {INTERVAL} OHLCV for {len(pool_addresses)} pools...")
all_ohlcv = []
async with aiohttp.ClientSession() as session:
tasks = [self.fetch_pool_ohlcv_paginated(session, addr) for addr in pool_addresses]
results = await asyncio.gather(*tasks, return_exceptions=True)
for i, result in enumerate(results):
if isinstance(result, list):
all_ohlcv.extend(result)
elif isinstance(result, Exception):
logging.warning(f"OHLCV fetch failed for pool {pool_addresses[i]}: {result}")
return all_ohlcv
def load_pools_data(self, pools: List[Dict]):
"""Load pools data into ClickHouse with volume ranking."""
if not pools: return
logging.info("Processing and loading pools data...")
for i, pool in enumerate(pools):
tokens = pool.get('tokens', [])
pool['token0_symbol'] = tokens[0]['symbol'] if len(tokens) > 0 else None
pool['token1_symbol'] = tokens[1]['symbol'] if len(tokens) > 1 else None
pool['volume_rank'] = i + 1
df = pd.DataFrame(pools)
df = df[['id', 'dex_name', 'volume_usd', 'created_at', 'token0_symbol', 'token1_symbol', 'volume_rank']]
df = df.rename(columns={'id': 'address', 'volume_usd': 'volume_24h_usd'})
df['created_at'] = pd.to_datetime(df['created_at'])
self.client.insert_df('pools', df)
logging.info(f"Loaded {len(df)} pools into 'pools' table.")
def load_ohlcv_data(self, ohlcv_data: List[Dict]):
"""Load OHLCV data into ClickHouse."""
if not ohlcv_data: return
logging.info(f"Processing and loading {len(ohlcv_data)} OHLCV records...")
df = pd.DataFrame(ohlcv_data)
df['timestamp'] = pd.to_datetime(df['time_close'])
df = df[['timestamp', 'network', 'pool_address', 'open', 'high', 'low', 'close', 'volume_usd']]
self.client.insert_df('pool_ohlcv', df)
logging.info(f"Loaded {len(df)} records into 'pool_ohlcv' table.")
async def run_etl(self):
"""Run the complete ETL process."""
logging.info(f"Starting ClickHouse ETL process for top {TOP_POOLS_LIMIT} pools...")
pools = await self.fetch_top_pools()
if pools:
self.load_pools_data(pools)
pool_addresses = [pool['id'] for pool in pools if pool.get('id')]
for i in range(0, len(pool_addresses), BATCH_SIZE):
batch_addresses = pool_addresses[i:i + BATCH_SIZE]
batch_num = (i // BATCH_SIZE) + 1
total_batches = (len(pool_addresses) + BATCH_SIZE - 1) // BATCH_SIZE
logging.info(f"Processing OHLCV batch {batch_num}/{total_batches} ({len(batch_addresses)} pools)")
ohlcv_data = await self.fetch_pool_ohlcv_batch(batch_addresses)
self.load_ohlcv_data(ohlcv_data)
if i + BATCH_SIZE < len(pool_addresses):
logging.info(f"--- Finished batch {batch_num}, sleeping for 10 seconds ---")
await asyncio.sleep(10)
logging.info("ETL process completed!")
pool_count = self.client.command("SELECT COUNT() FROM pools")
ohlcv_count = self.client.command("SELECT COUNT() FROM pool_ohlcv")
unique_pools_with_data = self.client.command("SELECT COUNT(DISTINCT pool_address) FROM pool_ohlcv")
avg_records = ohlcv_count / unique_pools_with_data if unique_pools_with_data > 0 else 0
logging.info(f"Final counts - Pools: {pool_count}, OHLCV records: {ohlcv_count:,}")
logging.info(f"Coverage - {unique_pools_with_data} pools with data, avg {avg_records:.1f} records/pool.")
async def main():
etl = ClickHouseETL()
await etl.run_etl()
if __name__ == "__main__":
# pip install clickhouse-connect aiohttp pandas requests
asyncio.run(main())
```
This script is used for performance and reliability, using several good practices common in data pipelines:
* **Asynchronous operations:** By using `asyncio` and `aiohttp`, the script can make many API requests concurrently instead of one by one.
* **Dynamic windowing:** The `fetch_pool_ohlcv_paginated` function calculates how much data to request per API call based on the `OHLCV_API_LIMIT`.
* **Concurrency control & throttling:** An `asyncio.Semaphore`, combined with carefully tuned `BATCH_SIZE` and `asyncio.sleep()` calls, makes sure we don't hit the rate limit.
* **Resiliency:** The `fetch_with_retry` function automatically retries failed requests with an exponential backoff delay.
### **Required libraries**
```bash theme={null}
pip install clickhouse-connect aiohttp pandas requests
```
***
## Step 3: Lightning-fast analytics (Optional)
Once your database is populated, you can query it directly using any ClickHouse-compatible SQL client or a Python script. While the next step (AI Integration) is recommended for the most powerful analysis, running queries directly is a great way to verify your data.
You can create a file named `query_clickhouse.py` to see how fast ClickHouse can process complex analytical queries on the millions of rows you've ingested.
```python query_clickhouse.py [expandable] theme={null}
import clickhouse_connect
import pandas as pd
import time
client = clickhouse_connect.get_client(
host='localhost', port=8123, database='crypto_analytics'
)
print("=== ClickHouse 15-Minute Analytics Demo ===\n")
# Query 1: Top Pools by Volume with Data Coverage
print("--- Top 10 Pools by Volume (with data coverage) ---")
start_time = time.time()
result1 = client.query_df("""
SELECT
p.pair,
p.address,
max(p.volume_24h_usd) as volume_24h,
min(p.volume_rank) as best_rank,
count(o.timestamp) as ohlcv_records
FROM pools p
LEFT JOIN pool_ohlcv o ON p.address = o.pool_address
GROUP BY p.pair, p.address
ORDER BY volume_24h DESC
LIMIT 10
""")
print(result1)
print(f"Query executed in {time.time() - start_time:.3f} seconds\n")
# Query 2: 15-Minute Volume Patterns Analysis
print("--- Volume Patterns by 15-Minute Intervals ---")
result2 = client.query_df("""
SELECT
hour,
quarter_hour * 15 as minute_of_hour,
COUNT(DISTINCT pool_address) as active_pools,
round(avg(volume_usd), 2) as avg_15min_volume,
round(sum(volume_usd), 2) as total_15min_volume
FROM pool_ohlcv
WHERE volume_usd > 0 AND volume_usd < 1000000000 -- Defensive filter
GROUP BY hour, quarter_hour
ORDER BY total_15min_volume DESC
""")
print(result2.head(10))
# Query 3: High-Frequency Price Action Analysis (Top 5 Pools)
print("\n--- High-Frequency Volatility Analysis (Top 5 Pools) ---")
result3 = client.query_df("""
WITH top_pools AS (
SELECT address from pools ORDER BY volume_24h_usd DESC LIMIT 5
),
pool_volatility AS (
SELECT
o.pool_address,
p.pair,
(o.high - o.low) / o.low * 100 as interval_volatility
FROM pool_ohlcv o
JOIN pools p ON o.pool_address = p.address
WHERE o.pool_address IN (SELECT address FROM top_pools) AND o.low > 0
)
SELECT
pair,
pool_address,
avg(interval_volatility) as avg_15min_volatility,
max(interval_volatility) as max_15min_volatility
FROM pool_volatility
GROUP BY pair, pool_address
ORDER BY avg_15min_volatility DESC
""")
print(result3.head(15))
# Query 4: Peak Trading Hours Analysis
print("\n--- Peak Trading Hours Analysis ---")
result4 = client.query_df("""
SELECT
hour,
COUNT(DISTINCT pool_address) as active_pools,
round(sum(volume_usd), 2) as hourly_volume,
round(avg(volume_usd), 2) as avg_15min_volume,
round(avg((high - low) / low * 100), 4) as avg_volatility_pct
FROM pool_ohlcv
WHERE volume_usd > 0 AND low > 0 AND volume_usd < 1000000000 -- Defensive filter
GROUP BY hour
ORDER BY hourly_volume DESC
""")
print(result4.head(10))
# Query 5: Database performance and storage stats
print("\n--- Database Performance Stats ---")
stats = client.query_df("""
SELECT
table as table_name,
formatReadableSize(sum(bytes_on_disk)) as size,
sum(rows) as row_count,
formatReadableSize(sum(bytes_on_disk)/sum(rows)) as avg_row_size
FROM system.parts
WHERE database = 'crypto_analytics' AND active = 1
GROUP BY table
""")
print(stats)
# Query 6: Data quality check
print("\n--- Data Quality Summary ---")
quality_check = client.query_df("""
SELECT
'Total Records' as metric, toString(COUNT(*)) as value
FROM pool_ohlcv
UNION ALL SELECT
'Date Range', concat(toString(MIN(date)), ' to ', toString(MAX(date)))
FROM pool_ohlcv
UNION ALL SELECT
'Unique Pools with Data', toString(COUNT(DISTINCT pool_address))
FROM pool_ohlcv
UNION ALL SELECT
'Avg Records per Day', toString(ROUND(COUNT(*) / nullif(COUNT(DISTINCT date), 0)))
FROM pool_ohlcv
UNION ALL SELECT
'Expected 15min Intervals vs Actual',
concat(
toString(dateDiff('minute', MIN(timestamp), MAX(timestamp)) / 15),
' vs ',
toString(count())
)
FROM pool_ohlcv
""")
print(quality_check)
```
You can run the script by executing it from your terminal:
```bash theme={null}
python query_clickhouse.py
```
Now, let's move on to the recommended final step: connecting your database to an AI assistant.
***
## Step 4: AI-powered analysis with an MCP server
Enable seamless analysis of your local ClickHouse database through the [ClickHouse MCP Server](https://github.com/ClickHouse/mcp-clickhouse). This allows AI assistants like Claude Desktop to connect to your database, list tables, and run `SELECT` queries securely.
### 1. Install the MCP server
The server is a Python package that can be installed via `pip`:
```bash theme={null}
pip install clickhouse-mcp-server
```
### 2. Configure your AI client
Next, configure your AI client (e.g., Claude Desktop) to use the server. You'll need to edit its configuration file.
* **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
* **Windows:** `%APPDATA%/Claude/claude_desktop_config.json`
Add the following JSON block to the `mcpServers` section of the file. This tells the client how to run the server and provides the connection details for your local ClickHouse instance.
**Finding the command path**
The most common point of failure is an incorrect command path. The command should be the **absolute path** to the `clickhouse-mcp-server` executable that `pip` installed.
Find this path by running `which clickhouse-mcp-server` in your terminal and use the output in the `command` field below.
```json theme={null}
{
"mcpServers": {
"clickhouse-mcp-server": {
"command": "/path/to/your/clickhouse-mcp-server",
"args": [],
"env": {
"CLICKHOUSE_HOST": "localhost",
"CLICKHOUSE_USER": "default",
"CLICKHOUSE_PASSWORD": "",
"CLICKHOUSE_DATABASE": "crypto_analytics",
"CLICKHOUSE_SECURE": "false"
}
}
}
}
```
### 3. Restart and analyze
Save the configuration file and **restart your AI client**. Once restarted, you can start asking it to analyze the data in your `crypto_analytics` database.
### Troubleshooting & important notes
* **"Server disconnected" error:** This almost always means the `command` path in your configuration is incorrect. Double-check the absolute path using `which clickhouse-mcp-server`.
* **AI connects to the `default` database:** We observed that the AI client might sometimes choose to connect to the `default` database on its own, even if `crypto_analytics` is specified in the config. This will result in it seeing no tables.
* **Solution: Be explicit:** To ensure the AI works correctly, always specify the database in your prompt. This overrides the AI's tendency to use the default.
**Good example prompts:**
* "Using the clickhouse-mcp-server, **connect to the `crypto_analytics` database** and then list the tables."
* "**In the `crypto_analytics` database**, show me the top 10 pools by volume from the `pools` table."
* "Calculate the average daily volume for the top 5 most volatile pools **from the `crypto_analytics` database**."
***
## What you've built: A production-grade analytics pipeline
Congratulations! You've successfully built a scalable crypto analytics pipeline with ClickHouse. You've ingested a large dataset of OHLCV data, and you've enabled a powerful AI assistant to securely query and analyze that data.
**Key achievements:**
* **Built a production-ready ETL pipeline:** You have a reusable, high-performance Python script that can create a comprehensive, multi-million row database from any supported DEX and network.
* **Unlocked lightning-fast SQL:** You can now perform complex analytical queries on a massive dataset in milliseconds, directly on your machine.
* **Mastered a scalable workflow:** This "local-first" data strategy, combined with ClickHouse's power, provides a solid foundation for building real-time dashboards, conducting in-depth market research, and developing sophisticated trading algorithms.
* **Enabled secure AI analysis:** By connecting your database to an AI assistant via an MCP server, you've created a powerful and secure way to explore your data using natural language.
### FAQs
When your dataset no longer fits comfortably on a single machine or you need concurrent users and sub‑second queries on billions of rows.
Tune `BATCH_SIZE` and concurrency based on CPU/network; watch error rates and back off on timeouts.
`15m` is a great compromise; use `1m/5m` for ultra‑short‑term dashboards.
Run the ETL incrementally (cron or scheduler) to append the latest OHLCV windows.
# API tutorials
Source: https://docs.dexpaprika.com/tutorials/tutorial_intro
Learn how to use the DexPaprika API with step-by-step tutorials.
## Available tutorials
| Tutorial | Description |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| [CLI](/tutorials/cli) | Install the DexPaprika CLI and query DEX data from your terminal. |
| [Fetching token prices](/tutorials/fetch-token-price) | Retrieve the price of any token using the DexPaprika API. |
| [Batch token prices](/tutorials/batch-token-prices) | Fetch prices for multiple tokens in a single request -- reduce API calls by up to 90%. |
| [Pool filtering](/tutorials/pool-filtering) | Filter pools by volume, transaction count, and creation date using the advanced filter endpoint. |
| [Find new pools](/tutorials/find-new-pools) | Discover newly created liquidity pools on any network by sorting pools by creation date. |
| [Retrieve historical data](/tutorials/retrieve-historical-data) | Get OHLCV (Open, High, Low, Close, Volume) historical price data for any token. |
| [Vibe coding with AI](/tutorials/vibe-coding-with-ai) | Use Claude Code or Cursor with DexPaprika access to build a crypto dashboard from natural language prompts. |
| [Build a price alert bot](/tutorials/crypto-alert-bot) | Create a real-time cryptocurrency price alert system using DexPaprika API and Telegram. |
| [Local analytics with DuckDB](/tutorials/local-analytics-with-duckdb) | Build a local analytics database with DuckDB to query Uniswap v3 data instantly. |
| [Scaling with ClickHouse](/tutorials/scaling-with-clickhouse) | Create a production-grade ClickHouse pipeline for massive datasets. |
| [Real-time analytics with InfluxDB](/tutorials/real-time-analytics-with-influxdb) | Time-series analytics pipeline for real-time monitoring. |
Do you have an interesting implementation that you want to share with others? We'd be happy to share your tutorial utilizing our API with others. [Reach us out on Discord!](https://discord.gg/mS4cWp6a)
## Get support
Connect with our community and get real-time support.
Share your experience and help us improve the API.
### FAQs
No. All examples use the public API - no keys or registration required.
Check the [Networks API](/api-reference/networks/get-a-list-of-available-blockchain-networks) for the current list.
Use curl from your terminal or the API Reference playground directly in these docs.
# Vibe code a crypto dashboard with AI
Source: https://docs.dexpaprika.com/tutorials/vibe-coding-with-ai
Use Claude Code, Cursor, or any AI-assisted IDE with DexPaprika access to build a crypto dashboard from a natural language prompt. No manual API calls -- let the AI do the work.
## What is vibe coding?
Vibe coding means describing what you want in natural language and letting an AI assistant write the code. With DexPaprika connected to your AI tool, the AI can fetch real crypto data while it builds -- testing endpoints, checking response shapes, and writing working code from the start.
This tutorial shows the workflow, not a fixed script. Your results will vary based on your AI tool, your prompts, and what you ask for.
***
## Prerequisites
Connect DexPaprika to your AI tool using one of these methods:
| Tool | Setup |
| ------------------ | --------------------------------------------------------------------------------------------- |
| **Claude Code** | `/plugin marketplace add coinpaprika/claude-marketplace` then `/plugin install dexpaprika` |
| **Cursor** | Add MCP server URL `https://mcp.dexpaprika.com/sse` in Settings → Tools & Integrations |
| **VS Code** | Add MCP server via Copilot Chat settings |
| **Claude Desktop** | Add `"dexpaprika": {"url": "https://mcp.dexpaprika.com/sse"}` to `claude_desktop_config.json` |
See the [AI Integration overview](/ai-integration) for detailed setup instructions.
***
## Example 1: "Build me a token price dashboard"
### The prompt
Give your AI a clear, specific prompt:
```
Build a single-page HTML dashboard that shows:
1. The current price of SOL, ETH, and BTC
2. Their 24h volume and price change percentage
3. Auto-refreshes every 30 seconds
Use the DexPaprika API. No frameworks -- just vanilla HTML, CSS, and JavaScript.
The SOL address on Solana is So11111111111111111111111111111111111111112.
Use the search endpoint to find ETH and BTC addresses.
```
### What happens
The AI will:
1. Call the DexPaprika search endpoint to find ETH and BTC token addresses and networks
2. Read the token details endpoint to understand the response format
3. Write HTML/CSS/JS that fetches from the DexPaprika REST API
4. Use `summary.price_usd` for the price, `summary.24h.volume_usd` for volume, and `summary.24h.last_price_usd_change` for the percentage change
5. Add a `setInterval` for auto-refresh
### Tips for better results
* **Be specific about data fields.** "Show the 24h price change" is better than "show some stats"
* **Name the tokens and networks.** Don't assume the AI knows every address
* **Mention the API by name.** Say "Use the DexPaprika API" so the AI uses the MCP tools or REST endpoints
* **Start simple, then iterate.** Get a working version first, then ask for styling, charts, or more features
***
## Example 2: "Find me the hottest new pools"
### The prompt
```
Use DexPaprika to find pools created in the last 24 hours on Solana
that have more than $10,000 in daily volume and at least 100 transactions.
Show them in a table sorted by volume, with the pool address, DEX, volume,
and transaction count.
```
### What the AI does
The AI will use the filter endpoint:
```
GET /networks/solana/pools/filter?created_after={24h_ago_timestamp}&volume_24h_min=10000&txns_24h_min=100&sort_by=volume_24h&sort_dir=desc
```
Then format the results. It might also follow up with pool detail calls to get token pair names.
***
## Example 3: "Build a price comparison tool"
### The prompt
```
Build a Python script that compares the price of WETH across Ethereum,
Arbitrum, and Base networks. Use DexPaprika batch pricing.
Show the price on each network and highlight the highest and lowest.
```
### What the AI does
1. Finds WETH addresses on each network (via search or by knowing common addresses)
2. Makes three batch pricing calls (one per network)
3. Compares results and formats output
***
## Example 4: "Add a live price ticker"
### The prompt
```
Add a live price ticker to the dashboard that streams real-time prices
for SOL and ETH using the DexPaprika streaming API at
streaming.dexpaprika.com. Use Server-Sent Events.
```
### What the AI does
The AI will use the streaming API:
```javascript theme={null}
const evtSource = new EventSource(
"https://streaming.dexpaprika.com/stream?method=t_p&chain=solana&address=So11111111111111111111111111111111111111112"
);
evtSource.addEventListener("t_p", (event) => {
const data = JSON.parse(event.data);
// data.p is the price as a string
updatePrice(data.c, data.a, data.p);
});
```
For multiple tokens, the AI should use the POST endpoint with a JSON array.
***
## Iteration tips
Once you have a working first version, iterate with follow-up prompts:
* "Add a chart showing the last 7 days of price history" (AI will use OHLCV endpoint)
* "Show the top 5 pools for each token" (AI will use token pools endpoint)
* "Add error handling for when the API is down"
* "Make it responsive for mobile"
* "Add dark mode"
* "Export the data to CSV"
Each iteration builds on the previous code. The AI already has context about which endpoints to use and what the response formats look like.
***
## Common issues
Be explicit: "Use the DexPaprika API at api.dexpaprika.com" or "Use the DexPaprika MCP tool." If using an IDE integration, make sure the MCP server is connected and showing as active.
Point the AI to specific documentation: "Check the token endpoint response format at docs.dexpaprika.com" or provide the correct field path directly: "The price is at response.summary.price\_usd, not response.price."
The DexPaprika REST API supports CORS, so browser requests should work. The streaming API also supports CORS. If you see CORS errors, check that the URL is correct (https, not http).
If the AI invents endpoints, ground it: "Only use endpoints from the DexPaprika API reference at docs.dexpaprika.com/api-reference/introduction. The available endpoints are: /networks, /search, /networks//pools, /networks//tokens/, /networks//pools//ohlcv, etc."
***
## Next steps
Connect DexPaprika to your AI tool
Standard API workflows to reference in your prompts
Real-time price streaming for live dashboards
Advanced pool screening with the filter endpoint