pgibler / Binance.NET

A .NET Standard 2.0+ wrapper for the Binance API.
MIT License
6 stars 4 forks source link
api-client api-wrapper binance-api cryptocurrency cryptocurrency-exchanges

Latest .NET Standard License

Binance.NET

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

Built for ease-of-use and extensibility.

Features

Installation

Using Nuget

PM> Install-Package Binance.NET

From source

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

git clone https://github.com/pgibler/Binance.NET
cd Binance.NET/src
dotnet build

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:

// 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}"));
// 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 ```cs // 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 ```cs // 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 ```cs // 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 ```cs // 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs 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 ```cs binance.ChartStream(new[] {"ETH-BTC", "LTC-BTC"}, 9999, (response, interval, ohlcDict) => { Console.WriteLine("Chart call invoked."); }); ```

Resources