Ejemplo n.º 1
0
        public static string ToString(decimal amount, FiatCurrency from, FiatCurrency to)
        {
            var result = Convert(amount, from, to);
            var symbol = Map[to];

            return($"{symbol}{result:N}");
        }
Ejemplo n.º 2
0
        public async Task <GlobalData> GlobalAsync(FiatCurrency convert = FiatCurrency.USD)
        {
            GlobalData data = new GlobalData();

            try
            {
                HttpClient _httpClient = new HttpClient {
                    BaseAddress = new Uri(Endpoints.CoinMarketCapApiUrl)
                };
                var url = QueryStringService.AppendQueryString(Endpoints.GlobalData, new Dictionary <string, string>
                {
                    { "convert", convert.ToString() }
                });
                var response = await _httpClient.GetAsync(url);

                data = await JsonParserService.ParseResponse <GlobalData>(response);

                if (data == null)
                {
                    data = new GlobalData
                    {
                        Data     = null,
                        Metadata = new GlobalMetadata {
                            Error = int.MinValue
                        },
                        Success = false
                    };
                }
                data.Success = data.Metadata.Error == null;
            }
            catch { }

            return(data);
        }
Ejemplo n.º 3
0
        private static FiatCurrency GetFiatCurrency(string candidateName)
        {
            FiatCurrency retval = FiatCurrency.None;

            if (items == null)
            {
                items = LoadNames();
            }

            if (rx == null)
            {
                rx = new Regex(@"(?<Name>.+)_(?<Suffix>\w{3})$");
            }

            var res = rx.Match(candidateName);

            if (res.Success)
            {
                var currencyName = res.Groups["Suffix"].Value;
                var isValid      = items.ContainsKey(currencyName);
                return(!isValid ? FiatCurrency.None : items[currencyName]);
            }

            return(retval);
        }
