Beispiel #1
0
        public static async Task DeletePortfolioAsync(CloudTable table, PortfolioEntity deleteEntity)
        {
            try
            {
                if (deleteEntity == null)
                {
                    throw new ArgumentNullException("deleteEntity");
                }

                TableOperation deleteOperation = TableOperation.Delete(deleteEntity);
                TableResult    result          = await table.ExecuteAsync(deleteOperation);

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB
                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of Delete Operation: " + result.RequestCharge);
                }
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Beispiel #2
0
        public static async Task <PortfolioEntity> InsertOrMergePortfolioAsync(CloudTable table, PortfolioEntity entity)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }
            try
            {
                // Create the InsertOrReplace table operation
                TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(entity);

                // Execute the operation.
                TableResult result = await table.ExecuteAsync(insertOrMergeOperation);

                PortfolioEntity insertedPortfolio = result.Result as PortfolioEntity;

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure Cosmos DB
                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of InsertOrMerge Operation: " + result.RequestCharge);
                }

                return(insertedPortfolio);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
Beispiel #3
0
        public static async Task <PortfolioEntity> RetrievePortfolioUsingPointQueryAsync(CloudTable table, string partitionKey, string rowKey)
        {
            try
            {
                TableOperation retrieveOperation = TableOperation.Retrieve <PortfolioEntity>(partitionKey, rowKey);
                TableResult    result            = await table.ExecuteAsync(retrieveOperation);

                PortfolioEntity portfolio = result.Result as PortfolioEntity;
                if (portfolio != null)
                {
                    Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", portfolio.PartitionKey, portfolio.RowKey, portfolio.Stocks, portfolio.GuildId);
                }

                // Get the request units consumed by the current operation. RequestCharge of a TableResult is only applied to Azure CosmoS DB
                if (result.RequestCharge.HasValue)
                {
                    Console.WriteLine("Request Charge of Retrieve Operation: " + result.RequestCharge);
                }

                return(portfolio);
            }
            catch (StorageException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
                throw;
            }
        }
 public bool Contains(PortfolioEntity entity)
 {
     return(this.db.Portfolio.Any(
                p => p.Share == entity.Share &&
                p.UserEntityId == entity.UserEntityId &&
                p.ShareId == entity.ShareId
                ));
 }
 public void ChangeAmountOfShares(PortfolioEntity args, int value)
 {
     if ((args.Amount = args.Amount + value) < 0)
     {
         throw new ArgumentException("У продавца не хватает акций");
     }
     repo.SaveChanges();
 }
Beispiel #6
0
 public Portfolio MapToPortfolio(PortfolioEntity model, List <PortfolioProject> projects, List <SkillTypeEntity> skills)
 {
     return(new Portfolio()
     {
         Biography = model.Data.Biography,
         CVUrl = ResolveAssetURL(model.Data.CV.First()),
         Projects = projects,
         Skills = MapToSkills(skills)
     });
 }
Beispiel #7
0
        public async Task NewPortfolioAsync([Remainder][Summary("Protfolio name")] string name)
        {
            PortfolioEntity portfolio = new PortfolioEntity(Context.User.Id.ToString(), name);

            portfolio.GuildId = Context.Guild.Id.ToString();
            portfolio.Stocks  = string.Empty;
            await CloudTableUtility.InsertOrMergePortfolioAsync(table, portfolio);

            await ReplyAsync("New portfolio '" + name + "' added!");
        }
        public void AddNewUsersShares(PortfolioInfo args)
        {
            var PortfolioToAdd = new PortfolioEntity()
            {
                UserEntityId = args.UserId,
                ShareId      = args.ShareId,
                Amount       = args.Amount
            };

            repo.AddNewUsersShares(PortfolioToAdd);
            repo.SaveChanges();
        }
