Exemplo n.º 1
0
        public object aspect_spread(object rowObject)
        {
            ExchangeOrder order = (ExchangeOrder)rowObject;
            //LogManager.AddLogMessage(Name, "aspect_spread", "rate=" + order.symbol + " | " + order.market + " | " + order.amount, LogManager.LogMessageType.DEBUG);

            ExchangeTicker ticker = Tickers.FirstOrDefault(item => item.exchange == order.exchange && item.symbol == order.symbol && item.market == order.market);

            if (ticker != null)
            {
                if (order.market.Contains("USD"))
                {
                    return(ticker.last.ToString("C"));
                }
                else
                {
                    return(ticker.last.ToString("N8"));
                }

                //LogManager.AddLogMessage(Name, "aspect_spread", "rate=" + order.rate + " | " + ticker.last, LogManager.LogMessageType.DEBUG);
                //return 0;
            }
            else
            {
                return(0);
            }

            //return "10%";
        }
Exemplo n.º 2
0
        private void ProcessMessageTicker(ISerializedValue[] arguments)
        {
            var currencyPair          = CurrencyPair.Parse(arguments[0].Deserialize <string>());
            var priceLast             = arguments[1].Deserialize <double>();
            var orderTopSell          = arguments[2].Deserialize <double>();
            var orderTopBuy           = arguments[3].Deserialize <double>();
            var priceChangePercentage = arguments[4].Deserialize <double>();
            var volume24HourBase      = arguments[5].Deserialize <double>();
            var volume24HourQuote     = arguments[6].Deserialize <double>();
            var isFrozenInternal      = arguments[7].Deserialize <byte>();

            var marketData = new MarketData
            {
                PriceLast             = priceLast,
                OrderTopSell          = orderTopSell,
                OrderTopBuy           = orderTopBuy,
                PriceChangePercentage = priceChangePercentage,
                Volume24HourBase      = volume24HourBase,
                Volume24HourQuote     = volume24HourQuote,
                IsFrozenInternal      = isFrozenInternal
            };

            if (Tickers.ContainsKey(currencyPair))
            {
                Tickers[currencyPair] = marketData;
            }
            else
            {
                Tickers.Add(currencyPair, marketData);
            }

            OnTickerChanged?.Invoke(this, new TickerChangedEventArgs(currencyPair, marketData));
        }
Exemplo n.º 3
0
        public virtual void AllTests()
        {
            AddNothing();

            Tickers.Resume();
            AddData();

            Tickers.Resume();
            AddSingle();

            Tickers.Resume();
            RemoveEdge();

            Tickers.Resume();
            RemoveEdgeAsItem();

            Tickers.Resume();
            RemoveItem();

            Tickers.Resume();
            AddEdge();

            Tickers.Resume();
            ChangeEdge();

            Tickers.Resume();
            RemoveEdgeOfEdgeLeaf();
        }
Exemplo n.º 4
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async ValueTask <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                var _params = publicClient.MergeParamsAndArgs(args);

                var _json_value = await publicClient.CallApiGet1Async("/ticker/ALL", _params);

