Ejemplo n.º 1
0
        public void Indicator_Chaining_MAofMA()
        {
            var results1 = new List<DataPoint<decimal>>();
            var results2 = new List<DataPoint<decimal>>();
            var ma1 = new MovingAverageIndicator(2);
            var ma2 = new MovingAverageIndicator(2);
            ma1.Subscribe(ma2); // ma2 of ma1
            ma1.Subscribe(results1.Add);
            ma2.Subscribe(results2.Add);

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 1));
            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 2));
            Assert.That(results1.Last().Value, Is.EqualTo(1.5));
            Assert.That(results2.Any(), Is.EqualTo(false));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 3));
            Assert.That(results1.Last().Value, Is.EqualTo(2.5));
            Assert.That(results2.Last().Value, Is.EqualTo(2));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 4));
            Assert.That(results1.Last().Value, Is.EqualTo(3.5));
            Assert.That(results2.Last().Value, Is.EqualTo(3));

            ma1.OnNext(new DataPoint<decimal>(DateTime.Now, 5));
            Assert.That(results1.Last().Value, Is.EqualTo(4.5));
            Assert.That(results2.Last().Value, Is.EqualTo(4));

            ma1.Dispose();
            ma2.Dispose();
        }
Ejemplo n.º 2
0
        public void LawOfResistorsInSeriesTest(int in0)
        {
            Circuit sim = new Circuit();

            var volt0 = sim.Create<DCVoltageSource>();
            var volt1 = sim.Create<DCVoltageSource>();
            var resCompare = sim.Create<Resistor>(in0 * 100);

            List<Resistor> resistors = new List<Resistor>();
            for(int i = 0; i < in0; i++)
                resistors.Add(sim.Create<Resistor>());

            sim.Connect(volt0.leadPos, resistors.First().leadIn);

            for(int i = 1; i < in0 - 1; i++)
                sim.Connect(resistors[i - 1].leadOut, resistors[i].leadIn);

            sim.Connect(volt0.leadNeg, resistors.Last().leadOut);

            sim.Connect(volt1.leadPos, resCompare.leadIn);
            sim.Connect(resCompare.leadOut, volt1.leadNeg);

            sim.doTicks(100);

            Assert.AreEqual(Math.Round(resistors.Last().getCurrent(), 12), Math.Round(resCompare.getCurrent(), 12));
        }
Ejemplo n.º 3
0
        public void ProducesValues()
        {
            var sut = new MovingAverageIndicator(3);
            
            var results = new List<DataPoint<decimal>>();
            using (sut.Subscribe(results.Add))
            {
                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 1));
                Assert.That(results.Count, Is.EqualTo(0));

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 2));
                Assert.That(results.Count, Is.EqualTo(0));

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 3));
                Assert.That(results.Count, Is.EqualTo(1));
                Assert.That(results.Last().Value, Is.EqualTo(2));

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 4));
                Assert.That(results.Count, Is.EqualTo(2));
                Assert.That(results.Last().Value, Is.EqualTo(3));

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 2));
                Assert.That(results.Count, Is.EqualTo(3));
                Assert.That(results.Last().Value, Is.EqualTo(3));

                sut.Dispose();
            }
        }
Ejemplo n.º 4
0
        public void Couper()
        {
            var jeu = new List<Carte>(Paquet.TrenteDeuxCartes);
            jeu.Melanger();
            var anciennePremiere = jeu.First();
            var ancienneDerniere = jeu.Last();
            jeu = jeu.Couper();
            Check.That(jeu).HasSize(32);
            Check.That(jeu.First()).IsNotEqualTo(anciennePremiere);
            Check.That(jeu.Last()).IsNotEqualTo(ancienneDerniere);

            //Validation d'unicité des cartes
            var hashSet = new HashSet<Carte>(jeu);
            Check.That(hashSet).HasSize(32);
        }
