CCXT.NET Cryptocurrency Exchange Trading Library

repository·master·Indexed 42 days ago

https://github.com/odinsoft-lab/ccxt.net

A unified cryptocurrency exchange trading library for .NET compatible with .NET 8.0 and 9.0. It provides a consistent interface for public market data and private account management across over 120 exchanges, featuring strong typing, async/await support, and secure authentication handling. Version 1.5.3.

Tokens
6.1K
Snippets
18
Records
24
Agent score
52%

What's inside CCXT.NET

  1. Overview of CCXT.NET features

    master

    CCXT.NET is a unified API library for cryptocurrency exchange trading in .NET. Key features include:

    • Unified API: Consistent method signatures across different exchanges.
    • Market Data: Access to public data like tickers, order books, trades, and OHLCV.
    • Account Management: Private access to balances, orders, and trades.
    • Security: Built-in secure authentication handling for each exchange.
    • Developer Experience: Strong typing with full IntelliSense support and async/await throughout.
  2. Standard Parameter Conventions

    master

    When calling API methods, use the following standard parameter names to ensure consistency across different exchanges:

    • base_name: Base currency (e.g., "BTC")
    • quote_name: Quote currency (e.g., "USDT")
    • currency_name: Single currency (e.g., "ETH")
    • timeframe: Time period (e.g., "1h", "1d")
    • since: Unix timestamp in milliseconds (long)
    • limits: Number of results to return (int)
    • sideType: Buy or Sell enum
    • args: Dictionary<string, object> for exchange-specific parameters
  3. Handle Rate Limiting

    master

    To avoid being banned by exchanges, you must respect rate limits by calling ApiCallWait before making API requests. Use the appropriate TradeType based on the API category you are accessing:

    • TradeType.Public: For public market data endpoints.
    • TradeType.Private: For account management and transfer endpoints.
    • TradeType.Trade: For order placement and management endpoints.
    // Respect exchange rate limits
    await ApiCallWait(TradeType.Public);  // For public API
    await ApiCallWait(TradeType.Private); // For private API
    await ApiCallWait(TradeType.Trade);   // For trade API
  4. Understand the CCXT.NET repository structure

    master

    The repository is organized into source code, tests, samples, and documentation:

    • src/: Main library source code.
      • exchanges/: Contains exchange implementations organized by {country_code}/{exchange}/.
        • {exchange}.cs: The main exchange client class.
        • private/: Private API implementations (e.g., balance.cs, transfer.cs).
        • public/: Public API implementations (e.g., ticker.cs, orderBook.cs).
        • trade/: Trading API implementations (e.g., order.cs, place.cs).
      • shared/: Shared components.
        • standard/: Standard interfaces (IXApiClient) and base classes (XApiClient).
        • types/: Type definitions.
    • tests/: Test projects for private, public, and trade APIs.
    • samples/: Sample applications for demonstrating usage.
    • docs/: Documentation files.
    • scripts/: Build and deployment scripts.
  5. Check exchange implementation status

    master

    The library supports 120 exchanges. Exchanges are categorized into two implementation states:

    • Fully Implemented (🟢): Complete API implementation with full testing (e.g., Binance, Bitfinex, Kraken, OKEX).
    • Basic Implementation (🟡): Basic structure is implemented, but full API integration is pending (e.g., Coinbase, OKX, KuCoin, Bybit).
  6. Implement the Return Type Pattern

    master

    All API methods in CCXT.NET must follow a specific return pattern. They must return ValueTask<ApiResult<T>>, where ApiResult<T> wraps the actual result T with success or error information. This allows for consistent error handling across all exchange implementations.

    // Example of the expected return pattern
    public async ValueTask<ApiResult<Ticker>> FetchTickerAsync(string base_name, string quote_name)
    {
        var _result = new Ticker(base_name, quote_name);
        
        try
        {
            // ... API logic ...
            return _result.SetResult(_parsedResponse);
        }
        catch (Exception ex)
        {
            return _result.SetError(ex.Message);
        }
    }
  7. Publish CCXT.NET to NuGet

    master

    To publish the CCXT.NET package to NuGet.org, you must first ensure you have the .NET SDK installed and a valid NuGet API key with 'Push' permissions. You can use several methods to trigger the publication process from the project root.

    ### Method 1: Using Batch File (Simplest)
    1. Navigate to the `scripts` folder
    2. Double-click `publish-nuget.bat`
    3. Enter your NuGet API key when prompted
    4. Confirm publication
  8. Set up a local development environment for CCXT.NET

    master

    To contribute to CCXT.NET, you need to set up a local development environment.

    Prerequisites

    • .NET SDK 8.0 or 9.0
    • Visual Studio 2022 or VS Code (with C# extension)
    • Git
    • PowerShell (Windows) or bash (Linux/Mac)

    Initial Setup Steps

    1. Fork the repository to your GitHub account.
    2. Clone your fork and navigate to the directory.
    3. Add the original repository as an upstream remote to keep your fork in sync.
    4. Restore dependencies, build the project, and run tests to ensure a clean state.
    # Clone your fork
    git clone https://github.com/YOUR_USERNAME/ccxt.net.git
    cd ccxt.net
    
    # Add upstream remote
    git remote add upstream https://github.com/odinsoft-lab/ccxt.net.git
    
    # Install dependencies and build
    dotnet restore
    dotnet build
    
    # Run tests
    dotnet test
  9. Follow C# coding standards and naming conventions

    master

    CCXT.NET follows .NET coding conventions.

    Naming Conventions

    • Namespaces: CCXT.NET.{ExchangeName}
    • Classes: {ExchangeName}Client, {ExchangeName}PublicApi
    • Interfaces: I{Name} (e.g., IXApiClient)
    • Async Methods: {Method}Async (e.g., GetTickerAsync)
    • Private Fields: _{fieldName} (e.g., _httpClient)

    Best Practices

    • Use async/await for all I/O operations.
    • Use nullable reference types and perform null checks.
    • Use using statements for disposable resources.
    • Write XML documentation for all public APIs.
    // Use PascalCase for class names and methods
    public class ExchangeClient
    {
        // Use camelCase for local variables and parameters
        public async Task<ApiResult<Ticker>> GetTickerAsync(string symbol)
        {
            // Use meaningful variable names
            var tickerRequest = new TickerRequest(symbol);
            
            // Always use braces, even for single-line statements
            if (tickerRequest.IsValid)
            {
                return await SendRequestAsync(tickerRequest);
            }
            
            // Use explicit types for clarity
            ApiResult<Ticker> errorResult = new ApiResult<Ticker>();
            return errorResult;
        }
        
        // Private fields start with underscore
        private readonly HttpClient _httpClient;
        
        // Properties use PascalCase
        public string ExchangeName { get; set; }
    }
  10. Configure NuGet API Key via Environment Variable

    master

    Instead of passing the API key as a parameter, you can set the NUGET_API_KEY environment variable in your PowerShell session and then run the script without arguments.

    # Set API key in environment
    $env:NUGET_API_KEY = "YOUR_API_KEY_HERE"
    
    # Run without parameters (from project root)
    .\scripts\publish-nuget.ps1
  11. Quick Start with CCXT.NET

    master

    To use CCXT.NET, import the specific exchange namespace (e.g., CCXT.NET.Binance). You can create a client for public market data or a private client for account management using API keys. All operations are asynchronous and support await.

    using CCXT.NET.Binance;
    
    // Create client for public API
    var publicClient = new BinanceClient("public");
    
    // Get ticker
    var ticker = await publicClient.FetchTickerAsync("BTC/USDT");
    Console.WriteLine($"BTC/USDT Price: ${ticker.result.close}");
    
    // Create client for private API (requires API keys)
    var privateClient = new BinanceClient("private", "YOUR_API_KEY", "YOUR_SECRET_KEY");
    
    // Get account balance
    var balance = await privateClient.FetchBalanceAsync();
  12. Install CCXT.NET

    master

    You can install CCXT.NET using NuGet, the .NET CLI, or by cloning the repository. The library is compatible with .NET 8.0 and 9.0.

    # Package Manager Console
    Install-Package CCXT.NET -Version 1.5.3
    
    # .NET CLI
    dotnet add package CCXT.NET --version 1.5.3
    
    # PackageReference
    <PackageReference Include="CCXT.NET" Version="1.5.3" />