#if RAWJSON
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _json_data = publicClient.DeserializeObject <BTickers>(_json_value.Content);
                    if (_json_data.statusCode == 0)
                    {
                        var _timestamp = _json_data.result["date"].Value <long>();

                        foreach (var _t in _json_data.result)
                        {
                            if (_t.Value.GetType() == typeof(JValue))
                            {
                                continue;
                            }

                            var _ticker = publicClient.DeserializeObject <BTickerItem>(_t.Value.ToString());
                            {
                                _ticker.symbol    = _t.Key;
                                _ticker.timestamp = _timestamp;

                                _result.result.Add(_ticker);
                            }
                        }
                    }
                    else
                    {
                        var _message = publicClient.GetErrorMessage(_json_data.statusCode);
                        _json_result.SetFailure(
                            _message,
                            ErrorCode.ResponseDataError
                            );
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 5
0
        public override bool GetTickersInfo()
        {
            string address = "https://yobit.net/api/3/info";
            string text    = string.Empty;

            try {
                text = GetDownloadString(address);
            }
            catch (Exception) {
                return(false);
            }
            if (string.IsNullOrEmpty(text))
            {
                return(false);
            }
            Tickers.Clear();
            JObject res   = (JObject)JsonConvert.DeserializeObject(text);
            int     index = 0;

            res = res.Value <JObject>("pairs");
            foreach (JProperty prop in res.Children())
            {
                YobitTicker t = new YobitTicker(this);
                t.Index        = index;
                t.CurrencyPair = prop.Name;
                JObject obj = (JObject)prop.Value;
                t.Fee      = obj.Value <double>("fee");
                t.IsFrozen = obj.Value <int>("hidden") == 1;
                Tickers.Add(t);
                index++;
            }
            IsInitialized = true;
            return(true);
        }
Exemplo n.º 6
0
        public void UpdateTickersInfo()
        {
            string address = "https://poloniex.com/public?command=returnTicker";
            string text    = GetDownloadString(address);

            if (string.IsNullOrEmpty(text))
            {
                return;
            }
            JObject res = (JObject)JsonConvert.DeserializeObject(text);

            foreach (JProperty prop in res.Children())
            {
                PoloniexTicker t   = Tickers.FirstOrDefault((i) => i.CurrencyPair == prop.Name);
                JObject        obj = (JObject)prop.Value;
                t.Last       = obj.Value <double>("last");
                t.LowestAsk  = obj.Value <double>("lowestAsk");
                t.HighestBid = obj.Value <double>("highestBid");
                t.Change     = obj.Value <double>("percentChange");
                t.BaseVolume = obj.Value <double>("baseVolume");
                t.Volume     = obj.Value <double>("quoteVolume");
                t.IsFrozen   = obj.Value <int>("isFrozen") != 0;
                t.Hr24High   = obj.Value <double>("high24hr");
                t.Hr24Low    = obj.Value <double>("low24hr");
            }
        }
Exemplo n.º 7
0
        public override bool UpdateTickersInfo() {
            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(TickersUpdateAddress);
            }
            catch(Exception e) {
                Debug.WriteLine(e.ToString());
                return false;
            }
            if(bytes == null)
                return false;

            int startIndex = 0;
            List<string[]> list = JSonHelper.Default.DeserializeArrayOfArrays(bytes, ref startIndex, 11);
            for(int i = 0; i < list.Count; i++) {
                string[] item = list[i];
                BitFinexTicker ticker = (BitFinexTicker)Tickers.FirstOrDefault(t => t.CurrencyPair == item[0]);
                ticker.HighestBid = FastValueConverter.Convert(item[1]);
                ticker.LowestAsk = FastValueConverter.Convert(item[3]);
                ticker.Change = FastValueConverter.Convert(item[6]);
                ticker.Last = FastValueConverter.Convert(item[7]);
                ticker.Volume = FastValueConverter.Convert(item[8]);
                ticker.Hr24High = FastValueConverter.Convert(item[9]);
                ticker.Hr24Low = FastValueConverter.Convert(item[10]);
            }
            return true;
        }
Exemplo n.º 8
0
 protected void AddMarketSummary(PriceTicker ticker)
 {
     if (tickersMapping.TryAdd(ticker.Symbol, Tickers.Count))
     {
         Tickers.Add(ticker);
     }
 }
Exemplo n.º 9
0
        public override bool GetTickersInfo()
        {
            string text    = string.Empty;
            string address = "http://api.hitbtc.com/api/1/public/symbols";

            try {
                text = GetDownloadString(address);
            }
            catch (Exception) {
                return(false);
            }

            Tickers.Clear();
            Dictionary <string, object> res = null;

            lock (JsonParser) {
                res = (Dictionary <string, object>)JsonParser.Parse(text);
            }
            List <object> symbols = (List <object>)res["symbols"];
            int           index   = 0;

            foreach (Dictionary <string, object> s in symbols)
            {
                HitBtcTicker t = new HitBtcTicker();
                t.Index = index;
                index++;
                t.BaseCurrency   = s["currency"].ToString();
                t.MarketCurrency = s["commodity"].ToString();
                t.Step           = Convert.ToDecimal(s["step"]);
                Tickers.Add(t);
            }

            return(true);
        }