Ejemplo n.º 4
0
        public long?GetPriceInFiat(Common.CurrencyPrice currency, FiatCurrency fiatCurrency)
        {
            _ratesLock.EnterReadLock();
            try {
                long?cents = null;
                if (_rates.ContainsKey(currency))
                {
                    switch (fiatCurrency)
                    {
                    case FiatCurrency.Usd:
                        cents = _rates[currency].Usd;
                        break;

                    case FiatCurrency.Eur:
                        cents = _rates[currency].Eur;
                        break;

                    default:
                        throw new NotImplementedException("fiat currency not implemented");
                    }
                }
                return(cents);
            } finally {
                _ratesLock.ExitReadLock();
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Get the latest market quote for 1 or more cryptocurrencies. Use the "convert" option to return market values in multiple fiat and cryptocurrency conversions in the same call.
 /// <para>At least one "id" or "symbol" is required.</para>
 /// </summary>
 /// <param name="id">
 /// One or more comma-separated CoinMarketCap cryptocurrency IDs. Example: "1,2"
 /// </param>
 /// <param name="symbol">
 /// Alternatively pass one or more comma-separated cryptocurrency symbols. Example: "BTC,ETH".
 /// </param>
 /// <returns></returns>
 public Pro.Model.Cryptocurrency.QuotesData CryptocurrencyQuotesLatest(
     string id            = null,
     string symbol        = null,
     FiatCurrency convert = FiatCurrency.USD
     )
 {
     return(this.CryptocurrencyQuotesLatestAsync(id, symbol, convert).Result);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Get orderbook for specify markets.
        /// </summary>
        /// <param name="crypto"></param>
        /// <param name="fiat"></param>
        /// <returns></returns>
        public OrderBookModel OrderBook(CryptoCurrency crypto, FiatCurrency fiat)
        {
            IRestRequest   req       = new RestRequest($"/stats/orderbook_{crypto.ToString().ToLower()}{fiat.ToString().ToLower()}.json");
            string         response  = client.Execute(req).Content;
            OrderBookModel orderbook = JsonConvert.DeserializeObject <OrderBookModel>(response);

            return(orderbook);
        }
Ejemplo n.º 7
0
        public static async Task <BuyGoldFiatResult> BuyGoldFiatRev(
            IServiceProvider services,
            FiatCurrency fiatCurrency,
            BigInteger requiredGoldAmount,
            long?knownGoldRateCents = null,
            double discount         = 0d
            )
        {
            if (requiredGoldAmount <= 0)
            {
                return(new BuyGoldFiatResult());
            }

            var pricer = services.GetRequiredService <IPriceSource>();

            var goldRate = knownGoldRateCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldRate == null || goldRate <= 0)
            {
                return(new BuyGoldFiatResult()
                {
                    Status = BuyGoldStatus.TradingDisallowed,
                });
            }

            // round up
            var exchangeAmount = (requiredGoldAmount * new BigInteger(goldRate.Value) + BigInteger.Pow(10, TokensPrecision.Sumus) - 1) / BigInteger.Pow(10, TokensPrecision.Sumus);

            // discount
            var exchangeAmountMinusDiscount = GetDiscountRevBody(discount, exchangeAmount);

            if (exchangeAmountMinusDiscount < 1)
            {
                exchangeAmountMinusDiscount = 1;
            }

            if (exchangeAmountMinusDiscount > long.MaxValue)
            {
                return(new BuyGoldFiatResult()
                {
                    Status = BuyGoldStatus.ValueOverflow,
                });
            }

            return(new BuyGoldFiatResult()
            {
                Allowed = true,
                Status = BuyGoldStatus.Success,
                ExchangeCurrency = fiatCurrency,
                Discount = discount,
                CentsPerGoldRate = goldRate.Value,
                ResultCentsAmount = (long)exchangeAmountMinusDiscount,
                ResultGoldAmount = requiredGoldAmount,
            });
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Get a paginated list of all cryptocurrencies with latest market data.
 /// <para>You can configure this call to sort by market cap or another market ranking field. Use the "convert" option to return market values in multiple fiat and cryptocurrency conversions in the same call.</para>
 /// </summary>
 /// <param name="start">>=1, Default=1. Optionally offset the start (1-based index) of the paginated list of items to return.</param>
 /// <param name="limit">[1 ... 5000] Default=100. Optionally specify the number of results to return. Use this parameter and the "start" parameter to determine your own pagination size.</param>
 /// <param name="convert">Optionally calculate market quotes in up to 32 currencies at once by passing a comma-separated list of cryptocurrency or fiat currency symbols. Each additional convert option beyond the first requires an additional call credit. A list of supported fiat options can be found here. Each conversion is returned in its own "quote" object.</param>
 /// <param name="sort">What field to sort the list of cryptocurrencies by.</param>
 /// <param name="sort_dir">The direction in which to order cryptocurrencies against the specified sort.</param>
 /// <param name="cryptocurrency_type">The type of cryptocurrency to include.</param>
 /// <returns></returns>
 public Pro.Model.Cryptocurrency.ListingsData CryptocurrencyListingsLatest(
     int?start              = 1,
     int?limit              = 100,
     FiatCurrency convert   = FiatCurrency.USD,
     SortBy sort            = SortBy.market_cap,
     SortDirection sort_dir = SortDirection.desc,
     CryptocurrencyType cryptocurrency_type = CryptocurrencyType.all
     )
 {
     return(this.CryptocurrencyListingsLatestAsync(start, limit, convert, sort, sort_dir, cryptocurrency_type).Result);
 }
Ejemplo n.º 9
0
        public static async Task <BuyGoldFiatResult> BuyGoldFiat(
            IServiceProvider services,
            FiatCurrency fiatCurrency,
            long fiatAmountCents,
            long?knownGoldPriceCents = null,
            double discount          = 0d
            )
        {
            if (fiatAmountCents <= 0)
            {
                return(new BuyGoldFiatResult());
            }

            var pricer = services.GetRequiredService <IPriceSource>();

            var goldPrice = knownGoldPriceCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldPrice == null || goldPrice <= 0)
            {
                return(new BuyGoldFiatResult()
                {
                    Status = BuyGoldStatus.TradingDisallowed,
                });
            }

            // discount
            var fiatAmountCentsPlusDiscount = new BigInteger(fiatAmountCents) + GetDiscount(discount, new BigInteger(fiatAmountCents));

            if (fiatAmountCentsPlusDiscount > long.MaxValue)
            {
                return(new BuyGoldFiatResult()
                {
                    Status = BuyGoldStatus.ValueOverflow,
                });
            }

            // round down
            var goldAmount = fiatAmountCentsPlusDiscount * BigInteger.Pow(10, TokensPrecision.Sumus) / new BigInteger(goldPrice.Value);

            return(new BuyGoldFiatResult()
            {
                Allowed = true,
                Status = BuyGoldStatus.Success,
                ExchangeCurrency = fiatCurrency,
                Discount = discount,
                CentsPerGoldRate = goldPrice.Value,
                ResultCentsAmount = (long)fiatAmountCentsPlusDiscount,
                ResultGoldAmount = goldAmount,
            });
        }
Ejemplo n.º 10
0
        public async Task <Pro.Model.Cryptocurrency.ListingsData> CryptocurrencyListingsHistoricalAsync(
            DateTime timestamp,
            int?start              = 1,
            int?limit              = 100,
            FiatCurrency convert   = FiatCurrency.USD,
            SortBy sort            = SortBy.market_cap,
            SortDirection sort_dir = SortDirection.desc,
            CryptocurrencyType cryptocurrency_type = CryptocurrencyType.all
            )
        {
            HttpClient _httpClient = new HttpClient {
                BaseAddress = new Uri(Pro.Config.Cryptocurrency.CoinMarketCapProApiUrl)
            };

            _httpClient.DefaultRequestHeaders.Add("X-CMC_PRO_API_KEY", this.ProApiKey);

            var url = QueryStringService.AppendQueryString(Pro.Config.Cryptocurrency.CryptocurrencyListingsHistorical, new Dictionary <string, string>
            {
                { "timestamp", timestamp.ToUnixTimeSeconds().ToString() },
                { "start", start.HasValue && start.Value >= 1 ? start.Value.ToString() : null },
                { "limit", limit.HasValue && limit.Value >= 1 ? limit.Value.ToString() : null },
                { "convert", convert.ToString() },
                { "sort", sort.ToString() },
                { "sort_dir", sort_dir.ToString() },
                { "cryptocurrency_type", cryptocurrency_type.ToString() },
            });
            var response = await _httpClient.GetAsync(url);

            Pro.Model.Cryptocurrency.ListingsData data = await JsonParserService.ParseResponse <Pro.Model.Cryptocurrency.ListingsData>(response);

            if (data == null)
            {
                data = new Pro.Model.Cryptocurrency.ListingsData
                {
                    Data   = null,
                    Status = new Status {
                        ErrorCode = int.MinValue
                    },
                    Success = false
                };
            }
            data.Success = data.Status.ErrorCode == 0;

            // Add to Status List
            this.statusList.Add(data.Status);

            return(data);
        }
Ejemplo n.º 11
0
        private static void FillUsdPrices(List <PriceSourceItem> allPriceSourceItems)
        {
            List <FiatCurrency> fiatCurrencies = FiatCurrencyService.Instance.GetAll();

            foreach (var priceSourceItem in allPriceSourceItems)
            {
                FiatCurrency fiatCurrency = fiatCurrencies.FirstOrDefault(fc => fc.Code.ToLower() == priceSourceItem.PriceCurrency.ToLower());
                if (fiatCurrency == null)
                {
                    continue;
                }

                double priceUsd = priceSourceItem.Price / fiatCurrency.ExchangeRateUSD;
                priceSourceItem.PriceUSD = Math.Round(priceUsd, 2);
            }
        }
Ejemplo n.º 12
0
        public static async Task <SellGoldFiatResult> SellGoldFiat(
            IServiceProvider services,
            FiatCurrency fiatCurrency,
            BigInteger goldAmount,
            long?knownGoldRateCents = null
            )
        {
            if (goldAmount <= 0)
            {
                return(new SellGoldFiatResult());
            }

            var pricer = services.GetRequiredService <IPriceSource>();

            var goldRate = knownGoldRateCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldRate == null || goldRate <= 0)
            {
                return(new SellGoldFiatResult()
                {
                    Status = SellGoldStatus.TradingDisallowed,
                });
            }

            var exchangeAmount = goldAmount * new BigInteger(goldRate.Value) / BigInteger.Pow(10, TokensPrecision.Sumus);

            if (exchangeAmount > long.MaxValue)
            {
                return(new SellGoldFiatResult()
                {
                    Status = SellGoldStatus.ValueOverflow,
                });
            }

            return(new SellGoldFiatResult()
            {
                Allowed = true,
                Status = SellGoldStatus.Success,
                CentsPerGoldRate = goldRate.Value,
                ExchangeCurrency = fiatCurrency,
                ResultGoldAmount = goldAmount,
                ResultCentsAmount = (long)exchangeAmount,
            });
        }
Ejemplo n.º 13
0
        public async Task <Pro.Model.Cryptocurrency.QuotesData> CryptocurrencyQuotesLatestAsync(
            string id            = null,
            string symbol        = null,
            FiatCurrency convert = FiatCurrency.USD
            )
        {
            HttpClient _httpClient = new HttpClient {
                BaseAddress = new Uri(Pro.Config.Cryptocurrency.CoinMarketCapProApiUrl)
            };

            _httpClient.DefaultRequestHeaders.Add("X-CMC_PRO_API_KEY", this.ProApiKey);

            var url = QueryStringService.AppendQueryString(Pro.Config.Cryptocurrency.CryptocurrencyQuotesLatest, new Dictionary <string, string>
            {
                { "id", id },
                { "symbol", symbol },
                { "convert", convert.ToString() },
            });
            var response = await _httpClient.GetAsync(url);

            Pro.Model.Cryptocurrency.QuotesData data = await JsonParserService.ParseResponse <Pro.Model.Cryptocurrency.QuotesData>(response);

            if (data == null)
            {
                data = new Pro.Model.Cryptocurrency.QuotesData
                {
                    Data   = null,
                    Status = new Status {
                        ErrorCode = int.MinValue
                    },
                    Success = false
                };
            }
            data.Success = data.Status.ErrorCode == 0;

            // Add to Status List
            this.statusList.Add(data.Status);

            return(data);
        }
Ejemplo n.º 14
0
        public static async Task <SellGoldFiatResult> SellGoldFiatRev(
            IServiceProvider services,
            FiatCurrency fiatCurrency,
            long requiredFiatAmountWithFeeCents,
            long?knownGoldRateCents = null
            )
        {
            if (requiredFiatAmountWithFeeCents <= 0)
            {
                return(new SellGoldFiatResult());
            }

            var pricer = services.GetRequiredService <IPriceSource>();

            var goldRate = knownGoldRateCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldRate == null || goldRate <= 0)
            {
                return(new SellGoldFiatResult()
                {
                    Status = SellGoldStatus.TradingDisallowed,
                });
            }

            // round up
            var goldAmountToSell = (requiredFiatAmountWithFeeCents * BigInteger.Pow(10, TokensPrecision.Sumus) + new BigInteger(goldRate.Value - 1)) / new BigInteger(goldRate.Value);

            return(new SellGoldFiatResult()
            {
                Allowed = true,
                Status = SellGoldStatus.Success,
                ExchangeCurrency = fiatCurrency,
                CentsPerGoldRate = goldRate.Value,
                ResultGoldAmount = goldAmountToSell,
                ResultCentsAmount = requiredFiatAmountWithFeeCents,
            });
        }
