coingecko

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 7 Imported by: 0

README ΒΆ

CoinGecko Go API Client - Cryptocurrency Data Integration Library

CoinGecko Golang SDK

Go Version License GitHub

The most comprehensive Golang library for CoinGecko API integration - Access real-time cryptocurrency prices, market data, historical charts, DeFi analytics, NFT data, and more with a type-safe, production-ready Go client.

Perfect for building crypto trading bots, portfolio trackers, market analysis tools, DeFi applications, and blockchain data platforms.

Features β€’ Installation β€’ Quick Start β€’ Getting Started β€’ API Documentation β€’ Examples


🌟 Why Choose CoinGecko Go Client?

This Go cryptocurrency API library provides enterprise-grade access to CoinGecko's comprehensive crypto market data. Whether you're building a Bitcoin price tracker, Ethereum market analyzer, DeFi portfolio manager, or crypto trading bot, this library offers everything you need:

  • 14+ API Endpoint Groups covering coins, exchanges, DeFi, NFTs, derivatives, and more
  • Real-time WebSocket Support for live cryptocurrency price feeds
  • Historical Data Access for backtesting trading strategies and market analysis
  • Smart Contract Integration for ERC-20 tokens and multi-chain assets
  • Production-Ready with comprehensive error handling and rate limiting support
  • Type-Safe Go implementation with zero runtime surprises
  • Well-Tested with unit tests and real-world examples

πŸš€ Features

Core Capabilities
  • βœ… Complete API Coverage - All CoinGecko API v3 endpoints implemented (Simple, Coins, Contracts, Exchanges, DeFi, NFTs, and more)
  • πŸ” Pro API Support - Full support for CoinGecko Pro API with authentication and higher rate limits
  • πŸ’Ž Modern Go - Built with Go 1.21+ features, generics support, and idiomatic Go patterns
  • πŸ›‘οΈ Type Safety - Strongly typed parameters and return values prevent runtime errors
  • πŸ“¦ Minimal Dependencies - Only standard library (plus gorilla/websocket for WebSocket support)
  • πŸ”„ Flexible Configuration - Customizable HTTP client, timeouts, retry logic, and middleware
  • 🎨 Clean API Design - Intuitive, chainable methods for excellent developer experience
  • ⚑ High Performance - Efficient HTTP client with connection pooling and concurrent request support
  • πŸ“š Comprehensive Documentation - Detailed examples, API reference, and integration guides
Cryptocurrency Data Access
  • πŸ’° Price Data - Real-time and historical prices for 10,000+ cryptocurrencies
  • πŸ“Š Market Data - Market cap, volume, supply, price changes, and market dominance
  • πŸ“ˆ Charts & OHLC - Historical price charts, candlestick data, and technical indicators
  • πŸ” Search & Discovery - Search coins, trending cryptocurrencies, and new listings
  • 🏦 Exchange Data - Trading volumes, tickers, and exchange rankings
  • πŸ’Ή Derivatives - Futures, perpetuals, and derivatives market data
  • 🎨 NFT Analytics - NFT collection data, floor prices, and trading volumes
  • πŸ›οΈ Treasury Data - Corporate and institutional crypto holdings
  • 🌐 Global Metrics - Total market cap, DeFi TVL, and market statistics

πŸ“‹ Requirements

  • Go 1.21 or higher (supports Go 1.21, 1.22, and later)
  • Operating Systems: Linux, macOS, Windows
  • Optional: CoinGecko API key for Pro tier access

πŸ“¦ Installation

Install the CoinGecko Golang client using Go modules:

go get github.com/tigusigalpa/coingecko-go

Import in your Go application:

import coingecko "github.com/tigusigalpa/coingecko-go"

🎯 Quick Start

Get up and running with the CoinGecko Golang client in under 60 seconds:

Basic Usage - Free API
package main

import (
    "fmt"
    "log"
    
    coingecko "github.com/tigusigalpa/coingecko-go"
)

func main() {
    // Create a new CoinGecko client (no API key needed for free tier)
    cg := coingecko.New()
    
    // Get Bitcoin price in USD
    prices, err := cg.Simple().Price(
        []string{"bitcoin"},
        []string{"usd"},
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Bitcoin: $%.2f\n", prices["bitcoin"]["usd"])
}
Pro API with Authentication

Unlock higher rate limits and advanced features with CoinGecko Pro:

cg := coingecko.New(
    coingecko.WithAPIKey("your-api-key-here"),
    coingecko.WithProAPI(true),
)
Advanced Configuration

Customize the HTTP client for production environments:

import (
    "net/http"
    "time"
)

// Configure custom HTTP client with timeout and retry logic
httpClient := &http.Client{
    Timeout: 60 * time.Second,
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
        IdleConnTimeout:     90 * time.Second,
    },
}

cg := coingecko.New(
    coingecko.WithHTTPClient(httpClient),
    coingecko.WithAPIKey("your-api-key"),
    coingecko.WithProAPI(true),
    coingecko.WithTimeout(60 * time.Second),
)

πŸ“˜ Getting Started Guide

Common Use Cases
1. Get Current Cryptocurrency Prices

Fetch real-time prices for single or multiple cryptocurrencies:

// Single coin, single currency
prices, err := cg.Simple().Price(
    []string{"bitcoin"},
    []string{"usd"},
    nil,
)