Ejemplo n.º 5
0
        public async Task Can_report_progress_when_downloading_async()
        {
            var hold = AsyncServiceClient.BufferSize;
            AsyncServiceClient.BufferSize = 100;

            try
            {
                var asyncClient = new JsonServiceClient(ListeningOn);

                var progress = new List<string>();

                //Note: total = -1 when 'Transfer-Encoding: chunked'
                //Available in ASP.NET or in HttpListener when downloading responses with known lengths: 
                //E.g: Strings, Files, etc.
                asyncClient.OnDownloadProgress = (done, total) =>
                    progress.Add("{0}/{1} bytes downloaded".Fmt(done, total));

                var response = await asyncClient.GetAsync(new TestProgress());

                progress.Each(x => x.Print());

                Assert.That(response.Length, Is.GreaterThan(0));
                Assert.That(progress.Count, Is.GreaterThan(0));
                Assert.That(progress.First(), Is.EqualTo("100/1160 bytes downloaded"));
                Assert.That(progress.Last(), Is.EqualTo("1160/1160 bytes downloaded"));
            }
            finally
            {
                AsyncServiceClient.BufferSize = hold;
            }
        }         
        public void Index_WhenCalls_SetsUpViewModelWithAllContentDescriptorsAndSelectedList()
        {
            List<ESRBContentDescriptor> selectedContentDescriptors = new List<ESRBContentDescriptor>();
            List<ESRBContentDescriptor> allContentDescriptors = new List<ESRBContentDescriptor>
            {
                new ESRBContentDescriptor(),
                new ESRBContentDescriptor()
            };

            Mock<IVeilDataAccess> dbStub = TestHelpers.GetVeilDataAccessFake();
            Mock<DbSet<ESRBContentDescriptor>> contentDescriptorsDbSetStub = TestHelpers.GetFakeAsyncDbSet(allContentDescriptors.AsQueryable());

            dbStub.
                Setup(db => db.ESRBContentDescriptors).
                Returns(contentDescriptorsDbSetStub.Object);

            ESRBDescriptionController controller = new ESRBDescriptionController(dbStub.Object);

            var result = controller.Index(selectedContentDescriptors);

            Assert.That(result != null);
            Assert.That(result.Model, Is.InstanceOf<ESRBDescriptionViewModel>());

            var model = (ESRBDescriptionViewModel)result.Model;

            Assert.That(model.Selected, Is.SameAs(selectedContentDescriptors));
            Assert.That(model.All.Count(), Is.EqualTo(allContentDescriptors.Count));
            Assert.That(model.All, Has.Member(allContentDescriptors.First()).And.Member(allContentDescriptors.Last()));
        }
        public void Index_WhenCalls_SetsUpViewModelWithAllPlatformsAndSelectedList()
        {
            List<Platform> selectedPlatforms = new List<Platform>();
            List<Platform> allPlatforms = new List<Platform>
            {
                new Platform(),
                new Platform()
            };

            Mock<IVeilDataAccess> dbStub = TestHelpers.GetVeilDataAccessFake();
            Mock<DbSet<Platform>> platformDbSetStub = TestHelpers.GetFakeAsyncDbSet(allPlatforms.AsQueryable());

            dbStub.
                Setup(db => db.Platforms).
                Returns(platformDbSetStub.Object);

            PlatformsController controller = new PlatformsController(dbStub.Object);

            var result = controller.Index(selectedPlatforms);

            Assert.That(result != null);
            Assert.That(result.Model, Is.InstanceOf<PlatformViewModel>());

            var model = (PlatformViewModel) result.Model;

            Assert.That(model.Selected, Is.SameAs(selectedPlatforms));
            Assert.That(model.AllPlatforms.Count(), Is.EqualTo(allPlatforms.Count));
            Assert.That(model.AllPlatforms, Has.Member(allPlatforms.First()).And.Member(allPlatforms.Last()));
        }
