public void Init()
        {
            _log                 = Substitute.For <ILog>();
            _dateCalculator      = Substitute.For <IDateCalculator>();
            _powerService        = Substitute.For <IPowerService>();
            _positionAggregator  = Substitute.For <IPositionAggregator>();
            _fileNameGenerator   = Substitute.For <IFileNameGenerator>();
            _reportContentWriter = Substitute.For <IReportContentWriter>();
            _file                = Substitute.For <IFile>();
            _reportGenerator     = new ReportGenerator(_log, _dateCalculator, _powerService, _positionAggregator, _fileNameGenerator, _reportContentWriter, _file);

            _reportFolder = @"C:\Temp\";
            _dates        = new DateResult {
                ExtractDateTime = new DateTime(2015, 10, 5, 23, 34, 0), RequestDate = new DateTime(2015, 10, 6)
            };

            _powerTradeOne = new PowerTrade();
            _powerTradeTwo = new PowerTrade();
            _powerTrades   = new[] { _powerTradeOne, _powerTradeTwo };
            _powerPosition = new PowerPosition(_dates.RequestDate);
            _fileName      = "PowerPositions.csv";
            _content       = "Local time, Volume etc";

            _dateCalculator.Calculate().Returns(_dates);
            _powerService.GetTrades(_dates.RequestDate).Returns(_powerTrades);
            _positionAggregator.Aggregate(_dates.RequestDate, Arg.Is <List <PowerTrade> >(x => x[0] == _powerTradeOne && x[1] == _powerTradeTwo)).Returns(_powerPosition);
            _fileNameGenerator.Generate(_dates.ExtractDateTime).Returns(_fileName);
            _reportContentWriter.Write(_powerPosition).Returns(_content);
        }
        public void When_Positions_Have_The_Same_Period_Then_Are_Sumed()
        {
            //Arrange
            var powerService = Substitute.For <IPowerService>();
            var exporter     = Substitute.For <IReportExporter>();
            var dataProvider = new FakeReportDateProvider();
            var sut          = new InterDayReportGenerator(powerService, exporter, dataProvider);

            var firstPowerTrade  = PowerTrade.Create(new DateTime(2016, 11, 05), 24);
            var secondPowerTrade = PowerTrade.Create(new DateTime(2016, 11, 05), 24);

            var trades = new[] { firstPowerTrade, secondPowerTrade };

            for (int k = 0; k < trades.Length; k++)
            {
                for (int i = 0; i < trades[k].Periods.Length; i++)
                {
                    trades[k].Periods[i].Volume = i;
                }
            }
            dataProvider.WithCurrentDateAndTime(new DateTime(2016, 11, 05));
            powerService.GetTradesAsync(new DateTime(2016, 11, 05)).Returns(trades);

            //Act
            Task.Factory.StartNew(async() => await sut.CreateReportAsync(1, ""), CancellationToken.None, TaskCreationOptions.None, BackgroundScheduler.Default);

            //Assert
            exporter.Received().Export(Arg.Any <string>(), Arg.Any <DateTime>(), Arg.Is <InterdayPowerReportPosition[]>(o => o.Length == 24 && o[6].Volume == 12));
        }
