All Projects β†’ Marfusios β†’ binance-client-websocket

Marfusios / binance-client-websocket

Licence: Apache-2.0 license
πŸ› οΈ C# client for Binance websocket API

Programming Languages

C#
18002 projects
HCL
1544 projects

Projects that are alternatives of or similar to binance-client-websocket

BitView
A crypto portfolio written in Flutter. It supports Binance, Bittrex, HitBTC, Coinbase, Coinbase Pro and Mercatox
Stars: ✭ 50 (+21.95%)
Mutual labels:  exchange, binance, binance-api
bitmex-client-websocket
πŸ› οΈ C# client for Bitmex websocket API
Stars: ✭ 60 (+46.34%)
Mutual labels:  api-client, exchange
Cryptotrader
A cryptocurrency trader for all famous exchanges
Stars: ✭ 228 (+456.1%)
Mutual labels:  exchange, binance
Binance
A .NET Standard Binance API library.
Stars: ✭ 199 (+385.37%)
Mutual labels:  api-client, binance
Twitter Activated Crypto Trading Bot
Buys crypto through keyword detection in new tweets. Executes buy in 1 second and holds for a given time (e.g. Elon tweets 'doge', buys Dogecoin and sells after 5 minutes). Tested on Kraken and Binance exchanges
Stars: ✭ 92 (+124.39%)
Mutual labels:  binance, binance-api
My Token
πŸ“ˆTrack token prices of your favorite exchanges in terminal!
Stars: ✭ 141 (+243.9%)
Mutual labels:  exchange, binance
Pykrakenapi
A python implementation of the Kraken API.
Stars: ✭ 124 (+202.44%)
Mutual labels:  api-client, exchange
Crypto vba
An Excel/VBA project to communicate with various cryptocurrency exchanges APIs
Stars: ✭ 103 (+151.22%)
Mutual labels:  exchange, binance
java-binance-api
Java Binance API Client
Stars: ✭ 72 (+75.61%)
Mutual labels:  binance, binance-api
hands-on-elixir-and-otp-cryptocurrency-trading-bot
Source code to generate the "Hands-on Elixir & OTP: Cryptocurrency trading bot" book
Stars: ✭ 210 (+412.2%)
Mutual labels:  binance, binance-api
binance-rs-async
Async client for the Binance APIs
Stars: ✭ 74 (+80.49%)
Mutual labels:  binance, binance-api
Cryptocurrency Portfolio
Google Sheets automatic creation with Google Apps Script (GAS) for managing a cryptocurrency tracking spreadsheet with multi exchanges
Stars: ✭ 134 (+226.83%)
Mutual labels:  exchange, binance
Tardis Node
Convenient access to tick-level real-time and historical cryptocurrency market data via Node.js
Stars: ✭ 126 (+207.32%)
Mutual labels:  exchange, binance
Krypto Trading Bot
Self-hosted crypto trading bot (automated high frequency market making) written in C++
Stars: ✭ 2,589 (+6214.63%)
Mutual labels:  exchange, binance
Kupi Terminal
Ccxt based, open source, customized, extendable trading platform that supports 130+ crypto exchanges.
Stars: ✭ 104 (+153.66%)
Mutual labels:  exchange, binance
Coinbase Pro Node
Coinbase Pro API written in TypeScript and covered by tests.
Stars: ✭ 116 (+182.93%)
Mutual labels:  api-client, exchange
Mida
The open-source and cross-platform trading framework
Stars: ✭ 263 (+541.46%)
Mutual labels:  exchange, binance
Crypto Trading Bot
Cryptocurrency trading bot in javascript for Bitfinex, Bitmex, Binance, FTX, Bybit ... (public edition)
Stars: ✭ 1,089 (+2556.1%)
Mutual labels:  exchange, binance
Frostybot Js
Frostybot-JS is a cryptocurrency trading API endpoint, designed to execute webhook or REST requests as orders on a variety of well-known exchanges. While primarily designed to automate your Tradingview strategies, Frostybot can also be integrated with any other software using webhooks or REST. Bitmex, FTX, Deribit and Binance are supported.
Stars: ✭ 72 (+75.61%)
Mutual labels:  exchange, binance
Coinapi Sdk
SDKs for CoinAPI
Stars: ✭ 238 (+480.49%)
Mutual labels:  api-client, exchange

Logo

Binance websocket API client Build Status NuGet version

This is a C# implementation of the Binance websocket API found here:

https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md

Releases and breaking changes

License:

Apache License 2.0

Features

  • installation via NuGet (Binance.Client.Websocket)
  • public and authenticated API
  • targeting .NET Standard 2.0 (.NET Core, Linux/MacOS compatible)
  • reactive extensions (Rx.NET)
  • integrated logging abstraction (LibLog)

Usage

var exitEvent = new ManualResetEvent(false);
var url = BinanceValues.ApiWebsocketUrl;

using (var communicator = new BinanceWebsocketCommunicator(url))
{
    using (var client = new BinanceWebsocketClient(communicator))
    {
        client.Streams.TradesStream.Subscribe(response =>
        {
            var trade = response.Data;
            Console.WriteLine($"Trade executed [{trade.Symbol}] price: {trade.Price}");
        });

        client.SetSubscriptions(
            new TradeSubscription("btcusdt"),
            new TradeSubscription("ethbtc"),
            new TradeSubscription("bnbbtc"),
            );
        await communicator.Start();

        exitEvent.WaitOne(TimeSpan.FromSeconds(30));
    }
}

More usage examples:

  • console sample (link)
  • integration tests (link)
  • desktop sample (link)

API coverage

PUBLIC Covered
Aggregate trades βœ”
Trades βœ”
Kline/Candlesticks
Individual mini tickers
All mini tickers
Individual tickers
All tickers
Partial orderbook βœ”
Diff. orderbook βœ”

