/// <summary>
 ///
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="limit"></param>
 /// <returns></returns>
 public static void Subscribe <TClient>(this ICandlestickCache <TClient> cache, string symbol, CandlestickInterval interval, int limit)
     where TClient : ICandlestickClient
 => cache.Subscribe(symbol, interval, limit, null);
Esempio n. 2
0
 public Task SubscribeCandlesticks(Exchange exchange, string symbol, CandlestickInterval candlestickInterval, int limit, Action <CandlestickEventArgs> callback, Action <Exception> exception, CancellationToken cancellationToken)
 {
     return(exchanges[exchange].SubscribeCandlesticks(symbol, candlestickInterval, limit, callback, exception, cancellationToken));
 }
 public async Task <IEnumerable <Candlestick> > GetCandlesticksAsync(string symbol, CandlestickInterval interval, DateTime startTime, DateTime endTime, int limit = default(int), CancellationToken token = default(CancellationToken))
 {
     throw new NotImplementedException();
 }
Esempio n. 4
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="symbol">The symbol.</param>
        /// <param name="interval">The interval.</param>
        /// <param name="openTime">The open time.</param>
        /// <param name="open">The open price.</param>
        /// <param name="high">The high price.</param>
        /// <param name="low">The low price.</param>
        /// <param name="close">The close price.</param>
        /// <param name="volume">The volume in base asset units.</param>
        /// <param name="closeTime">The close time.</param>
        /// <param name="quoteAssetVolume">The volume in quote assset units.</param>
        /// <param name="numberOfTrades">The number of trades.</param>
        /// <param name="takerBuyBaseAssetVolume">The taker buy base asset volume.</param>
        /// <param name="takerBuyQuoteAssetVolume">The taker buy quote asset volume.</param>
        public Candlestick(
            string symbol,
            CandlestickInterval interval,
            DateTime openTime,
            decimal open,
            decimal high,
            decimal low,
            decimal close,
            decimal volume,
            DateTime closeTime,
            decimal quoteAssetVolume,
            long numberOfTrades,
            decimal takerBuyBaseAssetVolume,
            decimal takerBuyQuoteAssetVolume)
        {
            Throw.IfNull(symbol, nameof(symbol));

            if (open < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: price must not be less than 0.", nameof(open));
            }
            if (high < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: price must not be less than 0.", nameof(high));
            }
            if (low < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: price must not be less than 0.", nameof(low));
            }
            if (close < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: price must not be less than 0.", nameof(close));
            }

            if (numberOfTrades < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: number of trades must not be less than 0.", nameof(numberOfTrades));
            }

            if (volume < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: volume must not be less than 0.", nameof(volume));
            }
            if (quoteAssetVolume < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: volume must not be less than 0.", nameof(quoteAssetVolume));
            }
            if (takerBuyBaseAssetVolume < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: volume must not be less than 0.", nameof(takerBuyBaseAssetVolume));
            }
            if (takerBuyQuoteAssetVolume < 0)
            {
                throw new ArgumentException($"{nameof(Candlestick)}: volume must not be less than 0.", nameof(takerBuyQuoteAssetVolume));
            }

            Symbol                   = symbol.FormatSymbol();
            Interval                 = interval;
            OpenTime                 = openTime;
            Open                     = open;
            High                     = high;
            Low                      = low;
            Close                    = close;
            Volume                   = volume;
            CloseTime                = closeTime;
            QuoteAssetVolume         = quoteAssetVolume;
            NumberOfTrades           = numberOfTrades;
            TakerBuyBaseAssetVolume  = takerBuyBaseAssetVolume;
            TakerBuyQuoteAssetVolume = takerBuyQuoteAssetVolume;
        }
