private AccountModel ToAccount(JToken token) { if (token["isTotal"] != null) { return(null); } var account = new AccountModel { Id = token["accountId"].ToString(), Name = token["accountName"].ToString(), }; var balance = new BalanceModel { Currency = _baseCurrency, Cash = token["balance"].ToDecimal(), Equity = token["equity"].ToDecimal(), Profit = token["grossPL"].ToDecimal(), DayProfit = token["dayPL"].ToDecimal(), }; account.Balances.Add(balance); return(account); }
private static List <TransactionReceivedCoins> GetListTransaction(BitcoinSecret sonBitPrivateKey) { List <TransactionReceivedCoins> list = new List <TransactionReceivedCoins>(); try { var address = sonBitPrivateKey.GetAddress(); QBitNinjaClient client = new QBitNinjaClient(Network.TestNet); BalanceModel myBalance = client.GetBalance(address, unspentOnly: true).Result; foreach (BalanceOperation op in myBalance.Operations) { List <Coin> lstCoin = new List <Coin>(); var receivedCoins = op.ReceivedCoins; foreach (Coin e in receivedCoins) { lstCoin.Add(e); } TransactionReceivedCoins objTransactionReceivedCoins = new TransactionReceivedCoins { ListCoins = lstCoin, TransactionID = op.TransactionId, Confirm = op.Confirmations }; list.Add(objTransactionReceivedCoins); } } catch (Exception ex) { Utilitys.WriteLog(fileLog, ex.Message); list = null; } return(list); }
private async void ContinuePowerAction(bool shouldContinue) { if (shouldContinue) { _loader.StartAnimating(); _actionButton.Enabled = false; var model = new BalanceModel(_powerAmount, _walletPresenter.Balances[0].MaxDecimals, _walletPresenter.Balances[0].CurrencyType) { UserInfo = _walletPresenter.Balances[0].UserInfo }; var response = await _walletPresenter.TryPowerUpOrDown(model, _powerAction); _loader.StopAnimating(); _actionButton.Enabled = true; if (response.IsSuccess) { _walletPresenter.UpdateWallet?.Invoke(); NavigationController.PopViewController(true); } else { ShowAlert(response.Exception); } } }
public BalanceModel GetBalance(string address) { // TODO read the values properly int confirmationsNeeded = 10; int currentBlockHeight = this.blocksRepository.GetAll(false).Last().Height; decimal confirmedBalance = this.GetBalanceTo(address, 0, currentBlockHeight - confirmationsNeeded) - this.GetBalanceFrom(address, 0, currentBlockHeight - confirmationsNeeded); decimal lastBalance = this.GetBalanceTo(address, Math.Max(0, currentBlockHeight - confirmationsNeeded), currentBlockHeight) - this.GetBalanceFrom(address, Math.Max(0, currentBlockHeight - confirmationsNeeded), currentBlockHeight); decimal pendingBalance = this.GetBalanceTo(address, -10, 0); var result = new BalanceModel() { Address = address, ConfirmedBalance = new BalanceInfo() { Balance = confirmedBalance, Confirmations = confirmationsNeeded, }, LastMinedBalance = new BalanceInfo() { Balance = confirmedBalance + lastBalance, Confirmations = 1, }, PendingBalance = new BalanceInfo() { Balance = confirmedBalance + lastBalance + pendingBalance, Confirmations = 0, }, }; return(result); }
//[ChildActionOnly] public async Task <ActionResult> Balance() { var userId = _userManager.GetUserId(User); var user = await _userManager.GetUserAsync(User); var model = new BalanceModel(); if (user == null) { return(PartialView(model)); } model.Balance = user.Balance; model.IncomingNotAccepted = (from c in _db.Collections join co in _db.CollectionOperations on c.CollectionId equals co.CollectionId into operations from co in operations.OrderByDescending(o => o.OperationDateTime).Take(1) where c.CollectorId == userId && co.OperationTypeId == CollectionOperationType.COType.New select new { c.Amount }).DefaultIfEmpty().Sum(c => c.Amount); model.IssuedNotAccepted = (from c in _db.Collections join co in _db.CollectionOperations on c.CollectionId equals co.CollectionId into operations from co in operations.OrderByDescending(o => o.OperationDateTime).Take(1) where c.ProviderId == userId && co.OperationTypeId == CollectionOperationType.COType.New select new { c.Amount }).DefaultIfEmpty().Sum(c => c.Amount); return(PartialView(model)); }
public void OnGet_AlreadyInitialzed_Redirect() { const string userName = "******"; var Context = new DbContextOptionsBuilder <ApplicationDbContext>() .UseSqlite(CreateInMemoryDatabase()) .Options; IdentityUser user = new IdentityUser(userName); UserManager.CreateAsync(user); var tempBalance = new BalanceModel { BalanceAmount = 2000, OwnerID = UserID, OwnerName = "Test" }; Context.BalanceModel.Add(tempBalance); //arrange var pageModel = new IndexModel(Context, AuthorizationService, UserManager); //act var result = pageModel.OnGet(); //assert RedirectToPageResult redirect = result as RedirectToPageResult; //<--cast here Assert.Equal("/Dashbaord", redirect.PageName); }
public WalletModel GetWallet(string apiKey, string fiatCurrencyToDisplayValues) { WalletModel model = new WalletModel(); List <BalanceModel> balances = new List <BalanceModel>(); foreach (var currency in _currencyService.GetSupportedCurrencies(apiKey)) { Random randomAmount = new Random(); BalanceModel item = new BalanceModel() { Currency = currency, Amount = (decimal)(randomAmount.NextDouble() * randomAmount.Next(0, 999999)), FiatCurrencyToDisplay = fiatCurrencyToDisplayValues }; item.ValueInCurrencyToDisplay = randomAmount.Next(1, 10) * item.Amount; balances.Add(item); } model.Balances = balances.OrderByDescending(b => b.ValueInCurrencyToDisplay); model.CurrentCelBalance = (decimal?)398264.123; return(model); }
private async void DoPowerAction() { _powerBtnLoader.Visibility = ViewStates.Visible; _powerBtn.Text = string.Empty; var model = new BalanceModel(_powerAmount, _balance.MaxDecimals, _balance.CurrencyType) { UserInfo = _balance.UserInfo }; var response = await Presenter.TryPowerUpOrDown(model, _powerAction); if (!IsInitialized || IsDetached) { return; } _powerBtnLoader.Visibility = ViewStates.Gone; _powerBtn.Text = AppSettings.LocalizationManager.GetText(_powerAction == PowerAction.PowerUp ? LocalizationKeys.PowerUp : LocalizationKeys.PowerDown); if (response.IsSuccess) { TargetFragment.OnActivityResult(WalletFragment.WalletFragmentPowerUpOrDownRequestCode, (int)Result.Ok, null); Activity.ShowAlert(LocalizationKeys.TransferSuccess, ToastLength.Short); BackBtnOnClick(null, null); } else { Activity.ShowAlert(response.Exception, ToastLength.Short); } }
private static void ShowBalance(string password, string walletName, string wallet) { try { Safe loadedSafe = Safe.Load( password, Path.Combine(WalletFilePath, $"{walletName}.json")); } catch { WriteLine("Wrong wallet or password!"); return; } QBitNinjaClient client = new QBitNinjaClient(TestNetwork); decimal totalBalance = 0; BalanceModel balance = client. GetBalance(BitcoinAddress.Create(wallet, TestNetwork), true).Result; foreach (BalanceOperation entry in balance.Operations) { foreach (ICoin coin in entry.ReceivedCoins) { Money coinAmount = (Money)coin.Amount; decimal amount = coinAmount.ToDecimal(MoneyUnit.BTC); totalBalance += amount; } } WriteLine($"Balance of wallet: {totalBalance}"); }
public async Task <BalanceModel> search() { BalanceModel balanceToReturn = new BalanceModel(); BalanceModel balanceDetail = new BalanceModel(); //TO DO asignar a balanceDetail los valores que se regresaran, Amount(monto de deuda), Concept(concepto o servicio), DueDate(fecha de vencimiento) balanceToReturn.Contract = BalanceRequest.Contract; if (balanceDetail != null) { balanceToReturn.Amount = balanceDetail.Amount; balanceToReturn.Concept = balanceDetail.Concept; balanceToReturn.DueDate = balanceDetail.DueDate; balanceToReturn.IdError = (int)ErrorEnum.ErrorResponce.Success; balanceToReturn.Status = true; } else { balanceToReturn.Amount = 0.0; balanceToReturn.Concept = ""; balanceToReturn.DueDate = ""; balanceToReturn.IdError = (int)ErrorEnum.ErrorResponce.Contract_Not_Found; balanceToReturn.Status = false; } return(balanceToReturn); }
private static void GetHistory() { Console.WriteLine("Wallet name:"); string walletName = GetInput(); Console.WriteLine("Password:"******"Enter wallet address:"); string address = Console.ReadLine(); try { string walletFile = $"{WalletFilePath}{walletName}{WalletFileExtension}"; Safe.Load(pass, walletFile); } catch { Console.WriteLine("Wallet with such name does not exist"); return; } QBitNinjaClient client = new QBitNinjaClient(CurrentNetwork); BalanceModel balance = client.GetBalance(BitcoinAddress.Create(address), true).Result; string received = "-----COINS RECEIVED-----"; Console.WriteLine(received); foreach (BalanceOperation balanceOperation in balance.Operations) { foreach (ICoin balanceOperationReceivedCoin in balanceOperation.ReceivedCoins) { Money amount = balanceOperationReceivedCoin.Amount as Money; Console.WriteLine($"Transaction ID: {balanceOperationReceivedCoin.Outpoint}; Received coins: {amount?.ToDecimal(MoneyUnit.BTC) ?? 0}"); } } Console.WriteLine(new string('-', received.Length)); BalanceModel balanceWithSpent = client.GetBalance(BitcoinAddress.Create(address), false).Result; string spent = "-----COINS SPENT-----"; Console.WriteLine(spent); foreach (BalanceOperation balanceOperation in balanceWithSpent.Operations) { foreach (ICoin balanceOperationReceivedCoin in balanceOperation.SpentCoins) { Money amount = balanceOperationReceivedCoin.Amount as Money; Console.WriteLine($"Transaction ID: {balanceOperationReceivedCoin.Outpoint}; Received coins: {amount?.ToDecimal(MoneyUnit.BTC) ?? 0}"); } } Console.WriteLine(new string('-', spent.Length)); }
public void RemoveBalance(BalanceModel balance) { using (Context.AppContext dbContext = new Context.AppContext()) { dbContext.Balance.Remove(balance); dbContext.SaveChanges(); } }
private IEnumerable <PaymentBcnTransaction> GetIncomingPaymentOperations(BalanceModel balance, string walletAddress) { return(balance?.Operations? .Where(o => o.ReceivedCoins.Any(coin => coin.GetDestinationAddress(_bitcoinNetwork).ToString().Equals(walletAddress)) && o.Amount.ToDecimal(MoneyUnit.BTC) > 0) .Select(x => x.ToDomainPaymentTransaction(walletAddress))); }
public static SerializableBalanceModel GetSerializable(this BalanceModel balanceModel) { return(new SerializableBalanceModel { ConflictedOperations = balanceModel.ConflictedOperations.Select(bo => bo.GetSerializable()).ToList(), Continuation = balanceModel.Continuation, Operations = balanceModel.Operations.Select(bo => bo.GetSerializable()).ToList() }); }
internal void UpdateBalance(BalanceModel updateBalance) { using (Context.AppContext dbContext = new Context.AppContext()) { BalanceModel currentBalance = dbContext.Balance.FirstOrDefault(b => b.Id == updateBalance.Id); dbContext.Entry(currentBalance).CurrentValues.SetValues(updateBalance); dbContext.SaveChanges(); } }
public BalanceEntity MapFromBalanceModelToBalanceEntity(BalanceModel model) { return(new BalanceEntity() { BalanceId = model.BalanceId, Balance = model.Balance, CardId = model.CardId }); }
public ActionResult AgentRT(BalanceModel balanceModel) { //BalanceModel balanceModel = new BalanceModel(); List <BalanceCommon> balanceCommons = _balance.GetAgentName(); Dictionary <string, string> agentName = new Dictionary <string, string>(); Dictionary <string, string> bankList = _balance.GetBankList(); foreach (BalanceCommon bcommon in balanceCommons) { agentName.Add(bcommon.AgentId, bcommon.Name); } balanceModel.NameList = ApplicationUtilities.SetDDLValue(agentName, "", "--Agent--"); balanceModel.BankAccountList = ApplicationUtilities.SetDDLValue(bankList, "", "--Bank--"); if (Convert.ToDecimal(balanceModel.Amount) > 500000 && balanceModel.Type == "T") { ModelState.AddModelError("Amount", "Amount Cannot Be Greater then 500000 (5 Lakhs)"); return(View(balanceModel)); } if (balanceModel.Type == "R") { ModelState.Remove(("BankId")); if (Convert.ToDecimal(balanceModel.Amount) > 100000 && balanceModel.Type == "R") { ModelState.AddModelError("Amount", "Amount Cannot Be Greater then 100000 (1 Lakh)"); return(View(balanceModel)); } } if (ModelState.IsValid) { balanceModel.CreatedBy = Session["UserName"].ToString(); balanceModel.AgentId = agentName.FirstOrDefault(x => x.Key == balanceModel.Name).Key.ToString(); balanceModel.Name = agentName.FirstOrDefault(x => x.Key == balanceModel.Name).Value.ToString(); if (balanceModel.Type == "T") { balanceModel.BankName = bankList.FirstOrDefault(x => x.Key == balanceModel.BankId).Value.ToString(); } balanceModel.CreatedIp = ApplicationUtilities.GetIP(); BalanceCommon balanceCommon = balanceModel.MapObject <BalanceCommon>(); CommonDbResponse dbResponse = _balance.AgentTR(balanceCommon); if (dbResponse.Code == 0) { dbResponse.SetMessageInTempData(this); return(RedirectToAction("AgentRT", ControllerName)); } } else { return(View(balanceModel)); } return(RedirectToAction("AgentRT", ControllerName)); }
public BalanceModel GetBalances(int id) { BalanceModel balance = new BalanceModel() { ArgBalance = GetAccountBalance(id, "ARS"), UsdBalance = GetAccountBalance(id, "USD") }; return(balance); }
public BalanceViewModel() { Model = new BalanceModel { Id = SystemUtility.GetGuid(), Currency = NumberFormatInfo.CurrentInfo.CurrencySymbol }; IsNew = true; }
private async Task <Exception> Claim(BalanceModel balance) { var error = await Presenter.TryClaimRewards(balance); if (error == null) { _claimBtn.Visibility = ViewStates.Gone; } return(error); }
public static Balance ToBalance(this BalanceModel balance) { var decodedAssetId = BalanceModelIdConverter.DecodeId(balance.Id); return(new Balance { Asset = decodedAssetId.asset, Amount = balance.Amount, Liabilities = balance.Liabilities }); }
private static async Task Proceed(string address) { var client = new CustomQBitNinjaClient(Network.Main); var addr = BitcoinAddress.Create(address, Network.Main); var listAllOperations = new List <BalanceOperation>(); string continuation = null; do { Console.WriteLine($"Retrieving balance {addr}. Already retrieved {listAllOperations.Count} ops. Continuation - \"{continuation}\""); BalanceModel balance = await GetBalanceModel(client, addr, continuation); continuation = balance.Continuation; listAllOperations.AddRange(balance.Operations); } while (continuation != null); var result = new List <(string transactionId, decimal fee, bool isCashout, DateTime date, string address)>(); var counter = 0; var validOps = listAllOperations.Where(p => p.BlockId != null).ToList(); Task.WaitAll(validOps.ForEachAsyncSemaphore(8, async(op) => { await Policy.Handle <Exception>().WaitAndRetryAsync(10, retryAttempt => TimeSpan.FromSeconds(3), (ex, timeSpan) => { Console.WriteLine($"Exception: {ex}"); Console.WriteLine($"Retrying in {timeSpan.Seconds} seconds"); }).ExecuteAsync(async() => { result.Add(await Execute(client, op, addr)); }); Console.WriteLine($"Processed {Interlocked.Increment(ref counter)} of {validOps.Count} tx at {addr}"); })); Console.WriteLine($"[{DateTime.UtcNow}] Retrieve data done for {addr}"); var fl = $"result-{addr}-{DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm-ss")}.csv"; File.AppendAllText(fl, string.Join(";", "address", "transactionHash", "fee", "date", "in/out") + Environment.NewLine); foreach (var item in result.OrderByDescending(p => p.date)) { File.AppendAllText(fl, string.Join(";", item.address, item.transactionId, item.fee.ToString(CultureInfo.InvariantCulture), item.date.ToString("yyyy-MM-ddTHH:mm:ss.fff"), item.isCashout ? "out" : "in") + Environment.NewLine); } }
public async Task <IActionResult> Requery(BalanceModel model) { try { return(Ok(await _service.Requery(x => x.Id == model.Id))); } catch (Exception e) { return(BadRequest(e.Message)); } }
public async Task <IActionResult> Delete(BalanceModel model) { try { return(Ok(await _service.Delete(model))); } catch (Exception e) { return(BadRequest(e.Message)); } }
public ActionResult Balance() { //获得用户ID string UserId = (string)Session["id"]; //double Balance = getBalace(UserId); //获得账户余额,填充model BalanceModel model = new BalanceModel(); //model.Balance = Balace; return(View(model));//View(model) }
private async void CancelPowerDown() { var balance = Presenter.Balances[_walletPager.CurrentItem]; var model = new BalanceModel(0, balance.MaxDecimals, balance.CurrencyType) { UserInfo = balance.UserInfo }; await Presenter.TryPowerUpOrDown(model, PowerAction.CancelPowerDown); TryUpdateBalance(balance); }
private static void ShowHistory(string password, string walletName, string wallet) { try { Safe loadedSafe = Safe.Load( password, Path.Combine(WalletFilePath, $"{walletName}.json")); } catch { WriteLine("Wrong wallet or password!"); return; } QBitNinjaClient client = new QBitNinjaClient(TestNetwork); BalanceModel coinsReceived = client.GetBalance( BitcoinAddress.Create(wallet, TestNetwork), true).Result; string header = "-----COINS RECEIVED-----"; WriteLine(header); foreach (BalanceOperation entry in coinsReceived.Operations) { foreach (ICoin coin in entry.ReceivedCoins) { Money amount = (Money)coin.Amount; WriteLine( $"Transaction ID: {coin.Outpoint}; Received coins: {amount.ToDecimal(MoneyUnit.BTC)}"); } } WriteLine(new string('-', header.Length)); string footer = "-----COINS SPENT-----"; WriteLine(footer); BalanceModel coinsSpent = client.GetBalance( BitcoinAddress.Create(wallet, TestNetwork)).Result; foreach (BalanceOperation entry in coinsSpent.Operations) { foreach (ICoin coin in entry.SpentCoins) { Money amount = (Money)coin.Amount; WriteLine( $"Transaction ID: {coin.Outpoint}; Spent coins: {amount.ToDecimal(MoneyUnit.BTC)}"); } } WriteLine(new string('-', footer.Length)); }
public async Task <List <BalanceModel> > GetBalanceValues() { List <BinanceBalance> balances = await GetBalances(); if (balances != null) { using (var client = new BinanceClient()) { decimal bitcoinTotal = 0; var lastPrices = await client.Get24HPricesListAsync(); decimal bitcoinPrice = lastPrices.Data.Where(p => p.Symbol == "BTCUSDT").Select(p => p.LastPrice).Single(); List <Binance24HPrice> btc = lastPrices.Data.Where(p => p.Symbol.Contains("BTC")).ToList(); List <BalanceModel> balanceModels = new List <BalanceModel>(); if (lastPrices.Success) { foreach (BinanceBalance balance in balances) { BalanceModel balanceModel = new BalanceModel(); if (balance.Asset != "BTC") { decimal bitcoinValue = btc.Where(a => a.Symbol.Contains(balance.Asset)).Select(a => a.LastPrice).Single() * balance.Total; balanceModel.BitcoinValue = bitcoinValue; bitcoinTotal += bitcoinValue; } else { bitcoinTotal += balance.Total; balanceModel.BitcoinValue = balance.Total; } balanceModel.Symbol = balance.Asset; balanceModel.Amount = balance.Total; balanceModel.USDValue = decimal.Round(bitcoinPrice * balanceModel.BitcoinValue, 2); balanceModels.Add(balanceModel); } bitcoinTotal = decimal.Round(bitcoinTotal, 7); } BalanceModel binanceBalance = new BalanceModel() { Symbol = "TotalBitcoin", Amount = bitcoinTotal, USDValue = decimal.Round(bitcoinPrice * bitcoinTotal, 2) }; balanceModels.Add(binanceBalance); return(balanceModels); } } else { return(null); } }
public async Task <IActionResult> TopUp(BalanceModel summ) { try { var response = await _userService.TopUp(summ); return(Ok(response)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public ActionResult DistributorRT() { BalanceModel balanceModel = new BalanceModel(); Dictionary <string, string> distributorName = new Dictionary <string, string>(); distributorName = _balance.GetDistributorName(); Dictionary <string, string> bankList = _balance.GetBankList(); balanceModel.NameList = ApplicationUtilities.SetDDLValue(distributorName, "", "--Distributor--"); balanceModel.BankAccountList = ApplicationUtilities.SetDDLValue(bankList, "", "--Bank--"); return(View(balanceModel)); }
public ActionResult Index(int message = 0, int page = 1) { var user = _userRepository.GetByUsername(User.Identity.Name); var totalCount = _paymentTransactionRepository.GetByUserIdCount(user.Id); var totalPages = Math.Ceiling(totalCount / (decimal)PageSize); var skip = (page - 1) * PageSize; var transactions = _paymentTransactionRepository.GetByUserId(user.Id, skip, PageSize); var model = new BalanceModel { Balance = user.Balance, Hold = user.Hold, AvailableForWithdrawal = user.AvailableForWithdrawal, Transactions = transactions, Page = page, TotalPages = totalPages }; ViewBag.Message = message; return View(model); }