tigusigalpa/coingecko-php

A comprehensive PHP/Laravel package for CoinGecko API integration with support for all endpoints including coins, markets, contracts, and more. Easy to use, well-documented, and Laravel-ready.

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/tigusigalpa/coingecko-php

v1.0.0 2025-12-18 04:51 UTC

This package is auto-updated.

Last update: 2025-12-18 11:02:56 UTC


README

CoinGecko PHP SDK

Latest Version on Packagist Total Downloads License

A comprehensive, modern PHP/Laravel package for seamless integration with the CoinGecko API. Get real-time cryptocurrency prices, market data, historical charts, and more with an elegant, developer-friendly interface.

Features โ€ข Installation โ€ข Quick Start โ€ข Documentation โ€ข Examples

๐Ÿš€ Features

  • โœ… Complete API Coverage - All CoinGecko API endpoints implemented
  • ๐Ÿ” Pro API Support - Full support for CoinGecko Pro API with authentication
  • ๐ŸŽฏ Laravel Integration - Service provider, facade, and configuration out of the box
  • ๐Ÿ’Ž Modern PHP - Built with PHP 8.0+ features and best practices
  • ๐Ÿ›ก๏ธ Type Safety - Fully typed parameters and return values
  • ๐Ÿ“ฆ Zero Configuration - Works immediately with sensible defaults
  • ๐Ÿ”„ Flexible - Use as standalone PHP library or Laravel package
  • ๐ŸŽจ Clean API - Intuitive, chainable methods for better developer experience
  • โšก Performance - Efficient HTTP client with connection pooling
  • ๐Ÿ“š Well Documented - Comprehensive examples and API reference

๐Ÿ“‹ Requirements

  • PHP 8.0 or higher
  • Laravel 9.x, 10.x, or 11.x (for Laravel integration)
  • Guzzle HTTP client 7.x

๐Ÿ“ฆ Installation

Install the package via Composer:

composer require tigusigalpa/coingecko-php

Laravel Setup

The package will automatically register its service provider. Publish the configuration file:

php artisan vendor:publish --tag=coingecko-config

Add your CoinGecko API credentials to your .env file:

COINGECKO_API_KEY=your-api-key-here
COINGECKO_IS_PRO=false

Note: API key is optional for free tier. Set COINGECKO_IS_PRO=true if you have a Pro API subscription.

๐ŸŽฏ Quick Start

Standalone PHP Usage

use Tigusigalpa\Coingecko\Coingecko;

// Initialize client (no API key needed for free tier)
$coingecko = new Coingecko();

// Get Bitcoin price in USD
$price = $coingecko->simple()->price('bitcoin', 'usd');
echo "Bitcoin: $" . $price['bitcoin']['usd'];

// With Pro API
$coingecko = new Coingecko('your-api-key', true);

Laravel Usage

use Tigusigalpa\Coingecko\Facades\Coingecko;

// Using Facade
$price = Coingecko::simple()->price('bitcoin', 'usd');

// Using Dependency Injection
use Tigusigalpa\Coingecko\Coingecko;

class CryptoController extends Controller
{
    public function __construct(private Coingecko $coingecko)
    {
    }

    public function index()
    {
        $markets = $this->coingecko->coins()->markets('usd', perPage: 10);
        return view('crypto.index', compact('markets'));
    }
}

๐Ÿ“– Documentation

API Endpoints

The package is organized into logical API groups:

  • Simple API - Quick price lookups and supported currencies
  • Coins API - Comprehensive coin data, markets, and historical charts
  • Contract API - Token data by contract address
  • Ping API - Server status and API usage

Simple API

Get cryptocurrency prices and basic market data quickly.

Get Coin Prices

// Single coin, single currency
$price = $coingecko->simple()->price('bitcoin', 'usd');
// Returns: ['bitcoin' => ['usd' => 45000]]

// Multiple coins, multiple currencies
$prices = $coingecko->simple()->price(
    ids: ['bitcoin', 'ethereum', 'cardano'],
    vsCurrencies: ['usd', 'eur', 'gbp'],
    includeMarketCap: true,
    include24hrVol: true,
    include24hrChange: true
);

// Example response:
// [
//     'bitcoin' => [
//         'usd' => 45000,
//         'eur' => 42000,
//         'usd_market_cap' => 850000000000,
//         'usd_24h_vol' => 35000000000,
//         'usd_24h_change' => 2.5
//     ],
//     ...
// ]

