Beispiel #1
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 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));
        }
Beispiel #3
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));
        }
Beispiel #4
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);
        }
Beispiel #5
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));
        }
Beispiel #6
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);
        }
Beispiel #7
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));
            }
        }
        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);
        }
        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);
        }
Beispiel #10
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);
        }
    }
Beispiel #11
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
            });
        }
Beispiel #13
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>());
        }
Beispiel #14
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");
        }
Beispiel #19
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);
        }