void BuySomethingWithOptionalCurrency(ProductCode productCode, decimal price, CurrencyCode? currencyCode)
        {
            if (productCode == null) { throw new ArgumentNullException("productCode"); }
            currencyCode = currencyCode ?? "gbp".ToCurrencyCode();

            Console.WriteLine("Bought {0} for {1}{2}", productCode, price, currencyCode);
        }
        void BuySomething(ProductCode productCode, decimal price, CurrencyCode currencyCode)
        {
            if (productCode == null) { throw new ArgumentNullException("productCode"); }
            if (currencyCode == null) { throw new ArgumentNullException("currencyCode"); }

            Console.WriteLine("Bought {0} for {1}{2}", productCode, price, currencyCode);
        }
Пример #3
0
        static decimal GetExchangeRateA(DateTime date, CurrencyCode baseCurrency, CurrencyCode targetCurrency)
        {
            if (baseCurrency == targetCurrency)
            {
                return(decimal.One);
            }

            var item = ExchangeRate.Queryable.SingleOrDefault(x => x.Date == date && x.Base == baseCurrency &&
                                                              x.Target == targetCurrency);

            if (item != null)
            {
                return(item.Rate);
            }

            item = ExchangeRate.Queryable.SingleOrDefault(x => x.Date == date && x.Base == targetCurrency &&
                                                          x.Target == baseCurrency);

            if (item != null)
            {
                return(decimal.One / item.Rate);
            }

            return(decimal.Zero);
        }
Пример #4
0
        public CatalogSearchQuery PriceBetween(
            decimal?fromPrice,
            decimal?toPrice,
            bool?includeFrom = null,
            bool?includeTo   = null)
        {
            if (fromPrice == null && toPrice == null)
            {
                return(this);
            }

            Guard.NotEmpty(CurrencyCode, nameof(CurrencyCode));

            var fieldName = "price_c-" + CurrencyCode.EmptyNull().ToLower();

            if (fromPrice.HasValue && toPrice.HasValue && fromPrice == toPrice)
            {
                var forbidden = includeFrom.HasValue && includeTo.HasValue && !includeFrom.Value && !includeTo.Value;

                return(WithFilter(SearchFilter.ByField(fieldName, decimal.ToDouble(fromPrice.Value)).Mandatory(!forbidden).ExactMatch().NotAnalyzed()));
            }
            else
            {
                var filter = SearchFilter.ByRange(fieldName,
                                                  fromPrice.HasValue ? decimal.ToDouble(fromPrice.Value) : null,
                                                  toPrice.HasValue ? decimal.ToDouble(toPrice.Value) : null,
                                                  includeFrom ?? fromPrice.HasValue,
                                                  includeTo ?? toPrice.HasValue);

                return(WithFilter(filter.Mandatory().ExactMatch().NotAnalyzed()));
            }
        }