Pull Requests are welcome!

Other websocket libraries


Extensions
All order books together, etc.

Bitmex

Bitfinex

Coinbase

Reconnecting

There is a built-in reconnection which invokes after 1 minute (default) of not receiving any messages from the server. It is possible to configure that timeout via communicator.ReconnectTimeoutMs. Also, there is a stream ReconnectionHappened which sends information about a type of reconnection. However, if you are subscribed to low rate channels, it is very likely that you will encounter that timeout - higher the timeout to a few minutes or call PingRequest by your own every few seconds.

In the case of Binance outage, there is a built-in functionality which slows down reconnection requests (could be configured via communicator.ErrorReconnectTimeoutMs, the default is 1 minute).

Backtesting

The library is prepared for backtesting. The dependency between Client and Communicator is via abstraction IBinanceCommunicator. There are two communicator implementations:

  • BinanceWebsocketCommunicator - a realtime communication with Binance via websocket API.
  • BinanceFileCommunicator - a simulated communication, raw data are loaded from files and streamed. If you are interested in buying historical raw data (trades, order book events), contact me.

Feel free to implement IBinanceCommunicator on your own, for example, load raw data from database, cache, etc.

Usage:

var communicator = new BinanceFileCommunicator();
communicator.FileNames = new[]
{
    "data/binance_raw_btcusdt_2018-11-13.txt"
};
communicator.Delimiter = ";;";

var client = new BinanceWebsocketClient(communicator);
client.Streams.TradesStream.Subscribe(response =>
{
    // do something with trade
});

await communicator.Start();

Multi-threading

Observables from Reactive Extensions are single threaded by default. It means that your code inside subscriptions is called synchronously and as soon as the message comes from websocket API. It brings a great advantage of not to worry about synchronization, but if your code takes a longer time to execute it will block the receiving method, buffer the messages and may end up losing messages. For that reason consider to handle messages on the other thread and unblock receiving thread as soon as possible. I've prepared a few examples for you:

Default behavior

Every subscription code is called on a main websocket thread. Every subscription is synchronized together. No parallel execution. It will block the receiving thread.

client
    .Streams
    .TradesStream
    .Subscribe(trade => { code1 });

client
    .Streams
    .BookStream
    .Subscribe(book => { code2 });

// 'code1' and 'code2' are called in a correct order, according to websocket flow
// ----- code1 ----- code1 ----- ----- code1
// ----- ----- code2 ----- code2 code2 -----

Parallel subscriptions

Every single subscription code is called on a separate thread. Every single subscription is synchronized, but different subscriptions are called in parallel.

client
    .Streams
    .TradesStream
    .ObserveOn(TaskPoolScheduler.Default)
    .Subscribe(trade => { code1 });

client
    .Streams
    .BookStream
    .ObserveOn(TaskPoolScheduler.Default)
    .Subscribe(book => { code2 });

// 'code1' and 'code2' are called in parallel, do not follow websocket flow
// ----- code1 ----- code1 ----- code1 -----
// ----- code2 code2 ----- code2 code2 code2

Parallel subscriptions with synchronization

In case you want to run your subscription code on the separate thread but still want to follow websocket flow through every subscription, use synchronization with gates:

private static readonly object GATE1 = new object();
client
    .Streams
    .TradesStream
    .ObserveOn(TaskPoolScheduler.Default)
    .Synchronize(GATE1)
    .Subscribe(trade => { code1 });

client
    .Streams
    .BookStream
    .ObserveOn(TaskPoolScheduler.Default)
    .Synchronize(GATE1)
    .Subscribe(book => { code2 });

// 'code1' and 'code2' are called concurrently and follow websocket flow
// ----- code1 ----- code1 ----- ----- code1
// ----- ----- code2 ----- code2 code2 ----

Async/Await integration

Using async/await in your subscribe methods is a bit tricky. Subscribe from Rx.NET doesn't await tasks, so it won't block stream execution and cause sometimes undesired concurrency. For example:

client
    .Streams
    .TradesStream
    .Subscribe(async trade => {
        // do smth 1
        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
        // do smth 2
    });

That await Task.Delay won't block stream and subscribe method will be called multiple times concurrently. If you want to buffer messages and process them one-by-one, then use this:

client
    .Streams
    .TradesStream
    .Select(trade => Observable.FromAsync(async () => {
        // do smth 1
        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
        // do smth 2
    }))
    .Concat() // executes sequentially
    .Subscribe();

If you want to process them concurrently (avoid synchronization), then use this

client
    .Streams
    .TradesStream
    .Select(trade => Observable.FromAsync(async () => {
        // do smth 1
        await Task.Delay(5000); // waits 5 sec, could be HTTP call or something else
        // do smth 2
    }))
    .Merge() // executes concurrently
    // .Merge(4) you can limit concurrency with a parameter
    // .Merge(1) is same as .Concat()
    // .Merge(0) is invalid (throws exception)
    .Subscribe();

More info on Github issue.

Don't worry about websocket connection, those sequential execution via .Concat() or .Merge(1) has no effect on receiving messages. It won't affect receiving thread, only buffers messages inside TradesStream.

But beware of producer-consumer problem when the consumer will be too slow. Here is a StackOverflow issue with an example how to ignore/discard buffered messages and always process only the last one.

Desktop application (WinForms or WPF)

Due to the large amount of questions about integration of this library into a desktop application (old full .NET Framework), I've prepared WinForms example (link).

WinForms example screen

Available for help

I do consulting, please don't hesitate to contact me if you have a custom solution you would like me to implement (web, [email protected])

Donations gratefully accepted.

  • Donate with Bitcoin
  • Donate with Litecoin
  • Donate with Ethereum
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].