Exemplo n.º 1
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);
        }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
0
        public void Create_ShouldReturnError_WhenAmountIsLowerOrEqualTo0(int amount)
        {
            var price = Price.Create("HKD", amount);

            price.IsSuccess.Should().BeFalse();
            price.Error.Should().Be(Errors.InvalidAmount);
        }
        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));
        }
Exemplo n.º 6
0
        public void PriceValueShouldBeNotLessThanZeroTest()
        {
            var price = Price.Create(-10.0M);

            price.Failure.Should().BeTrue();
            price.Error.Should().Be(nameof(Parameters.INVALID_VALUE_MONEY));
        }
Exemplo n.º 7
0
        internal void GetSlippage_SellOrderFilledVariousAveragePrices_ReturnsExpectedResult(decimal averagePrice, decimal expectedSlippage)
        {
            // Arrange
            var order = new StubOrderBuilder()
                        .WithOrderSide(OrderSide.Sell)
                        .WithPrice(Price.Create(1.20000m, 5))
                        .BuildStopMarketOrder();

            var event1 = StubEventMessageProvider.OrderSubmittedEvent(order);
            var event2 = StubEventMessageProvider.OrderAcceptedEvent(order);
            var event3 = StubEventMessageProvider.OrderWorkingEvent(order, order.Price);
            var event4 = StubEventMessageProvider.OrderFilledEvent(order, Price.Create(averagePrice, 5));

            order.Apply(event1);
            order.Apply(event2);
            order.Apply(event3);
            order.Apply(event4);

            // Act
            var result = order.Slippage;

            // Assert
            Assert.Equal(OrderState.Filled, order.State);
            Assert.Equal(expectedSlippage, result);
        }
Exemplo n.º 8
0
        public void Create_ShouldReturnError_WhenCurrencyIsNot3CharLong(string currency)
        {
            var price = Price.Create(currency, 10);

            price.IsSuccess.Should().BeFalse();
            price.Error.Should().Be(Errors.InvalidCurrency);
        }
        public void SameAs()
        {
            Price price1 = Price.Create(new decimal(10));
            Price price2 = Price.Create(new decimal(10));

            Assert.True(price1.SameAs(price2));
        }
Exemplo n.º 10
0
        public static OrderPartiallyFilled OrderPartiallyFilledEvent(
            Order order,
            Quantity filledQuantity,
            Quantity leavesQuantity,
            Price?averagePrice = null)
        {
            if (averagePrice is null)
            {
                averagePrice = Price.Create(1.00000m);
            }

            return(new OrderPartiallyFilled(
                       AccountId.FromString("FXCM-02851908-DEMO"),
                       order.Id,
                       new ExecutionId("None"),
                       new PositionIdBroker("None"),
                       order.Symbol,
                       order.OrderSide,
                       filledQuantity,
                       leavesQuantity,
                       averagePrice,
                       Currency.USD,
                       StubZonedDateTime.UnixEpoch() + Period.FromMinutes(1).ToDuration(),
                       Guid.NewGuid(),
                       StubZonedDateTime.UnixEpoch()));
        }
        public static Price CreatePrice(decimal net, decimal tax)
        {
            var netResult = Money.Create(net, SupportedCurrencies.USD());
            var taxResult = Money.Create(tax, SupportedCurrencies.USD());

            return(Price.Create(netResult.Value, taxResult.Value, MockObjectsBuilder.BuildSingleCurrencyPolicy(true)).Value);
        }
Exemplo n.º 12
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);
        }
        public static Price CreatePrice(decimal net, decimal tax, Currency currency)
        {
            var netResult = Money.Create(net, currency);
            var taxResult = Money.Create(tax, currency);

            return(Price.Create(netResult.Value, taxResult.Value, MockObjectsBuilder.BuildSingleCurrencyPolicy(true)).Value);
        }
Exemplo n.º 14
0
            private static Price GetPriceService(RequestContext context)
            {
                var pricingDataManager = new PricingDataServiceManager(context);
                var salesParameters    = pricingDataManager.GetPriceParameters();

                return(Price.Create(salesParameters));
            }