Ejemplo n.º 8
0
        public void Initial_snapshot_and_subsequent_deltas_yield_full_snapshot_each_time()
        {
            var key = "EURUSD";
            // arrange
            var observations = new List<Update>();
            _observableDictionary.Get(key)
                .Only(DictionaryNotificationType.Values) // ignore meta notifications
                .Select(dn => dn.Value) // select out the new value in the dictionary
                .Subscribe(observations.Add);

            // act
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new FullUpdate(key) { { "bid", "1.234"}, { "ask", "1.334"}, { "valueDate", "2014-07-16"} }));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "bid", "1.233" }}));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "ask", "1.333" }}));
            _serverUpdateStream.OnNext(new Either<FullUpdate, DeltaUpdate>(new DeltaUpdate(key) { { "bid", "1.231" }, { "ask", "1.331" }}));

            // assert

            observations.ForEach(update => Assert.AreEqual(4, update.Values.Count));
            var first = observations.First();
            var last = observations.Last();

            Assert.AreEqual("1.234", first.Values["bid"]);
            Assert.AreEqual("1.334", first.Values["ask"]);

            Assert.AreEqual("1.231", last.Values["bid"]);
            Assert.AreEqual("1.331", last.Values["ask"]);
        }
Ejemplo n.º 9
0
        public void SetUp()
        {
            MigrationTestHelper.Clear();
            _versionsFromDatabase = new List<long> { 0 };

            var provider = new Mock<IDataProvider>();
            provider.Setup(x => x.DatabaseKind).Returns(DatabaseKind.Oracle);

            var database = new Mock<IDatabase>();
            database.Setup(x => x.Provider).Returns(provider.Object);

            _dataClient = new Mock<IDataClient>();
            _dataClient.Setup(p => p.TableExists(VersionRepository.VERSION_TABLE_NAME)).Returns(true);
            _dataClient.Setup(x => x.Database).Returns(database.Object);

            _versionRepository = new Mock<IVersionRepository>();
            _versionRepository.Setup(x => x.GetCurrentVersion()).Returns(() => _versionsFromDatabase.Last());
            _versionRepository.Setup(x => x.GetAppliedMigrations()).Returns(() => _versionsFromDatabase);
            _versionRepository.Setup(x => x.InsertVersion(It.IsAny<MigrationInfo>()))
                .Callback<MigrationInfo>(m => _versionsFromDatabase.Add(m.Version));
            _versionRepository.Setup(x => x.RemoveVersion(It.IsAny<MigrationInfo>()))
                .Callback<MigrationInfo>(m => _versionsFromDatabase.Remove(m.Version));

            _runner = new Runner(_dataClient.Object, Assembly.GetExecutingAssembly());
            _runner.VersionRepository = _versionRepository.Object;
        }
        public void CreateRandomBets_GivenXBatchSize_ReturnsXInBatchSize(int numberOfBets, int maxBetsBatchSize)
        {
            // Given
            var betsRecieved = new List<List<Bet>>();
            var randomBetDataProvider = new RandomBetDataProvider(numberOfBets, maxBetsBatchSize);
            randomBetDataProvider.BetsProvided += (sender, args) => { betsRecieved.Add(new List<Bet>(args.Bets)); };
            randomBetDataProvider.BetsProviderFinished += (sender, args) =>
            {
                lock (_lockObject)
                {
                    Monitor.Pulse(_lockObject);
                }
            };

            // When
            randomBetDataProvider.Start();
            lock (_lockObject)
            {
                Monitor.Wait(_lockObject, TimeOut);
            }

            // Then
            var lastBatch = betsRecieved.Last();
            foreach (var betsRecievedBatch in betsRecieved)
            {
                if(betsRecievedBatch != lastBatch)
                    Assert.That(betsRecievedBatch.Count, Is.EqualTo(maxBetsBatchSize));
                else
                    Assert.That(betsRecievedBatch.Count, Is.LessThanOrEqualTo(maxBetsBatchSize));
            }
        }