Ejemplo n.º 15
0
 public static decimal Convert(decimal amount,
                               FiatCurrency from,
                               FiatCurrency to) =>
 amount * UsdTo[to] / UsdTo[from];
Ejemplo n.º 16
0
 /// <summary>Gets the ticker.</summary>
 /// <param name="limit">The limit.</param>
 /// <param name="convertTo">The convert to.</param>
 /// <returns>A list of Tickers with market data for an specific cryto currency</returns>
 public IList <ITicker> GetTicker(int?limit, FiatCurrency convertTo)
 {
     return(this.GetTicker(string.Empty, limit, convertTo));
 }
Ejemplo n.º 17
0
 public static IEnumerable <string> ToTables(
     this IEnumerable <CryptoExchangeBase> exchanges,
     FiatCurrency fiat = FiatCurrency.USD
     ) =>
 exchanges.Select(exchange => $"{exchange.Name}\n{exchange.ToTable ( fiat )}");
Ejemplo n.º 18
0
        private Task <List <ITicker> > GetTickerCore(string cryptoCurrencyId, int?limit, FiatCurrency convertTo)
        {
            const string DefaultResource = "v1/ticker";

            string resource = string.IsNullOrWhiteSpace(cryptoCurrencyId) ? DefaultResource : string.Format("{0}/{1}", DefaultResource, cryptoCurrencyId);

            RestRequest request = new RestRequest(DefaultResource);

            if (limit.HasValue)
            {
                var limitResults = new Parameter();
                limitResults.Type  = ParameterType.QueryString;
                limitResults.Value = "limit";
                limitResults.Value = (int)limit;

                request.AddParameter(limitResults);
            }

            if (convertTo != FiatCurrency.None)
            {
                var convertToCurrency = new Parameter();
                convertToCurrency.Type  = ParameterType.QueryString;
                convertToCurrency.Value = Enum.GetName(typeof(FiatCurrency), convertTo);
                convertToCurrency.Name  = "convert";
            }

            var response = this.HttpClient.Execute <List <Ticker> >(request);
            var retval   = response.Data.ConvertAll <ITicker>(x => x);

            return(Task.FromResult(retval));
        }
