CryptoExchange.Net

CryptoExchange.Net is a base library which is used to implement different cryptocurrency (exchange) API's. It provides a standardized way of implementing different API's, which results in a very similar experience for users of the API implementations.

All libraries can be used in the same project as well as indivually, just install the exchange libraries you need!

The following API's are directly supported. Note that there are 3rd party implementations going around, but only these are created and supported by me

Exchange Repository Nuget
BinanceJKorf/Binance.Net
BingXJKorf/BingX.Net
BitfinexJKorf/Bitfinex.Net
BitgetJKorf/Bitget.Net
BybitJKorf/Bybit.Net
CoinExJKorf/CoinEx.Net
CoinGeckoJKorf/CoinGecko.Net
HuobiJKorf/Huobi.Net
KrakenJKorf/Kraken.Net
KucoinJKorf/Kucoin.Net
MexcJKorf/Mexc.Net
OKXJKorf/OKX.Net

Supported Frameworks

The library is targeting both .NET Standard 2.0 and .NET Standard 2.1 for optimal compatibility

.NET implementation Version Support
.NET Core2.0 and higher
.NET Framework4.6.1 and higher
Mono5.4 and higher
Xamarin.iOS10.14 and higher
Xamarin.Android8.0 and higher
UWP10.0.16299 and higher
Unity2018.1 and higher

Discord

A Discord server is available here. Feel free to join for discussion and/or questions around the CryptoExchange.Net and implementation libraries.

Support the project

Donate

Make a one time donation in a crypto currency of your choice. If you prefer to donate a currency not listed here please contact me.

Btc: bc1q277a5n54s2l2mzlu778ef7lpkwhjhyvghuv8qf
Eth: 0xcb1b63aCF9fef2755eBf4a0506250074496Ad5b7
USDT (TRX): TKigKeJPXZYyMVDgMyXxMf17MWYia92Rjd

Sponsor

Alternatively, sponsor me on Github using Github Sponsors.

I develop and maintain these packages on my own for free in my spare time, any support is greatly appreciated.

Getting Started

All packages are available on Nuget. After installing the package the API is available by using one of the library clients, or through the ICrypoRestClient, ICryptoSocketClient or ISpotClient interfaces.


Installation

Add the package via dotnet, or add it via the package manager. Any number of libraries can be installed, just make sure you're always using the latest at that moment.

dotnet add package Binance.Net
dotnet add package JK.BingX.Net
dotnet add package Bitfinex.Net
dotnet add package JK.Bitget.Net
dotnet add package Bybit.Net
dotnet add package CoinGecko.Net
dotnet add package CoinEx.Net
dotnet add package Huobi.Net
dotnet add package KrakenExchange.Net
dotnet add package Kucoin.Net
dotnet add package JK.Mexc.Net
dotnet add package JK.OKX.Net

Dependency Injection

All client libraries support and encourage usage via the Dotnet dependency injection system. Add all necesary services by calling the Add[Library](); extension method on the service collection. Options for the clients can be passed as parameters.

Using the dependecy injection mechanism also makes sure the HttpClient is used correctly
builder.Services.AddBinance();
builder.Services.AddBingX();
builder.Services.AddBitfinex();
builder.Services.AddBitget();
builder.Services.AddBybit();
builder.Services.AddCoinGecko();
builder.Services.AddCoinEx();
builder.Services.AddHuobi();
builder.Services.AddKraken();
builder.Services.AddKucoin();
builder.Services.AddMexc();
builder.Services.AddOKX();

This registers the following interfaces which can then be injected

InterfaceDescription
IBinanceRestClient The client for accessing the Binance REST API
IBinanceSocketClient The client for accessing the Binance Websocket API
IBinanceOrderBookFactory A factory for creating SymbolOrderBook instances for the Binance API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Binance. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IBingXRestClient The client for accessing the BingX REST API
IBingXSocketClient The client for accessing the BingX Websocket API
IBingXOrderBookFactory A factory for creating SymbolOrderBook instances for the BingX API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for BingX. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IBitfinexRestClient The client for accessing the Bitfinex REST API
IBitfinexSocketClient The client for accessing the Bitfinex Websocket API
IBitfinexOrderBookFactory A factory for creating SymbolOrderBook instances for the Bitfinex API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Bitfinex. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IBitgetRestClient The client for accessing the Bitget REST API
IBitgetSocketClient The client for accessing the Bitget Websocket API
IBitgetOrderBookFactory A factory for creating SymbolOrderBook instances for the Bitget API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Bitget. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IBybitRestClient The client for accessing the Bybit REST API
IBybitSocketClient The client for accessing the Bybit Websocket API
IBybitOrderBookFactory A factory for creating SymbolOrderBook instances for the Bybit API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Bybit. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
ICoinGeckoRestClient The client for accessing the CoinGecko REST API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
InterfaceDescription
ICoinExRestClient The client for accessing the CoinEx REST API
ICoinExSocketClient The client for accessing the CoinEx Websocket API
ICoinExOrderBookFactory A factory for creating SymbolOrderBook instances for the CoinEx API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for CoinEx. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IHuobiRestClient The client for accessing the Huobi REST API
IHuobiSocketClient The client for accessing the Huobi Websocket API
IHuobiOrderBookFactory A factory for creating SymbolOrderBook instances for the Huobi API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Huobi. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IKrakenRestClient The client for accessing the Kraken REST API
IKrakenSocketClient The client for accessing the Kraken Websocket API
IKrakenOrderBookFactory A factory for creating SymbolOrderBook instances for the Kraken API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Kraken. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IKucoinRestClient The client for accessing the Kucoin REST API
IKucoinSocketClient The client for accessing the Kucoin Websocket API
IKucoinOrderBookFactory A factory for creating SymbolOrderBook instances for the Kucoin API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Kucoin. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IMexcRestClient The client for accessing the Mexc REST API
IMexcSocketClient The client for accessing the Mexc Websocket API
IMexcOrderBookFactory A factory for creating SymbolOrderBook instances for the Mexc API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for Mexc. The ISpotClient offers basic Spot API functionality in a combined interface
InterfaceDescription
IOKXRestClient The client for accessing the OKX REST API
IOKXSocketClient The client for accessing the OKX Websocket API
IOKXOrderBookFactory A factory for creating SymbolOrderBook instances for the OKX API
ICryptoRestClient An aggregating client from which multiple different library REST clients can be accessed
ICryptoSocketClient An aggregating client from which multiple different library Websocket clients can be accessed
ISpotClient An implementation of the ISpotClient interface for OKX. The ISpotClient offers basic Spot API functionality in a combined interface

