internal bool requestAssetPurchase(String token, long assetID, int expectedPrice, CurrencyType currency, String cookies)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://m.roblox.com/Catalog/ProcessPurchase");

            request.KeepAlive = true;
            request.Accept = "text/html, */*; q=0.01";
            request.Headers.Add("Origin", @"https://m.roblox.com");
            request.Headers.Add("X-Requested-With", @"XMLHttpRequest");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
            request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
            request.Referer = "https://m.roblox.com/items/295133189";
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            request.Headers.Set(HttpRequestHeader.Cookie, cookies);
            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;

            string body = @"__RequestVerificationToken=" + token + "&CurrencyType=" + ((currency == CurrencyType.ROBUX) ? "1" : "2") + "&AssetID="+assetID+"&UserAssetOptionID=0&ExpectedPrice="+expectedPrice;
            byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
            request.ContentLength = postBytes.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(postBytes, 0, postBytes.Length);
            stream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (BufferedStream receiveStream = new BufferedStream(response.GetResponseStream()))
            {
                using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    String s = readStream.ReadToEnd();
                    return s.Contains("successfully");
                }
            }
        }
        public ActionResult ConvertCurrency(double amount, CurrencyType convertFrom, CurrencyType convertTo)
        {
            double multiplier = GetMultiplier(convertFrom, convertTo);
            double convertedAmount = amount * multiplier;

            return Json(convertedAmount, JsonRequestBehavior.AllowGet);
        }
        public LimitedPurchaseResponse requestLimitedPurchase(String XRSFToken, int productID, CurrencyType currency, int expectedPrice, int expectedSellerID, int userAssetID, String cookies)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.roblox.com/api/item.ashx?rqtype=purchase&productID=" + productID + "&expectedCurrency=" + ((currency == CurrencyType.ROBUX) ? "1" : "2") + "&expectedPrice=" + expectedPrice + "&expectedSellerID=" + expectedSellerID + "&userAssetID=" + userAssetID);

            request.KeepAlive = true;
            request.Accept = "*/*";
            request.Headers.Add("Origin", @"http://www.roblox.com");
            request.Headers.Add("X-CSRF-TOKEN", XRSFToken);
            request.UserAgent = RobloxUtils.UserAgent;
            request.ContentType = "application/json; charset=utf-8";
            request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
            request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-US,en;q=0.8");
            request.Headers.Set(HttpRequestHeader.Cookie, cookies);

            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;

            string body = @"";
            byte[] postBytes = Encoding.UTF8.GetBytes(body);
            request.ContentLength = postBytes.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(postBytes, 0, postBytes.Length);
            stream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream receiveStream = RobloxUtils.decodeStream(response))
            {
                using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    String s = readStream.ReadToEnd();
                    return JsonConvert.DeserializeObject<LimitedPurchaseResponse>(s);
                }
            }
        }
Exemple #4
0
 public AccountDTO(Int32 accountID, Decimal balance, CurrencyType currency, Int32 client_ClientID)
 {
     this.AccountID = accountID;
     this.Balance = balance;
     this.Currency = currency;
     this.Client_ClientID = client_ClientID;
 }
		public QuerySettings(string origin, string destination = "-", DateTime? departDate = null, DateTime? returnDate = null, CurrencyType currency = CurrencyType.RUB)
            : this(origin, destination)
		{
			Currency = currency;
			DepartDate = departDate;
			ReturnDate = returnDate;
        }
 public static void RaiseRateChanging(CurrencyType currencyRiseChanger)
 {
     ((System.Collections.Generic.IEnumerable<CurrencyWapper>)CurrencyTable).ForEach<CurrencyWapper>(delegate(CurrencyWapper p)
     {
         p.RaiseRateChanged();
     });
 }
Exemple #7
0
        public static decimal ConvertTo(decimal fromAmount, CurrencyType fromCurrencyType, CurrencyType toCurrencyType, Currency[] currencies)
        {
            if (fromCurrencyType == toCurrencyType)
                return fromAmount;

            if ((fromCurrencyType != CurrencyType.CZK && currencies.All(c => c.CurrencyType != fromCurrencyType)) ||
                toCurrencyType != CurrencyType.CZK && currencies.All(c => c.CurrencyType != toCurrencyType))
            {
                throw new Exception(String.Format(ValidationResource.Currency_CannotProccessCurrencyChange_ErrorMessage, fromCurrencyType, toCurrencyType));
            }

            decimal amountTo = fromAmount;
            Currency currency;

            // Převod konta na CZK
            if (fromCurrencyType != CurrencyType.CZK)
            {
                currency = currencies.Single(c => c.CurrencyType == fromCurrencyType);
                amountTo = amountTo * currency.ExchangeRateToCZK;
            }

            // Převod konta na aktuální měnu
            if (toCurrencyType != CurrencyType.CZK)
            {
                currency = currencies.Single(c => c.CurrencyType == toCurrencyType);
                amountTo = amountTo / currency.ExchangeRateToCZK;
            }

            return amountTo;
        }
 public PaymentTransactionConfirmed(int paymentTransactionID,string txID, int confirmations, CurrencyType currencyType, int byUserID = 0)
 {
     this.PaymentTransactionID = paymentTransactionID;
     this.TxID = txID;
     this.Confirmations = confirmations;
     this.Currency = currencyType;
     this.ByUserID = byUserID;
 }
