public async Task SetupSubscriberToStopOnFailedConnection()
        {
            // Setup

            var heartbeat = TimeSpan.FromMilliseconds(500);
            var waitTime  = TimeSpan.FromMilliseconds(1000);

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new DerivedWebSocketSubscriber(messenger.Object, log, heartbeat)
            {
                ConnectCallback = (token) => Task.FromException(new AuthenticationException())
            };

            // Execute

            socket.Start();
            await Task.Delay(waitTime); // wait for possible heartbeat recharge

            socket.Dispose();

            // Check

            // 1 call Connect/Stop. No retries.
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.Never);
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
        }
예제 #2
0
        public void RepositoryHandlesConcurrencyConflictsOnUpdate()
        {
            var      logger   = new LogToMemory();
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            // Clear table and insert entity
            var storage = CreateStorage <CandleTableEntity>(logger, clear: true);
            var candle  = new FeedCandle()
            {
                DateTime = baseTime, Open = 0, Close = 0, High = 0, Low = 0
            };

            new CandleHistoryRepository(storage).InsertOrMergeAsync(candle, PriceType.Ask, TimeInterval.Hour).Wait();

            // Run multiple update tasks simultaneously
            var tasks = new List <Task>();

            for (int t = 1; t < 11; t++)
            {
                tasks.Add(Task.Run(() =>
                {
                    var repo    = new CandleHistoryRepository(CreateStorage <CandleTableEntity>(logger, clear: false));
                    var candlet = new FeedCandle()
                    {
                        DateTime = baseTime.AddHours(t), Open = t, Close = t, High = t, Low = t
                    };
                    repo.InsertOrMergeAsync(candlet, PriceType.Ask, TimeInterval.Hour).Wait();
                }));
            }
            Task.WhenAll(tasks).Wait();
        }
        public async Task SetupSubscriberToContinueOnFailedConnection()
        {
            // Setup

            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new DerivedWebSocketSubscriber(messenger.Object, log)
            {
                ConnectCallback = (token) =>
                {
                    var failure = count++ == 0;
                    if (failure)
                    {
                        throw new InvalidOperationException();
                    }
                    return(Task.CompletedTask);
                }
            };

            // Execute
            //
            socket.Start();
            await Task.Delay(ReconnectionTime.Add(TimeSpan.FromMilliseconds(100))); // wait for connection retry

            socket.Dispose();

            // Check
            //

            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeastOnce);
        }
        public async Task SubscriberHandlesExceptionsOnResponse()
        {
            // Setup
            //
            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Callback(() =>
            {
                if (count++ == 0)
                {
                    throw new TimeoutException();
                }
            }).Returns(Task.FromResult(""));
            var socket = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            socket.Start();
            await Task.Delay(ReconnectionTime.Add(TimeSpan.FromMilliseconds(500))); // wait for connection retry

            socket.Stop();
            socket.Dispose();

            // Check

            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));

            // Expecting logged exception
            Assert.True(log.ContainsErrors());
        }
        public async Task SubscriberHandlesExceptionsOnHandle()
        {
            // Setup

            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s =>
            {
                if (count++ == 0)
                {
                    throw new InvalidOperationException();
                }
                return(Task.FromResult(0));
            });

            // Execute

            socket.Start();
            await Task.Delay(100);

            socket.Stop();
            socket.Dispose();

            // Check

            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));

            Assert.True(count > 1); // Expecting messages to continue
            // Expecting logged exception
            Assert.True(log.ContainsErrors());
        }
        public async Task SubscriberCanBeRestartedMultipleTimes()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            var income = new List <string>();
            var socket = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s => { income.Add(s); return(Task.FromResult(0)); });

            // Execute

            for (var i = 0; i < 10; i++)
            {
                messenger
                .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
                .Returns(Task.FromResult(i.ToString()));

                socket.Start();
                await Task.Delay(50);

                socket.Stop();
            }
            socket.Dispose();

            // Check

            // Should receive all 'i': from 1 to 10
            Assert.Equal(45, income.GroupBy(i => i).Select(g => Int32.Parse(g.Key)).Sum());

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task HeartbeatDoesNotRestartAfterStop()
        {
            // Setup

            var heartbeat = TimeSpan.FromMilliseconds(500);
            var waitTime  = TimeSpan.FromMilliseconds(1000);

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log, heartbeat);

            // Execute

            socket.Start();
            await Task.Delay(TimeSpan.FromMilliseconds(50)); // give time to charge heartbeat

            socket.Stop();
            await Task.Delay(waitTime); // wait for possible heartbeat recharge

            socket.Dispose();

            // Check

            // 1 call Connect/Stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
