Giter VIP home page Giter VIP logo

binance's Introduction

Binance

A .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

  • Beta release with majority coverage of the official Binance API including REST API and Web Sockets.
    • NOTE: Not actively adding new features or providing support...
    • 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

Donate NIM

binance's People

Contributors

sonvister avatar tritao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

binance's Issues

Cancel token doesn't unsubscribe UserDataWebSocketClient subscription

Hello,

It seems that calling the cancel method on the CancellationTokenSource for the UserDataWebSocketClient instance does't unsubscribe the the user subscription. I notice that when the stream drops out, I execute the cancel method and then try and reconnect using the SubscribeAndStreamAsync method on the UserDataWebSocketClient instance it throws an exception because the user is already subscribed on this line:

        if (_listenKeys.ContainsKey(user))
            throw new InvalidOperationException($"{nameof(UserDataWebSocketClient)}: Already subscribed to user.");

        try

    public virtual async Task SubscribeAsync(IBinanceApiUser user, Action<UserDataEventArgs> callback, CancellationToken token = default)
    {
        Throw.IfNull(user, nameof(user));

        if (_listenKeys.ContainsKey(user))
            throw new InvalidOperationException($"{nameof(UserDataWebSocketClient)}: Already subscribed to user.");

        try
        {
            _listenKeys[user] = await _api.UserStreamStartAsync(user, token)
                .ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(_listenKeys[user]))
                throw new Exception($"{nameof(IUserDataWebSocketClient)}: Failed to get listen key from API.");

            SubscribeStream(_listenKeys[user], callback);
        }
        catch (OperationCanceledException) { }
        catch (Exception e)
        {
            if (!token.IsCancellationRequested)
            {
                Logger?.LogError(e, $"{nameof(UserDataWebSocketClient)}.{nameof(SubscribeAsync)}");
                throw;
            }
        }
    }

It may be that the cancel token is not supposed to unsubscribe the user and I should just execute the StreamAsync method on the webSocket?

Also, just wondering why the exception doesn't get propagated to the client. It doesn't get raised and the code just continues as if nothing happened. Is it because i'm running it on a different thread Dim cnnTask = Task.Run(Async Sub() ConnectSocket()) ? if so, can you recommend a way that I can get exceptions raised in the client (apologies if this may be a basic question, my parallel programming experience is not great)?

CandlestickEventArgs throws for -1 TradeId value

It seems that Binance returns -1 for the TradeId field when there were no trades and because of this the candlestick wss API fails.

Perhaps extending the range to -1 instead of 0 would be beneficial and/or translating -1 to a nullable TradeId?

Reconnecting websocket

I noticed that the library will not connect automatically if the connection was closed by binance.
any advice would be highly appreciated :)

2018/01/22 10:54:48.089|INFO|The remote party closed the WebSocket connection without completing the close handshake. |Demo.Program|
2018/01/22 10:54:53.091|INFO|DepthWebSocketClient is already subscribed to symbol: "ETHUSDT" |Demo.Program|

-1100: Illegal characters found in parameter 'quantity

i want place order with Quantity = 0.002m

await _binanceClient.Api.PlaceAsync(new LimitOrder(_binanceClient.User) { Symbol = Symbol.BTC_USDT, Side = Binance.Account.Orders.OrderSide.Buy, Quantity = 0.002m, Price = 16000 });
i get exception:

  •   $exception	{Binance.Api.BinanceHttpException: [BadRequest]: 'Bad Request' - Illegal characters found in parameter 'quantity'; legal range is '^([0-9]{1,20})(\.[0-9]{1,20})?$'. (-1100)
    
    at Binance.Api.Json.BinanceJsonApi.d__49.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Binance.Api.Json.BinanceJsonApi.d__31.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Binance.Api.BinanceApi.d__18.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at MusicWeb.Core.Orders.OrderAction.d__7.MoveNext() in C:\MusicWeb\MusicWeb\Core\Orders\OrderAction.cs:line 59} Binance.Api.BinanceHttpException

why i get this error ?
this is restrict binance server api ?

Alter default rate limits on BinanceApi