Exemple #9
0
        public CreateAccount(CurrencyType currency, int userID)
        {
            Check.Argument.IsNotNegativeOrZero(userID, "userID");
            Check.Argument.IsNotNull(currency, "currency");

            this.Currency = currency;
            this.UserID = userID;
        }
Exemple #10
0
			public override decimal GetRate(CurrencyType @from, CurrencyType to) {
				if(ExchangeRates.ContainsKey(@from) && ExchangeRates[@from].ContainsKey(to))
					return ExchangeRates[@from][to];
				if(ExchangeRates.ContainsKey(to) && ExchangeRates[to].ContainsKey(@from))
					return 1m / ExchangeRates[to][@from];

				throw new UnknownExchangeRateException(String.Format("Exchange rate between '{0}' and '{1}' not known", @from.Code, to.Code));
			}
        public FixedFeeCurrencyWallet(decimal entryFixedFee, decimal exitFixedFee, CurrencyType currencyType, IExchange exchange)
        {
            _entryFixedFee = entryFixedFee;
            _exitFixedFee = exitFixedFee;
            Currency = currencyType;

            _exchange = exchange;
        }
        public PercentageFeeCurrencyWallet(decimal entryPercentFee, decimal exitPercentFee, CurrencyType currencyWallet, IExchange exchange)
        {
            _exchange = exchange;
            _entryPercentFee = entryPercentFee;
            _exitPercentFee = exitPercentFee;

            Currency = currencyWallet;
        }
        public GeneratePaymentAddress(int userID, CurrencyType currency)
        {
            Check.Argument.IsNotNegativeOrZero(userID, "userID");
            Check.Argument.IsNotNegativeOrZero((int)currency, "currency");

            this.UserID = userID;
            this.Currency = currency;
        }
        public TinyMoneyManager.CurrencyConverterByWebService.Currency SwitchCurrency(CurrencyType localVer)
        {
            TinyMoneyManager.CurrencyConverterByWebService.Currency cNY = TinyMoneyManager.CurrencyConverterByWebService.Currency.CNY;
            switch (localVer)
            {
                case CurrencyType.CNY:
                    return cNY;

                case CurrencyType.USD:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.USD;

                case CurrencyType.NTD:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.TWD;

                case CurrencyType.HKD:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.HKD;

                case CurrencyType.AUD:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.AUD;

                case CurrencyType.EUR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.EUR;

                case CurrencyType.JPY:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.JPY;

                case CurrencyType.GBP:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.GBP;

                case CurrencyType.MYR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.MYR;

                case CurrencyType.SGD:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.SGD;

                case CurrencyType.THP:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.THB;

                case CurrencyType.PKR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.PKR;

                case CurrencyType.INR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.INR;

                case CurrencyType.KRW:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.KRW;

                case CurrencyType.IDR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.IDR;

                case CurrencyType.BYR:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.RUB;

                case CurrencyType.PHP:
                    return TinyMoneyManager.CurrencyConverterByWebService.Currency.PHP;
            }
            return cNY;
        }
Exemple #15
0
 public VirtualCoinDepositCompleted(int depositID, int depositUserID, int accountID, decimal depositAmount, CurrencyType currency, int byUserID)
 {
     this.DepositID = depositID;
     this.DepositUserID = depositUserID;
     this.Currency = currency;
     this.AccountID = accountID;
     this.DepositAmount = depositAmount;
     this.ByUserID = byUserID;
 }
Exemple #16
0
 public AccountChangedByCancelDeposit(int userID, int accountID, decimal depositAmount, int depositID, CurrencyType currency)
 {
     this.UserID = userID;
     this.AccountID = accountID;
     this.DepositID = depositID;
     this.DepositAmount = depositAmount;
     this.Currency = currency;
     this.ModifyType = Convert.ToInt32(AccountModifyType.Deposit.ToString("D") + currency.ToString("D"));
 }
 //user id 为兼容恒星币人工充值,以后开通自动就无保留必要了
 public PaymentTransactionCreated(string txid, string address, CurrencyType currency, decimal amount, ReceivePaymentTransaction ptxEntity, int userID = 0)
 {
     this.UserID = userID;
     this.PtxEntity = ptxEntity;
     this.TxID = txid;
     this.Currency = currency;
     this.Address = address;
     this.Amount = amount;
 }