Get Token Prices by Contract Address

// Get price for a token on Ethereum
$tokenPrice = $coingecko->simple()->tokenPrice(
    assetPlatform: 'ethereum',
    contractAddresses: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', // UNI token
    vsCurrencies: 'usd',
    includeMarketCap: true,
    include24hrVol: true
);

Get Supported Currencies

$currencies = $coingecko->simple()->supportedVsCurrencies();
// Returns: ['usd', 'eur', 'gbp', 'jpy', ...]

Coins API

Access detailed coin information, market data, and historical charts.

List All Coins

// Get list of all coins with IDs
$coinsList = $coingecko->coins()->list();

// Include platform information
$coinsWithPlatforms = $coingecko->coins()->list(includePlatform: true);

Top Gainers & Losers

$topMovers = $coingecko->coins()->topGainersLosers(
    vsCurrency: 'usd',
    duration: '24h',
    topCoins: 100
);

// Returns top gainers and losers with percentage changes

Recently Added Coins

$newCoins = $coingecko->coins()->recentlyAdded();

Coins Market Data

// Get top 100 coins by market cap
$markets = $coingecko->coins()->markets(
    vsCurrency: 'usd',
    order: 'market_cap_desc',
    perPage: 100,
    page: 1,
    sparkline: true,
    priceChangePercentage: '1h,24h,7d'
);

// Filter by specific coins
$specificCoins = $coingecko->coins()->markets(
    vsCurrency: 'usd',
    ids: ['bitcoin', 'ethereum', 'cardano']
);

// Filter by category
$defiCoins = $coingecko->coins()->markets(
    vsCurrency: 'usd',
    category: 'decentralized-finance-defi',
    perPage: 50
);

Detailed Coin Data

// Get comprehensive data for a specific coin
$bitcoin = $coingecko->coins()->coin(
    id: 'bitcoin',
    localization: true,
    tickers: true,
    marketData: true,
    communityData: true,
    developerData: true,
    sparkline: true
);

// Access various data points:
// $bitcoin['market_data']['current_price']['usd']
// $bitcoin['market_data']['market_cap']['usd']
// $bitcoin['market_data']['total_volume']['usd']
// $bitcoin['community_data']['twitter_followers']
// $bitcoin['developer_data']['stars']

Coin Tickers

// Get all trading pairs for a coin
$tickers = $coingecko->coins()->tickers(
    id: 'bitcoin',
    exchangeIds: ['binance', 'coinbase'],
    page: 1,
    order: 'volume_desc'
);

Historical Data

// Get coin data at a specific date
$historicalData = $coingecko->coins()->history(
    id: 'bitcoin',
    date: '30-12-2023', // DD-MM-YYYY format
    localization: false
);

Market Chart Data

// Get price, market cap, and volume chart data
$chartData = $coingecko->coins()->marketChart(
    id: 'bitcoin',
    vsCurrency: 'usd',
    days: 30, // 1, 7, 14, 30, 90, 180, 365, 'max'
    interval: 'daily' // optional: 'daily' or 'hourly'
);

// Returns:
// [
//     'prices' => [[timestamp, price], ...],
//     'market_caps' => [[timestamp, market_cap], ...],
//     'total_volumes' => [[timestamp, volume], ...]
// ]

// Get chart data for specific time range
$rangeData = $coingecko->coins()->marketChartRange(
    id: 'ethereum',
    vsCurrency: 'usd',
    from: 1609459200, // Unix timestamp
    to: 1640995200,   // Unix timestamp
    precision: '2'
);

OHLC Chart Data

// Get candlestick (OHLC) data
$ohlc = $coingecko->coins()->ohlc(
    id: 'bitcoin',
    vsCurrency: 'usd',
    days: 7 // 1, 7, 14, 30, 90, 180, 365
);

// Returns: [[timestamp, open, high, low, close], ...]

Supply Charts

// Circulating supply chart
$circulatingSupply = $coingecko->coins()->circulatingSupplyChart(
    id: 'bitcoin',
    days: 30,
    interval: 'daily'
);

// Circulating supply for specific time range
$circulatingRange = $coingecko->coins()->circulatingSupplyChartRange(
    id: 'bitcoin',
    from: 1609459200,
    to: 1640995200
);

