Skip to content
Projetos

binance/binance-connector-dotnet

Ver no GitHub

Sobre

Lightweight connector for integration with Binance API

Negócios e finanças

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
-1
em 15 dias
0
em 1 mês
Coletando histórico

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

Binance .NET Connector

Build Status Open Issues .NET Docs License: MIT

Official collection of .NET connectors for Binance APIs.

Every connector offers typed REST API, WebSocket API and WebSocket Streams clients, built on the shared Binance.Common library (configuration, signing, errors, logging and connection management).

Migration Guide

If you're upgrading from the previous 4.x connector, refer to our Migration Guide for detailed steps on transitioning to the new modular structure. The legacy connector will still be available for a limited time. You can find the code for the old connector in the legacy branch.

Prerequisites

Before using the connectors, ensure you have:

  • .NET 8 or later (the packages target net8.0 and net10.0); to build this repository, the .NET SDK 10 (see global.json)
  • Examples: the projects under examples/ target net10.0, so running them needs the .NET 10 SDK; the packages themselves run on net8.0 and later
  • Supported platforms: win-x64, win-x86, win-arm64, linux-x64, linux-arm64, linux-arm, linux-musl-x64, linux-musl-arm64, osx-x64 and osx-arm64 (see src/Binance.Common/README.md)

Install or update .NET from dot.net and check it with:

dotnet --version

Available Connectors

Each connector is a NuGet package and a project under src/ (src/Binance.<Product>/). Install only the ones you need:

  • algo - Algo Trading connector (Binance.Algo)
  • alpha - Alpha connector (Binance.Alpha)
  • c2c - C2C connector (Binance.C2C)
  • cms - CMS (Binance announcements) connector, WebSocket Streams only (Binance.Cms)
  • convert - Convert connector (Binance.Convert)
  • copy_trading - Copy Trading connector (Binance.CopyTrading)
  • crypto_loan - Crypto Loan connector (Binance.CryptoLoan)
  • derivatives_trading_coin_futures - Derivatives Trading (COIN-M Futures) connector (Binance.DerivativesTradingCoinFutures)
  • derivatives_trading_options - Derivatives Trading (Options) connector (Binance.DerivativesTradingOptions)
  • derivatives_trading_portfolio_margin - Derivatives Trading (Portfolio Margin) connector (Binance.DerivativesTradingPortfolioMargin)
  • derivatives_trading_portfolio_margin_pro - Derivatives Trading (Portfolio Margin Pro) connector (Binance.DerivativesTradingPortfolioMarginPro)
  • derivatives_trading_usds_futures - Derivatives Trading (USDS-M Futures) connector (Binance.DerivativesTradingUsdsFutures)
  • dual_investment - Dual Investment connector (Binance.DualInvestment)
  • fiat - Fiat connector (Binance.Fiat)
  • gift_card - Gift Card connector (Binance.GiftCard)
  • margin_trading - Margin Trading connector (Binance.MarginTrading)
  • mining - Mining connector (Binance.Mining)
  • pay - Pay connector (Binance.Pay)
  • rebate - Rebate connector (Binance.Rebate)
  • simple_earn - Simple Earn connector (Binance.SimpleEarn)
  • spot - Spot Trading connector (Binance.Spot)
  • staking - Staking connector (Binance.Staking)
  • stock_options - Stock Options connector (Binance.StockOptions)
  • stocks - Stocks connector (Binance.Stocks)
  • sub_account - Sub Account connector (Binance.SubAccount)
  • vip_loan - VIP Loan connector (Binance.VipLoan)
  • w3w_prediction - W3W Prediction connector (Binance.W3WPrediction)
  • wallet - Wallet connector (Binance.Wallet)

The cms and w3w_prediction WebSocket Streams are signed: set ApiKey and ApiSecret (or PrivateKeyPem / PrivateKeyFile) in the WebSocketStreamsConfig.

Documentation

Installation

Each connector is published as a separate NuGet package. For example:

dotnet add package Binance.Spot
using Binance.Common;
using Binance.Spot.RestApi;

using var rest = SpotRestApi.Production(new RestApiConfig
{
    ApiKey = Environment.GetEnvironmentVariable("API_KEY"),
    ApiSecret = Environment.GetEnvironmentVariable("API_SECRET"),
});
var time = await rest.TimeAsync();
Console.WriteLine(time.Data()!.ServerTime);

The platform library (libbinance_c) ships inside the packages; on a platform it does not support, the first client you create throws a BinanceLibraryException.

A signed order on the Spot testnet (create testnet keys at testnet.binance.vision); the credentials come from the API_KEY and API_SECRET environment variables:

using Binance.Common;
using Binance.Spot.RestApi;

using var client = SpotRestApi.Testnet(new RestApiConfig
{
    ApiKey = Environment.GetEnvironmentVariable("API_KEY"),
    ApiSecret = Environment.GetEnvironmentVariable("API_SECRET"),
});

try
{
    var response = await client.NewOrderAsync(new()
    {
        Symbol = "BTCUSDT",
        Side = NewOrderSide.Buy,
        Type = NewOrderType.Market,
        Quantity = 0.001m,
    });
    Console.WriteLine($"Order {response.Data()!.OrderId} placed");
}
catch (BinanceException e)
{
    Console.Error.WriteLine($"{e.Kind} {e.Code}: {e.Message}");
}

