public static async Task <RequestStatus> WithdrawCryptoCurrencyAsync(string units, string address, string destinaion, CurrencyType currency) { if (currency == CurrencyType.XRP) { int xrpDestination = 0; int.TryParse(destinaion, out xrpDestination); var request = new XRPWithdrawalRequest { apiKey = _apiKey, secretKey = _apiSecretKey, units = units, address = address, currency = currency.ToString(), destination = xrpDestination }; return(await RestClient.Instance.PostAsync <XRPWithdrawalRequest, RequestStatus>(PrivateAPI.Cancel, request)); } else { var request = new CryptoCurrencyWithdrawalRequest { apiKey = _apiKey, secretKey = _apiSecretKey, units = units, address = address, currency = currency.ToString(), destination = destinaion }; return(await RestClient.Instance.PostAsync <CryptoCurrencyWithdrawalRequest, RequestStatus>(PrivateAPI.Cancel, request)); } }
/// <summary> /// Request to create new invoice with preset checkout currency /// </summary> /// <param name="itemName">Name of an item or service.</param> /// <param name="amount">Invoice amount</param> /// <param name="currency">Invoice currency</param> /// <param name="language">Language of the checkout page</param> /// <param name="order_id">Order ID for your accounting purposes</param> /// <param name="item_description">Description of an item or service.</param> /// <param name="success_url">An URL to which users will be redirected after a successful payment</param> /// <param name="failed_url">An URL to which users will be redirected after a cancelled or failed payment</param> /// <returns></returns> public async Task <InvoiceWithSign> CreateInvoice(string itemName, string amount = "0.0015", CurrencyType currency = CurrencyType.bitcoin, LangPayment language = LangPayment.ru, string order_id = "", string item_description = "", string success_url = "", string failed_url = "") { if (merchant_id.IsNullOrWhiteSpaces() || secret_hash.IsNullOrWhiteSpaces()) { throw new ApiFailed($"{nameof(merchant_id)} or {nameof(secret_hash)} is empty or null"); } try { using (HttpClient requestClient = HttpCreator.Create()) { #region PostData var postContent = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("merchant_id", merchant_id), new KeyValuePair <string, string>("item_name", itemName), new KeyValuePair <string, string>("order_id", order_id), new KeyValuePair <string, string>("item_description", item_description), new KeyValuePair <string, string>("checkout_currency", currency.ToString()), new KeyValuePair <string, string>("invoice_amount", amount), new KeyValuePair <string, string>("invoice_currency", currency.ToString()), new KeyValuePair <string, string>("success_url", success_url), new KeyValuePair <string, string>("failed_url", failed_url), new KeyValuePair <string, string>("language", language.ToString()), new KeyValuePair <string, string>("secret_hash", secret_hash), }.SignPostData()); #endregion #region Request var responseMessage = await requestClient.PostAsync(string.Concat(ApiUrl, "createinvoice"), postContent); if (responseMessage.StatusCode != HttpStatusCode.Created) { throw new ApiFailed("Api error response", new ApiFailed(await responseMessage?.Content?.ReadAsStringAsync())); } #endregion #region Result return((await responseMessage.Content.ReadAsStringAsync())?.Deserialize <InvoiceWithSign>()); #endregion } } catch (HttpRequestException e) { throw e; } catch (Exception e) { throw e; } }
public CurrencyRate GetCurrencyRate(CurrencyType currency) { return(CurrencyRates?.First(x => x.Symbol.Equals(currency.ToString(), StringComparison.OrdinalIgnoreCase)) ?? new CurrencyRate { Symbol = currency.ToString(), UsdRate = 1 }); }
public string ToString(string format, IFormatProvider formatProvider) { var amount = Value.ToString(format, formatProvider); if (Currency == CurrencyType.None) { return(amount); } return(string.Format("{0} {1}", amount, Currency.ToString().ToUpperInvariant())); }
public bool AnyItemAvailableToBuy(CurrencyType currencyType = CurrencyType.AutoDetect) { var items = itemConfigModel.GetAllItems(); var itemIds = items.Select(item => item.id); // Remove items that are in inventory: inventoryStateModel.GetState().items.ForEach(item => { if (itemIds.Contains(item.itemConfigId)) { items.RemoveAt(items.FirstIndex(i => i.id == item.itemConfigId)); } }); if (currencyType != CurrencyType.AutoDetect) { // Remove items that are not of the relevant currency type items.RemoveAll(item => item.costs.Any(cost => cost.key != currencyType.ToString()) || item.alternativeCosts.Any(alterCost => alterCost.key != currencyType.ToString())); } // If any item has costs and there's enough VC to buy it - then it's available to purchase if (items.Where(itemConfigModel.HasAnyCosts).Any(HasSufficientCurrencyForItem)) { return(true); } return(false); }
/// <summary> /// Gets the crypto currency. /// </summary> /// <param name="tickername">The ticker name.</param> /// <param name="commodity"></param> /// <param name="exchangeModel">The exchangeModel.</param> /// <param name="details">The details.</param> /// <returns></returns> private SecurityBase GetCryptoCurrency(string tickername, string commodity, ExchangeModel exchangeModel, SecurityDetails details) { //Get all tickers associated to this crypto currency from config, for this broker model var configured = Config.SecurityConfig.Where(x => String.Equals(x.Ticker, tickername, StringComparison.CurrentCultureIgnoreCase) && String.Equals(x.Exchange, exchangeModel.Name, StringComparison.CurrentCultureIgnoreCase) && x.Brokers.Select(b => b.ToLower()).Contains(_brokerModel.BrokerType.ToString().ToLower())) .ToArray(); //Check if we have items if (!configured.Any()) { return(new UnknownSecurity(tickername)); } //Get shortest path for this currency for the account currency var found = configured.FirstOrDefault(x => String.Equals(x.Currency, _accountcurrency.ToString(), StringComparison.CurrentCultureIgnoreCase)) ?? configured.FirstOrDefault(); //Return what we have if (found != null) { var basecurrency = (CurrencyType)Enum.Parse(typeof(CurrencyType), found.Currency); return(new CryptoSecurity(new TickerSymbol(tickername, commodity, basecurrency), exchangeModel, details, _currency)); } else { return(new UnknownSecurity(tickername)); } }
public static FundingBalance Find(int entityId, EntityType entityType, CurrencyType currencyType) => Connection().Query <FundingBalance>( $@"SELECT * FROM funding_balances WHERE entity_id = @entity_id AND entity_type = '{entityType.ToString()}' AND currency_type = '{currencyType.ToString()}' LIMIT 1", new { entity_id = entityId } ).FirstOrDefault();
/// <summary> /// Get symbol crosses used for calculating base currency values /// </summary> /// <param name="basecurrency"></param> /// <returns></returns> public static string GetPositionValueSymbolCrosses(CurrencyType basecurrency, ISecurity basesecurity) { if (basesecurity.Type == SecurityType.Forex) { string starts = basesecurity.Name.Substring(0, 3); return(starts + basecurrency.ToString().ToUpper()); } else if (basesecurity.Type == SecurityType.CFD) { return(basesecurity.Currency.ToString() + basecurrency.ToString()); } else { return(string.Empty); } }
/// <summary> /// Executes the transaction. /// </summary> /// <param name="amount">The amount.</param> /// <param name="toCurrencyType">Type of to currency.</param> /// <param name="fromCurrencyTypeValue">From currency type value.</param> /// <param name="currencyToConvert">The currency to convert.</param> /// <param name="toCurrencyTypeValue">To currency type value.</param> /// <param name="user">The user.</param> /// <param name="currencyFromConvert">The currency from convert.</param> /// <returns></returns> private User ExecuteTransaction(decimal amount, CurrencyType toCurrencyType, string fromCurrencyTypeValue, Currency currencyToConvert, string toCurrencyTypeValue, User user, Currency currencyFromConvert) { //get currency rate var fromCurrencyTypeRate = _currencies.Single(r => r.Currency != null && r.Currency.Equals(fromCurrencyTypeValue)).Rate; // new rate for convert var toCurrencyTypeRate = 0M; //new amount for transaction var convertedAmount = 0M; // If user has to Converting currency if (currencyToConvert != null) { toCurrencyTypeRate = _currencies.Single(r => r != null && r.Currency.Equals(toCurrencyTypeValue)).Rate; //Get Converted Value convertedAmount = (amount * toCurrencyTypeRate) / fromCurrencyTypeRate; user = StartCompleteTransaction(user, currencyFromConvert, currencyToConvert, amount, convertedAmount); } else { toCurrencyTypeRate = _currencies.Single(r => r != null && r.Currency.Equals(toCurrencyType.ToString() .ToUpper())).Rate; convertedAmount = (amount * toCurrencyTypeRate) / fromCurrencyTypeRate; user = StartUnCompleteTransaction(user, currencyFromConvert, toCurrencyType, amount, convertedAmount); } return(user); }
public async Task <SortedDictionary <DateTime, Dictionary <CurrencyType, double> > > GetDataStoredOffllineAsync(CurrencyType baseCurrency) { var fileName = CreateFileNameForBase(baseCurrency.ToString()); try { if (File.Exists(fileName)) { using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { using (var streamReader = new StreamReader(fileStream)) { var json = await streamReader.ReadToEndAsync(); return(JsonConvert.DeserializeObject <SortedDictionary <DateTime, Dictionary <CurrencyType, double> > >(json)); } } } } catch (Exception ex) { Crashes.TrackError(ex); File.Delete(fileName); } return(new SortedDictionary <DateTime, Dictionary <CurrencyType, double> >()); }
private static void Validate(string name, string address, long contact, CurrencyType currency, string shortName, string email, string firstName, string lastName, string url) { if (string.IsNullOrEmpty(name)) { throw new Exception(); } if (string.IsNullOrEmpty(contact.ToString())) { throw new Exception(); } if (string.IsNullOrEmpty(currency.ToString())) { throw new Exception(); } if (string.IsNullOrEmpty(shortName)) { throw new Exception(); } if (string.IsNullOrEmpty(firstName)) { throw new Exception(); } if (string.IsNullOrEmpty(lastName)) { throw new Exception(); } if (string.IsNullOrEmpty(url)) { throw new Exception(); } if (string.IsNullOrEmpty(email)) { throw new Exception(); } }
[InlineData("COTTON", 0, 500, 0.01, CurrencyType.USD, 71.40, 1, 500)] //High tick value and a high contract size //Test to see all pipvalue calculations public void PipValueCalcutionsCFD(string symbol, decimal tickvalue, decimal contractsize, decimal ticksize, CurrencyType basecurrency, decimal tick, decimal basevalue, decimal value) { //Arrange SimAccount naccount = new SimAccount("testing", "test account", 1000, 100); TickImpl ntick = new TickImpl(symbol); ntick.Bid = tick; ntick.Ask = tick; ntick.BidSize = int.MaxValue; ntick.AskSize = ntick.BidSize; TickImpl ntickbase = new TickImpl("USD" + basecurrency.ToString()); ntickbase.Ask = basevalue; ntickbase.Bid = basevalue; ntickbase.BidSize = int.MaxValue; ntickbase.AskSize = int.MaxValue; CFDSecurity nsecurity = new CFDSecurity(symbol); nsecurity.TickValue = tickvalue; nsecurity.ContractSize = contractsize; nsecurity.TickSize = ticksize; nsecurity.Currency = basecurrency; //add security naccount.Securities.AddSecurity(nsecurity); //Act naccount.OnTick(ntickbase); naccount.OnTick(ntick); naccount.OnTick(ntick); //Assert naccount.Securities[symbol].PipValue.Should().BeApproximately(value, .00001M); }
private void CoinSelected(CurrencyType pickedCoin) { _pickedCoin = pickedCoin; _pickerLabel.Text = _pickedCoin.ToString().ToUpper(); _transferFacade.UserBalance = AppSettings.User.AccountInfo?.Balances?.First(b => b.CurrencyType == pickedCoin); IsEnoughBalance(null, null); }
public UserSubscriptionInfo UpdateSelectedCurrency(CurrencyType currency) { ExecuteSql( $@"UPDATE user_subscription_info SET selected_currency = '{currency.ToString()}', updated_at = CURRENT_TIMESTAMP " + "WHERE id = @id", new { id } ); return(this); }
/// <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); } }
public async Task <ActionResult <User> > ConvertUserCurrency(int id, decimal amount, CurrencyType fromCurrencyType, CurrencyType toCurrencyType) { #region Check out arguments if ((id <= 0) || (amount <= 0) || (!Enum.IsDefined(typeof(CurrencyType), fromCurrencyType)) || (!Enum.IsDefined(typeof(CurrencyType), toCurrencyType))) { return(BadRequest("Any value is incorrect")); } #endregion var user = await _repo.GetById(id); if (user is null) { throw new ArgumentNullException(nameof(user)); } var currencyFromConvert = user.Currencies .FirstOrDefault(currency => currency.TypeOfCurrency.Equals(fromCurrencyType)); var currencyToConvert = user.Currencies .FirstOrDefault(currency => currency.TypeOfCurrency.Equals(toCurrencyType)); // If user has not enough money if (currencyFromConvert == null) { return(NoContent()); } if (currencyFromConvert.Count < amount) { return(BadRequest("You have not enough money")); } // get comparing Currency name var fromCurrencyTypeValue = fromCurrencyType.ToString().ToUpper(); var toCurrencyTypeValue = toCurrencyType.ToString().ToUpper(); // If Public API has Converting currencies rates if (_currencies.Any(c => c.Currency.Equals(fromCurrencyTypeValue)) && _currencies.Any(c => c.Currency.Equals(fromCurrencyTypeValue))) { user = ExecuteTransaction(amount, toCurrencyType, fromCurrencyTypeValue, currencyToConvert, toCurrencyTypeValue, user, currencyFromConvert); _repo.Update(user); if (await _repo.SaveAll()) { return(CreatedAtAction("GetUser", new { id = user.Id }, user)); } } else { return(NoContent()); } return(NoContent()); }
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 static FundingTransaction[] Get( int entityId, EntityType entityType, CurrencyType currencyType, int limit = 10 ) => Connection().Query <FundingTransaction>( $@"SELECT * FROM funding_transactions WHERE entity_id = @entity_id AND entity_type = '{entityType.ToString()}' AND currency_type = '{currencyType.ToString()}' LIMIT @limit", new { entity_id = entityId, limit } ).ToArray();
public static int Create(int entityId, EntityType entityType, CurrencyType currencyType) => ExecuteScalarInt( $@"INSERT INTO funding_balances(guid, entity_id, entity_type, currency_type) VALUES (@guid, @entity_id, '{entityType.ToString()}', '{currencyType.ToString()}'); SELECT currval('funding_balances_id_seq');" , new { guid = Guid.NewGuid().ToString(), entity_id = entityId } );
void OnGUI() { string text = type.ToString(); if (amount > 1) { text += " (" + amount + ")"; } // draw text as billboard with background }
private CurrencyValue ConvertApiObjectToEntity(NBPCurrencyObjectRates nbpCurrencyObjectRates, CurrencyType currencyType) { return(new CurrencyValue { ReferenceNumber = nbpCurrencyObjectRates.no, Type = (CurrencyType)Enum.Parse(typeof(CurrencyType), currencyType.ToString()), Value = nbpCurrencyObjectRates.mid, Date = DateTime.Parse(nbpCurrencyObjectRates.effectiveDate) }); }
void ITalkingDataSDK.OnChargeRequest(string orderId, string iapId, double currencyAmount, CurrencyType currencyType, double virtualCurrencyAmount, PaymentType payType) { if (!string.IsNullOrEmpty(orderId)) { onChargeRequst(orderId, iapId, currencyAmount, currencyType.ToString(), virtualCurrencyAmount, payType.ToString()); } else { } }
public Currency GetCurrency(CurrencyType type) { if (Currencies.ContainsKey(type)) { return(Currencies[type]); } else { throw new UnknownCurrencyException("Unknow currency type: " + type.ToString()); } }
public void RemoveCurrency(CurrencyType type) { if (Currencies.ContainsKey(type)) { Currencies.Remove(type); } else { throw new UnknownCurrencyException("Unknow currency type: " + type.ToString()); } }
public static int Create(User.User user, CurrencyType currencyType, decimal amount, string address) { return(ExecuteScalarInt( $@"INSERT INTO withdrawal_requests(guid, user_id, currency_type, amount, address) VALUES (@guid, @user_id, '{currencyType.ToString()}', @amount, @address); SELECT currval('withdrawal_requests_id_seq');" , new { guid = Guid.NewGuid().ToString(), user_id = user.id, amount, address } )); }
public static int Create( UserModel user, CurrencyType currencyType, decimal setBalance = 0 ) => ExecuteScalarInt( $@"INSERT INTO user_balances(guid, user_id, currency_type, balance) VALUES (@guid, @user_id, '{currencyType.ToString()}', @balance); SELECT currval('user_balances_id_seq');" , new { guid = Guid.NewGuid().ToString(), user_id = user.id, balance = setBalance } );
public ActionResult Deposits(CurrencyType currency) { ViewBag.Currency = this.Lang(currency.GetDescription()); ViewBag.CurrencyCode = currency.ToString(); string viewName = string.Empty; #region 获取充值地址 if (currency == CurrencyType.CNY) viewName = "CNYDeposits"; else viewName = "VirtualCoinDeposits"; #endregion return View(viewName); }
public ActionResult Index(CurrencyType currency) { ViewBag.Currency = this.Lang(currency.GetDescription()); ViewBag.CurrencyCode = currency.ToString(); var currentUserID = this.CurrentUser.UserID; var account = IoC.Resolve<IAccountQuery>().GetAccountByUserID(currentUserID, currency); var paymentAddress = string.Empty; var viewName = string.Empty; ViewBag.Balance = (account == null || account.ID == 0) ? 0 : account.Balance; if (currency == CurrencyType.CNY) viewName = "CNY"; return View(viewName); }
public async Task <ResponseData <PromotionProduct> > GetPromotionProductAsync(CurrencyType currencyType, int page = 1) { // products/list-promotion-products?api_key=[yourAPIkey]&time=[time]&lkid=[yourlinkid]¤cy=[currency]&page=[page]&sign=[signature] var arguments = new Dictionary <string, string> { { "time", Utils.CurrentTicks() }, { "currency", currencyType.ToString() }, { "page", page.ToString() } }; return(await HandleGetResquest <PromotionProduct>(promotionProductResource, arguments)); }
public List <CurrencyValue> GetCurrencyValueFromRange(CurrencyType currencyType, DateTime dateFrom, DateTime dateTo) { var result = new List <CurrencyValue>(); var currencyData = new WebClient().DownloadString(GetDownloadRangeString(currencyType.ToString(), dateFrom, dateTo)); var myObjectList = JsonConvert.DeserializeObject <NBPCurrencyObject>(currencyData); foreach (var myObject in myObjectList.rates) { result.Add(ConvertApiObjectToEntity(myObject, currencyType)); } return(result); }
public ExchangeRate GetExchangeRate(CurrencyType from, CurrencyType to) { var collection = this.dbManager.GetDatabase().GetCollection <ExchangeRate>("rate"); collection.EnsureIndex(x => x.change); var exchangeRate = collection.Find(LiteDB.Query.EQ("change", $"{from.ToString()}_{to.ToString()}")); if (exchangeRate is null) { throw new Exception("EXCHANGE_RATE_NOT_FOUND"); } return(exchangeRate.FirstOrDefault()); }
public static async Task <JObject> GetUserTransactionAsync(int offset, int count, string searchGb, CurrencyType currency) { var request = new TransactionRequest { apiKey = _apiKey, secretKey = _apiSecretKey, offset = offset, count = count, searchGb = searchGb, currency = currency.ToString() }; return(await RestClient.Instance.PostAsync <TransactionRequest, JObject>(PrivateAPI.UserTransactions, request)); }
public static async Task <Orders> GetOrdersAsync(string orderID, string transactionType, int count, int after, CurrencyType currency) { var request = new OrderHistoryRequest { apiKey = _apiKey, secretKey = _apiSecretKey, order_id = orderID, type = transactionType, count = count, after = after, currency = currency.ToString() }; return(await RestClient.Instance.PostAsync <OrderHistoryRequest, Orders>(PrivateAPI.Orders, request)); }
private static QueueingBasicConsumer GetSendTransactionListenerConsumer(CurrencyType currency) { var mqname = currency.ToString() + "SendTransactionListener"; var channel = _mqpool.GetMQChannel(mqname); var exchangeAndQueueName = Utilities.GenerateVirtualCoinSendPaymentExchangeAndQueueName(currency); channel.ExchangeDeclare(exchangeAndQueueName.Item1, ExchangeType.Direct, true, false, null); channel.QueueDeclare(exchangeAndQueueName.Item2, true, false, false, null); channel.QueueBind(exchangeAndQueueName.Item2, exchangeAndQueueName.Item1, string.Empty); channel.BasicQos(0, 1, false); var consumer = new QueueingBasicConsumer(channel); //auto ack ,最大程度上避免重复发出币 channel.BasicConsume(exchangeAndQueueName.Item2, true, consumer); return consumer; }
public ActionResult GenerateNewAddress(CurrencyType currency) { var result = FCJsonResult.CreateFailResult(this.Lang("Unknow Exception,Please refresh the page and try again")); var cacheKey = CacheKey.USER_GENERATE_PAYMENT_ADDRESS + currency.ToString() + this.CurrentUser.UserID; object tmp; if (Config.Debug || !Cache.TryGet(cacheKey, out tmp)) { try { var cmd = new GeneratePaymentAddress(this.CurrentUser.UserID, currency); this.CommandBus.Send(cmd); Cache.Add(cacheKey, cmd.ID); result = FCJsonResult.CreateSuccessResult(this.Lang("Generating deposit address ...")); } catch (Exception ex) { Log.Error("Action GenerateNewAddress Error", ex); } } return Json(result); }
public int CountVirtualCoinDepositByUserID(int userID, CurrencyType currency) { Check.Argument.IsNotNegativeOrZero(userID, "userID"); return this.Context.Sql(countVirtualCoinDepositByUserID_Sql.FormatWith(currency.ToString())) .Parameter("@userID", userID) .QuerySingle<int>(); }
/***********************************************************/ public int CountReceivePayMentTransactionBySearch(CurrencyType currency, DepositState state) { var paramters = new object[] { (int)state }; return this.Context.Sql(countReceivePayMentTransactionBySearch_Sql.FormatWith(currency.ToString())) .Parameters(paramters) .QuerySingle<int>(); }
private static void SendWithdrawFailOrAddressInvalidCommand(CurrencyType currency, string withdrawUniqueID, VirtualCoinWithdrawFailProcessType processType) { var cmdMessage = string.Empty; try { var mqname = currency.ToString() + "SendWithdrawFailOrAddressInvalidCommand"; var channel = _mqpool.GetMQChannel(mqname); var exchangeAndQueueName = Utilities.GenerateVirtualCoinWithdrawTranferFailOrAddressInvalidExchangeAndQueueName(); var nullUserID = 0; if (processType == VirtualCoinWithdrawFailProcessType.Cancel) { Log.Info("{0}提现{1}的发送到p2p失败,发送处理失败指令", currency, withdrawUniqueID); var cmd = new CancelVirtualCoinWithdraw(withdrawUniqueID, nullUserID, string.Empty, currency); cmdMessage = IoC.Resolve<IJsonSerializer>().Serialize(cmd); } else { Log.Info("{0}提现{1}的提现地址不合法,发送撤销提现指令", currency, withdrawUniqueID); var cmd = new VirtualCoinWithdrawFail(withdrawUniqueID, nullUserID, string.Empty, currency); cmdMessage = IoC.Resolve<IJsonSerializer>().Serialize(cmd); } var build = new BytesMessageBuilder(channel); build.WriteBytes(Encoding.UTF8.GetBytes(cmdMessage)); ((IBasicProperties)build.GetContentHeader()).DeliveryMode = 2; try { channel.BasicPublish(exchangeAndQueueName.Item1, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); } catch (EndOfStreamException ex) { if (ex.Message.Equals("SharedQueue closed", StringComparison.OrdinalIgnoreCase)) { channel = _mqpool.GetMQChannel(mqname); channel.BasicPublish(exchangeAndQueueName.Item1, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); } } catch (Exception ex) { Log.Error("发送提现失败处理消息时--失败了:" + cmdMessage, ex); } } catch (Exception ex) { Log.Error("发送提现失败处理消息时--失败了:" + cmdMessage, ex); } }
private decimal GetUserWithdrawDayLimitRemain(CurrencyType currency) { var limiteAmount = 0M; var cacheKey = CacheKey.USER_WITHDRAW_DAY_LIMITE + currency.ToString() + this.CurrentUser.UserID; var currencySetting = IoC.Resolve<ICurrencyQuery>().GetCurrency(currency); Cache.TryGet(cacheKey, out limiteAmount); return currencySetting.WithdrawDayLimit - limiteAmount; }
public int CountMyCoinWithdraw_Sql(int userID, CurrencyType currency) { return this.Context.Sql(countMyCoinWithdraw_Sql.FormatWith(currency.ToString())) .Parameter("@userID", userID) .QuerySingle<int>(); }
private static void ProcessTx(int userID, GetTransactionResponse tx, UInt64 nxtAccountID, CurrencyType currency) { var cacheKey = currency.ToString() + tx.SenderRS + tx.Transaction + "create"; if (tx.Type != TransactionType.Ordinary || tx.Recipient != nxtAccountID) { //如果交易类型不是普通交易或者收款账户非当前账户(非收款),忽略,并加入忽略名单,防止多次请求交易明细,浪费资源 Cache.Add(cacheKey, tx.Confirmations); return; } object obj = null; if (Cache.TryGet(cacheKey, out obj)) return; Log.Info("发现新的交易...."); var actualAmount = tx.AmountNQT / 100000000; #region 发送交易到处理消息队列 var mqname = "NXTReceiveTransactionListener"; _channel = _mqpool.GetMQChannel(mqname); var exchangeName = Utilities.GenerateVirtualCoinReceivePaymentExchangeAndQueueName(currency).Item1; var build = new BytesMessageBuilder(_channel); var cmd = new CreateReceivePaymentTransaction(tx.Transaction, tx.RecipientRS, actualAmount, currency); build.WriteBytes(Encoding.UTF8.GetBytes(IoC.Resolve<IJsonSerializer>().Serialize(cmd))); ((IBasicProperties)build.GetContentHeader()).DeliveryMode = 2; try { Log.Info("交易将被发送到Exchange->{0}", exchangeName); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); Log.Info("交易成功发送到Exchange->{0}", exchangeName); Cache.Add(cacheKey, tx.Confirmations); } catch (RabbitMQ.Client.Exceptions.AlreadyClosedException ex) { Log.Error("发送{0}新交易创建指令时发现消息队列服务器已关闭".FormatWith(Config.CoinCode), ex); try { _channel = _mqpool.GetMQChannel(mqname); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); Log.Info("交易成功发送到Exchange->{0}", exchangeName); } catch (Exception eex) { Log.Fatal("重新链接消息队列发送NXT新交易仍然出错了".FormatWith(Config.CoinCode), eex); } } catch (Exception ex) { Log.Error("发送{0}新交易创建指令时出现错误".FormatWith(Config.CoinCode), ex); } #endregion #region 提取币到总账户中 try { var nxtclient = new NXTClient4Net(Config.NXTServer, Config.SecretPhrase + userID); var result = nxtclient.SendMoneyAsnc(Config.NxtSumAccount, actualAmount - 1).Result; Log.Info("用户充值的币发送到总帐户成功"); } catch (Exception ex) { Log.Fatal("用户ID={0}充值的{1}NXT发送到总帐户失败了,请及时处理".FormatWith(userID, actualAmount), ex); } #endregion }
public IEnumerable<DotPay.ViewModel.VirtualCurrencyDepositInListModel> GetVirtualCurrencyDepositBySearch(int? userID, DateTime? starttime, DateTime? endtime, CurrencyType currency, DepositState state, int page, int pageCount) { var paramters = new object[] { userID.HasValue ? userID.Value : 0, starttime.HasValue ? starttime.Value.ToUnixTimestamp() : 0, endtime.HasValue ? endtime.Value.ToUnixTimestamp() : 0, (int)state, (page - 1) * pageCount, pageCount }; var users = this.Context.Sql(depositVirtualCurrency_Sql.FormatWith(currency.ToString())) .Parameters(paramters) .QueryMany<VirtualCurrencyDepositInListModel>(); return users; }
private static int GetNeedConfirmationCount(CurrencyType currency) { var needConfirmationCount = Config.DefaultConfirmations; ; var cacheKey = currency.ToString() + "_" + "NXTTransactionConfirmationValidator".GetHashCode().ToString() + "_needConfirm"; var cacheCount = Cache.Get(cacheKey); if (cacheCount != null) needConfirmationCount = (int)cacheCount; else { var sql = @"SELECT NeedConfirm FROM " + Config.Table_Prefix + Config.CurrencyTableName + " WHERE ID=@id"; var db_needConfirmations = _dbContext.Sql(sql).Parameter("@id", currency).QuerySingle<int>(); if (db_needConfirmations > 0) { needConfirmationCount = db_needConfirmations; Cache.Add(cacheKey, needConfirmationCount, new TimeSpan(0, 0, 600)); } } return needConfirmationCount; }
public IEnumerable<DotPay.ViewModel.WithdrawListModel> GetMyVirtualCoinWithdraw(int userID, CurrencyType currency, int start, int limit) { Check.Argument.IsNotNegativeOrZero(userID, "userID"); var paramters = new object[] { userID }; var result = this.Context.Sql(getLastTenVirtualCoinWithdrawByUserID_Sql.FormatWith(currency.ToString())) .Parameter("@userID", userID) .Parameter("@start", start) .Parameter("@limit", limit) .QueryMany<WithdrawListModel>(); return result; }
private static void ProcessTx(GetTransactionResponse tx, CurrencyType currency) { if (!ExistConfirmTx(tx, currency)) { Log.Info("txid={0}的交易确认已达到{1}个,开始发送确认消息..", tx.Transaction, tx.Confirmations); var mqname = "NXTTransactionConfirmationValidator"; _channel = _mqpool.GetMQChannel(mqname); var build = new BytesMessageBuilder(_channel); var exchangeName = Utilities.GenerateVirtualCoinReceivePaymentExchangeAndQueueName(currency).Item1; try { var amount = tx.AmountNQT / 100000000; var cmd = new ConfirmReceivePaymentTransaction(tx.Transaction, tx.RecipientRS, tx.Confirmations, amount, currency); build.WriteBytes(Encoding.UTF8.GetBytes(IoC.Resolve<IJsonSerializer>().Serialize(cmd))); ((IBasicProperties)build.GetContentHeader()).DeliveryMode = 2; _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); var cacheKey = currency.ToString() + tx.Transaction + "_" + amount + "confirm"; Cache.Add(cacheKey, tx.Confirmations); Log.Info("txid={0}的交易确认消息发送完毕", tx.Transaction, tx.Confirmations); } catch (RabbitMQ.Client.Exceptions.AlreadyClosedException ex) { Log.Error("发送{0}新交易创建指令时发现消息队列服务器已关闭".FormatWith(Config.CoinCode), ex); try { _channel = _mqpool.GetMQChannel(mqname); _channel.BasicPublish(exchangeName, string.Empty, ((IBasicProperties)build.GetContentHeader()), build.GetContentBody()); } catch (Exception eex) { Log.Fatal("NXTTransactionConfirmationValidator消息队列服务器连接重试后仍无法连接成功,可能消息队列服务器已经挂掉,请尽快处理!", eex); } } catch (Exception ex) { Log.Error("发送{0}新交易创建指令时出现错误".FormatWith(Config.CoinCode), ex); } } }
/// <summary> /// generate virtual coin send payment exchange and queue name /// <para>tuple's item1 is exchange name and item2 is queue name</para> /// </summary> /// <param name="CurrencyType">currency</param> ///<returns></returns> public static Tuple<string, string> GenerateVirtualCoinSendPaymentExchangeAndQueueName(CurrencyType currency) { Check.Argument.IsNotNegativeOrZero((int)currency, "currency"); var exchangeName = currency.ToString() + "_GENERATE_SEND_PAYMENT_EXCHANGE"; var queueName = currency.ToString() + "_GENERATE_SEND_PAYMENT_QUEUE"; return new Tuple<string, string>(exchangeName, queueName); }
public CurrencyWapper(CurrencyType currency, string currencyString) { this.Currency = currency; this.CurrencyString = currencyString; this.CurrencyStringWithNameFirst = currency.ToString().Substring(0, 2) + currencyString; }
public static string GetIBCurrency(CurrencyType currencyType) { string currency = "USD"; switch (currencyType) { case CurrencyType.AUD: currency = "AUD"; break; case CurrencyType.BRL: case CurrencyType.CNY: case CurrencyType.INR: case CurrencyType.None: currency = ""; // Currency types not supported by IB break; case CurrencyType.CAD: currency = "CAD"; break; case CurrencyType.CHF: currency = "CHF"; break; case CurrencyType.EUR: currency = "EUR"; break; case CurrencyType.GBP: currency = "GBP"; break; case CurrencyType.HKD: currency = "HKD"; break; case CurrencyType.JPY: currency = "JPY"; break; case CurrencyType.KRW: currency = "KRW"; break; case CurrencyType.MXN: currency = "MXN"; break; case CurrencyType.NOK: currency = "NOK"; break; case CurrencyType.NZD: currency = "NZD"; break; case CurrencyType.RUB: currency = "RUB"; break; case CurrencyType.SEK: currency = "SEK"; break; case CurrencyType.SGD: currency = "SGD"; break; case CurrencyType.USD: currency = "USD"; break; default: currency = currencyType.ToString(); break; } return currency; }
public int CountVirtualCurrencyDepositBySearch(int? userID, DateTime? starttime, DateTime? endtime, CurrencyType currency, DepositState state) { var paramters = new object[] { (userID.HasValue ? userID.Value : 0), starttime.HasValue ? starttime.Value.ToUnixTimestamp() : 0, endtime.HasValue ? endtime.Value.ToUnixTimestamp() : 0, (int)state }; return this.Context.Sql(countdepositVirtualCurrency_Sql.FormatWith(currency.ToString())) .Parameters(paramters) .QuerySingle<int>(); }
private static void StartSendPaymentTransactionConsumer(CurrencyType currency) { var thread = new Thread(new ThreadStart(() => { var consumer = GetSendTransactionListenerConsumer(currency); Log.Info("启动{0}提现处理器成功!", currency); while (true) { if (Program.Fusing) { Log.Info("发生熔断事件,虚拟币提现处理器停止运行"); break; } Log.Info("正在监听{0}新的提现指令...", currency); BasicDeliverEventArgs ea = null; try { ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); var body = ea.Body; var message = Encoding.UTF8.GetString(body); var withdrawMessage = IoC.Resolve<IJsonSerializer>().Deserialize<VirtualCoinWithdrawProcessMessage>(message); Log.Info("收到{0}新的提现指令:{1}", currency, message); if (Config.CoinCode != withdrawMessage.Currency.ToString()) { Log.Fatal("收到的提现指令中指定的币种与配置文件中的币种不一致!"); break; } var txid = string.Empty; var txfee = 0M; if (TrySendTransactionToP2p(withdrawMessage.MsgID, withdrawMessage.Address, withdrawMessage.NXTPublicKey, withdrawMessage.Amount, out txid, out txfee)) { SendCompleteCommand(withdrawMessage.Currency, withdrawMessage.WithdrawUniqueID, txid, txfee); } else { SendWithdrawFailOrAddressInvalidCommand(withdrawMessage.Currency, withdrawMessage.WithdrawUniqueID, VirtualCoinWithdrawFailProcessType.MarkFail); Log.Error("提现处理时,发送交易到P2P网络失败,请及时手工处理该笔交易!msg:" + message); } Log.Info("成功处理{0}提现指令", currency); } catch (RabbitMQ.Client.Exceptions.AlreadyClosedException ex) { Log.Warn("提现NXT处理时,消息队列的链接断开了,准备自动重连", ex); consumer = GetSendTransactionListenerConsumer(currency); } catch (System.IO.EndOfStreamException ex) { if (ex.Message.Equals("SharedQueue closed", StringComparison.OrdinalIgnoreCase)) { Log.Warn("提现NXT处理时,消息队列的链接断开了,准备自动重连", ex); consumer = GetSendTransactionListenerConsumer(currency); } } catch (Exception ex) { Log.Error(currency.ToString() + "提现指令处理过程中出现错误:" + ex.Message); } } })); thread.Start(); }
public IEnumerable<DepositInListModel> GetVirtualCoinDepositByUserID(int userID, CurrencyType currency, int start, int limit) { Check.Argument.IsNotNegativeOrZero(userID, "userID"); var deposits = this.Context.Sql(getVirtualCoinDepositByUserID_Sql.FormatWith(currency.ToString())) .Parameter("@userID", userID) .Parameter("@start", start) .Parameter("@limit", limit) .QueryMany<DepositInListModel>(); return deposits; }
public CurrencyListModel GetCurrency(CurrencyType currency) { return this.GetAllCurrencies().Single(c => c.Code == currency.ToString()); }
private static bool ExistTx(string accountRS, string txid, CurrencyType currency) { bool isExist = false; var cacheKey = currency.ToString() + accountRS + txid + "create"; var tmp = new object(); if (Cache.TryGet(cacheKey, out tmp)) { isExist = true; } else { var sql = @"SELECT COUNT(*) FROM " + Config.Table_Prefix + Config.TxTableName + " WHERE TxID=@txid AND Address=@address"; var count = _dbContext.Sql(sql).Parameter("@txid", txid) .Parameter("@address", accountRS) .QuerySingle<int>(); if (count > 0) isExist = true; } return isExist; }
public ActionResult Index(CurrencyType currency) { var viewName = string.Empty; if (currency == CurrencyType.CNY) viewName = "CNY"; else viewName = "VirtualCoin"; ViewBag.VirtualCoinName = currency.ToString(); var currentUserID = this.CurrentUser.UserID; var account = IoC.Resolve<IAccountQuery>().GetAccountByUserID(currentUserID, currency); ViewBag.Balance = (account != null && account.ID > 0) ? account.Balance : 0; ViewBag.CurrentDayLimit = GetUserWithdrawDayLimitRemain(currency); ViewBag.CurrencySetting = IoC.Resolve<ICurrencyQuery>().GetCurrency(currency); ViewBag.Currency = currency; ViewBag.TodayLimit = this.GetUserWithdrawDayLimitRemain(currency); return View(viewName); }
public ActionResult InsideTransfer(CurrencyType currency) { ViewBag.Currency = currency.ToString(); return View("Inside"); }
private static void StartNXTBalanceWatcher(CurrencyType currency) { var currencyQuery = IoC.Resolve<ICurrencyQuery>(); var thread = new Thread(new ThreadStart(() => { while (true) { var balance = 0M; if (TryGetBalance(out balance)) { UpdateBalanceRecord(currency, balance); var currencySetting = currencyQuery.GetAllCurrencies().SingleOrDefault(c => c.Code == currency.ToString()); //如果小于该币提现日限额*3的数量,则发送预警消息 var warnLine = currencySetting.WithdrawOnceLimit * 3; if (balance < warnLine) { SendBalanceWarnMessage("{0}已不足{1:#####},请及时补充".FormatWith(currency, warnLine)); } } else { Log.Warn("获取{0}钱包余额失败,flg={1}", currency, Config.StatisticsFlg); } var sleepTime = Config.Debug ? 1000 : 300 * 1000; Thread.Sleep(sleepTime); } })); Log.Info("{0}钱包余额监控器正在启动...", currency); thread.Start(); Log.Warn("{0}钱包余额监控器启动成功!", currency); }
public int CountVirtualCoinWithdrawBySearch(int?userID, CurrencyType currencyType, VirtualCoinTxState state) { var paramters = new object[] { userID.HasValue ? userID.Value : 0, (int)state }; return this.Context.Sql(getVirtualCoinWithdrawCount_Sql.FormatWith(currencyType.ToString())) .Parameters(paramters) .QuerySingle<int>(); }
private void UpdateUserWithdrawDayLimitRemain(decimal withdrawAmount, CurrencyType currency) { var limiteAmount = 0M; var cacheKey = CacheKey.USER_WITHDRAW_DAY_LIMITE + currency.ToString() + this.CurrentUser.UserID; Cache.TryGet(cacheKey, out limiteAmount); limiteAmount += withdrawAmount; var now = DateTime.Now; Cache.Add(cacheKey, limiteAmount, new DateTime(now.Year, now.Month, now.Day, 23, 59, 56)); }
public IEnumerable<DotPay.ViewModel.VirtualCoinWithdrawListModel> GetVirtualCoinWithdrawBySearch(int? userID, CurrencyType currencyType, VirtualCoinTxState state, int page, int pageCount) { var paramters = new object[] { userID.HasValue ? userID.Value : 0, (int)state, (page - 1) * pageCount, pageCount }; var users = this.Context.Sql(getVirtualCoinWithdraw_Sql.FormatWith(currencyType.ToString())) .Parameters(paramters) .QueryMany<VirtualCoinWithdrawListModel>(); return users; }
private static bool ExistConfirmTx(GetTransactionResponse tx, CurrencyType currency) { bool isExist = false; var cacheKey = currency.ToString() + tx.Transaction + "_" + (tx.AmountNQT / 100000000) + "confirm"; var tmp = new object(); if (Cache.TryGet(cacheKey, out tmp)) { isExist = true; } return isExist; }