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
- β 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
- PHP 8.0 or higher
- Laravel 9.x, 10.x, or 11.x (for Laravel integration)
- Guzzle HTTP client 7.x
Install the package via Composer:
composer require tigusigalpa/coingecko-phpThe package will automatically register its service provider. Publish the configuration file:
php artisan vendor:publish --tag=coingecko-configAdd your CoinGecko API credentials to your .env file:
COINGECKO_API_KEY=your-api-key-here
COINGECKO_IS_PRO=falseNote: API key is optional for free tier. Set
COINGECKO_IS_PRO=trueif you have a Pro API subscription.
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);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'));
}
}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
Get cryptocurrency prices and basic market data quickly.
// 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 price for a token on Ethereum
$tokenPrice = $coingecko->simple()->tokenPrice(
assetPlatform: 'ethereum',
contractAddresses: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', // UNI token
vsCurrencies: 'usd',
includeMarketCap: true,
include24hrVol: true
);$currencies = $coingecko->simple()->supportedVsCurrencies();
// Returns: ['usd', 'eur', 'gbp', 'jpy', ...]Access detailed coin information, market data, and historical charts.
// Get list of all coins with IDs
$coinsList = $coingecko->coins()->list();
// Include platform information
$coinsWithPlatforms = $coingecko->coins()->list(includePlatform: true);$topMovers = $coingecko->coins()->topGainersLosers(
vsCurrency: 'usd',
duration: '24h',
topCoins: 100
);
// Returns top gainers and losers with percentage changes$newCoins = $coingecko->coins()->recentlyAdded();// 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
);// 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']// Get all trading pairs for a coin
$tickers = $coingecko->coins()->tickers(
id: 'bitcoin',
exchangeIds: ['binance', 'coinbase'],
page: 1,
order: 'volume_desc'
);// Get coin data at a specific date
$historicalData = $coingecko->coins()->history(
id: 'bitcoin',
date: '30-12-2023', // DD-MM-YYYY format
localization: false
);// 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'
);// 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], ...]// 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
);Get token data using contract addresses on various blockchain platforms.
// 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.// 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
);Check API server status and monitor your API usage.
$status = $coingecko->ping()->ping();
// Returns: ['gecko_says' => '(V3) To the Moon!']$usage = $coingecko->ping()->apiUsage();
// Returns information about your API key usage and rate limitsuse 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);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;
}
}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)
];
}
}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);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');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 clientuse 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);
}
}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);
});
}
}composer testPlease see CHANGELOG for more information on what has changed recently.
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
If you discover any security-related issues, please email sovletig@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
- Igor Sazonov
- CoinGecko for providing the API
- All contributors
- **Package **: https://packagist.org/packages/tigusigalpa/coingecko-php
- Repository: https://github.com/tigusigalpa/coingecko-php
- CoinGecko API Documentation: https://docs.coingecko.com
- CoinGecko Website: https://www.coingecko.com
Made with β€οΈ by Igor Sazonov
