コード例 #1
0
 public async Task GetExchangeDataAsync()
 {
     foreach (var resourceUri in Dates.Select(ResourceApi.GetUri))
     {
         ExchangeRates.Add(await XmlConverter.ParseObjAsync <ExchangeRate>(resourceUri));
     }
 }
コード例 #2
0
        private void NewRate(LatestPriceResultMessage result)
        {
            UiDispatcher.Invoke(() =>
            {
                var e = ExchangeRates.FirstOrDefault(x => x.IsSimilarRequest(result));
                if (e != null)
                {
                    ExchangeRates.Remove(e);
                }
                ExchangeRates.Add(result);

                var exrs = ExchangeRates.OrderBy(x => x.Pair.ToString()).ToList();
                ExchangeRates.Clear();

                foreach (var er in exrs)
                {
                    ExchangeRates.Add(er);
                }

                if (AssetLeft.IsNone() || AssetRight.IsNone() || ConvertLeft == 0)
                {
                    return;
                }

                var ap = new AssetPair(AssetLeft, AssetRight);
                if (!result.Pair.Equals(ap))
                {
                    return;
                }

                _isConverted    = result.IsConverted;
                ResultViewModel = new ExchangeRateResultViewModel(this, result);
                LoadingInfo     = "";
            });
        }
コード例 #3
0
        public async Task <ExchangeRates> GetRatesAsync()
        {
            var response = await _Client.GetAsync($"https://api.quadrigacx.com/v2/ticker?book=all");

            response.EnsureSuccessStatusCode();
            var rates = JObject.Parse(await response.Content.ReadAsStringAsync());

            var exchangeRates = new ExchangeRates();

            foreach (var prop in rates.Properties())
            {
                var rate = new ExchangeRate();
                if (!Rating.CurrencyPair.TryParse(prop.Name, out var pair))
                {
                    continue;
                }
                rate.CurrencyPair = pair;
                rate.Exchange     = QuadrigacxName;
                if (!TryToBidAsk((JObject)prop.Value, out var v))
                {
                    continue;
                }
                rate.BidAsk = v;
                exchangeRates.Add(rate);
            }
            return(exchangeRates);
        }
コード例 #4
0
        public async Task <ExchangeRates> GetRatesAsync()
        {
            string url = Exchange == CoinAverageName ? $"https://apiv2.bitcoinaverage.com/indices/{Market}/ticker/short"
                                         : $"https://apiv2.bitcoinaverage.com/exchanges/{Exchange}";

            var request = new HttpRequestMessage(HttpMethod.Get, url);
            var auth    = Authenticator;

            if (auth != null)
            {
                await auth.AddHeader(request);
            }
            var resp = await HttpClient.SendAsync(request);

            using (resp)
            {
                if ((int)resp.StatusCode == 401)
                {
                    throw new CoinAverageException("Unauthorized access to the API");
                }
                if ((int)resp.StatusCode == 429)
                {
                    throw new CoinAverageException("Exceed API limits");
                }
                if ((int)resp.StatusCode == 403)
                {
                    throw new CoinAverageException("Unauthorized access to the API, premium plan needed");
                }
                resp.EnsureSuccessStatusCode();
                var rates = JObject.Parse(await resp.Content.ReadAsStringAsync());
                if (Exchange != CoinAverageName)
                {
                    rates = (JObject)rates["symbols"];
                }

                var exchangeRates = new ExchangeRates();
                foreach (var prop in rates.Properties())
                {
                    ExchangeRate exchangeRate = new ExchangeRate();
                    exchangeRate.Exchange = Exchange;
                    if (!TryToBidAsk(prop, out var value))
                    {
                        continue;
                    }
                    exchangeRate.BidAsk = value;
                    if (CurrencyPair.TryParse(prop.Name, out var pair))
                    {
                        exchangeRate.CurrencyPair = pair;
                        exchangeRates.Add(exchangeRate);
                    }
                }
                return(exchangeRates);
            }
        }