REST API client

Each library provides a REST API client. This client follows the following naming convention: [Library]RestClient. The REST API client is split into different sub-API access clients, which in turn are split into different topics. This structure is the same for each library, which makes it easier to navigate the clients.

The client can be injected via dependency injection, or constructed manually.

var client = new BinanceRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new BingXRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new BitfinexRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new BitgetRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new BybitRestClient();
var tickersResult = await client.V5Api.ExchangeData.GetSpotTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new CoinGeckoRestClient();
var assetsResult = await client.Api.GetAssetsAsync();
if (!assetsResult.Success)
{
  // Handle error, assetsResult.Error contains more information
}
else
{
  // Handle data, assetsResult.Data will contain the actual data
}
var client = new CoinExRestClient();
var tickersResult = await client.SpotApiV2.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new HuobiRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new KrakenRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new KucoinRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new MexcRestClient();
var tickersResult = await client.SpotApi.ExchangeData.GetTickersAsync();
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}
var client = new OKXRestClient();
var tickersResult = await client.UnifiedApi.ExchangeData.GetTickersAsync(OKXInstrumentType.Spot);
if (!tickersResult.Success)
{
  // Handle error, tickersResult.Error contains more information
}
else
{
  // Handle data, tickersResult.Data will contain the actual data
}

The response object

Calls made with the REST API client will return a WebCallResult object. This object contains information about both the request that was send and the response that was received. The WebCallResult object exposes the following properties:

PropertyDescription
Success Whether or not the call was completed successfully
Data The parsed response object, only available when Success is true
Error Error information, only available when Success is false
OriginalData The raw response data, only filled when the OutputOriginalData is enabled in the client options
RequestMethod The HTTP method that was used for the request
RequestHeaders The list of headers which were send with the request
RequestId A unique request id
RequestUrl The full urls which was called
RequestBody The request body send with the request
ResponseLength The length of the response in bytes
ResponseHeaders The list of headers send along with the response
ResponseTime The time it took from sending the request to receiving the response

Websocket API client

If the API supports websocket connections then the library provides a Websocket API client. This client follows the following naming convention: [Library]SocketClient. The Websocket API client is split into different sub-API access clients, which in turn are sometimes split into different topics. This structure is the same for each library, which makes it easier to navigate the clients.

The client can be injected via dependency injection, or constructed manually. When constructing manually keep in mind that when the client is disposed all connections will get closed as well.

Subscribing