Пример #5
0
        public static double CalculateHistoricalExchange(double Amount, CurrencyCode FromCurrencyCode, CurrencyCode ToCurrencyCode, int Year, int Month, int Day)
        {
            try
            {
                string SYear  = String.Format("{0:0000}", Year);
                string SMonth = String.Format("{0:00}", Month);
                string SDay   = String.Format("{0:00}", Day);

                Dictionary <string, Currency> CurrencyRates = GetCurrencyRates("http://www.tcmb.gov.tr/kurlar/" + SYear + SMonth + "/" + SDay + SMonth + SYear + ".xml");

                if (!CurrencyRates.Keys.Contains(FromCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + FromCurrencyCode.ToString() + ") was not found!");
                }
                else if (!CurrencyRates.Keys.Contains(ToCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + ToCurrencyCode.ToString() + ") was not found!");
                }
                else
                {
                    Currency MainCurrency  = CurrencyRates[FromCurrencyCode.ToString()];
                    Currency OtherCurrency = CurrencyRates[ToCurrencyCode.ToString()];

                    return((OtherCurrency.ForexBuying == 0 || MainCurrency.ForexBuying == 0) ? 0 : Math.Round(Amount * (MainCurrency.ForexBuying / OtherCurrency.ForexBuying), 4));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("The date specified may be a weekend or a public holiday!");
            }
        }
Пример #6
0
        public static Currency GetTodaysCrossRates(CurrencyCode ToCurrencyCode, CurrencyCode FromCurrencyCode)
        {
            try
            {
                Dictionary <string, Currency> CurrencyRates = GetCurrencyRates("http://www.tcmb.gov.tr/kurlar/today.xml");

                if (!CurrencyRates.Keys.Contains(FromCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + FromCurrencyCode.ToString() + ") was not found!");
                }
                else if (!CurrencyRates.Keys.Contains(ToCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + ToCurrencyCode.ToString() + ") was not found!");
                }
                else
                {
                    Currency MainCurrency  = CurrencyRates[FromCurrencyCode.ToString()];
                    Currency OtherCurrency = CurrencyRates[ToCurrencyCode.ToString()];

                    return(new Currency(
                               OtherCurrency.Name,
                               OtherCurrency.Code,
                               OtherCurrency.Code + "/" + MainCurrency.Code,
                               (OtherCurrency.ForexBuying == 0 || MainCurrency.ForexBuying == 0)? 0: Math.Round((OtherCurrency.ForexBuying / MainCurrency.ForexBuying), 4),
                               (OtherCurrency.ForexSelling == 0 || MainCurrency.ForexSelling == 0)? 0: Math.Round((OtherCurrency.ForexSelling / MainCurrency.ForexSelling), 4),
                               (OtherCurrency.BanknoteBuying == 0 || MainCurrency.BanknoteBuying == 0)? 0: Math.Round((OtherCurrency.BanknoteBuying / MainCurrency.BanknoteBuying), 4),
                               (OtherCurrency.BanknoteSelling == 0 || MainCurrency.BanknoteSelling == 0)? 0: Math.Round((OtherCurrency.BanknoteSelling / MainCurrency.BanknoteSelling), 4)
                               ));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("The date specified may be a weekend or a public holiday!");
            }
        }
Пример #7
0
        public static double CalculateTodaysExchange(double Amount, CurrencyCode FromCurrencyCode, CurrencyCode ToCurrencyCode)
        {
            try
            {
                Dictionary <string, Currency> CurrencyRates = GetCurrencyRates("http://www.tcmb.gov.tr/kurlar/today.xml");

                if (!CurrencyRates.Keys.Contains(FromCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + FromCurrencyCode.ToString() + ") was not found!");
                }
                else if (!CurrencyRates.Keys.Contains(ToCurrencyCode.ToString()))
                {
                    throw new Exception("The specified currency(" + ToCurrencyCode.ToString() + ") was not found!");
                }
                else
                {
                    Currency MainCurrency  = CurrencyRates[FromCurrencyCode.ToString()];
                    Currency OtherCurrency = CurrencyRates[ToCurrencyCode.ToString()];

                    return((OtherCurrency.ForexBuying == 0 || MainCurrency.ForexBuying == 0) ? 0 : Math.Round(Amount * (MainCurrency.ForexBuying / OtherCurrency.ForexBuying), 4));
                }
            }
            catch (Exception ex)
            {
                throw new Exception("The date specified may be a weekend or a public holiday!");
            }
        }
Пример #8
0
        public static CryptocurrencyQuotesResponse From(
            CurrencyCode baseCryptocurrencyCode, IEnumerable <QuoteCurrency> quotes)
        {
            if (baseCryptocurrencyCode is null)
            {
                throw new ArgumentNullException(
                          nameof(baseCryptocurrencyCode),
                          $"{nameof(CryptocurrencyQuotesResponse)} {nameof(baseCryptocurrencyCode)} is required");
            }
            if (quotes is null)
            {
                throw new ArgumentNullException(
                          nameof(quotes),
                          $"{nameof(CryptocurrencyQuotesResponse)} {nameof(quotes)} is required");
            }

            return(new CryptocurrencyQuotesResponse
            {
                BaseCryptocurrencyCode = baseCryptocurrencyCode,
                Quotes = quotes.Select(quote =>
                                       new QuoteCurrencyDetails
                {
                    Code = quote.Code,
                    ExchangeRate = quote.ExchangeRate
                }).ToList()
            });
        }
Пример #9
0
        public OrderBuilder WithItems(params OrderLine[] items)
        {
            if (items == null || !items.Any())
            {
                throw new ArgumentException("Items must be specified");
            }

            if (items.GroupBy(x => x.ProductUID).Any(x => x.Count() > 1))
            {
                throw new ArgumentException("Duplicates founded in order items");
            }

            if (items.Any(x => x.Amount == null || x.Amount.Value < 0)) // An item could costs 0 (a gift for example)
            {
                throw new ArgumentException("Invalid item(s) detected");
            }

            if (items.GroupBy(x => x.Amount.Currency).Select(x => x.Key).Distinct().Count() > 1)
            {
                throw new ArgumentException("Multiply currencies have been detected in order items");
            }

            _items = items;

            CurrencyCode itemsCurrency = items.GroupBy(x => x.Amount.Currency).Select(x => x.Key).Distinct().First();

            if (_amount != null && (Math.Abs(items.Sum(x => x.Amount.Value) - _amount.Value) >= 1m || _amount.Currency != itemsCurrency))
            {
                throw new ArgumentException("Order amount is not equals to order items summ or order currency different from order items");
            }

            return(this);
        }
Пример #10
0
        public ShopifyShop(string address1, string city, string country, DateTime createdAt,
				string domain, string email, int id, string name, string phone, string province,
				bool Public, string source, string zip, CurrencyCode currency,
				string timezone, string shopOwner, string moneyFormat, bool taxesIncluded,
				string taxShipping, AccountType planName)
        {
            this.Address1 = address1;
            this.City = city;
            this.Country = country;
            this.CreatedAt = createdAt;
            this.Domain = domain;
            this.Email = email;
            this.Id = id;
            this.Name = name;
            this.Phone = phone;
            this.Province = province;
            this.Public = Public;
            this.Source = source;
            this.Zip = zip;
            this.Currency = currency;
            this.Timezone = timezone;
            this.ShopOwner = shopOwner;
            this.MoneyFormat = moneyFormat;
            this.TaxesIncluded = taxesIncluded;
            this.TaxShipping = taxShipping;
            this.PlanName = planName;
        }
        public void SetAmount(CurrencyCode currencyCode, decimal amount)
        {
            Ensure.This(amount).CompliesWith(a => a != default(decimal), "Transaction amount cannot be 0");

            CurrencyCode = currencyCode;
            Amount       = amount;
        }
Пример #12
0
 public Product(ProductCode productCode, SupplierCode supplierCode, decimal price, CurrencyCode currencyCode)
 {
     ProductCode = productCode;
     SupplierCode = supplierCode;
     Price = price;
     CurrencyCode = currencyCode;
 }
Пример #13
0
 public AppViewModel(ApiConfig apiConfig)
 {
     _primaryCurrency   = CurrencyCode.Xbt;
     _secondaryCurrency = CurrencyCode.Usd;
     _numberOfHoursInThePastToRetrieve = 96;
     _numberOfRecentTradesToRetrieve   = 10;
     _pageIndex                 = 1;
     _pageSize                  = 10;
     _limitOrderType            = OrderType.LimitBid;
     _marketOrderType           = OrderType.MarketOffer;
     _limitOrderPrice           = 500;
     _orderVolume               = 0.1m;
     _orderGuid                 = string.Empty;
     _fromTimestampUtc          = new DateTime(2014, 8, 1);
     _toTimestampUtc            = null;
     _withdrawalAmount          = 50;
     _withdrawalBankAccountName = null;
     _address         = null;
     ApiConfig        = apiConfig;
     TransactionTypes = new ObservableCollection <TransactionTypeViewModel>();
     using (var client = Client.Create(apiConfig))
     {
         var types = client.GetValidTransactionTypes();
         foreach (var transactionType in types)
         {
             TransactionTypes.Add(new TransactionTypeViewModel {
                 IsSelected = false, Type = transactionType
             });
         }
     }
 }
Пример #14
0
 public WorldPay(HtmlHelper html, string installationId, string cartId, string amount, CurrencyCode currency)
 {
     fWorldPayPaymentModel.instId = installationId;
          fWorldPayPaymentModel.cartId = cartId;
          fWorldPayPaymentModel.amount = amount;
          fWorldPayPaymentModel.currency = currency.ToString();
 }
Пример #15
0
        private void StartTransaction()
        {
            if (!_registerClient.IsRegisterInstalled)
            {
                new Android.Support.V7.App.AlertDialog.Builder(this)
                .SetTitle(Resource.String.install_register_title)
                .SetMessage(Resource.String.install_register_message)
                .SetPositiveButton(Resource.String.install_register_confirm,
                                   (sender, e) => _registerClient.OpenRegisterPlayStoreListing())
                .SetNegativeButton(Android.Resource.String.Cancel,
                                   (sender, e) => { })
                .Show();
                return;
            }

            var amountString = _transactionAmountEditText.Text;
            var amount       = string.IsNullOrWhiteSpace(amountString) ? 0 : int.Parse(amountString);
            var currencyCode = _currencyCodeEditText.Text;
            var note         = _noteEditText.Text;

            var tenderTypes = new List <ChargeRequest.TenderType>();

            if (_cardCheckbox.Checked)
            {
                tenderTypes.Add(ChargeRequest.TenderType.Card);
            }
            if (_cashCheckbox.Checked)
            {
                tenderTypes.Add(ChargeRequest.TenderType.Cash);
            }
            if (_otherTenderCheckbox.Checked)
            {
                tenderTypes.Add(ChargeRequest.TenderType.Other);
            }

            var locationId    = _locationIdEditText.Text;
            var timeoutString = _autoReturnTimeoutEditText.Text;
            var timeout       = string.IsNullOrWhiteSpace(timeoutString)
                ? RegisterApi.AutoReturnNoTimeout
                : int.Parse(timeoutString);
            var requestMetadata = _requestMetadataEditText.Text;

            var chargeRequest = new ChargeRequest.Builder(amount, CurrencyCode.ValueOf(currencyCode.ToUpper()))
                                .Note(note)
                                .EnforceBusinessLocation(locationId)
                                .AutoReturn(timeout, TimeUnit.Milliseconds)
                                .RequestMetadata(requestMetadata)
                                .RestrictTendersTo(tenderTypes)
                                .Build();

            try
            {
                var chargeIntent = _registerClient.CreateChargeIntent(chargeRequest);
                StartActivityForResult(chargeIntent, ChargeRequestCode);
            }
            catch (ActivityNotFoundException)
            {
                ShowSnackbar("Square Register was just uninstalled.");
            }
        }
Пример #16
0
 /// <summary>
 /// Checks whether the <paramref name="money"/> has the same currency as the instance, throwing an exception if that is not the case.
 /// </summary>
 /// <param name="money"><see cref="Money"/> instance to check against.</param>
 /// <exception cref="DifferentCurrencyException"><paramref name="money"/> has a different currency from the instance's.</exception>
 public void AssertSameCurrency(Money money)
 {
     if (!HasSameCurrencyAs(money))
     {
         throw new DifferentCurrencyException(CurrencyCode.ToString(), money.CurrencyCode.ToString());
     }
 }
Пример #17
0
        public async Task <Svea.WebPay.SDK.CheckoutApi.Data> CreatePaymentOrder(string consumerProfileRef = null)
        {
            var orderItems = _cartService.CartLines.ToOrderItems().ToList();

            try
            {
                var noRegion = new RegionInfo("NO");
                var nok      = new CurrencyCode("NOK");

                var seRegion            = new RegionInfo("SE");
                var sek                 = new CurrencyCode("SEK");
                var paymentOrderRequest = new CreateOrderModel(seRegion, sek, new Language("sv-SE"), DateTime.Now.Ticks.ToString(),
                                                               new Svea.WebPay.SDK.CheckoutApi.MerchantSettings(_merchantSettings.PushUri, _merchantSettings.TermsUri, _merchantSettings.CheckoutUri, _merchantSettings.ConfirmationUri, _merchantSettings.CheckoutValidationCallbackUri),
                                                               new Svea.WebPay.SDK.CheckoutApi.Cart(orderItems));

                var data = await _sveaClient.Checkout.CreateOrder(paymentOrderRequest);

                return(data);
            }
            catch (Exception ex)
            {
                Debug.Write(ex.Message);
                return(null);
            }
        }
Пример #18
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (ResourceName.Length != 0)
            {
                hash ^= ResourceName.GetHashCode();
            }
            if (paymentsAccountId_ != null)
            {
                hash ^= PaymentsAccountId.GetHashCode();
            }
            if (name_ != null)
            {
                hash ^= Name.GetHashCode();
            }
            if (currencyCode_ != null)
            {
                hash ^= CurrencyCode.GetHashCode();
            }
            if (paymentsProfileId_ != null)
            {
                hash ^= PaymentsProfileId.GetHashCode();
            }
            if (secondaryPaymentsProfileId_ != null)
            {
                hash ^= SecondaryPaymentsProfileId.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Пример #19
0
        private bool GetTickerSymbol(string pair, out TickerSymbol tickerSymbol, out CurrencyCode currencyCode)
        {
            bool okay1 = Enum.TryParse <TickerSymbol>(pair, true, out tickerSymbol);
            bool okay2 = Enum.TryParse <CurrencyCode>(pair.Substring(3), true, out currencyCode);

            return(okay1 && okay2);
        }
        private static QuoteCurrency CreateQuoteCurrencyFromGetLatestCryptocurrencyQuotesResponseJsonContent(
            string jsonText)
        {
            var jsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(jsonText), isFinalBlock: true, state: default);

            CurrencyCode         currencyCode = null;
            CurrencyExchangeRate crossRate    = null;

            var currentPropertyName = string.Empty;

            while (jsonReader.Read())
            {
                switch (jsonReader.TokenType)
                {
                case JsonTokenType.PropertyName:
                    var previousPropertyName = currentPropertyName;
                    currentPropertyName = jsonReader.GetString();
                    TryParseQuoteCurrencyCode(previousPropertyName, currentPropertyName, ref currencyCode);
                    continue;

                case JsonTokenType.Number:
                    TryParseQuoteCurrencyCrossRate(jsonReader.GetDecimal(), currentPropertyName, ref crossRate);
                    break;

                default:
                    continue;
                }
            }

            return(QuoteCurrency.Of(currencyCode, crossRate));
        }
Пример #21
0
        }                                                           //quoted as FgnCcy/DomCcy

        public FxSwap(Date startDate,
                      Date maturityDate,
                      Date spotDate,
                      Date nearStrikeDate,
                      DayGap dayGap,
                      double notional,
                      ICalendar domCalendar,
                      CurrencyCode domCcy,
                      double fgnNotional,
                      ICalendar fgnCalendar,
                      CurrencyCode fgnCcy,
                      double nearStrikeFxRate,
                      double farStrikeFxRate,
                      CurrencyCode settlementCcy
                      )
        {
            StartDate = startDate;
            UnderlyingMaturityDate = maturityDate;
            SpotDate       = spotDate;
            NearStrikeDate = nearStrikeDate;
            SettlmentGap   = dayGap ?? new DayGap("0BD");

            Notional    = notional;
            DomCalendar = domCalendar;
            DomCcy      = domCcy;

            NotionalInFgnCcy = fgnNotional;
            FgnCalendar      = fgnCalendar;
            FgnCcy           = fgnCcy;

            NearStrikeFxRate = nearStrikeFxRate;
            FarStrikeFxRate  = farStrikeFxRate;

            SettlementCcy = settlementCcy;
        }
Пример #22
0
 public LookbackOption(Date startDate,
                       Date maturityDate,
                       OptionExercise exercise,
                       OptionType optionType,
                       StrikeStyle strikeStyle,
                       double strike,
                       InstrumentType underlyingInstrumentType,
                       ICalendar calendar,
                       IDayCount dayCount,
                       CurrencyCode payoffCcy,
                       CurrencyCode settlementCcy,
                       Date[] exerciseDates,
                       Date[] observationDates,
                       Dictionary <Date, double> fixings,
                       double notional                      = 1,
                       DayGap settlementGap                 = null,
                       Date optionPremiumPaymentDate        = null,
                       double optionPremium                 = 0,
                       bool isMoneynessOption               = false,
                       double initialSpotPrice              = 0.0,
                       Dictionary <Date, double> dividends  = null,
                       bool hasNightMarket                  = false,
                       bool commodityFuturesPreciseTimeMode = false
                       )
     : base(startDate, maturityDate, exercise, optionType, new double[] { strike }, underlyingInstrumentType, calendar, dayCount,
            settlementCcy, payoffCcy, exerciseDates, observationDates, notional, settlementGap,
            optionPremiumPaymentDate, optionPremium,
            isMoneynessOption: isMoneynessOption, initialSpotPrice: initialSpotPrice, dividends: dividends, hasNightMarket: hasNightMarket,
            commodityFuturesPreciseTimeMode: commodityFuturesPreciseTimeMode)
 {
     Fixings     = fixings;
     StrikeStyle = strikeStyle;
 }
Пример #23
0
 public async IAsyncEnumerable <IStake> ListStakesAsync(CurrencyCode currencyCode)
 {
     foreach (var stakeAddress in GetStakes().Select(x => x.Symbol))
     {
         yield return(await GetStakeAsync(stakeAddress, currencyCode));
     }
 }
    public override int GetHashCode()
    {
        int hashcode = 157;

        unchecked {
            if (__isset.currencyCode)
            {
                hashcode = (hashcode * 397) + CurrencyCode.GetHashCode();
            }
            if (__isset.currencyName)
            {
                hashcode = (hashcode * 397) + CurrencyName.GetHashCode();
            }
            if (__isset.currencySign)
            {
                hashcode = (hashcode * 397) + CurrencySign.GetHashCode();
            }
            if (__isset.preferred)
            {
                hashcode = (hashcode * 397) + Preferred.GetHashCode();
            }
            if (__isset.coinRate)
            {
                hashcode = (hashcode * 397) + CoinRate.GetHashCode();
            }
            if (__isset.creditRate)
            {
                hashcode = (hashcode * 397) + CreditRate.GetHashCode();
            }
        }
        return(hashcode);
    }
Пример #25
0
 public TransactionLogic(List <Rate> rates, CurrencyCode taxCurrencyCode = CurrencyCode.SEK)
 {
     _rates           = rates;
     _taxCurrencyCode = taxCurrencyCode;
     _taxBaseAmounts  = new List <Currency>();
     _taxBaseRates    = new List <Currency>();
 }
Пример #26
0
        public CheckoutOrderBuilder UseTestValues()
        {
            var pushUri         = new Uri("https://svea.com/push.aspx?sid=123&svea_order=123");
            var termsUri        = new Uri("http://localhost:51898/terms");
            var checkoutUri     = new Uri("http://localhost:8080/php-checkout/examples/create-order.php");
            var confirmationUri = new Uri("http://localhost/php-checkout/examples/get-order.php");

            var orderRows = new List <OrderRow>
            {
                new OrderRow(
                    "ABC80",
                    "Computer",
                    MinorUnit.FromInt(10),
                    MinorUnit.FromDecimal(5000),
                    MinorUnit.FromDecimal(10),
                    MinorUnit.FromDecimal(25),
                    null,
                    null,
                    1)
            };

            this.cart              = new Cart(orderRows);
            this.merchantSettings  = new MerchantSettings(pushUri, termsUri, checkoutUri, confirmationUri);
            this.countryCode       = new RegionInfo("SE");
            this.currency          = new CurrencyCode("SEK");
            this.locale            = new Language("sv-SE");
            this.clientOrderNumber = DateTime.Now.Ticks.ToString();

            return(this);
        }
Пример #27
0
        public static CurrencyExchange LookupCurrencyExchange(FGAContext db, CurrencyCode Unit, CurrencyCode Quoted, DateTime dateOfData)
        {
            CurrencyExchange forex;

            forex = db.CurrencyExchanges.Where <CurrencyExchange>(t => (t.Date == dateOfData && t.UnitCurrency.Currency == Unit.Currency && t.QuotedCurrency.Currency == Unit.Currency)).FirstOrDefault <CurrencyExchange>();
            return(forex);
        }
Пример #28
0
        public static Index CreateIndexObject(FGAContext db, IDictionary <string, string> data, ILog ExceptionLogger)
        {
            Index        index;
            string       isin = data["isin"];
            CurrencyCode c    = data["currency"] == null ? CurrencyCode.EUR : (CurrencyCode)data["currency"];

            index = new Index(Name: data["name"], ISIN: isin, IndexCurrency: c);
            index.IndexFrequency = FrequencyCode.getFrequencyByLabel("DAILY");
            index.Identification.OtherIdentification = data["id"];
            index.Identification.RIC       = (RICIdentifier)data["ric"];
            index.Identification.Bloomberg = (BloombergIdentifier)data["bloomberg"];
            index.FamilyKeyObject          = new MSCIFamilyObject();
            if (data["country"] != null)
            {
                try
                {
                    index.Identification.DomesticIdentificationSource = (CountryCode)data["country"];
                }
                catch (Exception e)
                {
                    ExceptionLogger.Info("Country code :" + data["country"] + " Not recognized");
                }
            }
            db.Indexes.Add(index);
            return(index);
        }
Пример #29
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="startDate">开始日期</param>
 /// <param name="maturityDate">到期日</param>
 /// <param name="exercise">行权方式</param>
 /// <param name="optionType">看涨看跌</param>
 /// <param name="strike">行权价</param>
 /// <param name="underlyingInstrumentType">标的资产类型</param>
 /// <param name="calendar">交易日历</param>
 /// <param name="dayCount">日期规则</param>
 /// <param name="payoffCcy">收益计算币种</param>
 /// <param name="settlementCcy">结算币种</param>
 /// <param name="exerciseDates">行权日</param>
 /// <param name="observationDates">观察日</param>
 /// <param name="notional">名义本金</param>
 /// <param name="settlementGap">结算日规则</param>
 /// <param name="optionPremiumPaymentDate">权利金支付日</param>
 /// <param name="optionPremium">权利金</param>
 /// <param name="isMoneynessOption">是否为相对行权价期权</param>
 /// <param name="initialSpotPrice">标的资产期初价格</param>
 /// <param name="dividends">标的资产分红</param>
 /// <param name="hasNightMarket">标的资产是否有夜盘交易</param>
 /// <param name="commodityFuturesPreciseTimeMode">是否启用精确时间计算模式</param>
 public VanillaOption(Date startDate,
                      Date maturityDate, //underlying maturity,  for option on forward
                      OptionExercise exercise,
                      OptionType optionType,
                      double strike,
                      InstrumentType underlyingInstrumentType,
                      ICalendar calendar,
                      IDayCount dayCount,
                      CurrencyCode payoffCcy,
                      CurrencyCode settlementCcy,
                      Date[] exerciseDates,
                      Date[] observationDates,
                      double notional                      = 1,
                      DayGap settlementGap                 = null,
                      Date optionPremiumPaymentDate        = null,
                      double optionPremium                 = 0.0,
                      bool isMoneynessOption               = false,
                      double initialSpotPrice              = 0.0,
                      Dictionary <Date, double> dividends  = null,
                      bool hasNightMarket                  = false,
                      bool commodityFuturesPreciseTimeMode = false
                      )
     : base(startDate, maturityDate, exercise, optionType, new double[] { strike }, underlyingInstrumentType,
            calendar, dayCount, payoffCcy, settlementCcy, exerciseDates, observationDates, notional, settlementGap,
            optionPremiumPaymentDate, optionPremium,
            isMoneynessOption: isMoneynessOption, initialSpotPrice: initialSpotPrice, dividends: dividends, hasNightMarket: hasNightMarket,
            commodityFuturesPreciseTimeMode: commodityFuturesPreciseTimeMode)
 {
     if (Exercise == OptionExercise.European && exerciseDates.Length != 1)
     {
         throw new PricingLibraryException("Vanilla European option can have only 1 observation date");
     }
 }
Пример #30
0
        private List <SqlDataRecord> BuildSqlRecordList(CurrencyModel DataModel)
        {
            string  CurrencyCode;
            decimal CurrencyRate;

            PropertyInfo[] PublicProps;
            Type           ModelType;
            SqlDataRecord  Record;

            SqlMetaData[]        Columns;
            SqlMetaData          C_Code, C_Rate;
            List <SqlDataRecord> CurrencyTable = new List <SqlDataRecord>();

            C_Code  = new SqlMetaData("Code", SqlDbType.NVarChar, 5);
            C_Rate  = new SqlMetaData("Rate", SqlDbType.Decimal, 18, 2);
            Columns = new SqlMetaData[] { C_Code, C_Rate };

            ModelType   = typeof(CurrencyRateModel);
            PublicProps = ModelType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo Property in PublicProps)
            {
                CurrencyCode = Property.Name.ToString();
                CurrencyRate = Convert.ToDecimal(Property.GetValue(DataModel.quotes).ToString());
                Record       = new SqlDataRecord(Columns);
                Record.SetValue(Record.GetOrdinal("Code"), CurrencyCode.Substring(3));
                Record.SetValue(Record.GetOrdinal("Rate"), Math.Round(CurrencyRate, 2));
                CurrencyTable.Add(Record);
            }
            Record = new SqlDataRecord(Columns);
            Record.SetValue(Record.GetOrdinal("Code"), DataModel.source);
            Record.SetValue(Record.GetOrdinal("Rate"), 1.00M);
            CurrencyTable.Add(Record);
            return(CurrencyTable);
        }