Exemplo n.º 15
0
 public Task <Result <Price> > GetPriceAsync(ExamId examId)
 {
     return(Task.FromResult(Price.Create(
                                net: Money.Create(100, SupportedCurrencies.USD()).Value,
                                tax: Money.Create(0, SupportedCurrencies.USD()).Value,
                                _singleCurrencyPolicy)));
 }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        public Price GetTotalPrice()
        {
            Price totalPrice = Price.Create(0);

            OrderItems.ToList().ForEach(x => totalPrice = Price.Add(totalPrice, x.GetTotalPrice()));

            return(totalPrice);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Returns a Price? extracted from the given unpacked dictionary.
        /// </summary>
        /// <param name="unpacked">The MessagePack object to extract from.</param>
        /// <returns>The extracted Price?.</returns>
        internal static Price?AsNullablePrice(byte[] unpacked)
        {
            var unpackedString = Decode(unpacked);

            return(unpackedString == None
                ? null
                : Price.Create(Parser.ToDecimal(unpackedString)));
        }
Exemplo n.º 19
0
        public void PriceValueOddTest(decimal value1, decimal value2, decimal expectedResult)
        {
            var priceOne = Price.Create(value1).Value;
            var priceTwo = Price.Create(value2).Value;
            var result   = priceOne - priceTwo;

            Assert.Equal(expectedResult, result.Money);
        }
Exemplo n.º 20
0
        public void Price_EqualPricesBasedOnDate_ReturnsTrue()
        {
            var date       = DateTime.Now.AddDays(1);
            var price      = Price.Create(date, 1);
            var otherPrice = Price.Create(date, 1);

            Assert.IsTrue(price.Equals(otherPrice));
        }
 public static ItemTestBuilder AnItem()
 {
     return(new ItemTestBuilder(Item.ItemBuilder.Item()
                                .WithName("Headphone")
                                .WithDescription("Just a simple headphone")
                                .WithAmountOfStock(50)
                                .WithPrice(Price.Create(new decimal(49.95)))));
 }
Exemplo n.º 22
0
        public void Price_ValidDate_CreatesPrice()
        {
            var date  = DateTime.Now.AddDays(1);
            var price = Price.Create(date, 1);

            Assert.IsNotNull(price);
            Assert.AreEqual(1, price.Value);
        }
Exemplo n.º 23
0
 public static Product Create(string name, decimal price, int pieces)
 {
     return(new Product
     {
         Name = name,
         Price = Price.Create(price),
         Pieces = pieces
     });
 }
Exemplo n.º 24
0
 public static OrderItemTestBuilder AnOrderItem()
 {
     return(new OrderItemTestBuilder(OrderItem.OrderItemBuilder.OrderItem()
                                     .WithItemId(Guid.NewGuid())
                                     .WithItemPrice(Price.Create(new decimal(49.95)))
                                     .WithOrderedAmount(10)
                                     .WithShippingDateBasedOnAvailableItemStock(15)
                                     ));
 }
Exemplo n.º 25
0
        public void GetShippingDate_givenItemWasNotInStock_thenReturnCurrentDatePlusSevenDays()
        {
            OrderItem orderItem = new OrderItem(OrderItem.OrderItemBuilder.OrderItem()
                                                .WithOrderedAmount(5)
                                                .WithItemPrice(Price.Create(50))
                                                .WithShippingDateBasedOnAvailableItemStock(4));

            Assert.Equal(DateTime.Now.AddDays(7).Date, orderItem.ShippingDate.Date);
        }
Exemplo n.º 26
0
        public void Price_NotEqualPrices_ReturnsTrue()
        {
            var date       = DateTime.Now.AddDays(1);
            var dateTwo    = DateTime.Now.AddDays(2);
            var price      = Price.Create(date, 1);
            var otherPrice = Price.Create(dateTwo, 1);

            Assert.IsFalse(price.Equals(otherPrice));
        }
Exemplo n.º 27
0
        public void SetPriceValue_ValidValue_UpdatesPrice()
        {
            var date  = DateTime.Now.AddDays(1);
            var price = Price.Create(date, 1);

            price.SetPriceValue(2);
            Assert.IsNotNull(price);
            Assert.AreEqual(2, price.Value);
        }
Exemplo n.º 28
0
        internal void Create_WhenGivenStringFormatting_ReturnsExpectedResult()
        {
            // Arrange
            // Act
            var result1 = Price.Create(1.0, 2);

            // Assert
            Assert.Equal("1.00", result1.ToString());
        }
Exemplo n.º 29
0
        public void ShouldReturnExpectedResult(decimal net, decimal tax, bool expected, string because)
        {
            var netValue = Money.Create(net, SupportedCurrencies.USD()).Value;
            var taxValue = Money.Create(tax, SupportedCurrencies.USD()).Value;

            var priceResult = Price.Create(netValue, taxValue, MockObjectsBuilder.BuildSingleCurrencyPolicy(true));

            priceResult.IsSuccess.Should().Be(expected, because);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Returns the instrument from the Redis database matching the given key.
        /// </summary>
        /// <param name="key">The instrument key to read.</param>
        /// <returns>The keys.</returns>
        public QueryResult <Instrument> Read(string key)
        {
            Debug.NotEmptyOrWhiteSpace(key, nameof(key));

            if (!this.redisDatabase.KeyExists(key))
            {
                return(QueryResult <Instrument> .Fail($"Cannot find {key}"));
            }

            var instrumentDict = this.redisDatabase.HashGetAll(key)
                                 .ToDictionary(
                hashEntry => hashEntry.Name.ToString(),
                hashEntry => hashEntry.Value.ToString());

            var securityType = instrumentDict[nameof(Instrument.SecurityType)].ToEnum <SecurityType>();

            if (securityType == SecurityType.Forex)
            {
                var forexCcy = new ForexInstrument(
                    Symbol.FromString(instrumentDict[nameof(Instrument.Symbol)]),
                    int.Parse(instrumentDict[nameof(Instrument.PricePrecision)]),
                    int.Parse(instrumentDict[nameof(Instrument.SizePrecision)]),
                    int.Parse(instrumentDict[nameof(Instrument.MinStopDistanceEntry)]),
                    int.Parse(instrumentDict[nameof(Instrument.MinLimitDistanceEntry)]),
                    int.Parse(instrumentDict[nameof(Instrument.MinStopDistance)]),
                    int.Parse(instrumentDict[nameof(Instrument.MinLimitDistance)]),
                    Price.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.TickSize)])),
                    Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.RoundLotSize)])),
                    Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.MinTradeSize)])),
                    Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.MaxTradeSize)])),
                    Parser.ToDecimal(instrumentDict[nameof(Instrument.RolloverInterestBuy)]),
                    Parser.ToDecimal(instrumentDict[nameof(Instrument.RolloverInterestSell)]),
                    instrumentDict[nameof(Instrument.Timestamp)].ToZonedDateTimeFromIso());

                return(QueryResult <Instrument> .Ok(forexCcy));
            }

            var instrument = new Instrument(
                Symbol.FromString(instrumentDict[nameof(Instrument.Symbol)]),
                instrumentDict[nameof(Instrument.QuoteCurrency)].ToEnum <Currency>(),
                securityType,
                int.Parse(instrumentDict[nameof(Instrument.PricePrecision)]),
                int.Parse(instrumentDict[nameof(Instrument.SizePrecision)]),
                int.Parse(instrumentDict[nameof(Instrument.MinStopDistanceEntry)]),
                int.Parse(instrumentDict[nameof(Instrument.MinLimitDistanceEntry)]),
                int.Parse(instrumentDict[nameof(Instrument.MinStopDistance)]),
                int.Parse(instrumentDict[nameof(Instrument.MinLimitDistance)]),
                Price.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.TickSize)])),
                Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.RoundLotSize)])),
                Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.MinTradeSize)])),
                Quantity.Create(Parser.ToDecimal(instrumentDict[nameof(Instrument.MaxTradeSize)])),
                Parser.ToDecimal(instrumentDict[nameof(Instrument.RolloverInterestBuy)]),
                Parser.ToDecimal(instrumentDict[nameof(Instrument.RolloverInterestSell)]),
                instrumentDict[nameof(Instrument.Timestamp)].ToZonedDateTimeFromIso());

            return(QueryResult <Instrument> .Ok(instrument));
        }