Ejemplo n.º 1
0
 public async Task RemoveCashTransactionsFromTrade(Trade trade, IEnumerable <CashTransaction> cashTransactions)
 {
     foreach (var ct in cashTransactions)
     {
         await TradesRepository.RemoveCashTransaction(trade, ct).ConfigureAwait(false);
     }
 }
Ejemplo n.º 2
0
        private async Task Open(IList trades)
        {
            foreach (Trade trade in trades)
            {
                trade.Open = true;
            }

            await TradesRepository.UpdateTrade(trades : trades.Cast <Trade>());
        }
Ejemplo n.º 3
0
        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);
        }
Ejemplo n.º 4
0
        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();
        }
Ejemplo n.º 5
0
        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>());
        }
Ejemplo n.º 6
0
        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();
        }
Ejemplo n.º 7
0
        /// <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);
            }
        }
Ejemplo n.º 8
0
        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();
        }
Ejemplo n.º 9
0
        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);
        }
Ejemplo n.º 10
0
        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();
        }
Ejemplo n.º 11
0
        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();
        }
Ejemplo n.º 12
0
        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();
        }
Ejemplo n.º 13
0
        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();
        }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        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;
        }
Ejemplo n.º 16
0
        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);
            }
        }
Ejemplo n.º 17
0
        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();
        }
Ejemplo n.º 18
0
 public async Task RemoveFxTransactionFromTrade(Trade trade, FXTransaction fxTransaction)
 {
     await TradesRepository.RemoveFXTransaction(trade, fxTransaction);
 }
Ejemplo n.º 19
0
 public async Task AddFxTransactionToTrade(Trade trade, FXTransaction fxTransaction)
 {
     await TradesRepository.AddFXTransaction(trade, fxTransaction);
 }
Ejemplo n.º 20
0
        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();
            }
        }
Ejemplo n.º 21
0
 public async Task AddCashTransactionsToTrade(Trade trade, IEnumerable <CashTransaction> cashTransactions)
 {
     await TradesRepository.AddCashTransactions(trade, cashTransactions).ConfigureAwait(false);
 }
Ejemplo n.º 22
0
 public async Task AddOrders(Trade trade, List <Order> orders)
 {
     await TradesRepository.AddOrders(trade, orders);
 }
Ejemplo n.º 23
0
 public async Task RemoveOrder(Trade trade, Order order)
 {
     await TradesRepository.RemoveOrder(trade, order);
 }
Ejemplo n.º 24
0
 private async Task Close(IList trades)
 {
     await TradesRepository.CloseTrades(trades);
 }