// Total supply chart
$totalSupply = $coingecko->coins()->totalSupplyChart(
    id: 'ethereum',
    days: 90
);

// Total supply for specific time range
$totalRange = $coingecko->coins()->totalSupplyChartRange(
    id: 'ethereum',
    from: 1609459200,
    to: 1640995200
);

Contract API

Get token data using contract addresses on various blockchain platforms.

Get Token Data by Contract Address

// Get comprehensive token data
$tokenData = $coingecko->contract()->coin(
    assetPlatform: 'ethereum',
    contractAddress: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984' // UNI token
);

// Supported platforms: ethereum, binance-smart-chain, polygon-pos, 
// avalanche, arbitrum-one, optimistic-ethereum, etc.

Token Market Chart by Contract

// Get price chart for a token
$tokenChart = $coingecko->contract()->marketChart(
    assetPlatform: 'ethereum',
    contractAddress: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
    vsCurrency: 'usd',
    days: 30
);

// Get chart data for specific time range
$tokenRangeChart = $coingecko->contract()->marketChartRange(
    assetPlatform: 'ethereum',
    contractAddress: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
    vsCurrency: 'usd',
    from: 1609459200,
    to: 1640995200
);

Ping API

Check API server status and monitor your API usage.

Check Server Status

$status = $coingecko->ping()->ping();
// Returns: ['gecko_says' => '(V3) To the Moon!']

Check API Usage (Pro API only)

$usage = $coingecko->ping()->apiUsage();
// Returns information about your API key usage and rate limits

๐Ÿ’ก Examples

Real-World Use Cases

Portfolio Tracker

use Tigusigalpa\Coingecko\Facades\Coingecko;

class PortfolioService
{
    public function getPortfolioValue(array $holdings): float
    {
        $coinIds = array_keys($holdings);
        $prices = Coingecko::simple()->price($coinIds, 'usd');
        
        $totalValue = 0;
        foreach ($holdings as $coinId => $amount) {
            $totalValue += $prices[$coinId]['usd'] * $amount;
        }
        
        return $totalValue;
    }
}

// Usage
$portfolio = [
    'bitcoin' => 0.5,
    'ethereum' => 10,
    'cardano' => 1000
];

$service = new PortfolioService();
$value = $service->getPortfolioValue($portfolio);
echo "Portfolio Value: $" . number_format($value, 2);

Price Alert System

use Tigusigalpa\Coingecko\Coingecko;

class PriceAlertChecker
{
    public function __construct(private Coingecko $coingecko)
    {
    }

    public function checkAlerts(array $alerts): array
    {
        $coinIds = array_unique(array_column($alerts, 'coin_id'));
        $prices = $this->coingecko->simple()->price(
            ids: $coinIds,
            vsCurrencies: 'usd',
            include24hrChange: true
        );
        
        $triggered = [];
        foreach ($alerts as $alert) {
            $currentPrice = $prices[$alert['coin_id']]['usd'];
            
            if ($alert['type'] === 'above' && $currentPrice >= $alert['target_price']) {
                $triggered[] = $alert;
            } elseif ($alert['type'] === 'below' && $currentPrice <= $alert['target_price']) {
                $triggered[] = $alert;
            }
        }
        
        return $triggered;
    }
}

Market Analysis Dashboard

use Tigusigalpa\Coingecko\Facades\Coingecko;

class MarketAnalyzer
{
    public function getDashboardData(): array
    {
        // Get top 10 coins by market cap
        $topCoins = Coingecko::coins()->markets(
            vsCurrency: 'usd',
            order: 'market_cap_desc',
            perPage: 10,
            sparkline: true,
            priceChangePercentage: '1h,24h,7d,30d'
        );
        
        // Get top gainers and losers
        $movers = Coingecko::coins()->topGainersLosers('usd', '24h', 100);
        
        // Get recently added coins
        $newCoins = Coingecko::coins()->recentlyAdded();
        
        return [
            'top_coins' => $topCoins,
            'gainers' => array_slice($movers['top_gainers'] ?? [], 0, 5),
            'losers' => array_slice($movers['top_losers'] ?? [], 0, 5),
            'new_listings' => array_slice($newCoins, 0, 5)
        ];
    }
}

Historical Price Comparison

use Tigusigalpa\Coingecko\Coingecko;