Esempio n. 5
0
        /// <summary>
        /// Get candlesticks for a symbol. Candlesticks/K-Lines are uniquely identified by their open time.
        /// If startTime and endTime are not sent, the most recent candlesticks are returned.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="symbol"></param>
        /// <param name="interval"></param>
        /// <param name="limit">Default 500; max 500.</param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task <string> GetCandlesticksAsync(this IBinanceHttpClient client, string symbol, CandlestickInterval interval, int limit = default, DateTime startTime = default, DateTime endTime = default, CancellationToken token = default)
        {
            Throw.IfNull(client, nameof(client));
            Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));

            if (client.RateLimiter != null)
            {
                await client.RateLimiter.DelayAsync(token : token)
                .ConfigureAwait(false);
            }

            var request = new BinanceHttpRequest("/api/v1/klines");

            request.AddParameter("symbol", symbol.FormatSymbol());
            request.AddParameter("interval", interval.AsString());

            if (limit > 0)
            {
                request.AddParameter("limit", limit);
            }

            if (startTime != default)
            {
                if (startTime.Kind != DateTimeKind.Utc)
                {
                    throw new ArgumentException("Date/Time must be UTC.", nameof(startTime));
                }

                request.AddParameter("startTime", startTime.ToTimestamp());
            }

            if (endTime != default)
            {
                if (endTime.Kind != DateTimeKind.Utc)
                {
                    throw new ArgumentException("Date/Time must be UTC.", nameof(endTime));
                }

                request.AddParameter("endTime", endTime.ToTimestamp());
            }

            return(await client.GetAsync(request, token)
                   .ConfigureAwait(false));
        }
Esempio n. 6
0
        private async Task <ImmutableList <Candlestick> > InitializeCandleticks(string symbol, CandlestickInterval interval)
        {
            var candlesticks = await _binanceApi.GetCandlesticksAsync(symbol, interval);

            var immutableCandlesticks = candlesticks.ToImmutableList();

            _cache.SetCandlestick(symbol, interval, immutableCandlesticks);

            return(immutableCandlesticks);
        }
Esempio n. 7
0
        public virtual IEnumerable <Candlestick> DeserializeMany(string json, string symbol, CandlestickInterval interval)
        {
            Throw.IfNullOrWhiteSpace(json, nameof(json));
            Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));

            symbol = symbol.FormatSymbol();

            return(JArray.Parse(json).Select(item => new Candlestick(
                                                 symbol, interval,
                                                 item[0].Value <long>(),    // open time
                                                 item[1].Value <decimal>(), // open
                                                 item[2].Value <decimal>(), // high
                                                 item[3].Value <decimal>(), // low
                                                 item[4].Value <decimal>(), // close
                                                 item[5].Value <decimal>(), // volume
                                                 item[6].Value <long>(),    // close time
                                                 item[7].Value <decimal>(), // quote asset volume
                                                 item[8].Value <long>(),    // number of trades
                                                 item[9].Value <decimal>(), // taker buy base asset volume
                                                 item[10].Value <decimal>() // taker buy quote asset volume
                                                 )).ToArray());
        }
 public ImmutableList <Candlestick> GetCandlesticks(string symbol, CandlestickInterval interval)
 {
     return(_memoryCache.Get <ImmutableList <Candlestick> >($"{symbol}{SYMBOL_CANDLESTICK}{interval.AsString()}"));
 }
 public void SetCandlestick(string symbol, CandlestickInterval interval, ImmutableList <Candlestick> candlesticks)
 {
     _memoryCache.Set($"{symbol}{SYMBOL_CANDLESTICK}{interval.AsString()}", candlesticks, TimeSpan.FromMinutes(CACHE_TIME_IN_MINUTES));
 }
Esempio n. 10
0
 /// <summary>
 /// Get count of second in selected interval.
 /// </summary>
 /// <param name="resolution">Candlestick interval object.</param>
 /// <returns>Count of second.</returns>
 public static int GetSecond(this CandlestickInterval resolution)
 {
     return((int)resolution);
 }
 public void ClearCandlestick(string symbol, CandlestickInterval interval)
 {
     _memoryCache.Remove($"{symbol}{SYMBOL_CANDLESTICK}{interval.AsString()}");
 }
