Example #1
0
 public AutoMapperProfile()
 {
     CreateMap <UserCreateEditModel, User>();
     CreateMap <User, UserModel>();
     CreateMap <FtpCredential, FtpCredentialGridVm>();
     CreateMap <FtpCredential, FtpCredentialCreateEditModel>().ReverseMap();
     CreateMap <MasterAccount, MasterAccountVm>().ReverseMap();
     CreateMap <MasterAccount, MasterAccountGridVm>()
     .ForMember(a => a.CreatedBy, opt => opt.MapFrom(src => src.CreatedBy.Email))
     .ForMember(a => a.UpdatedBy, opt => opt.MapFrom(src => src.UpdatedBy.Email));
     CreateMap <User, UserGridViewModel>()
     .ForMember(x => x.Roles, opt => opt.MapFrom(y => y.Roles.Select(r => r.Name)));
     CreateMap <TradeAccount, TradeAccountInfoGridViewModel>();
     CreateMap <TradingPermission, TradingPermissionsGridVM>();
     CreateMap <TradeAccountNote, TradeAccountNoteVm>()
     .ForMember(acc => acc.CreatedBy, opt => opt.MapFrom(src => src.CreatedBy.Email));
     CreateMap <TradeAccount, AccountInfoGridVM>()
     .ForMember(acc => acc.MasterAccount, opt => opt.MapFrom(src => TradeUtils.ResolveMasterAccountName(src.MasterAccount)));
     CreateMap <TradeAccountNoteCreateEditModel, TradeAccountNote>();
     CreateMap <TradeAccountRankEditModel, TradeAccount>();
     CreateMap <MasterAccount, MasterAccountCreateEditModel>().ReverseMap();
     CreateMap <TradeAccount, TradeAccountModel>();
     CreateMap <TradeNav, PortfolioVm>();
     CreateMap <TradeSytossOpenPosition, OpenPositionVm>();
     CreateMap <TradesExe, TradesExeInformationVm>();
 }
Example #2
0
        //Execute rule logic
        //Place Sell Limit orders when notified by OnOpenForTrading rule
        override protected bool ExcuteRuleLogic(Niffle message)
        {
            if (IsTickMessageEmpty(message))
            {
                return(false);
            }
            if (EntryPipsFromTradeOpenPrice == 0.0)
            {
                return(false);                                     //trigger points should be set when initialised
            }
            if (OpenPrice == 0.0)
            {
                return(false);                  //Open price should be set once activated
            }
            double EntryPrice = TradeUtils.AddPipsToPrice(OpenPrice, EntryPipsFromTradeOpenPrice);

            for (int orderNumber = 1; orderNumber <= NumberOfOrders; orderNumber++)
            {
                TradePublisher.PlaceSellLimit(SymbolCode,
                                              StrategyId + "-" + orderNumber,
                                              TradeUtils.CalculateNextOrderVolume(orderNumber),
                                              TradeUtils.AddPipsToPrice(EntryPrice, TradeUtils.CalculateNextEntryPips(orderNumber)));
            }

            //Set inactive if only executing once
            SetActiveState(false);

            //return true to publish a success Service Notify message
            return(true);
        }
Example #3
0
        public PaginationModel <TradeAccountInfoGridViewModel> GetAccountsInfo(int pageIndex, int pageSize,
                                                                               string sorting, long[] idMasterAccounts, long[] idTradeAccounts, Period period)
        {
            var result = new PaginationModel <TradeAccountInfoGridViewModel>();

            var query = _tradeAccountRepository.Query().Where(acc => !acc.Deleted &&
                                                              acc.IsClientInfo &&
                                                              DbFunctions.TruncateTime(acc.DateFunded) <=
                                                              DbFunctions.TruncateTime(period.ToDate));

            query = SortAccountsInfoQuery(query, sorting);

            if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                query = query.Where(acc => idMasterAccounts.Contains(acc.MasterAccountId));
            }
            else if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                query = query.Where(acc => idTradeAccounts.Contains(acc.Id));
            }

            var accounts = query.Skip(pageSize * pageIndex).Take(pageSize).ToList();

            result.Data = accounts.Select(acc => _mapper.Map <TradeAccountInfoGridViewModel>(acc)).ToList();

            result.DataLength = query.Count();

            return(result);
        }
Example #4
0
        private decimal LoadTotalAumTotal(Period period, long[] idMasterAccounts, long[] idTradeAccounts)
        {
            decimal total;
            var     tradeNav = _tradeRepository.TradeNavsQuery();

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                total = tradeNav
                        .Where(s => DbFunctions.TruncateTime(s.ReportDate) == DbFunctions.TruncateTime(period.ToDate) &&
                               idTradeAccounts.Contains(s.TradeAccount.Id))
                        .Select(t => t.Total).DefaultIfEmpty(0).Sum();
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                total = tradeNav
                        .Where(s => DbFunctions.TruncateTime(s.ReportDate) == DbFunctions.TruncateTime(period.ToDate) &&
                               idMasterAccounts.Contains(s.TradeAccount.MasterAccountId)).Select(t => t.Total)
                        .DefaultIfEmpty(0).Sum();
            }
            else
            {
                total = tradeNav
                        .Where(s => DbFunctions.TruncateTime(s.ReportDate) == DbFunctions.TruncateTime(period.ToDate))
                        .Select(t => t.Total).DefaultIfEmpty(0)
                        .Sum();
            }

            return(total);
        }
        private decimal NewClientsTableData(string findPeriod, long[] idMasterAccounts, long[] idTradeAccounts, bool dif)
        {
            var tradeAccounts = _tradeRepository
                                .TradeAccountsQuery().Where(s => s.IsClientInfo == true);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                tradeAccounts = tradeAccounts.Where(fee => idTradeAccounts.Contains(fee.Id));
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                tradeAccounts = tradeAccounts.Where(fee => idMasterAccounts.Contains(fee.MasterAccount.Id));
            }

            switch (findPeriod)
            {
            case "LD":
                var startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                var endDate   = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).AddDays(-1);
                tradeAccounts = dif ? tradeAccounts.Where(s => s.DateOpened >= endDate && s.DateOpened <= startDate) : tradeAccounts.Where(s => s.DateFunded >= endDate && s.DateFunded <= startDate);
                return(tradeAccounts.Count());

            case "MTD":
                startDate     = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                endDate       = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                tradeAccounts = dif ? tradeAccounts.Where(s => s.DateOpened <= endDate && s.DateOpened >= startDate) : tradeAccounts.Where(s => s.DateFunded <= endDate && s.DateFunded >= startDate);
                return(tradeAccounts.Count());

            case "LM":
                var today = DateTime.Today;
                var month = new DateTime(today.Year, today.Month, 1);
                var first = month.AddMonths(-1);
                var last  = month.AddDays(-1);
                tradeAccounts = dif ? tradeAccounts.Where(s => s.DateOpened <= last && s.DateOpened >= first) : tradeAccounts.Where(s => s.DateFunded <= last && s.DateFunded >= first);
                return(tradeAccounts.Count());

            case "MAVG":
                today = DateTime.Today;
                month = new DateTime(today.Year, today.Month, 1);
                first = month.AddMonths(-1);
                last  = month.AddDays(-1);
                var numberOfDays = (last - first).TotalDays;
                tradeAccounts = dif ? tradeAccounts.Where(s => s.DateOpened <= last && s.DateOpened >= first) : tradeAccounts.Where(s => s.DateFunded <= last && s.DateFunded >= first);
                return(Math.Round(Convert.ToDecimal(tradeAccounts.Count() / numberOfDays), 2));

            case "12MAVG":
                decimal daysLeft       = new DateTime(DateTime.Now.Year, 12, 31).DayOfYear - DateTime.Now.DayOfYear;
                var     firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                endDate       = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                tradeAccounts = dif ? tradeAccounts.Where(s => s.DateOpened <= endDate && s.DateOpened >= firstDayOfYear) : tradeAccounts.Where(s => s.DateFunded <= endDate && s.DateFunded >= firstDayOfYear);
                return(Math.Round(tradeAccounts.Count() / daysLeft, 2));

            case "ALL":
                tradeAccounts = tradeAccounts.Where(s => s.DateFunded != null);
                return(tradeAccounts.Count());

            default:
                return(0);
            }
        }
Example #6
0
        private decimal LoadWithdrawals(Period period, long[] idMasterAccounts,
                                        long[] idTradeAccounts)
        {
            decimal total;
            var     cash = _tradeRepository.TradeCashesQuery();

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                total = cash
                        .Where(s => s.ReportDate <= period.ToDate && s.ReportDate >= period.FromDate &&
                               idTradeAccounts.Contains(s.TradeAccount.Id)).Select(t => t.Withdrawals)
                        .DefaultIfEmpty(0).Sum();
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                total = cash
                        .Where(s => s.ReportDate <= period.ToDate && s.ReportDate >= period.FromDate &&
                               idMasterAccounts.Contains(s.TradeAccount.MasterAccountId)).Select(t => t.Withdrawals)
                        .DefaultIfEmpty(0).Sum();
            }
            else
            {
                total = cash.Where(s => s.ReportDate <= period.ToDate && s.ReportDate >= period.FromDate)
                        .Select(t => t.Withdrawals).DefaultIfEmpty(0).Sum();
            }

            return(total);
        }
Example #7
0
        private decimal LoadTotalNewClients(Period period, long[] idMasterAccounts,
                                            long[] idTradeAccounts)
        {
            var feesClientsEnd = _tradeRepository
                                 .TradeAccountsQuery()
                                 .Where(fee => fee.DateFunded <= period.ToDate && fee.TradeStatus == "O");

            var feesClientsStart = _tradeRepository
                                   .TradeAccountsQuery()
                                   .Where(fee => fee.DateFunded <= period.FromDate && fee.TradeStatus == "O");

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                var end   = feesClientsEnd.Count(fee => idTradeAccounts.Contains(fee.Id));
                var start = feesClientsStart.Count(fee => idTradeAccounts.Contains(fee.Id));
                return(end - start);
            }

            if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                var end   = feesClientsEnd.Count(fee => idMasterAccounts.Contains(fee.MasterAccountId));
                var start = feesClientsStart.Count(fee => idMasterAccounts.Contains(fee.MasterAccountId));
                return(end - start);
            }

            return(feesClientsEnd.Count() - feesClientsStart.Count());
        }
Example #8
0
        public IEnumerable <IdNameModel> GetTradeAccountsIdName(int pageIndex, int pageLength, string sortBy,
                                                                IEnumerable <long> masterAccounts, IEnumerable <long> tradeAccounts, Period period)
        {
            var query = _tradeAccountRepository.Query().Where(acc => !acc.Deleted &&
                                                              acc.IsClientInfo &&
                                                              DbFunctions.TruncateTime(acc.DateFunded) <=
                                                              DbFunctions.TruncateTime(period.ToDate));

            query = SortAccountsInfoQuery(query, sortBy);

            if (TradeUtils.IsSortingByMasterAccounts(masterAccounts.ToArray()))
            {
                query = query.Where(acc => masterAccounts.Contains(acc.MasterAccountId));
            }
            else if (TradeUtils.IsSortingByTradeAccounts(tradeAccounts.ToArray()))
            {
                query = query.Where(acc => tradeAccounts.Contains(acc.Id));
            }

            var accounts = query.Skip(pageLength * pageIndex).Take(pageLength).ToList();

            return(accounts.Select(acc => new IdNameModel {
                Id = acc.Id, Name = acc.AccountName
            }));
        }
Example #9
0
        private Dictionary <long, ChartDataVm.DataSet> GetDictionaryByMasterAccounts(long[] idMasterAccounts)
        {
            var result = new Dictionary <long, ChartDataVm.DataSet>();

            var accountsQuery = _tradeAccountRepository.MasterAccountsQuery();

            if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                accountsQuery = accountsQuery.Where(account => idMasterAccounts.Contains(account.Id));
            }

            var accounts = accountsQuery.Select(account => new ExtractedAccountData
            {
                Id           = account.Id,
                AccountName  = account.AccountName,
                AccountAlias = account.AccountAlias
            }).ToList();

            accounts.ForEach(account =>
            {
                result.Add(account.Id, new ChartDataVm.DataSet());
                result[account.Id].Label = string.IsNullOrEmpty(account.AccountAlias)
                    ? account.AccountName
                    : account.AccountAlias;
            });

            return(result);
        }
Example #10
0
        private decimal LoadTotalIncomeTotal(Period period, long[] idMasterAccounts, long[] idTradeAccounts)
        {
            decimal total;
            var     fees = _tradeRepository
                           .TradeFeesQuery()
                           .Include(a => a.TradeAccount.MasterAccount)
                           .Where(s => s.ExternalDate >= period.FromDate && s.ExternalDate <= period.ToDate);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                total = fees.Where(fee => idTradeAccounts.Contains(fee.TradeAccountId)).Select(s => s.NetInBase)
                        .DefaultIfEmpty(0).Sum();
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                total = fees.Where(fee => idMasterAccounts.Contains(fee.TradeAccount.MasterAccount.Id)).Select(s => s.NetInBase)
                        .DefaultIfEmpty(0).Sum();
            }
            else
            {
                total = fees.Select(s => s.NetInBase).DefaultIfEmpty(0).Sum();
            }

            return(total);
        }
 public IEnumerable <IdNameModel> GetIdNames()
 {
     return(_masterAccountRepository.GetAll().Select(acc => new IdNameModel
     {
         Id = acc.Id,
         Name = TradeUtils.ResolveMasterAccountName(acc)
     }));
 }
Example #12
0
        //Retreive data from config to initialise the rule
        public override void Init()
        {
            SymbolCode = GetSymbolCode();

            //Get Rule Config params
            ExecuteOnlyOnce             = GetRuleConfigBoolParam(RuleConfiguration.EXECUTEONLYONCE);
            NumberOfOrders              = GetRuleConfigIntegerParam(RuleConfiguration.NUMBEROFORDERS);
            EntryPipsFromTradeOpenPrice = TradeUtils.CalcPipsForBroker(GetRuleConfigDoubleParam(RuleConfiguration.ENTRYPIPSFROMTRADEOPENPRICE));
            TakeProfitPips              = TradeUtils.CalcPipsForBroker(GetRuleConfigDoubleParam(RuleConfiguration.TAKEPROFIPIPS));

            //Listen for state updates for this strategy
            StateManager.ListenForStateUpdates();
        }
Example #13
0
        private bool IsActive = true; //Default state is active

        public IRule(StrategyConfiguration strategyConfig, RuleConfiguration ruleConfig)
        {
            this.StrategyConfig = strategyConfig;
            this.RuleConfig     = ruleConfig;

            StrategyId = StrategyConfig.StrategyId;
            if (String.IsNullOrEmpty(StrategyId))
            {
                IsInitialised = false;
            }

            ExchangeName = StrategyConfig.Exchange;
            if (String.IsNullOrEmpty(ExchangeName))
            {
                IsInitialised = false;
            }

            BrokerId = StrategyConfig.BrokerId;
            if (String.IsNullOrEmpty(BrokerId))
            {
                IsInitialised = false;
            }

            //Initialise TradeUtils for broker specific config
            TradeUtils = new TradeUtils(new BrokerConfiguration(BrokerId), ruleConfig);

            //Initialise a TradesPublisher
            TradePublisher = new TradePublisher(Publisher, TradeUtils, GetServiceName());

            //Add Rule configuration to Firebase
            StateManager = new StateManager(StrategyId);
            if (StateManager == null)
            {
                IsInitialised = false;
            }
            StateManager.SetInitialStateAsync(RuleConfig.Params);

            //Manage State updates if subscribed to by the derived rule
            StateManager.StateUpdateReceived += OnStateEventUpdate;

            StateManager.SetActivationRulesAsync(GetServiceName(), RuleConfig.ActivateRules);
            StateManager.SetDeactivationRulesAsync(GetServiceName(), RuleConfig.DeactivateRules);

            //If this rule has activation rules default state IsActive = false
            if (RuleConfig.ActivateRules != null)
            {
                IsActive = false;
            }
            StateManager.UpdateRuleStatusAsync(GetServiceName(), RuleConfiguration.ISACTIVE, IsActive);
        }
Example #14
0
        private decimal LoadTotalClientsTotal(Period period, long[] idMasterAccounts, long[] idTradeAccounts)
        {
            var accounts = _tradeRepository
                           .TradeAccountsQuery()
                           .Include(acc => acc.MasterAccount)
                           .Where(account => account.DateOpened != null &&
                                  account.DateOpened <= period.ToDate &&
                                  (account.DateClosed == null ||
                                   account.DateClosed != null && account.DateClosed > period.ToDate));

            return(TradeUtils.IsSortingByMasterAccounts(idMasterAccounts)
                ? accounts.Count(account => idMasterAccounts.Contains(account.MasterAccountId))
                : accounts.Count());
        }
Example #15
0
        public TotalAccountListModel FilterListData(TotalAccountListEnum elementNumber, string searchExpression, IEnumerable <long> idMasterAccounts, IEnumerable <long> idTradeAccounts)
        {
            var tradeAccounts = _tradeRepository.TradeAccountsQuery().Where(s => s.IsClientInfo == true);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts.ToArray()))
            {
                tradeAccounts = tradeAccounts.Where(fee => idTradeAccounts.Contains(fee.Id));
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts.ToArray()))
            {
                tradeAccounts = tradeAccounts.Where(fee => idMasterAccounts.Contains(fee.MasterAccount.Id));
            }

            var listModel = RetriveListData(tradeAccounts, elementNumber);

            listModel.AccountTotalList = string.IsNullOrEmpty(searchExpression) ? listModel.AccountTotalList : listModel.AccountTotalList.Where(s => s.Key.ToLower().Contains(searchExpression.ToLower())).ToList();
            return(listModel);
        }
Example #16
0
        private decimal LoadTotalAbandoment(Period period, long[] idMasterAccounts,
                                            long[] idTradeAccounts)
        {
            var totalAbondmentEndPeriod = _tradeRepository
                                          .TradeAccountsQuery()
                                          .Where(fee => fee.DateClosed <= period.ToDate);

            var totalAbondmentStartPeriod = _tradeRepository
                                            .TradeAccountsQuery()
                                            .Where(fee => fee.DateClosed <= period.FromDate);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                var endPeriod = totalAbondmentEndPeriod
                                .Where(fee => idTradeAccounts.Contains(fee.Id)).Count(c => c.TradeStatus == "C");

                var startPeriod = totalAbondmentStartPeriod
                                  .Where(fee => idTradeAccounts.Contains(fee.Id)).Count(c => c.TradeStatus == "C");

                return(endPeriod - startPeriod);
            }

            if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                var endPeriod = totalAbondmentEndPeriod
                                .Where(fee => idMasterAccounts.Contains(fee.MasterAccountId))
                                .Count(c => c.TradeStatus == "C");

                var startPeriod = totalAbondmentStartPeriod
                                  .Where(fee => idMasterAccounts.Contains(fee.MasterAccountId))
                                  .Count(c => c.TradeStatus == "C");

                return(endPeriod - startPeriod);
            }

            var endPer   = totalAbondmentEndPeriod.Count(c => c.TradeStatus == "C");
            var startPer = totalAbondmentStartPeriod.Count(c => c.TradeStatus == "C");

            return(endPer - startPer);
        }
Example #17
0
        public ChartDataVm GetPortfolioChartData(PortfolioChartDataQueryParam queryParams)
        {
            var result = ChartDataVm.Default;

            result.Labels = TradeUtils.GetPeriodLabels(queryParams.Periods.ToPeriodList()).ToArray();

            switch (queryParams.ChartType)
            {
            case PortfolioChartType.Nav:
                result.Data = new[] { GetPortfolioNavChartData(queryParams) };
                break;

            case PortfolioChartType.OpenPositions:
                result.Data = new[] { GetPortfolioOpenPositionsChartData(queryParams) };
                break;

            case PortfolioChartType.TotalUn:
                result.Data = new[] { GetPortfolioTotalUnChartData(queryParams) };
                break;
            }

            return(result);
        }
Example #18
0
        public List <TotalAccountListModel> GetListData(Period period, IEnumerable <long> idMasterAccounts, IEnumerable <long> idTradeAccounts)
        {
            var list          = new List <TotalAccountListModel>();
            var tradeAccounts = _tradeRepository
                                .TradeAccountsQuery().Where(s => s.IsClientInfo == true);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts.ToArray()))
            {
                tradeAccounts = tradeAccounts.Where(fee => idTradeAccounts.Contains(fee.Id));
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts.ToArray()))
            {
                tradeAccounts = tradeAccounts.Where(fee => idMasterAccounts.Contains(fee.MasterAccount.Id));
            }

            var city = RetriveListData(tradeAccounts, TotalAccountListEnum.CityList);

            var state = RetriveListData(tradeAccounts, TotalAccountListEnum.CountryList);

            var capabilities = RetriveListData(tradeAccounts, TotalAccountListEnum.AccountCapabilitiesList);

            var accType = RetriveListData(tradeAccounts, TotalAccountListEnum.AccountTypeList);

            var idEntity = RetriveListData(tradeAccounts, TotalAccountListEnum.IbEntityList);

            var currency = RetriveListData(tradeAccounts, TotalAccountListEnum.BaseCurrencyList);

            //adding to list
            list.Add(city);
            list.Add(state);
            list.Add(capabilities);
            list.Add(accType);
            list.Add(idEntity);
            list.Add(currency);

            return(list);
        }
Example #19
0
        public ChartDataVm LoadTotalClients(IEnumerable <Period> periodsParam, long[] idMasterAccounts,
                                            long[] idTradeAccounts)
        {
            var result    = ChartDataVm.Default;
            var periods   = periodsParam.ToList();
            var endPeriod = periods.LastOrDefault()?.ToDate;

            if (endPeriod == null)
            {
                return(result);
            }

            Dictionary <long, ChartDataVm.DataSet> data;

            result.Labels = TradeUtils.GetPeriodLabels(periods).ToArray();

            var accountsQuery = _tradeRepository
                                .TradeAccountsQuery()
                                .Include(a => a.MasterAccount)
                                .Where(account => account.DateOpened != null &&
                                       account.DateOpened <= endPeriod &&
                                       (account.DateClosed == null ||
                                        (account.DateClosed != null && account.DateClosed > endPeriod)));

            data = GetDictionaryByMasterAccounts(idMasterAccounts);

            // sorting by selected master accounts
            if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                accountsQuery = accountsQuery.Where(s => idMasterAccounts.Contains(s.MasterAccountId));
            }

            periods.ForEach(period =>
            {
                var extractedAccountData = accountsQuery
                                           .GroupBy(group => new
                {
                    group.MasterAccount.Id,
                    group.MasterAccount.AccountName,
                    group.MasterAccount.AccountAlias
                })
                                           .Select(select => new ExtractedAccountData
                {
                    Id           = select.Key.Id,
                    AccountName  = select.Key.AccountName,
                    AccountAlias = select.Key.AccountAlias,
                    Number       = select.Count(account => account.DateOpened != null &&
                                                account.DateOpened <= period.ToDate &&
                                                (account.DateClosed == null ||
                                                 account.DateClosed != null &&
                                                 account.DateClosed > period.ToDate))
                })
                                           .ToList();

                ProcessExtractedData(extractedAccountData, data);
            });

            if (data.Any())
            {
                result.Data = data.Select(d => d.Value).ToArray();
            }

            return(result);
        }
Example #20
0
        private decimal?LoadTotalFutures(Period period, long[] idMasterAccounts,
                                         long[] idTradeAccounts)
        {
            decimal?total;
            decimal?end;
            decimal?start;
            var     tradeAs   = _tradeRepository.TradeAsQuery().Where(t => t.AssetCategory == "FUT");
            var     endDate   = period.ToDate.Date;
            var     dateEnd   = DateTime.ParseExact(endDate.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);
            var     startDate = period.FromDate.Date == endDate ? DateTime.MinValue : period.FromDate.Date;
            var     dateStart =
                DateTime.ParseExact(startDate.ToString("yyyyMMdd"), "yyyyMMdd", CultureInfo.InvariantCulture);


            if (tradeAs.Where(s => s.ReportDate == dateEnd).Select(q => q.Quantity).Sum() == null)
            {
                var tempEndDate = tradeAs.Where(s => s.ReportDate <= dateEnd).OrderByDescending(s => s.ReportDate)
                                  .Select(q => q.ReportDate).FirstOrDefault();
                var tempEnd = tradeAs.Where(s => s.ReportDate >= dateEnd).OrderBy(s => s.ReportDate)
                              .Select(q => q.ReportDate).FirstOrDefault();
                dateEnd = tempEndDate == DateTime.MinValue ? tempEnd : tempEndDate;
            }

            if (tradeAs.Where(s => s.ReportDate == dateStart).Select(q => q.Quantity).Sum() == null &&
                startDate != DateTime.MinValue)
            {
                var tempStartDate = tradeAs.Where(s => s.ReportDate >= dateStart).OrderBy(s => s.ReportDate)
                                    .Select(q => q.ReportDate).FirstOrDefault();
                var tempStart = tradeAs.Where(s => s.ReportDate <= dateStart).OrderByDescending(s => s.ReportDate)
                                .Select(q => q.ReportDate).FirstOrDefault();
                dateStart = tempStart == DateTime.MinValue ? tempStartDate : tempStart;
            }

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                end = tradeAs.Where(s => s.ReportDate == dateEnd && idTradeAccounts.Contains(s.TradeAccount.Id))
                      .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                start = tradeAs.Where(s => s.ReportDate == dateStart && idTradeAccounts.Contains(s.TradeAccount.Id))
                        .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                total = end - start;
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                end = tradeAs
                      .Where(s => s.ReportDate == dateEnd && idMasterAccounts.Contains(s.TradeAccount.MasterAccountId))
                      .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                start = tradeAs
                        .Where(s => s.ReportDate == dateStart && idMasterAccounts.Contains(s.TradeAccount.MasterAccountId))
                        .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                total = end - start;
            }
            else
            {
                end = tradeAs.Where(s => s.ReportDate == dateEnd)
                      .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                start = tradeAs.Where(s => s.ReportDate == dateStart)
                        .Select(q => q.Quantity).DefaultIfEmpty(0).Sum();
                total = end - start;
            }

            return(total);
        }
Example #21
0
        private decimal NewClientsTableData(string findPeriod, long[] idMasterAccounts, long[] idTradeAccounts, bool dif)
        {
            var tradeAccounts = _tradeAccountRepository
                                .TradeAccountsQuery();

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                tradeAccounts = tradeAccounts.Where(fee => idTradeAccounts.Contains(fee.Id));
            }
            else if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
            {
                tradeAccounts = tradeAccounts.Where(fee => idMasterAccounts.Contains(fee.MasterAccount.Id));
            }

            switch (findPeriod)
            {
            case "LD":
                var     startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                var     endDate   = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day).AddDays(-1);
                decimal res       = dif ? tradeAccounts.Where(s => s.DateOpened >= endDate && s.DateOpened <= startDate).Select(s => s.TradeFees.Select(sum => sum.NetInBase).DefaultIfEmpty(0).Sum()).FirstOrDefault() : tradeAccounts.Where(s => s.DateFunded >= endDate && s.DateFunded <= startDate).Select(s => s.TradeInterestAccruas.Select(sum => sum.EndingAccrualBalance).DefaultIfEmpty(0).Sum()).FirstOrDefault();
                return(Math.Round(res, 2));

            case "MTD":
                startDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
                endDate   = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                res       = dif ? tradeAccounts
                            .Where(s => s.DateOpened <= endDate && s.DateOpened >= startDate)
                            .Select(s => s.TradeFees.Select(sum => sum.NetInBase)
                                    .DefaultIfEmpty(0).Sum()).FirstOrDefault() :
                            tradeAccounts.Where(s => s.DateFunded <= endDate && s.DateFunded >= startDate)
                            .Select(s => s.TradeInterestAccruas
                                    .Select(sum => sum.EndingAccrualBalance)
                                    .DefaultIfEmpty(0).Sum()).FirstOrDefault();
                return(Math.Round(res, 2));

            case "LM":
                var today = DateTime.Today;
                var month = new DateTime(today.Year, today.Month, 1);
                var first = month.AddMonths(-1);
                var last  = month.AddDays(-1);
                res = dif ? tradeAccounts.Where(s => s.DateOpened <= last && s.DateOpened >= first).Select(s => s.TradeFees.Select(sum => sum.NetInBase).DefaultIfEmpty(0).Sum()).FirstOrDefault() : tradeAccounts.Where(s => s.DateFunded <= last && s.DateFunded >= first).Select(s => s.TradeInterestAccruas.Select(sum => sum.EndingAccrualBalance).DefaultIfEmpty(0).Sum()).FirstOrDefault();
                return(Math.Round(res, 2));

            case "MAVG":
                today = DateTime.Today;
                month = new DateTime(today.Year, today.Month, 1);
                first = month.AddMonths(-1);
                last  = month.AddDays(-1);
                int numberOfDays = (int)(last - first).TotalDays;
                res = dif ? tradeAccounts.Where(s => s.DateOpened <= last && s.DateOpened >= first).Select(s => s.TradeFees.Select(sum => sum.NetInBase).DefaultIfEmpty(0).Sum()).FirstOrDefault() : tradeAccounts.Where(s => s.DateFunded <= last && s.DateFunded >= first).Select(s => s.TradeInterestAccruas.Select(sum => sum.EndingAccrualBalance).DefaultIfEmpty(0).Sum()).FirstOrDefault();
                return(Math.Round(Convert.ToDecimal(res / numberOfDays), 2));

            case "12MAVG":
                decimal daysLeft       = new DateTime(DateTime.Now.Year, 12, 31).DayOfYear - DateTime.Now.DayOfYear;
                var     firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                endDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                res     = dif ? tradeAccounts.Where(s => s.DateOpened <= endDate && s.DateOpened >= firstDayOfYear).Select(s => s.TradeFees.Select(sum => sum.NetInBase).DefaultIfEmpty(0).Sum()).FirstOrDefault() : tradeAccounts.Where(s => s.DateFunded <= endDate && s.DateFunded >= firstDayOfYear).Select(s => s.TradeInterestAccruas.Select(sum => sum.EndingAccrualBalance).DefaultIfEmpty(0).Sum()).FirstOrDefault();
                return(Math.Round(res / daysLeft, 2));

            default:
                return(0);
            }
        }
Example #22
0
        public ChartDataVm LoadTotalIncome(IEnumerable <Period> periodsParam, long[] idMasterAccounts,
                                           long[] idTradeAccounts)
        {
            var periods      = periodsParam.ToList();
            var startPeriods = periods.FirstOrDefault()?.FromDate;
            var endPeriods   = periods.LastOrDefault()?.ToDate;
            var result       = ChartDataVm.Default;

            if (startPeriods == null || endPeriods == null)
            {
                return(result);
            }

            result.Labels = TradeUtils.GetPeriodLabels(periods).ToArray();
            Dictionary <long, ChartDataVm.DataSet> data;

            var fees = _tradeRepository
                       .TradeFeesQuery()
                       .Include(f => f.TradeAccount.MasterAccount)
                       .Where(s => s.ExternalDate >= startPeriods && s.ExternalDate <= endPeriods);

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                fees = fees.Where(fee => idTradeAccounts.Contains(fee.TradeAccountId));
                data = GetDictionaryByTradeAccounts(idTradeAccounts);

                periods.ForEach(period =>
                {
                    var extractedData = fees
                                        .Where(fee => fee.ExternalDate >= period.FromDate && fee.ExternalDate <= period.ToDate)
                                        .GroupBy(group => new
                    {
                        group.TradeAccount.Id,
                        group.TradeAccount.AccountName,
                        group.TradeAccount.AccountAlias,
                    })
                                        .Select(select => new ExtractedAccountData
                    {
                        Id           = select.Key.Id,
                        AccountName  = select.Key.AccountName,
                        AccountAlias = select.Key.AccountAlias,
                        Number       = select.Sum(f => f.NetInBase)
                    })
                                        .ToList();

                    ProcessExtractedData(extractedData, data);
                });
            }
            else
            {
                data = GetDictionaryByMasterAccounts(idMasterAccounts);

                if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
                {
                    fees = fees.Where(fee => idMasterAccounts.Contains(fee.TradeAccount.MasterAccountId));
                }

                periods.ForEach(period =>
                {
                    var extractedData = fees
                                        .Where(fee => fee.ExternalDate >= period.FromDate && fee.ExternalDate <= period.ToDate)
                                        .GroupBy(group => new
                    {
                        group.TradeAccount.MasterAccount.Id,
                        group.TradeAccount.MasterAccount.AccountName,
                        group.TradeAccount.MasterAccount.AccountAlias
                    })
                                        .Select(select => new ExtractedAccountData
                    {
                        Id           = select.Key.Id,
                        AccountName  = select.Key.AccountName,
                        AccountAlias = select.Key.AccountAlias,
                        Number       = select.Sum(f => f.NetInBase)
                    })
                                        .ToList();


                    ProcessExtractedData(extractedData, data);
                });
            }

            if (data.Any())
            {
                result.Data = data.Select(d => d.Value).ToArray();
            }

            return(result);
        }
Example #23
0
        public ChartDataVm LoadInterest(IEnumerable <Period> periodsParam, long[] idMasterAccounts, long[] idTradeAccounts)
        {
            var result    = ChartDataVm.Default;
            var periods   = periodsParam.ToList();
            var endPeriod = periods.LastOrDefault()?.ToDate;

            if (endPeriod == null)
            {
                return(result);
            }

            result.Labels = TradeUtils.GetPeriodLabels(periods).ToArray();
            Dictionary <long, ChartDataVm.DataSet> data;

            var tradeInterestAccruaQuery = _tradeAccountRepository.TradeInterestAccrua();

            if (TradeUtils.IsSortingByTradeAccounts(idTradeAccounts))
            {
                data = GetDictionaryByTradeAccounts(idTradeAccounts);

                tradeInterestAccruaQuery = tradeInterestAccruaQuery.Where(nav => idTradeAccounts.Contains(nav.TradeAccountId));

                periods.ForEach(period =>
                {
                    var extractedData = tradeInterestAccruaQuery
                                        .Where(tradeNav =>
                                               DbFunctions.TruncateTime(tradeNav.ReportDate) == DbFunctions.TruncateTime(period.ToDate))
                                        .GroupBy(group => new
                    {
                        group.TradeAccount.Id,
                        group.TradeAccount.AccountName,
                        group.TradeAccount.AccountAlias,
                    })
                                        .Select(select => new ExtractedAccountData
                    {
                        Id           = select.Key.Id,
                        AccountName  = select.Key.AccountName,
                        AccountAlias = select.Key.AccountAlias,
                        Number       = select.Sum(tradeInterest => tradeInterest.EndingAccrualBalance)
                    })
                                        .ToList();

                    ProcessExtractedData(extractedData, data);
                });
            }
            else
            {
                data = GetDictionaryByMasterAccounts(idMasterAccounts);

                if (TradeUtils.IsSortingByMasterAccounts(idMasterAccounts))
                {
                    tradeInterestAccruaQuery = tradeInterestAccruaQuery.Where(nav =>
                                                                              idMasterAccounts.Contains(nav.TradeAccount.MasterAccountId));
                }

                periods.ForEach(period =>
                {
                    var extractedData = tradeInterestAccruaQuery
                                        .Where(tradeNav =>
                                               DbFunctions.TruncateTime(tradeNav.ReportDate) == DbFunctions.TruncateTime(period.ToDate))
                                        .GroupBy(group => new
                    {
                        group.TradeAccount.MasterAccount.Id,
                        group.TradeAccount.MasterAccount.AccountName,
                        group.TradeAccount.MasterAccount.AccountAlias
                    })
                                        .Select(select => new ExtractedAccountData
                    {
                        Id           = select.Key.Id,
                        AccountName  = select.Key.AccountName,
                        AccountAlias = select.Key.AccountAlias,
                        Number       = select.Sum(tradeInterest => tradeInterest.EndingAccrualBalance)
                    })
                                        .ToList();

                    ProcessExtractedData(extractedData, data);
                });
            }

            if (data.Any())
            {
                result.Data = data.Select(d => d.Value).ToArray();
            }

            return(result);
        }
Example #24
0
        public ChartDataVm GetChartData(AnalyticsChartDataParams @params)
        {
            var result = new ChartDataVm();

            var impQuery = ImportRepository.ImportedFilesQuery();
            var delQuery = ImportRepository.FileUploadQuery().Include(f => f.ImportedFile);

            if (@params.MasterAccountId != 0)
            {
                impQuery = impQuery.Where(f => f.MasterAccountId == @params.MasterAccountId);
                delQuery = delQuery.Where(f => f.ImportedFile.MasterAccountId == @params.MasterAccountId);
            }

            if (@params.FtpCredentialId != 0)
            {
                impQuery = impQuery.Where(f => f.FtpCredentialId == @params.FtpCredentialId);
                delQuery = delQuery.Where(f => f.ImportedFile.FtpCredentialId == @params.FtpCredentialId);
            }

            var srcFilesData = new ChartDataVm.DataSet {
                Label = "Source files"
            };
            var impFilesData = new ChartDataVm.DataSet {
                Label = "Imported files"
            };
            var delFilesData = new ChartDataVm.DataSet {
                Label = "ZOHO files"
            };
            var sentFilesData = new ChartDataVm.DataSet {
                Label = "Sent ZOHO files"
            };

            var periods = @params.Periods.ToPeriodList().ToList();

            periods.ToList().ForEach(period =>
            {
                var srcFiles = impQuery.Count(f =>
                                              DbFunctions.TruncateTime(f.FileCreateDate) >= DbFunctions.TruncateTime(period.FromDate) &&
                                              DbFunctions.TruncateTime(f.FileCreateDate) <= DbFunctions.TruncateTime(period.ToDate));

                var impFiles = impQuery.Count(f =>
                                              DbFunctions.TruncateTime(f.FileCreateDate) >= DbFunctions.TruncateTime(period.FromDate) &&
                                              DbFunctions.TruncateTime(f.FileCreateDate) <= DbFunctions.TruncateTime(period.ToDate) &&
                                              f.ImportedDate != null);

                var delFiles = delQuery.Count(f =>
                                              DbFunctions.TruncateTime(f.ImportedFile.FileCreateDate) >=
                                              DbFunctions.TruncateTime(period.FromDate) &&
                                              DbFunctions.TruncateTime(f.ImportedFile.FileCreateDate) <= DbFunctions.TruncateTime(period.ToDate));

                var sentFiles = delQuery.Count(f => f.IsSent &&
                                               DbFunctions.TruncateTime(f.ImportedFile.FileCreateDate) >=
                                               DbFunctions.TruncateTime(period.FromDate) &&
                                               DbFunctions.TruncateTime(f.ImportedFile.FileCreateDate) <=
                                               DbFunctions.TruncateTime(period.ToDate));

                srcFilesData.Data.Add(srcFiles);
                impFilesData.Data.Add(impFiles);
                delFilesData.Data.Add(delFiles);
                sentFilesData.Data.Add(sentFiles);
            });

            result.Data   = new[] { srcFilesData, impFilesData, delFilesData, sentFilesData };
            result.Labels = TradeUtils.GetPeriodLabels(periods).ToArray();

            return(result);
        }