Exemple #1
0
 public EditCashTradeCommand(EditCashTradeWindowViewModel editCashTradeWindowVM,
                             ITransactionService transactionService, TransactionsBO transaction)
 {
     _editCashTradeWindowVM = editCashTradeWindowVM;
     _transactionService    = transactionService;
     _transaction           = transaction;
 }
Exemple #2
0
        public override async Task ExecuteAsync(object parameter)
        {
            try
            {
                TransactionTypeDIM tradeType = _transactionService.GetTradeType(_addTradeWindowVM.TradeType);
                CustodiansDIM      custodian = _transactionService.GetCustodian(_addTradeWindowVM.Custodian);
                TransactionsBO     newTrade  = new TransactionsBO
                {
                    SecurityId        = _addTradeWindowVM.SelectedSecurity.SecurityId,
                    Quantity          = _addTradeWindowVM.Quantity,
                    Price             = _addTradeWindowVM.Price,
                    TradeAmount       = _addTradeWindowVM.TradeAmount,
                    TradeDate         = _addTradeWindowVM.TradeDate,
                    SettleDate        = _addTradeWindowVM.SettleDate,
                    CreatedDate       = _addTradeWindowVM.CreatedDate,
                    LastModified      = _addTradeWindowVM.LastModifiedDate,
                    Fees              = _addTradeWindowVM.Commission,
                    isActive          = _addTradeWindowVM.isActive,
                    isLocked          = _addTradeWindowVM.isLocked,
                    isCashTransaction = false,
                    FundId            = _addTradeWindowVM.FundId,
                    TransactionTypeId = tradeType.TransactionTypeId,
                    CurrencyId        = _addTradeWindowVM.SelectedSecurity.CurrencyId,
                    Comment           = "",
                    CustodianId       = custodian.CustodianId
                };
                await _transactionService.CreateTransaction(newTrade);

                _addTradeWindowVM.CloseAction();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public override void AddTransaction(TransactionsBO transaction)
        {
            if (transaction.Security.SecurityName != Security.SecurityName || transaction.Security.Currency.Symbol != Security.Currency.Symbol)
            {
                throw new InvalidOperationException("The transaction ticker does not match the ticker of this position");
            }

            if (transaction.Custodian.Name != Custodian.Name)
            {
                throw new InvalidOperationException("These transactions belongs to a different custodian");
            }

            if (_positionBreakdown.Count > 0)
            {
                if (_positionBreakdown[_positionBreakdown.Count - 1].date > transaction.TradeDate)
                {
                    throw new InvalidOperationException("A trade must take place after the most recent trade.");
                }
            }

            if (transaction.TransactionType.TypeName == "Trade")
            {
                AddTradeEvent(transaction);
            }
            else
            {
                AddCorporateActionEvent(transaction);
            }
        }
        public void CreateEditCashTradeWindow(TransactionsBO cashTrade)
        {
            Window view = new EditCashTradeWindow();
            ViewModelWindowBase viewModel = new EditCashTradeWindowViewModel(_transactionService, _staticReferences, cashTrade);

            view = ApplyWindowAttributes(view, viewModel);
            view.ShowDialog();
        }
Exemple #5
0
 public async Task UpdateTransaction(TransactionsBO transaction)
 {
     using (PortfolioAceDbContext context = _contextFactory.CreateDbContext())
     {
         TransactionsBO originalTransaction = context.Transactions.First(t => t.TransactionId == transaction.TransactionId);
         context.Entry(originalTransaction).CurrentValues.SetValues(transaction);
         await context.SaveChangesAsync();
     }
 }
Exemple #6
0
        public async Task <TransactionsBO> CreateTransaction(TransactionsBO transaction)
        {
            using (PortfolioAceDbContext context = _contextFactory.CreateDbContext())
            {
                EntityEntry <TransactionsBO> res = await context.Transactions.AddAsync(transaction);

                await context.SaveChangesAsync();

                return(res.Entity);
            }
        }
Exemple #7
0
 public async Task RestoreFXTransaction(TransactionsBO transaction)
 {
     using (PortfolioAceDbContext context = _contextFactory.CreateDbContext())
     {
         IEnumerable <TransactionsBO> linkedTransactions = context.Transactions.Where(t => t.LinkedTradeId == transaction.LinkedTradeId);
         // To DO im not happy with this it needs to be neater
         foreach (TransactionsBO linkedTransaction in linkedTransactions)
         {
             TransactionsBO tempTransaction = linkedTransaction;
             tempTransaction.isActive = true;
             context.Entry(linkedTransaction).CurrentValues.SetValues(tempTransaction);
         }
         await context.SaveChangesAsync();
     }
 }
        private void UpdatePosition(TransactionsBO transaction)
        {
            _netQuantity = _openLots.Sum(lots => lots.quantity);
            _averageCost = CalculateWeightedAverageCost();
            AppendBreakdown(transaction.TradeDate);

            // If the position changes direction it gets updated here. i.e. long to short from a single trade.
            if (_netQuantity < 0 && _isLong)
            {
                _isLong = false;
            }
            else if (_netQuantity > 0 && !_isLong)
            {
                _isLong = true;
            }
        }
        private void AddTradeEvent(TransactionsBO transaction)
        {
            // I need to ignore/prevent trades where quantity = 0

            decimal quantityRef = transaction.Quantity; // a reference to the transaction quantity so it doesn't get manipulated


            TaxLotsOpen lot = new TaxLotsOpen(transaction.TradeDate, quantityRef, transaction.Price);

            if (_netQuantity == 0)
            {
                _isLong = (quantityRef >= 0);
            }

            // this means the trade is not in the same direction as the quantity
            else if (quantityRef * _netQuantity < 0)
            {
                while (_openLots.Count > 0 && quantityRef != 0)
                {
                    decimal pnl;
                    int     multiplier = (_isLong) ? 1 : -1; // this is important because it allows me to calculate pnl taking direction into account.
                    if (Math.Abs(quantityRef) >= Math.Abs(_openLots.Peek().quantity))
                    {
                        pnl          = Math.Abs(_openLots.Peek().quantity) * (transaction.Price - _openLots.Peek().price) * multiplier;
                        quantityRef += _openLots.Peek().quantity;
                        _openLots.Dequeue();
                    }
                    else
                    {
                        pnl = Math.Abs(quantityRef) * (transaction.Price - _openLots.Peek().price) * multiplier;
                        _openLots.Peek().quantity += quantityRef;
                        quantityRef = 0;
                    }
                    _realisedPnL += pnl;
                }
                if (quantityRef != 0)
                {
                    lot.quantity = quantityRef;
                }
            }
            if (quantityRef != 0)
            {
                _openLots.Enqueue(lot);
            }
            UpdatePosition(transaction);
            Debug.Assert(_netQuantity == _openLots.Sum(s => s.quantity));
        }
Exemple #10
0
 public EditCashTradeWindowViewModel(ITransactionService transactionService, IStaticReferences staticReferences, TransactionsBO transaction)
 {
     _transactionService              = transactionService;
     _transaction                     = transaction;
     _staticReferences                = staticReferences;
     _validationErrors                = new ValidationErrors();
     _validationErrors.ErrorsChanged += ChangedErrorsEvents;
     _lastLockedDate                  = _staticReferences.GetMostRecentLockedDate(transaction.FundId);
     _cashType            = transaction.TransactionType.TypeName;
     _cashAmount          = transaction.TradeAmount;
     _tradeCurrency       = transaction.Currency.Symbol;
     _tradeDate           = transaction.TradeDate;
     _settleDate          = transaction.SettleDate;
     _custodian           = transaction.Custodian.Name;
     _launchDate          = transaction.Fund.LaunchDate;
     _notes               = transaction.Comment;
     EditCashTradeCommand = new EditCashTradeCommand(this, transactionService, transaction);
 }
        public override void AddTransaction(TransactionsBO transaction)
        {
            if (transaction.Currency.Symbol != this.Currency.Symbol)
            {
                throw new InvalidOperationException("The transaction currency does not match the currency of this position");
            }

            if (transaction.Custodian.Name != this.Custodian.Name)
            {
                throw new InvalidOperationException("These transactions belongs to a different custodian");
            }

            if (_asOfDate == null || _asOfDate < transaction.TradeDate)
            {
                _asOfDate = transaction.TradeDate;
            }
            _balance += transaction.TradeAmount;
        }
        private void AddTradeEvent(TransactionsBO transaction)
        {
            // I need to ignore/prevent trades where quantity = 0

            decimal quantityRef = transaction.Quantity; // a reference to the transaction quantity so it doesn't get manipulated


            TaxLotsOpen lot = new TaxLotsOpen(transaction.TradeDate, quantityRef, transaction.Price);

            if (_netQuantity == 0)
            {
                _isLong = (quantityRef >= 0);
            }

            // this means the trade is not in the same direction as the quantity
            else if (quantityRef * _netQuantity < 0)
            {
                while (_openLots.Count > 0 && quantityRef != 0)
                {
                    if (Math.Abs(quantityRef) >= Math.Abs(_openLots.Peek().quantity))
                    {
                        quantityRef += _openLots.Peek().quantity;
                        _openLots.Dequeue();
                    }
                    else
                    {
                        _openLots.Peek().quantity += quantityRef;
                        quantityRef = 0;
                    }
                }
                if (quantityRef != 0)
                {
                    lot.quantity = quantityRef;
                }
            }
            if (quantityRef != 0)
            {
                _openLots.Enqueue(lot);
            }
            UpdatePosition(transaction);
            Debug.Assert(_netQuantity == _openLots.Sum(s => s.quantity));
        }
 private void AddCorporateActionEvent(TransactionsBO transaction)
 {
     if (transaction.TransactionType.TypeName == "Dividends")
     {
         if (transaction.Quantity == 0)
         {
             // cash dividend
             _realisedPnL += transaction.TradeAmount;
         }
         else
         {
             // stock dividend
             TaxLotsOpen dividendLot = new TaxLotsOpen(transaction.TradeDate, transaction.Quantity, transaction.Price);
             _openLots.Enqueue(dividendLot);
             UpdatePosition(transaction);
         }
     }
     else
     {
         throw new NotImplementedException();
     }
     Debug.Assert(_netQuantity == _openLots.Sum(s => s.quantity));
 }
Exemple #14
0
        public override async Task ExecuteAsync(object parameter)
        {
            try
            {
                // cash symbol would be something like EURc name = EUR CASH
                SecuritiesDIM      security     = _transactionService.GetSecurityInfo(_addCashTradeWindowVM.Symbol);
                TransactionTypeDIM tradeType    = _transactionService.GetTradeType(_addCashTradeWindowVM.CashType);
                CustodiansDIM      custodian    = _transactionService.GetCustodian(_addCashTradeWindowVM.Custodian);
                TransactionsBO     newCashTrade = new TransactionsBO
                {
                    SecurityId        = security.SecurityId,
                    Quantity          = _addCashTradeWindowVM.Quantity,
                    Price             = _addCashTradeWindowVM.Price,
                    TradeAmount       = _addCashTradeWindowVM.CashAmount,
                    TradeDate         = _addCashTradeWindowVM.TradeDate,
                    SettleDate        = _addCashTradeWindowVM.SettleDate,
                    CreatedDate       = _addCashTradeWindowVM.CreatedDate,
                    LastModified      = _addCashTradeWindowVM.LastModifiedDate,
                    Fees              = _addCashTradeWindowVM.Fees,
                    isActive          = _addCashTradeWindowVM.isActive,
                    isLocked          = _addCashTradeWindowVM.isLocked,
                    isCashTransaction = true,
                    FundId            = _addCashTradeWindowVM.FundId,
                    TransactionTypeId = tradeType.TransactionTypeId,
                    CurrencyId        = security.CurrencyId,
                    Comment           = _addCashTradeWindowVM.Notes,
                    CustodianId       = custodian.CustodianId
                };
                await _transactionService.CreateTransaction(newCashTrade);

                _addCashTradeWindowVM.CloseAction();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Exemple #15
0
        public async Task LockNav(NavValuations navValuations)
        {
            using (PortfolioAceDbContext context = _contextFactory.CreateDbContext())
            {
                DateTime             asOfDate = navValuations.AsOfDate;
                int                  fundId   = navValuations.fund.FundId;
                AccountingPeriodsDIM period   = context.Periods.Where(p => p.FundId == fundId && p.AccountingDate == asOfDate).FirstOrDefault();
                period.isLocked = true;
                context.Entry(period).CurrentValues.SetValues(period);

                List <TransactionsBO> allTransactions;
                if (navValuations.fund.NAVFrequency == "Daily")
                {
                    allTransactions = navValuations.fund.Transactions.Where(t => t.TradeDate == asOfDate).ToList();
                }
                else
                {
                    allTransactions = navValuations.fund.Transactions.Where(t => t.TradeDate.Month == asOfDate.Month).ToList();
                }
                foreach (TransactionsBO transaction in allTransactions)
                {
                    transaction.isLocked = true;
                }
                context.Transactions.UpdateRange(allTransactions);

                NAVPriceStoreFACT newNavPrice = new NAVPriceStoreFACT
                {
                    FinalisedDate     = asOfDate,
                    Currency          = navValuations.fund.BaseCurrency,
                    FundId            = fundId,
                    NAVPeriodId       = period.PeriodId,
                    SharesOutstanding = navValuations.SharesOutstanding,
                    NetAssetValue     = navValuations.NetAssetValue,
                    NAVPrice          = navValuations.NetAssetValuePerShare,
                };
                context.NavPriceData.Add(newNavPrice);

                List <PositionFACT> newPositions = new List <PositionFACT>();
                foreach (ValuedSecurityPosition secPosition in navValuations.SecurityPositions)
                {
                    PositionFACT newPosition = new PositionFACT
                    {
                        PositionDate  = secPosition.AsOfDate,
                        SecurityId    = secPosition.Position.Security.SecurityId,
                        AssetClassId  = secPosition.Position.Security.AssetClassId,
                        FundId        = fundId,
                        AverageCost   = secPosition.Position.AverageCost,
                        CurrencyId    = secPosition.Position.Security.CurrencyId,
                        MarketValue   = secPosition.MarketValueBase,
                        Price         = secPosition.MarketPrice,
                        Quantity      = secPosition.Position.NetQuantity,
                        RealisedPnl   = secPosition.Position.RealisedPnL,
                        UnrealisedPnl = secPosition.UnrealisedPnl
                    };
                    newPositions.Add(newPosition);
                }
                foreach (ValuedCashPosition cashPosition in navValuations.CashPositions)
                {
                    string        currencySecSymbol = $"{cashPosition.CashPosition.Currency.Symbol}c";
                    SecuritiesDIM securitisedCash   = context.Securities.AsNoTracking().Where(s => s.Symbol == currencySecSymbol).Include(s => s.AssetClass).FirstOrDefault();

                    PositionFACT newPosition = new PositionFACT
                    {
                        PositionDate  = cashPosition.AsOfDate,
                        SecurityId    = securitisedCash.SecurityId,
                        AssetClassId  = securitisedCash.AssetClassId,
                        FundId        = fundId,
                        AverageCost   = 1,
                        CurrencyId    = cashPosition.CashPosition.Currency.CurrencyId,
                        MarketValue   = cashPosition.MarketValueBase,
                        Price         = cashPosition.fxRate,
                        Quantity      = cashPosition.CashPosition.NetQuantity,
                        RealisedPnl   = 0,
                        UnrealisedPnl = 0
                    };
                    newPositions.Add(newPosition);
                }

                await context.Positions.AddRangeAsync(newPositions);

                List <InvestorHoldingsFACT> newHoldings = new List <InvestorHoldingsFACT>();
                foreach (ClientHoldingValuation clientHolding in navValuations.ClientHoldings)
                {
                    InvestorHoldingsFACT newHolding = new InvestorHoldingsFACT
                    {
                        NetValuation          = clientHolding.NetValuation,
                        AverageCost           = clientHolding.Holding.AverageCost,
                        HighWaterMark         = clientHolding.Holding.Investor.HighWaterMark,
                        ManagementFeesAccrued = clientHolding.ManagementFeesAccrued,
                        Units = clientHolding.Holding.Units,
                        PerformanceFeesAccrued = clientHolding.PerformanceFeesAccrued,
                        HoldingDate            = asOfDate,
                        FundId     = fundId,
                        InvestorId = clientHolding.Holding.Investor.InvestorId
                    };
                    newHoldings.Add(newHolding);
                }
                await context.InvestorHoldings.AddRangeAsync(newHoldings);

                var pendingTAs = navValuations.fund.TransferAgent.Where(ta => !ta.IsNavFinal && ta.TransactionDate == asOfDate).ToList();
                foreach (var pendingTA in pendingTAs)
                {
                    SecuritiesDIM      security = context.Securities.AsNoTracking().Where(s => s.Symbol == $"{pendingTA.Currency}c").First();
                    int                secId    = security.SecurityId;
                    int                currId   = security.CurrencyId;
                    TransactionTypeDIM tradeType;
                    int                custodianId = context.Custodians.AsNoTracking().Where(c => c.Name == "Default").First().CustodianId; // FOR NOW TODO

                    if (pendingTA.IssueType == "Subscription")
                    {
                        //add tradeamount..
                        pendingTA.Units      = pendingTA.TradeAmount / navValuations.NetAssetValuePerShare;
                        pendingTA.NAVPrice   = navValuations.NetAssetValuePerShare;
                        pendingTA.IsNavFinal = true;
                        tradeType            = context.TransactionTypes.AsNoTracking().Where(tt => tt.TypeName == "Deposit").First();
                    }
                    else
                    {
                        pendingTA.TradeAmount = pendingTA.Units * navValuations.NetAssetValuePerShare;
                        pendingTA.NAVPrice    = navValuations.NetAssetValuePerShare;
                        pendingTA.IsNavFinal  = true;
                        tradeType             = context.TransactionTypes.AsNoTracking().Where(tt => tt.TypeName == "Withdrawal").First();
                        //reduce units..
                    }
                    // id need to create deposit and withdrawals here as well as save these updated TAs

                    // I need to set main custodian for a fund where all subs and reds initially go to.TODO
                    TransactionsBO newCashTrade = new TransactionsBO
                    {
                        SecurityId        = secId,
                        Quantity          = pendingTA.Units,
                        Price             = pendingTA.NAVPrice,
                        TradeAmount       = pendingTA.TradeAmount,
                        TradeDate         = pendingTA.TransactionDate,
                        SettleDate        = pendingTA.TransactionSettleDate,
                        CreatedDate       = DateTime.Now,
                        LastModified      = DateTime.Now,
                        Fees              = decimal.Zero,
                        isActive          = true,
                        isLocked          = true,
                        isCashTransaction = false,
                        FundId            = fundId,
                        TransactionTypeId = tradeType.TransactionTypeId,
                        CurrencyId        = currId,
                        Comment           = pendingTA.IssueType.ToUpper(),
                        CustodianId       = custodianId
                    };

                    context.Transactions.Add(newCashTrade);
                    context.TransferAgent.Update(pendingTA);
                }

                await context.SaveChangesAsync();

                // Lock all transactions with this trade Date... DONE
                // Add to Position SnapShot Fact Table... DONE
                // Lock Period... DONE
                // Update TransferAgent Fact Table.... DONE
                // NavPrices DONE
            }
        }
        public override async Task ExecuteAsync(object parameter)
        {
            try
            {
                if (_fundInitialiseVM.dgSeedingInvestors.Count == 0)
                {
                    throw new ArgumentException("Your fund must have initial investors.");
                }
                if (_fundInitialiseVM.dgSeedingInvestors.Count != _fundInitialiseVM.dgSeedingInvestors.ToHashSet().Count)
                {
                    throw new ArgumentException("You must net an investors seed capital.");
                }

                Fund updateFund = _fundInitialiseVM.TargetFund;
                updateFund.IsInitialised = true;

                string             cashSymbol = $"{updateFund.BaseCurrency}c";
                SecuritiesDIM      security   = _staticReferences.GetSecurityInfo(cashSymbol);
                TransactionTypeDIM tradeType  = _staticReferences.GetTransactionType("Deposit");
                CustodiansDIM      custodian  = _staticReferences.GetCustodian(_fundInitialiseVM.Custodian);

                List <TransferAgencyBO>     subscriptions    = new List <TransferAgencyBO>();
                List <TransactionsBO>       transactions     = new List <TransactionsBO>();
                List <FundInvestorBO>       fundInvestors    = new List <FundInvestorBO>();
                List <InvestorHoldingsFACT> investorHoldings = new List <InvestorHoldingsFACT>();

                foreach (SeedingInvestor seedInvestor in _fundInitialiseVM.dgSeedingInvestors)
                {
                    if (seedInvestor.SeedAmount >= updateFund.MinimumInvestment)
                    {
                        FundInvestorBO fundInvestor = new FundInvestorBO
                        {
                            InceptionDate = updateFund.LaunchDate,
                            FundId        = updateFund.FundId,
                            InvestorId    = seedInvestor.InvestorId
                        };
                        // The highwatermark is only applicable if the fund has a highwatermark...
                        fundInvestor.HighWaterMark = (updateFund.HasHighWaterMark) ? _fundInitialiseVM.NavPrice : (decimal?)null;
                        fundInvestors.Add(fundInvestor);

                        InvestorHoldingsFACT investor = new InvestorHoldingsFACT
                        {
                            ManagementFeesAccrued  = decimal.Zero,
                            PerformanceFeesAccrued = decimal.Zero,
                            FundId       = updateFund.FundId,
                            HoldingDate  = updateFund.LaunchDate,
                            InvestorId   = seedInvestor.InvestorId,
                            AverageCost  = _fundInitialiseVM.NavPrice,
                            Units        = seedInvestor.SeedAmount / _fundInitialiseVM.NavPrice,
                            NetValuation = seedInvestor.SeedAmount,
                        };
                        investor.HighWaterMark = (updateFund.HasHighWaterMark) ? _fundInitialiseVM.NavPrice : (decimal?)null;
                        investorHoldings.Add(investor);
                        // hwm
                        TransferAgencyBO newSubscription = new TransferAgencyBO
                        {
                            TradeAmount           = seedInvestor.SeedAmount,
                            NAVPrice              = _fundInitialiseVM.NavPrice,
                            TransactionDate       = updateFund.LaunchDate,
                            TransactionSettleDate = updateFund.LaunchDate,
                            Currency              = updateFund.BaseCurrency,
                            FundId       = updateFund.FundId,
                            Fees         = 0,
                            IssueType    = "Subscription",
                            Units        = seedInvestor.SeedAmount / _fundInitialiseVM.NavPrice,
                            IsNavFinal   = true,
                            FundInvestor = fundInvestor
                        };
                        subscriptions.Add(newSubscription);
                        TransactionsBO newTransaction = new TransactionsBO
                        {
                            SecurityId        = security.SecurityId,
                            Quantity          = seedInvestor.SeedAmount,
                            Price             = decimal.One,
                            TradeAmount       = seedInvestor.SeedAmount,
                            TradeDate         = updateFund.LaunchDate,
                            SettleDate        = updateFund.LaunchDate,
                            CreatedDate       = DateTime.Now,
                            LastModified      = DateTime.Now,
                            Fees              = decimal.Zero,
                            isActive          = true,
                            isLocked          = true,
                            isCashTransaction = false,
                            FundId            = updateFund.FundId,
                            TransactionTypeId = tradeType.TransactionTypeId,
                            CurrencyId        = security.CurrencyId,
                            Comment           = "Initial Subscription",
                            CustodianId       = custodian.CustodianId
                        };
                        transactions.Add(newTransaction);
                    }
                    else
                    {
                        throw new ArgumentException("The seed amount must be greater than the Funds minimum investment");
                    }
                }

                int PeriodId = _staticReferences.GetPeriod(updateFund.LaunchDate, updateFund.FundId).PeriodId;
                NAVPriceStoreFACT initialNav = new NAVPriceStoreFACT
                {
                    FinalisedDate     = updateFund.LaunchDate,
                    NAVPrice          = _fundInitialiseVM.NavPrice,
                    FundId            = updateFund.FundId,
                    NetAssetValue     = subscriptions.Sum(ni => ni.TradeAmount),
                    SharesOutstanding = subscriptions.Sum(ni => ni.Units),
                    Currency          = updateFund.BaseCurrency,
                    NAVPeriodId       = PeriodId
                };
                await _investorService.InitialiseFundAction(updateFund, subscriptions, transactions, initialNav, fundInvestors, investorHoldings);

                _fundInitialiseVM.CloseAction();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
 public abstract void AddTransaction(TransactionsBO transaction);
Exemple #18
0
        public async Task <TransactionsBO> CreateFXTransaction(ForexDTO fxTransaction)
        {
            using (PortfolioAceDbContext context = _contextFactory.CreateDbContext())
            {
                SecuritiesDIM fxSecurity = context.Securities.AsNoTracking().Where(s => s.Symbol == fxTransaction.Symbol).FirstOrDefault();
                AssetClassDIM assetClass = context.AssetClasses.AsNoTracking().Where(a => a.Name == "FXForward").FirstOrDefault();
                CustodiansDIM custodian  = context.Custodians.AsNoTracking().Where(c => c.Name == fxTransaction.Custodian).FirstOrDefault();
                IEnumerable <TransactionTypeDIM> transactionTypes = context.TransactionTypes;
                List <CurrenciesDIM>             currencies       = context.Currencies.AsNoTracking().ToList();

                CurrenciesDIM buyCurrency  = context.Currencies.AsNoTracking().Where(c => c.Symbol == fxTransaction.BuyCurrency).First();
                CurrenciesDIM sellCurrency = context.Currencies.AsNoTracking().Where(c => c.Symbol == fxTransaction.SellCurrency).First();
                if (fxSecurity == null)
                {
                    fxSecurity = new SecuritiesDIM
                    {
                        AssetClassId = assetClass.AssetClassId,
                        CurrencyId   = buyCurrency.CurrencyId,
                        SecurityName = fxTransaction.Name,
                        Symbol       = fxTransaction.Symbol
                    };
                    context.Securities.Add(fxSecurity);
                }
                // Created LinkedTransactions Here
                LinkedTradesBO linkReference  = new LinkedTradesBO();
                TransactionsBO refTransaction = new TransactionsBO
                {
                    Security          = fxSecurity,
                    FundId            = fxTransaction.FundId,
                    isActive          = true,
                    isLocked          = false,
                    TradeAmount       = 0,
                    Price             = fxTransaction.Price,
                    Quantity          = fxTransaction.BuyAmount,
                    CurrencyId        = buyCurrency.CurrencyId,
                    TransactionTypeId = transactionTypes.Where(tt => tt.TypeName == "FXTrade").First().TransactionTypeId,
                    Comment           = "",
                    CustodianId       = custodian.CustodianId,
                    Fees = 0,
                    isCashTransaction = false,
                    TradeDate         = fxTransaction.TradeDate,
                    SettleDate        = fxTransaction.SettleDate,
                    CreatedDate       = DateTime.Now,
                    LastModified      = DateTime.Now,
                    LinkedTrades      = linkReference
                };
                TransactionsBO refTransactionCollapse = new TransactionsBO
                {
                    Security          = fxSecurity,
                    FundId            = fxTransaction.FundId,
                    isActive          = true,
                    isLocked          = false,
                    TradeAmount       = 0,
                    Price             = fxTransaction.Price,
                    Quantity          = fxTransaction.BuyAmount * -1,
                    CurrencyId        = buyCurrency.CurrencyId,
                    TransactionTypeId = transactionTypes.Where(tt => tt.TypeName == "FXTradeCollapse").First().TransactionTypeId,
                    Comment           = "",
                    CustodianId       = custodian.CustodianId,
                    Fees = 0,
                    isCashTransaction = false,
                    TradeDate         = fxTransaction.SettleDate,
                    SettleDate        = fxTransaction.SettleDate,
                    CreatedDate       = DateTime.Now,
                    LastModified      = DateTime.Now,
                    LinkedTrades      = linkReference
                };
                EntityEntry <TransactionsBO> res = await context.Transactions.AddAsync(refTransaction);

                context.Transactions.Add(refTransactionCollapse);

                SecuritiesDIM fxBuySecurity  = context.Securities.AsNoTracking().Where(s => s.Symbol == $"{fxTransaction.BuyCurrency}c").FirstOrDefault();
                SecuritiesDIM fxSellSecurity = context.Securities.AsNoTracking().Where(s => s.Symbol == $"{fxTransaction.SellCurrency}c").FirstOrDefault();

                TransactionsBO fxBuyLegCash = new TransactionsBO
                {
                    SecurityId        = fxBuySecurity.SecurityId,
                    FundId            = fxTransaction.FundId,
                    isActive          = true,
                    isLocked          = false,
                    TradeAmount       = fxTransaction.BuyAmount,
                    Price             = 1,
                    Quantity          = fxTransaction.BuyAmount,
                    CurrencyId        = buyCurrency.CurrencyId,
                    TransactionTypeId = transactionTypes.Where(tt => tt.TypeName == "FXBuy").First().TransactionTypeId,
                    Comment           = fxTransaction.Description,
                    CustodianId       = custodian.CustodianId,
                    Fees = 0,
                    isCashTransaction = false,
                    TradeDate         = fxTransaction.SettleDate,
                    SettleDate        = fxTransaction.SettleDate,
                    CreatedDate       = DateTime.Now,
                    LastModified      = DateTime.Now,
                    LinkedTrades      = linkReference
                };
                TransactionsBO fxSellLegCash = new TransactionsBO
                {
                    SecurityId        = fxSellSecurity.SecurityId,
                    FundId            = fxTransaction.FundId,
                    isActive          = true,
                    isLocked          = false,
                    TradeAmount       = fxTransaction.SellAmount,
                    Price             = 1,
                    Quantity          = fxTransaction.SellAmount,
                    CurrencyId        = sellCurrency.CurrencyId,
                    TransactionTypeId = transactionTypes.Where(tt => tt.TypeName == "FXSell").First().TransactionTypeId,
                    Comment           = fxTransaction.Description,
                    CustodianId       = custodian.CustodianId,
                    Fees = 0,
                    isCashTransaction = false,
                    TradeDate         = fxTransaction.SettleDate,
                    SettleDate        = fxTransaction.SettleDate,
                    CreatedDate       = DateTime.Now,
                    LastModified      = DateTime.Now,
                    LinkedTrades      = linkReference
                };
                context.Transactions.Add(fxBuyLegCash);
                context.Transactions.Add(fxSellLegCash);

                await context.SaveChangesAsync();

                return(refTransaction);
            }
        }