What is the correct way to alter the rate limiter on the BinanceApi. This does not seem to work:

        var client = new BinanceApi();
        var httpClient = client.HttpClient;
        httpClient.RateLimiter.IsEnabled = true;
        httpClient.Options.RequestRateLimit.Count = 50;
        httpClient.Options.RequestRateLimit.DurationMinutes = 1;
        httpClient.Options.RequestRateLimit.BurstCount = 1;
        httpClient.Options.RequestRateLimit.BurstDurationSeconds = 5;

Thanks,

real-time all symbol price monitoring

Is there an API to monitor prices for all symbols real-time?

For example, when you open up the main page (href: /) then there is a new WebSocket connection established:

wss://stream2.binance.com:9443/ws/!miniTicker@arr@3000ms

which seems to be monitoring price changes for all currencies simultaneously. Output format for each currency is:

E:1514912813087
c:"0.00239528"
e:"24hrMiniTicker"
h:"0.00274990"
l:"0.00214001"
o:"0.00252900"
q:"73675.51226164"
s:"XRPETH"
v:"30218342.00000000"

Unfortunately, I can not find the websocket endpoint in the official list of endpoints and so I could not find an API in this binance project which would provide a similar kind of results.

So my question is - is there support for this functionality planned, if not, then what would be the best approach to get this data real-time?
I can of course spam GetPricesAsync API but then that would certainly not be a correct way of doing it..

SingleUserDataWebSocketClient: throw when OnKeepAliveTimer raises error

Hello,

SingleUserDataWebSocketClient

Would it be ok to propagate the error when its raised in the OnKeepAliveTimer function?

        /// <summary>
        /// Keep-alive timer callback.
        /// </summary>
        /// <param name="state"></param>
        private async void OnKeepAliveTimer(object state)
        {
            try
            {
                Logger?.LogDebug($"{nameof(SingleUserDataWebSocketClient)}.{nameof(OnKeepAliveTimer)}: User stream keep alive (\"{_listenKey}\").  [thread: {Thread.CurrentThread.ManagedThreadId}]");

                await _api.UserStreamKeepAliveAsync(User, _listenKey, (CancellationToken)state)
                    .ConfigureAwait(false);
            }
            catch (Exception e)
            {
                Logger?.LogError(e, $"{nameof(SingleUserDataWebSocketClient)}.{nameof(OnKeepAliveTimer)}: Failed to ping user data stream.");
            }
        }

Whilst I was testing the keep alive failed for some reason and I stopped getting user updates. I did see the errors in the log however. It would be good if the error was propagated. I also failed to get a notification that the socket was closed. I would imagine that if the keep alive token issn't issued then it would close eventually but for some reason my event didn't fire.

Illegal characters found in parameter

Hi.
I wrote some programm, it works for me on win10 and VS2017. But my friend can't launch it. He uses win10 and VS2017 too. When i use something like this,

var res = api.PlaceAsync(new LimitOrder(user)
            {
                Symbol = Symbol.BTC_USDT,
                Side = OrderSide.Buy,
                Quantity = 0.0001m,
                Price = 11500

            }).Result;

I fails with exception:

Inner Exception 1:
BinanceHttpException: [BadRequest]: 'Bad Request' - Illegal characters found in parameter 'quantity'; legal range is '^([0-9]{1,20})(\.[0-9]{1,20})?$'. (-1100)

What could it be? Thanks!

ETCBTC causing failure in GetSymbolsAsync method

From the API ETCBTC's symbol name is 'ETC' which fails the symbol name comparison within the GetSymbolsAsync method.

I think instead of this logic:

if (symbol.ToString() != jToken["symbol"].Value<string>())
{
    throw new BinanceApiException($"Symbol does not match assets ({jToken["symbol"].Value<string>()} != {symbol}).");
}

Taking just the symbol's name and use it would be a better solution.

Live Feeds Stopped

I am subscribed to live feeds for orderbook, candles and user account data. Just observed the data stop coming through.

All websockets are done through the RetryTaskController. No internet drop out at all.

It appears that Binance itself just stopped... Is there anything we could maybe do to subscribe to get a notification in this event?

Here is the end of my log:

[dbug] 08/02/2018 00:28:34 +00:00
DepthWebSocketClient: "{"lastUpdateId":61381760,"bids":[["7784.02000000","0.00027300",[]],["7784.01000000","0.00350000",[]],["7784.00000000","0.00350000",[]],["7783.99000000","0.00300000",[]],["7783.98000000","0.00650000",[]],["7783.97000000","0.00970900",[]],["7783.96000000","0.00650000",[]],["7783.95000000","0.00650000",[]],["7783.94000000","0.00650000",[]],["7783.93000000","0.00650000",[]],["7783.92000000","0.70000000",[]],["7783.91000000","0.10684500",[]],["7783.90000000","0.00350000",[]],["7783.84000000","0.00300000",[]],["7783.82000000","0.00650000",[]],["7783.81000000","0.50900500",[]],["7776.57000000","0.00280000",[]],["7775.17000000","1.13837300",[]],["7774.43000000","0.04803000",[]],["7774.01000000","0.00259000",[]]],"asks":[["7789.90000000","0.18342100",[]],["7790.00000000","0.06768000",[]],["7794.87000000","0.00650000",[]],["7794.88000000","0.88799100",[]],["7794.91000000","2.69621300",[]],["7796.21000000","0.00280000",[]],["7797.24000000","0.00280000",[]],["7800.28000000","0.00280000",[]],["7800.75000000","0.00280000",[]],["7801.77000000","0.00280000",[]],["7809.93000000","0.46100000",[]],["7809.94000000","0.60375000",[]],["7810.00000000","0.22260000",[]],["7812.77000000","0.00280000",[]],["7818.97000000","0.04721300",[]],["7818.98000000","1.13246500",[]],["7819.00000000","9.24307000",[]],["7819.30000000","0.04564300",[]],["7819.32000000","0.01120000",[]],["7822.61000000","0.00378800",[]]]}"
[dbug] 08/02/2018 00:29:10 +00:00
CandlestickWebSocketClient: "{"e":"kline","E":1518049747510,"s":"BTCUSDT","k":{"t":1518049680000,"T":1518049694788,"s":"BTCUSDT","i":"1m","f":14776398,"L":14776497,"o":"7790.00000000","c":"7784.02000000","h":"7794.91000000","l":"7783.81000000","v":"8.15356400","n":100,"x":true,"q":"63515.48081620","V":"6.60431900","Q":"51454.16786924","B":"0"}}"
[dbug] 08/02/2018 00:29:10 +00:00
CandlestickCache (BTCUSDT): Updating candlestick (open time: 08/02/2018 00:28:00). [thread: 24]
[dbug] 08/02/2018 00:32:11 +00:00
SingleUserDataWebSocketClient.OnKeepAliveTimer: User stream keep alive ("4jmcGH7DngUB0DTpVszE5ZqhKPRUTnvuRvAoNz2TpXtlY2emz4siNpdfRJu0"). [thread: 23]
[dbug] 08/02/2018 00:32:11 +00:00
BinanceHttpClient.RequestAsync: [PUT] "/api/v1/userDataStream?listenKey=4jmcGH7DngUB0DTpVszE5ZqhKPRUTnvuRvAoNz2TpXtlY2emz4siNpdfRJu0"
[dbug] 08/02/2018 00:32:12 +00:00
BinanceHttpClient: "{}"

Sample application throws timestamp error

account
! Exception: [BadRequest]: 'Bad Request' - Timestamp for this request is not valid. (-1021)

Should i enter a timezone somewhere? I entered my API keys in the setttings file succesfully.

BinanceApi constructor crashes on Android

Using the latest nuget package "v.0.2.0-alpha25" in an Xamarin.Android project, calling the parameterless constructor of BinanceApi crashes with System.NotImplementedException: The method or operation is not implemented.

Problems with multiple streams and Aggregate trade socket

Binance-0.2.0-alpha24

Here is the code that I have used for creating two test streams:

Dim TradeSocketLoggerFactory As ILoggerFactory = New Microsoft.Extensions.Logging.LoggerFactory()
        Dim TradeSocketStreamClientLogger As New Logger(Of DefaultWebSocketClient)(TradeSocketLoggerFactory)
        Dim TradeSocketStreamLogger As New Logger(Of BinanceWebSocketStream)(TradeSocketLoggerFactory) '
        Dim AggregateTradeSocketLogger As New Logger(Of AggregateTradeWebSocketClient)(TradeSocketLoggerFactory)

        TradeSocketLoggerFactory.AddFile("logs/Binance - TRADE SOCKET - ApiLogger." & Date.Now.ToSortableDate & ".txt", LogLevel.Information)

        m_BinanceTradeSocketStreamClient = New DefaultWebSocketClient(TradeSocketStreamClientLogger)
        m_BinanceTradeSocketStream = New BinanceWebSocketStream(m_BinanceTradeSocketStreamClient, TradeSocketStreamLogger)
        m_BinanceAggregateTradeSocket = New AggregateTradeWebSocketClient(m_BinanceTradeSocketStream, AggregateTradeSocketLogger)

        Me.m_BinanceAggregateTradeSocketCancel = New CancellationTokenSource

        Me.m_BinanceAggregateTradeSocket.SubscribeAndStreamAsync("BTCUSDT", m_BinanceAggregateTradeSocketCancel.Token)
        Me.m_BinanceAggregateTradeSocket.SubscribeAndStreamAsync("POEBTC", m_BinanceAggregateTradeSocketCancel.Token)

When I register one stream, say BTCUSDT, then I am able to receive events on the AggregateTrade event:

Private Sub m_BinanceAggregateTradeSocket_AggregateTrade(sender As Object, e As AggregateTradeEventArgs) Handles m_BinanceAggregateTradeSocket.AggregateTrade

However, when I register two streams, as in the snippet above, the event stop firing. I am still able to receive events on the message event handler for the trade socket stream:

Private Sub m_BinanceSocketTradeStreamClient_Message(sender As Object, e As WebSocketClientEventArgs) Handles m_BinanceTradeSocketStreamClient.Message

The message shows data for both streams. Here is the event log for the above test:

[info] 3/02/2018 9:16:35 PM +11:00
AggregateTradeWebSocketClient.Subscribe: "BTCUSDT" (callback: no). [thread: 1]
[info] 3/02/2018 9:16:35 PM +11:00
BinanceWebSocketStream.Subscribe: Adding stream ("btcusdt@aggTrade"). [thread: 1]
[info] 3/02/2018 9:16:35 PM +11:00
BinanceWebSocketStream.Subscribe: Adding callback for stream ("btcusdt@aggTrade"). [thread: 1]
[info] 3/02/2018 9:16:35 PM +11:00
BinanceWebSocketStream.StreamAsync: "wss://stream.binance.com:9443/ws/btcusdt@aggTrade" [thread: 1]
[info] 3/02/2018 9:16:36 PM +11:00
AggregateTradeWebSocketClient.Subscribe: "POEBTC" (callback: no). [thread: 1]
[warn] 3/02/2018 9:16:36 PM +11:00
BinanceWebSocketStream.Subscribe: IWebSocketClient is already streaming. [thread: 1]
[info] 3/02/2018 9:16:36 PM +11:00
BinanceWebSocketStream.Subscribe: Adding stream ("poebtc@aggTrade"). [thread: 1]
[info] 3/02/2018 9:16:36 PM +11:00
BinanceWebSocketStream.Subscribe: Adding callback for stream ("poebtc@aggTrade"). [thread: 1]
[fail] 3/02/2018 9:16:39 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:40 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:40 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 5]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:40 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 5]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:42 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 10]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:43 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:43 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 5]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:46 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:46 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.
Parameter name: value)
[fail] 3/02/2018 9:16:46 PM +11:00
BinanceWebSocketStream: Unhandled StreamAsync exception. [thread: 6]
(exception: Value cannot be null.

Exception when PlaceLimitOrder

I apologize if I did sth foolish, but I keep getting System.AggregateException: 'One or more errors occurred. (Object reference not set to an instance of an object.)' when I try to place limit order. (both TestPlaceOrder and real)
The inner exception stack trace is :
at Binance.Api.BinanceHttpClientExtensions.d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Binance.Api.BinanceApi.d__34.MoveNext()

I am using version 0.2.0-alpha27, please help!

Thanks.

candlestick retrieval for the interval not working

I am trying to use an API to retrieve historical data about candles.

var candles = await _api.GetCandlesticksAsync(Symbol.ADA_BTC, CandlestickInterval.Minutes_5, (1518048000000, 1517898000000));
// 1518048000000 = 2/6/2018 8:20:00 AM (UTC)
// 1517898000000 = 2/8/2018 2:00:00 AM (UTC)

Which yields 0 results. If the interval is taken away, then the data retrieval is working as expected.
Also, for the date range - I have tried using seconds, instead of milliseconds. Same result.

No exceptions or any kind of errors are thrown.

What could be wrong here?

Nuget Package for .NET Framework

Hi. For now, .NET Standard and .NET Core have limited application domain. Is it possible that the library can also be published on Nuget as .NET Framework build, too?

We cannot use .NET Standard on WPF yet. And UWP only works on Windows 10.

Reconnecting on the close event stops event handler AggregateTradeWebSocketClient.AggregateTrade firing

Hello,

I seem to have an issue with reconnecting the socket in the Close event (DefaultWebSocketClient.Close) . If I disconnect by executing Cancel on the token service and then reconnect with another button, the service reconnects successfully. But if I try and reconnect in the close event the AggregateTradeWebSocketClient.AggregateTrade event stop firing. The socket is transmitting data, however, because I can see aggregate trade update messages in the DefaultWebSocketClient.Message event handler
TryConnectOnClose.zip

The best way I can demonstrate is with a sample application. See attached.

Multiple Orderbook Cache

Due to the dependency injection, it looks like OrderBookCache has to be a singleton. It is not possible to have two or more OrderBookCaches in one instance.

I tried to listen to two orderbooks but seems the later will overwrite the websocket streaming of the first one. Just tried with "BTCUSDT" and "ETHUSDT" and I got:

OrderBookCache is already linked to this DepthWebSocketClient.
info: Binance.Api.WebSocket.BinanceWebSocketStream[0]
BinanceWebSocketStream.StreamAsync: "wss://stream.binance.com:9443/ws/ethbtc@depth20"

@sonvister can you please confirm my understanding?

failed to parse JSON api response

upon a call of GetOpenOrdersAsync
There is an existing stop-limit order for a combination. Seems like parser has troubles with it..

There was an exception: System.AggregateException: One or more errors occurred. (BinanceApi.GetOpenOrdersAsync failed to parse JSON api response: "[{"symbol":"BTSBNB","orderId":1240076,"clientOrderId":"suD1UBfBadgTMr8TaN57Up","price":"0.16120000","origQty":"70.00000000","executedQty":"0.00000000","status":"NEW","timeInForce":"GTC","type":"TAKE_PROFIT_LIMIT","side":"SELL","stopPrice":"0.16100000","icebergQty":"0.00000000","time":1513782457496,"isWorking":false}]") ---> Binance.Api.BinanceApiException: BinanceApi.GetOpenOrdersAsync failed to parse JSON api response: "[{"symbol":"BTSBNB","orderId":1240076,"clientOrderId":"suD1UBfBadgTMr8TaN57Up","price":"0.16120000","origQty":"70.00000000","executedQty":"0.00000000","status":"NEW","timeInForce":"GTC","type":"TAKE_PROFIT_LIMIT","side":"SELL","stopPrice":"0.16100000","icebergQty":"0.00000000","time":1513782457496,"isWorking":false}]" ---> System.Exception: Failed to convert order type: "TAKE_PROFIT_LIMIT"
at Binance.StringExtensions.ConvertOrderType(String type)
at Binance.Api.BinanceApi.FillOrder(Order order, JToken jToken)
at Binance.Api.BinanceApi.d__25.MoveNext()
--- End of inner exception stack trace ---

candlestick start and end dates - what is the time zone?

Short question - what is the datetime zone for candlesticks? I was thinking that it's in UTC, however, after calling the API a couple of times - I am feeling lost.

At the moment of writing current UTC time is: 2/8/2018 12:06:11 PM
Latest candle close dateime from API is: 2/8/2018 12:28:14 AM
Which is 12 hours difference.

This does not make any sense. It feels like that new candles are either added by binance with some delay, or candle timezone is -12 (average?? not exact) hours from UTC.

Therefore following clarifications are necessary:

  1. What is the datetime zone for candles (open/close DT) returned from API? Is it in UTC?
  2. How often does binance update/add new candles? Is there such info?

P.s. in my tests I was using 5 minute interval.

Thanks in advance,
Aleksandrs

A question that into the mind.

Greetings;
I want to get your views on a topic.
For example, I want to buy in a synchronous manner. In this, I remove the await tag and add .GetAwaiter (). GetResult () to the method end.
But when I do this, it does not come back to me even though it's done on the server side. I waited about 30 minutes to test, but there was no return. In some cases, asynchronous processing affects negatively. How should I follow a relevant path?
I also specify that the value of recwindow is 0.
how can I do these operations more quickly and synchronously? The advantage for my software being synchronous is that it may be waiting on acceptable values ​​that are not a problem waiting to happen. but I do and I do transactions with the time cycle and I chain transactions with each other. Automatic trading. If this is the case, asynchronous operations can cause jumps in some cases.

Commission throw exception

It looks like the commission returns from the api of binance as the quantity rather than the percent. Please confirm the issue and fix in the next release.

Alpha 21 is so Hard :(

Greetings;

Thanks for the new update. But the datetime surprise in the new update surprised me a lot. it was really difficult to make the project mistakes. TimeStamp was actually able to solve the transformation very easily on the user side. At least I did not encounter this problem at all. Well, whatever the developer knows, it's the best thing. Thank you.
It will be my proposal. A development for chart data is not bad. For example, it would be very helpful if there was a method to handle the indicator data.
SMA, TEMA, EMA, RSI, MACD indicators will add a truly unrivaled library. Even if it succeeds, it will be very good and far ahead of all the stock market libraries. Because it is really difficult to create these indicators and equalize and process the data, and on our behalf this information will not be as stable and fast as yours.
I wish you good work.
Best regards...

BinanceHttpException on Win Server 2016.

Hi, I have another problem, maybe you now what's the problem.
When I use something like GetOrderBookTopAsync() or -GetOpenOrdersAsync() on Win server 2016 (I install VS 2017 and .NET Core 2.0) it returns sometimes Binance.Api.BinanceHttpException: [Forbidden]: 'Forbidden' - [NO MSG] [NO CODE]. When i retry code - it returns the same error. I'm waiting about 1-2 minutes and problem dissapears.
I'm trying to re-create this problem on local machine - no result. When it crashes on server - it passed on local machine.

I compare request for two machines - they are the same.
But one difference - server send's and recieve's requests 4-5 times faster.

Thx.

Failing to parse JSON for GetDepositAddress

Was getting deposit address for BTC, and I see this error:

Binance.Api.BinanceApiException: 'BinanceApi.GetDepositAddressAsync failed to parse JSON api response: "{"address":"blah","success":true,"addressTag":"","url":"https://btc.com/[Ljava.lang.String;@4ea6f448"}"'

ArgumentNullException: Value cannot be null.

I don't use it, but I'm implementing and testing all features you have implemented in your wrapper, and came across this. No rush, for me anyway, I dont need this.

Timestamp error

Helloes,
the first call to the API always throws the timestamp exception:

using (var user = new BinanceApiUser("key", "secret"))
{
      var api = new BinanceApi();
      var order = await api.GetAccountInfoAsync(user);
      var deposits = await api.GetDepositsAsync(user, "BTC");
      var withdrawals = await api.GetWithdrawalsAsync(user, "BTC");
      var account = await api.GetTradesAsync(user, Symbol.XVG_BTC);
}

screenshot_2

It doesn't appear when continued and called for the second time and so on.

I can always handle the exception and do the call again as a workaround, however you might want to fix this.

Unit test fix for commit 80dcb6ed869de65bc767edda10ead09fce0a8455

Apply patch @sonvister :

From f52bd81d64f1ed5ad8e374938593c893d8b7ce92 Mon Sep 17 00:00:00 2001
From: brad [email protected]
Date: Wed, 3 Jan 2018 17:18:09 -0500
Subject: [PATCH] update unit test to match
80dcb6e implementation

---
test/Binance.Tests/Market/SymbolStatisticsTest.cs | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/test/Binance.Tests/Market/SymbolStatisticsTest.cs b/test/Binance.Tests/Market/SymbolStatisticsTest.cs
index a078bbf..363dd9b 100644
--- a/test/Binance.Tests/Market/SymbolStatisticsTest.cs
+++ b/test/Binance.Tests/Market/SymbolStatisticsTest.cs
@@ -61,7 +61,8 @@ namespace Binance.Tests.Market
Assert.Throws("lastTradeId", () => new SymbolStatistics(symbol, period, priceChange, priceChangePercent, weightedAveragePrice, previousClosePrice, lastPrice, lastQuantity, bidPrice, bidQuantity, askPrice, askQuantity, openPrice, highPrice, lowPrice, volume, quoteVolume, openTime, closeTime, lastTradeId, firstTradeId, tradeCount));

Assert.Throws("tradeCount", () => new SymbolStatistics(symbol, period, priceChange, priceChangePercent, weightedAveragePrice, previousClosePrice, lastPrice, lastQuantity, bidPrice, bidQuantity, askPrice, askQuantity, openPrice, highPrice, lowPrice, volume, quoteVolume, openTime, closeTime, firstTradeId, lastTradeId, -1));
- Assert.Throws("tradeCount", () => new SymbolStatistics(symbol, period, priceChange, priceChangePercent, weightedAveragePrice, previousClosePrice, lastPrice, lastQuantity, bidPrice, bidQuantity, askPrice, askQuantity, openPrice, highPrice, lowPrice, volume, quoteVolume, openTime, closeTime, firstTradeId, lastTradeId, tradeCount + 1));
+ // TODO: Binance API stream occasionally returns invalid trade counts...
+ //Assert.Throws("tradeCount", () => new SymbolStatistics(symbol, period, priceChange, priceChangePercent, weightedAveragePrice, previousClosePrice, lastPrice, lastQuantity, bidPrice, bidQuantity, askPrice, askQuantity, openPrice, highPrice, lowPrice, volume, quoteVolume, openTime, closeTime, firstTradeId, lastTradeId, tradeCount + 1));
}

[Fact]
--
2.9.2.windows.1

symbols

Hi,

I'm getting exception : Symbol does not match assets (ETC != ETCBTC) when doing the "symbols" command. I think this was working before...

Thanks

Buy And Sell Fee Calculates.

Greetings;
I felt I needed to consult you on a problem.
My problem is that way. when I have a purchase or sale transaction, I have them on a bond basis.
For example, I get 3 USDT money and I get BTC at 11200.00. I have to get 0.00026786 BTC according to the calculation. but when we add Fee to the account, this amount is even lower. Now let's face it.
I record this when I register it in the database, but when the feeler on the binance side is deducted, the purchase BTC amount is lower. When I sell it, it is not the real value of binance but it opens my sales order. in this case sometimes it is likely that the rest of the body is taking it. This is affecting my other purchases. I am getting insufficient funds in my purchases awaiting sale as the balance is getting low.
Do we have a relevant area for buying and selling, for example?
I would like to make the purchase and sale stabilize in this way, indicating how much real amount I will get in the amount of USDT I want to buy and the actual value of the current coin I am going to buy. Is there a feature that we can use in this way?
If not, is it possible to add it? If you can not add or wait, do you have a temporary solution to me until this time?
I am using C # Windows Forms.
Thank you very much for your interest.

I did not find your donation links.
Could you please share your donation links?
I am using such a large amount of labor. And as a casualty, I would like to make a contribution to you. As much as I can
.
Best regards...

missing symbols in latest available version

Latest available version in nuget is 0.2.0-alpha.8. However, it seems to me missing some of the new symbols in API. On the other hand, the source code in Git already contains new codes. For example:
public static readonly Symbol NAV_BTC

Is it possible to upgrade to latest available version (trunc) somehow locally?
What is the build cycle of this project and how often when can we expect to get updates, even in Alpha releases?

In the example above, I'd like to have support for NAV_BTC. I would to appreciate to hear any advices on how to add support for it locally when there is no latest build available..

Thanks.

Extension With MVC Web Application

Greetings;
Your plug-in is really very successful. I used it in my desktop application, but I can not use it in my MVC application.

var client = api.HttpClient; // ... property on IBinanceApi.

I can not find the part.
I have not found any simple link and usage examples in the document section for MVC web.
Could you tell me how to use it on the web side?
When I write it under ActionResult, it is waiting for processing (hours) but I can not get anything.

Trouble opening the solution file in VS 2015

After cloning the project, having some trouble opening the solution file in VS 2015. I'm curious to hear if your build environment is significantly different than mine?

Attached is the specific error that I'm receiving

I'm also having a similar error while using the nuget package while targeting .NET 4.5.2. But that may be related to this
capture

Streams mysteriously stopped

Hey, making a project using this (Thanks btw!) and have run it for 18+ hours several times (before finding a bug in my own logic and restarting after making the fix).
I restarted last night at around 2am, for this reason. I left it run overnight whilst I went to be. When I came back to it, the 2 streams I had setup had stopped.
I started off an OrderBook stream for BTC_USDT, and another for AccountInfo. The last orderbook update was at just past 6am, (but I was looking at it at gone 7am). Also during that time a trade had filled, but the program had not been notified of this (as it hadn't updated to show that like it should have done).

Unfortuntely, I turned off the main logging, as it was messing up the appearance of my console. Ive turned it back on now, but not added it to console so it only goes to file.

Not sure why this may have happened, perhaps my internet dropped for a period of time? What would be best for me to do, have something that checks to see how long ago the most recent update was, and if its out of date then try and reconnect somehow? Is there any event fired or something when streams are stopped for any reason other than I asked them to?

[Question] Serializing an OrderBook to JSON?

Hi, I am using your Binance library to make a tool for simulations and graphs, my program is split in two. One part mines data in realtime with a specific interval and duration, then when it's done it serializes it to JSON and saves it to disc. I can then run the second part of the program which reads one of my many saved datafiles, deserializes it back into a list of OrderBooks and runs some analysis and simulations on them. I do realize that I can get historic data directly from Binance but I would prefer to do it through regular GetOrderBookAsync because of the control it gives me.

Serializing the OrderBook works without any problems, but deserializing it is proving a bit troublesome.

The first error I encountered was this: Newtonsoft.Json.JsonSerializationException:
'Unable to find a constructor to use for type Binance.Market.OrderBookTop. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'orderbook.Top.Symbol', line 16, position 23.'

I solved this one by adding the [JsonConstructor] attribute to this constructor:
public OrderBookTop(string symbol, decimal bidPrice, decimal bidQuantity, decimal askPrice, decimal askQuantity)

This solved that error but gives me an even more troublesome issue.

In this constructor of OrderBook: public OrderBook(string symbol, long lastUpdateId, IEnumerable<(decimal, decimal)> bids, IEnumerable<(decimal, decimal)> asks)
I get the following error: System.ArgumentException: 'An entry with the same key already exists.'
On this line: _bids.Add(bid.Item1, new OrderBookPriceLevel(bid.Item1, bid.Item2));

When looking inside of the "bids" array all the entries are "0, 0" in price and quantity.
I have absolutely no idea how to solve this, which leads me to my question.
Have you managed to serialize an OrderBook before? Do you have an example of how to do that?

Here is a minimal example of how to reproduce the issue: https://pastebin.com/FMceXnLj

FileNotFoundException

I get the following exception:
Could not load file or assembly 'Microsoft.Extensions.Options, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.

I am truing to do the simplest test. Build fine, but throws exception on run-time.

Code:

class Program { static void Main(string[] args) { var a = new BinanceApi(); } }

Correct way to stop streaming

Hello,

Many thanks for your work on this project.
I am just starting to use your API and have successfully streamed trade information using the AggregateTradeWebSocketClient with the following code:

        Private WithEvents m_BinanceAggregateTradeSocket As AggregateTradeWebSocketClient

        cancel = New CancellationTokenSource
        streamTask = m_BinanceAggregateTradeSocket.StreamAsync("ETHBTC", cancel.Token)

I retrieve trade updates as expected handling the event on the AggregateTradeWebSocketClient:

        Private Sub m_BinanceAggregateTradeSocket_AggregateTrade(sender As Object, e As 
                 AggregateTradeEventArgs) Handles m_BinanceAggregateTradeSocket.AggregateTrade

I have used the same instance of m_BinanceAggregateTradeSocket to subscribe to multiple symbols and this also works well. The problem is I would like to remove streaming for a symbol at a certain point. When I use the CancellationTokenSource to cancel, it cancels all of the streaming symbols. This is the case even though I create multiple instances of CancellationTokenSource and link each instance to a particular symbol.

What would be the best way to stop streaming a particular symbol?

I have also tried the Unsubscribe function on the WebSocketClient but I can't get this to work.

Thanks in advance for your help.

LOT_SIZE errors and rounding

I'm sure I'm doing something wrong, but recently I can't place orders often because of the LOT_SIZE error. What's the ideal way to know how to round my quantity requests? This wasn't happening to me a few weeks ago, I'm not sure if Binance changed, my code or this API.

Any help is much appreciated!

Which .net version to use?

I have tried using both 2.0 and 4.7.1 but none of these seems to work and I always get the error which says that the package has no refference for my version of .net framework

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.