Skip to content

Token Prices API

Get real-time cryptocurrency prices across multiple networks. This API provides current market prices, historical data, and price change information.

Endpoint

GET /v1/tokens/prices

Authentication

This endpoint requires API key authentication:

Authorization: Bearer YOUR_API_KEY

Query Parameters

ParameterTypeRequiredDescription
tokensstringComma-separated list of token symbols (e.g., "ETH,USDC,MATIC")
addressesstringComma-separated list of token addresses with chain IDs
chainIdsstringComma-separated list of chain IDs to filter by
baseCurrencystringBase currency for prices (default: "USD")
includeChangebooleanInclude 24h price change data (default: false)
includeMarketCapbooleanInclude market cap data (default: false)

Example Requests

# Get prices for specific tokens
GET /v1/tokens/prices?tokens=ETH,USDC,MATIC&includeChange=true
 
# Get prices by contract addresses
GET /v1/tokens/prices?addresses=1:0xA0b86a33E6441b8e776f89d2b5B977c737C5e0b6,137:0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359
 
# Get all supported tokens on specific chains
GET /v1/tokens/prices?chainIds=1,137,10&baseCurrency=EUR

Response Format

Success Response

{
  "success": true,
  "data": {
    "prices": [
      {
        "symbol": "ETH",
        "name": "Ethereum",
        "price": "2456.78",
        "baseCurrency": "USD",
        "networks": [
          {
            "chainId": 1,
            "chainName": "Ethereum",
            "address": "0x0000000000000000000000000000000000000000",
            "decimals": 18,
            "price": "2456.78",
            "liquidity": "high"
          },
          {
            "chainId": 10,
            "chainName": "Optimism",
            "address": "0x0000000000000000000000000000000000000000",
            "decimals": 18,
            "price": "2456.78",
            "liquidity": "high"
          }
        ],
        "change24h": {
          "absolute": "45.23",
          "percentage": "1.87"
        },
        "marketCap": "295847392847",
        "volume24h": "12847392847",
        "lastUpdated": 1759231185
      },
      {
        "symbol": "USDC",
        "name": "USD Coin",
        "price": "1.0001",
        "baseCurrency": "USD",
        "networks": [
          {
            "chainId": 1,
            "chainName": "Ethereum",
            "address": "0xA0b86a33E6441b8e776f89d2b5B977c737C5e0b6",
            "decimals": 6,
            "price": "1.0001",
            "liquidity": "high"
          },
          {
            "chainId": 137,
            "chainName": "Polygon",
            "address": "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
            "decimals": 6,
            "price": "1.0001",
            "liquidity": "high"
          }
        ],
        "change24h": {
          "absolute": "0.0001",
          "percentage": "0.01"
        },
        "marketCap": "32847392847",
        "volume24h": "8847392847",
        "lastUpdated": 1759231185
      }
    ],
    "metadata": {
      "totalTokens": 2,
      "baseCurrency": "USD",
      "lastUpdated": 1759231185,
      "updateFrequency": "30s"
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Single Token Price

Get price for a specific token:

GET /v1/tokens/prices/{symbol}

Path Parameters

ParameterTypeRequiredDescription
symbolstringToken symbol (e.g., "ETH", "USDC")

Example Response

{
  "success": true,
  "data": {
    "symbol": "ETH",
    "name": "Ethereum",
    "price": "2456.78",
    "baseCurrency": "USD",
    "networks": [
      {
        "chainId": 1,
        "chainName": "Ethereum",
        "address": "0x0000000000000000000000000000000000000000",
        "decimals": 18,
        "price": "2456.78",
        "liquidity": "high"
      }
    ],
    "change24h": {
      "absolute": "45.23",
      "percentage": "1.87"
    },
    "priceHistory": {
      "1h": "2451.34",
      "24h": "2411.55",
      "7d": "2389.12",
      "30d": "2234.67"
    },
    "marketData": {
      "marketCap": "295847392847",
      "volume24h": "12847392847",
      "circulatingSupply": "120384756",
      "totalSupply": "120384756"
    },
    "lastUpdated": 1759231185
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Historical Prices

Get historical price data:

GET /v1/tokens/prices/{symbol}/history

Query Parameters

ParameterTypeRequiredDescription
periodstringTime period: "1h", "24h", "7d", "30d", "1y" (default: "24h")
intervalstringData interval: "1m", "5m", "1h", "1d" (default: "1h")
baseCurrencystringBase currency (default: "USD")

Example Response

{
  "success": true,
  "data": {
    "symbol": "ETH",
    "period": "24h",
    "interval": "1h",
    "baseCurrency": "USD",
    "prices": [
      {
        "timestamp": 1759144800,
        "price": "2411.55",
        "volume": "847392847"
      },
      {
        "timestamp": 1759148400,
        "price": "2418.23",
        "volume": "923847392"
      },
      {
        "timestamp": 1759152000,
        "price": "2425.67",
        "volume": "1047392847"
      }
    ],
    "summary": {
      "high": "2467.89",
      "low": "2398.45",
      "open": "2411.55",
      "close": "2456.78",
      "change": "45.23",
      "changePercent": "1.87"
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Error Responses

Token Not Found

{
  "success": false,
  "error": {
    "code": "TOKEN_NOT_FOUND",
    "message": "Token not found or not supported",
    "details": {
      "symbol": "UNKNOWN",
      "supportedTokens": ["ETH", "USDC", "USDT", "DAI", "MATIC"]
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Invalid Chain ID

{
  "success": false,
  "error": {
    "code": "INVALID_CHAIN_ID",
    "message": "Chain ID not supported",
    "details": {
      "chainId": 999,
      "supportedChains": [1, 10, 137, 42161, 8453]
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

Code Examples

JavaScript/TypeScript

import { CyberPaySDK } from '@cyberpay/sdk';
 
const sdk = new CyberPaySDK({
  apiKey: 'YOUR_API_KEY',
  environment: 'production'
});
 
async function getTokenPrices() {
  try {
    // Get prices for multiple tokens
    const prices = await sdk.tokens.getPrices({
      tokens: ['ETH', 'USDC', 'MATIC'],
      includeChange: true,
      includeMarketCap: true
    });
    
    console.log('Token prices:', prices);
    
    // Get single token price
    const ethPrice = await sdk.tokens.getPrice('ETH');
    console.log('ETH price:', ethPrice.price);
    
    // Get historical data
    const history = await sdk.tokens.getPriceHistory('ETH', {
      period: '7d',
      interval: '1h'
    });
    
    console.log('ETH price history:', history);
    
    return prices;
  } catch (error) {
    console.error('Error fetching prices:', error);
  }
}
 
// Real-time price monitoring
async function monitorPrices(tokens: string[], callback: (prices: any) => void) {
  const fetchPrices = async () => {
    try {
      const prices = await sdk.tokens.getPrices({
        tokens,
        includeChange: true
      });
      callback(prices);
    } catch (error) {
      console.error('Error fetching prices:', error);
    }
  };
  
  // Initial fetch
  await fetchPrices();
  
  // Set up polling every 30 seconds
  const interval = setInterval(fetchPrices, 30000);
  
  // Return cleanup function
  return () => clearInterval(interval);
}

React Hook Example

import { useState, useEffect } from 'react';
import { CyberPaySDK } from '@cyberpay/sdk';
 
export function useTokenPrices(tokens: string[], refreshInterval: number = 30000) {
  const [prices, setPrices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  useEffect(() => {
    const sdk = new CyberPaySDK({ apiKey: process.env.REACT_APP_CYBERPAY_API_KEY });
    
    const fetchPrices = async () => {
      try {
        const result = await sdk.tokens.getPrices({
          tokens,
          includeChange: true
        });
        
        setPrices(result.prices);
        setError(null);
        setLoading(false);
      } catch (err: any) {
        setError(err.message);
        setLoading(false);
      }
    };
    
    // Initial fetch
    fetchPrices();
    
    // Set up polling
    const interval = setInterval(fetchPrices, refreshInterval);
    
    return () => clearInterval(interval);
  }, [tokens, refreshInterval]);
  
  return { prices, loading, error };
}
 
// Usage in component
function TokenPriceList({ tokens }: { tokens: string[] }) {
  const { prices, loading, error } = useTokenPrices(tokens);
  
  if (loading) return <div>Loading prices...</div>;
  if (error) return <div>Error: {error}</div>;
  
  return (
    <div className="token-prices">
      {prices.map((token) => (
        <div key={token.symbol} className="token-price">
          <span className="symbol">{token.symbol}</span>
          <span className="price">${token.price}</span>
          <span className={`change ${parseFloat(token.change24h.percentage) >= 0 ? 'positive' : 'negative'}`}>
            {token.change24h.percentage}%
          </span>
        </div>
      ))}
    </div>
  );
}

cURL Examples

# Get prices for multiple tokens
curl -X GET "https://api.cyberpay.org/v1/tokens/prices?tokens=ETH,USDC,MATIC&includeChange=true" \
  -H "Authorization: Bearer YOUR_API_KEY"
 
# Get single token price
curl -X GET "https://api.cyberpay.org/v1/tokens/prices/ETH" \
  -H "Authorization: Bearer YOUR_API_KEY"
 
# Get historical data
curl -X GET "https://api.cyberpay.org/v1/tokens/prices/ETH/history?period=7d&interval=1h" \
  -H "Authorization: Bearer YOUR_API_KEY"

Python Example

import requests
import time
 
class CyberPayPrices:
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.cyberpay.org/v1"
        self.headers = {"Authorization": f"Bearer {api_key}"}
    
    def get_prices(self, tokens=None, include_change=False):
        url = f"{self.base_url}/tokens/prices"
        params = {}
        
        if tokens:
            params['tokens'] = ','.join(tokens)
        if include_change:
            params['includeChange'] = 'true'
        
        response = requests.get(url, headers=self.headers, params=params)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API Error: {response.json()}")
    
    def get_single_price(self, symbol):
        url = f"{self.base_url}/tokens/prices/{symbol}"
        response = requests.get(url, headers=self.headers)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API Error: {response.json()}")
    
    def get_price_history(self, symbol, period='24h', interval='1h'):
        url = f"{self.base_url}/tokens/prices/{symbol}/history"
        params = {'period': period, 'interval': interval}
        
        response = requests.get(url, headers=self.headers, params=params)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"API Error: {response.json()}")
 
# Usage
if __name__ == "__main__":
    client = CyberPayPrices("YOUR_API_KEY")
    
    # Get current prices
    prices = client.get_prices(['ETH', 'USDC'], include_change=True)
    print("Current prices:", prices)
    
    # Get ETH price details
    eth_price = client.get_single_price('ETH')
    print("ETH price:", eth_price['data']['price'])
    
    # Get price history
    history = client.get_price_history('ETH', '7d', '1h')
    print("Price history points:", len(history['data']['prices']))

Supported Tokens

Major Cryptocurrencies

SymbolNameNetworks
ETHEthereumEthereum, Optimism, Arbitrum, Base
USDCUSD CoinEthereum, Polygon, Optimism, Arbitrum, Base
USDTTether USDEthereum, Polygon, Optimism, Arbitrum
DAIDai StablecoinEthereum, Polygon, Optimism, Arbitrum
WBTCWrapped BitcoinEthereum, Polygon, Optimism, Arbitrum
MATICPolygonEthereum, Polygon

DeFi Tokens

SymbolNameNetworks
UNIUniswapEthereum, Polygon, Optimism, Arbitrum
AAVEAaveEthereum, Polygon, Optimism, Arbitrum
COMPCompoundEthereum
SUSHISushiSwapEthereum, Polygon, Optimism, Arbitrum
CRVCurve DAO TokenEthereum, Polygon, Optimism, Arbitrum

Rate Limits

  • Standard: 300 requests per minute
  • Premium: 3000 requests per minute
  • Enterprise: Custom limits available

Best Practices

Caching

  • Cache price data for at least 30 seconds
  • Use ETags for conditional requests
  • Implement proper cache invalidation

Error Handling

  • Handle rate limits with exponential backoff
  • Implement fallback data sources
  • Validate token symbols before requests

Performance

  • Batch multiple token requests
  • Use WebSocket for real-time updates
  • Implement proper timeout handling

WebSocket Real-Time Prices

For real-time price updates:

const ws = new WebSocket('wss://api.cyberpay.org/v1/tokens/prices/stream');
 
ws.onopen = function() {
  ws.send(JSON.stringify({
    action: 'subscribe',
    tokens: ['ETH', 'USDC', 'MATIC'],
    apiKey: 'YOUR_API_KEY'
  }));
};
 
ws.onmessage = function(event) {
  const update = JSON.parse(event.data);
  console.log('Price update:', update);
};

Next Steps

Support