Exemplo n.º 1
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/Public/LiveTickers", "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            foreach (var item in tickersResponse.tickers)
            {
                if (item.currencyPair.Equals(Utilities.GatecoinSymbol(instr)))
                {
                    result.BidPrice   = item.bid;
                    result.AskPrice   = item.ask;
                    result.BidSize    = item.bidQ;
                    result.AskSize    = item.askQ;
                    result.LastPrice  = item.last;
                    result.LastSize   = item.lastQ;
                    result.LocalTime  = DateTime.Now;
                    result.ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(item.createDateTime));
                }
            }

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo 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;
            }
        }
Exemplo n.º 3
0
 private void SendReport(string symbol, Subscribe symbolSubscribe)
 {
     _client.OnReport(ExchName, ExchName + symbol,
                      new MarketBook()
     {
         BidPrice   = symbolSubscribe.market.buy_list.Last().Key,
         BidSize    = symbolSubscribe.market.buy_list.Last().Value,
         AskPrice   = symbolSubscribe.market.sell_list.First().Key,
         AskSize    = symbolSubscribe.market.sell_list.First().Value,
         LocalTime  = DateTime.Now,
         ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(symbolSubscribe.market.ServerTime)
     });
 }
Exemplo n.º 4
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/" + Utilities.BitcoinIndonesiaSymbol(instr) + "/ticker", "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            result.AskPrice   = Convert.ToDouble(tickersResponse.ticker.sell);
            result.BidPrice   = Convert.ToDouble(tickersResponse.ticker.buy);
            result.LocalTime  = DateTime.Now;
            result.ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(tickersResponse.ticker.server_time));
            result.LastPrice  = Convert.ToDouble(tickersResponse.ticker.last);

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 5
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/ticker?symbol=" + Utilities.AllcoinSymbol(instr), "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            result.AskPrice  = Convert.ToDouble(tickersResponse.data.sell);
            result.BidPrice  = Convert.ToDouble(tickersResponse.data.buy);
            result.LocalTime = DateTime.Now;
            result.LastPrice = Convert.ToDouble(tickersResponse.data.last);
            result.LastSize  = Convert.ToDouble(tickersResponse.data.vol);

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 6
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/exchange/ticker?currencyPair=" + instr.First + "/" + instr.Second, "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            result.AskPrice  = tickersResponse.best_ask;
            result.BidPrice  = tickersResponse.best_bid;
            result.LastPrice = tickersResponse.last;
            result.LastSize  = tickersResponse.volume;
            result.LocalTime = DateTime.Now;

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 7
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/orderbook?currency=" + instr.First, "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            result.AskPrice   = Convert.ToDouble(tickersResponse.ask.First().price);
            result.BidPrice   = Convert.ToDouble(tickersResponse.bid.First().price);
            result.AskSize    = Convert.ToDouble(tickersResponse.ask.First().qty);
            result.BidSize    = Convert.ToDouble(tickersResponse.bid.First().qty);
            result.LocalTime  = DateTime.Now;
            result.ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToInt64(tickersResponse.timestamp));

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 8
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/Ticker?pair=" + Utilities.KrakenSymbol(instr), "GET");

            var tickersResponse = JsonConvert.DeserializeObject <GetTickerResponse>(response);
            var data            = tickersResponse.result.Values.First();

            result.AskPrice  = Convert.ToDouble(data.a.First());
            result.BidPrice  = Convert.ToDouble(data.b.First());
            result.LastPrice = Convert.ToDouble(data.c.First());
            result.LastSize  = Convert.ToDouble(data.v.First());
            result.LocalTime = DateTime.Now;

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 9
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            string response = await REST.SendRequest(rest_domain + "/ticker/" + instr.First, "GET");

            JObject jT   = JObject.Parse(response);
            var     data = jT["data"];

            MarketBook result = new MarketBook()
            {
                BidPrice   = (double)data["buy_price"],
                AskPrice   = (double)data["sell_price"],
                LocalTime  = DateTime.Now,
                ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(Convert.ToDouble(data["date"]))
            };

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 10
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            var        symbol   = Utilities.WEXSymbol(instr);
            string     response = await REST.SendRequest(rest_domain + "/ticker/" + symbol, "GET");

            JObject jT = JObject.Parse(response);

            var data            = jT[symbol].ToString();
            var tickersResponse = JsonConvert.DeserializeObject <Ticker>(data);

            result.AskPrice   = Convert.ToDouble(tickersResponse.buy);
            result.BidPrice   = Convert.ToDouble(tickersResponse.sell);
            result.LocalTime  = DateTime.Now;
            result.ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(tickersResponse.updated));

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 11
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/markets/" + Utilities.itBitSymbol(instr) + "/ticker", "GET");

            var tickersResponse = JsonConvert.DeserializeObject <TickerResponse>(response);

            result.AskPrice   = Convert.ToDouble(tickersResponse.ask);
            result.AskSize    = Convert.ToDouble(tickersResponse.askAmt);
            result.BidPrice   = Convert.ToDouble(tickersResponse.bid);
            result.BidSize    = Convert.ToDouble(tickersResponse.bidAmt);
            result.LastPrice  = Convert.ToDouble(tickersResponse.lastPrice);
            result.LastSize   = Convert.ToDouble(tickersResponse.lastAmt);
            result.LocalTime  = DateTime.Now;
            result.ServerTime = tickersResponse.serverTimeUTC;

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 12
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/bidandask/", "GET");

            var tickersResponse = JsonConvert.DeserializeObject <BidAsk>(response);

            var dataAsks = tickersResponse.asks.First();
            var dataBids = tickersResponse.bids.Last();

            result.AskPrice  = Convert.ToDouble(dataAsks[0]);
            result.AskSize   = Convert.ToDouble(dataAsks[1]);
            result.BidPrice  = Convert.ToDouble(dataBids[0]);
            result.BidSize   = Convert.ToDouble(dataBids[1]);
            result.LocalTime = DateTime.Now;

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 13
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook result   = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/ticker", "GET");

            var tickerResponse = JsonConvert.DeserializeObject <Dictionary <string, Symbol> >(response);

            foreach (var item in tickerResponse)
            {
                if (item.Key.Equals(Utilities.LakeBTCSymbol(instr)))
                {
                    result.BidPrice  = Convert.ToDouble(item.Value.bid);
                    result.AskPrice  = Convert.ToDouble(item.Value.ask);
                    result.LastPrice = Convert.ToDouble(item.Value.last);
                    result.LastSize  = Convert.ToDouble(item.Value.vol);
                    result.LocalTime = DateTime.Now;
                }
            }

            _client.OnReport(Name, instr.Id(), result);
            return(result);
        }