To sign with a private key instead of an HMAC secret, set PrivateKeyFile = "/path/to/ed25519-private-key.pem" (or PrivateKeyPem) in place of ApiSecret.

using Binance.Spot.WebSocketStreams;

var client = SpotWebSocketStreams.Production();
await using var connection = await client.ConnectAsync();
using var trades = connection.AggTrade(new() { Symbol = "btcusdt" });
await foreach (var trade in trades.Events.ReadAllAsync())
    Console.WriteLine($"{trade.S} {trade.P}");

As in the other Binance connectors, the WebSocket clients hold the configuration, and ConnectAsync() returns an open connection with the methods.

Each module (RestApi, WebSocketApi, WebSocketStreams) has factories for its environments: Production, Testnet and, where available, Demo. The README of every connector, in src/Binance.<Product>/, has more, including the configuration options (timeouts, retries, proxies, custom CAs and certificate pinning), error handling and logging.

Dependency injection

The optional Binance.Common.DependencyInjection package registers any client:

services.AddBinanceRestApi<SpotRestApi>(SpotRestApi.Production, o => o.ApiKey = Environment.GetEnvironmentVariable("API_KEY"));

Logging

BinanceLogging.Configure(loggerFactory) sends the log, which is process-wide, to ILogger.

Versioning

Releases follow Semantic Versioning. Every package has its own version, listed in Versions.props, and its own changelog (src/Binance.<Product>/CHANGELOG.md): a connector gets a new version when its API changes, and depends on the Binance.Common version it was built with, or a later one. Binance.Spot 5.x replaces the HttpClient based 4.x connector, see MIGRATION.md.

Building from source

dotnet build Binance.slnx -c Release
dotnet format whitespace Binance.slnx --verify-no-changes
dotnet test Binance.slnx --filter "Category!=Native"        # tests that do not load the platform library
dotnet test Binance.slnx                                    # everything (needs the platform library for your system, see below)

Tests marked [Trait("Category", "Native")] load the platform library, which comes from binance-connector-cpp: the packages ship the release named in src/Binance.Common/native-version.txt. make native-download fetches that release's library for your system (with curl and unzip; NATIVE_RID=<rid> picks another), and make test then uses it:

make native-download && make test

To change the C interface, build the library from a clone of binance-connector-cpp next to this repository (or NATIVE_SRC=<path>) with make native. It needs CMake 3.24+, Ninja, a C++20 compiler and vcpkg with VCPKG_ROOT set:

brew install cmake ninja                               # macOS (with the Xcode command line tools)
sudo apt install build-essential cmake ninja-build     # Debian / Ubuntu
git clone https://github.com/microsoft/vcpkg.git ~/vcpkg && ~/vcpkg/bootstrap-vcpkg.sh && export VCPKG_ROOT=~/vcpkg
git clone https://github.com/binance/binance-connector-cpp.git ../binance-connector-cpp
make native && make test

make help lists the other targets.

To pack, put the libraries into src/Binance.Common/runtimes/<rid>/native/ (they are not committed; see src/Binance.Common/README.md for the override), and run dotnet pack.

The project list

Binance.slnx (the solution file) lists the projects of src/*, examples/* and tests/*. After adding a product, run

scripts/update-slnx.sh

It writes the file from the projects on disk, one solution folder for each of src, examples and tests: running it twice changes nothing, and a deleted project drops out.

Contributing

We encourage you to:

  1. Open a GitHub issue to discuss your ideas or report bugs
  2. Allow maintainers to implement the necessary changes

The connector projects (src/Binance.<Product>/, examples/Binance.<Product>.Examples/ and tests/Binance.<Product>.Tests/) are maintained from the Binance API definitions, so a change to them is made there; manual edits to those folders would be overwritten. src/Binance.Common/, src/Binance.Common.DependencyInjection/ and tests/Binance.Common.Tests/ (with the test support shared by the product tests) are maintained by hand and take pull requests as usual.

Disclaimer

This SDK is provided by Binance on an "as is" and "as available" basis for use at your own risk. Binance makes no representations or warranties of any kind, whether express or implied, as to the operation of the SDK, its accuracy, reliability, completeness, or fitness for any particular purpose.

To the fullest extent permitted by law, Binance shall not be liable for any losses, damages, or expenses of any kind arising from or in connection with your use of, or inability to use, this SDK, including but not limited to any financial losses resulting from errors, bugs, interruptions, or inaccuracies in the SDK.

Your use of this SDK to access the Binance Platform is subject to the Binance API Key Terms and the Binance Terms of Use, which shall prevail in the event of any conflict with this disclaimer. You are solely responsible for any orders or transactions executed through the Binance Platform using this SDK.

This SDK is not intended to constitute investment advice or a recommendation to buy, sell, or hold any digital asset. You should independently evaluate and verify all information before acting.

License

This project is licensed under the MIT License - see the LICENCE file for details.

Explore projetos relacionados

Carregando…