Пример #3
0
        public void WillSumAllTradePeriodsAndSetOnPosition()
        {
            var tradeOne = PowerTrade.Create(new DateTime(2015, 1, 3), 24);

            for (int i = 0; i < 24; i++)
            {
                tradeOne.Periods[i].Volume = 10;
            }

            var tradeTwo = PowerTrade.Create(new DateTime(2015, 1, 3), 24);

            for (int i = 0; i < 24; i++)
            {
                tradeTwo.Periods[i].Volume = -5;
            }

            _trades.Add(tradeOne);
            _trades.Add(tradeTwo);

            var position = _aggregator.Aggregate(_date, _trades);

            Assert.IsNotNull(position);
            Assert.AreEqual(24, position.Periods.Length);
            for (int i = 0; i < position.Periods.Length; i++)
            {
                Assert.AreEqual(5, position.Periods[i].Volume);
            }
        }
        public void Init()
        {
            _log = Substitute.For<ILog>();
            _dateCalculator = Substitute.For<IDateCalculator>();
            _powerService = Substitute.For<IPowerService>();
            _positionAggregator = Substitute.For<IPositionAggregator>();
            _fileNameGenerator = Substitute.For<IFileNameGenerator>();
            _reportContentWriter = Substitute.For<IReportContentWriter>();
            _file = Substitute.For<IFile>();
            _reportGenerator = new ReportGenerator(_log, _dateCalculator, _powerService, _positionAggregator, _fileNameGenerator, _reportContentWriter, _file);

            _reportFolder = @"C:\Temp\";
            _dates = new DateResult { ExtractDateTime = new DateTime(2015, 10, 5, 23, 34, 0), RequestDate = new DateTime(2015, 10, 6) };

            _powerTradeOne = new PowerTrade();
            _powerTradeTwo = new PowerTrade();
            _powerTrades = new[] { _powerTradeOne, _powerTradeTwo };
            _powerPosition = new PowerPosition();
            _fileName = "PowerPositions.csv";
            _content = "Local time, Volume etc";

            _dateCalculator.Calculate().Returns(_dates);
            _powerService.GetTrades(_dates.RequestDate).Returns(_powerTrades);
            _positionAggregator.Aggregate(_dates.RequestDate, Arg.Is<List<PowerTrade>>(x => x[0] == _powerTradeOne && x[1] == _powerTradeTwo)).Returns(_powerPosition);
            _fileNameGenerator.Generate(_dates.ExtractDateTime).Returns(_fileName);
            _reportContentWriter.Write(_powerPosition).Returns(_content);
        }
Пример #5
0
        private static void ExportTradeToCSV(PowerTrade pTrade, string pCSVFilePath, bool pAppend)
        {
            if (!string.IsNullOrEmpty(pCSVFilePath))
            {
                using (CsvWriter writer = new CsvWriter(pCSVFilePath, pAppend, ','))
                {
                    if (!pAppend)
                    {
                        CsvRow row = new CsvRow();
                        row.Add("LocalTime");
                        row.Add("Volume");

                        writer.WriteRow(row);
                    }

                    foreach (PowerPeriod period in pTrade.Periods)
                    {
                        CsvRow row = new CsvRow();
                        row.Add(ConvertPeriodToTime(period.Period));
                        row.Add(period.Volume);
                        writer.WriteRow(row);
                    }
                }
            }
            else
            {
                throw new Exception("CSV file path was empty");
            }
        }
Пример #6
0
        public void ValidateInvalidPowerTrades()
        {
            var powerTrades = new PowerTrades {
                Day = SummerDay, Trades = new[] { PowerTrade.Create(SummerDay.DateTime, 24), PowerTrade.Create(SummerDay.DateTime, 23) }
            };

            Assert.Throws <ArgumentException>(() => PositionReport.ValidateTrades(powerTrades));
        }
Пример #7
0
        public void WillThrowAnExceptionIfAnyTradesDoNotHaveTwentyFourPeriods()
        {
            var tradeOne = PowerTrade.Create(new DateTime(2015, 1, 3), 24);
            var tradeTwo = PowerTrade.Create(new DateTime(2015, 1, 3), 20);

            _trades.Add(tradeOne);
            _trades.Add(tradeTwo);
            _aggregator.Aggregate(_date, _trades);
        }
Пример #8
0
        public void BuildPositionOnePowerTrade()
        {
            var powerTrade = PowerTrade.Create(SummerDay.DateTime, 24);
            var trades     = new PowerTrades {
                Day = SummerDay, Trades = new[] { powerTrade }
            };
            var actual          = PositionReport.BuildPosition(trades);
            var expectedPeriods = powerTrade.Periods;

            Assert.That(actual.Day, Is.EqualTo(trades.Day));
            CollectionAssert.AreEqual(expectedPeriods, actual.Periods, new PowerPeriodComparer(0.0001));
        }