Exemplo n.º 10
0
        public bool UpdateUI(bool resize = false)
        {
            if (InvokeRequired)
            {
                UpdateUICallback d = new UpdateUICallback(UpdateUI);
                Invoke(d, new object[] { resize });
            }
            else
            {
                List <ExchangeTicker> list = Tickers.Where(item => item.exchange == Exchange.Name).OrderBy(item => item.symbol).ToList();
                //LogManager.AddLogMessage(Name, "UpdateUI", "selectedMarket=" + CurrentMarket, LogManager.LogMessageType.DEBUG);

                if (Exchange.CurrentMarket == "ALL")
                {
                    column_market.IsVisible = true;
                    listView.SetObjects(list);
                }
                else
                {
                    // FILTER BY MARKET SYMBOL
                    column_market.IsVisible = false;
                    listView.SetObjects(list.Where(item => item.market == Exchange.CurrentMarket));
                }
                toolStripLabel_title.Text = listView.Items.Count + " TICKERS";

                if (resize)
                {
                    ResizeUI();
                }
            }
            return(true);
        }
Exemplo n.º 11
0
        public PanelViewModel(string panel, string market)
        {
            _panel                  = panel;
            MainButtonAction        = "Update Database";
            BackgroundWorkerNotBusy = true;

            if (Tickers == null)
            {
                Tickers = new ObservableCollection <Ticker>();
            }
            const string path = "Resources/Tickers.xml";

            var serializer = new XmlSerializer(typeof(Tickers));

            var reader  = new StreamReader(path);
            var tickers = ((Tickers)serializer.Deserialize(reader)).Ticker;

            reader.Close();

            foreach (var ticker in tickers.Where(x => x.Market == market && x.Sources.Count > 0))
            {
                ticker.LastUpdate = "Not Available";
                Tickers.Add(ticker);
            }

            if (!String.IsNullOrEmpty(Properties.Settings.Default[_panel + "Path"].ToString()))
            {
                MetastockFolder = Properties.Settings.Default[_panel + "Path"].ToString();
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async Task <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                var _params = new Dictionary <string, object>();
                {
                    _params.Add("command", "returnTicker");

                    if (args != null)
                    {
                        foreach (var _a in args)
                        {
                            if (_params.ContainsKey(_a.Key) == true)
                            {
                                _params.Remove(_a.Key);
                            }

                            _params.Add(_a.Key, _a.Value);
                        }
                    }
                }

                var _json_value = await publicClient.CallApiGet1Async("", _params);

#if DEBUG
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _tickers = publicClient.DeserializeObject <Dictionary <string, JToken> >(_json_value.Content);
                    {
                        foreach (var _t in _tickers)
                        {
                            var _ticker = publicClient.DeserializeObject <PTickerItem>(_t.Value.ToString());

                            _ticker.symbol    = _t.Key;
                            _ticker.timestamp = CUnixTime.NowMilli;

                            _result.result.Add(_ticker);
                        }
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 13
0
        public async Task <ITickers> GetTickers(string currencies, decimal exchangeRate)
        {
            ITickers tickers = new Tickers(Common.StockExchange.Types.StockExchange.QuadrigaCx);

            try
            {
                foreach (string currency in currencies.Split(','))
                {
                    string uri = $"{BaseUri}/ticker?book={currency}";

                    HttpWebRequest = WebRequest.Create(uri) as HttpWebRequest;
                    if (HttpWebRequest != null)
                    {
                        HttpWebRequest.Method = "GET";
                        HttpWebRequest.Accept = "application/json";

                        using (HttpWebResponse = await HttpWebRequest.GetResponseAsync() as HttpWebResponse)
                        {
                            if (HttpWebResponse != null)
                            {
                                StreamReader = new StreamReader(HttpWebResponse.GetResponseStream() ?? throw new InvalidOperationException());
                            }

                            JObject resultsJson = JsonConvert.DeserializeObject <JObject>(StreamReader.ReadToEnd());

                            string  pair      = currency.Replace("_", "/").ToUpper();
                            decimal lastPrice = Convert.ToDecimal(resultsJson["last"]);
                            decimal bidPrice  = Convert.ToDecimal(resultsJson["bid"]);
                            decimal askPrice  = Convert.ToDecimal(resultsJson["ask"]);
                            decimal highPrice = Convert.ToDecimal(resultsJson["high"]);
                            decimal lowPrice  = Convert.ToDecimal(resultsJson["low"]);
                            decimal volume    = Convert.ToDecimal(resultsJson["volume"]);

                            if (!pair.Equals("BTC/CAD"))
                            {
                                if (pair.Split('/')[1].Equals("CAD"))
                                {
                                    pair       = pair.Replace("CAD", "USD");
                                    lastPrice *= exchangeRate;
                                    bidPrice  *= exchangeRate;
                                    askPrice  *= exchangeRate;
                                    highPrice *= exchangeRate;
                                    lowPrice  *= exchangeRate;
                                }

                                tickers.PairTickers.Add(new PairTickerVolumeHighLowPrice(pair, lastPrice, bidPrice, askPrice, volume, highPrice, lowPrice));
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(tickers);
        }
Exemplo n.º 14
0
 /// <summary>
 /// add new ticker for an unadded coin
 /// </summary>
 private void AddNewTicker()
 {
     if (String.IsNullOrEmpty(NewCoin) || IsCoinValid(NewCoin) == false)
     {
         return;
     }
     Tickers.Add(new Ticker(NewCoin, 0, 0));
     NewCoin = "";
 }
 protected virtual void UpdateTickersList()
 {
     Tickers.Clear();
     for (int i = 0; i < StrategyInfo.Tickers.Count; i++)
     {
         Tickers.Add(StrategyInfo.Tickers[i].Ticker);
     }
     Ticker = Tickers.Count > 0 ? Tickers[0] : null;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async ValueTask <Tickers> FetchTickersAsync(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarketsAsync();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                //var _asset_pairs = new StringBuilder();
                //{
                //    foreach (var _market in _markets.result)
                //        _asset_pairs.Append($"{_market.Value.symbol},");
                //    _asset_pairs.Length--;
                //}

                var _params = new Dictionary <string, object>();
                {
                    _params.Add("pair", String.Join(",", _markets.result.Select(m => m.Value.symbol)));

                    publicClient.MergeParamsAndArgs(_params, args);
                }

                var _json_value = await publicClient.CallApiGet1Async("/0/public/Ticker", _params);

#if RAWJSON
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _json_data = publicClient.DeserializeObject <JObject>(_json_value.Content);
                    {
                        var _tickers = publicClient.DeserializeObject <Dictionary <string, JToken> >(_json_data["result"].ToString());

                        foreach (var _t in _tickers)
                        {
                            var _ticker = publicClient.DeserializeObject <KTickerItem>(_t.Value.ToString());

                            _ticker.symbol    = _t.Key;
                            _ticker.timestamp = CUnixTime.NowMilli;

                            _result.result.Add(_ticker);
                        }
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 17
0
        public bool SetExchange(ExchangeManager.Exchange exchange)
        {
            if (InvokeRequired)
            {
                SetExchangeCallback d = new SetExchangeCallback(SetExchange);
                Invoke(d, new object[] { exchange });
            }
            else
            {
                Visible  = false;
                Exchange = exchange;
                List <ExchangeTicker> list = Tickers.Where(item => item.exchange == Exchange.Name).ToList();
                //LogManager.AddDebugMessage(this.Name, "ExchangeTickerListControl_Load", "list count=" + list.Count + " | " + exchange);
                var markets = list.Select(p => p.market).OrderByDescending(m => m).Distinct();
                // CLEAR MARKET BUTTONS
                foreach (ToolStripItem item in toolStrip.Items)
                {
                    if (item.Alignment == ToolStripItemAlignment.Right)
                    {
                        toolStrip.Items.Remove(item);
                    }
                }
                // REBUILD BUTTONS
                foreach (string market in markets)
                {
                    ToolStripRadioButton button = new ToolStripRadioButton()
                    {
                        Text = market,
                        RadioButtonGroupId = 1,
                        Alignment          = ToolStripItemAlignment.Right,
                        Image   = ContentManager.GetSymbolIcon(market),
                        Checked = IsMarketButton(market)
                    };
                    button.Click += new EventHandler(marketButton_Click);
                    toolStrip.Items.Add(button);
                    toolStrip.Items.Add(new ToolStripSeparator()
                    {
                        Alignment = ToolStripItemAlignment.Right
                    });
                }

                ToolStripRadioButton allButton = new ToolStripRadioButton()
                {
                    Text = "ALL",
                    RadioButtonGroupId = 1,
                    Image     = Properties.Resources.ConnectionStatus_ACTIVE,
                    Checked   = IsMarketButton("ALL"),
                    Alignment = ToolStripItemAlignment.Right
                };
                allButton.Click += new EventHandler(marketButton_Click);
                toolStrip.Items.Add(allButton);
                Visible = true;
                UpdateUI(true);
            }
            return(true);
        }
Exemplo n.º 18
0
 public override void RemoveItem()
 {
     base.RemoveItem();
     Tickers.Resume();
     InitGraphTest("** remove " + Data.One);
     Graph.Remove(Data.One);
     FullReportGraph(Graph, "Removed:\t" + Data.One);
     IsRemoved(Data.One);
     ReportSummary();
 }
Exemplo n.º 19
0
        public async Task <decimal> ValueBitfinex(string AskOrBid)
        {
            BitfinexApi.BitfinexAssets assets = new BitfinexApi.BitfinexAssets();
            Tickers bitfinexClient            = new Tickers();

            decimal answer = await bitfinexClient.Market(assets.ETH, assets.BTC, AskOrBid);

            Console.WriteLine($"Bitfinex is {AskOrBid} {answer}");
            return(answer);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async Task <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                var _params = publicClient.MergeParamsAndArgs(args);

                var _currency_pairs = "";
                foreach (var _market in _markets.result.GroupBy(m => m.Value.quoteName))
                {
                    if (String.IsNullOrEmpty(_currency_pairs) == false)
                    {
                        _currency_pairs += "/";
                    }
                    _currency_pairs += _market.Key;
                }

                var _json_value = await publicClient.CallApiGet1Async($"/tickers/{_currency_pairs}", _params);

#if DEBUG
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _json_data = publicClient.DeserializeObject <CTickers>(_json_value.Content);
                    if (_json_data.success == true)
                    {
                        foreach (var _ticker in _json_data.result)
                        {
                            _ticker.symbol = _ticker.symbol.Replace(':', '/');

                            _result.result.Add(_ticker);
                        }
                    }
                    else
                    {
                        _json_result.SetFailure(_json_data.message);
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async Task <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                var _params = new Dictionary <string, object>();
                {
                    _params.Add("currency", "all");

                    publicClient.MergeParamsAndArgs(_params, args);
                }

                var _json_value = await publicClient.CallApiGet1Async("/ticker", _params);

#if DEBUG
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _tickers = publicClient.DeserializeObject <Dictionary <string, JToken> >(_json_value.Content);
                    {
                        var _timestamp = _tickers["timestamp"].Value <long>() * 1000;

                        foreach (var _t in _tickers)
                        {
                            if (_t.Value.GetType() == typeof(JValue))
                            {
                                continue;
                            }

                            var _ticker = publicClient.DeserializeObject <CTickerItem>(_t.Value.ToString());

                            _ticker.symbol    = _t.Key;
                            _ticker.timestamp = _timestamp;

                            _result.result.Add(_ticker);
                        }
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 22
0
        public override bool GetTickersInfo()
        {
            if (Tickers.Count > 0)
            {
                return(true);
            }

            string address = "https://api.bitfinex.com/v1/symbols";

            byte[] bytes = null;
            try {
                bytes = GetDownloadBytes(address);
            }
            catch (Exception) {
                return(false);
            }
            if (bytes == null)
            {
                return(false);
            }

            string text = UTF8Encoding.Default.GetString(bytes);

            text = text.Replace('[', ' ');
            text = text.Replace(']', ' ');
            text = text.Replace('"', ' ');

            string[] tickers = text.Split(',');
            foreach (string item in tickers)
            {
                BitFinexTicker m            = new BitFinexTicker(this);
                string         currencyPair = item.Trim();

                m.MarketCurrency = currencyPair.Substring(0, 3).ToUpper();
                m.BaseCurrency   = currencyPair.Substring(3, 3).ToUpper();
                m.CurrencyPair   = "t" + currencyPair.ToUpper();
                m.MarketName     = m.CurrencyPair;
                m.Index          = Tickers.Count;
                Tickers.Add(m);
            }
            address = "https://api.bitfinex.com/v2/tickers?symbols=";
            foreach (BitFinexTicker ticker in Tickers)
            {
                address += ticker.CurrencyPair;
                if (Tickers.IndexOf(ticker) < Tickers.Count - 1)
                {
                    address += ",";
                }
            }
            TickersUpdateAddress = address;

            IsInitialized = true;
            return(true);
        }
Exemplo n.º 23
0
        public async Task <ITickers> GetTickers(string currencies, decimal exchangeRate)
        {
            string uri = $"{BaseUri}/instrument/active{currencies}";

            ITickers tickers = new Tickers(Common.StockExchange.Types.StockExchange.Bitmex);

            try
            {
                HttpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

                if (HttpWebRequest != null)
                {
                    HttpWebRequest.Method = "GET";
                    HttpWebRequest.Accept = "application/json";

                    using (HttpWebResponse = await HttpWebRequest.GetResponseAsync() as HttpWebResponse)
                    {
                        if (HttpWebResponse != null)
                        {
                            StreamReader = new StreamReader(HttpWebResponse.GetResponseStream() ?? throw new InvalidOperationException());
                        }

                        JArray resultsJson = JsonConvert.DeserializeObject <JArray>(StreamReader.ReadToEnd());

                        foreach (JToken ticker in resultsJson)
                        {
                            string baseCurrency  = ticker["underlying"].ToString();
                            string quoteCurrency = ticker["quoteCurrency"].ToString();

                            string  pair      = $"{baseCurrency}/{quoteCurrency}";
                            decimal lastPrice = string.IsNullOrEmpty(ticker["lastPrice"].ToString()) ? 0m : Convert.ToDecimal(ticker["lastPrice"]);
                            decimal bidPrice  = string.IsNullOrEmpty(ticker["bidPrice"].ToString()) ? 0m : Convert.ToDecimal(ticker["bidPrice"]);
                            decimal askPrice  = string.IsNullOrEmpty(ticker["askPrice"].ToString()) ? 0m : Convert.ToDecimal(ticker["askPrice"]);
                            decimal volume    = string.IsNullOrEmpty(ticker["volume"].ToString()) ? 0m : Convert.ToDecimal(ticker["volume"]);
                            decimal highPrice = string.IsNullOrEmpty(ticker["highPrice"].ToString()) ? 0m : Convert.ToDecimal(ticker["highPrice"]);
                            decimal lowPrice  = string.IsNullOrEmpty(ticker["lowPrice"].ToString()) ? 0m : Convert.ToDecimal(ticker["lowPrice"]);

                            pair = pair.Replace("XBT", "BTC").Replace("DASH", "DSH");

                            if (!IsPairExist(tickers.PairTickers, pair))
                            {
                                tickers.PairTickers.Add(new PairTickerVolumeHighLowPrice(pair, lastPrice, bidPrice, askPrice, volume, highPrice, lowPrice));
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(tickers);
        }
Exemplo n.º 24
0
        public async Task <List <Ticker> > UpdateTickersAsync(List <Product> products)
        {
            string json = null;

            try
            {
                ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.General,
                                            "Updating Update Tickers Information.");
                if (products == null || !products.Any())
                {
                    return(Tickers);
                }
                if (Tickers == null)
                {
                    Tickers = new List <Ticker>();
                }
                //Get price of all products
                foreach (Product product in products)
                {
                    Request request = new Request(ConnectionAdapter.Authentication.EndpointUrl, "GET",
                                                  $"/products/{product.ID}/ticker");
                    json = await ConnectionAdapter.RequestAsync(request);

                    if (string.IsNullOrEmpty(json))
                    {
                        return(Tickers);
                    }
                    Ticker ticker = JsonSerializer.Deserialize <Ticker>(json);
                    Tickers?.RemoveAll(x => x.ProductID == product.ID);
                    if (ticker == null)
                    {
                        continue;
                    }
                    ticker.ProductID = product.ID;
                    Tickers.Add(ticker);
                }

                foreach (Ticker ticker in Tickers)
                {
                    if (decimal.TryParse(ticker.Price, out decimal decimalPrice))
                    {
                        CurrentPrices[ticker.ProductID] = decimalPrice;
                    }
                }
            }
            catch (Exception e)
            {
                ProcessLogBroadcast?.Invoke(ApplicationName, MessageType.Error,
                                            $"Method: UpdateTickersAsync\r\nException Stack Trace: {e.StackTrace}\r\nJSON: {json}");
            }

            return(Tickers);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async Task <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                //var _asset_pairs = new StringBuilder();
                //{
                //    foreach (var _market in _markets.result)
                //        _asset_pairs.Append($"{_market.Value.symbol},");
                //    _asset_pairs.Length--;
                //}

                var _params = new Dictionary <string, object>();
                {
                    _params.Add("extraCcyPairs", String.Join(",", _markets.result.Select(m => m.Value.symbol)));

                    publicClient.MergeParamsAndArgs(_params, args);
                }

                var _json_value = await publicClient.CallApiGet1Async("money/ticker", _params);

#if DEBUG
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _json_data = publicClient.DeserializeObject <ATickers>(_json_value.Content);
                    {
                        foreach (var _t in _json_data.result)
                        {
                            var _ticker = _t.Value;
                            _ticker.symbol = _t.Key;

                            _result.result.Add(_ticker);
                        }
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
        public override bool GetTickersInfo()
        {
            string address = "https://www.bitmex.com/api/v1/instrument?columns=typ,symbol,rootSymbol,quoteCurrency,highPrice,lowPrice,bidPrice,askPrice,lastChangePcnt,hasLiquidity,volume,tickSize,takerFee&start=0&count=500";
            string text    = string.Empty;

            try {
                text = GetDownloadString(address);

                if (string.IsNullOrEmpty(text))
                {
                    return(false);
                }
                Tickers.Clear();
                JArray res   = JsonConvert.DeserializeObject <JArray>(text);
                int    index = 0;
                foreach (JObject obj in res.Children())
                {
                    if (!obj.Value <bool>("hasLiquidity"))
                    {
                        continue;
                    }
                    string       pair = obj.Value <string>("symbol");
                    BitmexTicker t    = (BitmexTicker)Tickers.FirstOrDefault(tt => tt.CurrencyPair == pair);
                    if (t == null)
                    {
                        t = new BitmexTicker(this);
                    }
                    t.Index          = index;
                    t.ContractTicker = true;
                    t.ContractValue  = 1; // 1 USD
                    t.CurrencyPair   = pair;
                    t.MarketCurrency = obj.Value <string>("rootSymbol");
                    t.BaseCurrency   = obj.Value <string>("quoteCurrency");
                    t.TickSize       = ToDouble(obj, "tickSize");
                    t.Last           = ToDouble(obj, "lastPrice");
                    t.Hr24High       = ToDouble(obj, "highPrice");
                    t.Hr24Low        = ToDouble(obj, "lowPrice");
                    t.HighestBid     = ToDouble(obj, "bidPrice");
                    t.LowestAsk      = ToDouble(obj, "askPrice");
                    t.Timestamp      = Convert.ToDateTime(obj.Value <string>("timestamp"));
                    t.Change         = ToDouble(obj, "lastChangePcnt");
                    t.Volume         = ToDouble(obj, "volume24h");
                    t.Fee            = ToDouble(obj, "takerFee") * 100;
                    Tickers.Add(t);
                    index++;
                }
            }
            catch (Exception) {
                return(false);
            }
            IsInitialized = true;
            return(true);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Fetch price change statistics
        /// </summary>
        /// <param name="args">Add additional attributes for each exchange</param>
        /// <returns></returns>
        public override async ValueTask <Tickers> FetchTickers(Dictionary <string, object> args = null)
        {
            var _result = new Tickers();

            var _markets = await this.LoadMarkets();

            if (_markets.success == true)
            {
                publicClient.ExchangeInfo.ApiCallWait(TradeType.Public);

                var _params = publicClient.MergeParamsAndArgs(args);

                var _json_value = await publicClient.CallApiGet1Async("/1/tickers", _params);

#if RAWJSON
                _result.rawJson = _json_value.Content;
#endif
                var _json_result = publicClient.GetResponseMessage(_json_value.Response);
                if (_json_result.success == true)
                {
                    var _tickers = publicClient.DeserializeObject <Dictionary <string, GTickerItem> >(_json_value.Content);
                    {
                        foreach (var _t in _tickers)
                        {
                            var _ticker = _t.Value;

                            _ticker.symbol = _t.Key;
                            // openPrice 제공안함
                            _ticker.average   = (_ticker.lastPrice + _ticker.openPrice) / 2;
                            _ticker.timestamp = CUnixTime.NowMilli;
                            if (_ticker.baseVolume != 0)
                            {
                                _ticker.vwap = _ticker.quoteVolume / _ticker.baseVolume;
                            }

                            _result.result.Add(_ticker);
                        }
                    }
                }

                _result.SetResult(_json_result);
            }
            else
            {
                _result.SetResult(_markets);
            }

            return(_result);
        }
Exemplo n.º 28
0
        public override bool GetTickersInfo()
        {
            Context cc = GetContext(DefaultAccount);

            Tickers.Clear();
            cc.MarketStocksAsync().ContinueWith(t => {
                MarketInstrumentList list = t.Result;
                foreach (MarketInstrument i in list.Instruments)
                {
                    Tickers.Add(new Tinkoff.TinknoffInvestTicker(this, i));
                }
                IsInitialized = true;
            });
            return(true);
        }
Exemplo n.º 29
0
        public async Task <ITickers> GetTickers(string currencies, decimal exchangeRate)
        {
            ITickers tickers = new Tickers(Common.StockExchange.Types.StockExchange.Cex);

            try
            {
                string uri = $"{BaseUri}/tickers/{currencies}";

                HttpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

                if (HttpWebRequest != null)
                {
                    HttpWebRequest.Method = "GET";
                    HttpWebRequest.Accept = "application/json";

                    using (HttpWebResponse = await HttpWebRequest.GetResponseAsync() as HttpWebResponse)
                    {
                        if (HttpWebResponse != null)
                        {
                            StreamReader = new StreamReader(HttpWebResponse.GetResponseStream() ?? throw new InvalidOperationException());
                        }

                        JObject resultsJson = JsonConvert.DeserializeObject <JObject>(StreamReader.ReadToEnd());

                        foreach (JToken ticker in resultsJson["data"])
                        {
                            string pair = ticker["pair"].ToString().Replace(":", "/");

                            tickers.PairTickers.Add(new PairTickerVolumeHighLowPrice(
                                                        pair,
                                                        Convert.ToDecimal(ticker["last"]),
                                                        Convert.ToDecimal(ticker["bid"]),
                                                        Convert.ToDecimal(ticker["ask"]),
                                                        Convert.ToDecimal(ticker["volume"]),
                                                        Convert.ToDecimal(ticker["high"]),
                                                        Convert.ToDecimal(ticker["low"]))
                                                    );
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(tickers);
        }
Exemplo n.º 30
0
        public async Task <ITickers> GetTickers(string currencies, decimal exchangeRate)
        {
            string uri = $"{BaseUri}/tickers?symbols={currencies}";

            ITickers tickers = new Tickers(Common.StockExchange.Types.StockExchange.Bitfinex);

            try
            {
                HttpWebRequest = WebRequest.Create(uri) as HttpWebRequest;

                if (HttpWebRequest != null)
                {
                    HttpWebRequest.Method = "GET";
                    HttpWebRequest.Accept = "application/json";

                    using (HttpWebResponse = await HttpWebRequest.GetResponseAsync() as HttpWebResponse)
                    {
                        if (HttpWebResponse != null)
                        {
                            StreamReader = new StreamReader(HttpWebResponse.GetResponseStream() ?? throw new InvalidOperationException());
                        }

                        JArray resultsJson = JsonConvert.DeserializeObject <JArray>(StreamReader.ReadToEnd());

                        foreach (JToken ticker in resultsJson)
                        {
                            string pair = ticker[0].ToString().Remove(0, 1).Insert(3, "/");
                            tickers.PairTickers.Add(new PairTickerVolumeHighLowPrice(
                                                        pair,
                                                        Convert.ToDecimal(ticker[7]),
                                                        Convert.ToDecimal(ticker[1]),
                                                        Convert.ToDecimal(ticker[3]),
                                                        Convert.ToDecimal(ticker[8]),
                                                        Convert.ToDecimal(ticker[9]),
                                                        Convert.ToDecimal(ticker[10]))
                                                    );
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }

            return(tickers);
        }