1. Go to this page and download the library: Download tigusigalpa/coingecko-php library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tigusigalpa / coingecko-php example snippets
use Tigusigalpa\Coingecko\Coingecko;
// Demo API key (or omit it when your plan permits keyless calls).
$coingecko = new Coingecko('your-demo-api-key');
$prices = $coingecko->simple()->price(
ids: ['bitcoin', 'ethereum'],
vsCurrencies: ['usd', 'eur'],
use Tigusigalpa\Coingecko\Facades\Coingecko;
// Facade: useful in a controller, command or job.
$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(): \Illuminate\View\View
{
$markets = $this->coingecko->coins()->markets('usd', perPage: 10);
return view('crypto.index', compact('markets'));
}
}
use Illuminate\Support\Facades\Cache;
use Tigusigalpa\Coingecko\Coingecko;
final class PriceService
{
public function __construct(private Coingecko $coingecko)
{
}
public function bitcoinUsd(): float
{
$price = Cache::remember('coingecko:bitcoin:usd', now()->addMinute(), function (): array {
return $this->coingecko->simple()->price('bitcoin', 'usd');
});
return (float) ($price['bitcoin']['usd'] ?? 0);
}
}
// Get price for a token on Ethereum
$tokenPrice = $coingecko->simple()->tokenPrice(
assetPlatform: 'ethereum',
contractAddresses: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', // UNI token
vsCurrencies: 'usd',
// Get list of all coins with IDs
$coinsList = $coingecko->coins()->list();
// Include platform information, including inactive coins when needed
$coinsWithPlatforms = $coingecko->coins()->list(
$topMovers = $coingecko->coins()->topGainersLosers(
vsCurrency: 'usd',
duration: '24h',
topCoins: 1000,
priceChangePercentage: '1h,24h,7d'
);
// 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'
);
// 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 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
);
// Get all asset platforms
$platforms = $coingecko->assetPlatforms()->list();
// Filter platforms
$filtered = $coingecko->assetPlatforms()->list(filter: 'nft');
// Get all tokens on a specific platform
$tokens = $coingecko->assetPlatforms()->tokenLists(
assetPlatformId: 'ethereum',
page: 1
);
// Get list of all coin categories
$categories = $coingecko->categories()->list();
// Get categories with market data
$categoriesData = $coingecko->categories()->listWithMarketData(
order: 'market_cap_desc'
);
// Available order options: market_cap_desc, market_cap_asc, name_desc, name_asc,
// market_cap_change_24h_desc, market_cap_change_24h_asc
// Get all exchanges with data
$exchanges = $coingecko->exchanges()->list(
perPage: 100,
page: 1
);
// Get simple list of exchange IDs
$exchangeIds = $coingecko->exchanges()->listIdMap();
// Get detailed data for a specific exchange
$binance = $coingecko->exchanges()->exchange('binance');
// Get all tickers for an exchange
$tickers = $coingecko->exchanges()->tickers(
id: 'binance',
coinIds: ['bitcoin', 'ethereum'],
// Get volume chart for an exchange
$volumeChart = $coingecko->exchanges()->volumeChart(
id: 'binance',
days: 30
);
// Get volume chart for specific time range
$volumeRange = $coingecko->exchanges()->volumeChartRange(
id: 'binance',
from: 1609459200,
to: 1640995200
);
// Get all derivatives tickers
$derivativesTickers = $coingecko->derivatives()->tickers(
// Get all derivatives exchanges
$derivativesExchanges = $coingecko->derivatives()->exchanges(
order: 'open_interest_btc_desc',
perPage: 100,
page: 1
);
// Get specific derivatives exchange data
$exchange = $coingecko->derivatives()->exchange(
id: 'binance_futures',
// Get simple list of derivatives exchange IDs
$exchangeIds = $coingecko->derivatives()->exchangesList();
// Get list of all entities
$entities = $coingecko->entities()->list();
// Get companies holding Bitcoin
$bitcoinHolders = $coingecko->entities()->treasuryByCoinId('bitcoin');
// Get companies holding Ethereum
$ethereumHolders = $coingecko->entities()->treasuryByCoinId('ethereum');
// Get treasury holdings for a specific entity
$treasury = $coingecko->entities()->treasuryByEntityId(
entityId: 'strategy',
holdingAmountChange: '7d,30d',
holdingChangePercentage: '7d,30d'
);
// Get historical treasury chart data
$chart = $coingecko->entities()->treasuryChart(
entityId: 'strategy',
coinId: 'bitcoin',
days: 365
);
// Get transaction history for an entity
$transactions = $coingecko->entities()->transactionHistory(
entityId: 'strategy',
coinIds: ['bitcoin'],
page: 1,
perPage: 100
);
// Get list of all NFT collections
$nfts = $coingecko->nfts()->list(
order: 'h24_volume_native_desc',
assetPlatformId: 'ethereum',
perPage: 100,
page: 1
);
// Get detailed NFT collection data
$collection = $coingecko->nfts()->collection('cryptopunks');
// Get NFT data by contract address
$nft = $coingecko->nfts()->collectionByContract(
assetPlatformId: 'ethereum',
contractAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb'
);
// Get NFT collections with market data
$nftMarkets = $coingecko->nfts()->markets(
assetPlatformId: 'ethereum',
order: 'h24_volume_native_desc',
perPage: 100,
page: 1
);
// Get market chart for NFT collection
$chart = $coingecko->nfts()->marketChart(
id: 'cryptopunks',
days: 30
);
// Get market chart by contract address
$chartByContract = $coingecko->nfts()->marketChartByContract(
assetPlatformId: 'ethereum',
contractAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
days: 30
);
// Get tickers for NFT collection
$tickers = $coingecko->nfts()->tickers('cryptopunks');
// Get Bitcoin exchange rates for all currencies
$rates = $coingecko->exchangeRates()->rates();
// Returns rates for BTC to USD, EUR, and many other currencies
// Unsubscribe from a channel
$unsubscribe = $coingecko->webSocket()->createUnsubscribeMessage(
\Tigusigalpa\Coingecko\Api\WebSocketApi::CHANNEL_SIMPLE_PRICE
);
// Your WebSocket client must handle server ping/pong control frames. There is
// no JSON ping message in the CoinGecko protocol.
$status = $coingecko->ping()->ping();
// Returns: ['gecko_says' => '(V3) To the Moon!']
$usage = $coingecko->ping()->apiUsage();
// Returns information about your API key usage and rate limits
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.0;
foreach ($holdings as $coinId => $amount) {
// A coin can disappear or be temporarily unavailable. Treat it as
// missing instead of breaking the entire portfolio page.
$price = (float) ($prices[$coinId]['usd'] ?? 0);
$totalValue += $price * $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',
} 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', 1000);
// 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\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 GuzzleHttp\Client;
use Tigusigalpa\Coingecko\Coingecko;
use Tigusigalpa\Coingecko\CoingeckoClient;
// A supplied client is used as-is, so give it the matching CoinGecko base URI.
$httpClient = new Client([
'base_uri' => CoingeckoClient::PRO_BASE_URL . '/',
'timeout' => 15,
'connect_timeout' => 5,
'verify' => true,
]);
// The package still supplies the Accept and API-key headers for each request.
$coingecko = new Coingecko('your-pro-api-key', true, $httpClient);
use Illuminate\Support\Facades\Log;
use Tigusigalpa\Coingecko\Facades\Coingecko;
use Tigusigalpa\Coingecko\Exceptions\CoingeckoException;
try {
$price = Coingecko::simple()->price('bitcoin', 'usd');
} catch (CoingeckoException $e) {
Log::warning('CoinGecko API request failed', [
'message' => $e->getMessage(),
'status' => $e->getStatusCode(),
]);
$statusCode = $e->getStatusCode();
if ($statusCode === 429) {
// Rate limit exceeded
return response()->json(['error' => 'Rate limit exceeded'], 429);
}
}
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()->addMinute(), function () use ($coinId, $currency) {
return Coingecko::simple()->price($coinId, $currency);
});
}
}