Crypto.Websocket.Extensions 2.8.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Crypto.Websocket.Extensions --version 2.8.0                
NuGet\Install-Package Crypto.Websocket.Extensions -Version 2.8.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Crypto.Websocket.Extensions" Version="2.8.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Crypto.Websocket.Extensions --version 2.8.0                
#r "nuget: Crypto.Websocket.Extensions, 2.8.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Crypto.Websocket.Extensions as a Cake Addin
#addin nuget:?package=Crypto.Websocket.Extensions&version=2.8.0

// Install Crypto.Websocket.Extensions as a Cake Tool
#tool nuget:?package=Crypto.Websocket.Extensions&version=2.8.0                

Logo

Cryptocurrency websocket extensions Build Status NuGet version

This is a library that provides extensions to cryptocurrency websocket exchange clients.

It helps to unify data models and usage of more clients together.

Releases and breaking changes

License:

Apache License 2.0

Features

Supported exchanges

Logo Name Websocket client
bitfinex Bitfinex bitfinex-client-websocket
bitmex BitMEX bitmex-client-websocket
binance Binance binance-client-websocket
coinbase Coinbase coinbase-client-websocket
bitstamp Bitstamp bitstamp-client-websocket

Extensions

Order book

  • efficient data structure, based on howtohft blog post
  • CryptoOrderBook class - unified order book across all exchanges
  • support for L2 (grouped by price), L3 (every single order) market data
  • support for snapshots and deltas/diffs
  • provides streams:
    • OrderBookUpdatedStream - streams on an every order book update
    • BidAskUpdatedStream - streams when bid or ask price changed (top level of the order book)
    • TopLevelUpdatedStream - streams when bid or ask price/amount changed (top level of the order book)
  • provides properties and methods:
    • BidLevels and AskLevels - ordered array of current state of the order book
    • BidLevelsPerPrice and AskLevelsPerPrice - dictionary of all L3 orders split by price
    • FindLevelByPrice and FindLevelById - returns specific order book level

Usage:

var url = BitmexValues.ApiWebsocketUrl;
var communicator = new BitmexWebsocketCommunicator(url);
var client = new BitmexWebsocketClient(communicator);

var pair = "XBTUSD";

var source = new BitmexOrderBookSource(client);
var orderBook = new CryptoOrderBook(pair, source);

// orderBook.BidAskUpdatedStream.Subscribe(xxx)
orderBook.OrderBookUpdatedStream.Subscribe(quotes =>
{
    var currentBid = orderBook.BidPrice;
    var currentAsk = orderBook.AskPrice;

    var bids = orderBook.BidLevels;
    // xxx
});
        
await communicator.Start();

Trades

  • ITradeSource - unified trade info stream across all exchanges

Orders (authenticated)

  • CryptoOrders class - unified orders status across all exchanges with features:
    • orders view and searching - only executed, search by id, client id, etc.
    • our vs all orders - using client id prefix to distinguish between orders

Position (authenticated)

  • IPositionSource - unified position info stream across all exchanges

Wallet (authenticated)

  • IWalletSource - unified wallet status stream across all exchanges

More usage examples:

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

Pull Requests are welcome!

Powerfull Rx.NET

Don't forget that you can do pretty nice things with reactive extensions and observables. For example, if you want to check latest bid/ask prices from all exchanges all together, you can do something like this:

Observable.CombineLatest(new[]
            {
                bitmexOrderBook.BidAskUpdatedStream,
                bitfinexOrderBook.BidAskUpdatedStream,
                binanceOrderBook.BidAskUpdatedStream,
            })
            .Subscribe(HandleQuoteChanged);

// Method HandleQuoteChanged(IList<CryptoQuotes> quotes)
// will be called on every exchange's price change

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.

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, m@mkotas.cz)

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.9.0 139 6/17/2024
2.8.0 112 4/29/2024
2.7.1 438 2/20/2024
2.7.0 241 2/16/2024
2.6.40 1,627 11/20/2021
2.5.39 978 8/9/2021
2.5.37 950 3/18/2021
2.5.35 857 3/3/2021
2.5.34 816 2/2/2021
2.5.33 830 1/27/2021
2.5.32 840 1/27/2021
2.5.31 817 1/27/2021
2.5.30 838 1/24/2021
2.5.29 909 11/30/2020
2.4.28 913 10/18/2020
2.4.24 884 9/24/2020
2.4.23 958 9/7/2020
2.4.18 938 8/21/2020
2.4.16 932 8/21/2020
2.4.15 971 8/13/2020
2.4.14 908 8/8/2020
2.4.11 918 7/2/2020
2.4.10 954 5/4/2020
2.4.5 937 3/23/2020
2.4.2 925 3/10/2020
2.3.55 1,211 1/24/2020
2.3.53 994 1/17/2020
2.3.52 898 1/16/2020
2.3.51 960 12/29/2019
2.2.50 962 12/18/2019
2.2.49 978 12/10/2019
2.2.47 937 12/6/2019
2.2.46 951 12/6/2019
2.2.45 995 11/13/2019
2.2.42 977 11/7/2019
2.1.41 967 11/7/2019
2.1.40 990 10/8/2019
2.1.39 1,161 8/30/2019
2.1.38 1,042 8/22/2019
2.1.35 1,003 8/20/2019
2.0.27 1,080 8/6/2019
2.0.25 1,104 8/5/2019
2.0.24 1,036 8/4/2019
2.0.23 1,033 8/4/2019
2.0.22 1,042 7/19/2019
2.0.21 1,027 7/16/2019
1.0.18 998 7/16/2019
1.0.17 992 7/12/2019
1.0.16 1,021 7/11/2019
1.0.15 1,019 7/10/2019
1.0.14 1,068 7/10/2019
1.0.13 1,049 7/10/2019
1.0.12 1,103 4/23/2019
1.0.11 1,046 4/7/2019
1.0.10 1,029 4/5/2019
1.0.9 1,050 4/5/2019
1.0.8 1,037 4/5/2019
1.0.7 1,024 4/5/2019
1.0.6 1,047 4/5/2019
1.0.5 1,036 4/5/2019
1.0.4 1,024 4/5/2019
1.0.3 1,022 4/5/2019
1.0.2 1,064 4/4/2019

Enhancements