Esempio n. 1
0
        public async Task Start()
        {
            IsStarted = true;
            _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);

            _keepTimer = new PeriodicTaskWrapper(_logger, _name);
            await _keepTimer.Start(keepTimer, new PeriodicTaskParams { period = 5000 }, _source.Token);
        }
Esempio n. 2
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            string symbol = msg.chnlName;

            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (String.IsNullOrEmpty(jsonResponse))
                {
                    _logger.Log(LogPriority.Warning, $"<--Report : Empty message received - '{jsonResponse}' : ", ExchName);
                    return;
                }

                if (symbol.Equals(BinanceClient.connectSymbol + "@ticker"))
                {
                    return;
                }

                JObject jToken     = JObject.Parse(jsonResponse);
                var     symbolItem = jToken["s"].ToString();

                MarketBook mb = new MarketBook()
                {
                    AskPrice   = jToken["a"].ToObject <double>(),
                    AskSize    = jToken["A"].ToObject <double>(),
                    BidPrice   = jToken["b"].ToObject <double>(),
                    BidSize    = jToken["B"].ToObject <double>(),
                    ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(jToken["E"].ToObject <double>()),
                    LocalTime  = DateTime.Now
                };
                _client.OnReport(ExchName, ExchName + symbolItem, mb);
            }
            break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(ExchName, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    if (SubscribeList.Count > 0)
                    {
                        foreach (var i in SubscribeList)
                        {
                            chnl = new WebSocketWrapper(Uri + i.Key, i.Key, _logger, ExchName);
                            await chnl.Start(ParseMessage);
                        }
                    }
                }
            }
            break;

            default:
                break;
            }
        }
Esempio n. 3
0
        /// <summary>
        /// IBrokerClient implementation,
        /// One should stop websocket here, clear all other resources, like subscriptions etc...
        /// </summary>
        /// <returns></returns>
        public async Task Stop()
        {
            using (await _lock.LockAsync())
            {
                if (SubscribeList.Count > 0)
                {
                    foreach (var i in SubscribeList)
                    {
                        await i.Value.Stop();
                    }
                }
            }
            IsStarted = false;
            await connectChannel.Stop();

            _client.OnEvent(Name, BrokerEvent.ConnectorStopped, string.Empty);
        }
Esempio n. 4
0
 public async Task KeepTimer(object o, CancellationToken token)
 {
     using (await _lock.LockAsync())
     {
         foreach (var item in SubscribeList.Values)
         {
             if (item.mode == SubscriptionModel.TopBook)
             {
                 try
                 {
                     await GetTicker(item.pair);
                 }
                 catch (Exception ex)
                 {
                     if (ex.Message == "Object reference not set to an instance of an object.")
                     {
                         _client.OnEvent(Name, BrokerEvent.SubscribedCoinIsNotValid, "Pair: " + item.pair + "is not valid");
                         _logger.Log(LogPriority.Info, "SubscribedCoinIsNotValid - Pair: " + item.pair + "is not valid", Name);
                     }
                 }
             }
         }
     }
 }
Esempio n. 5
0
        public async Task Stop()
        {
            var source = _source;

            source?.Cancel();
            using (await _lock.LockAsync())
            {
                if (SubscribeList != null)
                {
                    SubscribeList.Clear();
                }
            }
            IsStarted = false;
            await chnl.Stop();

            _client.OnEvent(Name, BrokerEvent.ConnectorStopped, string.Empty);
        }