コード例 #5
0
        public async Task <ExchangeRates> GetRatesAsync(CancellationToken cancellationToken)
        {
            var result  = new ExchangeRates();
            var symbols = await GetSymbolsAsync(cancellationToken);

            var    normalizedPairsList = symbols.Where(s => !notFoundSymbols.ContainsKey(s)).Select(s => _Helper.NormalizeMarketSymbol(s)).ToList();
            var    csvPairsList        = string.Join(",", normalizedPairsList);
            JToken apiTickers          = await MakeJsonRequestAsync <JToken>("/0/public/Ticker", null, new Dictionary <string, object> {
                { "pair", csvPairsList }
            }, cancellationToken : cancellationToken);

            var tickers = new List <KeyValuePair <string, ExchangeTicker> >();

            foreach (string symbol in symbols)
            {
                var ticker = ConvertToExchangeTicker(symbol, apiTickers[symbol]);
                if (ticker != null)
                {
                    try
                    {
                        string global  = null;
                        var    mapped1 = _TickerMapping.Where(t => symbol.StartsWith(t.Key, StringComparison.OrdinalIgnoreCase))
                                         .Select(t => new { KrakenTicker = t.Key, PayTicker = t.Value }).SingleOrDefault();
                        if (mapped1 != null)
                        {
                            var p2 = symbol.Substring(mapped1.KrakenTicker.Length);
                            if (_TickerMapping.TryGetValue(p2, out var mapped2))
                            {
                                p2 = mapped2;
                            }
                            global = $"{p2}_{mapped1.PayTicker}";
                        }
                        else
                        {
                            global = await _Helper.ExchangeMarketSymbolToGlobalMarketSymbolAsync(symbol);
                        }
                        if (CurrencyPair.TryParse(global, out var pair))
                        {
                            result.Add(new ExchangeRate("kraken", pair.Inverse(), new BidAsk(ticker.Bid, ticker.Ask)));
                        }
                        else
                        {
                            notFoundSymbols.TryAdd(symbol, symbol);
                        }
                    }
                    catch (ArgumentException)
                    {
                        notFoundSymbols.TryAdd(symbol, symbol);
                    }
                }
            }
            return(result);
        }
コード例 #6
0
        public ExchangeRates GetExchangeRates(ReqEmpty req)
        {
            ExchangeRates rates = HttpContext.Current.Application["exchangeRates"] as ExchangeRates;

            if (rates == null || rates.Date < Provider.Database.Now.Date)
            {
                rates = new ExchangeRates {
                    Date = Provider.Database.Now.Date
                };

                List <ExchangeRate> list =
                    Provider.Database.ReadList <ExchangeRate>("select * from ExchangeRate where InsertDate>={0}",
                                                              Provider.Database.Now.Date);
                if (list == null || list.Count == 0)
                {
                    XmlTextReader rdr = new XmlTextReader("http://www.tcmb.gov.tr/kurlar/today.xml");
                    DataSet       ds  = new DataSet();
                    ds.ReadXml(rdr);

                    foreach (DataRow dr in ds.Tables["Currency"].Rows)
                    {
                        try
                        {
                            ExchangeRate rate = new ExchangeRate
                            {
                                Currency =
                                    (dr["CurrencyCode"].ToString() == "USD")
                                            ? "$"
                                            : (dr["CurrencyCode"].ToString() == "EUR" ? "€" : dr["CurrencyCode"].ToString()),
                                PriceTL =
                                    Convert.ToInt32(
                                        decimal.Parse(dr["ForexSelling"].ToString(), CultureInfo.InvariantCulture) *
                                        1000000 / int.Parse(dr["Unit"].ToString()))
                            };
                            rate.Save();

                            rates.Add(rate.ToEntityInfo <ExchangeRateInfo>());
                        }
                        catch { }
                    }

                    HttpContext.Current.Application["exchangeRates"] = rates;
                }
                else
                {
                    rates.Date = Provider.Database.Now.Date;
                    rates.AddRange(list.ToEntityInfo <ExchangeRateInfo>());
                    HttpContext.Current.Application["exchangeRates"] = rates;
                }
            }

            return(rates);
        }
コード例 #7
0
        public async Task MergeRatesAsync(ExchangeRates toMerge, CancellationToken cancellationToken)
        {
            using (await fLock.LockForWritingAsync(cancellationToken))
            {
                var newRates = new ExchangeRates(fRates);
                foreach (var rate in toMerge)
                {
                    newRates.Add(rate.Key, rate.Value);
                }

                fRates = newRates;
            }
        }
