internal void CanSerializeAndDeserialize_AccountStateEvent()
        {
            // Arrange
            var accountEvent = new AccountStateEvent(
                new AccountId("FXCM", "D123456", "SIMULATED"),
                Currency.USD,
                Money.Create(100000, Currency.USD),
                Money.Create(100000, Currency.USD),
                Money.Zero(Currency.USD),
                Money.Zero(Currency.USD),
                Money.Zero(Currency.USD),
                0m,
                "N",
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = this.serializer.Serialize(accountEvent);
            var unpacked = (AccountStateEvent)this.serializer.Deserialize(packed);

            // Assert
            Assert.Equal("FXCM-D123456-SIMULATED", accountEvent.AccountId.Value);
            Assert.Equal(accountEvent, unpacked);
            this.Output.WriteLine(Convert.ToBase64String(packed));
        }
Beispiel #2
0
        internal void OnOrderFilledEvent_WithNoPosition_OpensPosition()
        {
            // Arrange
            var order      = new StubOrderBuilder().EntryOrder("O-123456").BuildMarketOrder();
            var traderId   = TraderId.FromString("TESTER-000");
            var accountId  = AccountId.FromString("NAUTILUS-000-SIMULATED");
            var positionId = new PositionId("P-123456");
            var strategyId = new StrategyId("SCALPER", "001");

            var submitOrder = new SubmitOrder(
                traderId,
                accountId,
                strategyId,
                positionId,
                order,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.engine.Endpoint.SendAsync(submitOrder).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderSubmittedEvent(order)).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderAcceptedEvent(order)).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderFilledEvent(order)).Wait();
            Task.Delay(100).Wait();  // Buffer to avoid intermittent tests

            // Assert
            Assert.Single(this.database.GetPositions());
        }
        internal void Build_WithAllParametersModified_ThenReturnsExpectedOrder()
        {
            // Arrange
            // Act
            var order = new StubOrderBuilder()
                        .WithSymbol(new Symbol("AUD/USD", new Venue("FXCM")))
                        .WithOrderId("O-678910")
                        .WithOrderSide(OrderSide.Sell)
                        .WithQuantity(Quantity.Create(100000))
                        .WithPrice(Price.Create(1.00000m, 5))
                        .WithTimeInForce(TimeInForce.GTD)
                        .WithExpireTime(StubZonedDateTime.UnixEpoch() + Period.FromMinutes(5).ToDuration())
                        .WithTimestamp(StubZonedDateTime.UnixEpoch() + Period.FromMinutes(1).ToDuration())
                        .BuildStopMarketOrder();

            // Assert
            Assert.Equal(new Symbol("AUD/USD", new Venue("FXCM")), order.Symbol);
            Assert.Equal("O-678910", order.Id.Value);
            Assert.Equal(OrderSide.Sell, order.OrderSide);
            Assert.Equal(OrderType.Stop, order.OrderType);
            Assert.Equal(Quantity.Create(100000), order.Quantity);
            Assert.Equal(Price.Create(1m, 5), order.Price);
            Assert.Equal(TimeInForce.GTD, order.TimeInForce);
            Assert.Equal(StubZonedDateTime.UnixEpoch() + Period.FromMinutes(5).ToDuration(), order.ExpireTime);
            Assert.Equal(StubZonedDateTime.UnixEpoch() + Period.FromMinutes(1).ToDuration(), order.Timestamp);
        }
        internal void CanSerializeAndDeserialize_SubmitBracketOrderCommands_WithNoTakeProfit()
        {
            // Arrange
            var entry        = new StubOrderBuilder().BuildMarketOrder();
            var stopLoss     = new StubOrderBuilder().BuildStopMarketOrder();
            var bracketOrder = new BracketOrder(entry, stopLoss);

            var command = new SubmitBracketOrder(
                new TraderId("TESTER", "000"),
                new AccountId("FXCM", "028999999", "SIMULATED"),
                new StrategyId("EMACross", "001"),
                new PositionId("P-123456"),
                bracketOrder,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = this.serializer.Serialize(command);
            var unpacked = (SubmitBracketOrder)this.serializer.Deserialize(packed);

            // Assert
            Assert.Equal(command, unpacked);
            Assert.Equal(bracketOrder, unpacked.BracketOrder);
            this.Output.WriteLine(Convert.ToBase64String(packed));
            this.Output.WriteLine(Encoding.UTF8.GetString(packed));
        }
        internal void CanSerializeAndDeserialize_Disconnected()
        {
            // Arrange
            var correlationId = Guid.NewGuid();

            var response = new Disconnected(
                "Ok",
                new ServerId("NautilusData.TickProvider"),
                SessionId.Create(new ClientId("Trader-001"), StubZonedDateTime.UnixEpoch(), "None"),
                correlationId,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = this.serializer.Serialize(response);
            var unpacked = (Disconnected)this.serializer.Deserialize(packed);

            // Assert
            Assert.Equal(response, unpacked);
            Assert.Equal(correlationId, unpacked.CorrelationId);
            Assert.Equal("NautilusData.TickProvider", unpacked.ServerId.Value);
            Assert.Equal("Trader-001-e5db3dad8222a27e5d2991d11ad65f0f74668a4cfb629e97aa6920a73a012f87", unpacked.SessionId.Value);
            this.Output.WriteLine(Convert.ToBase64String(packed));
            this.Output.WriteLine(Encoding.UTF8.GetString(packed));
        }
Beispiel #6
0
        internal void OnSubmitOrderCommand_WhenCommandValid_OperatesDatabaseAndSendsToGateway()
        {
            // Arrange
            var order      = new StubOrderBuilder().EntryOrder("O-123456").BuildMarketOrder();
            var traderId   = TraderId.FromString("TESTER-000");
            var accountId  = AccountId.FromString("NAUTILUS-000-SIMULATED");
            var positionId = new PositionId("P-123456");
            var strategyId = new StrategyId("SCALPER", "001");

            var command = new SubmitOrder(
                traderId,
                accountId,
                strategyId,
                positionId,
                order,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.engine.Endpoint.SendAsync(command).Wait();
            Task.Delay(100).Wait();  // Buffer to avoid intermittent tests

            // Assert
            Assert.Null(this.engine.UnhandledMessages.FirstOrDefault());
            Assert.Equal(2, this.engine.ProcessedCount);
            Assert.Equal(1, this.engine.CommandCount);
            Assert.Single(this.tradingGateway.CalledMethods);
            Assert.Single(this.tradingGateway.ReceivedObjects);
            Assert.Equal("SubmitOrder", this.tradingGateway.CalledMethods[0]);
            Assert.Equal(order, this.tradingGateway.ReceivedObjects[0]);
        }
        internal void CanSerializeAndDeserialize_OrderWorkingWithExpireTimeEvents()
        {
            // Arrange
            var order = new StubOrderBuilder()
                        .WithTimeInForce(TimeInForce.GTD)
                        .WithExpireTime(StubZonedDateTime.UnixEpoch() + Duration.FromMinutes(1))
                        .BuildStopMarketOrder();

            var working = new OrderWorking(
                AccountId.FromString("FXCM-02851908-DEMO"),
                order.Id,
                new OrderIdBroker("B" + order.Id.Value),
                order.Symbol,
                order.OrderSide,
                order.OrderType,
                order.Quantity,
                order.Price,
                order.TimeInForce,
                order.ExpireTime,
                StubZonedDateTime.UnixEpoch(),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = this.serializer.Serialize(working);
            var unpacked = (OrderWorking)this.serializer.Deserialize(packed);

            // Assert
            Assert.Equal(working, unpacked);
            this.Output.WriteLine(Convert.ToBase64String(packed));
        }
Beispiel #8
0
        internal void Ingest_MultipleTicksDifferentSymbols_CorrectlyAddsTicksToRepository()
        {
            // Arrange
            var audusd = StubInstrumentProvider.AUDUSD();
            var eurusd = StubInstrumentProvider.EURUSD();

            this.repository.Update(audusd);
            this.repository.Update(eurusd);

            var tick1 = StubQuoteTickProvider.Create(audusd.Symbol);
            var tick2 = StubQuoteTickProvider.Create(audusd.Symbol, StubZonedDateTime.UnixEpoch() + Duration.FromDays(1));
            var tick3 = StubQuoteTickProvider.Create(audusd.Symbol, StubZonedDateTime.UnixEpoch() + Duration.FromDays(2));
            var tick4 = StubQuoteTickProvider.Create(eurusd.Symbol, StubZonedDateTime.UnixEpoch());
            var tick5 = StubQuoteTickProvider.Create(eurusd.Symbol, StubZonedDateTime.UnixEpoch() + Duration.FromDays(1));

            // Act
            this.repository.Ingest(tick1);
            this.repository.Ingest(tick2);
            this.repository.Ingest(tick3);
            this.repository.Ingest(tick4);
            this.repository.Ingest(tick5);

            // Assert
            // TODO: System.InvalidCastException : Specified cast is not valid. (inside StackExchange.Redis)
            // Assert.Equal(3, this.repository.TicksCount(audusd.Symbol));
            // Assert.Equal(2, this.repository.TicksCount(eurusd.Symbol));
        }
Beispiel #9
0
        internal void GivenUnaddressedEnvelope_WhenSubscriberSubscribedToSpecificType_PublishesToSubscriber()
        {
            // Arrange
            var subscribe = new Subscribe <Type>(
                typeof(MarketOpened),
                this.receiver.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var message = new MarketOpened(
                new Symbol("AUD/USD", new Venue("FXCM")),
                StubZonedDateTime.UnixEpoch(),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var envelope = new Envelope <MarketOpened>(
                message,
                null,
                ComponentAddress.DataService,
                StubZonedDateTime.UnixEpoch());

            this.messageBus.Endpoint.SendAsync(subscribe).Wait();

            // Act
            this.messageBus.Endpoint.SendAsync(envelope).Wait();

            Task.Delay(TestAssertionsTaskDelay).Wait(); // Allow sending to complete for assertions

            // Assert
            Assert.Contains(envelope, this.receiver.Messages);
        }
Beispiel #10
0
        internal void CanSerializeAndDeserialize_DataRequests()
        {
            // Arrange
            var serializer = new MsgPackRequestSerializer();

            var symbol   = new Symbol("AUD/USD", new Venue("FXCM"));
            var dateTime = StubZonedDateTime.UnixEpoch();
            var query    = new Dictionary <string, string>
            {
                { "DataType", "Tick[]" },
                { "Symbol", symbol.ToString() },
                { "FromDateTime", dateTime.ToIso8601String() },
                { "ToDateTime", dateTime.ToIso8601String() },
            };

            var request = new DataRequest(
                query,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = serializer.Serialize(request);
            var unpacked = (DataRequest)serializer.Deserialize(packed);

            // Assert
            Assert.Equal(request, unpacked);
            Assert.Equal("Tick[]", unpacked.Query["DataType"]);
            Assert.Equal(symbol.ToString(), unpacked.Query["Symbol"]);
            Assert.Equal(dateTime.ToIso8601String(), unpacked.Query["FromDateTime"]);
            Assert.Equal(dateTime.ToIso8601String(), unpacked.Query["ToDateTime"]);
            this.Output.WriteLine(Convert.ToBase64String(packed));
            this.Output.WriteLine(Encoding.UTF8.GetString(packed));
        }
Beispiel #11
0
        internal void GivenMultipleSubscribeAndUnsubscribe_HandlesCorrectly()
        {
            // Arrange
            var receiver2 = new MockComponent(this.container, "2");

            var subscribe1 = new Subscribe <Type>(
                typeof(Tick),
                this.receiver.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var subscribe2 = new Subscribe <Type>(
                typeof(Tick),
                receiver2.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var unsubscribe = new Unsubscribe <Type>(
                typeof(Tick),
                receiver2.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.dataBus.Endpoint.SendAsync(subscribe1).Wait();
            this.dataBus.Endpoint.SendAsync(subscribe2).Wait();
            this.dataBus.Endpoint.SendAsync(unsubscribe).Wait();
            this.dataBus.Stop().Wait();

            // Assert
            Assert.Equal(1, this.dataBus.Subscriptions.Count);
        }
        internal void CanSerializeAndDeserialize_InstrumentResponses()
        {
            // Arrange
            var dataSerializer = new InstrumentSerializer();
            var instrument     = StubInstrumentProvider.AUDUSD();
            var correlationId  = Guid.NewGuid();

            Instrument[] instruments           = { instrument };
            var          serializedInstruments = dataSerializer.Serialize(instruments);

            var metadata = new Dictionary <string, string> {
                { "Symbol", instrument.Symbol.ToString() }
            };
            var data = dataSerializer.SerializeBlob(serializedInstruments, metadata);

            var response = new DataResponse(
                data,
                typeof(Instrument[]).Name,
                dataSerializer.BlobEncoding,
                correlationId,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var serializedResponse   = this.serializer.Serialize(response);
            var deserializedResponse = (DataResponse)this.serializer.Deserialize(serializedResponse);
            var deserializedData     = dataSerializer.DeserializeBlob(deserializedResponse.Data);

            // Assert
            Assert.Equal(response, deserializedResponse);
            Assert.Equal(instrument, deserializedData[0]);
            Assert.Equal(correlationId, deserializedResponse.CorrelationId);
            this.Output.WriteLine(Convert.ToBase64String(serializedResponse));
            this.Output.WriteLine(Encoding.UTF8.GetString(serializedResponse));
        }
        internal void GivenInstrumentRequest_WithInstrument_ReturnsValidInstrumentResponse()
        {
            // Arrange
            var provider = new InstrumentProvider(
                this.container,
                this.messagingAdapter,
                this.repository,
                this.dataSerializer);

            provider.Start().Wait();

            var instrument = StubInstrumentProvider.AUDUSD();

            this.repository.Add(instrument);

            var query = new Dictionary <string, string>
            {
                { "DataType", "Instrument[]" },
                { "Symbol", instrument.Symbol.Value },
            };

            var request = new DataRequest(
                query,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var response = (DataResponse)provider.FindData(request);
            var data     = this.dataSerializer.DeserializeBlob(response.Data);

            // Assert
            Assert.Equal(typeof(DataResponse), response.Type);
            Assert.Equal(instrument, data[0]);
        }
Beispiel #14
0
        internal void OnOrderPartiallyFilledEvent_UpdatesOrderSendsToPublisher()
        {
            // Arrange
            var order      = new StubOrderBuilder().EntryOrder("O-123456").BuildMarketOrder();
            var traderId   = TraderId.FromString("TESTER-000");
            var accountId  = AccountId.FromString("NAUTILUS-000-SIMULATED");
            var positionId = new PositionId("P-123456");
            var strategyId = new StrategyId("SCALPER", "001");

            var submitOrder = new SubmitOrder(
                traderId,
                accountId,
                strategyId,
                positionId,
                order,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.engine.Endpoint.SendAsync(submitOrder).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderAcceptedEvent(order)).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderPartiallyFilledEvent(
                                               order,
                                               Quantity.Create(50000),
                                               Quantity.Create(50000))).Wait();
            Task.Delay(100).Wait();  // Buffer to avoid intermittent tests

            // Assert
            Assert.Null(this.engine.UnhandledMessages.FirstOrDefault());
            Assert.Equal(4, this.engine.ProcessedCount);
            Assert.Equal(1, this.engine.CommandCount);
            Assert.Equal(2, this.engine.EventCount);
            Assert.Equal(3, this.receiver.Messages.Count);
            Assert.Equal(OrderState.PartiallyFilled, order.State);
        }
        internal void CanSerializeAndDeserialize_OrderFilledEvents()
        {
            // Arrange
            var order = new StubOrderBuilder()
                        .WithQuantity(Quantity.Create(100000))
                        .BuildStopLimitOrder();

            var filled = new OrderFilled(
                AccountId.FromString("FXCM-02851908-DEMO"),
                order.Id,
                new ExecutionId("E123456"),
                new PositionIdBroker("P123456"),
                order.Symbol,
                order.OrderSide,
                order.Quantity,
                Price.Create(2m, 1),
                Currency.USD,
                StubZonedDateTime.UnixEpoch(),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var packed   = this.serializer.Serialize(filled);
            var unpacked = (OrderFilled)this.serializer.Deserialize(packed);

            // Assert
            Assert.Equal(filled, unpacked);
            this.Output.WriteLine(Convert.ToBase64String(packed));
        }
        internal void GivenInstrumentsRequest_WithNoInstruments_ReturnsQueryFailedMessage()
        {
            // Arrange
            var provider = new InstrumentProvider(
                this.container,
                this.messagingAdapter,
                this.repository,
                this.dataSerializer);

            provider.Start().Wait();

            var query = new Dictionary <string, string>
            {
                { "DataType", "Instrument[]" },
                { "Venue", "FXCM" },
            };

            var request = new DataRequest(
                query,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var response = (QueryFailure)provider.FindData(request);

            // Assert
            Assert.Equal(typeof(QueryFailure), response.Type);
        }
Beispiel #17
0
        internal void OnModifyOrderCommand_WhenNoOrderExists_DoesNotSendToGateway()
        {
            // Arrange
            var order     = new StubOrderBuilder().EntryOrder("O-123456").BuildMarketOrder();
            var traderId  = TraderId.FromString("TESTER-000");
            var accountId = AccountId.FromString("NAUTILUS-000-SIMULATED");

            var modify = new ModifyOrder(
                traderId,
                accountId,
                order.Id,
                order.Quantity,
                Price.Create(1.00010m, 5),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.engine.Endpoint.SendAsync(modify);
            Task.Delay(100).Wait();  // Buffer to avoid intermittent tests

            // Assert
            Assert.Null(this.engine.UnhandledMessages.FirstOrDefault());
            Assert.Equal(2, this.engine.ProcessedCount);
            Assert.Equal(1, this.engine.CommandCount);
            Assert.Equal(0, this.engine.EventCount);
            Assert.Empty(this.tradingGateway.CalledMethods);
            Assert.Empty(this.tradingGateway.ReceivedObjects);
            Assert.Empty(this.receiver.Messages);
        }
        internal void LoadAccountsCache_WhenAccountInDatabase_CorrectlyCachesAccount()
        {
            // Arrange
            var account = StubAccountProvider.Create();

            this.database.UpdateAccount(account);

            var message = new AccountStateEvent(
                new AccountId("FXCM", "123456789", "SIMULATED"),
                Currency.AUD,
                Money.Create(150000m, Currency.AUD),
                Money.Create(150000m, Currency.AUD),
                Money.Zero(Currency.AUD),
                Money.Zero(Currency.AUD),
                Money.Zero(Currency.AUD),
                decimal.Zero,
                string.Empty,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            account.Apply(message);
            this.database.UpdateAccount(account);

            this.database.ClearCaches();

            // Act
            this.database.LoadAccountsCache();

            // Assert
            Assert.Equal(account.Id, this.database.GetAccountIds().FirstOrDefault());
        }
Beispiel #19
0
        internal void Equals_VariousValues_ReturnsExpectedResult(
            decimal price1,
            decimal price2,
            int millisecondsOffset,
            bool expected)
        {
            // Arrange
            var tick1 = new TradeTick(
                this.symbol,
                Price.Create(price1),
                Quantity.Create(10000),
                Maker.Buyer,
                new MatchId("123456789"),
                StubZonedDateTime.UnixEpoch());

            var tick2 = new TradeTick(
                this.symbol,
                Price.Create(price2),
                Quantity.Create(10000),
                Maker.Buyer,
                new MatchId("123456789"),
                StubZonedDateTime.UnixEpoch() + Duration.FromMilliseconds(millisecondsOffset));

            // Act
            var result1 = tick1.Equals(tick2);
            var result2 = tick1 == tick2;

            // Assert
            Assert.Equal(expected, result1);
            Assert.Equal(expected, result2);
        }
Beispiel #20
0
        internal void CreateStopMarketOrder_WithValidParameters_ReturnsExpectedObject()
        {
            // Arrange
            // Act
            var order = OrderFactory.StopMarket(
                new OrderId("O-123456"),
                new Symbol("SYMBOL", "LMAX"),
                OrderSide.Buy,
                Quantity.Create(10),
                Price.Create(2000m, 1),
                TimeInForce.GTD,
                StubZonedDateTime.UnixEpoch() + Period.FromMinutes(5).ToDuration(),
                StubZonedDateTime.UnixEpoch(),
                Guid.NewGuid());

            // Assert
            Assert.Equal(new Symbol("SYMBOL", "LMAX"), order.Symbol);
            Assert.Equal("O-123456", order.Id.Value);
            Assert.Equal(OrderSide.Buy, order.OrderSide);
            Assert.Equal(OrderType.Stop, order.OrderType);
            Assert.Equal(10, order.Quantity.Value);
            Assert.Equal(Price.Create(2000m, 1), order.Price);
            Assert.Null(order.AveragePrice);
            Assert.Null(order.Slippage);
            Assert.Equal(TimeInForce.GTD, order.TimeInForce);
            Assert.Equal(StubZonedDateTime.UnixEpoch() + Period.FromMinutes(5).ToDuration(), order.ExpireTime);
            Assert.Equal(StubZonedDateTime.UnixEpoch(), order.LastEvent.Timestamp);
            Assert.Equal(OrderState.Initialized, order.State);
        }
Beispiel #21
0
        internal void Equals_WithUnequalObject_ReturnsFalse()
        {
            // Arrange
            var bar1 = new Bar(
                Price.Create(0.80000m, 5),
                Price.Create(0.80010m, 5),
                Price.Create(0.79990m, 5),
                Price.Create(0.80001m, 5),
                Quantity.Create(1000000),
                StubZonedDateTime.UnixEpoch());

            var bar2 = new Bar(
                Price.Create(0.80000m, 5),
                Price.Create(0.80010m, 5),
                Price.Create(0.79990m, 5),
                Price.Create(0.80001m, 5),
                Quantity.Create(1000000),
                StubZonedDateTime.UnixEpoch() + Duration.FromMinutes(1));

            // Act
            var result1 = bar1.Equals(bar2);
            var result2 = bar1 == bar2;

            // Assert
            Assert.False(result1);
            Assert.False(result2);
        }
Beispiel #22
0
        internal void GivenBarDataRequest_WithNoBars_ReturnsQueryFailedMessage()
        {
            // Arrange
            var provider = new BarProvider(
                this.container,
                this.messagingAdapter,
                this.repository,
                this.barSerializer);

            provider.Start().Wait();

            var barType = StubBarType.AUDUSD_OneMinuteAsk();

            var query = new Dictionary <string, string>
            {
                { "DataType", "Bar[]" },
                { "Symbol", barType.Symbol.Value },
                { "Specification", barType.Specification.ToString() },
                { "FromDateTime", StubZonedDateTime.UnixEpoch().ToString() },
                { "ToDateTime", StubZonedDateTime.UnixEpoch().ToString() },
                { "Limit", "0" },
            };

            var request = new DataRequest(
                query,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var response = provider.FindData(request);

            // Assert
            Assert.Equal(typeof(QueryFailure), response.Type);
        }
Beispiel #23
0
        internal void UpdateAccount_WhenAccountExists_CorrectlyUpdatesAccount()
        {
            // Arrange
            var account = StubAccountProvider.Create();

            this.database.UpdateAccount(account);

            var message = new AccountStateEvent(
                new AccountId("FXCM", "123456789", "SIMULATED"),
                Currency.AUD,
                Money.Create(150000m, Currency.AUD),
                Money.Create(150000m, Currency.AUD),
                Money.Zero(Currency.AUD),
                Money.Zero(Currency.AUD),
                Money.Zero(Currency.AUD),
                decimal.Zero,
                string.Empty,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            account.Apply(message);

            // Act
            this.database.UpdateAccount(account);

            // Assert
            Assert.True(true); // Does not throw
        }
Beispiel #24
0
        internal void GivenTickDataRequest_WithNoTicks_ReturnsQueryFailedMessage()
        {
            // Arrange
            var provider = new TickProvider(
                this.container,
                this.messagingAdapter,
                this.repository,
                this.tickSerializer,
                new TradeTickSerializer());

            provider.Start().Wait();

            var symbol = new Symbol("AUD/USD", new Venue("FXCM"));

            var query = new Dictionary <string, string>
            {
                { "DataType", "Tick[]" },
                { "Symbol", symbol.Value },
                { "FromDateTime", StubZonedDateTime.UnixEpoch().ToIso8601String() },
                { "ToDateTime", StubZonedDateTime.UnixEpoch().ToIso8601String() },
                { "Limit", "0" },
            };

            var request = new DataRequest(
                query,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            var response = (QueryFailure)provider.FindData(request);

            // Assert
            Assert.Equal(typeof(QueryFailure), response.Type);
        }
Beispiel #25
0
        internal void GivenDisconnectMessage_WhenConnected_SendsDisconnectedToSender()
        {
            // Arrange
            var server = new MessageServerFacade(
                this.container,
                this.messagingAdapter,
                this.compressor,
                EncryptionSettings.None(),
                this.testRequestAddress,
                this.testResponseAddress);

            server.Start().Wait();

            var dealer = new TestDealer(
                this.container,
                this.headerSerializer,
                this.requestSerializer,
                this.responseSerializer,
                this.compressor,
                EncryptionSettings.None(),
                this.testRequestAddress,
                this.testResponseAddress,
                "001");

            dealer.Start().Wait();

            var connect = new Connect(
                dealer.ClientId,
                "None",
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            dealer.Send(connect);
            var response1 = (Connected)dealer.Receive();

            var disconnect = new Disconnect(
                dealer.ClientId,
                response1.SessionId,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            dealer.Send(disconnect);
            var response2 = (Disconnected)dealer.Receive();

            // Assert
            Assert.Equal(typeof(Connected), response1.Type);
            Assert.Equal(typeof(Disconnected), response2.Type);
            Assert.Equal(2, server.ReceivedCount);
            Assert.Equal(2, server.SentCount);
            Assert.Equal("TestDealer-001 connected to test-server session None", response1.Message);
            Assert.Equal("TestDealer-001 disconnected from test-server session None", response2.Message);

            // Tear Down
            dealer.Stop().Wait();
            server.Stop().Wait();
            dealer.Dispose();
            server.Dispose();
        }
Beispiel #26
0
        internal void GetHashCode_ReturnsExpectedInteger()
        {
            // Arrange
            var message = new TestMessage(Guid.NewGuid(), StubZonedDateTime.UnixEpoch());

            // Act
            // Assert
            Assert.IsType <int>(message.GetHashCode());
        }
Beispiel #27
0
        internal void GivenMultipleSubscribe_HandlesCorrectly()
        {
            // Arrange
            var receiver2 = new MockComponent(this.container, "2");

            var subscribe1 = new Subscribe <Type>(
                typeof(Event),
                this.receiver.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var subscribe2 = new Subscribe <Type>(
                typeof(Event),
                receiver2.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var subscribe3 = new Subscribe <Type>(
                typeof(MarketOpened),
                this.receiver.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var subscribe4 = new Subscribe <Type>(
                typeof(SessionConnected),
                this.receiver.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var subscribe5 = new Subscribe <Type>(
                typeof(SessionConnected),
                receiver2.Mailbox,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.messageBus.Endpoint.SendAsync(subscribe1).Wait();
            this.messageBus.Endpoint.SendAsync(subscribe2).Wait();
            this.messageBus.Endpoint.SendAsync(subscribe3).Wait();
            this.messageBus.Endpoint.SendAsync(subscribe4).Wait();
            this.messageBus.Endpoint.SendAsync(subscribe5).Wait();
            this.messageBus.Stop().Wait();
            this.receiver.Stop().Wait();
            receiver2.Stop().Wait();

            Task.Delay(TestAssertionsTaskDelay).Wait(); // Allow sending to complete for assertions

            // Assert
            Assert.Contains(typeof(Event), this.messageBus.Subscriptions);
            Assert.Contains(typeof(MarketOpened), this.messageBus.Subscriptions);
            Assert.Contains(typeof(SessionConnected), this.messageBus.Subscriptions);
            Assert.Equal(2, this.messageBus.Subscriptions[typeof(Event)].Count);
            Assert.Equal(1, this.messageBus.Subscriptions[typeof(MarketOpened)].Count);
            Assert.Equal(2, this.messageBus.Subscriptions[typeof(SessionConnected)].Count);
            Assert.Equal(1, this.messageBus.Subscriptions[typeof(MarketOpened)].Count);
            Assert.Equal(5, this.messageBus.SubscriptionCount);
        }
        internal void CanSerializeAndDeserialize_TickDataResponse()
        {
            // Arrange
            var dataSerializer = new QuoteTickSerializer();
            var datetimeFrom   = StubZonedDateTime.UnixEpoch() + Duration.FromMinutes(1);
            var datetimeTo     = datetimeFrom + Duration.FromMinutes(1);

            var symbol = new Symbol("AUD/USD", new Venue("FXCM"));

            var tick1 = new QuoteTick(
                symbol,
                Price.Create(1.00000m),
                Price.Create(1.00000m),
                Quantity.One(),
                Quantity.One(),
                datetimeFrom);

            var tick2 = new QuoteTick(
                symbol,
                Price.Create(1.00010m),
                Price.Create(1.00020m),
                Quantity.One(),
                Quantity.One(),
                datetimeTo);

            var ticks = new[] { tick1, tick2 };

            var correlationId = Guid.NewGuid();
            var id            = Guid.NewGuid();

            var metadata = new Dictionary <string, string> {
                { "Symbol", symbol.Value }
            };
            var serializedTicks = dataSerializer.Serialize(ticks);
            var data            = dataSerializer.SerializeBlob(serializedTicks, metadata);

            var response = new DataResponse(
                data,
                typeof(Tick[]).Name,
                dataSerializer.BlobEncoding,
                correlationId,
                id,
                StubZonedDateTime.UnixEpoch());

            // Act
            var serializedResponse   = this.serializer.Serialize(response);
            var deserializedResponse = (DataResponse)this.serializer.Deserialize(serializedResponse);
            var deserializedData     = dataSerializer.DeserializeBlob(deserializedResponse.Data);

            // Assert
            Assert.Equal(response, deserializedResponse);
            Assert.Equal(tick1, deserializedData[0]);
            Assert.Equal(tick2, deserializedData[1]);
            Assert.Equal(correlationId, deserializedResponse.CorrelationId);
            this.Output.WriteLine(Convert.ToBase64String(serializedResponse));
            this.Output.WriteLine(Encoding.UTF8.GetString(serializedResponse));
        }
Beispiel #29
0
        internal void MarketDataRequestMessage()
        {
            // Arrange
            // Act
            var message = MarketDataRequestFactory.Create("AUD/USD", 1, StubZonedDateTime.UnixEpoch());

            // Assert
            Assert.Equal("8=FIX.4.49=6735=V262=MD_0263=1264=1265=0267=2269=0269=1146=155=AUD/USD10=238", message.ToString());
        }
Beispiel #30
0
        internal void OnModifyOrderCommand_WhenOrderAlreadyBeingModified_DoesNotSendToGateway()
        {
            // Arrange
            var order      = new StubOrderBuilder().EntryOrder("O-123456").BuildStopMarketOrder();
            var traderId   = TraderId.FromString("TESTER-000");
            var accountId  = AccountId.FromString("NAUTILUS-000-SIMULATED");
            var positionId = new PositionId("P-123456");
            var strategyId = new StrategyId("SCALPER", "001");

            var submit = new SubmitOrder(
                traderId,
                accountId,
                strategyId,
                positionId,
                order,
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var modify1 = new ModifyOrder(
                traderId,
                accountId,
                order.Id,
                order.Quantity,
                Price.Create(1.00010m, 5),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            var modify2 = new ModifyOrder(
                traderId,
                accountId,
                order.Id,
                order.Quantity,
                Price.Create(1.00010m, 5),
                Guid.NewGuid(),
                StubZonedDateTime.UnixEpoch());

            // Act
            this.engine.Endpoint.SendAsync(submit).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderAcceptedEvent(order)).Wait();
            this.engine.Endpoint.SendAsync(StubEventMessageProvider.OrderWorkingEvent(order)).Wait();
            this.engine.Endpoint.SendAsync(modify1).Wait();
            this.engine.Endpoint.SendAsync(modify2).Wait();
            Task.Delay(100).Wait();  // Buffer to avoid intermittent tests

            // Assert
            Assert.Null(this.engine.UnhandledMessages.FirstOrDefault());
            Assert.Equal(6, this.engine.ProcessedCount);
            Assert.Equal(3, this.engine.CommandCount);
            Assert.Equal(2, this.engine.EventCount);
            Assert.Equal(2, this.tradingGateway.CalledMethods.Count);
            Assert.Equal(2, this.tradingGateway.ReceivedObjects.Count);
            Assert.Equal("SubmitOrder", this.tradingGateway.CalledMethods[0]);
            Assert.Equal("ModifyOrder", this.tradingGateway.CalledMethods[1]);
            Assert.Equal(3, this.receiver.Messages.Count);
        }