Beispiel #9
0
 public void ChangeAmountOfShares(PortfolioEntity args, int value)
 {
     try
     {
         this.portfolioServices.ChangeAmountOfShares(args, value);
         Logger.Log.Info($"У пользователя изменено количество акций {args.Share.Name} на {value} шт.");
     }
     catch (ArgumentException ex)
     {
         Logger.Log.Error(ex.Message);
         throw ex;
     }
 }
        public override object ExecuteCommand(InCourseRequest inCourseRequest)
        {
            var entidad = (from d in context.Portfolios where d.IdPortfolio == r_id select d);

            ValidateExiste(entidad.Count(), r_id, CodigosMensajes.FE_ACTUALIZA_NO_EXISTE);

            PortfolioEntity request = entidad.FirstOrDefault();

            request.Nombre      = Nombre;
            request.Codigo      = Codigo;
            request.EsDeSistema = EsDeSistema;

            return(null);
        }
Beispiel #11
0
        public override object ExecuteCommand(InCourseRequest inCourseRequest)
        {
            DTOPortfolio    favorito  = CachingManager.Instance.GetPortfolioByCodigo("F" + IdUsuario.ToString());
            int             idPlazo   = CachingManager.Instance.GetAllPlazos().Find(x => x.Descripcion == Plazo).IdPlazo;
            PortfolioEntity portfolio = new PortfolioEntity();

            if (favorito == null)
            {
                portfolio.Codigo      = "F" + IdUsuario.ToString();
                portfolio.EsDeSistema = false;
                portfolio.Nombre      = "Favorito_" + IdUsuario.ToString();
                portfolio.EsFavorito  = true;

                var portfolioComposicion = new PortfolioComposicionEntity()
                {
                    IdMercado  = 1,
                    IdPlazo    = (byte)idPlazo,
                    IdProducto = IdProducto,
                    Orden      = 1,
                    Portfolio  = portfolio
                };

                var portfolioUsuario = new PortfolioUsuarioEntity()
                {
                    IdUsuario = IdUsuario,
                    Portfolio = portfolio
                };

                this.AgregarAlContextoParaAlta(portfolio);
                this.AgregarAlContextoParaAlta(portfolioUsuario);
                this.AgregarAlContextoParaAlta(portfolioComposicion);
            }
            else
            {
                var portfolioComposicion = new PortfolioComposicionEntity()
                {
                    IdMercado   = 1,
                    IdPlazo     = (byte)idPlazo,
                    IdProducto  = IdProducto,
                    Orden       = 1,
                    IdPortfolio = favorito.IdPortfolio
                };

                this.AgregarAlContextoParaAlta(portfolioComposicion);
            }

            return(ExecutionResult.ReturnInmediatelyAndQueueOthers(new { Ok = true }));
        }
        private IEnumerable <FileParserInput> DownloadDepots()
        {
            var downloadResults = new List <FileParserInput>();

            try
            {
                NavigateDepots();
                Browser.WaitForJavaScript();

                for (var i = 1; i < GetAccountLinks().Count; i++)
                {
                    GetAccountLinks()[i].Click();
                    Browser.WaitForJavaScript(2000);
                    var portfolioNumber = Browser.FindElement(new ByChained(By.ClassName("info-box"), By.TagName("h3"))).Text.CleanString();
                    var portfolio       = PortfolioRepository.GetByPortfolioNumberAndBankName(portfolioNumber,
                                                                                              Constants.DownloadHandler.BankNameRaiffeisen);
                    if (portfolio == null)
                    {
                        portfolio = new PortfolioEntity
                        {
                            PortfolioNumber = portfolioNumber,
                            BankName        = Constants.DownloadHandler.BankNameRaiffeisen,
                            AccountName     = Constants.DownloadHandler.AccountNameDepot
                        };
                        PortfolioRepository.Insert(portfolio);
                    }

                    TakeScreenshot(portfolio.PortfolioNumber);

                    var resultingFile = DownloadFromWebElement(Browser.FindElement(By.ClassName("icon-csv")), portfolioNumber);
                    downloadResults.Add(new FileParserInput
                    {
                        OwningEntity = portfolio,
                        FileParser   =
                            ComponentContext.ResolveKeyed <IFileParser>(Constants.UniqueContainerKeys.FileParserRaiffeisenDepot),
                        FilePath     = resultingFile,
                        TargetEntity = typeof(RaiffeisenPositionEntity)
                    });
                }
            }
            catch (NoSuchElementException e)
            {
                Logger.LogWarning(e, "Error occured downloading depot status.");
            }
            return(downloadResults);
        }
        public void ShouldChangeAmountOfShareByUser()
        {
            var portfolioTableRepository = Substitute.For <IPortfolioTableRepository>();
            PortfolioServices portfolio  = new PortfolioServices(portfolioTableRepository);
            PortfolioEntity   args       = new PortfolioEntity()
            {
                UserEntityId = 1,
                ShareId      = 1,
                Amount       = 50
            };

            portfolio.ChangeAmountOfShares(args, -10);

            portfolioTableRepository.Contains(Arg.Is <PortfolioEntity>(
                                                  u => u.UserEntityId == args.UserEntityId &&
                                                  u.ShareId == args.ShareId &&
                                                  u.Amount == args.Amount - 10)).Returns(true);
            portfolioTableRepository.Received(1).SaveChanges();
        }
