Code Monkey home page Code Monkey logo

binance's Introduction

Binance

A full-featured .NET API library (a.k.a. wrapper) for the official Binance web API.

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
    {
        // 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 =>
{
    // Get symbol from cache (update cache if a symbol is missing).
    var symbol = Symbol.Cache.Get(evt.OrderBook.Symbol);

    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

Decred (DCR): Dsd7amDBfC7n6G93NJzbaJjUdiSeN5D3tmR

Thank you.

Follow @sonvister

binance's People

Contributors

sonvister avatar tritao avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.