Пример #31
0
        private string priceToWords(CurrencyCode currency, double number)
        {
            if (number == 0)
            {
                return("zero");
            }

            if (number < 0)
            {
                return("minus " + priceToWords(currency, Math.Abs(number)));
            }

            string words = "";

            string[] CurrencyProperty = getCurrencyProperty(currency).Split(',');

            int    intPortion = (int)number;
            double fraction   = (number - intPortion) * int.Parse(CurrencyProperty[2]);
            int    decPortion = (int)fraction;

            words = numberToWords(intPortion);
            if (decPortion > 0)
            {
                words += " " + CurrencyProperty[0] + " and ";
                words += numberToWords(decPortion) + " " + CurrencyProperty[1] + ".";
            }
            else
            {
                words += " " + CurrencyProperty[0];
            }
            TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;

            return(textInfo.ToTitleCase(words));
        }
        public override int GetHashCode()
        {
            int hash = 1;

            if (BaseCurrencyCode.Length != 0)
            {
                hash ^= BaseCurrencyCode.GetHashCode();
            }
            if (CurrencyCode.Length != 0)
            {
                hash ^= CurrencyCode.GetHashCode();
            }
            if (BuyRate != 0F)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(BuyRate);
            }
            if (SellRate != 0F)
            {
                hash ^= pbc::ProtobufEqualityComparers.BitwiseSingleEqualityComparer.GetHashCode(SellRate);
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        public void Update(CurrencyCode currencyCode)
        {
            CurrencyCode currencyCodeToUpdate = _currencyCodes.SingleOrDefault(c => c.CurrencyCodeId == currencyCode.CurrencyCodeId);

            currencyCodeToUpdate.CodeName = currencyCode.CodeName;
            currencyCodeToUpdate.Code     = currencyCode.Code;
        }
Пример #34
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="accStartDate">计息开始日</param>
 /// <param name="accEndDate">计息结束日</param>
 /// <param name="paymentDate">支付日</param>
 /// <param name="paymentAmount">支付金额</param>
 /// <param name="paymentCurrency">支付币种</param>
 /// <param name="cashflowType">现金流类型</param>
 /// <param name="isFixed">是否固定现金流</param>
 /// <param name="df">折现因子</param>
 /// <param name="cfCalcDetails">计算细节</param>
 /// <param name="refStartDate">参考开始日</param>
 /// <param name="refEndDate">参考结束日</param>
 /// <param name="startPrincipal">开始本金</param>
 /// <param name="couponRate">利率</param>
 public Cashflow(
     Date accStartDate,
     Date accEndDate,
     Date paymentDate,
     double paymentAmount,
     CurrencyCode paymentCurrency,
     CashflowType cashflowType,
     bool isFixed,
     double df,
     CfCalculationDetail[] cfCalcDetails,
     Date refStartDate     = null,
     Date refEndDate       = null,
     double startPrincipal = 100.0,
     double couponRate     = 0.0)
 {
     AccrualStartDate   = accStartDate;
     AccrualEndDate     = accEndDate;
     PaymentDate        = paymentDate;
     PaymentAmount      = paymentAmount;
     PaymentCurrency    = paymentCurrency;
     CashflowType       = cashflowType;
     DiscountFactor     = df;
     IsFixed            = isFixed;
     CalculationDetails = cfCalcDetails;
     RefStartDate       = refStartDate;
     RefEndDate         = refEndDate;
     CouponRate         = couponRate;
     StartPrincipal     = startPrincipal;
 }
Пример #35
0
        public decimal GetPriceAt(CurrencyCode from, CurrencyCode to, DateTimeOffset date)
        {
            _logger.LogTrace($"Get price from '{from}' to '{to}'");
            if (from != "RUB")
            {
                var directPrice = GetPriceAt(from, date);
                _logger.LogTrace($"Direct price of '{from}' is {directPrice} RUB");
                if (to != "RUB")
                {
                    var transferPrice = GetPriceAt(to, date);
                    _logger.LogTrace($"Transfer price of '{to}' is {transferPrice} RUB");
                    if (transferPrice == 0)
                    {
                        return(0);
                    }
                    var result = directPrice / transferPrice;
                    _logger.LogTrace($"Final price of '{from}' to '{to}' is {result}");
                    return(result);
                }
                _logger.LogTrace($"Direct price of '{from}' to '{to}' is {directPrice} RUB");
                return(directPrice);
            }
            var priceDiv = GetPriceAt(to, date);

            if (priceDiv == 0)
            {
                return(0);
            }
            var inversePrice = 1m / priceDiv;

            _logger.LogTrace($"Inverse price from '{from}' to '{to}' is {inversePrice}");
            return(inversePrice);
        }
 private Currency(CurrencyCode currencyCode, string name,
     string description, string symbol, bool isCoinsSuppose)
 {
     Code = currencyCode;
     Name = name;
     Description = description;
     Symbol = symbol;
     IsCoinsSuppose = isCoinsSuppose;
 }
Пример #37
0
		public Task<Balance> GetWalletBalanceAsync(Guid walletId, CurrencyCode currency)
		{
			if (walletId == Guid.Empty)
				throw new ArgumentException("walletId");
			if (!Enum.IsDefined(typeof(CurrencyCode), currency))
				throw new ArgumentException("currency");

			var request = new GetWalletBalanceMessageBuilder(walletId, currency);
			return SendAsync(request).ReadAsAsync<Balance>();
		}
 /// <summary>
 /// Find all matching. Note that productCode and supplierCode are optional but currencyCode is not.
 /// </summary>
 public IEnumerable<Product> FindMatchingProducts(ProductCode? productCode, SupplierCode? supplierCode,
                                                  CurrencyCode currencyCode)
 {
     return _allProducts
         .Where(p =>
             (!productCode.HasValue || p.ProductCode == productCode.Value)
             && (!supplierCode.HasValue || p.SupplierCode == supplierCode.Value)
             && (p.CurrencyCode == currencyCode)
         );
 }
Пример #39
0
 public static NewOrder Buy(TickerSymbol instrument, CurrencyCode currency, decimal amount, decimal price)
 {
     return new NewOrder {
         Side = OrderSide.buy,
         Instrument = instrument,
         Type = OrderType.limit,
         Currency = currency,
         Price = price,
         Amount = amount,
         Display = amount
     };
 }
Пример #40
0
        public static decimal GetExchangeRate(DateTime date, CurrencyCode baseCurrency, CurrencyCode targetCurrency)
        {
            var val = GetExchangeRateA (date, baseCurrency, targetCurrency);

            if (val != decimal.Zero)
                return val;

            var val1 = GetExchangeRateA (date, baseCurrency, WebConfig.BaseCurrency);
            var val2 = GetExchangeRateA (date, targetCurrency, WebConfig.BaseCurrency);

            return val2 == decimal.Zero ? decimal.Zero : (val1 / val2);
        }
Пример #41
0
 private static double GetExchangeRate(CurrencyCode currencyCode)
 {
     if (currencyCode == CurrencyCode.USD)
     {
         return 1;
     }
     else
     {
         ClientDataContext db = new ClientDataContext();
         var currency = from c in db.Currencies where c.CurrencyCode.Equals(currencyCode.ToString()) select c;
         return currency.FirstOrDefault().Rate.Value;
     }
 }
Пример #42
0
        public static double ConvertAmount(
            double amount, 
            CurrencyCode originalCurrencyCode, 
            CurrencyCode targetCurrencyCode,
            int decimalDigits = 2,
            MidpointRounding midPointRounding = MidpointRounding.AwayFromZero)
        {
            double originalExchangeRate = GetExchangeRate(originalCurrencyCode);
            double targetExchangeRate = GetExchangeRate(targetCurrencyCode);

            double amount_USD = amount / originalExchangeRate;
            double amount_TargetCurrency = Math.Round(amount_USD * targetExchangeRate, decimalDigits, midPointRounding);

            return amount_TargetCurrency;
        }
 /// <summary>
 /// Returns instanse type of <see cref="Currency"/> from it's <see cref="CurrencyCode"/>.
 /// </summary>
 /// <returns>
 /// Instance type of <see cref="Currency"/>.
 /// </returns>
 /// <param name="currencyCode">Required <see cref="Currency"/>.</param>
 public static Currency GetCurrency(CurrencyCode currencyCode)
 {
     switch (currencyCode)
     {
         case CurrencyCode.USD:
             return Usd;
         case CurrencyCode.EUR:
             return Eur;
         case CurrencyCode.BYR:
             return Byr;
         case CurrencyCode.RUB:
             return Rub;
         default:
             return null;
     }
 }
Пример #44
0
        public static string FormatMoney(
            double amount, 
            CurrencyCode currencyCode = CurrencyCode.USD, 
            int decimalDigits = 2)
        {
            StringBuilder moneyString = new StringBuilder();

            if (amount < 0)
            {
                moneyString.Append("-");
                amount = -amount;
            }

            moneyString.Append(CustomStringAttribute.GetCustomString(currencyCode));

            moneyString.Append(amount.ToString(string.Format("C{0}", decimalDigits)).Remove(0, 1));

            return moneyString.ToString();
        }
        /// <summary>
        /// Updates exchange rate data from openexchangerates.org if necessary and converts a <paramref name="money"/> value to another currency represented by <paramref name="toCode"/>
        /// </summary>
        /// <param name="money">the money value to convert</param>
        /// <param name="toCode">the target currency</param>
        /// <returns></returns>
        public async Task<Money> Convert(Money money, CurrencyCode toCode)
        {
            if (money.Currency.Code == toCode)
                return new Money(money);

            if (this.ExchangeData == null || this.ExchangeData.LastChecked <= DateTime.Now.AddHours(-1))
                await this.refreshExchangeRates();

            if (money.Currency.Code.ToString() == this.ExchangeData.Base)
            {
                // direct conversion
                return new Money(money.Amount * ExchangeData.Rates[toCode], Currency.FromCurrencyCode(toCode));
            }
            else
            {
                // indirect conversion, go to the base rate first
                var baseRate = money.Amount / this.ExchangeData.Rates[money.Currency.Code];

                return new Money(baseRate * this.ExchangeData.Rates[toCode], Currency.FromCurrencyCode(toCode));
            }
        }
        public Task<ConvertResponseContext> ConvertAsync(decimal amount, CurrencyCode fromCurrency, CurrencyCode toCurrency)
        {
            if (!Enum.IsDefined(typeof(CurrencyCode), fromCurrency))
                throw new ArgumentNullException("fromCurrency");

            if (!Enum.IsDefined(typeof(CurrencyCode), toCurrency))
                throw new ArgumentNullException("toCurrency");

            if (fromCurrency == toCurrency)
                throw new ArgumentException("fromCurrency and toCurrency paramaters cannot be the same");

            string fromCurrencyStr = fromCurrency.ToString();
            string toCurrencyStr = toCurrency.ToString();

            //NOTE: HttpContext.Current nulls itself after async call
            //get a reference of it and work on that one.
            _currentHttpContext = HttpContext.Current;

            return getRatesStatusAsync().Then(ratesStatus => {

                //NOTE: we are here sure that these two paramates have not the same value set
                if (fromCurrency == CurrencyCode.TRY || toCurrency == CurrencyCode.TRY) {

                    //NOTE: request has been made for some sort of TRY convert
                    //deal with it accordingly

                    //NOTE: if request is to convert from TRY
                    if (fromCurrency == CurrencyCode.TRY) {

                        var ___currency = ratesStatus.Currencies.FirstOrDefault(cur =>
                            cur.CurrencyCode == toCurrencyStr && !string.IsNullOrEmpty(cur.ForexSelling)
                        );

                        if (___currency == null) {

                            return new ConvertResponseContext {
                                IsConvertSuccessful = false,
                                BaseAmount = amount,
                                ErrorMessage = string.Format(
                                    "There is no currency rate available for {0} currency", toCurrencyStr
                                )
                            };
                        }

                        decimal ___currenyRate;
                        if (!decimal.TryParse(___currency.ForexSelling, out ___currenyRate)) {

                            return new ConvertResponseContext {
                                IsConvertSuccessful = false,
                                BaseAmount = amount,
                                ErrorMessage = string.Format(
                                    "{0} amount for {1} currency is not in a correct format.", "ForexSelling", toCurrencyStr
                                )
                            };
                        }

                        var ___convertedAmount = (amount / ___currenyRate);

                        return new ConvertResponseContext {
                            IsConvertSuccessful = true,
                            BaseAmount = amount,
                            BaseCurrencyRate = ___currenyRate,
                            ConvertedFrom = fromCurrency,
                            ConvertedTo = toCurrency,
                            ConvertedAmount = decimal.Round(___convertedAmount, 2)
                        };
                    }
                    //NOTE: if request is to convert to TRY
                    else {

                        var ___currency = ratesStatus.Currencies.FirstOrDefault(cur =>
                            cur.CurrencyCode == fromCurrencyStr && !string.IsNullOrEmpty(cur.ForexSelling)
                        );

                        if (___currency == null) {

                            return new ConvertResponseContext {
                                IsConvertSuccessful = false,
                                BaseAmount = amount,
                                ErrorMessage = string.Format(
                                    "There is no currency rate available for {0} currency", fromCurrencyStr
                                )
                            };
                        }

                        decimal ___currenyRate;
                        if (!decimal.TryParse(___currency.ForexSelling, out ___currenyRate)) {

                            return new ConvertResponseContext {
                                IsConvertSuccessful = false,
                                BaseAmount = amount,
                                ErrorMessage = string.Format(
                                    "{0} amount for {1} currency is not in a correct format.", "ForexSelling", fromCurrencyStr
                                )
                            };
                        }

                        var ___convertedAmount = (amount * ___currenyRate);

                        return new ConvertResponseContext {
                            IsConvertSuccessful = true,
                            BaseAmount = amount,
                            BaseCurrencyRate = ___currenyRate,
                            ConvertedFrom = fromCurrency,
                            ConvertedTo = toCurrency,
                            ConvertedAmount = decimal.Round(___convertedAmount, 2)
                        };
                    }
                }
                else {

                    //NOTE: request has been made for some sort of cross rate calculation
                    //deal with it accordingly

                    return new ConvertResponseContext {
                        IsConvertSuccessful = false,
                        BaseAmount = amount,
                        ErrorMessage = string.Format(
                            "Cross-rate calculation is not supported."
                        )
                    };
                }

            }, runSynchronously: true);
        }
        private string ConvertCurrencyCodeToString(CurrencyCode currencyCode)
        {
            switch (currencyCode)
            {
                case CurrencyCode.GBP:
                    return "GBP";

                default:
                    throw new NotSupportedException();
            }
        }
 public decimal this[CurrencyCode code]
 {
     get
     {
         switch (code)
         {
             case CurrencyCode.AED: return AED;
             case CurrencyCode.AFN: return AFN;
             case CurrencyCode.ALL: return ALL;
             case CurrencyCode.AMD: return AMD;
             case CurrencyCode.ANG: return ANG;
             case CurrencyCode.AOA: return AOA;
             case CurrencyCode.ARS: return ARS;
             case CurrencyCode.AUD: return AUD;
             case CurrencyCode.AWG: return AWG;
             case CurrencyCode.AZN: return AZN;
             case CurrencyCode.BAM: return BAM;
             case CurrencyCode.BBD: return BBD;
             case CurrencyCode.BDT: return BDT;
             case CurrencyCode.BGN: return BGN;
             case CurrencyCode.BHD: return BHD;
             case CurrencyCode.BIF: return BIF;
             case CurrencyCode.BMD: return BMD;
             case CurrencyCode.BND: return BND;
             case CurrencyCode.BOB: return BOB;
             case CurrencyCode.BOV: throw new NotSupportedException("Provider does not support BOV");
             case CurrencyCode.BRL: return BRL;
             case CurrencyCode.BSD: return BSD;
             case CurrencyCode.BTN: return BTN;
             case CurrencyCode.BWP: return BWP;
             case CurrencyCode.BYR: return BYR;
             case CurrencyCode.BZD: return BZD;
             case CurrencyCode.CAD: return CAD;
             case CurrencyCode.CDF: return CDF;
             case CurrencyCode.CHE: throw new NotSupportedException("Provider does not support CHE");
             case CurrencyCode.CHF: return CHF;
             case CurrencyCode.CHW: throw new NotSupportedException("Provider does not support CHW");
             case CurrencyCode.CLF: return CLF;
             case CurrencyCode.CLP: return CLP;
             case CurrencyCode.CNY: return CNY;
             case CurrencyCode.COP: return COP;
             case CurrencyCode.COU: throw new NotSupportedException("Provider does not support COU");
             case CurrencyCode.CRC: return CRC;
             case CurrencyCode.CUC: return CUC;
             case CurrencyCode.CUP: return CUP;
             case CurrencyCode.CVE: return CVE;
             case CurrencyCode.CZK: return CZK;
             case CurrencyCode.DJF: return DJF;
             case CurrencyCode.DKK: return DKK;
             case CurrencyCode.DOP: return DOP;
             case CurrencyCode.DZD: return DZD;
             case CurrencyCode.EGP: return EGP;
             case CurrencyCode.ERN: return ERN;
             case CurrencyCode.ETB: return ETB;
             case CurrencyCode.EUR: return EUR;
             case CurrencyCode.FJD: return FJD;
             case CurrencyCode.FKP: return FKP;
             case CurrencyCode.GBP: return GBP;
             case CurrencyCode.GEL: return GEL;
             case CurrencyCode.GHS: return GHS;
             case CurrencyCode.GIP: return GIP;
             case CurrencyCode.GMD: return GMD;
             case CurrencyCode.GNF: return GNF;
             case CurrencyCode.GTQ: return GTQ;
             case CurrencyCode.GYD: return GYD;
             case CurrencyCode.HKD: return HKD;
             case CurrencyCode.HNL: return HNL;
             case CurrencyCode.HRK: return HRK;
             case CurrencyCode.HTG: return HTG;
             case CurrencyCode.HUF: return HUF;
             case CurrencyCode.IDR: return IDR;
             case CurrencyCode.ILS: return ILS;
             case CurrencyCode.INR: return INR;
             case CurrencyCode.IQD: return IQD;
             case CurrencyCode.IRR: return IRR;
             case CurrencyCode.ISK: return ISK;
             case CurrencyCode.JMD: return JMD;
             case CurrencyCode.JOD: return JOD;
             case CurrencyCode.JPY: return JPY;
             case CurrencyCode.KES: return KES;
             case CurrencyCode.KGS: return KGS;
             case CurrencyCode.KHR: return KHR;
             case CurrencyCode.KMF: return KMF;
             case CurrencyCode.KPW: return KPW;
             case CurrencyCode.KRW: return KRW;
             case CurrencyCode.KWD: return KWD;
             case CurrencyCode.KYD: return KYD;
             case CurrencyCode.KZT: return KZT;
             case CurrencyCode.LAK: return LAK;
             case CurrencyCode.LBP: return LBP;
             case CurrencyCode.LKR: return LKR;
             case CurrencyCode.LRD: return LRD;
             case CurrencyCode.LSL: return LSL;
             case CurrencyCode.LYD: return LYD;
             case CurrencyCode.MAD: return MAD;
             case CurrencyCode.MDL: return MDL;
             case CurrencyCode.MGA: return MGA;
             case CurrencyCode.MKD: return MKD;
             case CurrencyCode.MMK: return MMK;
             case CurrencyCode.MNT: return MNT;
             case CurrencyCode.MOP: return MOP;
             case CurrencyCode.MRO: return MRO;
             case CurrencyCode.MUR: return MUR;
             case CurrencyCode.MVR: return MVR;
             case CurrencyCode.MWK: return MWK;
             case CurrencyCode.MXN: return MXN;
             case CurrencyCode.MXV: throw new NotSupportedException("Provider does not support MXV");
             case CurrencyCode.MYR: return MYR;
             case CurrencyCode.MZN: return MZN;
             case CurrencyCode.NAD: return NAD;
             case CurrencyCode.NGN: return NGN;
             case CurrencyCode.NIO: return NIO;
             case CurrencyCode.NOK: return NOK;
             case CurrencyCode.NPR: return NPR;
             case CurrencyCode.NZD: return NZD;
             case CurrencyCode.OMR: return OMR;
             case CurrencyCode.PAB: return PAB;
             case CurrencyCode.PEN: return PEN;
             case CurrencyCode.PGK: return PGK;
             case CurrencyCode.PHP: return PHP;
             case CurrencyCode.PKR: return PKR;
             case CurrencyCode.PLN: return PLN;
             case CurrencyCode.PYG: return PYG;
             case CurrencyCode.QAR: return QAR;
             case CurrencyCode.RON: return RON;
             case CurrencyCode.RSD: return RSD;
             case CurrencyCode.RUB: return RUB;
             case CurrencyCode.RWF: return RWF;
             case CurrencyCode.SAR: return SAR;
             case CurrencyCode.SBD: return SBD;
             case CurrencyCode.SCR: return SCR;
             case CurrencyCode.SDG: return SDG;
             case CurrencyCode.SEK: return SEK;
             case CurrencyCode.SGD: return SGD;
             case CurrencyCode.SHP: return SHP;
             case CurrencyCode.SLL: return SLL;
             case CurrencyCode.SOS: return SOS;
             case CurrencyCode.SRD: return SRD;
             case CurrencyCode.SSP: throw new NotSupportedException("Provider does not support SSP");
             case CurrencyCode.STD: return STD;
             case CurrencyCode.SYP: return SYP;
             case CurrencyCode.SZL: return SZL;
             case CurrencyCode.THB: return THB;
             case CurrencyCode.TJS: return TJS;
             case CurrencyCode.TMT: return TMT;
             case CurrencyCode.TND: return TND;
             case CurrencyCode.TOP: return TOP;
             case CurrencyCode.TRY: return TRY;
             case CurrencyCode.TTD: return TTD;
             case CurrencyCode.TWD: return TWD;
             case CurrencyCode.TZS: return TZS;
             case CurrencyCode.UAH: return UAH;
             case CurrencyCode.UGX: return UGX;
             case CurrencyCode.USD: return USD;
             case CurrencyCode.USN: throw new NotSupportedException("Provider does not support USN");
             case CurrencyCode.USS: throw new NotSupportedException("Provider does not support USS");
             case CurrencyCode.UYI: throw new NotSupportedException("Provider does not support UYI");
             case CurrencyCode.UYU: return UYU;
             case CurrencyCode.UZS: return UZS;
             case CurrencyCode.VEF: return VEF;
             case CurrencyCode.VND: return VND;
             case CurrencyCode.VUV: return VUV;
             case CurrencyCode.WST: return WST;
             case CurrencyCode.XAF: return XAF;
             case CurrencyCode.XAG: return XAG;
             case CurrencyCode.XAU: return XAU;
             case CurrencyCode.XBA: throw new NotSupportedException("Provider does not support XBA");
             case CurrencyCode.XBB: throw new NotSupportedException("Provider does not support XBB");
             case CurrencyCode.XBC: throw new NotSupportedException("Provider does not support XBC");
             case CurrencyCode.XBD: throw new NotSupportedException("Provider does not support XBD");
             case CurrencyCode.XCD: return XCD;
             case CurrencyCode.XDR: return XDR;
             case CurrencyCode.XFU: throw new NotSupportedException("Provider does not support XFU");
             case CurrencyCode.XOF: return XOF;
             case CurrencyCode.XPD: return XPD;
             case CurrencyCode.XPF: return XPF;
             case CurrencyCode.XPT: return XPT;
             case CurrencyCode.XSU: throw new NotSupportedException("Provider does not support XSU");
             case CurrencyCode.XTS: throw new NotSupportedException("Provider does not support XTS");
             case CurrencyCode.XUA: throw new NotSupportedException("Provider does not support XUA");
             case CurrencyCode.XXX: throw new NotSupportedException("Provider does not support XXX");
             case CurrencyCode.YER: return YER;
             case CurrencyCode.ZAR: return ZAR;
             case CurrencyCode.ZMW: return ZMW;
             default:
                 throw new NotSupportedException("Provider does not support " + code.ToString());
         }
     }
 }
Пример #49
0
 public static decimal GetTodayExchangeRate(CurrencyCode baseCurrency, CurrencyCode targetCurrency)
 {
     return GetExchangeRate (DateTime.Today, baseCurrency, targetCurrency);
 }
Пример #50
0
        static decimal GetExchangeRateA(DateTime date, CurrencyCode baseCurrency, CurrencyCode targetCurrency)
        {
            if (baseCurrency == targetCurrency)
                return decimal.One;

            var item = ExchangeRate.Queryable.SingleOrDefault (x => x.Date == date && x.Base == baseCurrency &&
                                       x.Target == targetCurrency);

            if (item != null)
                return item.Rate;

            item = ExchangeRate.Queryable.SingleOrDefault (x => x.Date == date && x.Base == targetCurrency &&
                                       x.Target == baseCurrency);

            if (item != null)
                return decimal.One / item.Rate;

            return decimal.Zero;
        }
Пример #51
0
 public static WorldPay WorldPay(this HtmlHelper helper, string installationId, string cartId, string amount, CurrencyCode currency)
 {
     return new WorldPay(helper, installationId, cartId, amount, currency);
 }
 /// <summary>
 /// Converts the specified amount of the specified currecny into TRY
 /// </summary>
 /// <param name="amount"></param>
 /// <param name="fromCurrency"></param>
 /// <returns></returns>
 public Task<ConvertResponseContext> ConvertAsync(decimal amount, CurrencyCode fromCurrency)
 {
     return ConvertAsync(amount, fromCurrency, CurrencyCode.TRY);
 }
Пример #53
0
 /// <summary>
 /// Private constructor
 /// </summary>
 /// <param name="currencyCode">The currency's corresponding <see cref="CurrencyCode"/>.</param>
 private CurrencyInfo(CurrencyCode currencyCode)
 {
     Code = currencyCode;
 }
Пример #54
0
 /// <summary>
 /// Get the <see cref="CurrencyInfo"/> instance for <paramref name="currencyCode"/>.
 /// </summary>
 /// <remarks>
 /// Never returns null.
 /// </remarks>
 /// <param name="currencyCode">The <see cref="CurrencyCode"/> to get the <see cref="CurrencyInfo"/> instance for.</param>
 /// <returns>The <see cref="CurrencyInfo"/> instance for <paramref name="currencyCode"/>.</returns>
 public static CurrencyInfo GetCurrency(CurrencyCode currencyCode)
 {
     return _all[currencyCode];
 }
Пример #55
0
        IEnumerable<CustomerPayment> GetRemainingPayments(int customer, CurrencyCode currency)
        {
            var query = from x in CustomerPayment.Queryable
                    where x.Customer.Id == customer && x.Currency == currency &&
                     	(x.Allocations.Count == 0 || x.Amount > x.Allocations.Sum (y => y.Amount + y.Change))
                    select x;

            return query.ToList ();
        }
Пример #56
0
        public static string ConvertCurrencyCodeToString(CurrencyCode c)
        {
            string result = "USD";

            switch (c)
            {
                case CurrencyCode.AustalianDollar:
                    result = "AUD";
                    break;
                case CurrencyCode.Baht:
                    result = "THB";
                    break;
                case CurrencyCode.BritishPounds:
                    result = "GBP";
                    break;
                case CurrencyCode.CanadianDollar:
                    result = "CAD";
                    break;
                case CurrencyCode.DenmarkKrone:
                    result = "DKK";
                    break;
                case CurrencyCode.Drachma:
                    result = "GRD";
                    break;
                case CurrencyCode.Euro:
                    result = "EUR";
                    break;
                case CurrencyCode.HongKongDollar:
                    result = "HKD";
                    break;
                case CurrencyCode.NewZealandDollar:
                    result = "NZD";
                    break;
                case CurrencyCode.NorwayKrone:
                    result = "NOK";
                    break;
                case CurrencyCode.Peso:
                    result = "MXN";
                    break;
                case CurrencyCode.Ringgit:
                    result = "MYR";
                    break;
                case CurrencyCode.SingaporeDollar:
                    result = "SGD";
                    break;
                case CurrencyCode.SwedishKrona:
                    result = "SEK";
                    break;
                case CurrencyCode.SwissFranc:
                    result = "CHF";
                    break;
                case CurrencyCode.TaiwanDollar:
                    result = "TWD";
                    break;
                case CurrencyCode.UsDollar:
                    result = "USD";
                    break;
                default:
                    result = "USD";
                    break;
            }

            return result;
        }
Пример #57
0
 public static decimal GetTodayExchangeRate(CurrencyCode baseCurrency)
 {
     return GetExchangeRate (DateTime.Today, baseCurrency, WebConfig.BaseCurrency);
 }
 public NewCryptoCurrencyWithdrawal(CurrencyCode currency, decimal amount, string address)
 {
     Currency = currency;
     Amount = amount;
     Address = address;
 }
Пример #59
0
        public JsonResult code_get(string from_val, string to_val)
        {
            double min_v = 0;
            try
            {
                CurrencyData cd = new CurrencyData(CurrencyList.GetCode(from_val), CurrencyList.GetCode(to_val));
                CurrencyCode cc = new CurrencyCode();
                cc.AdjustToLocalTime = true;
                string st1 = CurrencyList.GetCode(from_val);
                string st2 = CurrencyList.GetCode(to_val);
                IList<CurrencyData> list = new List<CurrencyData>(1);
                cc.GetCurrencyData(ref cd);
                 min_v = cd.Rate;
                double max_v = cd.Max;

            }
            catch (Exception)
            {

                throw;
            }
            return Json(min_v, JsonRequestBehavior.AllowGet);
        }
 public GetWalletBalanceMessageBuilder(Guid walletId, CurrencyCode currencyCode)
 {
     _walletId = walletId;
     _currencyCode = Enum.GetName(typeof (CurrencyCode), currencyCode);
 }