Exemple #18
0
        public ActionResult InsideTransferSuccess(CurrencyType currency, string orderID)
        {
            var transfer = IoC.Resolve<IInsideTransferQuery>().GetInsideTransferBySequenceNo(orderID, TransactionState.Success, currency);
            var user = IoC.Resolve<IUserQuery>().GetUserByID(transfer.ToUserID);
            ViewBag.Transfer = transfer;
            ViewBag.Receiver = user;

            return View("InsideTransferSuccess");
        }
 public static decimal GetGlobleMoneyFrom(CurrencyType fromCurrency, decimal money)
 {
     CurrencyType defaultCurrency = AppSetting.Instance.DefaultCurrency;
     if (defaultCurrency == fromCurrency)
     {
         return money;
     }
     return (money * fromCurrency.GetConversionRateTo(defaultCurrency));
 }
Exemple #20
0
 public double ConvertCurrency(CurrencyType from, CurrencyType to, double amount)
 {
     if (from == to && to == CurrencyType.AustralianDollar)
     {
         return amount;
     }
     throw new
         NotSupportedException("Currency conversion for non-Australian dollars is not supported");
 }
Exemple #21
0
		public static string GetValueString(decimal value, CurrencyType currency, CultureInfo cultureInfo)
		{
			if(value == 0)
			{
				return null;
			}

			return value.ToString("### ### ### ###", cultureInfo) + CurrencyName.Names[currency];
		}
Exemple #22
0
        public InsideTransferModel GetInsideTransferBySequenceNo(string seqNo, TransactionState txstate, CurrencyType currency)
        {
            Check.Argument.IsNotEmpty(seqNo, "seqNo");

            return this.Context.Sql(getInsideTransferBySequenceNo_Sql.FormatWith(currency.ToString()))
                               .Parameter("@seqNo", seqNo)
                               .Parameter("@state", txstate)
                               .QuerySingle<InsideTransferModel>();
        }
 public InsideTransferTransactionCreated(int fromUserID, int toUserID, CurrencyType currency, decimal amount, PayWay payway, string description, InsideTransferTransaction tx)
 {
     this.FromUserID = fromUserID;
     this.ToUserID = toUserID;
     this.Currency = currency;
     this.Amount = amount;
     this.PayWay = payway;
     this.Description = description;
     this.TransactionEntity = tx;
 }
        public CreatePaymentAddress(int userID, string paymentAddress, CurrencyType currency)
        {
            Check.Argument.IsNotNegativeOrZero(userID, "userID");
            Check.Argument.IsNotEmpty(paymentAddress, "paymentAddress");
            Check.Argument.IsNotNegativeOrZero((int)currency, "currency");

            this.UserID = userID;
            this.PaymentAddress = paymentAddress;
            this.Currency = currency;
        }
 public static int GetPossion(CurrencyType currency)
 {
     if (!CurrencyPossion.ContainsKey(currency))
     {
         int num = (int)currency;
         CurrencyPossion[currency] = num;
         return num;
     }
     return CurrencyPossion[currency];
 }
        public static int Consume( Mobile from, int amount, bool bankbox, CurrencyType type, bool recurse )
        {
            Container[] containers = null;

            if ( bankbox )
                containers = new Container[]{ from.Backpack, from.BankBox };
            else
                containers = new Container[]{ from.Backpack };

            return Consume( containers, amount, type, recurse );
        }
Exemple #27
0
 public VirtualCoinDepositCreated(int userID, int accountID, string txid, CurrencyType currency, decimal amount, decimal fee, string memo, VirtualCoinDeposit deposit)
 {
     this.UserID = userID;
     this.AccountID = accountID;
     this.TxID = txid;
     this.Currency = currency;
     this.DepositAmount = amount;
     this.DepositFee = fee;
     this.Memo = memo;
     this.DepositEntity = deposit;
 }
Exemple #28
0
        public CreateInsideTransfer(int fromUserID, int toUserID, CurrencyType currency, decimal amount, string description)
        {
            Check.Argument.IsNotNegativeOrZero(fromUserID, "fromUserID");
            Check.Argument.IsNotNegativeOrZero(toUserID, "toUserID");
            Check.Argument.IsNotNegativeOrZero((int)currency, "currency");

            this.FromUserID = fromUserID;
            this.ToUserID = toUserID;
            this.Currency = currency;
            this.Amount = amount;
            this.Description = description;
        }
Exemple #29
0
        public AuthorizeCustomerServiceUserDepositAmount(int authTo, CurrencyType currency, decimal amount, int currentUserID)
        {
            Check.Argument.IsNotNegativeOrZero(authTo, "authTo");
            Check.Argument.IsNotNegativeOrZero((int)currency, "currency");
            Check.Argument.IsNotNegativeOrZero(amount, "amount");
            Check.Argument.IsNotNegativeOrZero(currentUserID, "currentUserID");

            this.UserID = authTo;
            this.Currency = currency;
            this.AuthrizeAmount = amount;
            this.AuthrizeBy = currentUserID;
        }
