public async Task RemoveCashTransactionsFromTrade(Trade trade, IEnumerable <CashTransaction> cashTransactions) { foreach (var ct in cashTransactions) { await TradesRepository.RemoveCashTransaction(trade, ct).ConfigureAwait(false); } }
private async Task Open(IList trades) { foreach (Trade trade in trades) { trade.Open = true; } await TradesRepository.UpdateTrade(trades : trades.Cast <Trade>()); }
public StatementHandler(IDBContext context, IDialogService dialogService, IDataSourcer dataSourcer) { _dialogService = dialogService; AssembleComponents(); DownloaderNames = StatementDownloaders.Select(x => x.Metadata.Name).ToList(); ParserNames = StatementParsers.Select(x => x.Metadata.Name).ToList(); _tradeRepository = new TradesRepository(context, dataSourcer); }
public FXTransactionsPageViewModel(IDBContext context, IDataSourcer datasourcer, IDialogService dialogService) : base(dialogService) { Context = context; TradesRepository = new TradesRepository(Context, datasourcer); FXTransactions = new CollectionViewSource(); FXTransactions.Source = Context.FXTransactions.Local; FXTransactions.View.SortDescriptions.Add(new SortDescription("DateTime", ListSortDirection.Descending)); CreateCommands(); }
private async Task UpdateTradeStats(IList trades) { if (trades == null || trades.Count == 0) { return; } foreach (Trade t in trades) { await TradesRepository.UpdateStats(t); } await TradesRepository.UpdateTrade(trades : trades.Cast <Trade>()); }
public FXTransactionsPageViewModel(IContextFactory contextFactory, IDataSourcer datasourcer, IDialogCoordinator dialogService, IAppSettings settings, DataContainer data, IMainViewModel mainVm) : base(dialogService) { _contextFactory = contextFactory; _mainVm = mainVm; FXTransactions = new CollectionViewSource(); FXTransactions.Source = data.FXTransactions; FXTransactions.View.SortDescriptions.Add(new SortDescription("DateTime", ListSortDirection.Descending)); TradesRepository = new TradesRepository(contextFactory, datasourcer, settings); CreateCommands(); }
/// <summary> /// Opens/closes a trade /// </summary> public async Task ChangeOpenState(bool newOpenState, Trade trade) { if (newOpenState == false && !trade.IsClosable()) { return; } using (var dbContext = _contextFactory.Get()) { trade.Open = newOpenState; await TradesRepository.UpdateStats(trade); await TradesRepository.UpdateTrade(trade); } }
public TradesPageViewModel(IDBContext context, IDialogService dialogService, IDataSourcer datasourcer, MainViewModel parent) : base(dialogService) { Context = context; Parent = parent; Datasourcer = datasourcer; TradesRepository = new TradesRepository(Context, Datasourcer); TradesSource = new CollectionViewSource(); TradesSource.Source = Context.Trades.Local; TradesSource.View.SortDescriptions.Add(new SortDescription("DateOpened", ListSortDirection.Descending)); Strategies = new ObservableCollection <Strategy>(); CreateCommands(); }
public async Task <Trade> CreateTrade(string name) { //only add a trade if there's a name in the box if (String.IsNullOrEmpty(name)) { return(null); } var newTrade = new Trade { Name = name, Open = true }; await TradesRepository.Add(newTrade); _data.Trades.Add(newTrade); return(newTrade); }
public OrdersPageViewModel(IDBContext context, IDialogService dialogService, IDataSourcer datasourcer, MainViewModel parent) : base(dialogService) { Context = context; Parent = parent; Datasourcer = datasourcer; TradesRepository = new TradesRepository(Context, Datasourcer); OrdersSource = new CollectionViewSource(); OrdersSource.Source = Context.Orders.Local; OrdersSource.SortDescriptions.Add(new SortDescription("TradeDate", ListSortDirection.Descending)); ExecutionStatsGenerator = new ExecutionStatsGenerator(datasourcer); CreateCommands(); }
public TradeWindow(TradeViewModel viewModel, IContextFactory contextFactory, TradesRepository tradesRepo) { _contextFactory = contextFactory; _tradesRepo = tradesRepo; ViewModel = viewModel; InitializeComponent(); DataContext = ViewModel; InitializeFontSizes(); FontFamilyComboBox.ItemsSource = Fonts.SystemFontFamilies; FontSizeComboBox.ItemsSource = FontSizes; //load the notes LoadNotes(); }
public TradesPageViewModel(IContextFactory contextFactory, IDialogCoordinator dialogService, IDataSourcer datasourcer, IAppSettings settings, DataContainer data, IMainViewModel parent) : base(dialogService) { Parent = parent; _contextFactory = contextFactory; Datasourcer = datasourcer; _data = data; TradesRepository = new TradesRepository(contextFactory, datasourcer, settings); TradesSource = new CollectionViewSource(); TradesSource.Source = _data.Trades; TradesSource.View.SortDescriptions.Add(new SortDescription("DateOpened", ListSortDirection.Descending)); Strategies = data.Strategies; CreateCommands(); }
public OrdersPageViewModel(IContextFactory contextFactory, IDialogCoordinator dialogService, IDataSourcer datasourcer, IAppSettings settings, DataContainer data, IScriptRunner scriptRunner, IMainViewModel parent) : base(dialogService) { Parent = parent; _contextFactory = contextFactory; Datasourcer = datasourcer; _data = data; _scriptRunner = scriptRunner; TradesRepository = new TradesRepository(contextFactory, datasourcer, settings); OrdersSource = new CollectionViewSource(); OrdersSource.Source = data.Orders; OrdersSource.SortDescriptions.Add(new SortDescription("TradeDate", ListSortDirection.Descending)); ExecutionStatsGenerator = new ExecutionStatsGenerator(datasourcer); CreateCommands(); }
public MainViewModel(IDBContext context, IDataSourcer datasourcer, IDialogCoordinator dialogService) : base(dialogService) { Context = context; Datasourcer = datasourcer; TradesRepository = new TradesRepository(context, datasourcer, Properties.Settings.Default.optionsCapitalUsageMultiplier); StatementHandler = new StatementHandler( context, dialogService, datasourcer, TradesRepository, this); CreateSubViewModels(); SelectedPageViewModel = OpenPositionsPageViewModel; CreateCommands(); ScriptRunner = new ScriptRunner(TradesRepository); }
public MainViewModel(IContextFactory contextFactory, IDataSourcer datasourcer, IDialogCoordinator dialogService, IAppSettings settings, DataContainer data) : base(dialogService) { Datasourcer = datasourcer; Settings = settings; Data = data; _tradesRepository = new TradesRepository(contextFactory, datasourcer, settings); StatementHandler = new StatementHandler( dialogService, contextFactory, settings, this); this._contextFactory = contextFactory; ScriptRunner = new ScriptRunner(contextFactory, _tradesRepository, data); CreateCommands(); CreateSubViewModels(); SelectedPageViewModel = OpenPositionsPageViewModel; }
private async Task ResetTrades(IList trades) { if (trades == null || trades.Count == 0) { return; } MessageDialogResult res = await DialogService.ShowMessageAsync(Parent, "Reset Trade", string.Format("Are you sure you want to reset {0} trades?", trades.Count), MessageDialogStyle.AffirmativeAndNegative); if (res != MessageDialogResult.Affirmative) { return; } //reset the trades foreach (Trade trade in trades) { await TradesRepository.Reset(trade); } }
public MainWindow() { //make sure we have a database connection and stuff, otherwise show the dialog to set db settings try { DBUtils.CheckDBConnection(); } catch { App.Splash.LoadComplete(); var dbDetailsWindow = new DBPicker(); dbDetailsWindow.ShowDialog(); } //initialize logging InitializeLogging(); //Log unhandled exceptions AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException; //set the connection string DBUtils.SetConnectionString(); Context = new DBContext(); //create db if it doesn't exist Context.Database.Initialize(false); //check for any currencies, seed the db with initial values if nothing is found if (!Context.Currencies.Any()) { Seed.DoSeed(); } //check for empty account fields if (Context.EquitySummaries.Any(x => x.AccountID == null)) { App.Splash.LoadComplete(); var accountMigrationWindow = new AccountMigrationWindow(); accountMigrationWindow.ShowDialog(); } var qdmsSource = new ExternalDataSources.QDMS(); Datasourcer = new DataSourcer(Context, qdmsSource); TradesRepository = new TradesRepository(Context, Datasourcer); IDialogService dialogService = new DialogService(this); ViewModel = new MainViewModel(Context, Datasourcer, dialogService); ///////////////////////////////////////////////////////// InitializeComponent(); ///////////////////////////////////////////////////////// DataContext = ViewModel; //Create the load statement menus using the loaded plugins PopulateStatementMenus(); //Restore column ordering, widths, and sorting LoadDataGridLayouts(); //A hack to force the heavy stuff to load, //providing snappier navigation at the expense of longer startup time #if !DEBUG ViewModel.TradesPageViewModel.Refresh(); TradesGrid.Measure(new Size(500, 500)); ViewModel.OrdersPageViewModel.Refresh(); OrdersGrid.Measure(new Size(500, 500)); ViewModel.CashTransactionsPageViewModel.Refresh(); CashTransactionsGrid.Measure(new Size(500, 500)); #endif //hiding the tab headers Style s = new Style(); s.Setters.Add(new Setter(VisibilityProperty, Visibility.Collapsed)); MainTabCtl.ItemContainerStyle = s; //load the open positions page data ViewModel.RefreshCurrentPage(); //close the slash screen App.Splash.LoadComplete(); ShowChangelog(); }
public async Task RemoveFxTransactionFromTrade(Trade trade, FXTransaction fxTransaction) { await TradesRepository.RemoveFXTransaction(trade, fxTransaction); }
public async Task AddFxTransactionToTrade(Trade trade, FXTransaction fxTransaction) { await TradesRepository.AddFXTransaction(trade, fxTransaction); }
internal static async Task Import(DataContainer existingData, DataContainer newData, string accountId, IContextFactory contextFactory, TradesRepository tradesRepo) { using (var dbContext = contextFactory.Get()) { //Accounts foreach (var newAccount in newData.Accounts) { if (!existingData.Accounts.Any(x => x.AccountId == newAccount.AccountId)) { dbContext.Accounts.Add(newAccount); existingData.Accounts.Add(newAccount); } else { dbContext.Attach(existingData.Accounts.First(x => x.AccountId == newAccount.AccountId)); } } var selectedAccount = existingData.Accounts.First(x => x.AccountId == accountId); //then we have to attach the existing currencies to prevent attempts at re-insertion foreach (var currency in existingData.Currencies) { dbContext.Attach(currency); } var currencyDict = existingData.Currencies.ToDictionary(x => x.Name, x => x); //attach existing instruments foreach (var instrument in existingData.Instruments) { dbContext.Attach(instrument); } //then add new instruments foreach (var newInstrument in newData.Instruments) { if (!existingData.Instruments.Any(x => x.ConID == newInstrument.ConID)) { dbContext.Instruments.Add(newInstrument); existingData.Instruments.Add(newInstrument); } } await dbContext.SaveChangesAsync().ConfigureAwait(false); //Cash Transactions var latestExistingCashTransaction = dbContext.CashTransactions.Where(x => x.AccountID == selectedAccount.ID).OrderByDescending(x => x.TransactionDate).FirstOrDefault(); var latestDate = latestExistingCashTransaction == null ? new DateTime(1970, 1, 1) : latestExistingCashTransaction.TransactionDate; foreach (var newCashTransaction in newData.CashTransactions) { if (newCashTransaction.TransactionDate <= latestDate) { continue; } newCashTransaction.Account = selectedAccount; newCashTransaction.Currency = currencyDict[newCashTransaction.CurrencyString]; newCashTransaction.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == newCashTransaction.ConID); dbContext.CashTransactions.Add(newCashTransaction); existingData.CashTransactions.Add(newCashTransaction); } //Orders + Executions DateTime lastDate = dbContext.Orders.Any(x => x.AccountID == selectedAccount.ID) ? dbContext.Orders.Where(x => x.AccountID == selectedAccount.ID).Max(x => x.TradeDate) : new DateTime(1970, 1, 1); foreach (var newOrder in newData.Orders) { if (newOrder.TradeDate <= lastDate) { continue; } if (newOrder.AssetCategory == AssetClass.Cash) { //These are currency trades. But currencies aren't provided in the SecuritiesInfos //So we have to hack around it and add the currency as an instrument "manually" if it's not in yet newOrder.Instrument = TryAddAndGetCurrencyInstrument(newOrder, existingData, dbContext); } else { newOrder.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == newOrder.ConID); } newOrder.Account = selectedAccount; newOrder.Currency = currencyDict[newOrder.CurrencyString]; newOrder.CommissionCurrency = currencyDict[newOrder.CommissionCurrencyString]; //then the executions in that order foreach (var exec in newOrder.Executions) { exec.Account = selectedAccount; exec.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == exec.ConID); exec.Currency = currencyDict[exec.CurrencyString]; exec.CommissionCurrency = currencyDict[exec.CommissionCurrencyString]; } //and finally add existingData.Orders.Add(newOrder); existingData.Executions.AddRange(newOrder.Executions); dbContext.Orders.Add(newOrder); } //Equity Summaries foreach (var eq in newData.EquitySummaries) { eq.Account = selectedAccount; if (existingData.EquitySummaries.Count(x => x.Date == eq.Date && x.AccountID == selectedAccount.ID) == 0) { dbContext.EquitySummaries.Add(eq); existingData.EquitySummaries.Add(eq); } } //Open Positions //start by deleting the old ones var toRemove = dbContext.OpenPositions.Where(x => x.AccountID == selectedAccount.ID).ToList(); dbContext.OpenPositions.RemoveRange(toRemove); //then add the new ones foreach (var op in newData.OpenPositions) { op.Account = selectedAccount; op.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == op.ConID); op.Currency = currencyDict[op.CurrencyString]; dbContext.OpenPositions.Add(op); } //FX Rates foreach (var fxRate in newData.FXRates) { fxRate.FromCurrency = currencyDict[fxRate.FromCurrencyString]; fxRate.ToCurrency = currencyDict[fxRate.ToCurrencyString]; if (!existingData.FXRates.Any(x => x.FromCurrency.ID == fxRate.ID && x.ToCurrency.ID == fxRate.ToCurrency.ID && x.Date == fxRate.Date)) { dbContext.FXRates.Add(fxRate); existingData.FXRates.Add(fxRate); } } //Prior Positions lastDate = dbContext.PriorPositions.Any(x => x.AccountID == selectedAccount.ID) ? dbContext.PriorPositions.Where(x => x.AccountID == selectedAccount.ID).Max(x => x.Date) : new DateTime(1, 1, 1); foreach (var priorPosition in newData.PriorPositions) { if (priorPosition.Date > lastDate) { priorPosition.Account = selectedAccount; priorPosition.Currency = currencyDict[priorPosition.CurrencyString]; priorPosition.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == priorPosition.ConID); dbContext.PriorPositions.Add(priorPosition); existingData.PriorPositions.Add(priorPosition); } } //Open Dividend Accruals //delete and then add the new ones dbContext.DividendAccruals.RemoveRange(dbContext.DividendAccruals.Where(x => x.AccountID == selectedAccount.ID).ToList()); existingData.DividendAccruals.Clear(); foreach (var dividendAccrual in newData.DividendAccruals) { dividendAccrual.Currency = currencyDict[dividendAccrual.CurrencyString]; dividendAccrual.Instrument = existingData.Instruments.FirstOrDefault(x => x.ConID == dividendAccrual.ConID); dividendAccrual.Account = selectedAccount; if (dividendAccrual.Instrument == null) { var logger = LogManager.GetCurrentClassLogger(); logger.Log(LogLevel.Error, "Could not find instrument for dividend accrual with conid: " + dividendAccrual.ConID); } else { dbContext.DividendAccruals.Add(dividendAccrual); existingData.DividendAccruals.Add(dividendAccrual); } } //FX Positions //remove existing then add fresh dbContext.FXPositions.RemoveRange(dbContext.FXPositions.Where(x => x.AccountID == selectedAccount.ID).ToList()); foreach (var fxPosition in newData.FXPositions) { fxPosition.FunctionalCurrency = currencyDict[fxPosition.FunctionalCurrencyString]; fxPosition.FXCurrency = currencyDict[fxPosition.FXCurrencyString]; fxPosition.Account = selectedAccount; dbContext.FXPositions.Add(fxPosition); } //FX Transactions lastDate = dbContext.FXTransactions.Any(x => x.AccountID == selectedAccount.ID) ? dbContext.FXTransactions.Where(x => x.AccountID == selectedAccount.ID).Max(x => x.DateTime) : new DateTime(1, 1, 1); foreach (var fxTransaction in newData.FXTransactions) { if (fxTransaction.DateTime > lastDate) { fxTransaction.FunctionalCurrency = currencyDict[fxTransaction.FunctionalCurrencyString]; fxTransaction.FXCurrency = currencyDict[fxTransaction.FXCurrencyString]; fxTransaction.Account = selectedAccount; dbContext.FXTransactions.Add(fxTransaction); existingData.FXTransactions.Add(fxTransaction); } } await tradesRepo.UpdateOpenTrades(existingData); //todo: this is slow, perhaps parallelize? qdmsclient probably doesn't like that, would need to make it thread-safe await dbContext.SaveChangesAsync(); } }
public async Task AddCashTransactionsToTrade(Trade trade, IEnumerable <CashTransaction> cashTransactions) { await TradesRepository.AddCashTransactions(trade, cashTransactions).ConfigureAwait(false); }
public async Task AddOrders(Trade trade, List <Order> orders) { await TradesRepository.AddOrders(trade, orders); }
public async Task RemoveOrder(Trade trade, Order order) { await TradesRepository.RemoveOrder(trade, order); }
private async Task Close(IList trades) { await TradesRepository.CloseTrades(trades); }