Пример #9
0
        private PowerTrade GetTrade(DateTime theDate, int numPeriods, double[] volumes)
        {
            var trade = PowerTrade.Create(theDate, 24);

            for (int i = 1; i <= 24; i++)
            {
                var period = trade.Periods[i - 1];
                period.Volume = volumes[i - 1];
            }

            return(trade);
        }
        private List <PowerTrade> SampleTrades(DateTime datetime)
        {
            var trades = new List <PowerTrade>()
            {
                PowerTrade.Create(datetime.AddMinutes(1), 24),
                PowerTrade.Create(datetime.AddMinutes(2), 24)
            };

            trades[0].Periods[0].Volume = 100;
            trades[1].Periods[0].Volume = 50;

            return(trades);
        }
Пример #11
0
        public void AddPowerTrade(PowerTrade powerTrade)
        {
            if (powerTrade.Date != ReportDate.Date)
            {
                throw new ArgumentException("PowerTrade has different date than report. Expected date is: " + ReportDate.Date + " trades date is: " + powerTrade.Date);
            }

            for (int i = 0; i < powerTrade.Periods.Length; i++)
            {
                var period = powerTrade.Periods[i];
                _accumulatedVolumes[period.Period] += period.Volume;
            }
        }
Пример #12
0
        public void ValidateValidPowerTrades()
        {
            var powerTrades = new PowerTrades {
                Day = SummerDay, Trades = Enumerable.Range(1, 2).Select(i => PowerTrade.Create(SummerDay.DateTime, 24)).ToArray()
            };
            var actual = PositionReport.ValidateTrades(powerTrades);

            Assert.That(actual.Day, Is.EqualTo(powerTrades.Day));
            for (var i = 0; i < powerTrades.Trades.Count(); i++)
            {
                CollectionAssert.AreEqual(actual.Trades[i].Periods, powerTrades.Trades[i].Periods, new PowerPeriodComparer(0.0001));
            }
        }
Пример #13
0
        private PowerTrade CreatePowerTrade(DateTimeOffset day, int numberOfPeriods)
        {
            var powerTrade = PowerTrade.Create(day.DateTime, numberOfPeriods);

            for (var i = 0; i < numberOfPeriods; i++)
            {
                powerTrade.Periods[i] = new PowerPeriod {
                    Period = i + 1, Volume = i
                }
            }
            ;

            return(powerTrade);
        }
    }
        public static PowerTrade GetPowerTrade3()
        {
            var date = new DateTime(2017, 12, 13);
            var pt   = PowerTrade.Create(date, 24);

            for (var i = 0; i < 24; i++)
            {
                pt.Periods[i] = new PowerPeriod
                {
                    Period = i + 1,
                    Volume = (i + 1) * 30
                };
            }
            return(pt);
        }
Пример #15
0
        public void When_Report_Is_Scheduled_Then_Power_Service_Is_Called()
        {
            //Arrange
            var powerService = Substitute.For <IPowerService>();
            var exporter     = Substitute.For <IReportExporter>();
            var dataProvider = new FakeReportDateProvider();
            var sut          = new InterDayReportGenerator(powerService, exporter, dataProvider);

            var powerTrade = PowerTrade.Create(new DateTime(2016, 11, 06), 24);

            powerService.GetTradesAsync(new DateTime(2016, 11, 07)).Returns(new[] { powerTrade });

            //Act
            Task.Factory.StartNew(async() => await sut.CreateReportAsync(1, ""), CancellationToken.None, TaskCreationOptions.None, BackgroundScheduler.Default);

            //Assert
            powerService.Received(1).GetTradesAsync(Arg.Any <DateTime>());
        }
        /// <summary>
        /// Aggregates the power trades for a day into the position.
        /// </summary>
        /// <param name="trades">The power trades for a day.</param>
        /// <returns>The position.</returns>
        public static Position BuildPosition(PowerTrades trades)
        {
            var settlementDay = Helpers.SettlementDay(trades.Day);
            var seed          = PowerTrade.Create(trades.Day.DateTime, settlementDay.NumberOfPeriods);
            var periods       =
                trades.Trades.Select(t => t.Periods)
                .Aggregate(seed.Periods,
                           (periods1, periods2) =>
                           periods1.Zip(periods2,
                                        (period1, period2) => new PowerPeriod {
                Period = period1.Period, Volume = period1.Volume + period2.Volume
            })
                           .ToArray());

            return(new Position {
                Day = trades.Day, Periods = periods
            });
        }