Esempio n. 6
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            string symbol = msg.chnlName;

            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (String.IsNullOrEmpty(jsonResponse))
                {
                    _logger.Log(LogPriority.Warning, $"<--Report : Empty message received - '{jsonResponse}' : ", ExchName);
                    return;
                }

                if (symbol.Equals(GeminiClient.connectSymbol))
                {
                    return;
                }

                JObject jToken = JObject.Parse(jsonResponse);
                var     type   = jToken["type"]?.Value <string>();

                if (type == "update")
                {
                    var subscribeResponse = JsonConvert.DeserializeObject <Update>(jsonResponse);

                    if (jsonResponse.Contains("initial"))
                    {
                        SortedDictionary <double, double> ask_book = new SortedDictionary <double, double>();
                        SortedDictionary <double, double> bid_book = new SortedDictionary <double, double>();

                        foreach (var item in subscribeResponse.events)
                        {
                            if (item.side == "ask")
                            {
                                ask_book.Add(item.price, item.remaining);
                            }
                            else
                            if (item.side == "bid")
                            {
                                bid_book.Add(item.price, item.remaining);
                            }
                        }
                        using (await _lock.LockAsync())
                        {
                            SubscribeList.Add(symbol, new Subscribe()
                                {
                                    market = new Market()
                                    {
                                        buy_list   = bid_book,
                                        sell_list  = ask_book,
                                        ServerTime = subscribeResponse.timestampms
                                    }
                                });

                            _client.OnEvent(ExchName, BrokerEvent.CoinSubscribed, symbol);
                            _logger.Log(LogPriority.Info, "Coin Subscribed - " + symbol, ExchName);

                            SendReport(symbol, SubscribeList[symbol]);
                        }
                    }
                    else
                    {
                        foreach (var eventItem in subscribeResponse.events)
                        {
                            if (eventItem.reason == "cancel" && eventItem.type == "change")
                            {
                                var       price = eventItem.price;
                                var       size  = eventItem.remaining;
                                var       side  = eventItem.side;
                                Subscribe data;
                                if (SubscribeList.TryGetValue(symbol, out data))
                                {
                                    using (await _lock.LockAsync())
                                    {
                                        if (side == "ask")
                                        {
                                            if (!data.market.sell_list.ContainsKey(price))
                                            {
                                                _logger.Log(LogPriority.Error, $"this Price '-{price}-' not exists for delete", symbol);
                                            }
                                            else
                                            if (size == 0)
                                            {
                                                data.market.sell_list.Remove(price);
                                            }
                                            else
                                            {
                                                data.market.sell_list.Remove(price);
                                                data.market.sell_list.Add(price, size);
                                            }
                                        }
                                        else
                                        if (side == "bid")
                                        {
                                            if (!data.market.buy_list.ContainsKey(price))
                                            {
                                                _logger.Log(LogPriority.Error, $"this Price '-{price}-' not exists for delete", symbol);
                                            }
                                            else
                                            if (size == 0)
                                            {
                                                data.market.buy_list.Remove(price);
                                            }
                                            else
                                            {
                                                data.market.buy_list.Remove(price);
                                                data.market.buy_list.Add(price, size);
                                            }
                                        }
                                        data.market.ServerTime = subscribeResponse.timestampms;
                                        SendReport(symbol, SubscribeList[symbol]);
                                    }
                                }
                            }
                            else
                            if ((eventItem.reason == "place" || eventItem.reason == "trade") && eventItem.type == "change")
                            {
                                var       price = eventItem.price;
                                var       size  = eventItem.remaining;
                                var       side  = eventItem.side;
                                Subscribe data;
                                if (SubscribeList.TryGetValue(symbol, out data))
                                {
                                    using (await _lock.LockAsync())
                                    {
                                        if (side == "ask")
                                        {
                                            if (data.market.sell_list.ContainsKey(price) && data.market.sell_list[price] == size)
                                            {
                                                _logger.Log(LogPriority.Error, $"this Price '-{price}-' already exists", symbol);
                                            }
                                            else
                                            if (data.market.sell_list.ContainsKey(price) && data.market.sell_list[price] != size)
                                            {
                                                data.market.sell_list[price] = size;
                                            }
                                            else
                                            if (size == 0)
                                            {
                                                data.market.sell_list.Remove(price);
                                            }
                                            else
                                            {
                                                data.market.sell_list.Add(price, size);
                                            }
                                        }
                                        else
                                        if (side == "bid")
                                        {
                                            if (data.market.buy_list.ContainsKey(price) && data.market.buy_list[price] == size)
                                            {
                                                _logger.Log(LogPriority.Error, $"this Price '-{price}-' already exists", symbol);
                                            }
                                            else
                                            if (data.market.buy_list.ContainsKey(price) && data.market.buy_list[price] != size)
                                            {
                                                data.market.buy_list[price] = size;
                                            }
                                            else
                                            if (size == 0)
                                            {
                                                data.market.buy_list.Remove(price);
                                            }
                                            else
                                            {
                                                data.market.buy_list.Add(price, size);
                                            }
                                        }
                                    }
                                }
                                data.market.ServerTime = subscribeResponse.timestampms;
                                SendReport(symbol, SubscribeList[symbol]);
                            }
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(ExchName, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    if (SubscribeList.Count > 0)
                    {
                        foreach (var i in SubscribeList)
                        {
                            chnl = new WebSocketWrapper(Uri + i.Key, i.Key, _logger, ExchName);
                            await chnl.Start(ParseMessage);
                        }
                    }
                }
            }

            break;

            default:
                break;
            }
        }
Esempio n. 7
0
        private async Task <bool?> ConnectToSignalR()
        {
            _hubConnection = new HubConnection(baseUrl);
            _hubProxy      = _hubConnection.CreateHubProxy("c2");

            _hubConnection.Closed         += _hubConnection_Closed;
            _hubConnection.ConnectionSlow += _hubConnection_ConnectionSlow;
            _hubConnection.Error          += _hubConnection_Error;
            _hubConnection.Received       += _hubConnection_Received;
            _hubConnection.Reconnected    += _hubConnection_Reconnected;
            _hubConnection.Reconnecting   += _hubConnection_Reconnecting;
            _hubConnection.StateChanged   += _hubConnection_StateChanged;

            try
            {
                await _hubConnection.Start().ConfigureAwait(false);

                #region obsolete
                if (_hubConnection.State == ConnectionState.Connected)
                {
                    _hubProxy.On(
                        "uE",
                        exchangeStateDelta => _updateExchangeState?.Invoke(exchangeStateDelta)
                        );
                    _client.OnEvent(Name, BrokerEvent.SessionLogon, string.Empty);

                    using (await _lock.LockAsync())
                    {
                        if (_subscribeList.Count > 0)
                        {
                            foreach (var i in _subscribeList)
                            {
                                if (i.Value.market != null)
                                {
                                    i.Value.market.ask_list.Clear();
                                    i.Value.market.bid_list.Clear();
                                    i.Value.market.nonce = 0;
                                }
                                try
                                {
                                    var res = await QueryExchangeState(i.Key);

                                    ParseMessage(Decode(res));
                                    await SubscribeToExchangeDeltas(i.Key);
                                }
                                catch (Exception ex)
                                {
                                    _logger.Log(LogPriority.Error, $"Connection error {ex.Message}", Name);
                                }
                            }
                        }
                    }
                    _client.OnEvent(Name, BrokerEvent.SessionLogon, string.Empty);
                    _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                }
                #endregion

                return(true);
            }
            catch (Exception ex)
            {
                _logger.Log(LogPriority.Error, $"Exception - {ex.Message}", Name);
                return(false);
            }
        }