// Multiple coins with market data
prices, err := cg.Simple().Price(
    []string{"bitcoin", "ethereum", "cardano", "solana"},
    []string{"usd", "eur", "gbp"},
    &coingecko.SimplePriceOptions{
        IncludeMarketCap:   true,
        Include24hrVol:     true,
        Include24hrChange:  true,
    },
)
2. Get Market Data and Rankings

Access comprehensive market data for crypto assets:

perPage := 10
page := 1

markets, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
    Order:   stringPtr("market_cap_desc"),
    PerPage: &perPage,
    Page:    &page,
})
3. Get Historical Price Data

Retrieve historical data for backtesting and analysis:

// Market chart with price, volume, and market cap
chartData, err := cg.Coins().MarketChart(
    "bitcoin",
    "usd",
    "30", // days: 1, 7, 14, 30, 90, 180, 365, "max"
    nil,
)

// OHLC candlestick data for technical analysis
ohlc, err := cg.Coins().OHLC("bitcoin", "usd", "7", nil)

Discover trending coins and search the crypto market:

// Search for specific cryptocurrency
results, err := cg.Search().Search("bitcoin")

// Get trending cryptocurrencies
trending, err := cg.Search().Trending()
5. Smart Contract Token Data

Access ERC-20 and other token data by contract address:

// Get token data by contract address
tokenData, err := cg.Contract().Coin(
    "ethereum",
    "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // Uniswap (UNI) token
)
Helper Functions for Optional Parameters

When working with optional parameters, use pointer helpers:

func stringPtr(s string) *string {
    return &s
}

func intPtr(i int) *int {
    return &i
}

// Usage example
category := "decentralized-finance-defi"
perPage := 50

markets, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
    Category: &category,
    PerPage:  &perPage,
})
Error Handling Best Practices

Always implement proper error handling in production code:

data, err := cg.Coins().List(false)
if err != nil {
    log.Printf("CoinGecko API error: %v", err)
    // Implement retry logic or fallback mechanism
    return
}
Rate Limiting and Caching

Implement caching to respect API rate limits and improve performance:

import (
    "time"
    "sync"
)

type Cache struct {
    data      map[string]interface{}
    timestamp map[string]time.Time
    mutex     sync.RWMutex
    ttl       time.Duration
}

func NewCache(ttl time.Duration) *Cache {
    return &Cache{
        data:      make(map[string]interface{}),
        timestamp: make(map[string]time.Time),
        ttl:       ttl,
    }
}

func (c *Cache) Get(key string) (interface{}, bool) {
    c.mutex.RLock()
    defer c.mutex.RUnlock()
    
    data, exists := c.data[key]
    if !exists {
        return nil, false
    }
    
    if time.Since(c.timestamp[key]) > c.ttl {
        return nil, false
    }
    
    return data, true
}

func (c *Cache) Set(key string, value interface{}) {
    c.mutex.Lock()
    defer c.mutex.Unlock()
    
    c.data[key] = value
    c.timestamp[key] = time.Now()
}

πŸ“– API Documentation

Complete API Endpoint Reference

The CoinGecko Go client provides access to all major cryptocurrency data endpoints, organized into 14 logical API groups for easy navigation:


Simple API

Get cryptocurrency prices and basic market data quickly.

Get Coin Prices
// Single coin, single currency
prices, err := cg.Simple().Price(
    []string{"bitcoin"},
    []string{"usd"},
    nil,
)

// Multiple coins with additional data
prices, err := cg.Simple().Price(
    []string{"bitcoin", "ethereum", "cardano"},
    []string{"usd", "eur", "gbp"},
    &coingecko.SimplePriceOptions{
        IncludeMarketCap:   true,
        Include24hrVol:     true,
        Include24hrChange:  true,
    },
)
Get Token Prices by Contract Address
tokenPrices, err := cg.Simple().TokenPrice(
    "ethereum",
    []string{"0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"}, // UNI token
    []string{"usd"},
    &coingecko.TokenPriceOptions{
        IncludeMarketCap: true,
        Include24hrVol:   true,
    },
)
Get Supported Currencies
currencies, err := cg.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, err := cg.Coins().List(false)

// Include platform information
coinsWithPlatforms, err := cg.Coins().List(true)
Top Gainers & Losers
duration := "24h"
topCoins := 100

topMovers, err := cg.Coins().TopGainersLosers("usd", &duration, &topCoins)
Recently Added Coins
newCoins, err := cg.Coins().RecentlyAdded()
Coins Market Data
// Get top 100 coins by market cap
perPage := 100
page := 1
priceChange := "1h,24h,7d"

markets, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
    Order:                 stringPtr("market_cap_desc"),
    PerPage:               &perPage,
    Page:                  &page,
    Sparkline:             true,
    PriceChangePercentage: &priceChange,
})

// Filter by specific coins
markets, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
    IDs: []string{"bitcoin", "ethereum", "cardano"},
})

// Filter by category
category := "decentralized-finance-defi"
markets, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
    Category: &category,
    PerPage:  &perPage,
})
Detailed Coin Data
bitcoin, err := cg.Coins().Coin("bitcoin", &coingecko.CoinOptions{
    Localization:  true,
    Tickers:       true,
    MarketData:    true,
    CommunityData: true,
    DeveloperData: true,
    Sparkline:     true,
})
Market Chart Data
// Get price, market cap, and volume chart data
chartData, err := cg.Coins().MarketChart(
    "bitcoin",
    "usd",
    "30", // days: 1, 7, 14, 30, 90, 180, 365, "max"
    &coingecko.MarketChartOptions{
        Interval: stringPtr("daily"),
    },
)