Exemplo n.º 14
0
        public async Task <MarketBook?> GetTicker(Instrument instr)
        {
            MarketBook mb       = new MarketBook();
            string     response = await REST.SendRequest(rest_domain + "/ticker/", "GET");

            var tickersResponse = JsonConvert.DeserializeObject <Dictionary <string, Ticker> >(response);

            foreach (var item in tickersResponse)
            {
                if (item.Key == Utilities.ExmoSymbol(instr))
                {
                    mb.AskPrice   = Convert.ToDouble(item.Value.sell_price);
                    mb.BidPrice   = Convert.ToDouble(item.Value.buy_price);
                    mb.LastPrice  = Convert.ToDouble(item.Value.last_trade);
                    mb.LastSize   = Convert.ToDouble(item.Value.vol);
                    mb.LocalTime  = DateTime.Now;
                    mb.ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(item.Value.updated));

                    _client.OnReport(Name, SubscribeList[item.Key].pair.Id(), mb);
                }
            }
            return(mb);
        }
Exemplo n.º 15
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }

                if (jsonResponse.Contains("depth.update"))
                {
                    var depthResponse = JsonConvert.DeserializeObject <GateIOUpdateResponse>(jsonResponse);

                    var status = depthResponse.@params[0].ToString();
                    var askbid = depthResponse.@params[1].ToString();
                    var symbol = depthResponse.@params[2].ToString();

                    if (status == "True")
                    {
                        var       askbidResponse = JsonConvert.DeserializeObject <AskBidResponse>(askbid);
                        var       symbolId       = symbol.GetHashCode();
                        Subscribe data;
                        if (SubscribeList.TryGetValue(symbolId, out data))
                        {
                            using (await _lock.LockAsync())
                            {
                                SubscribeList[symbolId].market = new MarketBook()
                                {
                                    AskPrice  = Convert.ToDouble(askbidResponse.asks[0][0]),
                                    AskSize   = Convert.ToDouble(askbidResponse.asks[0][1]),
                                    BidPrice  = Convert.ToDouble(askbidResponse.bids[0][0]),
                                    BidSize   = Convert.ToDouble(askbidResponse.bids[0][1]),
                                    LocalTime = DateTime.Now
                                };

                                _client.OnReport(Name, data.pair.Id(), SubscribeList[symbolId].market);
                            }
                        }
                    }
                    else
                    if (status == "False")
                    {
                        var       askbidResponse = JsonConvert.DeserializeObject <AskBidResponse>(askbid);
                        var       symbolId       = symbol.GetHashCode();
                        Subscribe data;
                        if (SubscribeList.TryGetValue(symbolId, out data))
                        {
                            using (await _lock.LockAsync())
                            {
                                if (askbidResponse.asks != null)
                                {
                                    if (askbidResponse.asks.Count == 1)
                                    {
                                        data.market.AskPrice = Convert.ToDouble(askbidResponse.asks[0][0]);
                                        data.market.AskSize  = Convert.ToDouble(askbidResponse.asks[0][1]);
                                    }
                                    else
                                    if (askbidResponse.asks.Count == 2)
                                    {
                                        data.market.AskPrice = Convert.ToDouble(askbidResponse.asks[1][0]);
                                        data.market.AskSize  = Convert.ToDouble(askbidResponse.asks[1][1]);
                                    }
                                }

                                if (askbidResponse.bids != null)
                                {
                                    if (askbidResponse.bids.Count == 1)
                                    {
                                        data.market.BidPrice = Convert.ToDouble(askbidResponse.bids[0][0]);
                                        data.market.BidSize  = Convert.ToDouble(askbidResponse.bids[0][1]);
                                    }
                                    else
                                    if (askbidResponse.bids.Count == 2)
                                    {
                                        data.market.BidPrice = Convert.ToDouble(askbidResponse.bids[1][0]);
                                        data.market.BidSize  = Convert.ToDouble(askbidResponse.bids[1][1]);
                                    }
                                }
                                data.market.LocalTime = DateTime.Now;

                                _client.OnReport(Name, data.pair.Id(), SubscribeList[symbolId].market);
                            }
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        if (item.Value.mode == SubscriptionModel.TopBook)
                        {
                            var request = new
                            {
                                id      = symbol.GetHashCode(),
                                method  = "depth.subscribe",
                                @params = new List <object>()
                                {
                                    symbol, 1, "0"
                                }
                            };

                            string paramData = JsonConvert.SerializeObject(request, Formatting.Indented);
                            await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 16
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }
                if (jsonResponse.Contains("auth"))
                {
                    _client.OnEvent(Name, BrokerEvent.Info, "Authentification success");
                }
                else
                if (jsonResponse.Contains("ping"))
                {
                    var request = new
                    {
                        e = "pong"
                    };
                    string paramData = JsonConvert.SerializeObject(request, Formatting.Indented);
                    await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                }
                else
                if (jsonResponse.Contains("order-book-subscribe"))
                {
                    var    tickerResponse = JsonConvert.DeserializeObject <Response>(jsonResponse);
                    string symbol         = tickerResponse.oid;
                    long   time           = tickerResponse.data.timestamp;

                    Subscribe data;
                    if (SubscribeList.TryGetValue(symbol, out data))
                    {
                        using (await _lock.LockAsync())
                        {
                            foreach (var bid in tickerResponse.data.bids)
                            {
                                if (!data.market.bid_list.ContainsKey(bid[0]))
                                {
                                    data.market.bid_list.Add(bid[0], bid[1]);
                                }
                            }

                            foreach (var ask in tickerResponse.data.asks)
                            {
                                if (!data.market.ask_list.ContainsKey(ask[0]))
                                {
                                    data.market.ask_list.Add(ask[0], ask[1]);
                                }
                            }

                            MarketBook mb = new MarketBook()
                            {
                                LocalTime  = DateTime.Now,
                                ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(time),
                                AskPrice   = data.market.ask_list.First().Key,
                                AskSize    = data.market.ask_list.First().Value,
                                BidPrice   = data.market.bid_list.Last().Key,
                                BidSize    = data.market.bid_list.Last().Value,
                            };

                            _client.OnReport(Name, data.pair.Id(), mb);
                        }
                    }
                }
                else
                if (jsonResponse.Contains("md_update"))
                {
                    var       updateResponse = JsonConvert.DeserializeObject <Response>(jsonResponse);
                    string    symbol         = updateResponse.data.pair;
                    long      time           = updateResponse.data.time;
                    Subscribe data;
                    if (SubscribeList.TryGetValue(symbol, out data))
                    {
                        using (await _lock.LockAsync())
                        {
                            if (updateResponse.data.asks.Count != 0)
                            {
                                foreach (var ask in updateResponse.data.asks)
                                {
                                    var askPrice = ask[0];
                                    var askSize  = ask[1];

                                    if (askSize == 0.0)
                                    {
                                        if (!data.market.ask_list.ContainsKey(askPrice))
                                        {
                                            _logger.Log(LogPriority.Error, $"this Price '-{askPrice}-' not exists for delete", Name);
                                        }
                                        else
                                        {
                                            data.market.ask_list.Remove(askPrice);
                                        }
                                    }
                                    else
                                    {
                                        if (data.market.ask_list.ContainsKey(askPrice))
                                        {
                                            data.market.ask_list[askPrice] = askSize;
                                        }
                                        else
                                        {
                                            data.market.ask_list.Add(askPrice, askSize);
                                        }
                                    }
                                }
                            }
                            else
                            if (updateResponse.data.bids.Count != 0)
                            {
                                foreach (var bid in updateResponse.data.bids)
                                {
                                    var bidPrice = bid[0];
                                    var bidSize  = bid[1];

                                    if (bidSize == 0.0)
                                    {
                                        data.market.bid_list.Remove(bidPrice);
                                    }
                                    else
                                    {
                                        if (data.market.bid_list.ContainsKey(bidPrice))
                                        {
                                            if (bidSize == data.market.bid_list[bidPrice])
                                            {
                                                _logger.Log(LogPriority.Error, $"this Price '-{bidPrice}-' not changed", Name);
                                            }
                                            else
                                            {
                                                data.market.bid_list[bidPrice] = bidSize;
                                            }
                                        }
                                        else
                                        {
                                            data.market.bid_list.Add(bidPrice, bidSize);
                                        }
                                    }
                                }
                            }
                        }

                        MarketBook mb = new MarketBook()
                        {
                            LocalTime  = DateTime.Now,
                            ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(time),
                            AskPrice   = data.market.ask_list.First().Key,
                            AskSize    = data.market.ask_list.First().Value,
                            BidPrice   = data.market.bid_list.Last().Key,
                            BidSize    = data.market.bid_list.Last().Value,
                        };
                        _client.OnReport(Name, data.pair.Id(), mb);
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                await Authentification();

                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        var request = new Request
                        {
                            e    = "order-book-subscribe",
                            data = new DataRequest {
                                pair = new List <string>()
                                {
                                    item.Value.pair.First, item.Value.pair.Second
                                }, subscribe = true, depth = 0
                            },
                            oid = symbol
                        };

                        string paramData = JsonConvert.SerializeObject(request, Formatting.Indented);
                        await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 17
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }

                if (jsonResponse.Contains("tick_id"))
                {
                    var tickerResponse = JsonConvert.DeserializeObject <TickerResponse>(jsonResponse);
                    using (await _lock.LockAsync())
                    {
                        string symbol = "";
                        var    temp   = [email protected]('_');
                        if (temp.Count() == 4)
                        {
                            symbol = temp[2] + "_" + temp[3];
                        }
                        else
                        if (temp.Count() == 5)
                        {
                            symbol = temp[2] + "_" + temp[3] + "_" + temp[4];
                        }

                        var       symbolId = symbol.GetHashCode();
                        Subscribe data;
                        if (SubscribeList.TryGetValue(symbolId, out data))
                        {
                            data.market = new MarketBook()
                            {
                                AskPrice   = Convert.ToDouble([email protected]_ask),
                                AskSize    = Convert.ToDouble([email protected]_ask_size),
                                BidPrice   = Convert.ToDouble([email protected]_bid),
                                BidSize    = Convert.ToDouble([email protected]_bid_size),
                                LocalTime  = DateTime.Now,
                                ServerTime = [email protected],
                                LastPrice  = [email protected],
                                LastSize   = [email protected]
                            };

                            _client.OnReport(Name, data.pair.Id(), data.market);
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        if (item.Value.mode == SubscriptionModel.TopBook)
                        {
                            string channelName = "lightning_ticker_" + symbol;
                            var    symbolId    = symbol.GetHashCode();
                            var    request     =
                                new
                            {
                                method  = "subscribe",
                                @params = new { channel = channelName },
                                id      = symbolId,
                            };

                            string paramData = JsonConvert.SerializeObject(request, Formatting.Indented);
                            await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 18
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse.Contains("error"))
                {
                    JObject jToken;
                    jToken = JObject.Parse(jsonResponse);
                    var dict = jToken["error"].ToObject <Dictionary <string, string> >();
                    _client.OnEvent(Name, BrokerEvent.InternalError, "Message: " + dict["message"] + ", Description: " + dict["description"]);
                }
                else if (jsonResponse.Contains("method"))
                {
                    var response = JsonConvert.DeserializeObject <TickerResponse>(jsonResponse);
                    var method   = response.method;
                    var symbol   = [email protected];
                    var data     = response.@params;
                    if (method == "ticker" && SubscribeList.ContainsKey(symbol))
                    {
                        MarketBook mb = new MarketBook()
                        {
                            LocalTime  = DateTime.Now,
                            ServerTime = data.timestamp,
                            AskPrice   = Convert.ToDouble(data.ask),
                            BidPrice   = Convert.ToDouble(data.bid),
                            LastPrice  = Convert.ToDouble(data.last),
                            LastSize   = Convert.ToDouble(data.volume),
                        };
                        _client.OnReport(Name, SubscribeList[symbol].pair.Id(), mb);
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        var request = $"{{\"method\":\"subscribeTicker\",\"params\":{{ \"symbol\":\"{item.Value.pair.Symbol}\"}}, \"id\": \"123\"}}";

                        await chnl.SendCommand(Encoding.UTF8.GetBytes(request));
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 19
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }
                if (jsonResponse.Contains("1002"))
                {
                    JArray token = JArray.Parse(jsonResponse);
                    if (token[2].HasValues)
                    {
                        var chnlKey = Convert.ToInt32(token[2][0]);

                        if (SubscribeList.ContainsKey(chnlKey))
                        {
                            MarketBook mb = new MarketBook()
                            {
                                AskPrice  = token[2][2].ToObject <double>(),
                                BidPrice  = token[2][3].ToObject <double>(),
                                LastSize  = token[2][1].ToObject <double>(),
                                LocalTime = DateTime.Now
                            };
                            _client.OnReport(Name, SubscribeList[chnlKey].pair.Id(), mb);
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Logon:
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        if (item.Value.mode == SubscriptionModel.TopBook)
                        {
                            string paramData = $"{{\"command\":\"subscribe\",\"channel\":\"1002\"}}";
                            await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                        }
                    }
                }
                break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            case StreamMessageType.Error:
                break;

            default:
                break;
            }
        }
Exemplo n.º 20
0
        public async void ParseMessage(string jsonResponse)
        {
            if (jsonResponse == "null")
            {
                return;
            }

            JObject msg;
            string  id;

            try
            {
                msg = JObject.Parse(jsonResponse);
            }
            catch (Exception ex)
            {
                _logger.Log(LogPriority.Debug, $"{jsonResponse}  exc: {ex.Message} {ex.StackTrace}", Name);
                throw;
            }

            //MarketBook part
            if (msg.ContainsKey(Keys.MarketName))
            {
                using (await _lock.LockAsync())
                {
                    if (!_subscribeList.ContainsKey(msg[Keys.MarketName].ToString()))
                    {
                        return;
                    }
                }
                IEnumerable <JToken> buy_msg  = msg[Keys.Buys].Children();
                IEnumerable <JToken> sell_msg = msg[Keys.Sells].Children();
                int currentNonce = msg[Keys.Nonce].Value <int>();

                using (await _lock.LockAsync())
                {
                    var data = _subscribeList[msg[Keys.MarketName].ToString()].market;
                    id = _subscribeList[msg[Keys.MarketName].ToString()].pair.Id();

                    if (data.nonce != 0 && data.nonce == currentNonce)
                    {
                        _logger.Log(LogPriority.Debug, $"Received a duplicate nonce - {currentNonce} ", Name);
                        return;
                    }
                    else if (data.nonce != 0 && ((currentNonce - data.nonce) != 1))
                    {
                        _logger.Log(LogPriority.Debug, $"Error of synchronization {id}: correct nonce - {data.nonce + 1}, received nonce - {currentNonce} ", Name);
                        await Resibscribe(msg[Keys.MarketName].ToString(), data);

                        return;
                    }

                    int checker = 0;
                    if (buy_msg.FirstOrDefault() != null)
                    {
                        checker = buy_msg.FirstOrDefault().Count();
                    }
                    else if (sell_msg.FirstOrDefault() != null)
                    {
                        checker = sell_msg.FirstOrDefault().Count();
                    }
                    else
                    {
                        _logger.Log(LogPriority.Debug, "Empty data in ask/bid list", Name);
                        return;
                    }

                    if (checker == (int)msgType.Update && data.nonce < currentNonce && data.nonce != 0)
                    {
                        foreach (var item in buy_msg)
                        {
                            var itemType  = (int)item[Keys.Type];
                            var itemSize  = (double)item[Keys.Quantity];
                            var itemPrice = (double)item[Keys.Rate];
                            if (itemType == (int)UpdMarket.Add)
                            {
                                if (data.bid_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' already exists, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' already exists, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.bid_list.Add(itemPrice, itemSize);
                                }
                            }
                            else if (itemType == (int)UpdMarket.Remove)
                            {
                                if (!data.bid_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' not exists for delete, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' not exists for delete, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.bid_list.Remove(itemPrice);
                                }
                            }
                            else if (itemType == (int)UpdMarket.Update)
                            {
                                if (!data.bid_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' not exists for update, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' not exists for update, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.bid_list[itemPrice] = itemSize;
                                }
                            }
                            data.nonce = currentNonce;
                        }

                        foreach (var item in sell_msg)
                        {
                            var itemType  = (int)item[Keys.Type];
                            var itemSize  = (double)item[Keys.Quantity];
                            var itemPrice = (double)item[Keys.Rate];
                            if (itemType == (int)UpdMarket.Add)
                            {
                                if (data.ask_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' already exists, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' already exists, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.ask_list.Add(itemPrice, itemSize);
                                }
                            }
                            else if (itemType == (int)UpdMarket.Remove)
                            {
                                if (!data.ask_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' not exists for delete, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' not exists for delete, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.ask_list.Remove(itemPrice);
                                }
                            }
                            else if (itemType == (int)UpdMarket.Update)
                            {
                                if (!data.ask_list.ContainsKey(itemPrice))
                                {
                                    _logger.Log(LogPriority.Error, $"this Price '-{itemPrice}-' not exists for update, refresh marketbook snapshot", Name);
                                    _client.OnEvent(Name, BrokerEvent.InternalError, $"this Price '-{itemPrice}-' not exists for update, refresh marketbook snapshot");
                                    await Resibscribe(msg[Keys.MarketName].ToString(), data);

                                    return;
                                }
                                else
                                {
                                    data.ask_list[itemPrice] = itemSize;
                                }
                            }
                            data.nonce = currentNonce;
                        }
                    }
                    else if (checker == (int)msgType.FullSnapShot)
                    {
                        data.nonce    = currentNonce;
                        data.bid_list = new SortedDictionary <double, double>
                                            (buy_msg.ToDictionary(u => (double)u[Keys.Rate], u => (double)u[Keys.Quantity]), Comparer <double> .Create((a, b) => b.CompareTo(a)));
                        data.ask_list = new SortedDictionary <double, double>
                                            (sell_msg.ToDictionary(u => (double)u[Keys.Rate], u => (double)u[Keys.Quantity]), Comparer <double> .Default);
                    }
                    else if (checker == (int)msgType.Update && data.nonce == 0)
                    {
                        return;
                    }

                    try
                    {
                        var Market = new MarketBook()
                        {
                            LocalTime = DateTime.Now,
                            BidPrice  = data.bid_list.First().Key,
                            AskPrice  = data.ask_list.First().Key,
                            BidSize   = data.bid_list.First().Value,
                            AskSize   = data.ask_list.First().Value,
                        };

                        if (_subscribeList[msg[Keys.MarketName].ToString()].mode == SubscriptionModel.TopBook)
                        {
                            _client.OnReport(Name, id, Market);
                        }
                    }
                    catch (Exception e)
                    {
                        _logger.Log(LogPriority.Error, $"Exception - {e.Message}", Name);
                    }
                }
            }
        }
Exemplo n.º 21
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }

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

                if (evnt == "data")
                {
                    string symbol = jToken["channel"].ToString().Remove(0, 11);
                    var    result = JsonConvert.DeserializeObject <OrderBookResponse>(data.ToString());

                    Subscribe dataItem;
                    if (SubscribeList.TryGetValue(symbol, out dataItem))
                    {
                        MarketBook mb = new MarketBook()
                        {
                            AskPrice   = Convert.ToDouble(result.asks[0][0]),
                            BidPrice   = Convert.ToDouble(result.bids[0][0]),
                            LocalTime  = DateTime.Now,
                            ServerTime = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(result.timestamp))
                        };
                        _client.OnReport(Name, dataItem.pair.Id(), mb);
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol  = item.Key;
                        var request = "{\"event\":\"pusher:subscribe\",\"data\":{\"channel\":\"order_book_" + symbol + "\"}}";
                        await chnl.SendCommand(Encoding.UTF8.GetBytes(request));

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

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 22
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }

                string  evnt   = "";
                JObject jToken = JObject.Parse(jsonResponse);
                evnt = jToken["event"]?.Value <string>();
                var data = jToken["data"].ToString();

                if (evnt == "updated")
                {
                    var    result = JsonConvert.DeserializeObject <Ticker>(data);
                    string symbol = result.currency_pair_code.ToLower();

                    Subscribe dataItem;
                    if (SubscribeList.TryGetValue(symbol, out dataItem))
                    {
                        MarketBook mb = new MarketBook()
                        {
                            AskPrice  = Convert.ToDouble(result.market_ask),
                            BidPrice  = Convert.ToDouble(result.market_bid),
                            LastPrice = Convert.ToDouble(result.last_traded_price),
                            LastSize  = Convert.ToDouble(result.last_traded_quantity),
                            LocalTime = DateTime.Now,
                        };
                        _client.OnReport(Name, dataItem.pair.Id(), mb);
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                var _pairs = await GetProducts();

                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol  = item.Key;
                        var chnlId  = _pairs[symbol];
                        var req     = "product_cash_" + symbol + "_" + chnlId;
                        var request = $"{{\"event\":\"pusher:subscribe\",\"data\":{{\"channel\":\"{req}\"}}}}";
                        await chnl.SendCommand(Encoding.UTF8.GetBytes(request));

                        _client.OnEvent(Name, BrokerEvent.CoinSubscribed, symbol);
                        _logger.Log(LogPriority.Info, "Coin Subscribed - " + symbol, Name);
                    }
                }
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 23
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var     jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                JObject jToken;
                JArray  jT;
                if (!jsonResponse.Contains('{') && !jsonResponse.Contains("hb"))
                {
                    jT = JArray.Parse(jsonResponse);
                    switch (jT[0].ToString())
                    {
                    case "0":
                        break;

                    default:
                    {
                        if (SubscribeList.ContainsKey((int)jT[0]))
                        {
                            var chn = SubscribeList[(int)jT[0]];
                            if (chn.name == "ticker")
                            {
                                _client.OnReport(Name, chn.Id,
                                                 new MarketBook()
                                        {
                                            BidPrice  = (double)jT[1][0],
                                            AskPrice  = (double)jT[1][2],
                                            BidSize   = (double)jT[1][1],
                                            AskSize   = (double)jT[1][3],
                                            LastPrice = (double)jT[1][6],
                                            LocalTime = DateTime.Now,
                                        });
                                break;
                            }
                        }
                    }
                    break;
                    }
                }
                else
                {
                    if (jsonResponse.Contains("\"hb\"") || jsonResponse.Contains("\"ps\"") || jsonResponse.Contains("\"os\"") || jsonResponse.Contains("\"ws\""))
                    {
                        return;
                    }

                    jToken = JObject.Parse(jsonResponse);
                    var type = jToken["event"]?.Value <string>();
                    switch (type)
                    {
                    case "subscribed":
                    {
                        var cId = Utilities.StrToInstr(jToken["pair"].Value <string>(), Name).Id();
                        using (await _lock.LockAsync())
                        {
                            SubscribeList.Add(jToken["chanId"].Value <int>(), new SubscribeChannels("ticker", jToken["pair"].Value <string>(), new MarketBook(), cId));
                        }
                        _logger.Log(LogPriority.Info, $"Channel {cId} - {jToken["channel"].Value<string>()}  is  subscribed.", Name);
                        _client.OnEvent(Name, BrokerEvent.CoinSubscribed, cId);

                        break;
                    }

                    case "unsubscribed":
                    {
                        using (await _lock.LockAsync())
                        {
                            if (SubscribeList.ContainsKey(jToken["chanId"].Value <int>()))
                            {
                                var chId = SubscribeList[jToken["chanId"].Value <int>()].Id;
                                SubscribeList.Remove(jToken["chanId"].Value <int>());
                                _logger.Log(LogPriority.Info, $"Channel '{chId.ToString()}'  is  unsubscribed.", Name);
                                _client.OnEvent(Name, BrokerEvent.CoinUnsubscribed, chId.ToString());
                            }
                        }
                        break;
                    }

                    case "error":
                    {
                        var code = jToken["code"]?.Value <string>();
                        _logger.Log(LogPriority.Info, jToken["msg"].ToString(), Name);
                        switch (code)
                        {
                        /*
                         *  Error Codes
                         *  10300 : Subscription failed (generic)
                         *  10301 : Already subscribed
                         *  10302 : Unknown channel
                         *  10400 : Unsubscription failed (generic)
                         *  10401 : Not subscribed
                         */
                        case "10300":
                        case "10301":
                        case "10302":
                        {
                            using (await _lock.LockAsync())
                            {
                                var ch = SubscribeList.Where(u => u.Value.pair.Contains(jToken["pair"].Value <string>()) && u.Value.name == jToken["channel"].Value <string>()).FirstOrDefault();
                                if (ch.Value != null)
                                {
                                    _client.OnEvent(Name, BrokerEvent.CoinSubscribedFault, ch.Value.Id);
                                    SubscribeList.Remove(ch.Key);
                                }
                                else
                                {
                                    _client.OnEvent(Name, BrokerEvent.InternalError, jToken["msg"].ToString());
                                }
                            }
                            break;
                        }

                        case "10401":
                        case "10400":
                        {
                            var ch = SubscribeList.Where(u => u.Value.pair.Contains(jToken["pair"].Value <string>()) && u.Value.name == jToken["channel"].Value <string>()).FirstOrDefault();
                            if (ch.Value != null)
                            {
                                _client.OnEvent(Name, BrokerEvent.CoinUnsubscribedFault, ch.Value.Id);
                            }
                            break;
                        }

                        default:
                        {
                            {
                                _client.OnEvent(Name, BrokerEvent.InternalError, jToken["msg"].ToString());
                                break;
                            }
                        }
                        }
                        break;
                    }

                    default:
                    {
                        _client.OnEvent(Name, BrokerEvent.Info, jsonResponse);
                        break;
                    }
                    }
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var request = $"{{\"event\":\"subscribe\",\"channel\":\"ticker\", \"symbol\": \"{item.Value.pair}\"}}";
                        await chnl.SendCommand(Encoding.UTF8.GetBytes(request));
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }
Exemplo n.º 24
0
        private async Task ParseMessage(SocketEventHandlerArgs msg)
        {
            switch (msg.type)
            {
            case StreamMessageType.Data:
            {
                var jsonResponse = Encoding.UTF8.GetString(msg.msg, 0, msg.msg.Length);
                if (jsonResponse == "[]")
                {
                    return;
                }

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


                if (type == "error")
                {
                    if (jToken["message"]?.Value <string>() == "Failed to subscribe")
                    {
                        _client.OnEvent(Name, BrokerEvent.CoinSubscribedFault, jToken["reason"]?.Value <string>());
                        _client.OnEvent(Name, BrokerEvent.InternalError, jToken["reason"]?.Value <string>());
                    }
                }
                else
                if (type == "ticker")
                {
                    string symbol = jToken["product_id"].ToString();

                    MarketBook mb = new MarketBook()
                    {
                        AskPrice  = (double)jToken["best_ask"],
                        BidPrice  = (double)jToken["best_bid"],
                        LocalTime = DateTime.Now,
                    };
                    _client.OnReport(Name, Name + symbol.Replace("-", ""), mb);
                }
            }
            break;

            case StreamMessageType.Error:
                break;

            case StreamMessageType.Logon:
            {
                _client.OnEvent(Name, BrokerEvent.ConnectorStarted, string.Empty);

                _client.OnEvent(Name, BrokerEvent.SessionLogon, "");
                using (await _lock.LockAsync())
                {
                    foreach (var item in SubscribeList)
                    {
                        var symbol = item.Key;

                        if (item.Value.mode == SubscriptionModel.TopBook)
                        {
                            var request = new
                            {
                                type        = "subscribe",
                                product_ids = new List <string>()
                                {
                                    symbol
                                },
                                channels = new List <string>()
                                {
                                    "ticker"
                                },
                            };

                            string paramData = JsonConvert.SerializeObject(request, Formatting.Indented);
                            await chnl.SendCommand(Encoding.UTF8.GetBytes(paramData));
                        }
                    }
                }
            }
            break;

            case StreamMessageType.Logout:
                _client.OnEvent(Name, BrokerEvent.SessionLogout, "");
                break;

            default:
                break;
            }
        }