Skip to content

WebSocket Clients

sonvister edited this page Mar 16, 2018 · 9 revisions

This library provides a complete implementation of the Binance WebSocket API.

General Information

Dependency Injection

As shown, each of the web socket clients can be instantiated using the dependency injection ServiceProvider.

var client = serviceProvider.GetService<IAggregateTradeWebSocketClient>();

For simplicity, the following examples use the default constructors to instantiate services.

Automatic Streaming

The web socket clients include automatic stream control triggered by calls to subscribe/unsubscribe. Streaming begins after the first subscribe and ends after the last unsubscribe.

Error Handling

An Error event handler can be added to receive ErrorEventArgs events.

client.Error += (s, e) => { /* ... */ };

Combined Streams

Instead of opening multiple web socket connections, a single web socket can be used to stream data from multiple endpoints. If multiple subscriptions are made using the same client, then that client will automatically use combined streams. To avoid using combined streams, instantiate a web socket client for each subscription.

To combine streams of multiple endpoint types (e.g. aggregate trade streams and depth streams), use the same BinanceWebSocketStream, BinanceWebSocketStreamController, or BinanceWebSocketStreamPublisher instance depending on you application. When using the dependency injection framework, a single, application-wide, combined web socket stream can be configured with the following:

serviceCollection.AddBinance(useSingleCombinedStream: true);

NOTE: Keep in mind when using combined streams that clients are sharing a single web socket. Any changes to subscriptions, once streaming begins, will interrupt the data flow to all clients when the shared web socket is restarted with a new URI.

Reference: Binance Official API

Depth Streams

Get real-time depth update events using an IDepthWebSocketClient. Set a valid limit to utilize the partial depth stream.

Reference: Official Binance API - Partial Depth Stream
Reference: Official Binance API - Diff. Depth Stream

// Initialize client.
var client = new AggregateTradeWebSocketClient();

// Subscribe to symbol with optional callback (begin streaming).
client.Subscribe(symbol, evt => {
    // Handle depth update event for symbol.
});

// ...

// Unsubscribe all symbols (end streaming).
client.Unsubscribe();

Optionally, add a DepthUpdate event handler that receives DepthUpdateEventArgs events for all subscribed symbols.

client.DepthUpdate += (s, e) => { /* ... */ };

Advanced Usage

View an example of instantiating the internal components of the web socket client.

// Initialize client.
var client = new DepthClient();

// Initialize stream.
var webSocket = new BinanceWebSocketStream();

// Initialize controller.
using (var controller = new RetryTaskController(webSocket.StreamAsync))
{
	// Optionally, add error event handler.
    controller.Error += (s, e) => { /* ... */ };

    // Subscribe to symbol with optional callback.
    client.Subscribe(symbol, evt => {
        // Handle depth update event for symbol.
    });

    // Set stream URI using client subscribed streams.
    webSocket.Uri = BinanceWebSocketStream.CreateUri(client);
    // NOTE: This must be done after client subscribe.

    // Route stream messages to client.
    webSocket.Message += (s, e) => client.HandleMessage(e.Subject, e.Json);

    // Begin streaming.
    controller.Begin();

    // ...

	// End streaming.
    await controller.CancelAsync();
}

Candlestick Streams

Get real-time candlestick events using ICandlestickWebSocketClient.

Reference: Official Binance API

// Initialize client.
var client = new CandlestickWebSocketClient();

// Subscribe to symbol with optional callback (begin streaming).
client.Subscribe(symbol, CandlestickInterval.Hour, evt => {
    // Handle candlestick event for symbol.
});

// ...

// Unsubscribe all symbols (end streaming).
client.Unsubscribe();

Optionally, add a Candlestick event handler that receives CandlestickEventArgs events for all subscribed symbols.

client.Candlestick += (s, e) => { /* ... */ };

Advanced Usage

View an example of instantiating the internal components of the web socket client.

// Initialize client.
var client = new CandlestickClient();

// Initialize stream.
var webSocket = new BinanceWebSocketStream();

// Initialize controller.
using (var controller = new RetryTaskController(webSocket.StreamAsync))
{
	// Optionally, add error event handler.
    controller.Error += (s, e) => { /* ... */ };

    // Subscribe to symbol with optional callback.
    client.Subscribe(symbol, CandlestickInterval.Hour, evt => {
        // Handle candlestick event for symbol.
    });

    // Set stream URI using client subscribed streams.
    webSocket.Uri = BinanceWebSocketStream.CreateUri(client);
    // NOTE: This must be done after client subscribe.

    // Route stream messages to client.
    webSocket.Message += (s, e) => client.HandleMessage(e.Subject, e.Json);

    // Begin streaming.
    controller.Begin();

    // ...

	// End streaming.
    await controller.CancelAsync();
}

Aggregate Trade Streams