// Get chart data for specific time range
rangeData, err := cg.Coins().MarketChartRange(
    "ethereum",
    "usd",
    1609459200, // Unix timestamp
    1640995200, // Unix timestamp
    nil,
)
OHLC Chart Data
ohlc, err := cg.Coins().OHLC("bitcoin", "usd", "7", nil)
// Returns: [][]float64 - [[timestamp, open, high, low, close], ...]

Contract API

Get token data using contract addresses on various blockchain platforms.

// Get comprehensive token data
tokenData, err := cg.Contract().Coin(
    "ethereum",
    "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984", // UNI token
)

// Get price chart for a token
tokenChart, err := cg.Contract().MarketChart(
    "ethereum",
    "0x1f9840a85d5af5bf1d1762f925bdaddc4201f984",
    "usd",
    "30",
)

Asset Platforms API
// Get all asset platforms
platforms, err := cg.AssetPlatforms().List(nil)

// Filter platforms
filter := "nft"
filtered, err := cg.AssetPlatforms().List(&filter)

// Get all tokens on a specific platform
tokens, err := cg.AssetPlatforms().TokenLists("ethereum", nil)

Categories API
// Get list of all coin categories
categories, err := cg.Categories().List()

// Get categories with market data
order := "market_cap_desc"
categoriesData, err := cg.Categories().ListWithMarketData(&order)

Exchanges API
// Get all exchanges with data
perPage := 100
page := 1
exchanges, err := cg.Exchanges().List(&coingecko.ExchangesListOptions{
    PerPage: &perPage,
    Page:    &page,
})

// Get detailed data for a specific exchange
binance, err := cg.Exchanges().Exchange("binance")

// Get exchange tickers
tickers, err := cg.Exchanges().Tickers("binance", &coingecko.ExchangeTickersOptions{
    CoinIDs: []string{"bitcoin", "ethereum"},
    Page:    &page,
})

// Get volume chart
volumeChart, err := cg.Exchanges().VolumeChart("binance", 30)

Global API
// Get global crypto market data
globalData, err := cg.Global().Crypto()

// Get global DeFi market data
defiData, err := cg.Global().DeFi()

// Get global market cap chart
marketCapChart, err := cg.Global().MarketCapChart(30, "usd")

Search API
// Search for coins, exchanges, categories, and NFTs
results, err := cg.Search().Search("bitcoin")

// Get trending searches
trending, err := cg.Search().Trending()

Ping API
// Check server status
status, err := cg.Ping().Ping()
fmt.Println(status.GeckoSays) // "(V3) To the Moon!"

// Check API usage (Pro API only)
usage, err := cg.Ping().APIUsage()


πŸ’‘ Real-World Examples

Building a Cryptocurrency Portfolio Tracker

Track your crypto portfolio value in real-time with automatic price updates:

package main

import (
    "fmt"
    "log"
    
    coingecko "github.com/tigusigalpa/coingecko-go"
)

func main() {
    cg := coingecko.New()
    
    // Portfolio holdings
    holdings := map[string]float64{
        "bitcoin":  0.5,
        "ethereum": 10,
        "cardano":  1000,
    }
    
    // Get coin IDs
    coinIDs := make([]string, 0, len(holdings))
    for coinID := range holdings {
        coinIDs = append(coinIDs, coinID)
    }
    
    // Get prices
    prices, err := cg.Simple().Price(coinIDs, []string{"usd"}, nil)
    if err != nil {
        log.Fatal(err)
    }
    
    // Calculate total value
    totalValue := 0.0
    for coinID, amount := range holdings {
        price := prices[coinID]["usd"].(float64)
        totalValue += price * amount
    }
    
    fmt.Printf("Portfolio Value: $%.2f\n", totalValue)
}
Building a Cryptocurrency Price Alert System

Create automated price alerts for Bitcoin, Ethereum, and other cryptocurrencies:

package main

import (
    "fmt"
    "log"
    
    coingecko "github.com/tigusigalpa/coingecko-go"
)

type Alert struct {
    CoinID      string
    TargetPrice float64
    Type        string // "above" or "below"
}

func checkAlerts(cg *coingecko.CoinGecko, alerts []Alert) []Alert {
    // Get unique coin IDs
    coinIDs := make([]string, 0, len(alerts))
    seen := make(map[string]bool)
    for _, alert := range alerts {
        if !seen[alert.CoinID] {
            coinIDs = append(coinIDs, alert.CoinID)
            seen[alert.CoinID] = true
        }
    }
    
    // Get prices
    prices, err := cg.Simple().Price(coinIDs, []string{"usd"}, nil)
    if err != nil {
        log.Fatal(err)
    }
    
    // Check alerts
    triggered := []Alert{}
    for _, alert := range alerts {
        currentPrice := prices[alert.CoinID]["usd"].(float64)
        
        if alert.Type == "above" && currentPrice >= alert.TargetPrice {
            triggered = append(triggered, alert)
        } else if alert.Type == "below" && currentPrice <= alert.TargetPrice {
            triggered = append(triggered, alert)
        }
    }
    
    return triggered
}

func main() {
    cg := coingecko.New()
    
    alerts := []Alert{
        {CoinID: "bitcoin", TargetPrice: 50000, Type: "above"},
        {CoinID: "ethereum", TargetPrice: 3000, Type: "below"},
    }
    
    triggered := checkAlerts(cg, alerts)
    fmt.Printf("Triggered alerts: %d\n", len(triggered))
}
Crypto Market Analysis Dashboard

Build a comprehensive cryptocurrency market analysis tool:

package main

import (
    "fmt"
    "log"
    
    coingecko "github.com/tigusigalpa/coingecko-go"
)

func main() {
    cg := coingecko.New()
    
    // Get top 10 coins by market cap
    perPage := 10
    page := 1
    priceChange := "1h,24h,7d,30d"
    
    topCoins, err := cg.Coins().Markets("usd", &coingecko.MarketsOptions{
        Order:                 stringPtr("market_cap_desc"),
        PerPage:               &perPage,
        Page:                  &page,
        Sparkline:             true,
        PriceChangePercentage: &priceChange,
    })
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println("Top 10 Cryptocurrencies by Market Cap:")
    for i, coin := range topCoins {
        name := coin["name"].(string)
        price := coin["current_price"].(float64)
        marketCap := coin["market_cap"].(float64)
        
        fmt.Printf("%d. %s: $%.2f (Market Cap: $%.0f)\n", 
            i+1, name, price, marketCap)
    }
}

func stringPtr(s string) *string {
    return &s
}
Running the Examples

The package includes 4 production-ready example applications:

# Basic cryptocurrency price lookup
cd examples/basic && go run main.go

# Portfolio value tracker
cd examples/portfolio && go run main.go

# Market analysis with top gainers/losers
cd examples/market_analysis && go run main.go

# DeFi token tracker with contract data
cd examples/defi_tracker && go run main.go

πŸ”§ Production Best Practices

Error Handling
prices, err := cg.Simple().Price(
    []string{"bitcoin"},
    []string{"usd"},
    nil,
)
if err != nil {
    log.Printf("CoinGecko API Error: %v", err)
    // Handle error appropriately
    return
}
Rate Limiting and Performance Optimization

Understanding and respecting CoinGecko API rate limits is crucial for production applications:

Rate Limits by Tier
  • Free API: 10-50 calls/minute (suitable for personal projects and testing)
  • Pro API: Higher limits based on your subscription plan (recommended for production)
  • Enterprise: Custom rate limits for high-volume applications
Implementing Smart Caching

Reduce API calls and improve response times with intelligent caching:

import (
    "time"
    "sync"
)

type CachedPrice struct {
    Price     map[string]map[string]interface{}
    Timestamp time.Time
}

var (
    cache      = make(map[string]*CachedPrice)
    cacheMutex sync.RWMutex
    cacheTTL   = 5 * time.Minute
)

func getCachedPrice(cg *coingecko.CoinGecko, coinID, currency string) (map[string]map[string]interface{}, error) {
    cacheKey := fmt.Sprintf("%s_%s", coinID, currency)
    
    cacheMutex.RLock()
    cached, exists := cache[cacheKey]
    cacheMutex.RUnlock()
    
    if exists && time.Since(cached.Timestamp) < cacheTTL {
        return cached.Price, nil
    }
    
    // Fetch fresh data
    prices, err := cg.Simple().Price([]string{coinID}, []string{currency}, nil)
    if err != nil {
        return nil, err
    }
    
    // Update cache
    cacheMutex.Lock()
    cache[cacheKey] = &CachedPrice{
        Price:     prices,
        Timestamp: time.Now(),
    }
    cacheMutex.Unlock()
    
    return prices, nil
}

πŸ§ͺ Testing and Quality Assurance

Run the comprehensive test suite to ensure reliability:

# Run all tests
go test ./...

# Run tests with coverage report
go test -v -race -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

# Run tests with verbose output
go test -v ./...

# Use Makefile for convenience
make test
Building the Package
# Build the package
go build ./...

# Format code
go fmt ./...

# Run linter
go vet ./...

# Or use Makefile
make build
make lint

🀝 Contributing to CoinGecko Go Client

We welcome contributions from the cryptocurrency and Go developer community! Whether you're fixing bugs, adding new features, improving documentation, or creating examples, your help is appreciated.

How to Contribute
  1. Fork the repository on GitHub
  2. Create your feature branch: git checkout -b feature/amazing-feature
  3. Make your changes with clear, well-documented code
  4. Add tests for new functionality
  5. Run the test suite: make test
  6. Commit your changes: git commit -m 'Add cryptocurrency trading bot example'
  7. Push to your branch: git push origin feature/amazing-feature
  8. Open a Pull Request with a clear description of your changes
Contribution Ideas
  • Add more real-world examples (trading bots, arbitrage tools, analytics dashboards)
  • Improve error handling and retry logic
  • Add support for new CoinGecko API endpoints
  • Enhance documentation with tutorials and guides
  • Optimize performance and reduce memory usage
  • Add integration tests with mock API responses

See CONTRIBUTING.md for detailed guidelines.

πŸ”’ Security and API Key Management

Protecting Your API Keys

When using CoinGecko Pro API, always protect your API keys:

// βœ… Good: Use environment variables
apiKey := os.Getenv("COINGECKO_API_KEY")
cg := coingecko.New(
    coingecko.WithAPIKey(apiKey),
    coingecko.WithProAPI(true),
)

// ❌ Bad: Never hardcode API keys
// cg := coingecko.New(coingecko.WithAPIKey("hardcoded-key-here"))
Reporting Security Issues

If you discover any security vulnerabilities or issues related to API key handling, cryptocurrency data integrity, or other security concerns, please email sovletig@gmail.com directly instead of using the public issue tracker. We take security seriously and will respond promptly.

πŸ“„ License

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