Ejemplo n.º 11
0
        public void Register_roll(int[] rolls, int nFrames, int totalScore)
        {
            var sut = new Integration(new Frames(), new Scorer());

            var results = new List<Game>();
            sut.Result += results.Add;

            rolls.ToList()
                    .ForEach(sut.Register_roll);

            Assert.AreEqual(nFrames, results.Last().Frames.Count());
            Assert.AreEqual(totalScore, results.Last().Score);

            Assert.IsTrue(results[rolls.Length-1].Finished);
            Assert.IsFalse(results[rolls.Length-2].Finished);
        }
        public void Add_Should_Save_And_Assigned_New_Ids_To_Multiple(IRepository<Contact, string> repository)
        {
            IList<Contact> contacts = new List<Contact>
                                            {
                                                new Contact { Name = "Contact 1"},
                                                new Contact { Name = "Contact 2"},
                                                new Contact { Name = "Contact 3"},
                                        };

            repository.Add(contacts);
            contacts.First().ContactId.ShouldNotBeEmpty();
            contacts.Last().ContactId.ShouldNotBeEmpty();
            contacts.First().ShouldNotBeSameAs(contacts.Last().ContactId);

            var added = repository.GetAll();
            added.Count().ShouldEqual(3);
        }
Ejemplo n.º 13
0
 public void can_shuffle()
 {
     var ints = new List<int>();
     1.UpTo(500, ints.Add);
     ints.Shuffle();
     (ints[0] == 1 && ints[1] == 2 && ints.Last() == 500).ShouldBeFalse();
     ints.Distinct().Count().ShouldEqual(500);
 }
Ejemplo n.º 14
0
            public void TwoLegsReturnsOne()
            {
                var traversal = new List<string>();
                var startLeg = "AB";
                var nextLeg = "BC";

                _traverser.Invoke(startLeg, new Dictionary<string, int> { {nextLeg, 7}, { startLeg, 3 } }, ref traversal);

                Assert.That(traversal.Count, Is.EqualTo(2));
                Assert.That(traversal.First(), Is.EqualTo(startLeg));
                Assert.That(traversal.Last(), Is.EqualTo(nextLeg));
            }
Ejemplo n.º 15
0
        public void ShouldNotFinishUntilAllMatchesPlayed()
        {
            var leagueSeason = A.LeagueSeason.Build();

            var fixtures = new List<Fixture>();
            leagueSeason.ScheduleFixtures(f => fixtures.Add(f));

            var allFixturesExceptLast = fixtures.Except(fixtures.Last().AsEnumerable()).ToList();
            allFixturesExceptLast.ForEach(f => leagueSeason.ApplyResult(A.MatchResult.ForFixture(f).Build()));

            Assert.That(leagueSeason.IsFinished, Is.False);
        }
Ejemplo n.º 16
0
        public void ForEach_EndDate()
        {
            DailyRecurrency daily = new DailyRecurrency(new DateTime(2011, 4, 5), new DateTime(2011, 4, 25), DailyType.EveryXDays, 5);
            var dates = new List<DateTime>();

            foreach (var date in daily.Dates())
            {
                dates.Add(date);
            }
            Assert.AreEqual(new DateTime(2011, 4, 5), dates.First());
            Assert.AreEqual(new DateTime(2011, 4, 25), dates.Last());
            Assert.AreEqual(5, dates.Count());
        }
Ejemplo n.º 17
0
            public void GuardsAgainstCircularPathReturnsThePath()
            {
                var traversal = new List<string>();
                var startLeg = "AB";
                var nextLeg = "BA";
                var inputGraph = new Dictionary<string, int> { {nextLeg, 7}, { startLeg, 3 } };

                _traverser.Invoke(startLeg, inputGraph, ref traversal);

                Assert.That(traversal.Count, Is.EqualTo(inputGraph.Count*3+1));
                Assert.That(traversal.First(), Is.EqualTo(startLeg));
                Assert.That(traversal.Last(), Is.EqualTo(startLeg));
            }
        public void Should_Add_Single_Item_To_Existing_List() {
            // Arrange
            IList<int> list = new List<int>(new [] { 1 });

            // Act
            list.AddRange(new [] { 2 });

            // Assert
            list.ShouldNotBeEmpty();
            list.Count.ShouldEqual(2);
            list.First().ShouldEqual(1);
            list.Last().ShouldEqual(2);
        }