예제 #8
0
        public void CandleCanTake100Characters()
        {
            var      interval = TimeInterval.Sec;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 3600) // 1 hour
                            select new FeedCandle()
            {
                DateTime = baseTime.AddSeconds(i),
                IsBuy    = true,
                Open     = 1234567890.123456,
                Close    = 1234567890.123456,
                High     = 1234567890.123456,
                Low      = 1234567890.123456
            };

            new CandleHistoryRepository(storage).InsertOrMergeAsync(candlesIn, PriceType.Ask, interval).Wait();

            // Select all candles
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Ask, interval,
                                                                                      @from: baseTime,
                                                                                      to: baseTime.AddHours(1)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(3600, queriedCandles.Count());
        }
        public void SetupSubscriberToContinueOnFailedHandle()
        {
            // Setup

            var count     = 0;
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var _lock     = new ManualResetEvent(false);
            var socket    = new DerivedWebSocketSubscriber(messenger.Object, log)
            {
                HandleCallback = (token) =>
                {
                    if (++count < 2)
                    {
                        throw new InvalidOperationException();
                    }
                    _lock.Set();
                    return(Task.CompletedTask);
                }
            };

            // Execute

            socket.Start();
            _lock.WaitOne();
            socket.Dispose();
            // Check

            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.AtLeast(2));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
        public void ProducerShouldBeStartedAutomatically()
        {
            // Produce messages
            // Stop producer
            // Produce another 3 messages
            // Check that all messages are consumed
            //
            var log = new LogToMemory();
            var pc  = new ProducerConsumerStub("component", log);

            pc.ProduceMessage("message 1");
            pc.ProduceMessage("message 2");
            pc.ProduceMessage("message 3");
            Task.Delay(100).Wait();
            pc.Stop();

            pc.ProduceMessage("message 4");
            pc.ProduceMessage("message 5");
            pc.ProduceMessage("message 6");
            Task.Delay(100).Wait();
            pc.Stop();

            Assert.Equal(6, pc.Consumed.Count);

            pc.Dispose();
        }
        public void SetupSubscriberToStopOnFailedHandle()
        {
            // Setup

            var heartbeat = Timeout.InfiniteTimeSpan;
            var lk        = new ManualResetEventSlim(false);
            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new DerivedWebSocketSubscriber(messenger.Object, log, heartbeat)
            {
                HandleCallback = (token) =>
                {
                    lk.Set();
                    return(Task.FromException(new AuthenticationException()));
                }
            };

            // Execute

            socket.Start();
            Thread.Sleep(10000);
            socket.Dispose();

            // Check

            // 1 call Connect/Stop. No retries.
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.GetResponseAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
        }
        public async Task MethodsStartStopAreIdempotent()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            var income = new List <string>();
            var socket = new WebSocketSubscriber(messenger.Object, log);

            socket.Subscribe(s => { income.Add(s); return(Task.FromResult(0)); });

            // Execute

            socket.Start();
            socket.Start();
            socket.Start();
            await Task.Delay(50);

            socket.Stop();
            socket.Stop();
            socket.Stop();
            socket.Dispose();
            socket.Dispose();
            socket.Dispose();

            // Check

            // Should receive all 'i': from 1 to 10
            Assert.True(income.Count > 0);

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
예제 #13
0
        public void WriteReadMinutes()
        {
            var      asset    = "EURUSD";
            var      interval = TimeInterval.Minute;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            var      repo     = new CandleHistoryRepository(storage);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 60 * 24 * 3) // 3 days
                            select new FeedCandle()
            {
                DateTime = baseTime.AddMinutes(i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            repo.InsertOrMergeAsync(candlesIn, asset, interval).Wait();

            // Select for 1 hour
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                      from: baseTime.AddHours(1),
                                                                                      to: baseTime.AddHours(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(60, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), IsBuy = true, Open = 60, Close = 60, High = 60, Low = 60
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1).AddMinutes(59), IsBuy = true, Open = 119, Close = 119, High = 119, Low = 119
            }));

            // Select for 1 day
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                  from: baseTime.AddDays(1),
                                                                                  to: baseTime.AddDays(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(60 * 24 * 1, queriedCandles.Count());

            // Read/write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 99
            }, asset, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(asset, interval, true, baseTime.AddHours(1)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 60
            }));
        }