var client = new BinanceSocketClient();
var subscribeResult = await client.SpotApi.ExchangeData.SubscribeToAllTickerUpdatesAsync(update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new BingXSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToTickerUpdatesAsync("ETH-USDT", update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new BitfinexSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToTickerUpdatesAsync("tETHUST", update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new BitgetSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new BybitSocketClient();
var subscribeResult = await client.V5SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", update => {
    // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new CoinExSocketClient();
var subscribeResult = await sclient.SpotApiV2.SubscribeToTickerUpdatesAsync(new[] { "ETHUSDT" }, update => {
    // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
    // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new HuobiSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToTickerUpdatesAsync(update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new KrakenSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToTickerUpdatesAsync("ETH/USD", update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new KucoinSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToAllTickerUpdatesAsync(update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new MexcSocketClient();
var subscribeResult = await client.SpotApi.SubscribeToMiniTickerUpdatesAsync(update => {
  // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler
var client = new OKXSocketClient();
var subscribeResult = await client.UnifiedApi.ExchangeData.SubscribeToTickerUpdatesAsync("ETH-USDT", update => {
    // Handle the data update, update.Data will contain the actual data
});
if (!subscribeResult.Success)
{
  // Handle error, subscribeResult.Error contains more information on why the subscription failed
}
// Subscribing was successfull, the data will now be streamed into the data handler

The subscription result object

Subscriptions calls will return a CallResult<UpdateSubscription> object. This object contains information about the status of the intial subscription, and the UpdateSubscription data object exposes events for status changes and methods for managing the subscription. The CallResult<UpdateSubscription> object exposes the following properties:

PropertyDescription
Success Whether or not the subscription was completed successfully
Error Error information, only available when Success is false
Data The UpdateSubscription object, only available when Success is true
Data.Id Unique id of the subscription
Data.SocketId The id of the underlying websocket
Data.ConnectionLost Event which will be invoked whenever the connection to the server is lost and reconnecting will be started
Data.ConnectionRestored Event which will be invoked when the connection to the server is restored after being disconnected
Data.ActivityPaused Event which will be invoked when the server has indicated that currently no operations will be accepted
Data.ActivityUnpaused Event which will be invoked when the server has indicated that operations will be accepted again after a previous ActivityPaused event
Data.Exception Event which will be invoked when the data handler of the subscription throws an exception

The subscription update event object

Whenever new data is received for a subscription the data handler will be called with a DataEvent<T> object. This object contains information about the event and the actual update data. The DataEvent<T> object exposes the following properties:

PropertyDescription
Timestamp The timestamp the data was received
Topic The topic of the update, typically the symbol or stream name
OriginalData The raw update data, only filled when the OutputOriginalData is enabled in the client options
UpdateType The type of update. SocketUpdateType.Snapshot means the update is a snapshot, not an incremental update. SocketUpdateType.Update means it's an update with new data
Data The data received in the update

Unsubscribing

When no longer interested in updates from a specific subscription it can be unsubscribed. This can be done in one of the following ways:

Unsubscribe via UpdateSubscription object
When you have the reference to the UpdateSubscription object received from the Subscribe method you can call the CloseAsync() method on that to unsubscribe

var subscribeResult = await client.SpotApi.SubscribeToTickerUpdates(data => {});
await subscribeResult.Data.CloseAsync();

Unsubscribe via CancellationToken
Passing in a CancellationToken as parameter in the subscribe method will allow you to cancel subscriptions by canceling the token. This can be useful when you need to cancel some streams but not others. In this example, both BTCUSDT and ETHUSDT streams get canceled, while the XRPUSDT stream remains active.

var cts = new CancellationTokenSource();
var subscriptionResult1 = await client.SpotApi.SubscribeToTickerUpdatesAsync("BTCUSDT", DataHandler, cts.Token);
var subscriptionResult2 = await client.SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", DataHandler, cts.Token);
var subscriptionResult3 = await client.SpotApi.SubscribeToTickerUpdatesAsync("XRPUSDT", DataHandler);
cts.Cancel();

Unsubscribe via the websocket client
The Websocket client has multiple ways of unsubscribing one or more subscriptions:

var subscribeResult = await client.SpotApi.SubscribeToTickerUpdates(data => {});
// Unsubscribe by passing the UpdateSubscription
await client.UnsubscribeAsync(subscribeResult.Data);
// OR store the ID and pass that
var subId = subscribeResult.Data.Id;
await client.UnsubscribeAsync(subId);
// OR unsubscribe all subscriptions at the same time
await client.UnsubscribeAllAsync();


Common Clients

CryptoExchange.Net exposes some common clients. These clients aim to make using the different API's easier.

(I)CryptoRestClient
The ICryptoRestClient (or CryptoRestClient when used directly) can be used to easily access REST clients for different API's through the different packages that have been installed. Each package adds it extension method to the interface, which allows the user to access the clients via it.

For example, having the Binance, Bybit and Kucoin packages installed allows you to use it like this:

var cryptoRestClient = new CryptoRestClient(); // Either construct it or inject the ICryptoRestClient into your service
var binanceTicker = await cryptoRestClient.Binance().SpotApi.ExchangeData.GetTickersAsync();
var bybitTicker = await cryptoRestClient.Bybit().V5Api.ExchangeData.GetTickers();
var kucoinTicker = await cryptoRestClient.Kucoin().SpotApi.ExchangeData.GetTickers();

(I)CryptoSocketClient
Similarly as the (I)CryptoRestClient this client allows you to access the different Websocket clients through a single access point.

Having the Bitget, Kraken and OKX packages installed would allow you to use it like this:

var cryptoRestClient = new CryptoSocketClient(); // Either construct it or inject the ICryptoRestClient into your service
var bitgetSub = await cryptoRestClient.Bitget().SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", data => {});
var krakenSub = await cryptoRestClient.Kraken().SpotApi.SubscribeToTickerUpdatesAsync("ETH/USD", data => {});
var okxSub = await cryptoRestClient.OKX().UnifiedApi.ExchangeData.SubscribeToTickerUpdatesAsync("ETH-USDT", data => {});

ISpotClient
The ISpotClient is a REST API client interface implemented by each library which implements a Spot trading API. It provided a common way of doing basic operations on the Spot market, for example getting ticker or trade data, but also placing and retrieving orders. Because this interface is implemented for each exchange with a Spot market the interface is relatively basic, only exposing methods that are supported by all the APIs.

The ISpotClient is added to the service collection when using dependency injection. Alternatively it can be accessed for a specific client by calling the `CommonSpotClient` property on the Spot sub-API of a client:

var spotClient = restClient.SpotApi.CommonSpotClient;


Options & Authorization

Options for the clients can be provided in a couple of different ways. If no options are configured the default options will be used. For accessing private endpoints and streams API credentials have to be provided.


Authorization

For private endpoints and data streams the clients will need to know the API credentials of the user accessing the API. API credentials are a way of identifying the user and validating that the user is who he says he is. You can compare it to a username and password login.

API credentials van be provided via the client options, see next section on how to set these options. There are currently 2 variants of API credentials supported, HMAC and RSA.

HMAC
HMAC authentication involves 2 values, the API key and API secret. The combination of the two gives access to the account. HMAC is the default authentication method and can be configured as such:

options.ApiCredentials = new ApiCredentials("YOUR API KEY", "YOUR API SECRET");

RSA
RSA authentication involves generating a private and public key and then uploading the public key to the server. After using the private key to sign the request the server can validate the request by comparing the signature using the public key. Not every exchange supports this authentication method. Depending on the version of dotnet used there are 2 ways of configuring the RSA authentication.

When running Dotnet version 3.0 or later the easiest way is to use the RsaPem type. This allows you to use the Private key directly. When running from an older Dotnet/.NET framework version you're forced to use the RsaXml type due to framework limitations. This means you'll have to convert the private key to XML format before using it.

RsaXml
// when using the .netstandard2.0 compiled version, from .NET framework or Dotnet core 2.2 or lower
// Private key should look something like this: <RSAKeyValue><Modulus>...</RSAKeyValue>
options.ApiCredentials = new ApiCredentials("YOUR PUBLIC KEY", "YOUR PRIVATE KEY", ApiCredentialsType.RsaXml);
RsaPem
// when using the .netstandard2.1 compiled version, from Dotnet core 3.0 or later
// Private key should look something like this: -----BEGIN PRIVATE KEY----- .. -----END PRIVATE KEY-----, or just a long random character string
options.ApiCredentials = new ApiCredentials("YOUR PUBLIC KEY", "YOUR PRIVATE KEY", ApiCredentialsType.RsaPem);

Setting options

Dependency injection

When adding a library to the service collection (see Dependency Injection) the options for the clients can be provided as argument to the calls. Options are split between the REST and the websocket client.

builder.Services.AddBinance(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddBingX(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddBitfinex(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddBitget(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddBybit(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddCoinGecko(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  });
builder.Services.AddCoinEx(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddHuobi(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddKraken(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddKucoin(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddMexc(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
builder.Services.AddOKX(
  restOptions => {
    restOptions.RequestTimeout = TimeSpan.FromSeconds(30);
  },
  socketOptions => {
    socketOptions.RequestTimeout = TimeSpan.FromSeconds(10);
  });
Client constructor

When creating a client via the constructor options can be provided as parameters

var binanceRestClient = new BinanceRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BingXRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BitfinexRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BitgetRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BybitRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new CoinGeckoRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new CoinExRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new HuobiRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new KrakenRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new KucoinRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new MexcRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new OKXRestClient(opts =>
{
    opts.RequestTimeout = TimeSpan.FromSeconds(30);
});
SetDefaultOptions

The options can be defined using the static SetDefaultOptions method on the client BEFORE creating the client. Any client created after this call will use the specified options

BinanceRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BinanceRestClient();
BingXRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BingXRestClient();
BitfinexRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BitfinexRestClient();
BitgetRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BitgetRestClient();
BybitRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new BybitRestClient();
CoinGeckoRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new CoinGeckoRestClient();
CoinExRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new CoinExRestClient();
HuobiRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new HuobiRestClient();
KrakenRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new KrakenRestClient();
KucoinRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new KucoinRestClient();
MexcRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new MexcRestClient();
OKXRestClient.SetDefaultOptions(options =>
{
    options.RequestTimeout = TimeSpan.FromSeconds(30);
});
var client = new OKXRestClient();

Option definitions

General options
Options available for all clients

OptionDescriptionDefault value
RequestTimeout The time to wait for an answer from the server on a request TimeSpan.FromSeconds(20)
ApiCredentials The credentials to use for private endpoints and streams. See Authorization for more info null
Proxy The proxy to use for connecting to the API null
OutputOriginalData When enabled the originally received string data will be available as well as the deserialized object. For REST API client calls the data will be in the WebCallResult.OriginalData property, for Websocket API client subscriptions the data will be available in the DataEvent.OriginalData property when receiving an update. false
RateLimiterEnabled Whether or not client side rate limiting should be applied. Note that not all libraries have ratelimiting implemented, if it's not implemented this flag does nothing true
RateLimitingBehaviour What should happen when a rate limit is reached. RateLimitingBehaviour.Wait: the request waits until it can be send while staying within the limits, RateLimitingBehaviour.Fail: the request will return an error RateLimitingBehaviour.Wait
Environment The environment the library should connect to. Some exchanges have testnet/sandbox environments which can be used instead of the real exchange. The environment option can be used to switch between different trade environments Live environment

REST client options
Options available for REST clients

OptionDescriptionDefault value
AutoTimestamp Whether or not the client should attempt to sync the time between the client and server. If the time between server and client is not in sync authentication errors might occur. This option should be disabled when the client time sure is to be in sync true
TimestampRecalculationInterval The interval of how often the time synchronization between client and server should be executed TimeSpan.FromHours(1)
[API].ApiCredentials Same as the in the base options, allows overriding per sub-API null
[API].OutputOriginalData Same as the in the base options, allows overriding per sub-API null
[API].AutoTimestamp Same as the in the base REST options, allows overriding per sub-API null
[API].TimestampRecalculationInterval Same as the in the base REST options, allows overriding per sub-API null

Websocket client options
Options available for websocket clients

OptionDescriptionDefault value
AutoReconnect Whether or not the socket should attempt to automatically reconnect when disconnected true
ReconnectInterval The time to wait between connection tries when reconnecting TimeSpan.FromSeconds(5)
SocketNoDataTimeout If no data is received during this timespan the connection is assumed to be dropped. This is mainly used for API's which have some sort of ping/keepalive system. For example; the Bitfinex API will sent a heartbeat message every 15 seconds, so the `SocketNoDataTimeout` could be set to 20 seconds. On API's without such a mechanism this might not work because there just might not be any update while still being fully connected default(TimeSpan)
SocketSubscriptionsCombineTarget The number of subscriptions that should be made on a single socket connection before setting up a new connection. Not all exchanges support multiple subscriptions on a single socket and some have limits on the amount of connections. Setting this to a higher number increases subscription speed because not every subscription needs to connect to the server, but having more subscriptions on a single connection will also increase the amount of traffic on that single connection, potentially leading to delays in updates if the data isn't handled quickly enough Dependent on the library
MaxConcurrentResubscriptionsPerSocket The maximum number of concurrent resubscriptions per socket when resubscribing after reconnecting 5
MaxSocketConnections The maximum number of distinct socket connections null
DelayAfterConnect The time to wait before sending messages after connecting to the server null
[API].SocketNoDataTimeout Same as the in the base websocket client options, allows overriding per sub-API null
[API].MaxSocketConnections Same as the in the base websocket client options, allows overriding per sub-API null


Additional Features


Orderbooks

Each client library provides an local orderbook implementation. These implementations will provide a client side orderbook, take care of synchronization with the server, and handle reconnecting and resynchronizing in case of a dropped connection. Orderbook implementations use the following naming convention: [ExchangeName][(Type)]SymbolOrderBook

Creation and starting
The order book implementations can be created directly, or can be instantiated via the I[Exchange]OrderBookFactory factory. After creation the synchronization can be started by calling the StartAync method

var book = new BinanceSpotSymbolOrderBook("ETHUSDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new BingXSpotSymbolOrderBook("ETH-USDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new BitfinexSymbolOrderBook("tETHUSD");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new BitgetSpotSymbolOrderBook("ETHUSDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new BybitSymbolOrderBook("ETHUSDT", Category.Spot);
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new CoinExSpotSymbolOrderBook("ETHUSDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new HuobiSpotSymbolOrderBook("ethusdt");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new KrakenSpotSymbolOrderBook("ETH/USD");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new KucoinSpotSymbolOrderBook("ETH-USDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new MexcSpotSymbolOrderBook("ETHUSDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();
var book = new OKXSymbolOrderBook("ETH-USDT");
var startResult = await book.StartAsync();
if (!startResult.Success)
{
  // Handle error, error info available in startResult.Error
}
// Book has successfully started and synchronized

// Once no longer needed you can stop the live sync functionality by calling StopAsync()
await book.StopAsync();

The order book object
The order book implementations for each client use a common base class and interface, which means you can use books from different exchanges in a common function.

// Create order books for different exchanges
var books = new List<ISymbolOrderBook>();
books.Add(new BinanceSpotSymbolOrderBook("ETHUSDT"));
books.Add(new BitgetSpotSymbolOrderBook("ETHUSDT"));
books.Add(new KrakenSpotSymbolOrderBook("ETH/USD"));
books.Add(new KucoinSpotSymbolOrderBook("ETH-USDT"));
books.Add(new OKXSymbolOrderBook("ETH-USDT"));

// Start the books
var results = await Task.WhenAll(books.Select(b => b.StartAsync()));

// Output the current best ask/bid for each exchange
foreach (var book in books.Where(b => b.Status == OrderBookStatus.Synced))
{
	Console.WriteLine(book.Id);
	Console.WriteLine($"{book.BestAsk} - {book.BestBid}");
}

The following properties and events are exposed by the order books:

FieldDescription
Status The current status of the order book. Note that the book is only acurate and up to date when the status is Synced
Id Identifier for the book, referencing the exchange it's for
Symbol The symbol the book is for
LastSequenceNumber The last sequence number that was processed. Order book update messages typically have sequence numbers to correctly sync the book
UpdateTime Timestamp of the last update that was processed
AskCount The current number of asks in the book
BidCount The current number of bids in the book
Asks Returns a snapshot of the current list of asks. This creates a copy of the list values at that moment
Bids Returns a snapshot of the current list of bids. This creates a copy of the list values at that moment
Book Returns a snapshot of the both the asks and bids. This makes sure the snapshot of the bids and asks are of the same exact time
BestAsk The best ask at that moment
BestBid The best bid at that moment
BestOffers The best bid and best ask at that moment
OnStatusChange Event called when the status of the order book changes
OnOrderBookUpdate Event called whenever the book changes. Note that this event can trigger a lot on large/high liquidity markets
OnBestOffersChanged Event called whenever the best ask or bid changes in the order book


Logging

The library provides extensive logging, which depends on the dotnet `Microsoft.Extensions.Logging.ILogger` interface. This should provide ease of use when connecting the library logging to your existing logging implementation.

When using the Dotnet dependency injection the logging configuration will de determined by the ILogger configuration.

External log providers
External logging libraries can be configured as expected. For example Serilog:

using Binance.Net;
using Serilog;

Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.Console()
        .CreateLogger();

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddBinance();
builder.Host.UseSerilog();
var app = builder.Build();

// startup

app.Run();

Logging without dependency injection
A LoggerFactory instance can be provided to the client to configure the logging

var logFactory = new LoggerFactory();
logFactory.AddProvider(new ConsoleLoggerProvider());
var binanceClient = new BinanceRestClient(new HttpClient(), logFactory, options => { });


Ratelimiting

The client libraries have build in support for rate limiting. Rate limiting in this case means that requests are throttled (or failed before sending based on configuration) when the client detects a server rate limit will be exceeded. Whether or not rate limiting is applied can be configured in the DI registration or client options. Not all libraries currently have rate limiting configured.

What to do when a limit is reached can be configured with the RateLimitingBehaviour client options, either Fail for returning an error or Wait to wait until the request can safely be send.

Client side rate limiting can only correctly work if there is only a single program talking to the exchange. When multiple different application send requests at the same time it's impossible for the client side to keep track of the rate limits. When using multiple concurrent applications it is advised to turn off rate limiting. Also note that when requests are rate limited with RateLimitBehaviour.Wait that the order of the requests being send is not guarenteed.

Client side rate limiting is currently implemented for the following libraries:

services.AddBinance(x =>
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
}, x =>
{
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
});

To be notified of when a rate limit is hit the static BinanceExchange.RateLimiter exposes an event which triggers when a rate limit is reached

BinanceExchange.RateLimiter.RateLimitTriggered += (rateLimitEvent) => Console.WriteLine("Limit triggered: " + rateLimitEvent);

// Output: Limit triggered: RateLimitEvent { ApiLimit = Spot Socket, LimitDescription = Limit of 6000 per 00:01:00, RequestDefinition = GET 1, Host = wss://ws-api.binance.com, Current = 5752, RequestWeight = 250, Limit = 6000, TimePeriod = 00:01:00, DelayTime = 00:00:38.7784145, Behaviour = Wait }
services.AddKraken(x =>
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
}, x =>
{
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
});

To be notified of when a rate limit is hit the static KrakenExchange.RateLimiter exposes an event which triggers when a rate limit is reached

KrakenExchange.RateLimiter.RateLimitTriggered += (rateLimitEvent) => Console.WriteLine("Limit triggered: " + rateLimitEvent);

// Output: Limit triggered: RateLimitEvent { ApiLimit = Spot Rest, LimitDescription = Limit of 15 with a decay rate of 0,33, RequestDefinition = POST 0/private/TradesHistory authenticated, Host = api.kraken.com, Current = 14, RequestWeight = 2, Limit = 15, TimePeriod = 00:00:01, DelayTime = 00:00:04, Behaviour = Wait }

Kraken applies different rate limits based on the account verification tier. By default the rate limit is set to the most conservative Starter tier. To change the rate limit tier call the Configure method

KrakenExchange.RateLimiter.Configure(Kraken.Net.Enums.RateLimitTier.Pro);
services.AddKucoin(x =>
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
}, x =>
{
    x.RatelimiterEnabled = true;
    x.RateLimitingBehaviour = RateLimitingBehaviour.Wait;
});

To be notified of when a rate limit is hit the static KucoinExchange.RateLimiter exposes an event which triggers when a rate limit is reached

KucoinExchange.RateLimiter.RateLimitTriggered += (rateLimitEvent) => Console.WriteLine("Limit triggered: " + rateLimitEvent);

// Output: Limit triggered: RateLimitEvent { ApiLimit = Public Rest, LimitDescription = Limit of 2000 per 00:00:30, RequestDefinition = GET api/v1/market/stats, Host = https://api.kucoin.com/, Current = 1995, RequestWeight = 15, Limit = 2000, TimePeriod = 00:00:30, DelayTime = 00:00:19.8111238, Behaviour = Wait }

Kucoin applies different rate limits based on the account VIP level. By default the rate limit is set to the most conservative VIP0 tier. To change the rate limit tier call the Configure method

KucoinExchange.RateLimiter.Configure(Kucoin.Net.Enums.VipLevel.Vip5);

Examples

See also the Examples folder in the source

Get Symbols

Get a list of supported symbols on the exchange and information about the symbols

// Name of the exchange can be whatever exchange library you have installed, for example Binance, Bybit, Kraken etc
var spotClient = cryptoRestClient.SpotClient("[Name of the exchange]");
await spotClient.GetSymbolsAsync();
await binanceClient.SpotApi.ExchangeData.GetExchangeInfoAsync();
await bingXClient.SpotApi.ExchangeData.GetSymbolsAsync();
await bitfinexClient.SpotApi.ExchangeData.GetSymbolsAsync();
await bitgetClient.SpotApi.ExchangeData.GetSymbolsAsync();
await bybitClient.V5Api.ExchangeData.GetSpotSymbolsAsync();
await coinExClient.SpotApiV2.ExchangeData.GetSymbolsAsync();
await huobiClient.SpotApi.ExchangeData.GetSymbolsAsync();
await krakenClient.SpotApi.ExchangeData.GetSymbolsAsync();
await kucoinClient.SpotApi.ExchangeData.GetSymbolsAsync();
await mexcClient.SpotApi.ExchangeData.GetExchangeInfoAsync();
await okxClient.UnifiedApi.ExchangeData.GetSymbolsAsync(OKXInstrumentType.Spot);
Getting Ticker

Get ticker/price statistics for a specific asset pair

// Name of the exchange can be whatever exchange library you have installed, for example Binance, Bybit, Kraken etc
var spotClient = cryptoRestClient.SpotClient("[Name of the exchange]");
await spotClient.GetTickerAsync(spotClient.GetSymbolName("BTC", "USDT"));
await binanceClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
await bingXClient.SpotApi.ExchangeData.GetTickersAsync("BTC-USDT");
await bitfinexClient.SpotApi.ExchangeData.GetTickerAsync("tBTCUST");
await bitgetClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT_SPBL");
await bybitClient.V5Api.ExchangeData.GetSpotTickersAsync("BTCUSDT");
await coinExClient.SpotApiV2.ExchangeData.GetTickersAsync(new[] { "BTCUSDT" });
await huobiClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
await krakenClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
await kucoinClient.SpotApi.ExchangeData.GetTickerAsync("BTC-USDT");
await mexcClient.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT");
await okxClient.UnifiedApi.ExchangeData.GetTickerAsync("BTC-USDT");
Get Balances

Get balance information. Requires API credentials to be set in the client options

// Name of the exchange can be whatever exchange library you have installed, for example Binance, Bybit, Kraken etc
var spotClient = cryptoRestClient.SpotClient("[Name of the exchange]");
await spotClient.GetBalancesAsync();
await binanceClient.SpotApi.Account.GetBalancesAsync();
await bingXClient.SpotApi.Account.GetBalancesAsync();
await bitfinexClient.SpotApi.Account.GetBalancesAsync();
await bitgetClient.SpotApi.Account.GetBalancesAsync();
await bybitClient.V5Api.Account.GetBalancesAsync(AccountType.Spot);
await coinExClient.SpotApiV2.Account.GetBalancesAsync();
// Need an account id, you probably want to already have done this before placing the order
var accounts = await huobiClient.SpotApi.Account.GetAccountsAsync();
var account = accounts.Data.Single(a => a.Type == AccountType.Spot);

var result = await huobiClient.SpotApi.Account.GetBalancesAsync();
await krakenClient.SpotApi.Account.GetBalancesAsync();
await kucoinClient.SpotApi.Account.GetAccountsAsync();
await mexcClient.SpotApi.Account.GetAccountInfoAsync();
await okxClient.UnifiedApi.Account.GetAccountBalanceAsync();
Placing Order

Place a limit buy order for 0.1 BTC at a price of 50.000 USDT. Requires API credentials to be set in the client options

// Name of the exchange can be whatever exchange library you have installed, for example Binance, Bybit, Kraken etc
var spotClient = cryptoRestClient.SpotClient("[Name of the exchange]");
await spotClient.PlaceOrderAsync(spotClient.GetSymbolName("BTC", "USDT"), CommonOrderSide.Buy, CommonOrderType.Limit, 0.1m, price: 50000);
await binanceClient.SpotApi.Trading.PlaceOrderAsync("BTCUSDT", OrderSide.Buy, SpotOrderType.Limit, 0.1m, price: 50000, timeInForce: TimeInForce.GoodTillCanceled);
await bingXClient.SpotApi.Trading.PlaceOrderAsync("BTC-USDT", OrderSide.Buy, OrderType.Limit, 0.1m, price: 50000);
await bitfinexClient.SpotApi.Trading.PlaceOrderAsync("tBTCUST", OrderSide.Buy, OrderType.Limit, 0.1m, 50000);
await bitgetClient.SpotApi.Trading.PlaceOrderAsync("BTCUSDT_SPBL", BitgetOrderSide.Buy, BitgetOrderType.Limit, 0.1m, timeInForce: BitgetTimeInForce.GoodTillCanceled, 50000);
await bybitClient.V5Api.Trading.PlaceOrderAsync(Category.Spot, "BTCUSDT", OrderSide.Buy, NewOrderType.Limit, 0.1m, price: 50000);
await coinExClient.SpotApiV2.Trading.PlaceOrderAsync("BTCUSDT", AccountType.Spot, OrderSide.Buy, OrderTypeV2.Limit, 0.1m, 50000);
// Need an account id, you probably want to already have done this before placing the order
var accounts = await huobiClient.SpotApi.Account.GetAccountsAsync();
var account = accounts.Data.Single(a => a.Type == AccountType.Spot);

var result = await huobiClient.SpotApi.Trading.PlaceOrderAsync(account.Id, "BTCUSDT", OrderSide.Buy, OrderType.Limit, 0.1m, price: 50000);
await krakenClient.SpotApi.Trading.PlaceOrderAsync("BTCUSDT",OrderSide.Buy, OrderType.Limit, 0.1m, 50000);
await kucoinClient.SpotApi.Trading.PlaceOrderAsync("BTC-USDT", OrderSide.Buy, NewOrderType.Limit, 0.1m, 50000);
await mexcClient.SpotApi.Trading.PlaceOrderAsync("BTCUSDT", Mexc.Net.Enums.OrderSide.Buy, Mexc.Net.Enums.OrderType.Limit, 0.1m, price: 50000);
await okxClient.UnifiedApi.Trading.PlaceOrderAsync("BTC-USDT", OKXOrderSide.Buy, OKXOrderType.LimitOrder, 0.1m, 50000);
Subscribe Ticker Updates

Subscribe to the websocket ticker update stream

await binanceSocketClient.SpotApi.ExchangeData.SubscribeToTickerUpdatesAsync("ETHUSDT", data => {
    // Handle update
});
await bingXSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH-USDT", data => {
    // Handle update
});
await bitfinexSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("tETHUST", data => {
    // Handle update
});
await bitgetSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", data => {
    // Handle update
});
await bybitSocketClient.V5SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", data => {
    // Handle update
});
await coinExSocketClient.SpotApiV2.SubscribeToTickerUpdatesAsync(new[] { "ETHUSDT" }, data => {
    // Handle update
});
await huobiSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ethusdt", data => {
    // Handle update
});
await krakenSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETHUSD", data => {
    // Handle update
});
await kucoinSocketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETH-USDT", data => {
    // Handle update
});
await mexcSocketClient.SpotApi.SubscribeToMiniTickerUpdatesAsync("ETHUSDT", data => {
    // Handle update
});
await okxSocketClient.UnifiedApi.ExchangeData.SubscribeToTickerUpdatesAsync("ETHUSDT", data => {
    // Handle update
});
Subscribe Order Updates

Subscribe to the websocket authenticated user order update stream

// Retrieve the listen key
var listenKey = await binanceClient.SpotApi.Account.StartUserStreamAsync();

// Subscribe using the key
await binanceSocketClient.SpotApi.Account.SubscribeToUserDataUpdatesAsync(listenKey.Data, data => {
    // Handle update
}, null, null, null);

// The listen key will stay valid for 60 minutes, after this no updates will be send anymore
// To extend the life time of the listen key it is recommended to call the KeepAliveUserStreamAsync method every 30 minutes
_ = Task.Run(async () => {
    while (true)
    {
        await Task.Delay(Timespan.FromMinutes(30));
        await binanceClient.SpotApi.Account.KeepAliveUserStreamAsync(listenKey.Data);
    }
});
// Retrieve the listen key
var listenKey = await bingXRestClient.SpotApi.Account.StartUserStreamAsync();

// Subscribe using the key
await bingXSocketClient.SpotApi.SubscribeToBalanceUpdatesAsync(listenKey.Data, data => {
    // Handle update
});

// The listen key will stay valid for 60 minutes, after this no updates will be send anymore
// To extend the life time of the listen key it is recommended to call the KeepAliveUserStreamAsync method every 30 minutes
_ = Task.Run(async () => {
    while (true)
    {
        await Task.Delay(Timespan.FromMinutes(30));
        await bingXClient.SpotApi.Account.KeepAliveUserStreamAsync(listenKey.Data);
    }
});
await bitfinexSocketClient.SpotApi.SubscribeToUserUpdatesAsync(orderHandler: data => {
    // Handle update
});
await bitgetSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(data => {
    // Handle update
});
await bybitSocketClient.V5PrivateApi.SubscribeToOrderUpdatesAsync(data => {
    // Handle update
});
await coinExSocketClient.SpotApiV2.SubscribeToOrderUpdatesAsync(data => {
    // Handle update
});
await huobiSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(onOrderMatched: data => {
    // Handle update
});
// Retrieve the token
var token = await krakenClient.SpotApi.Account.GetWebsocketTokenAsync();

// Subscribe using the token
await krakenSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(token.Data.Token, data => {
    // Handle update
});
await kucoinSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(data => {
    // Handle update
}, null, null);
// Retrieve the listen key
var token = await mexcClient.SpotApi.Account.StartUserStreamAsync();

// Subscribe using the key
await mexcSocketClient.SpotApi.SubscribeToOrderUpdatesAsync(token.Data, data => {
    // Handle update
});

// The listen key will stay valid for 60 minutes, after this the connection is closed and reconnecting with the same listen key will fail
// To extend the life time of the listen key it is recommended to call the KeepAliveUserStreamAsync method every 30 minutes
_ = Task.Run(async () => {
    while (true)
    {
        await Task.Delay(Timespan.FromMinutes(30));
        await mexcClient.SpotApi.Account.KeepAliveUserStreamAsync(token.Data);
    }
});
await okxSocketClient.UnifiedApi.Trading.SubscribeToOrderUpdatesAsync(OKXInstrumentType.Spot, null, null, data => {
    // Handle update
});
Minimal API

A minimal API example allowing the caller to retrieve ticker information for a specific exchange and asset pair

This API returns ticker information for the following path

/Ticker/[Exchange]/[QuoteAsset]/[BaseAsset] for example /Ticker/Kraken/ETH/BTC

using CryptoExchange.Net.Interfaces;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddBitfinex();
builder.Services.AddBitget();
builder.Services.AddKraken();
var app = builder.Build();

app.MapGet("Ticker/{exchange}/{baseAsset}/{quoteAsset}", async ([FromServices] ICryptoRestClient client, string exchange, string baseAsset, string quoteAsset) =>
{
    var spotClient = client.SpotClient(exchange)!;
    var result = await spotClient.GetTickerAsync(spotClient.GetSymbolName(baseAsset, quoteAsset));
    return result.Data;
});

app.Run();
		  

Glossary

DefinitionSynonymsMeaning
Symbol Market, Pair An asset pair on which can be traded, for example BTC-ETH
Asset Currency, Coin A coin for which you can hold balance and which makes up Symbols. For example both BTC, ETH or USD
Trade Execution, Fill The (partial) execution of an order. Orders can have multiple trades
Quantity Amount, Size The amount of asset
QuoteQuantity Value The amount of quote asset
Fee Commission The fee paid for an order, trade or withdrawal
Kline Candlestick, OHLC K-line data, used for candlestick charts. Contains Open/High/Low/Close/Volume
KlineInterval Period The time period of a single kline
Open order Active order, Unexecuted order An order which has not yet been fully filled
Closed order Completed order, executed order An order which is no longer active. Can be canceled or fully filled
Network Chain The network of an asset. For example ETH allows multiple networks like ERC20 and BEP2
Orderbook Market depth A list of (the top rows of) the current best bids and asks
Ticker Stats Statistics over the last 24 hours

FAQ

I occasionally get a NullReferenceException, what's wrong?

You probably don't check the result status of a call and just assume the data is always there. NullReferenceExecption will happen when you have code like this var symbol = client.GetTickersAync().Result.Data.Symbol because the Data property is null when the call fails. Instead check if the call is successful:

var tickerResult = await client.SpotApi.ExchangeData.GetTickersAync();
if(!tickerResult.Success)
{
  // Handle error
}
else
{
  // Handle result, it is now safe to access the Data property
  var symbol = tickerResult.Data.Symbol;
}

The socket client stops sending updates after a little while

You probably didn't keep a reference to the socket client and it got disposed.

// WRONG
private void SomeMethod()
{
  var socketClient = new BinanceSocketClient();
  socketClient.Spot.SubscribeToOrderBookUpdatesAsync("BTCUSDT", data => {
    // Handle data
  });
}
// RIGHT
private BinanceSocketClient _socketClient = new BinanceSocketClient();

// .. rest of the class

private void SomeMethod()
{
  _socketClient.Spot.SubscribeToOrderBookUpdates("BTCUSDT", data => {
    // Handle data
  });
}

Can I use the TestNet/US/other API with this library?

Yes, generally these are all supported and can be configured by setting the Environment in the client options. Some known environments should be available in the [Exchange]Environment class:

// Change environment to test
var client = new BinanceRestClient(options =>
{
    options.Environment = BinanceEnvironment.Testnet;
});

How are timestamps handled?

Exchange API's treat all timestamps as UTC, both incoming and outgoing. The client libraries do no conversion so received timestamps are always in UTC. When sending requests make sure to use UTC time as well.