Beispiel #14
0
        public override object ExecuteCommand(InCourseRequest inCourseRequest)
        {
            foreach (var id in Ids)
            {
                PortfolioEntity request = (from d in context.Portfolios where d.IdPortfolio == id select d).Single();

                // PortfolioComposicion
                var portfolioSComposicion = (from d in context.PortfoliosComposicion where d.IdPortfolio == id select d).ToList();;
                context.PortfoliosComposicion.RemoveRange(portfolioSComposicion);


                // PortfolioUsuario
                var portfoliosUsuario = (from d in context.PortfoliosUsuario where d.IdPortfolio == id select d).ToList();
                context.PortfoliosUsuario.RemoveRange(portfoliosUsuario);

                // Portfolio
                context.Remove(request);
            }
            return(null);
        }
        public override object ExecuteCommand(InCourseRequest inCourseRequest)
        {
            IdUsuario = MAEUserSession.Instancia.IdUsuario;
            PortfolioEntity request = new PortfolioEntity()
            {
                EsDeSistema = EsDeSistema,
                Nombre      = Nombre,
                Codigo      = Codigo
            };

            var portfolioUsuario = new PortfolioUsuarioEntity()
            {
                Portfolio = request,
                IdUsuario = IdUsuario
            };

            this.AgregarAlContextoParaAlta(request);

            return(null);
        }
Beispiel #16
0
        public async Task GetPortfolio([Remainder][Summary("Portfolio name")] string name)
        {
            PortfolioEntity portfolio = await CloudTableUtility.RetrievePortfolioUsingPointQueryAsync(table, Context.User.Id.ToString(), name);

            await ReplyAsync("Portfolio: " + portfolio.RowKey);

            string             returnString = "";
            StockEntity        stock;
            List <StockEntity> stockList = new List <StockEntity>();
            var symbolList   = portfolio.Stocks.Trim().Split(" ");
            var newPriceList = await Yahoo.Symbols(symbolList).Fields(Field.RegularMarketPrice).QueryAsync();

            double totalValue         = 0;
            double totalCost          = 0;
            double totalTotalChange   = 0;
            double totalChangePercent = 0;

            foreach (var s in symbolList)
            {
                stock = await CloudTableUtility.RetrieveStockUsingPointQueryAsync(table, portfolio.RowKey, s);

                var newHoldingValue = stock.Shares * newPriceList[s].RegularMarketPrice;
                var oldHoldingValue = stock.Shares * stock.StartPrice;
                var changeInValue   = Math.Round((((newHoldingValue - oldHoldingValue) / oldHoldingValue * 100)), 2);
                var totalChange     = newHoldingValue - oldHoldingValue;

                totalValue       = totalValue + newHoldingValue;
                totalCost        = totalCost + oldHoldingValue;
                totalTotalChange = Math.Round(totalTotalChange + totalChange, 2);


                returnString += s + "   " + newHoldingValue + "(" + oldHoldingValue + ")   " + newPriceList[s].RegularMarketPrice + "(" + Math.Round(stock.StartPrice, 2) + ")" + "   " + totalChange + "(" + changeInValue + "%)" + "\n";
            }
            totalChangePercent = Math.Round((((totalValue - totalCost) / totalCost * 100)), 2);
            await ReplyAsync("TICKER  VALUE(COST)  PRICE(AVG. COST)  TOTAL(%): \n" + returnString + "\n" +
                             "Totals:\n" +
                             "VALUE(COST)  TOTAL(%)\n" +
                             totalValue + "(" + totalCost + ")" + "   " + totalTotalChange + "(" + totalChangePercent + "%)" + "\n");
        }