예제 #14
0
        public void WriteReadHours()
        {
            var      interval = TimeInterval.Hour;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            var      repo     = new CandleHistoryRepository(storage);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 24 * 31 * 3) // 3 months
                            select new FeedCandle()
            {
                DateTime = baseTime.AddHours(i), Open = i, Close = i, High = i, Low = i
            };

            repo.InsertOrMergeAsync(candlesIn, PriceType.Bid, interval).Wait();

            // Select for 1 day
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Bid, interval,
                                                                                      @from: baseTime.AddDays(1),
                                                                                      to: baseTime.AddDays(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(24, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddDays(1), IsBuy = true, Open = 24, Close = 24, High = 24, Low = 24
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddDays(1).AddHours(23), IsBuy = true, Open = 47, Close = 47, High = 47, Low = 47
            }));

            // Select for 1 month
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Bid, interval,
                                                                                  @from: baseTime.AddMonths(1),
                                                                                  to: baseTime.AddMonths(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(24 * 30, queriedCandles.Count());

            // Read/write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddDays(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 99
            }, PriceType.Bid, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(PriceType.Bid, interval, baseTime.AddDays(1)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddDays(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 24
            }));
        }
예제 #15
0
        public void WriteReadWeeks()
        {
            var      asset    = "EURUSD";
            var      interval = TimeInterval.Week;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            DateTime baseTime = new DateTime(2016, 12, 26, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 54 * 3) // > 3 years
                            select new FeedCandle()
            {
                DateTime = baseTime.AddDays(7 * i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            new CandleHistoryRepository(storage).InsertOrMergeAsync(candlesIn, asset, interval).Wait();

            // Select for 1 month
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                      from: baseTime,
                                                                                      to: baseTime.AddDays(28)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(4, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime, IsBuy = true, Open = 0, Close = 0, High = 0, Low = 0
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddDays(21), IsBuy = true, Open = 3, Close = 3, High = 3, Low = 3
            }));

            // Select for 1 year
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                  from: new DateTime(2017, 12, 25),
                                                                                  to: new DateTime(2017, 12, 25).AddDays(364)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(52, queriedCandles.Count());

            // Read/write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddDays(21), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 99
            }, asset, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(asset, interval, true, baseTime.AddDays(21)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddDays(21), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 3
            }));
        }
예제 #16
0
        public void WriteRead30Minutes()
        {
            var      interval = TimeInterval.Min30;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            var      repo     = new CandleHistoryRepository(storage);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 2 * 24 * 3) // 3 days
                            select new FeedCandle()
            {
                DateTime = baseTime.AddMinutes(30 * i), Open = i, Close = i, High = i, Low = i
            };

            repo.InsertOrMergeAsync(candlesIn, PriceType.Mid, interval).Wait();

            // Select for 1 hour
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Mid, interval,
                                                                                      @from: baseTime.AddHours(1),
                                                                                      to: baseTime.AddHours(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(2, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), Open = 2, Close = 2, High = 2, Low = 2
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1).AddMinutes(30), Open = 3, Close = 3, High = 3, Low = 3
            }));

            // Select for 1 day
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Mid, interval,
                                                                                  @from: baseTime.AddDays(1),
                                                                                  to: baseTime.AddDays(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(2 * 24, queriedCandles.Count());

            // Read/write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), Open = 99, Close = 99, High = 99, Low = 99
            }, PriceType.Mid, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(PriceType.Mid, interval, baseTime.AddHours(1)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1), Open = 99, Close = 99, High = 99, Low = 2
            }));
        }