class PriceComparison
{
    public function __construct(private Coingecko $coingecko)
    {
    }

    public function compareCoins(array $coinIds, int $days = 30): array
    {
        $comparison = [];
        
        foreach ($coinIds as $coinId) {
            $chartData = $this->coingecko->coins()->marketChart(
                id: $coinId,
                vsCurrency: 'usd',
                days: $days
            );
            
            $prices = array_column($chartData['prices'], 1);
            $startPrice = reset($prices);
            $endPrice = end($prices);
            $change = (($endPrice - $startPrice) / $startPrice) * 100;
            
            $comparison[$coinId] = [
                'start_price' => $startPrice,
                'end_price' => $endPrice,
                'change_percent' => round($change, 2),
                'chart_data' => $chartData['prices']
            ];
        }
        
        return $comparison;
    }
}

// Usage
$comparison = new PriceComparison(new Coingecko());
$results = $comparison->compareCoins(['bitcoin', 'ethereum', 'cardano'], 90);

DeFi Token Tracker

use Tigusigalpa\Coingecko\Facades\Coingecko;

class DeFiTracker
{
    public function trackToken(string $platform, string $contractAddress): array
    {
        // Get token data
        $tokenData = Coingecko::contract()->coin($platform, $contractAddress);
        
        // Get 7-day price chart
        $priceChart = Coingecko::contract()->marketChart(
            assetPlatform: $platform,
            contractAddress: $contractAddress,
            vsCurrency: 'usd',
            days: 7
        );
        
        return [
            'name' => $tokenData['name'],
            'symbol' => $tokenData['symbol'],
            'current_price' => $tokenData['market_data']['current_price']['usd'],
            'market_cap' => $tokenData['market_data']['market_cap']['usd'],
            'total_volume' => $tokenData['market_data']['total_volume']['usd'],
            'price_change_24h' => $tokenData['market_data']['price_change_percentage_24h'],
            'chart' => $priceChart
        ];
    }
}

// Usage - Track Uniswap (UNI) token
$tracker = new DeFiTracker();
$uniData = $tracker->trackToken('ethereum', '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984');

๐Ÿ”ง Advanced Configuration

Custom HTTP Client Options

use Tigusigalpa\Coingecko\CoingeckoClient;
use GuzzleHttp\Client;

// Create custom Guzzle client with specific options
$httpClient = new Client([
    'timeout' => 60,
    'connect_timeout' => 10,
    'verify' => true,
    'proxy' => 'http://proxy.example.com:8080'
]);

// Note: You can extend CoingeckoClient to use custom HTTP client

Error Handling

use Tigusigalpa\Coingecko\Facades\Coingecko;
use Tigusigalpa\Coingecko\Exceptions\CoingeckoException;

try {
    $price = Coingecko::simple()->price('bitcoin', 'usd');
} catch (CoingeckoException $e) {
    // Handle API errors
    Log::error('CoinGecko API Error: ' . $e->getMessage());
    
    // You can also check the status code
    $statusCode = $e->getCode();
    
    if ($statusCode === 429) {
        // Rate limit exceeded
        return response()->json(['error' => 'Rate limit exceeded'], 429);
    }
}

Rate Limiting

CoinGecko API has rate limits:

  • Free API: 10-50 calls/minute
  • Pro API: Higher limits based on your plan

The package doesn't implement automatic rate limiting, so you should implement your own caching strategy:

use Illuminate\Support\Facades\Cache;
use Tigusigalpa\Coingecko\Facades\Coingecko;

class CachedCoinGeckoService
{
    public function getPrice(string $coinId, string $currency): array
    {
        $cacheKey = "coingecko_price_{$coinId}_{$currency}";
        
        return Cache::remember($cacheKey, now()->addMinutes(5), function () use ($coinId, $currency) {
            return Coingecko::simple()->price($coinId, $currency);
        });
    }
}

๐Ÿงช Testing

composer test

๐Ÿ“ Changelog

Please see CHANGELOG for more information on what has changed recently.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ”’ Security

If you discover any security-related issues, please email sovletig@gmail.com instead of using the issue tracker.

๐Ÿ“„ License

The MIT License (MIT). Please see License File for more information.

๐Ÿ™ Credits

๐Ÿ”— Links

โฌ† back to top

Made with โค๏ธ by Igor Sazonov