Exemple #30
0
        public ActionResult InsideTransferConfirm(CurrencyType currency, string orderID)
        {
            var transfer = IoC.Resolve<IInsideTransferQuery>().GetInsideTransferBySequenceNo(orderID, TransactionState.Pending, currency);
            ViewBag.Transfer = transfer;

            if (transfer != null)
            {
                var user = IoC.Resolve<IUserQuery>().GetUserByID(transfer.ToUserID);
                ViewBag.Receiver = user;
            }
            return View("InsideConfirm");
        }
Exemple #31
0
 /// <summary>
 /// Get symbol crosses used for calculating pip values
 /// </summary>
 /// <param name="basecurrency"></param>
 /// <returns></returns>
 public static string GetPipValueSymbolCrosses(CurrencyType basecurrency, ISecurity basesecurity)
 {
     //Check for forex security
     if (basesecurity.Type == SecurityType.Forex)
     {
         string ends = basesecurity.Name.Substring(3, 3);
         return(basecurrency.ToString() + ends);
     }
     else if (basesecurity.Type == SecurityType.CFD)
     {
         return(basecurrency.ToString() + basesecurity.Currency.ToString());
     }
     else
     {
         return(string.Empty);
     }
 }
Exemple #32
0
        public static void HandleVendorPurchase(WorldSession session, ClientVendorPurchase vendorPurchase)
        {
            VendorInfo vendorInfo = session.Player.SelectedVendorInfo;

            if (vendorInfo == null)
            {
                return;
            }

            EntityVendorItemModel vendorItem = vendorInfo.GetItemAtIndex(vendorPurchase.VendorIndex);

            if (vendorItem == null)
            {
                return;
            }

            Item2Entry itemEntry      = GameTableManager.Instance.Item.GetEntry(vendorItem.ItemId);
            float      costMultiplier = vendorInfo.BuyPriceMultiplier * vendorPurchase.VendorItemQty;

            // do all sanity checks before modifying currency
            var currencyChanges = new List <(CurrencyType CurrencyTypeId, ulong CurrencyAmount)>();

            for (int i = 0; i < itemEntry.CurrencyTypeId.Length; i++)
            {
                CurrencyType currencyId = (CurrencyType)itemEntry.CurrencyTypeId[i];
                if (currencyId == CurrencyType.None)
                {
                    continue;
                }

                ulong currencyAmount = (ulong)(itemEntry.CurrencyAmount[i] * costMultiplier);
                if (!session.Player.CurrencyManager.CanAfford(currencyId, currencyAmount))
                {
                    return;
                }

                currencyChanges.Add((currencyId, currencyAmount));
            }

            foreach ((CurrencyType currencyTypeId, ulong currencyAmount) in currencyChanges)
            {
                session.Player.CurrencyManager.CurrencySubtractAmount(currencyTypeId, currencyAmount);
            }

            session.Player.Inventory.ItemCreate(itemEntry.Id, vendorPurchase.VendorItemQty * itemEntry.BuyFromVendorStackCount);
        }
Exemple #33
0
        private string CurrencyStringMap(CurrencyType type)
        {
            switch (type)
            {
            case CurrencyType.RON:
                return("RON");

            case CurrencyType.USD:
                return("USD");

            case CurrencyType.EUR:
                return("EUR");

            default:
                return("");
            }
        }
