Skip to content

A .NET Standard 2.0+ wrapper for the Binance API.

License

Notifications You must be signed in to change notification settings

pgibler/Binance.NET

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

49 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Latest .NET Standard License

Binance.NET

A .NET Standard 2.0+ wrapper for the Binance API.

Built for ease-of-use and extensibility.

Features

  • Static typing of API data using Newtonsoft.Json.
  • Custom error handling that lets you set default & API specific error handling. See error handling for more info.
  • Depth cache management built directly into the BinanceClient class.
  • Support for both REST & WebSocket APIs.
  • Demo application with example usage of every API.

Installation

Using Nuget

PM> Install-Package Binance.NET

From source

Binance.NET can be built on Windows, Mac, and Linux.

  • Clone and build the project using the following commands.
git clone https://github.com/pgibler/Binance.NET
cd Binance.NET/src
dotnet build
  • Locate the DLLs in the build directory at Binance.NET/src/Binance.NET/bin/Debug/netstandard{version}.
  • Add the DLLs from the build directory to your project.
  • Reference them from the .csproj file containing the classes that will utilize the BinanceClient class.

Once you have done these steps, to use Binance.NET in your C# application, create an instance of BinanceClient and invoke it's functionality from your code.

Example usage

// Retrieve your API key & secret from your account on binance and use those values here.
string apiKey = "<your binance API key>";
string apiSecret = "<your binance API secret>";

// Instantiate a Binance API client.
var binance = new BinanceClient(apiKey, apiSecret);

// Create a buy order.
binance.Buy("ETH-BTC", 1.0, 0.001);

// Create a sell order.
binance.Sell("ETH-BTC", 1.0, 0.0015)

Error handling

In some cases, the API request may fail because of any number of reasons. In the event that the Binance API responds with an error message, the success callback is skipped on the API call and an error callback is invoked. You can set up a custom error handler in 2 ways:

  • As a parameter of the API call. This is usually the last parameter of the method. Example:
// Buy order handling the response.
binance.Buy("ETH-BTC", 1.0, 0.00111213,
  response => Console.WriteLine(response.OrderId),
  Console.WriteLine($"API error. Message: {exception.Message}. Code: ${exception.Code}"));
  • Using the DefaultExceptionCallback property of the BinanceClient class.
// Handle all unmanaged exceptions across all API calls.
binance.DefaultExceptionCallback = exception => {
  Console.WriteLine($"API error. Message: {exception.Message}. Code: ${exception.Code}"));
  Logger.Log(exception);
}

You can also mix both methods. If you specify a DefaultExceptionCallback, it will be invoked whenever an API call results in an exception if you did not provide the API call with an exception callback. This way you can handle exceptions in a general use case and then specifically handle ones that require custom behavior.

For testing purposes, you can choose to eschew the usage of these as you try out the API methods. However, it is recommended you use them to see what goes wrong when you are testing.

APIs available

Included in Binance.NET are the following API calls. All of these functions are members of the BinanceClient class.


Buy(string symbol, double quantity, double price)

Submits a buy order.

View Example
// Simple buy order.
binance.Buy("ETH-BTC", 1.0, 0.001);

// Buy order handling the response.
binance.Buy("ETH-BTC", 1.0, 0.001,
  response => Console.WriteLine(response.OrderId),
  exception => Console.WriteLine($"Error message: {exception.Message}"));

Sell(string symbol, double quantity, double price)

Submits a sell order.

View Example
// Simple sell order.
binance.Sell("ETH-BTC", 1.0, 0.001);

// Sell order handling the response.
binance.Sell("ETH-BTC", 1.0, 0.001,
  response => Console.WriteLine(response.OrderId),
  exception => Console.WriteLine($"Error message: {exception.Message}"));

CancelOrder(string symbol, long orderId)

Cancels an order.

View Example
// Cancel order handling success and error responses.
long orderId = GetOrderId();
binance.CancelOrder("ETH-BTC", orderId,
  response => Console.WriteLine($"Order #{response.OrderId} cancelled"),
  exception => Console.WriteLine("Order failed to cancel"));

OrderStatus(string symbol, long orderId, Action<OrderResponse> successCallback)

Returns the status of an open order.

View Example
// Order status handling success and error responses.
long orderId = GetOrderId();
binance.OrderStatus("ETH-BTC", orderId,
  response => Console.WriteLine($"Order #{response.OrderId} has status {response.Status}"),
  exception => Console.WriteLine("Order failed to cancel"));

OpenOrders(string symbol, Action<OpenOrdersResponse> successCallback)

Returns a list of all open orders.

View Example
binance.OpenOrders("ETH-BTC", orders => Console.WriteLine($"First order open: {orders.First().OrderId}"));

AllOrders(string symbol, Action<AllOrdersResponse> successCallback)

Returns a list of all orders from the account.

View Example
binance.AllOrders("ETH-BTC", orders => Console.WriteLine($"First order ever: {orders.First().OrderId}"));

Depth(string symbol, Action<DepthCache> callback)

Returns the current depth of a symbol.

View Example
binance.Depth("ETH-BTC", depth => {
  Console.WriteLine($"Asks: {string.Join(",", depth.Asks.Keys)}, Bids: {string.Join(",", depth.Bids.Keys)}")
});

