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;
// 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'));
}
}
// 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
$coinsWithPlatforms = $coingecko->coins()->list(
$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'
);
// 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: 'microstrategy',
coinId: 'bitcoin'
);
// Get historical treasury chart data
$chart = $coingecko->entities()->treasuryChart(
entityId: 'microstrategy',
coinId: 'bitcoin',
days: 365
);
// Get transaction history for an entity
$transactions = $coingecko->entities()->transactionHistory(
entityId: 'microstrategy',
coinId: '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
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 client
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);
}
}
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);
});
}
}