Get real-time aggregate trade events using IAggregateTradeWebSocketClient.

Reference: Official Binance API

// Initialize client.
var client = new AggregateTradeWebSocketClient();

// Subscribe to symbol with optional callback (begin streaming).
client.Subscribe(symbol, evt => {
    // Handle aggregate trade event for symbol.
});

// ...

// Unsubscribe all symbols (end streaming).
client.Unsubscribe();

Optionally, add a AggregateTrade event handler that receives AggregateTradeEventArgs events for all subscribed symbols.

client.AggregateTrade += (s, e) => { /* ... */ };

Advanced Usage

View an example of instantiating the internal components of the web socket client.

// Initialize client.
var client = new AggregateTradeClient();

// Initialize stream.
var webSocket = new BinanceWebSocketStream();

// Initialize controller.
using (var controller = new RetryTaskController(webSocket.StreamAsync))
{
	// Optionally, add error event handler.
    controller.Error += (s, e) => { /* ... */ };

    // Subscribe to symbol with optional callback.
    client.Subscribe(symbol, evt => {
        // Handle aggregate trade event for symbol.
    });

    // Set stream URI using client subscribed streams.
    webSocket.Uri = BinanceWebSocketStream.CreateUri(client);
    // NOTE: This must be done after client subscribe.

    // Route stream messages to client.
    webSocket.Message += (s, e) => client.HandleMessage(e.Subject, e.Json);

    // Begin streaming.
    controller.Begin();

    // ...

	// End streaming.
    await controller.CancelAsync();
}

Trade Streams

Get real-time trade events using ITradeWebSocketClient.

Reference: Official Binance API

// Initialize client.
var client = new TradeWebSocketClient();

// Subscribe to symbol with optional callback (begin streaming).
client.Subscribe(symbol, evt => {
    // Handle trade event for symbol.
});

// ...

// Unsubscribe all symbols (end streaming).
client.Unsubscribe();

Optionally, add a Trade event handler that receives TradeEventArgs events for all subscribed symbols.

client.Trade += (s, e) => { /* ... */ };

Advanced Usage

View an example of instantiating the internal components of the web socket client.

// Initialize client.
var client = new TradeClient();

// Initialize stream.
var webSocket = new BinanceWebSocketStream();

// Initialize controller.
using (var controller = new RetryTaskController(webSocket.StreamAsync))
{
	// Optionally, add error event handler.
    controller.Error += (s, e) => { /* ... */ };

    // Subscribe to symbol with optional callback.
    client.Subscribe(symbol, evt => {
        // Handle trade event for symbol.
    });

    // Set stream URI using client subscribed streams.
    webSocket.Uri = BinanceWebSocketStream.CreateUri(client);
    // NOTE: This must be done after client subscribe.

    // Route stream messages to client.
    webSocket.Message += (s, e) => client.HandleMessage(e.Subject, e.Json);

    // Begin streaming.
    controller.Begin();

    // ...

	// End streaming.
    await controller.CancelAsync();
}

Symbol Statistics (Tickers) Streams

Get real-time 24-hour statistics events using ISymbolStatisticsWebSocketClient.

Reference: Official Binance API - Individual Symbol Streams
Reference: Official Binance API - All Symbols Stream

NOTE: Do not specify a symbol to subscribe to the all symbols stream.

// Initialize client.
var client = new SymbolStatisticsWebSocketClient();

// Subscribe to symbol with optional callback (begin streaming).
client.Subscribe(symbol, evt => {
    // Handle 24-hour statistics event for symbol.
});

// ...

// Unsubscribe all symbols (end streaming).
client.Unsubscribe();

Optionally, add a StatisticsUpdate event handler that receives SymbolStatisticsEventArgs events for all subscribed symbols.

client.StatisticsUpdate += (s, e) => { /* ... */ };

Advanced Usage

View an example of instantiating the internal components of the web socket client.

// Initialize client.
var client = new SymbolStatisticsClient();

// Initialize stream.
var webSocket = new BinanceWebSocketStream();

// Initialize controller.
using (var controller = new RetryTaskController(webSocket.StreamAsync))
{
	// Optionally, add error event handler.
    controller.Error += (s, e) => { /* ... */ };

    // Subscribe to symbol with optional callback.
    client.Subscribe(symbol, evt => {
        // Handle 24-hour statistics event for symbol.
    });

    // Set stream URI using client subscribed streams.
    webSocket.Uri = BinanceWebSocketStream.CreateUri(client);
    // NOTE: This must be done after client subscribe.

    // Route stream messages to client.
    webSocket.Message += (s, e) => client.HandleMessage(e.Subject, e.Json);

    // Begin streaming.
    controller.Begin();

    // ...

	// End streaming.
    await controller.CancelAsync();
}
Clone this wiki locally