Ejemplo n.º 19
0
 /// <summary>Gets the ticker.</summary>
 /// <param name="convertTo">The convert to.</param>
 /// <returns>A list of Tickers with market data for an specific cryto currency</returns>
 public IList <ITicker> GetTicker(FiatCurrency convertTo)
 {
     return(this.GetTicker(null, convertTo));
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Get a coin price in thai baht per day if we mining it.
        /// </summary>
        /// <param name="coinSymbol"></param>
        /// <param name="poolName"></param>
        /// <param name="exchangeName"></param>
        /// <returns></returns>
        public double GetTotalFiatMoneyMiningPerday(string coinSymbol, PoolName poolName, ExchangeName exchangeName, FiatCurrency fiat)
        {
            double totalBtcPerDay = GetTotalBtcMiningPerday(coinSymbol, poolName, exchangeName);
            double fiatPerBTC     = (fiat == FiatCurrency.THB) ? _thaiBahtPerBTC : _usdPerBTC;

            return(totalBtcPerDay * fiatPerBTC);
        }
Ejemplo n.º 21
0
        /// <summary>Gets the ticker.</summary>
        /// <param name="cryptoCurrencyId">The crypto currency identifier.</param>
        /// <param name="limit">The limit.</param>
        /// <param name="convertTo">The convert to.</param>
        /// <returns>A list of Tickers with market data for an specific cryto currency</returns>
        public IList <ITicker> GetTicker(string cryptoCurrencyId, int?limit, FiatCurrency convertTo)
        {
            var res = this.gate.Perform(() => this.GetTickerCore(cryptoCurrencyId, limit, convertTo));

            return(res.Result);
        }
Ejemplo n.º 22
0
 public TickerByIdData TickerById(int id, FiatCurrency convert = FiatCurrency.USD)
 {
     return(this.TickerByIdAsync(id, convert).Result);
 }
Ejemplo n.º 23
0
 public GlobalData Global(FiatCurrency convert = FiatCurrency.USD)
 {
     return(this.GlobalAsync(convert).Result);
 }
Ejemplo n.º 24
0
 public TickersData Tickers(int?start, int?limit, SortBy sort = SortBy.id, FiatCurrency convert = FiatCurrency.USD)
 {
     return(this.TickersAsync(start, limit, sort, convert).Result);
 }
Ejemplo n.º 25
0
        public async Task <TickersData> TickersAsync(int?start, int?limit, SortBy sort = SortBy.id, FiatCurrency convert = FiatCurrency.USD)
        {
            TickersData data = new TickersData();

            try
            {
                HttpClient _httpClient = new HttpClient {
                    BaseAddress = new Uri(Endpoints.CoinMarketCapApiUrl)
                };
                var url = QueryStringService.AppendQueryString(Endpoints.Ticker, new Dictionary <string, string>
                {
                    { "start", start >= 1 ? start.ToString() : null },
                    { "limit", limit >= 1 ? limit.ToString() : null },
                    { "sort", sort.ToString() },
                    { "convert", convert.ToString() }
                });
                var response = await _httpClient.GetAsync(url);

                data = await JsonParserService.ParseResponse <TickersData>(response);

                if (data == null)
                {
                    data = new TickersData
                    {
                        Data     = null,
                        Metadata = new TickerMetadata {
                            Error = int.MinValue
                        },
                        Success = false
                    };
                }
                data.Success = data.Metadata.Error == null;
            }
            catch { }

            return(data);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Get algorithm price in thai baht per day if we mining in auto btc pool.
        /// </summary>
        /// <param name="algorithmName">algorithm name ex. lyra2z</param>
        /// <param name="poolName">PoolName enum</param>
        /// <returns></returns>
        public double GetTotalFiatMoneyMiningPerday(string algorithmName, PoolName poolName, bool estimateCurrent, FiatCurrency fiat)
        {
            double totalBtcPerDay = GetTotalBtcMiningPerday(algorithmName, poolName, estimateCurrent);
            double fiatPerBTC     = (fiat == FiatCurrency.THB) ? _thaiBahtPerBTC : _usdPerBTC;

            return(totalBtcPerDay * fiatPerBTC);
        }
Ejemplo n.º 27
0
        private async Task <CoinGeckoPriceResult> GetCoinGeckoPrice(CancellationToken cancellationToken, FiatCurrency currency)
        {
            var client   = new RestClient("https://api.coingecko.com/api/v3/simple/");
            var request  = new RestRequest($"price?ids=x42-protocol&vs_currencies={currency}", Method.GET);
            var response = await client.ExecuteAsync <CoinGeckoPriceResult>(request, cancellationToken);

            if (response.ErrorException != null)
            {
                const string message = "Error retrieving response from CoinGecko. Check inner details for more info.";
                throw new Exception(message, response.ErrorException);
            }
            return(response.Data);
        }
Ejemplo n.º 28
0
        public static async Task <SellGoldCryptoResult> SellGoldCryptoRev(
            IServiceProvider services,
            TradableCurrency ethereumToken,
            FiatCurrency fiatCurrency,
            BigInteger requiredCryptoAmountWithFee,
            long?knownGoldRateCents   = null,
            long?knownCryptoRateCents = null
            )
        {
            if (requiredCryptoAmountWithFee <= 0)
            {
                return(new SellGoldCryptoResult());
            }

            var pricer     = services.GetRequiredService <IPriceSource>();
            var cryptoRate = (long?)0L;
            var decimals   = 0;

            if (ethereumToken == TradableCurrency.Eth)
            {
                decimals   = TokensPrecision.Ethereum;
                cryptoRate = pricer.GetPriceInFiat(CurrencyPrice.Eth, fiatCurrency);
            }
            else
            {
                throw new NotImplementedException($"Not implemented for { ethereumToken.ToString() }");
            }

            cryptoRate = knownCryptoRateCents ?? cryptoRate;
            if (cryptoRate == null || cryptoRate <= 0)
            {
                return(new SellGoldCryptoResult()
                {
                    Status = SellGoldStatus.TradingDisallowed,
                });
            }

            var goldRate = knownGoldRateCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldRate == null || goldRate <= 0)
            {
                return(new SellGoldCryptoResult()
                {
                    Status = SellGoldStatus.TradingDisallowed,
                });
            }

            var assetPerGold = AssetPerGold(ethereumToken, cryptoRate.Value, goldRate.Value);

            // round up
            var goldAmount = (requiredCryptoAmountWithFee * BigInteger.Pow(10, decimals) + assetPerGold - 1) / assetPerGold;

            return(new SellGoldCryptoResult()
            {
                Allowed = true,
                Status = SellGoldStatus.Success,
                Asset = ethereumToken,
                ExchangeCurrency = fiatCurrency,
                CentsPerGoldRate = goldRate.Value,
                CentsPerAssetRate = cryptoRate.Value,
                CryptoPerGoldRate = assetPerGold,
                ResultGoldAmount = goldAmount,
                ResultAssetAmount = requiredCryptoAmountWithFee,
            });
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Get the latest quote of aggregate market metrics. Use the "convert" option to return market values in multiple fiat and cryptocurrency conversions in the same call.
 /// </summary>
 /// <param name="convert">Optionally calculate market quotes in up to 32 currencies at once by passing a comma-separated list of cryptocurrency or fiat currency symbols. Each additional convert option beyond the first requires an additional call credit. A list of supported fiat options can be found here. Each conversion is returned in its own "quote" object.</param>
 /// <returns></returns>
 public CoinMarketCap.Pro.Model.GlobalMetrics.QuotesData GlobalMetricsQuotesLatest(FiatCurrency convert = FiatCurrency.USD)
 {
     return(this.GlobalMetricsQuotesLatestAsync(convert).Result);
 }
Ejemplo n.º 30
0
        public static async Task <BuyGoldCryptoResult> BuyGoldCryptoRev(
            IServiceProvider services,
            TradableCurrency ethereumToken,
            FiatCurrency fiatCurrency,
            BigInteger requiredGoldAmount,
            long?knownGoldRateCents   = null,
            long?knownCryptoRateCents = null,
            double discount           = 0d
            )
        {
            if (requiredGoldAmount <= 0)
            {
                return(new BuyGoldCryptoResult());
            }

            var pricer     = services.GetRequiredService <IPriceSource>();
            var cryptoRate = (long?)0L;

            if (ethereumToken == TradableCurrency.Eth)
            {
                cryptoRate = pricer.GetPriceInFiat(CurrencyPrice.Eth, fiatCurrency);
            }
            else
            {
                throw new NotImplementedException($"Not implemented for { ethereumToken.ToString() }");
            }

            cryptoRate = knownCryptoRateCents ?? cryptoRate;
            if (cryptoRate == null || cryptoRate <= 0)
            {
                return(new BuyGoldCryptoResult()
                {
                    Status = BuyGoldStatus.TradingDisallowed,
                });
            }

            var goldRate = knownGoldRateCents ?? pricer.GetPriceInFiat(CurrencyPrice.Gold, fiatCurrency);

            if (goldRate == null || goldRate <= 0)
            {
                return(new BuyGoldCryptoResult()
                {
                    Status = BuyGoldStatus.TradingDisallowed,
                });
            }

            var assetPerGold = AssetPerGold(ethereumToken, cryptoRate.Value, goldRate.Value);

            // round up
            var cryptoAmount = (requiredGoldAmount * assetPerGold + BigInteger.Pow(10, TokensPrecision.Sumus) - 1) / BigInteger.Pow(10, TokensPrecision.Sumus);

            // discount
            var cryptoAmountMinusDiscount = GetDiscountRevBody(discount, cryptoAmount);

            if (cryptoAmountMinusDiscount < 1)
            {
                cryptoAmountMinusDiscount = 1;
            }

            return(new BuyGoldCryptoResult()
            {
                Allowed = true,
                Status = BuyGoldStatus.Success,
                Asset = ethereumToken,
                ExchangeCurrency = fiatCurrency,
                Discount = discount,
                CentsPerAssetRate = cryptoRate.Value,
                CentsPerGoldRate = goldRate.Value,
                CryptoPerGoldRate = assetPerGold,
                ResultAssetAmount = cryptoAmountMinusDiscount,
                ResultGoldAmount = requiredGoldAmount,
            });
        }