Beispiel #17
0
        public async Task AddToPortfolio([Remainder][Summary("Portfolio name and symbol")] string portfolioAndSymbol)
        {
            string[] pasList = portfolioAndSymbol.Split(' ');
            if (pasList.Count() < 2)
            {
                if (pasList.Count() == 1)
                {
                    await ReplyAsync("No symbol defined. \n" + "Format: smb! add to [protfolio name] [symbol] [shares]");
                }
                else
                {
                    await ReplyAsync("Invalid parameters. \n" + "Format: smb! add to [protfolio name] [symbol] [shares]");
                }
            }
            else
            {
                PortfolioEntity portfolio = await CloudTableUtility.RetrievePortfolioUsingPointQueryAsync(table, Context.User.Id.ToString(), pasList[0]);

                if (portfolio == null)
                {
                    await ReplyAsync("No portfolio with that name.");
                }
                string[] symbols = new string[pasList.Length - 1];
                Array.Copy(pasList, 1, symbols, 0, pasList.Count() - 1);
                var prices = await Yahoo.Symbols(symbols).Fields(Field.RegularMarketPrice).QueryAsync();

                StockEntity        stock;
                List <StockEntity> newStocks = new List <StockEntity>();
                for (int i = 0; i < symbols.Length - 1; i++)
                {
                    if (i % 2 == 0)
                    {
                        int shares = 0;
                        int.TryParse(symbols[i + 1], out shares);
                        if (shares > 0)
                        {
                            stock            = new StockEntity(portfolio.RowKey, symbols[i]);
                            stock.Shares     = shares;
                            stock.StartPrice = prices[symbols[i]].RegularMarketPrice;
                            newStocks.Add(stock);
                        }
                        else
                        {
                            await ReplyAsync("Error adding holdings to portfolio.");

                            return;
                        }
                    }
                }
                foreach (var s in newStocks)
                {
                    if (portfolio.Stocks.Split(' ').Contains(s.RowKey))
                    {
                        StockEntity stockEntity = await CloudTableUtility.RetrieveStockUsingPointQueryAsync(table, portfolio.RowKey, s.RowKey);

                        var newAddedCost = s.Shares * s.StartPrice;
                        var oldCost      = stockEntity.Shares * stockEntity.StartPrice;
                        var totalShares  = s.Shares + stockEntity.Shares;
                        var startPrice   = Math.Round((newAddedCost + oldCost) / totalShares, 2);

                        stockEntity.Shares     = totalShares;
                        stockEntity.StartPrice = startPrice;

                        await CloudTableUtility.InsertOrMergeStockAsync(table, stockEntity);
                    }
                    else
                    {
                        await CloudTableUtility.InsertOrMergeStockAsync(table, s);

                        portfolio.Stocks += (" " + s.RowKey + " ").Trim();
                    }
                }

                await CloudTableUtility.InsertOrMergePortfolioAsync(table, portfolio);

                await ReplyAsync("Holdings added to " + portfolio.RowKey);
            }
        }
Beispiel #18
0
 public void ChangeAmountOfShares(PortfolioEntity args, int value)
 {
     this.portfolioServices.ChangeAmountOfShares(args, value);
     Logger.Log.Info($"У пользователя изменено количество акций {args.Share.Name} на {value} шт.");
 }
