[Python] How to use CoinGecko C# API: Error when using Cilent

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    I am using CoinGecko package for C# and essentially I'm trying to convert my python code to C#. I have installed CoinGecko.Net, CoinGecko.API, CoinGeckoAsync. I import via `using CoinGecko.Net.Clients;'

    However I get the following error on this line var coinGeckoClient = new CoinGeckoClient Error is The type or namespace name 'CoinGeckoClient' could not be found (are you missing a using directive or an assembly reference?)

    I have restarted VS code and reinstalled the above packages but to no avail. There isn't a clear guide or API documentation that I know of and the ones I've seen aren't much help.

    Here is my code that uses CoinGecko:

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using CoinGecko.Net.Clients;
    using CoinGecko;
    using CryptoExchange.Net.Objects;
    using CsvHelper;
    using CsvHelper.Configuration;

    namespace CryptoDataFetcher
    {
    public class Program
    {
    // Main cryptocurrency data class to hold our combined data
    public class CryptoCombinedData
    {
    // Market data properties
    public string Name { get; set; }
    public string Symbol { get; set; }
    public decimal CurrentPrice { get; set; }
    public decimal MarketCap { get; set; }
    public int? MarketCapRank { get; set; }
    public decimal TotalVolume { get; set; }
    public decimal? CirculatingSupply { get; set; }
    public decimal? TotalSupply { get; set; }
    public decimal? MaxSupply { get; set; }
    public decimal Ath { get; set; }
    public decimal Atl { get; set; }
    public DateTime LastUpdated { get; set; }

    // OHLC data properties
    public DateTime Timestamp { get; set; }
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    }

    // Class to store historical OHLC data
    public class OhlcData
    {
    public DateTime Timestamp { get; set; }
    public decimal Open { get; set; }
    public decimal High { get; set; }
    public decimal Low { get; set; }
    public decimal Close { get; set; }
    }

    public static async Task Main(string[] args)
    {
    // Create a CoinGecko client
    var coinGeckoClient = new CoinGeckoClient

    try
    {
    // Get top 10 cryptocurrencies
    Console.WriteLine("Getting the top 10 cryptocurrencies by market cap...");
    var topCryptos = await GetTopCryptosAsync(coinGeckoClient, 10);
    Console.WriteLine($"Top 10 cryptocurrencies: {string.Join(", ", topCryptos)}");

    // Get data for these cryptocurrencies
    var (combinedData, allOhlcData) = await GetMultipleCryptoDataAsync(coinGeckoClient, topCryptos);

    // Display the combined data (limited output for console)
    Console.WriteLine("\nCombined Market and OHLC Data:");
    foreach (var crypto in combinedData.Take(3)) // Show just first 3 for brevity
    {
    Console.WriteLine($"{crypto.Name} ({crypto.Symbol}): ${crypto.CurrentPrice}, Market Cap: ${crypto.MarketCap}, Timestamp: {crypto.Timestamp}");
    }
    Console.WriteLine($"... and {combinedData.Count - 3} more records");

    // Save to CSV
    SaveToCsv(combinedData, "top10_crypto_market_and_ohlc_data.csv");
    Console.WriteLine("\nData saved to 'top10_crypto_market_and_ohlc_data.csv'");

    // Show sample of Bitcoin's historical OHLC data if available
    if (allOhlcData.ContainsKey("bitcoin") && allOhlcData["bitcoin"].Any())
    {
    Console.WriteLine("\nBitcoin Historical OHLC Data:");
    foreach (var ohlc in allOhlcData["bitcoin"].Take(5))
    {
    Console.WriteLine($"Timestamp: {ohlc.Timestamp}, Open: {ohlc.Open}, High: {ohlc.High}, Low: {ohlc.Low}, Close: {ohlc.Close}");
    }
    }
    }
    catch (Exception ex)
    {
    Console.WriteLine($"An error occurred: {ex.Message}");
    if (ex.InnerException != null)
    {
    Console.WriteLine($"Inner exception: {ex.InnerException.Message}");
    }
    }
    }

    // Function to get top cryptocurrencies by market cap
    private static async Task<List<string>> GetTopCryptosAsync(CoinGeckoClient client, int limit)
    {
    var coinsMarkets = await client.CoinsClient.GetCoinsMarkets("usd", null, null, null, null, false, "market_cap_desc", 1, limit);

    if (!coinsMarkets.Success)
    throw new Exception($"Failed to get top cryptocurrencies: {coinsMarkets.Error}");

    return coinsMarkets.Data.Select(coin => coin.Id).ToList();
    }

    // Function to get both OHLC and market data for a single cryptocurrency
    private static async Task<(CryptoCombinedData, List<OhlcData>)> GetCryptoDataAsync(CoinGeckoClient client, string cryptoId, string vsCurrency = "usd", int days = 14)
    {
    // Get OHLC data
    var ohlcData = await client.CoinsClient.GetOhlc(cryptoId, vsCurrency, days);
    if (!ohlcData.Success)
    throw new Exception($"Failed to get OHLC data for {cryptoId}: {ohlcData.Error}");

    // Get detailed coin data
    var coinData = await client.CoinsClient.GetAllCoinDataWithId(cryptoId);
    if (!coinData.Success)
    throw new Exception($"Failed to get market data for {cryptoId}: {coinData.Error}");

    // Process OHLC data
    var processedOhlcData = ohlcData.Data.Select(dataPoint => new OhlcData
    {
    Timestamp = DateTimeOffset.FromUnixTimeMilliseconds((long)dataPoint[0]).DateTime,
    Open = dataPoint[1],
    High = dataPoint[2],
    Low = dataPoint[3],
    Close = dataPoint[4]
    }).ToList();

    // Get the most recent OHLC data point
    var latestOhlc = processedOhlcData.LastOrDefault();
    if (latestOhlc == null)
    throw new Exception($"No OHLC data found for {cryptoId}");

    // Combine market data with latest OHLC
    var marketData = coinData.Data.MarketData;
    var result = new CryptoCombinedData
    {
    // Market data
    Name = coinData.Data.Name,
    Symbol = coinData.Data.Symbol,
    CurrentPrice = marketData.CurrentPrice.ContainsKey("usd") ? marketData.CurrentPrice["usd"] : 0,
    MarketCap = marketData.MarketCap.ContainsKey("usd") ? marketData.MarketCap["usd"] : 0,
    MarketCapRank = marketData.MarketCapRank,
    TotalVolume = marketData.TotalVolume.ContainsKey("usd") ? marketData.TotalVolume["usd"] : 0,
    CirculatingSupply = marketData.CirculatingSupply,
    TotalSupply = marketData.TotalSupply,
    MaxSupply = marketData.MaxSupply,
    Ath = marketData.Ath.ContainsKey("usd") ? marketData.Ath["usd"] : 0,
    Atl = marketData.Atl.ContainsKey("usd") ? marketData.Atl["usd"] : 0,
    LastUpdated = coinData.Data.LastUpdated,

    // OHLC data
    Timestamp = latestOhlc.Timestamp,
    Open = latestOhlc.Open,
    High = latestOhlc.High,
    Low = latestOhlc.Low,
    Close = latestOhlc.Close
    };

    return (result, processedOhlcData);
    }

    // Function to get data for multiple cryptocurrencies
    private static async Task<(List<CryptoCombinedData>, Dictionary<string, List<OhlcData>>)> GetMultipleCryptoDataAsync(
    CoinGeckoClient client, List<string> cryptoIds, string vsCurrency = "usd", int days = 14)
    {
    var allData = new List<CryptoCombinedData>();
    var allOhlc = new Dictionary<string, List<OhlcData>>();

    foreach (var cryptoId in cryptoIds)
    {
    try
    {
    Console.WriteLine($"Fetching data for {cryptoId}...");
    var (resultData, ohlcData) = await GetCryptoDataAsync(client, cryptoId, vsCurrency, days);
    allData.Add(resultData);
    allOhlc[cryptoId] = ohlcData;

    // Sleep to respect API rate limits
    await Task.Delay(1500); // 1.5 seconds
    }
    catch (Exception ex)
    {
    Console.WriteLine($"Error fetching data for {cryptoId}: {ex.Message}");
    }
    }

    return (allData, allOhlc);
    }

    // Function to save data to CSV
    private static void SaveToCsv(List<CryptoCombinedData> data, string filePath)
    {
    var config = new CsvConfiguration(CultureInfo.InvariantCulture)
    {
    HasHeaderRecord = true,
    };

    using (var writer = new StreamWriter(filePath))
    using (var csv = new CsvWriter(writer, config))
    {
    csv.WriteRecords(data);
    }
    }
    }
    }


    Here is my project file:

    <Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="CoinGecko.Net" Version="3.4.0" />
    <PackageReference Include="CsvHelper" Version="33.0.1" />
    </ItemGroup>

    </Project>

    Continue reading...

Compartilhe esta Página