public async Task UpdatePage() { vm.Chart.IsLoading = true; vm.CurrencySymbol = App.currencySymbol; /// Empty diversification chart and reset the Total amounts PortfolioChartGrid.ColumnDefinitions.Clear(); PortfolioChartGrid.Children.Clear(); /// Update the purchase details first for (int i = 0; i < vm.Portfolio.Count; i++) { await PortfolioHelper.UpdatePurchase(vm.Portfolio[i]); } vm.TotalInvested = vm.Portfolio.Sum(x => x.InvestedQty); vm.TotalWorth = vm.Portfolio.Sum(x => x.Worth); vm.TotalDelta = vm.Portfolio.Sum(x => x.Profit); vm.ROI = Math.Round(100 * (vm.TotalWorth - vm.TotalInvested) / vm.TotalInvested, 1); /// Create the diversification grid var grouped = vm.Portfolio.GroupBy(x => x.Crypto).OrderByDescending(x => x.Sum(item => item.Worth)); foreach (var purchases in grouped) { var crypto = purchases.Key.ToUpperInvariant(); var worth = purchases.ToList().Sum(x => x.Worth); ColumnDefinition col = new ColumnDefinition(); col.Width = new GridLength(worth, GridUnitType.Star); PortfolioChartGrid.ColumnDefinitions.Add(col); // Use a grid for Vertical alignment var g = new Grid(); g.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 0, 255)); g.BorderThickness = new Thickness(0); g.VerticalAlignment = VerticalAlignment.Stretch; var val = Math.Round((worth / vm.TotalWorth) * 100, 1); ToolTipService.SetToolTip(g, $"{crypto} {val}% \n{worth}{vm.CurrencySymbol}"); ToolTipService.SetPlacement(g, PlacementMode.Right); var t = new TextBlock() { Text = crypto + "\n" + $"{val}%", FontSize = 12, HorizontalAlignment = HorizontalAlignment.Center, HorizontalTextAlignment = TextAlignment.Center, VerticalAlignment = VerticalAlignment.Center }; g.Children.Add(t); g.Background = ColorConstants.GetCoinBrush(crypto, 100); PortfolioChartGrid.Children.Add(g); Grid.SetColumn(g, PortfolioChartGrid.Children.Count - 1); } /// Finally, update the chart of the portfolio's worth await UpdatePortfolioChart(); }
public override void ExecuteAfterSuccess() { foreach (int IdProducto in Productos) { PortfolioHelper.DesAsociarProdutoParty(IdProducto); } }
private void button_import_Click(object sender, EventArgs e) { // 导入数据时,可以通过导入的方式进行改仓,或记录今昨 // 比如第一天收盘后多5手,第二天收盘后多2手,按此记录即可 // 它会在第二天的指定时间平仓3手 OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "CSV文件(*.csv)|*.csv|所有文件(*.*)|*.*"; //设置“另存为文件类型”或“文件类型”框中出现的选择内容 ofd.Title = "打开文件"; //获取或设置文件对话框标题 ofd.RestoreDirectory = true; if (ofd.ShowDialog() != DialogResult.OK) { return; } var list = PortfolioHelper.from_csv <PositionItem>(ofd.FileName); foreach (var it in list) { var inst = framework.InstrumentManager.GetBySymbol(it.Symbol); var pf = framework.PortfolioManager.GetByName(it.PortfolioName); if (pf == null) { pf = new SmartQuant.Portfolio(it.PortfolioName); framework.PortfolioManager.Add(pf); pf.Parent = framework.PortfolioManager.GetByName(it.Parent); } if (inst == null) { continue; } var position = pf.GetPosition(inst); var old_qty = 0.0; if (it.Side == PositionSide.Long) { if (position != null) { old_qty = position.LongPositionQty; } PortfolioHelper.AddLongPosition(framework, pf, it.EntryDate, inst, inst.CurrencyId, old_qty, it.Qty, it.EntryPrice, "Import from csv"); } else { if (position != null) { old_qty = position.ShortPositionQty; } PortfolioHelper.AddShortPosition(framework, pf, it.EntryDate, inst, inst.CurrencyId, old_qty, it.Qty, it.EntryPrice, "Import from csv"); } } // refresh(); }
private async void Page_Loaded(object sender, RoutedEventArgs e) { /// Get timespan before updating timeSpan = App._LocalSettings.Get <string>(UserSettings.Timespan); TimeRangeRadioButtons.TimeSpan = timeSpan; (timeUnit, limit, aggregate) = GraphHelper.TimeSpanParser[timeSpan]; /// Get the portfolio and group it LocalPurchases = await RetrievePortfolio(); vm.Portfolio = await PortfolioHelper.GroupPortfolio(LocalPurchases); await UpdatePage(); }
public override object ExecuteCommand(InCourseRequest inCourseRequest) { var request = (from d in context.PortfoliosComposicion where IdPortfoliosComposiciones.Contains(d.IdPortfoliosComposicion) select d).ToList(); Productos = request.Select(y => y.IdProducto).Distinct().ToList(); foreach (int IdProducto in Productos) { PortfolioHelper.DesHabilitarPortfoliosProductosFCE(IdProducto); //TODO poner la key que corresponda. string key = string.Empty; OrdenHelper.NotificarDesAsociacionProductoPortfolio(IdProducto, "EliminaPortfolioComposicionEmpresasCommand", key); } return(null); }
private async void NewPurchase_click(object sender, RoutedEventArgs e) { var dialog = new PortfolioEntryDialog() { NewPurchase = new PurchaseModel() { Crypto = vm.Coin.Name }, SuggestionCoin = new SuggestionCoin(vm.Coin) }; var response = await dialog.ShowAsync(); if (response == ContentDialogResult.Primary) { vm.Purchases.Add(dialog.NewPurchase); PortfolioHelper.AddPurchase(dialog.NewPurchase); } }
private async Task <DialogTurnResult> LoadPortfolioStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationtoken) { var portfolio = await portfolioStateAccessor.GetAsync(stepContext.Context); if (portfolio?.LoadedAt == null || portfolio.LoadedAt < DateTime.Now.AddDays(-1)) { try { portfolio = portfolio ?? new PortfolioState(); await stepContext.Context.SendActivityAsync($"Loading portfolio ..."); var reply = stepContext.Context.Activity.CreateReply(); reply.Text = null; reply.Type = ActivityTypes.Typing; await stepContext.Context.SendActivityAsync(reply); //show typing pause var userInfo = await userInfoAccessor.GetAsync(stepContext.Context); await investService.LoadPortfolio(userInfo, portfolio); if (portfolio.Status != Api.StockStatus.Success) { await stepContext.Context.SendActivityAsync(GetStockLoadErrorMessage(portfolio.Status)); return(await stepContext.EndDialogAsync()); } } catch (Exception ex) { await stepContext.Context.SendActivityAsync("Error: " + ex.Message); } } if (portfolio?.LoadedAt != null) { //await stepContext.Context.SendActivityAsync($"Portfolio with {portfolio.Stocks.Count()} positions last loaded at {portfolio.LoadedAt}."); var ratesMsg = new PortfolioHelper().GetRatesMessage(portfolio); await stepContext.Context.SendActivityAsync(ratesMsg); return(await stepContext.NextAsync()); } return(await stepContext.EndDialogAsync()); }
private async Task <DialogTurnResult> LoadPricesStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationtoken) { var portfolio = await portfolioStateAccessor.GetAsync(stepContext.Context); var missing = await investService.LoadPrices(portfolio); if (missing.Any()) { await stepContext.Context.SendActivityAsync( $"Not all prices loaded yet. Waiting for [{string.Join(", ", missing)}]"); } else { var helper = new PortfolioHelper(); //Recommendations are var recommendations = helper.GetRecommendations(portfolio); if (recommendations.Any()) { await stepContext.Context.SendActivityAsync("Recommendations for today: "); foreach (var r in recommendations) { await stepContext.Context.SendActivityAsync(r); } } else { await stepContext.Context.SendActivityAsync("Now all in the defined range."); } var marks = helper.GetMarksStatus(portfolio); if (!string.IsNullOrEmpty(marks)) { await stepContext.Context.SendActivityAsync(marks); } await stepContext.Context.SendActivityAsync("TOTALS: " + helper.GetSummary(portfolio)); } return(await stepContext.EndDialogAsync()); }
public IActionResult Orders() { if (HttpContext.Session.GetInt32("userid") == null) { return(RedirectToAction("Login", "User")); } var userlist = (new UserHelper()).GetUsers(); var myuser = userlist.FirstOrDefault(u => u.Id == HttpContext.Session.GetInt32("userid")); ViewData["AccountBalance"] = myuser.AccountBalance.ToString("#,##0"); var portfolioHelper = new PortfolioHelper(); var PortfolioValue = portfolioHelper.GetPortfolioByUser(myuser); ViewData["PortfolioValue"] = PortfolioValue.Value.ToString("#,##0"); var UserPortfolio = portfolioHelper.GetPortfolioByUser(myuser).Shares.ToList(); return(View("OrderHistory", UserPortfolio)); }
/// ############################################################################################### /// Add purchase dialog private async void AddTransaction_click(object sender, RoutedEventArgs e) { var dialog = new PortfolioEntryDialog() { NewPurchase = new PurchaseModel(), PrimaryButtonText = "Add", Title = "💵 New transaction" }; var response = await dialog.ShowAsync(); if (response == ContentDialogResult.Primary) { dialog.NewPurchase.CryptoName = App.coinListPaprika.FirstOrDefault( x => x.symbol == dialog.NewPurchase.Crypto).name; vm.Portfolio.Add(dialog.NewPurchase); await PortfolioHelper.AddPurchase(dialog.NewPurchase); // Update everything await UpdatePage(); } }
private async Task UpdatePortfolio() { var portfolio = await PortfolioHelper.GetPortfolio(vm.Coin.Name); vm.Purchases = new ObservableCollection <PurchaseModel>(portfolio); for (int i = 0; i < vm.Purchases.Count; i++) { vm.Purchases[i] = await PortfolioHelper.UpdatePurchase(vm.Purchases[i]); } vm.TotalQty = vm.Purchases.Sum(x => x.CryptoQty); vm.TotalProfit = vm.Purchases.Sum(x => x.Profit); vm.TotalValue = vm.TotalQty * vm.Coin.Price; //vm.TotalValue = vm.Purchases.Sum(x => x.Worth); var totalInvested = vm.Purchases.Sum(x => x.InvestedQty); if (totalInvested != 0) { vm.AvgPrice = NumberHelper.Rounder(totalInvested / vm.TotalQty); } }
public override object ExecuteCommand(InCourseRequest inCourseRequest) { PortfolioHelper.SetearPorDefecto(r_id, MAEUserSession.Instancia.IdUsuario); return(null); }
public override ExecutionResult Execute(InCourseRequest inCourseRequest) { PortfolioHelper.SetearPorDefecto(r_id, MAEUserSession.Instancia.IdUsuario); return(ExecutionResult.ReturnInmediatelyAndQueueOthers(null)); }
public Statistics(Settings settings, PortfolioHelper portfolio) { _settings = settings; _portfolio = portfolio; }
private void button_export_Click(object sender, EventArgs e) { // 导出时其实可以划分成今昨,分别导出成昨天收盘后的持仓与今天收盘后的持仓即可 var list = new List <PositionItem>(); // 先导出投资组合 foreach (var portfolio in framework.PortfolioManager.Portfolios) { var parent = portfolio.Parent == null ? "" : portfolio.Parent.Name; list.Add(new PositionItem() { Parent = parent, PortfolioName = portfolio.Name, Symbol = "", Side = PositionSide.Long, Qty = 0, EntryPrice = 0, EntryDate = DateTime.Today, }); } // 再导出持仓 foreach (var portfolio in framework.PortfolioManager.Portfolios.Reverse()) { var parent = portfolio.Parent == null ? "" : portfolio.Parent.Name; foreach (var position in portfolio.Positions) { // 注意,这种写法的入场价与入场时间并不对应 if (position.Fills.Count == 0) { continue; } var symbol = position.Instrument.Symbol; var fill = position.Fills.Last(); if (position.LongPositionQty > 0) { list.Add(new PositionItem() { Parent = parent, PortfolioName = portfolio.Name, Symbol = symbol, Side = PositionSide.Long, Qty = position.LongPositionQty, EntryPrice = fill.Price, EntryDate = fill.DateTime }); } if (position.ShortPositionQty > 0) { list.Add(new PositionItem() { Parent = parent, PortfolioName = portfolio.Name, Symbol = symbol, Side = PositionSide.Short, Qty = position.ShortPositionQty, EntryPrice = fill.Price, EntryDate = fill.DateTime }); } } } Console.WriteLine("=================================================="); Console.WriteLine("Parent,PortfolioName,Symbol,Side,Qty,EntryPrice,EntryDate"); foreach (var it in list) { Console.WriteLine(it); } SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "CSV文件(*.csv)|*.csv|所有文件|*.*"; //设置文件类型 sfd.FileName = "导出持仓"; //设置默认文件名 sfd.AddExtension = true; //设置自动在文件名中添加扩展名 if (sfd.ShowDialog() == DialogResult.OK) { PortfolioHelper.to_csv(sfd.FileName, list); } }
private void CellEndEdit(SmartQuant.Portfolio pf, SmartQuant.Position pos) { double price = GetCellDouble(this.treeGridView1.Rows[this.treeGridView1.CurrentCell.RowIndex].Cells[IDX_EntryPrice]); DateTime dateTime = GetCellDateTime(this.treeGridView1.Rows[this.treeGridView1.CurrentCell.RowIndex].Cells[IDX_EntryDate]); switch (this.treeGridView1.CurrentCell.ColumnIndex) { case IDX_AccountValue: { double new_data = GetCellDouble(this.treeGridView1.CurrentCell); PortfolioHelper.AddAccountValue(framework, pf, dateTime, pf.Account.CurrencyId, pf.AccountValue, new_data, "TreeGridView"); } break; case IDX_Short: { if (pos == null) { Console.WriteLine("Error:Position == null"); return; } double new_data = GetCellDouble(this.treeGridView1.CurrentCell); if (new_data < 0) { Console.WriteLine("Error:Short must >0"); return; } PortfolioHelper.AddShortPosition(framework, pf, dateTime, pos.Instrument, pos.Instrument.CurrencyId, pos.ShortPositionQty, new_data, price, "TreeGridView"); } break; case IDX_Long: { if (pos == null) { Console.WriteLine("Error:Position == null"); return; } double new_data = GetCellDouble(this.treeGridView1.CurrentCell); if (new_data < 0) { Console.WriteLine("Error:Long must >0"); return; } PortfolioHelper.AddLongPosition(framework, pf, dateTime, pos.Instrument, pos.Instrument.CurrencyId, pos.LongPositionQty, new_data, price, "TreeGridView"); } break; case IDX_Symbol: { string new_data = this.treeGridView1.CurrentCell.Value.ToString(); if (string.IsNullOrWhiteSpace(new_data)) { Console.WriteLine("Error:Symbol is empty"); return; } var inst = framework.InstrumentManager.Instruments[new_data]; if (inst == null) { Console.WriteLine("Error:Instrument is not exists"); return; } pos = pf.GetPosition(inst); if (pos != null) { Console.WriteLine("Error:Position is exists"); return; } PortfolioHelper.AddPosition2(framework, pf, dateTime, inst, inst.CurrencyId, OrderSide.Buy, SubSide.Undefined, 0, price, "TreeGridView"); } break; default: return; } }