Ejemplo n.º 19
0
        public void ProducesValues()
        {
            var sut = new CountIndicator(TimeSpan.FromMilliseconds(100));
            
            var results = new List<DataPoint<decimal>>();

            using (sut.Subscribe(results.Add))
            {
                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 1));
                Assert.That(results.Count, Is.EqualTo(0));

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 2));
                Assert.That(results.Count, Is.EqualTo(0));

                // 110: 1 tick 
                while (results.Count < 1)
                    Thread.Sleep(10);

                sut.OnNext(new DataPoint<decimal>(DateTime.Now, 3)); // this tick is in the next period
                Assert.That(results.Last().Value, Is.EqualTo(2));

                for(int i = 0; i < 10; i++)
                    Thread.Sleep(10);
                
                // 210: 2 ticks
                // actually, wait for the second tick here
                while (results.Count < 2)
                    Thread.Sleep(10);
                
                Assert.That(results.Last().Value, Is.EqualTo(1));

                for (int i = 0; i < 20; i++)
                    Thread.Sleep(10);
                // 410: no new ticks
                Assert.That(results.Last().Value, Is.EqualTo(0));
            }
            sut.Dispose();
        }
        public void should_be_sortable()
        {
            const string kingsCross = "Kings Cross";
            const string bank = "Bank";
            const string princeRegent = "Prince Regent";
            const short fare = 10;

            var accountId = Guid.NewGuid();

            var jny1 = new Journey(accountId, kingsCross, bank);
            var jny2 = new Journey(accountId, bank, princeRegent);
            var jny3 = new Journey(accountId, princeRegent, bank);

            jny1.AssignFare((o, d) => fare);
            jny2.AssignFare((o, d) => fare);
            jny3.AssignFare((o, d) => fare);

            var jourenys = new List<Journey>(new[] {jny2, jny3, jny1});
            jourenys.Sort();

            Assert.That(jourenys.First().Export().Origin, Is.EqualTo(kingsCross));
            Assert.That(jourenys.First().Export().Destination, Is.EqualTo(bank));
            Assert.That(jourenys.First().Export().Fare, Is.EqualTo(10));
            Assert.That(jourenys.First().Export().AccountId, Is.EqualTo(accountId));
            Assert.That(jourenys.First().Export().JourneyId, Is.Not.EqualTo(Guid.Empty));

            Assert.That(jourenys.ElementAt(1).Export().Origin, Is.EqualTo(bank));
            Assert.That(jourenys.ElementAt(1).Export().Destination, Is.EqualTo(princeRegent));
            Assert.That(jourenys.ElementAt(1).Export().Fare, Is.EqualTo(10));
            Assert.That(jourenys.ElementAt(1).Export().AccountId, Is.EqualTo(accountId));
            Assert.That(jourenys.ElementAt(1).Export().JourneyId, Is.Not.EqualTo(Guid.Empty));

            Assert.That(jourenys.Last().Export().Origin, Is.EqualTo(princeRegent));
            Assert.That(jourenys.Last().Export().Destination, Is.EqualTo(bank));
            Assert.That(jourenys.Last().Export().Fare, Is.EqualTo(10));
            Assert.That(jourenys.Last().Export().AccountId, Is.EqualTo(accountId));
            Assert.That(jourenys.Last().Export().JourneyId, Is.Not.EqualTo(Guid.Empty));
        }
        public void AddIfNotExists_AddsNewItem()
        {
            var source = new List<int> {1, 2, 3};
            source.AddIfNotExist(4);

            source.Count.ShouldEqual(4);
            source.ShouldContainInstance(4);

            //Add null
            var col = new List<object> {new object(), new object()};
            col.AddIfNotExist(null);
            col.Last().ShouldBeNull();
            col.ShouldCount(3);
        }
        private static ParentEntity Arrange()
        {
            // Arrange
            // Create untracked entities equivaelent to our collection
            // and then attempt to save and check list
            var childEntities = new List<ChildEntity>
            {
                new ChildEntity {Id = 1, Name = "ChildEntity 1", ParentEntityId = 1},
                new ChildEntity {Id = default(long), Name = "ChildEntity 3", ParentEntityId = 1}
            };

            var childEntityReferencingChildEntities = new List<ChildEntityReferencingChildEntity>
            {
                new ChildEntityReferencingChildEntity
                {
                    Id = 1,
                    Name = "ChildEntityReferencingChildEntity 1",
                    ChildEntityId = 1,
                    ChildEntity = childEntities.Single(x => x.Id == 1),
                    ParentEntityId = 1
                },
                new ChildEntityReferencingChildEntity
                {
                    Id = default(long),
                    Name = "ChildEntityReferencingChildEntity 3",
                    ChildEntityId = default(long),
                    ChildEntity = childEntities.Last(), // untracked and not yet added
                    ParentEntityId = 1
                }
            };

            // If this relationship is already established then the entities must be added
            childEntities.First().ChildEntityReferencingChildEntities =
                childEntityReferencingChildEntities.Where(x => x.ChildEntityId == 1).ToList();

            // GraphDiff cannot handle this situation where a collection is added
            // Must have an existing Id or else EF fails.
            //childEntities.Last().ChildEntityReferencingChildEntities =
            //    childEntityReferencingChildEntities.Where(x => x.ChildEntityId == default(long)).ToList();

            var parentEntity = new ParentEntity
            {
                Id = 1,
                Name = "ParentEntity 1",
                ChildEntities = childEntities.Where(x => x.ParentEntityId == 1).ToList(),
                ChildReferencingChildEntities =
                    childEntityReferencingChildEntities.Where(x => x.ParentEntityId == 1).ToList()
            };
            return parentEntity;
        }