예제 #17
0
        public void WriteReadDays()
        {
            var      asset    = "EURUSD";
            var      interval = TimeInterval.Day;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 31 * 12 * 3) // > 3 years
                            select new FeedCandle()
            {
                DateTime = baseTime.AddDays(i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            new CandleHistoryRepository(storage).InsertOrMergeAsync(candlesIn, asset, interval).Wait();

            // Select for 1 month
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                      from: baseTime.AddMonths(1),
                                                                                      to: baseTime.AddMonths(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(30, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddMonths(1), IsBuy = true, Open = 31, Close = 31, High = 31, Low = 31
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddMonths(1).AddDays(29), IsBuy = true, Open = 60, Close = 60, High = 60, Low = 60
            }));

            // Select for 1 year
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                  from: baseTime.AddYears(1),
                                                                                  to: baseTime.AddYears(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(365, queriedCandles.Count());

            // Read/write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddMonths(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 99
            }, asset, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(asset, interval, true, baseTime.AddMonths(1)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddMonths(1), IsBuy = true, Open = 99, Close = 99, High = 99, Low = 31
            }));
        }
        public static List <LogEntity> ToTypedList(this LogToMemory log)
        {
            var headers = log.TableData.Headers.ToList();

            return(log.TableData.Data
                   .Select(i => new LogEntity()
            {
                DateTime = i[headers.IndexOf("Date Time")],
                Level = i[headers.IndexOf("Level")],
                Component = i[headers.IndexOf("Component")],
                Process = i[headers.IndexOf("Process")],
                Context = i[headers.IndexOf("Context")],
                Type = i[headers.IndexOf("Type")],
                Msg = i[headers.IndexOf("Msg")]
            })
                   .ToList());
        }
        public async Task StopCallInterruptsGetResponse()
        {
            // Setup

            var waitTime      = TimeSpan.FromMilliseconds(100);
            var controlTime   = TimeSpan.FromMilliseconds(300);
            var executionTime = TimeSpan.FromSeconds(10);
            var log           = new LogToMemory();

            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Returns <CancellationToken>(async token =>
            {
                await Task.Delay(executionTime, token);     // Emulate long connection
                return("");
            });
            var socket = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            var watch = new Stopwatch();

            watch.Start();

            socket.Start();
            await Task.Delay(waitTime); // wait connection

            socket.Stop();
            socket.Dispose();

            watch.Stop();

            // Check

            // Connection must be interrupted
            Assert.True(watch.Elapsed < controlTime);

            // 1 call Connect/Stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(1));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
예제 #20
0
        public void WriteReadMonths()
        {
            var      asset    = "EURUSD";
            var      interval = TimeInterval.Month;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            var      repo     = new CandleHistoryRepository(storage);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 12 * 3) // 3 years
                            select new FeedCandle()
            {
                DateTime = baseTime.AddMonths(i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            repo.InsertOrMergeAsync(candlesIn, asset, interval).Wait();

            // Select for 1 year
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                      from: baseTime.AddYears(1),
                                                                                      to: baseTime.AddYears(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(12, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddYears(1), IsBuy = true, Open = 12, Close = 12, High = 12, Low = 12
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddYears(1).AddMonths(11), IsBuy = true, Open = 23, Close = 23, High = 23, Low = 23
            }));

            // Select for 1 month
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, interval, true,
                                                                                  from: baseTime,
                                                                                  to: baseTime.AddMonths(1)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(1, queriedCandles.Count());
        }
예제 #21
0
        public void WriteReadMultipleIntervals()
        {
            var      asset    = "EURUSD";
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            var      repo     = new CandleHistoryRepository(storage);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesMinutes = from i in Enumerable.Range(0, 60 * 24 * 3) // 3 days
                                 select new FeedCandle()
            {
                DateTime = baseTime.AddMinutes(i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            var candlesHours = from i in Enumerable.Range(0, 24 * 31 * 3) // 3 months
                               select new FeedCandle()
            {
                DateTime = baseTime.AddHours(i), IsBuy = true, Open = i, Close = i, High = i, Low = i
            };

            repo.InsertOrMergeAsync(new Dictionary <TimeInterval, IEnumerable <IFeedCandle> >()
            {
                { TimeInterval.Minute, candlesMinutes },
                { TimeInterval.Hour, candlesHours }
            }, asset).Wait();

            // Select minutes for 1 day
            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, TimeInterval.Minute, true,
                                                                                      from: baseTime.AddDays(1),
                                                                                      to: baseTime.AddDays(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(60 * 24 * 1, queriedCandles.Count());

            // Select hours for 1 month
            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(asset, TimeInterval.Hour, true,
                                                                                  from: baseTime.AddMonths(1),
                                                                                  to: baseTime.AddMonths(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(24 * 30, queriedCandles.Count());
        }
        public async Task SimpleCycleExecutesCorrectly()
        {
            // Setup

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();
            var socket    = new WebSocketSubscriber(messenger.Object, log);

            // Execute

            socket.Start();
            await Task.Delay(TimeSpan.FromMilliseconds(100)); // wait cycle to perform

            socket.Stop();
            socket.Dispose();

            // Check

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
        public async Task SubscriberRestartsWhenNoMessagesReceived()
        {
            // Setup

            var heartbeat     = TimeSpan.FromSeconds(1);
            var waitTime      = TimeSpan.FromSeconds(1.5);
            var executionTime = TimeSpan.FromSeconds(2);

            var log       = new LogToMemory();
            var messenger = CreateDefaultMockMessenger();

            messenger
            .Setup(m => m.GetResponseAsync(It.IsAny <CancellationToken>()))
            .Returns <CancellationToken>(async token =>
            {
                await Task.Delay(executionTime, token); return("");    // Emulate no messages for a long time
            });

            var socket = new WebSocketSubscriber(messenger.Object, log, heartbeat);

            // Execute

            socket.Start();
            await Task.Delay(waitTime); // wait cycle and restart to perform

            socket.Stop();
            socket.Dispose();

            // Check

            // Heartbeat restart causes 2 times connect/stop
            messenger.Verify(m => m.ConnectAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));
            messenger.Verify(m => m.StopAsync(It.IsAny <CancellationToken>()), Times.Exactly(2));

            // Expecting no exceptions and no errors
            Assert.True(log.NoErrors());
        }
예제 #24
0
        public void WriteReadSeconds()
        {
            var      interval = TimeInterval.Sec;
            var      logger   = new LogToMemory();
            var      storage  = CreateStorage <CandleTableEntity>(logger);
            DateTime baseTime = new DateTime(2017, 03, 01, 0, 0, 0, DateTimeKind.Utc);

            var candlesIn = from i in Enumerable.Range(0, 3600 * 3) // 3 hours
                            select new FeedCandle()
            {
                DateTime = baseTime.AddSeconds(i), Open = i, Close = i, High = i, Low = i
            };

            new CandleHistoryRepository(storage).InsertOrMergeAsync(candlesIn, PriceType.Ask, interval).Wait();

            // Select for 1 minute

            var queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Ask, interval,
                                                                                      @from: baseTime.AddHours(1).AddMinutes(1),
                                                                                      to: baseTime.AddHours(1).AddMinutes(2)).Result;

            Assert.NotNull(queriedCandles);
            Assert.Equal(60, queriedCandles.Count());

            Assert.True(queriedCandles.First().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1).AddMinutes(1), Open = 3660, Close = 3660, High = 3660, Low = 3660
            }));
            Assert.True(queriedCandles.Last().IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddHours(1).AddMinutes(1).AddSeconds(59), Open = 3719, Close = 3719, High = 3719, Low = 3719
            }));

            // Select for 1 hour

            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Ask, interval,
                                                                                  @from: baseTime.AddHours(1),
                                                                                  to: baseTime.AddHours(2)).Result;
            Assert.NotNull(queriedCandles);
            Assert.Equal(3600, queriedCandles.Count());

            // Select for 2 hours

            queriedCandles = new CandleHistoryRepository(storage).GetCandlesAsync(PriceType.Ask, interval,
                                                                                  @from: baseTime,
                                                                                  to: baseTime.AddHours(2)).Result;
            Assert.NotNull(queriedCandles);
            Assert.Equal(7200, queriedCandles.Count());

            //  Read / write 1 candle
            new CandleHistoryRepository(storage).InsertOrMergeAsync(
                new FeedCandle()
            {
                DateTime = baseTime.AddMinutes(1), Open = 99, Close = 99, High = 99, Low = 99
            }, PriceType.Ask, interval).Wait();

            var candle = new CandleHistoryRepository(storage).GetCandleAsync(PriceType.Ask, interval, baseTime.AddMinutes(1)).Result;

            Assert.True(candle.IsEqual(
                            new FeedCandle()
            {
                DateTime = baseTime.AddMinutes(1), Open = 99, Close = 99, High = 99, Low = 60
            }));
        }
 public static bool NoErrors(this LogToMemory log)
 {
     return(log
            .ToTypedList()
            .All(e => e.Level == LogEntity.InfoLevel || e.Level == LogEntity.WarningLevel));
 }
 public static bool ContainsErrors(this LogToMemory log)
 {
     return(log
            .ToTypedList()
            .Any(e => e.Level == LogEntity.ErrorLevel));
 }