Prices(Action<Dictionary<string, double>> callback)

Returns all price data.

View Example
binance.Prices(prices => {
  Console.WriteLine($"Assets on the market: {prices.Count}.");
  Console.WriteLine($"First asset price: Symbol - {prices.First().Key}, Price - {prices.First().Value}");
});

BookTickers(Action<Dictionary<string, BookPrice>> callback)

Returns all book tickers.

View Example
binance.BookTickers(tickers => {
    Console.WriteLine($"Tickers count: {tickers.Count}");
    Console.WriteLine($"First symbol & ask: {tickers.First().Key} & {tickers.First().Value.AskPrice}");
});

PreviousDay(string symbol, Action<PreviousDayResponse> successCallback)

Returns the 24hr ticker price change statistics.

View Example
binance.PreviousDay("ETH-BTC", previousDay => {
  Console.WriteLine($"24 hour % change - ${previousDay.PriceChangePercent}")
});

Account(Action<AccountResponse> successCallback)

Get the account info associated with the API key & secret.

View Example
binance.Account(account => {
  Console.WriteLine($"Account can trade: {account.CanTrade}")
});

Balance(Action<Dictionary<string, Balance>> callback)

Get the balance of all symbols from the account.

View Example
binance.Balance(balances => Console.WriteLine($"First asset: {balances.First().Key}"));

Trades(string symbol, Action<TradesResponse> successCallback)

Get all trades the account is involved in.

View Example
binance.Trades("ETH-BTC", trades => Console.WriteLine($"First trade price: {trades.First().Price}"));

DepthCache(string symbol)

Returns the depth cache of the symbol.

View Example
var cache = binance.DepthCache("ETH-BTC");
            
Console.WriteLine($"# Asks: {cache.Asks.Count()}, # Bids: {cache.Bids.Count()}");;

DepthVolume(string symbol)

Returns the depth volume of the symbol.

View Example
var volume = binance.DepthVolume("ETH-BTC");

Console.WriteLine($"Ask volume: {volume.Asks}, Bid volume: {volume.Bids}")

SortBids(string symbol, double max, bool baseValue)

Sorts all bids then collects them up until the max number of bids has been collected.

View Example
var sortedBids = binance.SortBids("ETH-BTC");

Console.WriteLine($"Bids: {string.Join(",", sortedBids.Keys)}");

SortAsks(string symbol, double max, bool baseValue)

Sorts all asks then collects them up until the max number of asks has been collected.

View Example
var sortedAsks = binance.SortAsks("ETH-BTC");

Console.WriteLine($"Asks: {string.Join(",", sortedAsks.Keys)}");

Streams available

Binance.NET comes with a set of streams that you can run to listen and communicate with the Binance WebSocket services.

Each of these functions return a CancellationTokenSource instance so you can halt its operation as needed.


DepthStream(string[] symbols, Action<DepthStreamResponse> successCallback)

Opens a stream that invokes the callback when data is received on any of the specified symbols.

View Example
binance.DepthStream(new[] {"ETH-BTC", "LTC-BTC"}, depth =>
{
  Console.WriteLine($"Incoming asks: {depth.Asks.First().Price}. Incoming bids: {depth.Bids.First().Price}");

  if (depth.Asks.Any())
  {
    var ask = depth.Asks.First();
    Console.WriteLine($"First ask values: Price {ask.Price}, Quantity {ask.Quantity}");
  }

  if (depth.Bids.Any())
  {
    var bid = depth.Bids.First();
    Console.WriteLine($"First bid values: Price {bid.Price}, Quantity {bid.Quantity}");
  }
});

DepthCacheStream(string[] symbols, Action<string, DepthCache> callback)

Opens a depth cache stream that invokes the callback when data is received on any of the specified symbols.

View Example
binance.DepthCacheStream(new[] { "ETH-BTC", "LTC-BTC" }, (symbol, depth) =>
{
  Console.WriteLine($"Depth cache stream received data for symbol {symbol}.");

  if (depth.Asks.Any())
  {
    var ask = depth.Asks.First();
    Console.WriteLine($"First ask values: Price {ask.Price}, Quantity {ask.Quantity}");
  }

  if (depth.Bids.Any())
  {
    var bid = depth.Bids.First();
    Console.WriteLine($"First bid values: Price {bid.Price}, Quantity {bid.Quantity}");
  }
});

TradesStream(string[] symbols, Action<TradesStreamResponse> successCallback)

Opens a trades stream that invokes the callback when data is received on any of the specified symbols.

View Example
binance.TradesStream(new[] {"ETH-BTC", "LTC-BTC"}, trade =>
{
  Console.WriteLine($"Trade time: {trade.TradeTime}");
});

ChartStream(string[] symbols, long interval, Action<JToken, long, Dictionary<long, OpenHighLowClose>> successCallback)

Opens a charts stream that invokes the callback when data is received on any of the specified symbols.

View Example
binance.ChartStream(new[] {"ETH-BTC", "LTC-BTC"}, 9999, (response, interval, ohlcDict) =>
{
  Console.WriteLine("Chart call invoked.");
});

Resources

Releases

No releases published

Packages

No packages published

Languages