πŸ™ Credits and Acknowledgments

  • Author: Igor Sazonov - Go cryptocurrency developer
  • CoinGecko: CoinGecko.com - World's largest independent cryptocurrency data aggregator
  • Contributors: All developers who have contributed to this open-source project
  • Community: Go developers and cryptocurrency enthusiasts worldwide
Project Resources
CoinGecko Resources
Go Resources

πŸ“Š Use Cases and Applications

This Go library is perfect for building:

  • πŸ“ˆ Cryptocurrency Trading Bots - Automated trading with real-time price data
  • πŸ’Ό Portfolio Management Apps - Track and analyze crypto investments
  • πŸ“Š Market Analysis Tools - Technical analysis and market research platforms
  • πŸ”” Price Alert Systems - Real-time cryptocurrency price notifications
  • πŸ“± Mobile Apps - iOS and Android crypto apps with Go backends
  • 🌐 Web Dashboards - Crypto market dashboards and analytics platforms
  • πŸ€– Telegram/Discord Bots - Crypto price bots for social platforms
  • πŸ“‰ Backtesting Systems - Historical data analysis for trading strategies
  • 🏦 DeFi Applications - Decentralized finance tools and platforms
  • 🎨 NFT Analytics - NFT market tracking and analysis tools

🏷️ Keywords

Go cryptocurrency API, CoinGecko Go client, Bitcoin price API Go, Ethereum market data Go, crypto trading bot Go, DeFi API Go, NFT data API, cryptocurrency portfolio tracker, Go blockchain library, crypto market analysis Go, real-time crypto prices, historical cryptocurrency data, Go crypto SDK


Documentation ΒΆ

Overview ΒΆ

Package coingecko provides a comprehensive Go client for the CoinGecko API.

CoinGecko is a cryptocurrency data aggregation platform that provides real-time pricing, market data, historical charts, and more for thousands of cryptocurrencies.

Features ΒΆ

  • Complete API coverage for all CoinGecko endpoints
  • Support for both Free and Pro API tiers
  • Type-safe API with strongly typed parameters
  • Configurable HTTP client with custom options
  • WebSocket support for real-time data
  • Comprehensive error handling

Installation ΒΆ

go get github.com/tigusigalpa/coingecko-go

Quick Start ΒΆ

Basic usage with the free API:

package main

import (
    "fmt"
    "log"
    coingecko "github.com/tigusigalpa/coingecko-go"
)