Esempio n. 12
0
 public SubscribeCandlesticks(string symbol, int limit, IExchangeApi exchangeApi, CandlestickInterval candlestickInterval)
     : base(symbol, limit, exchangeApi)
 {
     CandlestickInterval = candlestickInterval;
 }
 private static string GetKey(string symbol, CandlestickInterval interval)
 {
     return($"{symbol}{interval.AsString()}");
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="callback"></param>
 /// <returns></returns>
 public static void Subscribe <TClient>(this ICandlestickCache <TClient> cache, string symbol, CandlestickInterval interval, Action <CandlestickCacheEventArgs> callback)
     where TClient : ICandlestickClient
 => cache.Subscribe(symbol, interval, default, callback);
Esempio n. 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="symbol"></param>
        /// <param name="interval"></param>
        /// <param name="callback"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task StreamAsync(this ICandlestickWebSocketClient client, string symbol, CandlestickInterval interval, Action <CandlestickEventArgs> callback, CancellationToken token)
        {
            Throw.IfNull(client, nameof(client));

            client.Subscribe(symbol, interval, callback);

            return(client.WebSocket.StreamAsync(token));
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="client"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public static Task SubscribeAsync(this ICandlestickWebSocketClient client, string symbol, CandlestickInterval interval, CancellationToken token)
 => client.SubscribeAsync(symbol, interval, null, token);
Esempio n. 17
0
 private void SubscribeCandlestick(string symbol, CandlestickInterval interval)
 {
     _subscriber.Candlestick(symbol, interval, OnCandletickUpdate, OnCandlestickError);
 }
Esempio n. 18
0
        public IEnumerable <ICandleStick> GetCandleSticks(ITradePair tp, long start, long end, CandlestickInterval interval)
        {
            BlockApiCall();

            var intervalStr = "";

            switch (interval)
            {
            case CandlestickInterval.Hours_4:
                intervalStr = "4h";
                break;

            case CandlestickInterval.Daily:
                intervalStr = "1d";
                break;

            case CandlestickInterval.Minutes_5:
                break;

            case CandlestickInterval.Minutes_15:
                break;

            case CandlestickInterval.Minutes_30:
                break;

            case CandlestickInterval.Hours_2:
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(interval), interval, null);
            }

            var url = $"v1/klines?symbol={tp.Id}&interval={intervalStr}";

            var response = _restClient.Get <List <BinanceCandleStick> >(url);

            _sw.Restart();
            return(response);
        }
Esempio n. 19
0
 public async Task <IEnumerable <Candlestick> > GetCandlesticksAsync(string symbol, CandlestickInterval interval)
 {
     return(await GetCandlestick(symbol, interval));
 }
        private async Task <ImmutableList <Candlestick> > InitializeCandleticks(string symbol, CandlestickInterval interval)
        {
            try
            {
                var candlesticks = await _binanceApi.GetCandlesticksAsync(symbol, interval);

                var immutableCandlesticks = candlesticks.ToImmutableList();

                _cache.SetCandlestick(symbol, interval, immutableCandlesticks);

                return(immutableCandlesticks);
            }
            catch (Exception ex)
            {
                _cache.ClearCandlestick(symbol, interval);

                _log.LogError($"Canlestick initialization error {ex.Message}");

                return(new List <Candlestick>().ToImmutableList());
            }
        }
        /// <summary>
        /// Get candlesticks for a symbol. Candlesticks/K-Lines are uniquely identified by their open time.
        /// If startTime and endTime are not sent, the most recent candlesticks are returned.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="symbol"></param>
        /// <param name="interval"></param>
        /// <param name="limit">Default 500; max 500.</param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static Task <string> GetCandlesticksAsync(this IBinanceHttpClient client, string symbol, CandlestickInterval interval, int limit = default, long startTime = default, long endTime = default, CancellationToken token = default)
        {
            Throw.IfNull(client, nameof(client));
            Throw.IfNullOrWhiteSpace(symbol, nameof(symbol));

            var request = new BinanceHttpRequest("/api/v1/klines", 2);

            request.AddParameter("symbol", symbol.FormatSymbol());
            request.AddParameter("interval", interval.AsString());

            if (limit > 0)
            {
                request.AddParameter("limit", limit);
            }

            if (startTime > 0)
            {
                request.AddParameter("startTime", startTime);
            }

            if (endTime > 0)
            {
                request.AddParameter("endTime", endTime);
            }

            return(client.GetAsync(request, token));
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="limit"></param>
 /// <returns></returns>
 public static void Subscribe(this ICandlestickCache cache, string symbol, CandlestickInterval interval, int limit)
 => cache.Subscribe(symbol, interval, limit, null);
Esempio n. 23
0
        public async Task <IEnumerable <Candlestick> > GetCandlesticksAsync(string symbol, CandlestickInterval interval, DateTime startTime, DateTime endTime, int limit = 0, CancellationToken token = default)
        {
            var candlestickInterval = interval.ToKucoinCandlestickInterval();

            using (var kucoinClient = new KucoinClient())
            {
                var result = await kucoinClient.GetKlinesAsync(symbol, candlestickInterval, startTime, endTime).ConfigureAwait(false);

                Candlestick f(KucoinKline k)
                {
                    return(new Candlestick
                    {
                        Symbol = symbol,
                        Exchange = Exchange.Kucoin,
                        Interval = interval,
                        OpenTime = k.StartTime,
                        Open = k.Open,
                        High = k.High,
                        Low = k.Low,
                        Close = k.Close,
                        Volume = k.Volume
                    });
                };

                var candlesticks = (from k in result.Data select f(k)).ToList();

                return(candlesticks);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="cache"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="callback"></param>
 /// <returns></returns>
 public static void Subscribe(this ICandlestickCache cache, string symbol, CandlestickInterval interval, Action <CandlestickCacheEventArgs> callback)
 => cache.Subscribe(symbol, interval, default, callback);
Esempio n. 25
0
 public Task <IEnumerable <Candlestick> > GetCandlesticksAsync(Exchange exchange, string symbol, CandlestickInterval interval, DateTime startTime, DateTime endTime, int limit = default, CancellationToken token = default)
 {
     return(exchanges[exchange].GetCandlesticksAsync(symbol, interval, startTime, endTime, limit, token));
 }
Esempio n. 26
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="client"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 public static void Subscribe(this ICandlestickWebSocketClient client, string symbol, CandlestickInterval interval)
 => client.Subscribe(symbol, interval, null);
 public void SubscribeCandlesticks(string symbol, CandlestickInterval candlestickInterval, int limit, Action <CandlestickEventArgs> callback, Action <Exception> exception, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
Esempio n. 28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="client"></param>
 /// <param name="symbol"></param>
 /// <param name="interval"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public static Task StreamAsync(this ICandlestickWebSocketClient client, string symbol, CandlestickInterval interval, CancellationToken token)
 => StreamAsync(client, symbol, interval, null, token);
Esempio n. 29
0
        private async Task SubscribeToCandlestick(string symbol, CandlestickInterval interval, bool reConnect = false)
        {
            _log.LogInformation($"Subscribe to candlestick {symbol} {interval.AsString()}");

            var key = GetKey(symbol, interval);

            if (_candlestickSubscribers.ContainsKey(key) && !reConnect)
            {
                return;
            }

            try
            {
                CandlestickSubscriber subscriber = _candlestickSubscribers.ContainsKey(key) ? _candlestickSubscribers[key] : null;

                if (subscriber != null)
                {
                    subscriber.TokenSource.Cancel();
                    subscriber.TokenSource.Dispose();
                }
                else
                {
                    subscriber = new CandlestickSubscriber()
                    {
                        Symbol   = symbol,
                        Interval = interval
                    };

                    CandlestickReConnectionTimerInitialize(subscriber);

                    _candlestickSubscribers[key] = subscriber;
                }

                subscriber.TokenSource = new CancellationTokenSource();
                subscriber.CandlestickWebSocketClient = _serviceProvider.GetService <ICandlestickWebSocketClient>();
                subscriber.SubscribeTask = subscriber.CandlestickWebSocketClient.SubscribeAsync(symbol, interval, _onCandlestickUpdate, subscriber.TokenSource.Token);

                await subscriber.SubscribeTask;
            }
            catch (Exception ex)
            {
                if (_candlestickSubscribers.ContainsKey(key))
                {
                    var subscriber = _candlestickSubscribers[key];

                    subscriber.CandlestickReConnectionTimer?.Dispose();
                    subscriber.TokenSource?.Dispose();

                    CandlestickSubscriber removedSubscriber = null;

                    if (_candlestickSubscribers.TryRemove(key, out removedSubscriber))
                    {
                        _log.LogInformation($"subscriber removed for {symbol} {interval.AsString()}");
                    }
                }

                _log.LogError($"Error with candlestick websocket {ex.Message}", ex);

                _onCandlestickError?.Invoke(symbol, interval);
            }
        }
 private static string GetStreamName(string symbol, CandlestickInterval interval)
 => $"{symbol.ToLowerInvariant()}@kline_{interval.AsString()}";