Пример #17
0
        public void When_Report_Is_Crashed_And_Recover_Then_Report_Generated()
        {
            //Arrange
            var powerService = Substitute.For <IPowerService>();
            var exporter     = Substitute.For <IReportExporter>();
            var dataProvider = new FakeReportDateProvider();
            var sut          = new InterDayReportGenerator(powerService, exporter, dataProvider);

            dataProvider.WithCurrentDateAndTime(new DateTime(2016, 11, 06, 23, 00, 00));
            var powerTrade = PowerTrade.Create(new DateTime(2016, 11, 07), 24);

            powerService.GetTradesAsync(Arg.Any <DateTime>()).Returns(x => throw new ArgumentException(), x => new[] { powerTrade });

            //Act
            Task.Factory.StartNew(async() => await sut.CreateReportAsync(3, ""), CancellationToken.None, TaskCreationOptions.None, BackgroundScheduler.Default);

            //Assert
            powerService.Received(2).GetTradesAsync(Arg.Any <DateTime>());
        }
Пример #18
0
        /// <summary>
        /// Fetch trades and generate CSV file for captured trades
        /// </summary>
        /// <param name="pTradeDate"></param>
        public static void RunTrades(DateTime pTradeDate)
        {
            try
            {
                string       FilePath      = string.Format("{0}PowerPosition_{1}.csv", ConfigurationManager.AppSettings["csvFilePath"], pTradeDate.ToString("yyyyMMdd_HHmm"));
                PowerService _powerService = new PowerService();

                List <PowerTrade> powerTrades = new List <PowerTrade>();
                powerTrades.AddRange(_powerService.GetTrades(pTradeDate));

                PowerTrade result = PowerTrade.Create(pTradeDate, 24);// creating 24 power period for 24 hrs trades

                foreach (var item in powerTrades)
                {
                    foreach (PowerPeriod power in item.Periods)
                    {
                        var pow = result.Periods.FirstOrDefault(x => x.Period == power.Period);
                        if (pow != null)
                        {
                            pow.Volume += power.Volume;
                        }
                    }
                }


                //Sample code for verifying the total result
                int _counter = 1;
                foreach (PowerTrade p in powerTrades)
                {
                    ExportTradeToCSV(p, FilePath.Replace(".csv", string.Format("_{0}.csv", _counter)), false);
                    _counter++;
                }



                ExportTradeToCSV(result, FilePath, false);
            }
            catch (Exception ex)
            {
                EventLogger.WriteEntry(string.Format("Trade capturing failed at {0}.\n Failure Reason : {1}", pTradeDate.ToString(), ex.Message));
            }
        }
        public void When_PowerTrade_Has_The_Same_Date_As_Report_Then_Is_Calculated()
        {
            var powerService = Substitute.For <IPowerService>();
            var exporter     = Substitute.For <IReportExporter>();
            var dataProvider = new FakeReportDateProvider();
            var sut          = new InterDayReportGenerator(powerService, exporter, dataProvider);

            var powerTrade = PowerTrade.Create(new DateTime(2016, 11, 07), 24);

            for (int i = 0; i < powerTrade.Periods.Length; i++)
            {
                powerTrade.Periods[i].Volume = i;
            }
            dataProvider.WithCurrentDateAndTime(new DateTime(2016, 11, 07));
            powerService.GetTradesAsync(new DateTime(2016, 11, 07)).Returns(new[] { powerTrade });

            //Act
            Task.Factory.StartNew(async() => await sut.CreateReportAsync(1, ""), CancellationToken.None, TaskCreationOptions.None, BackgroundScheduler.Default);

            //Assert
            exporter.Received().Export(Arg.Any <string>(), Arg.Any <DateTime>(), Arg.Is <InterdayPowerReportPosition[]>(o => o.Length == 24 && o[6].Volume == 6));
        }
        public async Task Returns_Correctly_Mapped_Periods_In_Trades()
        {
            var inputDate = DateTime.UtcNow;

            var availableTrade1 = PowerTrade.Create(inputDate, 5);
            var availableTrades = new[]
            {
                availableTrade1,
            };

            var mockService = new Mock <IPowerService>();

            mockService.Setup(svc => svc.GetTradesAsync(inputDate))
            .ReturnsAsync(availableTrades);

            var sut = new PowerServiceAdapter(mockService.Object);

            var trades = await sut.GetTradesAsync(inputDate);

            var actualTrade1 = trades.Single();

            actualTrade1.Date.Should().Be(inputDate, "Service and Adapter DTOs must have the same date.");
            actualTrade1.Periods.Length.Should().Be(5, "Adapter DTO period counter must match Service DTO");

            var actualPeriod1 = actualTrade1.Periods.Select(p => new
            {
                P = p.Period,
                V = p.Volume
            }).ToArray();

            var expectedPeriod1 = availableTrade1.Periods.Select(p => new
            {
                P = p.Period,
                V = p.Volume
            }).ToArray();

            actualPeriod1.ShouldBeEquivalentTo(expectedPeriod1);
        }
        public async Task Returns_All_Available_Trades()
        {
            var inputDate = DateTime.UtcNow;

            var availableTrade1 = PowerTrade.Create(inputDate, 0);
            var availableTrade2 = PowerTrade.Create(inputDate, 5);
            var availableTrades = new[]
            {
                availableTrade1,
                availableTrade2,
            };

            var mockService = new Mock <IPowerService>();

            mockService.Setup(svc => svc.GetTradesAsync(inputDate))
            .ReturnsAsync(availableTrades);

            var sut = new PowerServiceAdapter(mockService.Object);

            var trades = await sut.GetTradesAsync(inputDate);

            trades.Count.Should().Be(availableTrades.Length, "Service and Adapter DTOs count must match.");
        }
        public async Task Returns_Same_Structured_Trades()
        {
            var inputDate = DateTime.UtcNow;

            var availableTrade1 = PowerTrade.Create(inputDate, 0);
            var availableTrades = new[]
            {
                availableTrade1,
            };

            var mockService = new Mock <IPowerService>();

            mockService.Setup(svc => svc.GetTradesAsync(inputDate))
            .ReturnsAsync(availableTrades);

            var sut = new PowerServiceAdapter(mockService.Object);

            var trades = await sut.GetTradesAsync(inputDate);

            var actualTrade1 = trades.Single();

            actualTrade1.Date.Should().Be(inputDate, "Service and Adapter DTOs must have the same date.");
            actualTrade1.Periods.Length.Should().Be(availableTrade1.Periods.Length, "Adapter DTO period counter must match Service DTO");
        }
Пример #23
0
        private List <PowerTrade> GeneratePowerPeriods(int totalTrades, int totalPeriods, double volumeFactor)
        {
            List <PowerTrade> testTrades = Enumerable.Range(0, totalTrades).Select(index => PowerTrade.Create(DateTime.Now, totalPeriods)).ToList();

            foreach (var trade in testTrades)
            {
                for (int i = 1; i <= totalPeriods; i++)
                {
                    trade.Periods[i - 1].Period = i;
                    trade.Periods[i - 1].Volume = 1 * volumeFactor;
                }
            }

            return(testTrades);
        }
Пример #24
0
 public PowerTradeAdapter(PowerTrade powerTrade)
 {
     this.powerTrade = powerTrade;
 }