Exemple #34
0
        public async Task <IActionResult> OnPostAsync(Guid?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            CurrencyType = await _context.CurrencyTypes.FindAsync(id);

            if (CurrencyType != null)
            {
                CurrencyType.IsDeleted = true;
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
Exemple #35
0
        public async Task <RaveResponse <ExchangeRateRes> > GetExchangeRate(CurrencyType originalCurrency, CurrencyType destinationCurrency, decimal amount)
        {
            var payload = new
            {
                SECKEY               = Config.SecretKey,
                origin_currency      = Util.GetCurrencyStr(originalCurrency),
                destination_currency = Util.GetCurrencyStr(destinationCurrency),
                amount
            };

            var requestBody = new HttpRequestMessage(HttpMethod.Post, Endpoints.ExchangeRates)
            {
                Content = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json")
            };

            return(await RaveApiRequest.Request(requestBody));
        }
Exemple #36
0
        public int GetCurrency(CurrencyType currency)
        {
            switch (currency)
            {
            case CurrencyType.Gold:
                return(Credits);

            case CurrencyType.Fame:
                return(CurrentFame);

            case CurrencyType.Tokens:
                return(Tokens);

            default:
                return(0);
            }
        }
Exemple #37
0
 public bool PopulateDataSource(CurrencyType currencyType, DateTime dateFrom, DateTime dateTo)
 {
     try
     {
         var currencyDataFromRange = ServiceConfiguration.DataProvider.GetCurrencyValueFromRange(currencyType, dateFrom, dateTo);
         CurrencyRepository.RemoveAll(currencyType);
         foreach (var currencyItem in currencyDataFromRange)
         {
             CurrencyRepository.Add(currencyItem);
         }
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Exemple #38
0
        /// <summary>
        /// KRW_TYPE
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string ToReversedCurrencyPair(this CurrencyType type)
        {
            if (type == CurrencyType.Bitcoin)
            {
                return("krw_btc");
            }
            else if (type == CurrencyType.Ethereum)
            {
                return("krw_eth");
            }
            else if (type == CurrencyType.EthereumClassic)
            {
                return("krw_etc");
            }

            throw new NotImplementedException($"{type}");
        }
        //Im asumming that all the external apis return the same structure
        private async Task <Exchange> FillCurrency(HttpResponseMessage response, CurrencyType currency)
        {
            Exchange exchange = new Exchange();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = await response.Content.ReadAsStringAsync();

                //the response from the extenal api doesnt have a valid key/value pair, only the value, hence the parse into JObject

                JArray jArray = JArray.Parse(content);
                exchange.BuyValue  = (double)jArray[0];
                exchange.SellValue = (double)jArray[1];
                exchange.Currency  = currency;
            }
            return(exchange);
        }
Exemple #40
0
        public static void HandleVendorSell(WorldSession session, ClientVendorSell vendorSell)
        {
            VendorInfo vendorInfo = session.Player.SelectedVendorInfo;

            if (vendorInfo == null)
            {
                return;
            }

            ItemInfo info = session.Player.Inventory.GetItem(vendorSell.ItemLocation).Info;

            if (info == null)
            {
                return;
            }

            float costMultiplier = vendorInfo.SellPriceMultiplier * vendorSell.Quantity;

            // do all sanity checks before modifying currency
            var currencyChange = new List <(CurrencyType CurrencyTypeId, ulong CurrencyAmount)>();

            for (int i = 0; i < info.Entry.CurrencyTypeIdSellToVendor.Length; i++)
            {
                CurrencyType currencyId = (CurrencyType)info.Entry.CurrencyTypeIdSellToVendor[i];
                if (currencyId == CurrencyType.None)
                {
                    continue;
                }

                ulong currencyAmount = (ulong)(info.Entry.CurrencyAmountSellToVendor[i] * costMultiplier);
                currencyChange.Add((currencyId, currencyAmount));
            }

            // TODO Insert calculation for cost here

            foreach ((CurrencyType currencyTypeId, ulong currencyAmount) in currencyChange)
            {
                session.Player.CurrencyManager.CurrencyAddAmount(currencyTypeId, currencyAmount);
            }

            // TODO Figure out why this is showing "You deleted [item]"
            Item soldItem = session.Player.Inventory.ItemDelete(vendorSell.ItemLocation);

            BuybackManager.Instance.AddItem(session.Player, soldItem, vendorSell.Quantity, currencyChange);
        }
Exemple #41
0
        /// <summary>
        /// Synchronizes the cash positions compared to current account.
        /// </summary>
        /// <param name="currency">The currency.</param>
        /// <param name="amount">The amount.</param>
        private void SyncFunds(CurrencyType currency, decimal amount)
        {
            lock (_locker)
            {
                //Get all holders
                decimal baseamount = GetBaseAccount(currency).TotalCash;
                _log.Info($"Syncing funds for currency {currency} and received amount {amount}. Current base amount = {baseamount}, currently allocated = {TotalAllocatedCash}");

                //If we have a lower amount
                if (amount > TotalCash || TotalAllocatedCash < amount)
                {
                    decimal adjust = amount - TotalCash;
                    GetBaseAccount(currency).AddCash(new SettledCash(adjust));
                    _log.Info($"Adjusted current base account with amount {adjust}");
                }
                //If we have more allocated than currently in funds, this should be reset proportionally
                else if (TotalAllocatedCash > amount)
                {
                    //Calculate proportions
                    _log.Warn($"The base account balance is lower than we have allocated in amount (base = {amount}, allocated = {TotalAllocatedCash}");
                    Dictionary <string, decimal> proportion = new Dictionary <string, decimal>();
                    _cashknown.Where(x => x.Key != BaseAccount).ForEach(x =>
                    {
                        decimal allocated = x.Value.Sum(funds => _conversion.Convert(funds.Value.TotalCash, funds.Value.BaseCurrency, currency));
                        proportion.Add(x.Key, allocated / amount);
                    });

                    //Adjust funds
                    proportion.ForEach(x =>
                    {
                        decimal current  = _cashknown[x.Key][currency].TotalCash;
                        decimal adjusted = current - (current * x.Value);
                        _cashknown[x.Key][currency].AddCash(new SettledCash(adjusted));
                        _log.Warn($"Adjusting funds for quant fund with id {x.Key} current = {current} new amount = {current + adjusted}, adjusted amount = {adjusted}");
                    });
                }
                else
                {
                    _log.Info($"Funds are all in sync, no actions needed");
                }

                //Logging
                _log.Info($"Syncing of funds finished, TotalFunds = {TotalCash}, TotalAllocatedFunds = {TotalAllocatedCash}, #QuantFunds = {_cashknown.Count - 1}, TotalUnallocatedFunds = {TotalUnallocatedCash}");
            }
        }
Exemple #42
0
        private void DropItemByID(uint _id, uint _killer, CurrencyType _currency = CurrencyType.None, uint _value = 0)
        {
            var itemInfo = Database.ServerDatabase.Context.ItemInformation.GetById(_id);

            if (itemInfo != null)
            {
                var loc = GetValidLocation();
                if (Map.IsValidItemLocation(loc))
                {
                    var coItem = new Structures.ConquerItem((uint)Map.ItemCounter.Counter, itemInfo);
                    if ((coItem.EquipmentSort == 1 || coItem.EquipmentSort == 3 || coItem.EquipmentSort == 4) && coItem.BaseItem.TypeDesc != "Earring")
                    {
                        coItem.Color = (byte)Common.Random.Next(3, 7);
                    }
                    if (coItem.EquipmentSort > 0 && coItem.EquipmentQuality > 3)
                    {
                        coItem.Durability = (ushort)Common.Random.Next(coItem.MaximumDurability);
                    }
                    else
                    {
                        coItem.Color = 3;
                    }
                    if (Common.PercentSuccess(Constants.CHANCE_PLUS))
                    {
                        coItem.Plus = 1;
                    }

                    if (coItem.IsWeapon)
                    {
                        if (Common.PercentSuccess(Constants.SOCKET_DROP))
                        {
                            coItem.Gem1 = 255;

                            if (Common.PercentSuccess(Constants.SOCKET_DROP))
                            {
                                coItem.Gem2 = 255;
                            }
                        }
                    }

                    var groundItem = new GroundItem(coItem, coItem.UniqueID, loc, Map, _killer, _currency, _value);
                    groundItem.AddToMap();
                }
            }
        }
Exemple #43
0
 private void Show(CurrencyType currencyType)
 {
     if (UniversalInputManager.UsePhoneUI != null)
     {
         this.ShowImmediate(currencyType);
     }
     else
     {
         bool flag = currencyType != CurrencyType.NONE;
         if (!DemoMgr.Get().IsCurrencyEnabled())
         {
             flag = false;
         }
         if (flag)
         {
             if ((this.m_state == State.SHOWN) || (this.m_state == State.ANIMATE_IN))
             {
                 this.ShowCurrencyType(currencyType);
             }
             else
             {
                 this.m_state = State.ANIMATE_IN;
                 base.gameObject.SetActive(true);
                 object[]  args      = new object[] { "amount", 1f, "delay", 0f, "time", 0.25f, "easeType", iTween.EaseType.easeOutCubic, "oncomplete", "ActivateCurrencyFrame", "oncompletetarget", base.gameObject };
                 Hashtable hashtable = iTween.Hash(args);
                 iTween.Stop(base.gameObject);
                 iTween.FadeTo(base.gameObject, hashtable);
                 this.ShowCurrencyType(currencyType);
             }
         }
         else if ((this.m_state == State.HIDDEN) || (this.m_state == State.ANIMATE_OUT))
         {
             this.ShowCurrencyType(currencyType);
         }
         else
         {
             this.m_state = State.ANIMATE_OUT;
             object[]  objArray2  = new object[] { "amount", 0f, "delay", 0f, "time", 0.25f, "easeType", iTween.EaseType.easeOutCubic, "oncomplete", "DeactivateCurrencyFrame", "oncompletetarget", base.gameObject };
             Hashtable hashtable2 = iTween.Hash(objArray2);
             iTween.Stop(base.gameObject);
             iTween.FadeTo(base.gameObject, hashtable2);
             this.ShowCurrencyType(currencyType);
         }
     }
 }
Exemple #44
0
 public NBURatesSource(string name, Uri baseSource, Dictionary <string, string> routeParams)
 {
     BaseSource  = baseSource;
     RouteParams = routeParams;
     if (routeParams != null)
     {
         RouteParamString = routeParams.ToList().Aggregate("?", (key, value) => key + "=" + value + "&");
     }
     else
     {
         RouteParamString = string.Empty;
     }
     BaseCurrency = CurrencyType.UAH;
     Name         = name;
     isInited     = true;
     Id           = Guid.NewGuid();
     BaseCurrency = CurrencyType.UAH;
 }
Exemple #45
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (CurrencyType.Length != 0)
            {
                hash ^= CurrencyType.GetHashCode();
            }
            if (Price != 0)
            {
                hash ^= Price.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemple #46
0
        public Balance GetBalanceFor(CurrencyType currencyType)
        {
            if (currencyType == CurrencyType.Money)
            {
                var accountMoney = new MoneyAccountDecorator(this);

                return(accountMoney.Balance);
            }

            if (currencyType == CurrencyType.Token)
            {
                var accountToken = new TokenAccountDecorator(this);

                return(accountToken.Balance);
            }

            throw new ArgumentException(nameof(currencyType));
        }
 static void LoadingFromBinary(out Dictionary <CurrencyType, uint> loadedWallet)
 {
     loadedWallet = new Dictionary <CurrencyType, uint>();
     using (FileStream fs = File.OpenRead(filePathBin))
         using (BinaryReader reader = new BinaryReader(fs))
         {
             // Get count.
             int count = reader.ReadInt32();
             // Read in all pairs.
             for (int i = 0; i < count; i++)
             {
                 CurrencyType key   = (CurrencyType)reader.ReadInt32();
                 uint         value = reader.ReadUInt32();
                 loadedWallet.Add(key, value);
             }
         }
     Debug.Log("Loaded from binary file " + filePathBin);
 }
        /// <summary>
        /// 当前行情
        /// </summary>
        /// <param name="currency"></param>
        /// <returns></returns>
        public static TickerModel GetTicker(CurrencyType currency)
        {
            var json = string.Empty;
            var url  = BaseUrl + $"ticker?currency={currency}";

            try
            {
                json = url.GetJsonFromUrl();
                var model = JObject.Parse(json)["ticker"].ToObject <TickerModel>();
                model.Date = JObject.Parse(json)["date"].ToObject <long>();
                return(model);
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat($"Response:{json},Parameters:{url},Ex:{ex}");
            }
            return(new TickerModel());
        }
Exemple #49
0
        private static TimeSpan m_MaxBTCQueryTime = new TimeSpan(1, 0, 0); // Max query of every hour

        /// <summary>
        /// Gets the exchange rate for a given currency relative to USD
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static decimal GetExchangeRate(CurrencyType target)
        {
            decimal exchangeRate = 1;

            switch (target)
            {
            case CurrencyType.USD:
                exchangeRate = 1;
                break;

            case CurrencyType.BTC:
                // get BTC usd price
                exchangeRate = GetBTCPrice();
                break;
            }

            return(exchangeRate);
        }
Exemple #50
0
        public static void CheckCache(DateTime date, CurrencyType currency, decimal value)
        {
            var key = $"{date}{currency}";

            if (Cache.ContainsKey(key))
            {
                var cacheValue = Cache[key];

                if (cacheValue != value)
                {
                    throw new InvalidOperationException($"Kurs dla {currency} z dnia {date} jest sprzeczny: {cacheValue} != {value}");
                }

                return;
            }

            Cache.Add(key, value);
        }
Exemple #51
0
 public bool checkCurrencyType_Select_IsMater(Session session, string currencyTypeId, bool isMaster)
 {
     try
     {
         CurrencyType currencyType = session.FindObject <CurrencyType>(
             CriteriaOperator.And(
                 new BinaryOperator("CurrencyTypeId", currencyTypeId, BinaryOperatorType.Equal),
                 new BinaryOperator("IsMaster", isMaster, BinaryOperatorType.Equal),
                 new BinaryOperator("RowStatus", Utility.Constant.ROWSTATUS_ACTIVE, BinaryOperatorType.Equal)
                 ));
         if (currencyType != null)
         {
             return(true);
         }
         return(false);
     }
     catch (Exception) { throw; }
 }
Exemple #52
0
        /// <summary>
        /// 获取未成交或部份成交的买单和卖单,每次请求返回pageSize小于等于10条记录
        /// </summary>
        /// <param name="currency">交易类型(目前仅支持btc_cny/ltc_cny/eth_cny/eth_btc/etc_cny/bts_cny/eos_cny/bcc_cny/qtum_cny)</param>
        /// <param name="pageIndex">当前页数</param>
        /// <param name="pageSize">每页数量</param>
        /// <returns></returns>
        public static List <OrderModel> GetUnfinishedOrdersIgnoreTradeType(CurrencyType currency, int pageIndex, int pageSize)
        {
            var json   = string.Empty;
            var method = "getUnfinishedOrdersIgnoreTradeType";
            var url    = BaseUrl + method;

            try
            {
                var queryString = new { method, GetApiKey().accesskey, currency, pageIndex, pageSize }.ToQueryString();
                json = url.MakeUrl(queryString, GetApiKey().secretkey).GetJsonFromUrl();
                return(JArray.Parse(json).ToObject <List <OrderModel> >());
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat($"Response:{json},Parameters:{url},Ex:{ex}");
            }
            return(new List <OrderModel>());
        }
Exemple #53
0
        /// <summary>
        /// 获取委托买单或卖单
        /// </summary>
        /// <param name="orderId">委托挂单号</param>
        /// <param name="currency">交易类型(目前仅支持btc_cny/ltc_cny/eth_cny/eth_btc/etc_cny/bts_cny/eos_cny/bcc_cny/qtum_cny)</param>
        /// <returns></returns>
        public static OrderModel GetOrder(string orderId, CurrencyType currency)
        {
            var json   = string.Empty;
            var method = "getOrder";
            var url    = BaseUrl + method;

            try
            {
                var queryString = new { method, GetApiKey().accesskey, id = orderId, currency }.ToQueryString();
                json = url.MakeUrl(queryString, GetApiKey().secretkey).GetJsonFromUrl();
                return(json.FromJSON <OrderModel>());
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat($"Response:{json},Parameters:{url},Ex:{ex}");
            }
            return(new OrderModel());
        }
Exemple #54
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (CurrencyType != 0)
            {
                hash ^= CurrencyType.GetHashCode();
            }
            if (Usage != 0L)
            {
                hash ^= Usage.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        /// <summary>
        /// 转换为货币
        /// </summary>
        /// <param name="param">带转换的金额</param>
        /// <param name="currencyType">货币类型,默认人民币</param>
        /// <returns></returns>
        public static string ConvertToCurrency(this decimal param, CurrencyType currencyType = null)
        {
            if (currencyType == null)
            {
                currencyType = CurrencyType.Cny;
            }

            IEnumerable <ICurrencyProvider> list =
                new ServiceProvider().GetServices <ICurrencyProvider>();
            var provider = list.FirstOrDefault(x => x.GetCurrencyType.Equals(currencyType));

            if (provider == null)
            {
                throw new BusinessException("暂不支持当前货币转换");
            }

            return(provider.ConvertToCurrency(param));
        }
Exemple #56
0
        public TradeImpl(Trade copytrade)
        {
            // copy constructor, for copying using by-value (rather than by default of by-reference)
            Id         = copytrade.Id;
            _cur       = copytrade.Currency;
            Security   = copytrade.Security;
            Exchange   = copytrade.Exchange;
            _accountid = copytrade.AccountName;
            Symbol     = copytrade.Symbol;
            Direction  = copytrade.Direction;
            Commission = copytrade.Commission;
            AgentId    = copytrade.AgentId;

            Xsize  = copytrade.Xsize;
            Xprice = copytrade.Xprice;
            Xtime  = copytrade.Xtime;
            Xdate  = copytrade.Xdate;
        }
Exemple #57
0
        public override double ConvertCurrency(double startingAmount, CurrencyType convertedCurrencyType)
        {
            double finalAmount = 0.0;

            if (convertedCurrencyType == CurrencyType.USD)
            {
                return(finalAmount = 1.54 * startingAmount);
            }
            else if (convertedCurrencyType == CurrencyType.Pounds)
            {
                return(finalAmount = startingAmount);
            }
            else if (convertedCurrencyType == CurrencyType.USD)
            {
                return(finalAmount = 1.35 * startingAmount);
            }
            return(0);
        }
        public bool Withdraw(CurrencyType currency, int amount)
        {
            if (amount <= (CurrencyType.Gold == currency ? Gold : Tokens))
            {
                if (CurrencyType.Gold == currency)
                {
                    Gold -= amount;
                }
                else
                {
                    Tokens -= amount;
                }

                return(true);
            }

            return(false);
        }
Exemple #59
0
 public Customer(Guid guid, string name, long contact, CurrencyType currency, string shortName, string email, string firstName, string lastName, string url, ICollection <CustomerSubscriptionDetails> subscription, CustomerLoginDetails loginDetails, Partner partner, CustomerAddress address, string role)
     : this()
 {
     CustomerId      = guid;
     CompanyName     = name;
     PrimaryContact  = contact;
     Currency        = currency;
     ShortName       = shortName;
     Email           = email;
     FirstName       = firstName;
     LastName        = lastName;
     WebsiteUrl      = url;
     Subscriptions   = subscription;
     LoginDetails    = loginDetails;
     Partner         = partner;
     CustomerAddress = address;
     Role            = role;
 }
        public void HomeLoanConstructor_WhenInitializedByConstructor_PropertiesAreSetCorrectly()
        {
            // Arrange
            decimal      loanAmount       = 1000;
            decimal      loanInterestRate = 3.5m;
            int          loanTerm         = 5;
            CurrencyType loanCurrency     = CurrencyType.UsDollars;


            // Act
            var loan = new HomeLoan(loanAmount, loanTerm, loanInterestRate, loanCurrency);

            // Assert
            Assert.AreEqual(loanAmount, loan.Principal, "Loan amount not set correctly by constructor");
            Assert.AreEqual(loanTerm, loan.Term, "Loan term not set correctly by constructor");
            Assert.AreEqual(loanInterestRate, loan.InterestRatePercentage, "Loan interest rate not set correctly by constructor");
            Assert.AreEqual(loanCurrency, loan.Currency, "Loan currency type not set correctly by constructor");
        }