Binance Client Websocket
🛠️ C# client for Binance websocket API
Install / Use
npx skills add Marfusios/binance-client-websocketInstalls into whichever agent you are using.
README

Binance websocket API client
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
License:
Apache License 2.0
Features
- installation via NuGet (Binance.Client.Websocket)
- public and authenticated API
- targets
netstandard2.0,netstandard2.1,net6.0,net7.0,net8.0,net9.0,net10.0 - built on Websocket.Client 5.5.0 for websocket transport, reconnects, and lower-allocation message handling
- 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:
API coverage
| PUBLIC | Covered |
|-------------------------|:-------:|
| Aggregate trades | ✔ |
| Trades | ✔ |
| Kline/Candlesticks | |
| Individual mini tickers | |
| All mini tickers | |
| Individual tickers | |
| All tickers | |
| Partial orderbook | ✔ |
| Diff. orderbook | ✔ |
| PRIVATE | Covered |
|-------------------------|:----------:|
| Account update | |
| Balance update | |
| Order update | ✔ |
Pull Requests are welcome!
Other websocket libraries
<table> <tr> <td> <a href="https://github.com/Marfusios/crypto-websocket-extensions"><img src="https://raw.githubusercontent.com/Marfusios/crypto-websocket-extensions/master/cwe_logo.png" height="80px"></a> <br /> <a href="https://github.com/Marfusios/crypto-websocket-extensions">Extensions</a> <br /> <span>All order books together, etc.</span> </td> <td> <a href="https://github.com/Marfusios/bitmex-client-websocket"><img src="https://user-images.githubusercontent.com/1294454/27766319-f653c6e6-5ed4-11e7-933d-f0bc3699ae8f.jpg"></a> <br /> <a href="https://github.com/Marfusios/bitmex-client-websocket">Bitmex</a> </td> <td> <a href="https://github.com/Marfusios/bitfinex-client-websocket"><img src="https://user-images.githubusercontent.com/1294454/27766244-e328a50c-5ed2-11e7-947b-041416579bb3.jpg"></a> <br /> <a href="https://github.com/Marfusios/bitfinex-client-websocket">Bitfinex</a> </td> <td> <a href="https://github.com/Marfusios/coinbase-client-websocket"><img src="https://user-images.githubusercontent.com/1294454/41764625-63b7ffde-760a-11e8-996d-a6328fa9347a.jpg"></a> <br /> <a href="https://github.com/Marfusios/coinbase-client-websocket">Coinbase</a> </td> </tr> </table>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.ReconnectTimeout. 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.ErrorReconnectTimeout, 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](ht
Related Skills
node-connect
385.5kDiagnose OpenClaw Android, iOS, or macOS node pairing, QR/setup code, route, auth, and connection failures.
blender-python-addon
40.5kBlender Python add-on rules for operators, panels, properties, registration, testing, and API-safe scripting
flutter-development-guidelines-cursorrules-prompt-file
40.5kCursor rules for Flutter development with MVVM architecture, Riverpod state management, Material widgets, and Dart style guidelines.
commit-push-pr
140.6kCommit, push, and open a PR