Ejemplo n.º 23
0
        public void ExpiresOn_should_be_180_days_after_the_last_membership_recharge_date()
        {
            var dateTime = DateTime.UtcNow.ToIST();
            var membershipReCharges = new List<MembershipReCharge>
                                          {
                                              new MembershipReCharge { RechargedOn = dateTime.Subtract(new TimeSpan(45,0,0,0))},
                                              new MembershipReCharge { RechargedOn = dateTime},
                                              new MembershipReCharge { RechargedOn = dateTime.AddMonths(1) },
                                              new MembershipReCharge { RechargedOn = dateTime.AddMonths(2)}
                                          };
            membershipReCharges.ForEach(membershipReCharge => membership.Recharge(membershipReCharge));

            membership.ExpiresOn.ShouldEqual(membershipReCharges.Last().RechargedOn.AddDays(180));
        }
        public void should_be_sortable()
        {
            const string bank = "Bank";
            const string princeRegent = "Prince Regent";
            const short fare = 10;

            var jny1Memento = new JourneyMemento
            {
                Origin = bank,
                Destination = princeRegent,
                Fare = 0
            };

            var jny2Memento = new JourneyMemento
            {
                Origin = princeRegent,
                Destination = bank,
                Fare = 0
            };

            var jny1 = new Journey(jny1Memento);
            var jny2 = new Journey(jny2Memento);

            jny1.AssignFare((o, d) => fare);
            jny2.AssignFare((o, d) => fare);

            var journeys = new List<Journey>(new[] {jny2, jny1});
            journeys.Sort();

            Assert.That(journeys.First().Project().Origin, Is.EqualTo(bank));
            Assert.That(journeys.First().Project().Destination, Is.EqualTo(princeRegent));
            Assert.That(journeys.First().Project().Fare, Is.EqualTo(10));

            Assert.That(journeys.Last().Project().Origin, Is.EqualTo(princeRegent));
            Assert.That(journeys.Last().Project().Destination, Is.EqualTo(bank));
            Assert.That(journeys.Last().Project().Fare, Is.EqualTo(10));
        }
        public void Should_Add_Two_Items_To_Existing_List() {
            // Arrange
            IList<int> list = new List<int>(new[] { 1, 2 });

            // Act
            list.AddRange(new[] { 3, 4 });

            // Assert
            list.ShouldNotBeEmpty();
            list.Count.ShouldEqual(4);
            list.First().ShouldEqual(1);
            list.Skip(1).First().ShouldEqual(2);
            list.Skip(2).First().ShouldEqual(3);
            list.Last().ShouldEqual(4);
        }
