Skip to content

martijnspaan/Binance

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Binance

A full-featured .NET Binance API designed for ease of use.

Compatible with .NET Standard 2.0 and .NET Framework 4.7.1

Built using TAP (Task-based Asynchronous Pattern).

Features

  • Complete coverage of the official Binance API including the latest REST API and Web Socket combined streams.
    • Binance account API-Key is not required to access the public REST and Web Socket endpoints (most market data).
  • Easy-to-use Web Socket managers (with combined streams) and in-memory cache implementations (with events).
  • Convenient assets and symbols (e.g. Symbol.BTC_USDT) with exchange info (price/quantity: min, max, etc.).
    • With methods for validating (w/ or w/o exceptions) client order price, quantity, and type for a symbol.
  • REST API includes automatic rate limiting and system-to-server time synchronization for reliability.
    • Advanced rate limiting includes distinct (request and order) rate limiters with endpoint weights incorporated.
  • Unique REST API implementation supports multiple users and requires user authentication only where necessary.
  • REST API exceptions provide the Binance server response ERROR code and message for easier troubleshooting.
  • REST API (low-level) utilizes a single, cached HttpClient for performance (implemented as singleton).
  • Simple API abstraction using domain/value objects that do not expose underlying (HTTP/REST) behavior.
    • Consistent use of domain models between REST API queries and real-time Web Socket client events.
  • Customizable multi-layer API with access to (low-level) JSON responses or deserialized domain/value objects.
    • Same serializers used in BinanceApi are available for application-level deserialization of JSON data.
  • Limited dependencies with use of Microsoft extensions for dependency injection, logging, and options.
  • Multiple .NET sample applications including live displays of market depth, trades, and candlesticks for a symbol.
    • Alternative IWebSocketClients for using WebSocketSharp or WebSocket4Net (for Windows 7 compatibility).
    • How to efficiently use combined streams with a single, application-wide, web socket (BinanceWebSocketStream).

Getting Started

Binance Sign-up

To use the private (authenticated) API methods you must have an account with Binance and create an API-Key. Please use my Referral ID: 10899093 when you Register (it's an easy way to give back at no cost to you).

NOTE: An account is not required to access the public market data.

Installation

Using Nuget Package Manager:

PM> Install-Package Binance


Example Usage

REST API

Test connectivity.

using Binance;

// Initialize REST API client.
var api = new BinanceApi();

// Check connectivity.
if (await api.PingAsync())
{
    Console.WriteLine("Successful!");
}

Place a TEST market order.

using Binance;

var api = new BinanceApi();

// Create user with API-Key and API-Secret.
using (var user = new BinanceApiUser("<API-Key>", "<API-Secret>"))
{
    // Create a client (MARKET) order.
    var clientOrder = new MarketOrder(user)
    {
        Symbol = Symbol.BTC_USDT,
        Side = OrderSide.Buy,
        Quantity = 0.01m
    };

    try
    {
        // Validate client order.
        clientOrder.Validate();
        
        // Send the TEST order.
        await api.TestPlaceAsync(clientOrder);
        
        Console.WriteLine("TEST Order Successful!");
    }
    catch (Exception e)
    {
        Console.WriteLine($"TEST Order Failed: \"{e.Message}\"");
    }
}

Web Socket

Get real-time aggregate trades (with automatic web socket re-connect).

using Binance;
using Binance.WebSocket;

// Initialize web socket client (with automatic streaming).
var webSocketClient = new AggregateTradeWebSocketClient();

// Handle error events.
webSocketClient.Error += (s, e) => { Console.WriteLine(e.Exception.Message); };

// Subscribe callback to BTC/USDT (automatically begin streaming).
webSocketClient.Subscribe(Symbol.BTC_USDT, evt =>
{
    var side = evt.Trade.IsBuyerMaker ? "SELL" : "BUY ";
	
    // Handle aggregate trade events.
    Console.WriteLine($"{evt.Trade.Symbol} {side} {evt.Trade.Quantity} @ {evt.Trade.Price}");
});

// ...

// Unsubscribe (automatically end streaming).
webSocketClient.Unsubscribe();

Maintain real-time order book (market depth) cache.

using Binance;
using Binance.Cache;
using Binance.WebSocket;

// Initialize web socket cache (with automatic streaming).
var webSocketCache = new DepthWebSocketCache();

// Handle error events.
webSocketCache.Error += (s, e) => { Console.WriteLine(e.Exception.Message); };

// Subscribe callback to BTC/USDT (automatically begin streaming).
webSocketCache.Subscribe(Symbol.BTC_USDT, evt =>
{
    Symbol symbol = evt.OrderBook.Symbol; // use implicit conversion.

    var minBidPrice = evt.OrderBook.Bids.Last().Price;
    var maxAskPrice = evt.OrderBook.Asks.Last().Price;

    // Handle order book update events.
    Console.WriteLine($"Bid Quantity: {evt.OrderBook.Depth(minBidPrice)} {symbol.BaseAsset} - " +
                      $"Ask Quantity: {evt.OrderBook.Depth(maxAskPrice)} {symbol.BaseAsset}");
});

// ...

// Unsubscribe (automatically end streaming).
webSocketCache.Unsubscribe();

Documentation

See: Wiki

NOTE: The samples demonstrate up-to-date usage of this library.

Binance Exchange API (for reference)

REST/WebSocket details: Binance Official Documentation
REST/WebSocket questions: Binance Official API Telegram (not for questions about this library)

Development

The master branch is currently used for development and may differ from the latest release.
To get the source code for a particular release, first select the corresponding Tag.

Build Environment

Microsoft Visual Studio Community 2017

Build status

Donate

DCR: Dsog2jYLS65Y3N2jDQSxsiBYC3SRqq7TGd4
LTC: MNhGkftcFDE7TsFFvtE6W9VVKhxH74T3eM
BTC: 3JjG3tRR1dx98UJyNdpzpkrxRjXmPfQHk9

Thank you.

Follow @sonvister

About

A full-featured .NET Binance API library designed for ease of use.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • C# 100.0%