From 764c7fe764dd52e2c2e54fe1b025ac3b8adb3597 Mon Sep 17 00:00:00 2001 From: Enzo Henrique Date: Thu, 25 Nov 2021 22:49:38 -0300 Subject: [PATCH] Implemented OnGetCandlesWebSocketAsync for BinanceGroup Implemented websocket Kline/Candlestick Streams following Binance docs: https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams. The data is received each 2 seconds. I know that MiniTicker method (right below this method in the docs) is faster (it updates each 1s) but there's no aggregation by period. That's why I believe this method is more suitable for this case. --- .../BinanceGroup/BinanceGroupCommon.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/ExchangeSharp/API/Exchanges/BinanceGroup/BinanceGroupCommon.cs b/src/ExchangeSharp/API/Exchanges/BinanceGroup/BinanceGroupCommon.cs index 9ebef848..736fd26d 100644 --- a/src/ExchangeSharp/API/Exchanges/BinanceGroup/BinanceGroupCommon.cs +++ b/src/ExchangeSharp/API/Exchanges/BinanceGroup/BinanceGroupCommon.cs @@ -1135,6 +1135,36 @@ protected override async Task OnUserDataWebSocketAsync(Action OnGetCandlesWebSocketAsync(Func callbackAsync, int periodSeconds, params string[] marketSymbols) + { + //Candlesticks are received each 2s. Miniticker method is faster (1s), but you can't aggregate by period. + //https://github.com/binance/binance-spot-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams + + if (marketSymbols == null || marketSymbols.Length == 0) + throw new ArgumentNullException(nameof(marketSymbols)); + + //only one symbol per connection + var symbol = marketSymbols[0].ToStringLowerInvariant(); + + var period = PeriodSecondsToString(periodSeconds); + + return await ConnectPublicWebSocketAsync($"/stream?streams={symbol}@kline_{period}", async (_socket, msg) => + { + JToken token = JToken.Parse(msg.ToStringFromUTF8()); + + if (token != null && token["data"] != null && token["data"]["k"] != null) + { + var candle = this.ParseCandle(token["data"]["k"], symbol, periodSeconds, "o", "h", "l", "c", "t", + TimestampType.UnixMilliseconds, "v", "q"); + + if (candle != null) + { + callbackAsync(candle); + } + } + }); + } + public async Task GetListenKeyAsync() { JToken response = await MakeJsonRequestAsync("/userDataStream", BaseUrlApi, null, "POST");