Ejemplo n.º 26
0
 public void Flatten()
 {
     var s = new ArcSegment2F
       {
     Point1 = new Vector2F(1, 2),
     Point2 = new Vector2F(10, -3),
       };
       var points = new List<Vector2F>();
       var tolerance = 1f;
       s.Flatten(points, 10, tolerance);
       Assert.IsTrue(Vector2F.AreNumericallyEqual(points[0], s.Point1));
       Assert.IsTrue(Vector2F.AreNumericallyEqual(points.Last(), s.Point2));
       var curveLength = s.GetLength(0, 1, 10, tolerance);
       Assert.IsTrue(CurveHelper.GetLength(points) >= curveLength - tolerance * points.Count / 2);
       Assert.IsTrue(CurveHelper.GetLength(points) <= curveLength);
 }
Ejemplo n.º 27
0
        public void AggregatesTicksIntoSecondBars()
        {
            var timeProvider = new ManualTimeProvider(TimeZones.NewYork);
            var enumerator = new TradeBarBuilderEnumerator(Time.OneSecond, TimeZones.NewYork, timeProvider);

            // noon new york time
            var currentTime = new DateTime(2015, 10, 08, 12, 0, 0);
            timeProvider.SetCurrentTime(currentTime);

            // add some ticks
            var ticks = new List<Tick>
            {
                new Tick(currentTime, "SPY", 199.55m, 199, 200) {Quantity = 10},
                new Tick(currentTime, "SPY", 199.56m, 199.21m, 200.02m) {Quantity = 5},
                new Tick(currentTime, "SPY", 199.53m, 198.77m, 199.75m) {Quantity = 20},
                new Tick(currentTime, "SPY", 198.77m, 199.75m) {Quantity = 0},
                new Tick(currentTime, "SPY", 199.73m, 198.77m, 199.75m) {Quantity = 20},
                new Tick(currentTime, "SPY", 198.77m, 199.75m) {Quantity = 0},
            };

            foreach (var tick in ticks)
            {
                enumerator.ProcessData(tick);
            }

            // even though no data is here, it will still return true
            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNull(enumerator.Current);

            // advance a second
            currentTime = currentTime.AddSeconds(1);
            timeProvider.SetCurrentTime(currentTime);

            Assert.IsTrue(enumerator.MoveNext());
            Assert.IsNotNull(enumerator.Current);

            // in the spirit of not duplicating the above code 5 times (OHLCV, we'll assert these ere as well)
            var bar = (TradeBar)enumerator.Current;
            Assert.AreEqual(currentTime.AddSeconds(-1), bar.Time);
            Assert.AreEqual(currentTime, bar.EndTime);
            Assert.AreEqual("SPY", bar.Symbol.Value);
            Assert.AreEqual(ticks.First().LastPrice, bar.Open);
            Assert.AreEqual(ticks.Max(x => x.LastPrice), bar.High);
            Assert.AreEqual(ticks.Min(x => x.LastPrice), bar.Low);
            Assert.AreEqual(ticks.Last().LastPrice, bar.Close);
            Assert.AreEqual(ticks.Sum(x => x.Quantity), bar.Volume);
        }
        public void BasicTest()
        {
            string goodInstance = "goodInstance";
            var statePersister = new Mock<IStatePersister>();
            // Creating fake data for the statePersister...
            var configurationsPersisted = new List<Configuration>()
            {
                GetConfig(1),
                GetConfig(2),
                GetConfig(3)
            };
            Configuration firstGoodConfiguration = GetConfig(1);
            Configuration secondGoodConfiguration = GetConfig(6);
            firstGoodConfiguration.Instance = goodInstance;
            secondGoodConfiguration.Instance = goodInstance;
            configurationsPersisted.Add(firstGoodConfiguration);
            configurationsPersisted.Add(secondGoodConfiguration);

            statePersister.Setup(o => o.Read()).Returns(configurationsPersisted);

            //Creating a fake requestmanager.
            var subscriptionsRequest = new Mock<IRequestManager<ConfigurationSubscription, ConfigurationSubscriptionAnswer>>();
            var updateRequest = new Mock<IRequestManager<ConfigurationUpdate, ConfigurationUpdateAnswer>>();
            var allAnswerSent = new List<AnwserMessage<ConfigurationSubscriptionAnswer>>();
            subscriptionsRequest.Setup(o => o.Send(It.IsAny<AnwserMessage<ConfigurationSubscriptionAnswer>>())).
                Callback<AnwserMessage<ConfigurationSubscriptionAnswer>>(allAnswerSent.Add);

            var toTest = new ConfigurationRequestHandler(subscriptionsRequest.Object, updateRequest.Object, statePersister.Object);

            //Sending a request to the manager
            var requestId = 1021;
            var request = GetRequestMessage(requestId, goodInstance);
            subscriptionsRequest.Raise(mock => mock.OnRequest += null, null, request);

            //We check that we received what we should, one message with two elements
            Assert.AreEqual(1, allAnswerSent.Count);
            Assert.AreEqual(requestId, allAnswerSent.First().id);
            var sentConfigurations = allAnswerSent.First().answer.result;
            Assert.AreEqual(2, sentConfigurations.Count);
            Assert.AreEqual(firstGoodConfiguration, sentConfigurations.First());
            Assert.AreEqual(secondGoodConfiguration, sentConfigurations.Last());

            //test wildcard :
            var requestAll = GetRequestMessage(requestId+1, ConfigurationRequestHandler.ConfigurationInstanceWildcard);
            subscriptionsRequest.Raise(mock => mock.OnRequest += null, null, requestAll);
            Assert.AreEqual(configurationsPersisted.Count, allAnswerSent.Last().answer.result.Count);
        }
Ejemplo n.º 29
0
        public void Init()
        {
            var taskList = new List<AttemptChainTaskHandler<int>>();

            for (var i = 0; i < _taskCount; i++)
            {
                var newTask = new AttemptChainTaskHandler<int>(new DemoAttemptChainTask() { Index = i });
                taskList.Add(newTask);
            }

            foreach (var task in taskList.Where(task => taskList.IndexOf(task) != taskList.IndexOf(taskList.Last())))
            {
                task.RegisterNext(taskList[taskList.IndexOf(task) + 1]);
            }

            _tasks = taskList;
        }
Ejemplo n.º 30
0
        /// <summary>
        ///     assumes pairs are sorted by the start element
        /// </summary>
        /// <param name = "input"></param>
        /// <returns></returns>
        public static IList<Pair<int, int>> Merge(Pair<int, int>[] input)
        {
            var result = new List<Pair<int, int>>
                {
                    input[0]
                };
            for (int i = 1; i < input.Length; i++)
            {
                var tuple = input[i];
                var last = result.Last();
                if (tuple.First >= last.First + last.Second)
                {
                    result.Add(tuple);
                    continue;
                }

                if (tuple.First + tuple.Second <= last.First + last.Second)
                {
                    continue;
                }

                if (tuple.First == last.First)
                {
                    if (tuple.First + tuple.Second > last.First + last.Second)
                    {
                        result[result.Count - 1] = tuple;
                        continue;
                    }
                }

                if (result.Count > 1)
                {
                    var penultimate = result[result.Count - 2];
                    if (penultimate.First + penultimate.Second >= tuple.First)
                    {
                        result[result.Count - 1] = tuple;
                        continue;
                    }
                }

                result.Add(tuple);
            }
            return result;
        }