コード例 #8
0
        public async Task <ExchangeRates> GetRatesAsync()
        {
            var result  = new ExchangeRates();
            var symbols = await GetSymbolsAsync();

            var    normalizedPairsList = symbols.Where(s => !notFoundSymbols.ContainsKey(s)).Select(s => _Helper.NormalizeSymbol(s)).ToList();
            var    csvPairsList        = string.Join(",", normalizedPairsList);
            JToken apiTickers          = await MakeJsonRequestAsync <JToken>("/0/public/Ticker", null, new Dictionary <string, object> {
                { "pair", csvPairsList }
            });

            var tickers = new List <KeyValuePair <string, ExchangeTicker> >();

            foreach (string symbol in symbols)
            {
                var ticker = ConvertToExchangeTicker(symbol, apiTickers[symbol]);
                if (ticker != null)
                {
                    try
                    {
                        string global = null;
                        if (symbol.StartsWith("DASH", StringComparison.OrdinalIgnoreCase))
                        {
                            var p2 = symbol.Substring(4);
                            p2     = p2 == "XBT" ? "BTC" : p2;
                            global = $"{p2}_{symbol.Substring(0, 4)}";
                        }
                        else
                        {
                            global = _Helper.ExchangeSymbolToGlobalSymbol(symbol);
                        }
                        if (CurrencyPair.TryParse(global, out var pair))
                        {
                            result.Add(new ExchangeRate("kraken", pair.Inverse(), new BidAsk(ticker.Bid, ticker.Ask)));
                        }
                        else
                        {
                            notFoundSymbols.TryAdd(symbol, symbol);
                        }
                    }
                    catch (ArgumentException)
                    {
                        notFoundSymbols.TryAdd(symbol, symbol);
                    }
                }
            }
            return(result);
        }
コード例 #9
0
 public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
 {
     if (
         (!IsInvocation || IsArgumentList) &&
         CurrencyPair.TryParse(node.Identifier.ValueText, out var currentPair))
     {
         var replacedPair = new CurrencyPair(left: currentPair.Left == "X" ? pair.Left : currentPair.Left,
                                             right: currentPair.Right == "X" ? pair.Right : currentPair.Right);
         if (IsInvocation) // eg. replace bittrex(BTC_X) to bittrex(BTC_USD)
         {
             ExchangeRates.Add(new ExchangeRate()
             {
                 CurrencyPair = replacedPair, Exchange = _ExchangeName
             });
             return(SyntaxFactory.IdentifierName(replacedPair.ToString()));
         }
         else // eg. replace BTC_X to BTC_USD, then replace by the expression for BTC_USD
         {
             var bestCandidate = parent.FindBestCandidate(replacedPair);
             if (nested > MaxNestedCount)
             {
                 Errors.Add(RateRulesErrors.TooMuchNestedCalls);
                 return(RateRules.CreateExpression($"ERR_TOO_MUCH_NESTED_CALLS({replacedPair})"));
             }
             var innerFlatten = CreateNewContext(replacedPair);
             var replaced     = innerFlatten.Visit(bestCandidate);
             if (replaced is ExpressionSyntax expression)
             {
                 var hasBinaryOps = new HasBinaryOperations();
                 hasBinaryOps.Visit(expression);
                 if (hasBinaryOps.Result)
                 {
                     replaced = SyntaxFactory.ParenthesizedExpression(expression);
                 }
             }
             if (Errors.Contains(RateRulesErrors.TooMuchNestedCalls))
             {
                 return(RateRules.CreateExpression($"ERR_TOO_MUCH_NESTED_CALLS({replacedPair})"));
             }
             return(replaced);
         }
     }
     return(base.VisitIdentifierName(node));
 }
コード例 #10
0
        void Populate()
        {
            var json = js.Invoke <string>("localStorage.getItem", "fxData");

            if (json != null)
            {
                var rawData = JsonSerializer.Deserialize <RawFxData>(json);
                LastUpdatedDate = rawData.Date;

                ExchangeRates.Clear();
                ExchangeRatesLookup.Clear();
                foreach (var currency in supportedCurrencies)
                {
                    if (rawData.Rates.TryGetValue(currency.Code, out var valueInEur))
                    {
                        var exchangeRate = new ExchangeRate(currency, valueInEur);
                        ExchangeRates.Add(exchangeRate);
                        ExchangeRatesLookup.Add(currency.Code, exchangeRate);
                    }
                }
            }
        }