Beispiel #19
0
        protected override IEnumerable <FileParserInput> DownloadTransactions()
        {
            var transactions = new List <FileParserInput>();

            try
            {
                Browser.WaitForJavaScript(5000);
                //Konto

                var accountNumber = Browser.FindElements(By.ClassName("C0"))[3].Text;
                var iban          = GetIban();

                //go to account transactions
                Browser.Navigate().GoToUrl("https://konto.flatex.at/banking-flatex.at/accountPostingsFormAction.do");
                Browser.WaitForJavaScript();
                var balanceString =
                    Browser.FindElements(new ByChained(By.ClassName("Details"), By.ClassName("Value")))[0].Text
                    .ExtractDecimalNumberString();
                var valueParserDe =
                    ComponentContext.ResolveKeyed <IValueParser>(Constants.UniqueContainerKeys.ValueParserGermanDecimal);
                var balance = (decimal)valueParserDe.Parse(balanceString);
                //Date range -1 year
                var fromDate = Browser.FindElement(By.Id("accountPostingsForm_dateRangeComponent_startDate"));
                fromDate.SetAttribute("value", DateTime.Today.AddMonths(-2).ToString("dd.MM.yyyy"));
                Browser.FindElement(By.Id("accountPostingsForm_applyFilterButton")).Click();
                //excel download
                TakeScreenshot(iban);
                var resultingFile =
                    DownloadFromWebElement(Browser.FindElement(By.Id("accountPostingsForm_excelExportButton")), iban);
                //check for account or create new
                var bankAccount = BankAccountRepository.GetByIban(iban);
                if (bankAccount == null)
                {
                    bankAccount = new BankAccountEntity
                    {
                        AccountNumber = accountNumber,
                        Iban          = iban,
                        BankName      = Constants.DownloadHandler.BankNameFlatex,
                        AccountName   = Constants.DownloadHandler.AccountNameGiro
                    };
                    BankAccountRepository.Insert(bankAccount);
                }
                transactions.Add(new FileParserInput
                {
                    OwningEntity = bankAccount,
                    FileParser   =
                        ComponentContext.ResolveKeyed <IFileParser>(Constants.UniqueContainerKeys.FileParserFlatexGiro),
                    FilePath            = resultingFile,
                    TargetEntity        = typeof(FlatexTransactionEntity),
                    Balance             = balance,
                    BalanceSelectorFunc =
                        () => BankTransactionRepository.GetAllForAccountId(bankAccount.Id).Sum(entity => entity.Amount)
                });
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "Exception occured while downloading Flatex Giro transactions");
            }
            try
            {
                //Depot
                NavigateHome();
                Browser.WaitForJavaScript(5000);
                var portfolioNumber = Browser.FindElements(By.ClassName("C0"))[5].Text;
                Browser.Navigate().GoToUrl("https://konto.flatex.at/banking-flatex.at/depositStatementFormAction.do");
                TakeScreenshot(portfolioNumber);
                var resultingFile = DownloadFromWebElement(
                    Browser.FindElement(By.Id("depositStatementForm_excelExportButton")), portfolioNumber);

                var portfolio = PortfolioRepository.GetByPortfolioNumberAndBankName(portfolioNumber,
                                                                                    Constants.DownloadHandler.BankNameFlatex);
                if (portfolio == null)
                {
                    portfolio = new PortfolioEntity
                    {
                        PortfolioNumber = portfolioNumber,
                        BankName        = Constants.DownloadHandler.BankNameFlatex,
                        AccountName     = Constants.DownloadHandler.AccountNameDepot
                    };
                    PortfolioRepository.Insert(portfolio);
                }

                transactions.Add(new FileParserInput
                {
                    OwningEntity = portfolio,
                    FileParser   = ComponentContext.ResolveKeyed <IFileParser>(Constants.UniqueContainerKeys.FileParserFlatexDepot),
                    FilePath     = resultingFile,
                    TargetEntity = typeof(FlatexPositionEntity)
                });
            }
            catch (Exception ex)
            {
                Logger.LogWarning(ex, "Exception occured while downloading Flatex Portfolio transactions");
            }
            return(transactions);
        }
 public void ChangeAmountOfShares(PortfolioEntity args, int value)
 {
     args.Amount = args.Amount + value;
     repo.SaveChanges();
 }
 public void AddNewUsersShares(PortfolioEntity args)
 {
     this.db.Portfolio.Add(args);
 }
Beispiel #22
0
 public async Task AddStockItem(PortfolioEntity dbItem)
 {
     _stocksContext.Portfolio.Add(dbItem);
     await _stocksContext.SaveChangesAsync();
 }