func main() {
    cg := coingecko.New()

    prices, err := cg.Simple().Price(
        []string{"bitcoin"},
        []string{"usd"},
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Bitcoin: $%.2f\n", prices["bitcoin"]["usd"])
}

Using Pro API ΒΆ

To use the Pro API with authentication:

cg := coingecko.New(
    coingecko.WithAPIKey("your-api-key"),
    coingecko.WithProAPI(true),
)

Custom HTTP Client ΒΆ

You can provide a custom HTTP client with specific settings:

import (
    "net/http"
    "time"
)

httpClient := &http.Client{
    Timeout: 60 * time.Second,
}

cg := coingecko.New(
    coingecko.WithHTTPClient(httpClient),
)

API Endpoints ΒΆ

The client provides access to all CoinGecko API endpoints organized into logical 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
  • Asset Platforms API: Blockchain platforms and token lists
  • Categories API: Coin categories with market data
  • Exchanges API: Exchange data, tickers, and volume charts
  • Derivatives API: Derivatives market data
  • Entities API: Crypto treasury holdings
  • NFTs API: NFT collections and market data
  • Exchange Rates API: BTC exchange rates
  • Search API: Search and trending data
  • Global API: Global market statistics
  • WebSocket API: Real-time data subscriptions
  • Ping API: Server status and API usage

Error Handling ΒΆ

All API methods return an error as the last return value. Always check for errors:

data, err := cg.Coins().List(false)
if err != nil {
    log.Printf("API error: %v", err)
    return
}

Rate Limiting ΒΆ

Be aware of CoinGecko's rate limits:

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

Implement caching to avoid hitting rate limits.

More Information ΒΆ

For detailed documentation and examples, visit: https://github.com/tigusigalpa/coingecko-go

CoinGecko API documentation: https://docs.coingecko.com

Index ΒΆ

Constants ΒΆ

View Source
const (
	BaseURLFree = "https://api.coingecko.com/api/v3"
	BaseURLPro  = "https://pro-api.coingecko.com/api/v3"
)
View Source
const (
	WebSocketURLPro = "wss://ws-pro.coingecko.com/v1"
)

Variables ΒΆ

This section is empty.

Functions ΒΆ

This section is empty.

Types ΒΆ

type AssetPlatform ΒΆ

type AssetPlatform struct {
	ID              string  `json:"id"`
	ChainIdentifier *int    `json:"chain_identifier,omitempty"`
	Name            string  `json:"name"`
	Shortname       string  `json:"shortname"`
	NativeCoinID    string  `json:"native_coin_id,omitempty"`
	ImageURL        *string `json:"image,omitempty"`
}

type AssetPlatformsAPI ΒΆ

type AssetPlatformsAPI struct {
	// contains filtered or unexported fields
}

func (*AssetPlatformsAPI) List ΒΆ

func (a *AssetPlatformsAPI) List(filter *string) ([]AssetPlatform, error)

func (*AssetPlatformsAPI) TokenLists ΒΆ

func (a *AssetPlatformsAPI) TokenLists(assetPlatformID string, page *int) (map[string]interface{}, error)

type CategoriesAPI ΒΆ

type CategoriesAPI struct {
	// contains filtered or unexported fields
}

func (*CategoriesAPI) List ΒΆ

func (c *CategoriesAPI) List() ([]Category, error)

func (*CategoriesAPI) ListWithMarketData ΒΆ

func (c *CategoriesAPI) ListWithMarketData(order *string) ([]map[string]interface{}, error)

type Category ΒΆ

type Category struct {
	CategoryID string `json:"category_id"`
	Name       string `json:"name"`
}

type Client ΒΆ

type Client struct {
	// contains filtered or unexported fields
}

func NewClient ΒΆ

func NewClient(options ...ClientOption) *Client

type ClientOption ΒΆ

type ClientOption func(*Client)

func WithAPIKey ΒΆ

func WithAPIKey(apiKey string) ClientOption

func WithHTTPClient ΒΆ

func WithHTTPClient(httpClient *http.Client) ClientOption

func WithProAPI ΒΆ

func WithProAPI(isPro bool) ClientOption

func WithTimeout ΒΆ

func WithTimeout(timeout time.Duration) ClientOption

type CoinGecko ΒΆ

type CoinGecko struct {
	// contains filtered or unexported fields
}

func New ΒΆ

func New(options ...ClientOption) *CoinGecko

func (*CoinGecko) AssetPlatforms ΒΆ

func (cg *CoinGecko) AssetPlatforms() *AssetPlatformsAPI

func (*CoinGecko) Categories ΒΆ

func (cg *CoinGecko) Categories() *CategoriesAPI

func (*CoinGecko) Coins ΒΆ

func (cg *CoinGecko) Coins() *CoinsAPI

func (*CoinGecko) Contract ΒΆ

func (cg *CoinGecko) Contract() *ContractAPI

func (*CoinGecko) Derivatives ΒΆ

func (cg *CoinGecko) Derivatives() *DerivativesAPI

func (*CoinGecko) Entities ΒΆ

func (cg *CoinGecko) Entities() *EntitiesAPI

func (*CoinGecko) ExchangeRates ΒΆ

func (cg *CoinGecko) ExchangeRates() *ExchangeRatesAPI

func (*CoinGecko) Exchanges ΒΆ

func (cg *CoinGecko) Exchanges() *ExchangesAPI

func (*CoinGecko) Global ΒΆ

func (cg *CoinGecko) Global() *GlobalAPI

func (*CoinGecko) NFTs ΒΆ

func (cg *CoinGecko) NFTs() *NFTsAPI

func (*CoinGecko) Ping ΒΆ

func (cg *CoinGecko) Ping() *PingAPI

func (*CoinGecko) Search ΒΆ

func (cg *CoinGecko) Search() *SearchAPI

func (*CoinGecko) Simple ΒΆ

func (cg *CoinGecko) Simple() *SimpleAPI

func (*CoinGecko) WebSocket ΒΆ

func (cg *CoinGecko) WebSocket() *WebSocketAPI

type CoinListItem ΒΆ

type CoinListItem struct {
	ID        string            `json:"id"`
	Symbol    string            `json:"symbol"`
	Name      string            `json:"name"`
	Platforms map[string]string `json:"platforms,omitempty"`
}

type CoinOptions ΒΆ

type CoinOptions struct {
	Localization  bool
	Tickers       bool
	MarketData    bool
	CommunityData bool
	DeveloperData bool
	Sparkline     bool
}

type CoinsAPI ΒΆ

type CoinsAPI struct {
	// contains filtered or unexported fields
}

func (*CoinsAPI) CirculatingSupplyChart ΒΆ

func (c *CoinsAPI) CirculatingSupplyChart(id string, days string, interval *string) (map[string]interface{}, error)

func (*CoinsAPI) CirculatingSupplyChartRange ΒΆ

func (c *CoinsAPI) CirculatingSupplyChartRange(id string, from int64, to int64) (map[string]interface{}, error)

func (*CoinsAPI) Coin ΒΆ

func (c *CoinsAPI) Coin(id string, options *CoinOptions) (map[string]interface{}, error)

func (*CoinsAPI) History ΒΆ

func (c *CoinsAPI) History(id string, date string, localization bool) (map[string]interface{}, error)

func (*CoinsAPI) List ΒΆ

func (c *CoinsAPI) List(includePlatform bool) ([]CoinListItem, error)

func (*CoinsAPI) MarketChart ΒΆ

func (c *CoinsAPI) MarketChart(id string, vsCurrency string, days string, options *MarketChartOptions) (map[string]interface{}, error)

func (*CoinsAPI) MarketChartRange ΒΆ

func (c *CoinsAPI) MarketChartRange(id string, vsCurrency string, from int64, to int64, precision *string) (map[string]interface{}, error)

func (*CoinsAPI) Markets ΒΆ

func (c *CoinsAPI) Markets(vsCurrency string, options *MarketsOptions) ([]map[string]interface{}, error)

func (*CoinsAPI) OHLC ΒΆ

func (c *CoinsAPI) OHLC(id string, vsCurrency string, days string, precision *string) ([][]float64, error)

func (*CoinsAPI) RecentlyAdded ΒΆ

func (c *CoinsAPI) RecentlyAdded() ([]map[string]interface{}, error)

func (*CoinsAPI) Tickers ΒΆ

func (c *CoinsAPI) Tickers(id string, options *TickersOptions) (map[string]interface{}, error)

func (*CoinsAPI) TopGainersLosers ΒΆ

func (c *CoinsAPI) TopGainersLosers(vsCurrency string, duration *string, topCoins *int) (map[string]interface{}, error)

func (*CoinsAPI) TotalSupplyChart ΒΆ

func (c *CoinsAPI) TotalSupplyChart(id string, days string, interval *string) (map[string]interface{}, error)

func (*CoinsAPI) TotalSupplyChartRange ΒΆ

func (c *CoinsAPI) TotalSupplyChartRange(id string, from int64, to int64) (map[string]interface{}, error)

type ContractAPI ΒΆ

type ContractAPI struct {
	// contains filtered or unexported fields
}

func (*ContractAPI) Coin ΒΆ

func (c *ContractAPI) Coin(assetPlatform string, contractAddress string) (map[string]interface{}, error)

func (*ContractAPI) MarketChart ΒΆ

func (c *ContractAPI) MarketChart(assetPlatform string, contractAddress string, vsCurrency string, days string) (map[string]interface{}, error)

func (*ContractAPI) MarketChartRange ΒΆ

func (c *ContractAPI) MarketChartRange(assetPlatform string, contractAddress string, vsCurrency string, from int64, to int64) (map[string]interface{}, error)

type DerivativesAPI ΒΆ

type DerivativesAPI struct {
	// contains filtered or unexported fields
}

func (*DerivativesAPI) Exchange ΒΆ

func (d *DerivativesAPI) Exchange(id string, includeTickers *string) (map[string]interface{}, error)

func (*DerivativesAPI) Exchanges ΒΆ

func (d *DerivativesAPI) Exchanges(options *DerivativesExchangesOptions) ([]map[string]interface{}, error)

func (*DerivativesAPI) ExchangesList ΒΆ

func (d *DerivativesAPI) ExchangesList() ([]map[string]interface{}, error)

func (*DerivativesAPI) Tickers ΒΆ

func (d *DerivativesAPI) Tickers(includeTickers *string) ([]map[string]interface{}, error)

type DerivativesExchangesOptions ΒΆ

type DerivativesExchangesOptions struct {
	Order   *string
	PerPage *int
	Page    *int
}

type EntitiesAPI ΒΆ

type EntitiesAPI struct {
	// contains filtered or unexported fields
}

func (*EntitiesAPI) List ΒΆ

func (e *EntitiesAPI) List() ([]map[string]interface{}, error)

func (*EntitiesAPI) TransactionHistory ΒΆ

func (e *EntitiesAPI) TransactionHistory(entityID string, coinID string, options *TransactionHistoryOptions) (map[string]interface{}, error)

func (*EntitiesAPI) TreasuryByCoinID ΒΆ

func (e *EntitiesAPI) TreasuryByCoinID(coinID string) (map[string]interface{}, error)

func (*EntitiesAPI) TreasuryByEntityID ΒΆ

func (e *EntitiesAPI) TreasuryByEntityID(entityID string, coinID string) (map[string]interface{}, error)

func (*EntitiesAPI) TreasuryChart ΒΆ

func (e *EntitiesAPI) TreasuryChart(entityID string, coinID string, days int) (map[string]interface{}, error)

type ExchangeRatesAPI ΒΆ

type ExchangeRatesAPI struct {
	// contains filtered or unexported fields
}

func (*ExchangeRatesAPI) Rates ΒΆ

func (e *ExchangeRatesAPI) Rates() (map[string]interface{}, error)

type ExchangeTickersOptions ΒΆ

type ExchangeTickersOptions struct {
	CoinIDs             []string
	Page                *int
	Depth               *string
	Order               *string
}

type ExchangesAPI ΒΆ

type ExchangesAPI struct {
	// contains filtered or unexported fields
}

func (*ExchangesAPI) Exchange ΒΆ

func (e *ExchangesAPI) Exchange(id string) (map[string]interface{}, error)

func (*ExchangesAPI) List ΒΆ

func (e *ExchangesAPI) List(options *ExchangesListOptions) ([]map[string]interface{}, error)

func (*ExchangesAPI) ListIDMap ΒΆ

func (e *ExchangesAPI) ListIDMap() ([]map[string]interface{}, error)

func (*ExchangesAPI) Tickers ΒΆ

func (e *ExchangesAPI) Tickers(id string, options *ExchangeTickersOptions) (map[string]interface{}, error)

func (*ExchangesAPI) VolumeChart ΒΆ

func (e *ExchangesAPI) VolumeChart(id string, days int) ([][]interface{}, error)

func (*ExchangesAPI) VolumeChartRange ΒΆ

func (e *ExchangesAPI) VolumeChartRange(id string, from int64, to int64) ([][]interface{}, error)

type ExchangesListOptions ΒΆ

type ExchangesListOptions struct {
	PerPage *int
	Page    *int
}

type GlobalAPI ΒΆ

type GlobalAPI struct {
	// contains filtered or unexported fields
}

func (*GlobalAPI) Crypto ΒΆ

func (g *GlobalAPI) Crypto() (map[string]interface{}, error)

func (*GlobalAPI) DeFi ΒΆ

func (g *GlobalAPI) DeFi() (map[string]interface{}, error)

func (*GlobalAPI) MarketCapChart ΒΆ

func (g *GlobalAPI) MarketCapChart(days int, vsCurrency string) (map[string]interface{}, error)

type MarketChartOptions ΒΆ

type MarketChartOptions struct {
	Interval  *string
	Precision *string
}

type MarketsOptions ΒΆ

type MarketsOptions struct {
	IDs                   []string
	Category              *string
	Order                 *string
	PerPage               *int
	Page                  *int
	Sparkline             bool
	PriceChangePercentage *string
	Locale                *string
	Precision             *string
}

type NFTsAPI ΒΆ

type NFTsAPI struct {
	// contains filtered or unexported fields
}

func (*NFTsAPI) Collection ΒΆ

func (n *NFTsAPI) Collection(id string) (map[string]interface{}, error)

func (*NFTsAPI) CollectionByContract ΒΆ

func (n *NFTsAPI) CollectionByContract(assetPlatformID string, contractAddress string) (map[string]interface{}, error)

func (*NFTsAPI) List ΒΆ

func (n *NFTsAPI) List(options *NFTsListOptions) ([]map[string]interface{}, error)

func (*NFTsAPI) MarketChart ΒΆ

func (n *NFTsAPI) MarketChart(id string, days int) (map[string]interface{}, error)

func (*NFTsAPI) MarketChartByContract ΒΆ

func (n *NFTsAPI) MarketChartByContract(assetPlatformID string, contractAddress string, days int) (map[string]interface{}, error)

func (*NFTsAPI) Markets ΒΆ

func (n *NFTsAPI) Markets(options *NFTsMarketsOptions) ([]map[string]interface{}, error)

func (*NFTsAPI) Tickers ΒΆ

func (n *NFTsAPI) Tickers(id string) (map[string]interface{}, error)

type NFTsListOptions ΒΆ

type NFTsListOptions struct {
	Order           *string
	AssetPlatformID *string
	PerPage         *int
	Page            *int
}

type NFTsMarketsOptions ΒΆ

type NFTsMarketsOptions struct {
	AssetPlatformID *string
	Order           *string
	PerPage         *int
	Page            *int
}

type PingAPI ΒΆ

type PingAPI struct {
	// contains filtered or unexported fields
}

func (*PingAPI) APIUsage ΒΆ

func (p *PingAPI) APIUsage() (map[string]interface{}, error)

func (*PingAPI) Ping ΒΆ

func (p *PingAPI) Ping() (*PingResponse, error)

type PingResponse ΒΆ

type PingResponse struct {
	GeckoSays string `json:"gecko_says"`
}

type SearchAPI ΒΆ

type SearchAPI struct {
	// contains filtered or unexported fields
}

func (*SearchAPI) Search ΒΆ

func (s *SearchAPI) Search(query string) (map[string]interface{}, error)

func (*SearchAPI) Trending ΒΆ

func (s *SearchAPI) Trending() (map[string]interface{}, error)

type SimpleAPI ΒΆ

type SimpleAPI struct {
	// contains filtered or unexported fields
}

func (*SimpleAPI) Price ΒΆ

func (s *SimpleAPI) Price(ids []string, vsCurrencies []string, options *SimplePriceOptions) (map[string]map[string]interface{}, error)

func (*SimpleAPI) SupportedVsCurrencies ΒΆ

func (s *SimpleAPI) SupportedVsCurrencies() ([]string, error)

func (*SimpleAPI) TokenPrice ΒΆ

func (s *SimpleAPI) TokenPrice(assetPlatform string, contractAddresses []string, vsCurrencies []string, options *TokenPriceOptions) (map[string]map[string]interface{}, error)

type SimplePriceOptions ΒΆ

type SimplePriceOptions struct {
	IncludeMarketCap     bool
	Include24hrVol       bool
	Include24hrChange    bool
	IncludeLastUpdatedAt bool
}

type TickersOptions ΒΆ

type TickersOptions struct {
	ExchangeIDs         []string
	Page                *int
	Order               *string
	Depth               *string
}

type TokenPriceOptions ΒΆ

type TokenPriceOptions struct {
	IncludeMarketCap     bool
	Include24hrVol       bool
	Include24hrChange    bool
	IncludeLastUpdatedAt bool
}

type TransactionHistoryOptions ΒΆ

type TransactionHistoryOptions struct {
	Page    *int
	PerPage *int
}

type WebSocketAPI ΒΆ

type WebSocketAPI struct {
	// contains filtered or unexported fields
}

func (*WebSocketAPI) CreateOnchainOHLCVSubscription ΒΆ

func (w *WebSocketAPI) CreateOnchainOHLCVSubscription(network string, poolAddress string, timeframe string) (string, error)

func (*WebSocketAPI) CreateOnchainSimpleTokenPriceSubscription ΒΆ

func (w *WebSocketAPI) CreateOnchainSimpleTokenPriceSubscription(network string, addresses []string, vsCurrencies []string) (string, error)

func (*WebSocketAPI) CreateOnchainTradeSubscription ΒΆ

func (w *WebSocketAPI) CreateOnchainTradeSubscription(network string, poolAddress string) (string, error)

func (*WebSocketAPI) CreatePingMessage ΒΆ

func (w *WebSocketAPI) CreatePingMessage() (string, error)

func (*WebSocketAPI) CreateSimplePriceSubscription ΒΆ

func (w *WebSocketAPI) CreateSimplePriceSubscription(coinIDs []string, vsCurrencies []string) (string, error)

func (*WebSocketAPI) CreateUnsubscribeMessage ΒΆ

func (w *WebSocketAPI) CreateUnsubscribeMessage(channel string) (string, error)

func (*WebSocketAPI) GetWebSocketURL ΒΆ

func (w *WebSocketAPI) GetWebSocketURL() string

type WebSocketSubscription ΒΆ

type WebSocketSubscription struct {
	Type   string                 `json:"type"`
	Params map[string]interface{} `json:"params,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL