private static void HandleSellSignals(SimulationDto simulationDto, IList <CompanyPricesDto> allPrices, SignalEvent signalEvent,
                                              SimulationResultDto simulationResult)
        {
            var prices = ConvertPrices(allPrices, signalEvent.CompaniesToSell, signalEvent.Date);

            foreach (var price in prices)
            {
                if (!simulationResult.CurrentCompanyQuantity.ContainsKey(price.Key))
                {
                    continue;
                }
                var transaction = new SimulationTransactionDto
                {
                    Date        = signalEvent.Date,
                    CompanyId   = price.Key,
                    Price       = price.Value,
                    Action      = SignalAction.Sell,
                    Quantity    = simulationResult.CurrentCompanyQuantity[price.Key],
                    BudgetAfter =
                        simulationDto.Budget + simulationResult.CurrentCompanyQuantity[price.Key] * price.Value
                };
                simulationResult.TransactionsLog.Add(transaction);
                simulationDto.Budget = transaction.BudgetAfter;
                simulationResult.CurrentCompanyQuantity.Remove(price.Key);
            }
        }
        private static decimal BuyAndKeepStrategyProfit(SimulationDto simulationDto, SimulationResultDto simulationResult,
                                                        IList <CompanyPricesDto> allPrices)
        {
            var budget           = simulationResult.StartBudget;
            var budgetPerCompany = budget / allPrices.Count;

            foreach (var companyPricesDto in allPrices)
            {
                var startDayPrice =
                    companyPricesDto.Prices.Where(item => item.Date >= simulationDto.StartDate)
                    .OrderBy(item => item.Date)
                    .FirstOrDefault();
                var endDatePrice =
                    companyPricesDto.Prices.Where(item => item.Date <= simulationDto.EndDate)
                    .OrderByDescending(item => item.Date)
                    .FirstOrDefault();
                if (startDayPrice == null || endDatePrice == null)
                {
                    continue;
                }
                var quantity = (int)Math.Floor(budgetPerCompany / startDayPrice.ClosePrice);
                budget += quantity * (endDatePrice.ClosePrice - startDayPrice.ClosePrice);
            }
            var keepStrategyProfit = budget;

            return(keepStrategyProfit);
        }
        public void GetSimulations_returnProperDtoCollection()
        {
            //Arrange
            EFSimulationRepository repository  = new EFSimulationRepository();
            List <SimulationDto>   simulations = new List <SimulationDto>();
            SimulationDto          dto1        = new SimulationDto()
            {
                Id = 1, Name = "a"
            };
            SimulationDto dto2 = new SimulationDto()
            {
                Id = 2, Name = "b"
            };
            SimulationDto dto3 = new SimulationDto()
            {
                Id = 3, Name = "c"
            };
            SimulationDto dto4 = new SimulationDto()
            {
                Id = 4, Name = "d"
            };

            simulations.AddRange(new SimulationDto[] { dto1, dto2, dto3, dto4 });
            clearSimulationsTables();
            repository.UpdateSimulations(simulations);

            //Act
            IEnumerable <SimulationDto> dtos = repository.GetSimulations().ToArray();

            //Assert
            bool areEqualArrays = simulations.HasEqualItems(dtos);

            Assert.IsTrue(areEqualArrays);
        }
        public void UpdateSimulations_WorksProperly_IfItemsAreOnlyAdded()
        {
            //Arrange
            EFSimulationRepository repository  = new EFSimulationRepository();
            List <SimulationDto>   simulations = new List <SimulationDto>();
            SimulationDto          dto1        = new SimulationDto()
            {
                Id = 1, Name = "a"
            };
            SimulationDto dto2 = new SimulationDto()
            {
                Id = 2, Name = "b"
            };
            SimulationDto dto3 = new SimulationDto()
            {
                Id = 3, Name = "c"
            };
            SimulationDto dto4 = new SimulationDto()
            {
                Id = 4, Name = "d"
            };

            simulations.AddRange(new SimulationDto[] { dto1, dto2, dto3, dto4 });

            //Act
            clearSimulationsTables();
            repository.UpdateSimulations(simulations);
            IEnumerable <SimulationDto> actualRecords = repository.GetSimulations();

            //Assert
            bool areEqual = simulations.HasEqualItems(actualRecords);

            Assert.IsTrue(areEqual);
        }
 public IActionResult GetDamage(SimulationDto simulationDto)
 {
     return(ExecFunc(() => {
         string token = Request.Headers["Authorization"];
         if (token == null)
         {
             return _simulationApplication.GetMoveDamageInCache(simulationDto);
         }
         return _simulationApplication.GetMoveDamage(simulationDto);
     }));
 }
Exemplo n.º 6
0
        public void Constructor_fromDto_hasCorrectProperties()
        {
            //Act.
            SimulationDto dto = new SimulationDto
            {
                Id   = DEFAULT_ID,
                Name = DEFAULT_NAME
            };
            var simulation = Simulation.FromDto(dto);

            //Assert.
            Assert.AreEqual(DEFAULT_ID, simulation.Id);
            Assert.AreEqual(DEFAULT_NAME, simulation.Name);
        }
        private static void HandleBuySignals(SimulationDto simulationDto, IList <CompanyPricesDto> allPrices, SignalEvent signalEvent,
                                             SimulationResultDto simulationResult)
        {
            var prices = ConvertPrices(allPrices, signalEvent.CompaniesToBuy, signalEvent.Date);

            //.OrderByDescending(item => item.Value);
            foreach (var price in prices)
            {
                var value = simulationDto.Budget;
                if (simulationDto.HasMaximalTransactionLimit)
                {
                    value = Math.Min(value, simulationDto.MaximalBudgetPerTransaction);
                }
                if (simulationDto.HasMinimalTransactionLimit)
                {
                    if (value < simulationDto.MinimalBudgetPerTransaction)
                    {
                        continue; // not enough money
                    }
                    value = Math.Max(value, simulationDto.MinimalBudgetPerTransaction);
                }
                if (value < price.Value)
                {
                    continue;
                }

                int quantity    = (int)Math.Floor(value / price.Value);
                var transaction = new SimulationTransactionDto
                {
                    Date        = signalEvent.Date,
                    CompanyId   = price.Key,
                    Price       = price.Value,
                    Action      = SignalAction.Buy,
                    Quantity    = quantity,
                    BudgetAfter =
                        simulationDto.Budget - quantity * price.Value
                };
                simulationResult.TransactionsLog.Add(transaction);
                if (simulationResult.CurrentCompanyQuantity.ContainsKey(price.Key))
                {
                    simulationResult.CurrentCompanyQuantity[price.Key] += quantity;
                }
                else
                {
                    simulationResult.CurrentCompanyQuantity.Add(price.Key, quantity);
                }
                simulationDto.Budget = transaction.BudgetAfter;
            }
        }
Exemplo n.º 8
0
        public void GetSimulationById_ReturnsNull_IfThereIsNoItemWithGivenCombination()
        {
            //Arrange
            Mock <ISimulationRepository> mockedRepository = new Mock <ISimulationRepository>();
            SimulationDto returnedDto = null;

            mockedRepository.Setup(r => r.GetSimulationById(1)).Returns(returnedDto);

            //Act
            SimulationService service = new SimulationService(mockedRepository.Object);

            //Assert
            Simulation baseSimulation = service.GetSimulationById(1);

            Assert.IsNull(baseSimulation);
        }
Exemplo n.º 9
0
        public void GetSimulationById_ReturnsProperItem_IfItemExists()
        {
            //Arrange
            Mock <ISimulationRepository> mockedRepository = new Mock <ISimulationRepository>();
            SimulationDto simulationDto = new SimulationDto()
            {
                Id = 1, Name = "a"
            };

            List <AnalysisTimestampDto> timestamps = new List <AnalysisTimestampDto>();
            AnalysisTimestampDto        timestamp1 = new AnalysisTimestampDto()
            {
                Id = 1, SimulationId = 1, AssetId = 1, TimeframeId = 1, AnalysisTypeId = 2, LastAnalysedItem = new DateTime(2016, 5, 2, 12, 0, 0)
            };
            AnalysisTimestampDto timestamp2 = new AnalysisTimestampDto()
            {
                Id = 2, SimulationId = 1, AssetId = 1, TimeframeId = 1, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 5, 2, 13, 0, 0)
            };
            AnalysisTimestampDto timestamp3 = new AnalysisTimestampDto()
            {
                Id = 3, SimulationId = 1, AssetId = 1, TimeframeId = 1, AnalysisTypeId = 4, LastAnalysedItem = new DateTime(2016, 5, 2, 14, 0, 0)
            };

            timestamps.AddRange(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3 });

            mockedRepository.Setup(r => r.GetSimulationById(1)).Returns(simulationDto);
            mockedRepository.Setup(r => r.GetAnalysisTimestampsForSimulation(1)).Returns(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3 });

            //Act
            SimulationService service = new SimulationService(mockedRepository.Object);
            var actualSimulation      = service.GetSimulationById(1);

            //Assert
            Simulation expectedSimulation = new Simulation()
            {
                Id = 1, Name = "a"
            };

            expectedSimulation.AddLastUpdate(timestamp1);
            expectedSimulation.AddLastUpdate(timestamp2);
            expectedSimulation.AddLastUpdate(timestamp3);
            bool areEqual = expectedSimulation.Equals(actualSimulation);

            Assert.IsTrue(areEqual);
        }
Exemplo n.º 10
0
        public void Update_AllItemsPassedToMethodArePassedToRepository()
        {
            //Arrange
            IEnumerable <SimulationDto>        simulationDtos = null;
            IEnumerable <AnalysisTimestampDto> timestampDtos  = null;
            Simulation simulation = new Simulation()
            {
                Id = 1, Name = "a"
            };
            AnalysisTimestamp timestamp1 = new AnalysisTimestamp()
            {
                Id = 1, SimulationId = 1, AssetId = 1, TimeframeId = 1, AnalysisTypeId = 2, LastAnalysedItem = new DateTime(2016, 5, 2, 12, 0, 0), LastAnalysedIndex = 15
            };
            AnalysisTimestamp timestamp2 = new AnalysisTimestamp()
            {
                Id = 2, SimulationId = 1, AssetId = 1, TimeframeId = 1, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 6, 2, 12, 0, 0), LastAnalysedIndex = 19
            };

            simulation.AddLastUpdate(timestamp1);
            simulation.AddLastUpdate(timestamp2);
            Mock <ISimulationRepository> mockedRepository = new Mock <ISimulationRepository>();

            mockedRepository.
            Setup(r => r.UpdateSimulations(It.IsAny <IEnumerable <SimulationDto> >())).
            Callback <IEnumerable <SimulationDto> >((col) => simulationDtos = col).Verifiable();
            mockedRepository.
            Setup(r => r.UpdateAnalysisTimestamps(It.IsAny <IEnumerable <AnalysisTimestampDto> >())).
            Callback <IEnumerable <AnalysisTimestampDto> >((col) => timestampDtos = col).Verifiable();

            //Act
            SimulationService service = new SimulationService(mockedRepository.Object);

            service.Update(simulation);

            //Assert
            IEnumerable <SimulationDto>        expectedSimulationDtos = new SimulationDto[] { simulation.ToDto() };
            IEnumerable <AnalysisTimestampDto> expectedTimestampDtos  = new AnalysisTimestampDto[] { timestamp1.ToDto(), timestamp2.ToDto() };

            mockedRepository.Verify(r => r.UpdateSimulations(It.IsAny <IEnumerable <SimulationDto> >()), Times.Exactly(1));
            mockedRepository.Verify(r => r.UpdateAnalysisTimestamps(It.IsAny <IEnumerable <AnalysisTimestampDto> >()), Times.Exactly(1));
            Assert.IsTrue(simulationDtos.HasEqualItems(expectedSimulationDtos));
            Assert.IsTrue(timestampDtos.HasEqualItems(expectedTimestampDtos));
        }
Exemplo n.º 11
0
        public void GetSimulationById_ReturnsAlwaysTheSameInstance()
        {
            //Arrange
            Mock <ISimulationRepository> mockedRepository = new Mock <ISimulationRepository>();
            List <SimulationDto>         dtos             = new List <SimulationDto>();
            SimulationDto simulationDto1 = new SimulationDto()
            {
                Id = 1, Name = "a"
            };

            dtos.AddRange(new SimulationDto[] { simulationDto1 });

            List <AnalysisTimestampDto> timestamps = new List <AnalysisTimestampDto>();
            AnalysisTimestampDto        timestamp1 = new AnalysisTimestampDto()
            {
                Id = 1, SimulationId = 1, AnalysisTypeId = 2, LastAnalysedItem = new DateTime(2016, 5, 2, 12, 0, 0)
            };
            AnalysisTimestampDto timestamp2 = new AnalysisTimestampDto()
            {
                Id = 2, SimulationId = 1, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 5, 2, 13, 0, 0)
            };
            AnalysisTimestampDto timestamp3 = new AnalysisTimestampDto()
            {
                Id = 3, SimulationId = 1, AnalysisTypeId = 4, LastAnalysedItem = new DateTime(2016, 5, 2, 14, 0, 0)
            };

            timestamps.AddRange(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3 });

            mockedRepository.Setup(r => r.GetSimulations()).Returns(dtos);
            mockedRepository.Setup(r => r.GetAnalysisTimestampsForSimulation(1)).Returns(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3 });

            //Act
            SimulationService service = new SimulationService(mockedRepository.Object);

            //Assert
            Simulation baseSimulation     = service.GetSimulationById(1);
            Simulation comparedSimulation = service.GetSimulationById(1);

            bool areTheSame = (baseSimulation == comparedSimulation);

            Assert.IsTrue(areTheSame);
        }
Exemplo n.º 12
0
        public void UpdateSimulations_WorksProperly_IfItemsAreAddedAndUpdated()
        {
            //Arrange
            AnalysisDataQueryDefinition queryDef    = new AnalysisDataQueryDefinition(1, 1);
            EFSimulationRepository      repository  = new EFSimulationRepository();
            List <SimulationDto>        simulations = new List <SimulationDto>();
            SimulationDto dto1 = new SimulationDto()
            {
                Id = 1, Name = "a"
            };
            SimulationDto dto2 = new SimulationDto()
            {
                Id = 2, Name = "b"
            };
            SimulationDto dto3 = new SimulationDto()
            {
                Id = 3, Name = "c"
            };
            SimulationDto dto4 = new SimulationDto()
            {
                Id = 4, Name = "d"
            };

            simulations.AddRange(new SimulationDto[] { dto1, dto2, dto3 });
            clearSimulationsTables();
            repository.UpdateSimulations(simulations);

            //Act
            dto1.Name  = "x";
            dto2.Name += "b";

            IEnumerable <SimulationDto> expectedRecords = new SimulationDto[] { dto1, dto2, dto3, dto4 };

            repository.UpdateSimulations(expectedRecords);
            IEnumerable <SimulationDto> actualRecords = repository.GetSimulations();

            //Assert
            bool areEqual = expectedRecords.HasEqualItems(actualRecords);

            Assert.IsTrue(areEqual);
        }
Exemplo n.º 13
0
        public SimulationReturnDto GetMoveDamageInCache(SimulationDto simulationDto)
        {
            //GET DATA
            List <PokemonDto> listPokemonDto;

            _cacheDomain.Cache.TryGetValue("Pokemons", out listPokemonDto);
            var attackingPokemon = listPokemonDto.FirstOrDefault(x => x.Id == simulationDto.AttackingPokemonId);
            var defendingPokemon = listPokemonDto.FirstOrDefault(x => x.Id == simulationDto.DefendingPokemonId);
            var move             = _moveRepository.GetById <Moves>(simulationDto.MoveId);

            attackingPokemon.PokemonSpecies = _pokemonRepository.GetById <Pokemon_Species>(attackingPokemon.PokemonSpecies.Id).ToDto();
            defendingPokemon.PokemonSpecies = _pokemonRepository.GetById <Pokemon_Species>(defendingPokemon.PokemonSpecies.Id).ToDto();
            var listTypeAdvantage = _typeAdvantageRepository.GetByIdAttackingType(move.Id_Type);

            //GET TYPES ADVANTAGES
            var firstTypeAdvantage  = listTypeAdvantage.FirstOrDefault(x => x.DefendingType.Id == defendingPokemon.PokemonSpecies.FirstType.Id);
            var secondTypeAdvantage = listTypeAdvantage.FirstOrDefault(x => x.DefendingType.Id == defendingPokemon.PokemonSpecies.SecondType?.Id);

            //SET CALCULATOR
            var simulationCalc = new SimulationCalc(
                attackerLevel: attackingPokemon.Level,
                moveBasePower: move.Base_Power,
                attackingStat: move.Move_Category == MoveCategoryEnum.Physical ? attackingPokemon.Attack : attackingPokemon.SpAttack,
                defendingStat: move.Move_Category == MoveCategoryEnum.Physical ? defendingPokemon.Defense : defendingPokemon.SpDefense,
                modifier: simulationDto.Modifier);
            var hasStab = attackingPokemon.PokemonSpecies.FirstType.Id == move.Id_Type ||
                          attackingPokemon.PokemonSpecies.SecondType?.Id == move.Id_Type;

            var typeEffect = secondTypeAdvantage == null ? firstTypeAdvantage.Effect : firstTypeAdvantage.Effect * secondTypeAdvantage.Effect;

            simulationCalc.AddTypesDataToModifier(hasStab, typeEffect);

            var damage = simulationCalc.CalculateDamage();

            return(new SimulationReturnDto()
            {
                Damage = damage, EffectDecimal = typeEffect
            });
        }
Exemplo n.º 14
0
        public void GetSimulationById_ReturnsProperSimulationDto_IfExists()
        {
            //Arrange
            EFSimulationRepository repository  = new EFSimulationRepository();
            List <SimulationDto>   simulations = new List <SimulationDto>();
            SimulationDto          expected    = new SimulationDto()
            {
                Id = 1, Name = "a"
            };

            simulations.AddRange(new SimulationDto[] { expected });
            clearSimulationsTables();
            repository.UpdateSimulations(simulations);

            //Act
            SimulationDto dto = repository.GetSimulationById(expected.Id);

            //Assert
            var areEqual = expected.Equals(dto);

            Assert.IsTrue(areEqual);
        }
Exemplo n.º 15
0
        public void CopyProperties_AfterwardAllPropertiesAreEqual()
        {
            //Arrange
            var baseItem = new SimulationDto()
            {
                Id   = 1,
                Name = "a"
            };

            var comparedItem = new SimulationDto()
            {
                Id   = 1,
                Name = "b"
            };

            //Act
            comparedItem.CopyProperties(baseItem);
            var areEqual = baseItem.Equals(comparedItem);

            //Assert
            Assert.IsTrue(areEqual);
        }
Exemplo n.º 16
0
        public void GetSimulationById_ReturnsNull_IfThereIsNoSimulationWithSuchId()
        {
            //Arrange
            EFSimulationRepository repository  = new EFSimulationRepository();
            List <SimulationDto>   simulations = new List <SimulationDto>();
            SimulationDto          dto0        = new SimulationDto()
            {
                Id = 1, Name = "a"
            };
            SimulationDto dto1 = new SimulationDto()
            {
                Id = 1, Name = "b"
            };

            simulations.AddRange(new SimulationDto[] { dto0, dto1 });
            clearSimulationsTables();
            repository.UpdateSimulations(simulations);

            //Act
            SimulationDto dto = repository.GetSimulationById(dto1.Id + 1);

            //Assert
            Assert.IsNull(dto);
        }
Exemplo n.º 17
0
        protected void Refresh_Routes()
        {
            if (SelectedSimulation == null)
            {
                SelectedSimulation = new SimulationDto {  Voyages = new ObservableCollection<VoyageDto>() };
                SelectedSimulation.Starting_Address = "Home";
                SelectedSimulation.Returning_Address = "Home";

                SelectedSimulation.Starting_Latitude =   44.1383781433105;
                SelectedSimulation.Starting_Longitude =   12.2387800216675;
                SelectedSimulation.Returning_Latitude =  44.1383781433105;
                SelectedSimulation.Returning_Longitude = 12.2387800216675;

                for (int i = 0; i < 1; i++)
                {
                    var v = new VoyageDto() { Orders = new ObservableCollection<int>() };
                    foreach(var order in Scenario.Orders)
                        v.Orders.Add(order.Number);

                    v.Departing = DateTime.Today.AddDays(1);
                    v.Exitmated_Time = TimeSpan.FromDays(1);
                    v.Extimated_Lenght_Km = 12;

                    SelectedSimulation.Voyages.Add(v);
                }
                Simulations.Add(SelectedSimulation);
            }

            var calculator = new BingRouteCalculator();
            calculator.Set_Starting_Point(SelectedSimulation.Starting_Latitude, SelectedSimulation.Starting_Longitude);
            calculator.Set_Ending_Point(SelectedSimulation.Returning_Latitude, SelectedSimulation.Returning_Longitude);

            foreach (var spot in SelectedSimulation.Voyages)
            {
                foreach(var orderId in spot.Orders)
                {
                    var order = GetOrder(orderId);
                    calculator.Add_Tour(order.Latitude, order.Longitude);
                }
            }

            var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

            calculator.Calculate_Routes()
                .ContinueWith((t) =>
                {
                    var results = calculator.Result.ToList();

                    Routes.Add(new RouteViewModel(null, results.Select(r => new maps.RouteService.Location { Latitude = r.Latitude, Longitude = r.Longitude })));
                }, scheduler);
        }
Exemplo n.º 18
0
        public void GetSimulations_ReturnsProperCollectionOfSimulations_IncludingLastUpdateTimestamps()
        {
            //Arrange
            Mock <ISimulationRepository> mockedRepository = new Mock <ISimulationRepository>();
            List <SimulationDto>         dtos             = new List <SimulationDto>();
            SimulationDto simulationDto1 = new SimulationDto()
            {
                Id = 1, Name = "a"
            };
            SimulationDto simulationDto2 = new SimulationDto()
            {
                Id = 2, Name = "b"
            };
            SimulationDto simulationDto3 = new SimulationDto()
            {
                Id = 3, Name = "c"
            };

            dtos.AddRange(new SimulationDto[] { simulationDto1, simulationDto2, simulationDto3 });

            List <AnalysisTimestampDto> timestamps = new List <AnalysisTimestampDto>();
            AnalysisTimestampDto        timestamp1 = new AnalysisTimestampDto()
            {
                Id = 1, AssetId = 1, TimeframeId = 1, SimulationId = 1, AnalysisTypeId = 2, LastAnalysedItem = new DateTime(2016, 5, 2, 12, 0, 0)
            };
            AnalysisTimestampDto timestamp2 = new AnalysisTimestampDto()
            {
                Id = 2, AssetId = 1, TimeframeId = 1, SimulationId = 1, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 5, 2, 13, 0, 0)
            };
            AnalysisTimestampDto timestamp3 = new AnalysisTimestampDto()
            {
                Id = 3, AssetId = 1, TimeframeId = 2, SimulationId = 1, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 5, 2, 14, 0, 0)
            };
            AnalysisTimestampDto timestamp4 = new AnalysisTimestampDto()
            {
                Id = 4, AssetId = 1, TimeframeId = 1, SimulationId = 2, AnalysisTypeId = 2, LastAnalysedItem = new DateTime(2016, 5, 2, 12, 0, 0)
            };
            AnalysisTimestampDto timestamp5 = new AnalysisTimestampDto()
            {
                Id = 5, AssetId = 1, TimeframeId = 1, SimulationId = 2, AnalysisTypeId = 3, LastAnalysedItem = new DateTime(2016, 5, 2, 13, 0, 0)
            };
            AnalysisTimestampDto timestamp6 = new AnalysisTimestampDto()
            {
                Id = 6, AssetId = 1, TimeframeId = 2, SimulationId = 2, AnalysisTypeId = 4, LastAnalysedItem = new DateTime(2016, 5, 2, 14, 0, 0)
            };

            timestamps.AddRange(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3, timestamp4, timestamp5, timestamp6 });

            mockedRepository.Setup(r => r.GetSimulations()).Returns(dtos);
            mockedRepository.Setup(r => r.GetAnalysisTimestampsForSimulation(1)).Returns(new AnalysisTimestampDto[] { timestamp1, timestamp2, timestamp3 });
            mockedRepository.Setup(r => r.GetAnalysisTimestampsForSimulation(2)).Returns(new AnalysisTimestampDto[] { timestamp4, timestamp5, timestamp6 });

            //Act
            SimulationService service = new SimulationService(mockedRepository.Object);
            var actualSimultations    = service.GetSimulations();

            //Assert
            List <Simulation> expectedSimulations = new List <Simulation>();
            Simulation        simulation1         = new Simulation()
            {
                Id = 1, Name = "a"
            };

            simulation1.AddLastUpdate(timestamp1);
            simulation1.AddLastUpdate(timestamp2);
            simulation1.AddLastUpdate(timestamp3);
            Simulation simulation2 = new Simulation()
            {
                Id = 2, Name = "b"
            };

            simulation2.AddLastUpdate(timestamp4);
            simulation2.AddLastUpdate(timestamp5);
            simulation2.AddLastUpdate(timestamp6);
            Simulation simulation3 = new Simulation()
            {
                Id = 3, Name = "c"
            };

            expectedSimulations.AddRange(new Simulation[] { simulation1, simulation2, simulation3 });
            bool areEqual = expectedSimulations.HasEqualItems(actualSimultations);

            Assert.IsTrue(areEqual);
        }
        /// <inheritdoc />
        public async Task <SimulationResultDto> RunSimulation(SimulationDto simulationDto)
        {
            var simulationResult = new SimulationResultDto
            {
                TransactionsLog        = new List <SimulationTransactionDto>(),
                CurrentCompanyQuantity = new Dictionary <int, int>(),
                StartBudget            = simulationDto.Budget,
            };
            var strategy = await _strategyService.GetStrategy(simulationDto.UserId, simulationDto.SelectedStrategyId);

            if (simulationDto.SelectedCompanyIds == null || !simulationDto.SelectedCompanyIds.Any())
            {
                throw new BusinessException("No companies were specified");
            }

            var signalEvents = await _indicatorsService.GetSignals(simulationDto.StartDate, simulationDto.EndDate,
                                                                   simulationDto.SelectedCompanyIds, strategy.Indicators, strategy.IsConjunctiveStrategy, strategy.SignalDaysPeriod ?? 1);

            var allPrices = await _priceService.GetPrices(simulationDto.SelectedCompanyIds);

            foreach (var signalEvent in signalEvents.OrderBy(item => item.Date))
            {
                // Shall we buy and sell companies thesame day?
                if (signalEvent.CompaniesToSell.Count > 0)
                {
                    HandleSellSignals(simulationDto, allPrices, signalEvent, simulationResult);
                }
                if (signalEvent.CompaniesToBuy.Count > 0)
                {
                    HandleBuySignals(simulationDto, allPrices, signalEvent, simulationResult);
                }
            }
            var keepStrategyProfit = BuyAndKeepStrategyProfit(simulationDto, simulationResult, allPrices);

            simulationResult.SimulationTotalValue = simulationResult.CurrentCompanyQuantity.Sum(x =>
            {
                var companyPricesDto = allPrices.FirstOrDefault(item => item.Company.Id == x.Key);
                var lastDayPrice     = companyPricesDto?.Prices.Where(item => item.Date <= simulationDto.EndDate)
                                       .OrderByDescending(item => item.Date)
                                       .FirstOrDefault();
                if (lastDayPrice != null)
                {
                    return(x.Value * lastDayPrice.ClosePrice);
                }
                return(0);
            }) + simulationDto.Budget;

            simulationResult.PercentageProfit = Math.Round((double)((simulationResult.SimulationTotalValue - simulationResult.StartBudget) / simulationResult.StartBudget) * 100, 2);
            CalculateMinimalAndMaximalSimulationValue(simulationDto.StartDate, simulationDto.EndDate, allPrices, simulationDto.SelectedCompanyIds, simulationResult);
            CalculateAverageGainAndLossOnTransaction(simulationResult, simulationDto.SelectedCompanyIds);
            simulationResult.KeepStrategyProfit = keepStrategyProfit;

            simulationResult.CurrentCompanies = new List <OwnedCompanyStocksDto>();
            var companies = await _companyService.GetCompanies(simulationDto.SelectedCompanyIds);

            foreach (var i in simulationResult.CurrentCompanyQuantity)
            {
                simulationResult.CurrentCompanies.Add(new OwnedCompanyStocksDto
                {
                    CompanyId        = i.Key,
                    CompanyName      = companies.FirstOrDefault(x => x.Id == i.Key)?.Code,
                    OwnedStocksCount = i.Value,
                    CurrentPrice     = allPrices.First(item => item.Company.Id == i.Key).Prices.Where(item => item.Date <= simulationDto.EndDate).OrderByDescending(item => item.Date).First().ClosePrice,
                    CurrentValue     = allPrices.First(item => item.Company.Id == i.Key).Prices.Where(item => item.Date <= simulationDto.EndDate).OrderByDescending(item => item.Date).First().ClosePrice *i.Value
                });
            }

            simulationResult.CurrentCompanies.Add(new OwnedCompanyStocksDto
            {
                CompanyId        = 0,
                CompanyName      = "Free Budget",
                OwnedStocksCount = 0,
                CurrentPrice     = 0,
                CurrentValue     = simulationDto.Budget
            });

            CalculateProfit(simulationResult);

            return(simulationResult);
        }
Exemplo n.º 20
0
        protected void Refresh_Routes_Old()
        {
            if (SelectedSimulation == null)
            {
                SelectedSimulation = new SimulationDto {  Voyages = new ObservableCollection<VoyageDto>() };
                SelectedSimulation.Starting_Address = "Home";
                SelectedSimulation.Returning_Address = "Home";

                SelectedSimulation.Starting_Latitude =   44.1383781433105;
                SelectedSimulation.Starting_Longitude =   12.2387800216675;
                SelectedSimulation.Returning_Latitude =  44.1383781433105;
                SelectedSimulation.Returning_Longitude = 12.2387800216675;

                for (int i = 0; i < 1; i++)
                {
                    var v = new VoyageDto() { Orders = new ObservableCollection<int>() };
                    foreach(var order in Scenario.Orders)
                        v.Orders.Add(order.Number);

                    v.Departing = DateTime.Today.AddDays(1);
                    v.Exitmated_Time = TimeSpan.FromDays(1);
                    v.Extimated_Lenght_Km = 12;

                    SelectedSimulation.Voyages.Add(v);
                }
                Simulations.Add(SelectedSimulation);
            }

            var service = maps.ServiceHelper.GetRouteService();
            service.CalculateRouteCompleted += (sender, e) =>
            {
                var voyage = e.UserState as VoyageDto;

                Routes.Add(new RouteViewModel(voyage, e.Result.Result.RoutePath.Points));
            };

            foreach (var route in SelectedSimulation.Voyages)
            {
                var wp = route.Orders.Select(v => new maps.RouteService.Waypoint
                    {
                        Description = v + "",
                        Location = new maps.RouteService.Location { Latitude = GetOrder(v).Latitude, Longitude = GetOrder(v).Longitude }
                    }).To_ObservableCollection();

                wp.Add(new maps.RouteService.Waypoint { Description = SelectedSimulation.Starting_Address, Location = new maps.RouteService.Location { Latitude = SelectedSimulation.Starting_Latitude, Longitude= SelectedSimulation.Starting_Longitude } });
                //wp.Add(new maps.RouteService.Waypoint { Description = SelectedSimulation.Returning_Address, Location = new maps.RouteService.Location { Latitude = SelectedSimulation.Returning_Latitude, Longitude =SelectedSimulation.Returning_Longitude } });

                var request = new maps.RouteService.RouteRequest
                {
                    Credentials = new maps.RouteService.Credentials() { Token = maps.ServiceHelper.GeocodeServiceCredentials },
                    Culture = System.Threading.Thread.CurrentThread.CurrentUICulture.ToString(),
                    Waypoints = wp

                };
                request.Options = new maps.RouteService.RouteOptions();
                request.Options.RoutePathType = maps.RouteService.RoutePathType.Points;

                service.CalculateRouteAsync(request, route);
            }
        }
Exemplo n.º 21
0
        //private maps.RouteService.Waypoint GeocodeResultToWaypoint(maps.RouteService.GeocodeResult result)
        //{
        //    PlatformServices.Waypoint waypoint = new PlatformServices.Waypoint();
        //    waypoint.Description = result.DisplayName;
        //    waypoint.Location = new Location();
        //    waypoint.Location.Latitude = result.Locations[0].Latitude;
        //    waypoint.Location.Longitude = result.Locations[0].Longitude;
        //    return waypoint;
        //}
        public void BuildDesignData()
        {
            Simulations = new ObservableCollection<SimulationDto>();
            ScenarioId = "scenario1";

            for (int i = 0; i < 10; i++)
            {
                var simul = new SimulationDto { Number = i, Name="Simulazione "+i, Created = DateTime.Now.AddDays(-i) };
                Simulations.Add(simul);
            }

            Routes = new ObservableCollection<RouteViewModel>();

            for (int i = 0; i < 10; i++)
            {
                //var route = new RouteViewModel() { };

                //Routes.Add(route);
            }
        }