private Money?CalculateLimit(
            EquityInstrumentIntraDayTimeBar tick,
            OrderDirections buyOrSell,
            OrderTypes tradeOrderType)
        {
            if (tradeOrderType != OrderTypes.LIMIT)
            {
                return(null);
            }

            if (buyOrSell == OrderDirections.BUY)
            {
                var price         = (decimal)Normal.Sample((double)tick.SpreadTimeBar.Bid.Value, this._limitStandardDeviation);
                var adjustedPrice = Math.Max(0, Math.Round(price, 2));

                return(new Money(adjustedPrice, tick.SpreadTimeBar.Bid.Currency));
            }

            if (buyOrSell == OrderDirections.SELL)
            {
                var price         = (decimal)Normal.Sample((double)tick.SpreadTimeBar.Ask.Value, this._limitStandardDeviation);
                var adjustedPrice = Math.Max(0, Math.Round(price, 2));

                return(new Money(adjustedPrice, tick.SpreadTimeBar.Ask.Currency));
            }

            return(null);
        }
        private IntradayPrices BuildIntraday(EquityInstrumentIntraDayTimeBar tick, decimal newBuy, string currency)
        {
            if (tick.DailySummaryTimeBar.IntradayPrices?.High == null ||
                tick.DailySummaryTimeBar.IntradayPrices?.Low == null)
            {
                return(new IntradayPrices(
                           new Money(newBuy, currency),
                           new Money(newBuy, currency),
                           new Money(newBuy, currency),
                           new Money(newBuy, currency)));
            }

            var adjustedHigh = tick.DailySummaryTimeBar.IntradayPrices.High.Value.Value < newBuy
                                   ? new Money(newBuy, tick.DailySummaryTimeBar.IntradayPrices.High.Value.Currency)
                                   : tick.DailySummaryTimeBar.IntradayPrices.High.Value;

            var adjustedLow = tick.DailySummaryTimeBar.IntradayPrices.Low.Value.Value < newBuy
                                  ? new Money(newBuy, tick.DailySummaryTimeBar.IntradayPrices.High.Value.Currency)
                                  : tick.DailySummaryTimeBar.IntradayPrices.Low.Value;

            var newIntraday = new IntradayPrices(
                tick.DailySummaryTimeBar.IntradayPrices.Open,
                tick.DailySummaryTimeBar.IntradayPrices.Close,
                adjustedHigh,
                adjustedLow);

            return(newIntraday);
        }
示例#3
0
        private SpreadTimeBar AdjustedSpread(
            EquityInstrumentIntraDayTimeBar tick,
            EquityInstrumentIntraDayTimeBar precedingTick)
        {
            switch (this._plan.EquityInstructions.PriceManipulation)
            {
            case PriceManipulation.Consistent:
                return(precedingTick.SpreadTimeBar);

            case PriceManipulation.Random:
                return(tick.SpreadTimeBar);

            case PriceManipulation.Increase:
                return(this.AdjustSpreadCalculation(
                           this._plan.EquityInstructions.PriceTickDelta.GetValueOrDefault(0) + 1,
                           precedingTick,
                           tick));

            case PriceManipulation.Decrease:
                return(this.AdjustSpreadCalculation(
                           1 - this._plan.EquityInstructions.PriceTickDelta.GetValueOrDefault(0),
                           precedingTick,
                           tick));
            }

            return(tick.SpreadTimeBar);
        }
示例#4
0
        /// <summary>
        /// The build description.
        /// </summary>
        /// <param name="mostRecentTrade">
        /// The most recent trade.
        /// </param>
        /// <param name="priceMovement">
        /// The price movement.
        /// </param>
        /// <param name="startTick">
        /// The start tick.
        /// </param>
        /// <param name="endTick">
        /// The end tick.
        /// </param>
        /// <returns>
        /// The <see cref="RuleBreachDescription"/>.
        /// </returns>
        private RuleBreachDescription BuildDescription(
            Order mostRecentTrade,
            decimal priceMovement,
            EquityInstrumentIntraDayTimeBar startTick,
            EquityInstrumentIntraDayTimeBar endTick)
        {
            switch (mostRecentTrade.OrderDirection)
            {
            case OrderDirections.BUY:
            case OrderDirections.COVER:
                return(priceMovement < 0
                        ? new RuleBreachDescription {
                    RuleBreached = true, Description = $" Prices in {mostRecentTrade.Instrument.Name} moved from ({endTick.SpreadTimeBar.Price.Currency}) {endTick.SpreadTimeBar.Price.Value} to ({startTick.SpreadTimeBar.Price.Currency}) {startTick.SpreadTimeBar.Price.Value} for a net change of {startTick.SpreadTimeBar.Price.Currency} {priceMovement} in line with the layering price pressure influence."
                }
                        : RuleBreachDescription.False());

            case OrderDirections.SELL:
            case OrderDirections.SHORT:
                return(priceMovement > 0
                        ? new RuleBreachDescription {
                    RuleBreached = true, Description = $" Prices in {mostRecentTrade.Instrument.Name} moved from ({endTick.SpreadTimeBar.Price.Currency}) {endTick.SpreadTimeBar.Price.Value} to ({startTick.SpreadTimeBar.Price.Currency}) {startTick.SpreadTimeBar.Price.Value} for a net change of {startTick.SpreadTimeBar.Price.Currency} {priceMovement} in line with the layering price pressure influence."
                } : RuleBreachDescription.False());

            default:
                this.logger.LogError($"Layering rule is not taking into account a new order position value (handles buy/sell) {mostRecentTrade.OrderDirection} (Arg Out of Range)");
                this.ruleContext.EventException($"Layering rule is not taking into account a new order position value (handles buy/sell) {mostRecentTrade.OrderDirection} (Arg Out of Range)");
                return(RuleBreachDescription.False());
            }
        }
示例#5
0
        private Order[] SetCancellationOrder(
            EquityInstrumentIntraDayTimeBar cancellationSecurity,
            int cancellationOrderTotal,
            int cancellationOrderTactic,
            Order[] orders)
        {
            switch (cancellationOrderTactic)
            {
                case 0:
                    // cannot be hit due to discrete uniform spread as we're not currently coding for detecting it on the surveillance service
                    orders = this.SingularCancelledOrder(cancellationSecurity, this._lastFrame.Exchange);
                    break;
                case 1:
                    orders = this.CancellationOrdersByValue(cancellationSecurity, cancellationOrderTotal);
                    break;
                case 2:
                    orders = this.CancellationOrdersByRatio(cancellationSecurity, cancellationOrderTotal);
                    break;
                case 3:
                    orders = this.CancellationOrdersByPercentOfVolume(cancellationSecurity, cancellationOrderTotal);
                    break;
            }

            return orders;
        }
示例#6
0
        private Order[] CancellationOrdersByValue(EquityInstrumentIntraDayTimeBar security, int totalOrders)
        {
            if (totalOrders == 0 || security == null) return new Order[0];

            var ordersToCancel = DiscreteUniform.Sample(1, totalOrders);
            var ordersToFulfill = totalOrders - ordersToCancel;

            // ReSharper disable RedundantCast
            var minimumPerOrderValue =
                (int)((decimal)this._valueOfCancelledTradeThreshold * (decimal)(1m / ordersToCancel) + 1);

            // ReSharper restore RedundantCast
            var orders = new List<Order>();

            for (var x = 0; x < ordersToCancel; x++)
                orders.Add(
                    this.OrderForValue(
                        OrderStatus.Cancelled,
                        minimumPerOrderValue,
                        security,
                        this._lastFrame.Exchange));

            for (var x = 0; x < ordersToFulfill; x++)
            {
                var fulfilledOrderValue = DiscreteUniform.Sample(0, minimumPerOrderValue * 3);
                orders.Add(
                    this.OrderForValue(OrderStatus.Filled, fulfilledOrderValue, security, this._lastFrame.Exchange));
            }

            return orders.ToArray();
        }
        private Order[] SpoofedOrder(
            EquityInstrumentIntraDayTimeBar security,
            int remainingSpoofedOrders,
            int totalSpoofedOrders)
        {
            if (security == null || remainingSpoofedOrders <= 0)
            {
                return(new Order[0]);
            }

            var priceOffset     = (100 + remainingSpoofedOrders) / 100m;
            var limitPriceValue = security.SpreadTimeBar.Bid.Value * priceOffset;
            var limitPrice      = new Money(limitPriceValue, security.SpreadTimeBar.Bid.Currency);

            var individualTradeVolumeLimit = 100 / totalSpoofedOrders;
            var volumeTarget = (100 + DiscreteUniform.Sample(0, individualTradeVolumeLimit)) / 100m;
            var volume       = (int)(security.SpreadTimeBar.Volume.Traded * volumeTarget);

            var statusChangedOn = DateTime.UtcNow.AddMinutes(-10 + remainingSpoofedOrders);
            var tradePlacedOn   = statusChangedOn;

            var spoofedTrade = new Order(
                security.Security,
                security.Market,
                null,
                Guid.NewGuid().ToString(),
                DateTime.UtcNow,
                "order-v1",
                "order-v1",
                "order-group-1",
                tradePlacedOn,
                tradePlacedOn,
                null,
                null,
                statusChangedOn,
                null,
                OrderTypes.LIMIT,
                OrderDirections.BUY,
                security.SpreadTimeBar.Price.Currency,
                security.SpreadTimeBar.Price.Currency,
                OrderCleanDirty.NONE,
                null,
                limitPrice,
                limitPrice,
                volume,
                volume,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                OptionEuropeanAmerican.NONE,
                new DealerOrder[0]);

            return(new[] { spoofedTrade }
                   .Concat(this.SpoofedOrder(security, remainingSpoofedOrders - 1, totalSpoofedOrders)).ToArray());
        }
        private int CalculateVolume(EquityInstrumentIntraDayTimeBar tick)
        {
            var upperLimit    = Math.Max(tick.SpreadTimeBar.Volume.Traded, 1);
            var tradingVolume = (int)Math.Sqrt(upperLimit);
            var volume        = DiscreteUniform.Sample(1, tradingVolume);

            return(volume);
        }
        private Volume CalculateNewVolume(EquityInstrumentIntraDayTimeBar tick)
        {
            var newVolumeSample      = (int)Normal.Sample(tick.SpreadTimeBar.Volume.Traded, this._tradingStandardDeviation);
            var newVolumeSampleFloor = Math.Max(0, newVolumeSample);
            var newVolume            = new Volume(newVolumeSampleFloor);

            return(newVolume);
        }
示例#10
0
        private Order[] SingularCancelledOrder(EquityInstrumentIntraDayTimeBar security, Market exchange)
        {
            var cancelledTradeOrderValue = DiscreteUniform.Sample(
                this._valueOfSingularCancelledTradeThreshold,
                10000000);
            var order = this.OrderForValue(OrderStatus.Cancelled, cancelledTradeOrderValue, security, exchange);

            return new[] { order };
        }
        private Money CalculateExecutedPrice(EquityInstrumentIntraDayTimeBar tick)
        {
            if (tick.SpreadTimeBar.Price.Value >= 0.01m)
            {
                return(tick.SpreadTimeBar.Price);
            }

            return(new Money(0.01m, tick.SpreadTimeBar.Price.Currency));
        }
        private Order GenerateTrade(EquityInstrumentIntraDayTimeBar tick, EquityIntraDayTimeBarCollection exchFrame)
        {
            if (tick == null)
            {
                return(null);
            }

            var direction              = this.CalculateTradeDirection();
            var orderType              = this.CalculateTradeOrderType();
            var limit                  = this.CalculateLimit(tick, direction, orderType);
            var executedPrice          = this.CalculateExecutedPrice(tick);
            var volume                 = this.CalculateVolume(tick);
            var orderStatus            = this.CalculateOrderStatus();
            var orderStatusLastChanged = tick.TimeStamp.AddMilliseconds(300);
            var orderSubmittedOn       = tick.TimeStamp;
            var traderId               = this.GenerateClientFactorString();
            var dealerInstructions     = "Process Asap";
            var orderCurrency          = tick?.SpreadTimeBar.Price.Currency.Code ?? string.Empty;

            var cancelledDate = orderStatus == OrderStatus.Cancelled ? (DateTime?)orderSubmittedOn : null;
            var filledDate    = orderStatus == OrderStatus.Filled ? (DateTime?)orderSubmittedOn : null;

            return(new Order(
                       tick.Security,
                       tick.Market,
                       null,
                       $"order-{Guid.NewGuid()}",
                       DateTime.UtcNow,
                       string.Empty,
                       string.Empty,
                       Guid.NewGuid().ToString(),
                       orderSubmittedOn,
                       orderSubmittedOn,
                       null,
                       cancelledDate,
                       filledDate,
                       orderStatusLastChanged,
                       OrderTypes.MARKET,
                       direction,
                       new Currency(orderCurrency),
                       new Currency(orderCurrency),
                       OrderCleanDirty.CLEAN,
                       null,
                       limit,
                       executedPrice,
                       volume,
                       volume,
                       traderId,
                       traderId,
                       "Clearing-Bank",
                       dealerInstructions,
                       new OrderBroker(string.Empty, string.Empty, "Mr Broker", DateTime.Now, true),
                       null,
                       null,
                       OptionEuropeanAmerican.NONE,
                       new DealerOrder[0]));
        }
示例#13
0
 private DailySummaryTimeBar AdjustedDailies(EquityInstrumentIntraDayTimeBar tick)
 {
     return(new DailySummaryTimeBar(
                tick.DailySummaryTimeBar.MarketCap.Value.Value,
                tick.DailySummaryTimeBar.MarketCap.Value.Currency.Code,
                tick.DailySummaryTimeBar.IntradayPrices,
                tick.DailySummaryTimeBar.ListedSecurities,
                tick.DailySummaryTimeBar.DailyVolume,
                tick.TimeStamp));
 }
示例#14
0
        public void ToString_PrintsOutExpected_ExchangeAndSecurities()
        {
            var market   = new Market("1", "xlon", "london stock exchange", MarketTypes.DarkPool);
            var date     = DateTime.UtcNow;
            var timeBars = new EquityInstrumentIntraDayTimeBar[0];
            var coll     = new EquityIntraDayTimeBarCollection(market, date, timeBars);

            var result = coll.ToString();

            Assert.AreEqual("Exchange (xlon.london stock exchange) Securities(0)", result);
        }
示例#15
0
        public void Ctor_AssignsVariables_Correctly()
        {
            var market   = new Market("1", "xlon", "london stock exchange", MarketTypes.DarkPool);
            var date     = DateTime.UtcNow;
            var timeBars = new EquityInstrumentIntraDayTimeBar[0];

            var coll = new EquityIntraDayTimeBarCollection(market, date, timeBars);

            Assert.AreEqual(market, coll.Exchange);
            Assert.AreEqual(date, coll.Epoch);
            Assert.AreEqual(timeBars, coll.Securities);
        }
示例#16
0
        private EquityInstrumentIntraDayTimeBar AdjustToPlan(
            EquityInstrumentIntraDayTimeBar tick,
            EquityInstrumentIntraDayTimeBar precedingTick)
        {
            var adjustedSpread = this.AdjustedSpread(tick, precedingTick);

            return(new EquityInstrumentIntraDayTimeBar(
                       tick.Security,
                       adjustedSpread,
                       this.AdjustedDailies(tick),
                       tick.TimeStamp,
                       tick.Market));
        }
        private decimal CalculateNewBuyValue(EquityInstrumentIntraDayTimeBar tick)
        {
            var newBuy = (decimal)Normal.Sample((double)tick.SpreadTimeBar.Price.Value, this._pricingStandardDeviation);

            if (newBuy < 0.01m)
            {
                newBuy = 0.01m;
            }

            newBuy = Math.Round(newBuy, 2);

            return(newBuy);
        }
示例#18
0
        public void TickSecurity_UpdatesWithNewTickData_Printing100IterationWalk()
        {
            var strategy    = new MarkovEquityStrategy();
            var identifiers = new InstrumentIdentifiers(
                string.Empty,
                string.Empty,
                string.Empty,
                "MSFT",
                "MS12345",
                "MSF123456789",
                "MSFT",
                "MSF12341234",
                "MSFT",
                "MSFT",
                "MSFT",
                "MSFT");
            var security = new FinancialInstrument(
                InstrumentTypes.Equity,
                identifiers,
                "Microsoft",
                "CFI",
                "USD",
                "Microsoft Company");
            var spread = new SpreadTimeBar(
                new Money(66, "GBP"),
                new Money(65, "GBP"),
                new Money(65, "GBP"),
                new Volume(200000));

            var tick = new EquityInstrumentIntraDayTimeBar(
                security,
                spread,
                new DailySummaryTimeBar(1000, "USD", null, 1000, new Volume(200000), DateTime.UtcNow),
                DateTime.UtcNow,
                new Market("1", "NASDAQ", "NASDAQ", MarketTypes.STOCKEXCHANGE));

            var printableInitialSecurity = JsonConvert.SerializeObject(security);

            Console.WriteLine(printableInitialSecurity);

            for (var i = 0; i < 99; i++)
            {
                tick = strategy.AdvanceFrame(tick, DateTime.UtcNow, true);

                var printableGeneratedSecurity = JsonConvert.SerializeObject(security);
                Console.WriteLine(printableGeneratedSecurity);

                Assert.IsTrue(tick.SpreadTimeBar.Bid.Value >= tick.SpreadTimeBar.Ask.Value);
            }
        }
        private decimal CalculateNewSellValue(EquityInstrumentIntraDayTimeBar tick, decimal newBuy)
        {
            var newSellSample = (decimal)Normal.Sample(
                (double)tick.SpreadTimeBar.Price.Value,
                this._pricingStandardDeviation);

            var newSellLimit = Math.Min(newBuy, newSellSample);
            var newSellFloor = newBuy * (1 - this._maxSpread); // allow for a max of 5% spread
            var newSell      = newSellFloor > newSellLimit ? newSellFloor : newSellLimit;

            newSell = Math.Round(newSell, 2);

            return(newSell);
        }
示例#20
0
        private Order OrderForValue(
            OrderStatus status,
            decimal value,
            EquityInstrumentIntraDayTimeBar security,
            Market exchange)
        {
            var volume = (int)(value / security.SpreadTimeBar.Ask.Value + 1);
            var orderPosition = (OrderDirections)DiscreteUniform.Sample(0, 3);

            var cancelledDate = status == OrderStatus.Cancelled ? (DateTime?)DateTime.UtcNow : null;
            var filledDate = status == OrderStatus.Filled ? (DateTime?)DateTime.UtcNow : null;

            var order = new Order(
                security.Security,
                exchange,
                null,
                Guid.NewGuid().ToString(),
                DateTime.UtcNow,
                "order-v1",
                "order-v1",
                "order-group-v1",
                DateTime.UtcNow,
                DateTime.UtcNow,
                null,
                null,
                cancelledDate,
                filledDate,
                OrderTypes.MARKET,
                orderPosition,
                security.SpreadTimeBar.Price.Currency,
                security.SpreadTimeBar.Price.Currency,
                OrderCleanDirty.NONE,
                null,
                security.SpreadTimeBar.Price,
                security.SpreadTimeBar.Price,
                volume,
                volume,
                "trader-1",
                "trader one",
                "clearing-agent",
                "dealing-instructions",
                new OrderBroker(string.Empty, string.Empty, "Mr Broker", DateTime.Now, true),
                null,
                null,
                OptionEuropeanAmerican.NONE,
                new DealerOrder[0]);

            return order;
        }
示例#21
0
        public EquityInstrumentIntraDayTimeBar AdvanceFrame(
            EquityInstrumentIntraDayTimeBar tick,
            DateTime advanceTick,
            bool walkIntraday)
        {
            if (!string.Equals(
                    tick.Security.Identifiers.Sedol,
                    this._plan.Sedol,
                    StringComparison.InvariantCultureIgnoreCase))
            {
                return(this._baseStrategy.AdvanceFrame(tick, advanceTick, walkIntraday));
            }

            var initialAdvancedFrame = this._baseStrategy.AdvanceFrame(tick, advanceTick, walkIntraday);

            return(this.AdjustToPlan(initialAdvancedFrame, tick));
        }
        private IUniverseEvent MapRowToIntradayMarketDataEvent(IntradayMarketDataParameters marketDataParam)
        {
            if (marketDataParam == null)
            {
                return(null);
            }

            if (string.IsNullOrWhiteSpace(marketDataParam.SecurityName) ||
                !this._securitySelection.Securities.ContainsKey(marketDataParam.SecurityName))
            {
                this._scenarioContext.Pending();
                return(null);
            }

            if (marketDataParam.Bid == null || marketDataParam.Ask == null || marketDataParam.Price == null)
            {
                this._scenarioContext.Pending();
                return(null);
            }

            var security = this._securitySelection.Securities[marketDataParam.SecurityName];
            var bid      = this.MapToMoney(marketDataParam.Bid, marketDataParam.Currency);
            var ask      = this.MapToMoney(marketDataParam.Ask, marketDataParam.Currency);
            var price    = this.MapToMoney(marketDataParam.Price, marketDataParam.Currency);
            var volume   = new Volume(marketDataParam.Volume.GetValueOrDefault(0));

            var intradayPrices = new SpreadTimeBar(bid.Value, ask.Value, price.Value, volume);

            var marketData = new EquityInstrumentIntraDayTimeBar(
                security.Instrument,
                intradayPrices,
                null,
                marketDataParam.Epoch,
                security.Market);

            var timeBarCollection = new EquityIntraDayTimeBarCollection(
                security.Market,
                marketDataParam.Epoch,
                new[] { marketData });
            var universeEvent = new UniverseEvent(
                UniverseStateEvent.EquityIntraDayTick,
                marketDataParam.Epoch,
                timeBarCollection);

            return(universeEvent);
        }
示例#23
0
        private SpreadTimeBar AdjustSpreadCalculation(
            decimal adjustmentFactor,
            EquityInstrumentIntraDayTimeBar precedingTick,
            EquityInstrumentIntraDayTimeBar tick)
        {
            var adjustedBid = new Money(
                precedingTick.SpreadTimeBar.Bid.Value * adjustmentFactor,
                precedingTick.SpreadTimeBar.Bid.Currency);
            var adjustedAsk = new Money(
                precedingTick.SpreadTimeBar.Ask.Value * adjustmentFactor,
                precedingTick.SpreadTimeBar.Ask.Currency);
            var adjustedPrice = new Money(
                precedingTick.SpreadTimeBar.Price.Value * adjustmentFactor,
                precedingTick.SpreadTimeBar.Price.Currency);

            return(new SpreadTimeBar(adjustedBid, adjustedAsk, adjustedPrice, tick.SpreadTimeBar.Volume));
        }
        private Order CounterTrade(EquityInstrumentIntraDayTimeBar security)
        {
            var volumeToTrade = (int)Math.Round(
                security.SpreadTimeBar.Volume.Traded * 0.01m,
                MidpointRounding.AwayFromZero);
            var statusChangedOn = DateTime.UtcNow;
            var tradePlacedOn   = statusChangedOn;

            var spoofedTrade = new Order(
                security.Security,
                this._lastFrame.Exchange,
                null,
                Guid.NewGuid().ToString(),
                DateTime.UtcNow,
                "order-v1",
                "order-v1",
                "order-group-1",
                tradePlacedOn,
                tradePlacedOn,
                null,
                null,
                null,
                statusChangedOn,
                OrderTypes.MARKET,
                OrderDirections.SELL,
                security.SpreadTimeBar.Price.Currency,
                security.SpreadTimeBar.Price.Currency,
                OrderCleanDirty.NONE,
                null,
                security.SpreadTimeBar.Price,
                security.SpreadTimeBar.Price,
                volumeToTrade,
                volumeToTrade,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                OptionEuropeanAmerican.NONE,
                new DealerOrder[0]);

            return(spoofedTrade);
        }
        public EquityInstrumentIntraDayTimeBar AdvanceFrame(
            EquityInstrumentIntraDayTimeBar tick,
            DateTime advanceTick,
            bool walkIntraday)
        {
            if (tick == null)
            {
                return(null);
            }

            var newBuy    = this.CalculateNewBuyValue(tick);
            var newSell   = this.CalculateNewSellValue(tick, newBuy);
            var newVolume = this.CalculateNewVolume(tick);

            var newSpread = new SpreadTimeBar(
                new Money(newBuy, tick.SpreadTimeBar.Bid.Currency),
                new Money(newSell, tick.SpreadTimeBar.Ask.Currency),
                new Money(newBuy, tick.SpreadTimeBar.Bid.Currency),
                newVolume);

            var newMarketCap =
                (tick.DailySummaryTimeBar.ListedSecurities ?? tick.DailySummaryTimeBar.DailyVolume.Traded) * newBuy;

            var newIntraday = walkIntraday
                                  ? this.BuildIntraday(tick, newBuy, tick.SpreadTimeBar.Bid.Currency.Code)
                                  : tick.DailySummaryTimeBar.IntradayPrices ?? this.BuildIntraday(
                tick,
                newBuy,
                tick.SpreadTimeBar.Bid.Currency.Code);

            var newDaily = new DailySummaryTimeBar(
                newMarketCap,
                "USD",
                newIntraday,
                tick.DailySummaryTimeBar.ListedSecurities,
                tick.DailySummaryTimeBar.DailyVolume,
                advanceTick);

            return(new EquityInstrumentIntraDayTimeBar(tick.Security, newSpread, newDaily, advanceTick, tick.Market));
        }
示例#26
0
        public void Ctor_AssignsVariables_Correctly()
        {
            var fi     = new FinancialInstrument();
            var prices = new IntradayPrices(null, null, null, null);
            var dates  = DateTime.UtcNow;

            var spreadTb = new SpreadTimeBar(
                new Money(100, "GBP"),
                new Money(100, "GBP"),
                new Money(100, "GBP"),
                new Volume(99));

            var dailyTb = new DailySummaryTimeBar(100, "USD", prices, 123, new Volume(123), dates);

            var market        = new Market("1", "XLON", "London Stock Exchange", MarketTypes.DealerBooks);
            var equityTimeBar = new EquityInstrumentIntraDayTimeBar(fi, spreadTb, dailyTb, dates, market);

            Assert.AreEqual(fi, equityTimeBar.Security);
            Assert.AreEqual(spreadTb, equityTimeBar.SpreadTimeBar);
            Assert.AreEqual(dailyTb, equityTimeBar.DailySummaryTimeBar);
            Assert.AreEqual(dates, equityTimeBar.TimeStamp);
            Assert.AreEqual(market, equityTimeBar.Market);
        }
示例#27
0
        private Order[] CancellationOrdersByPercentOfVolume(EquityInstrumentIntraDayTimeBar security, int totalOrders)
        {
            if (totalOrders == 0 || security == null) return new Order[0];

            var cancelledOrderPositionSize = 10000000;
            var ordersToCancel = 1;
            var ordersToFulfill = totalOrders - ordersToCancel;
            var minimumPerOrderValue =
                cancelledOrderPositionSize * this._cancellationOfPositionVolumeThresholdPercentage;
            var remainingOrderValue =
                cancelledOrderPositionSize * (1 - this._cancellationOfPositionVolumeThresholdPercentage);

            // ReSharper disable RedundantCast
            var remainingOrderValuePerOrder = (int)((decimal)remainingOrderValue * (decimal)(1m / ordersToFulfill) + 1);

            // ReSharper restore RedundantCast
            var orders = new List<Order>();

            for (var x = 0; x < ordersToCancel; x++)
                orders.Add(
                    this.OrderForValue(
                        OrderStatus.Cancelled,
                        minimumPerOrderValue,
                        security,
                        this._lastFrame.Exchange));

            for (var x = 0; x < ordersToFulfill; x++)
                orders.Add(
                    this.OrderForValue(
                        OrderStatus.Booked,
                        remainingOrderValuePerOrder,
                        security,
                        this._lastFrame.Exchange));

            return orders.ToArray();
        }
        public FinancialInstrumentTimeBarCsv Map(EquityInstrumentIntraDayTimeBar equityInstrumentIntraDayTimeBar)
        {
            if (equityInstrumentIntraDayTimeBar == null)
            {
                this.FailedMapTotal += 1;
                this._logger?.LogError(
                    "Failed to map security tick to financial instrument time bar csv due to being passed a null value");
                return(null);
            }

            var financialInstrumentTimeBarCsv = new FinancialInstrumentTimeBarCsv
            {
                Volume =
                    equityInstrumentIntraDayTimeBar.SpreadTimeBar.Volume.Traded
                    .ToString(),
                DailyVolume =
                    equityInstrumentIntraDayTimeBar.DailySummaryTimeBar
                    .DailyVolume.Traded.ToString(),
                Timestamp =
                    equityInstrumentIntraDayTimeBar.TimeStamp.ToString(
                        "yyyy-MM-ddTHH:mm:ss"),
                MarketCap =
                    equityInstrumentIntraDayTimeBar.DailySummaryTimeBar
                    .MarketCap?.ToString(),
                ListedSecurities =
                    equityInstrumentIntraDayTimeBar.DailySummaryTimeBar
                    .ListedSecurities?.ToString(),
                Currency = equityInstrumentIntraDayTimeBar.SpreadTimeBar.Price
                           .Currency.Code,

                // Spread
                Ask = equityInstrumentIntraDayTimeBar.SpreadTimeBar.Ask.Value
                      .ToString(),
                Bid = equityInstrumentIntraDayTimeBar.SpreadTimeBar.Bid.Value
                      .ToString(),
                Price = equityInstrumentIntraDayTimeBar.SpreadTimeBar.Price
                        .Value.ToString()
            };

            // Market
            if (equityInstrumentIntraDayTimeBar.Market != null)
            {
                financialInstrumentTimeBarCsv.MarketIdentifierCode =
                    equityInstrumentIntraDayTimeBar.Market.MarketIdentifierCode;
                financialInstrumentTimeBarCsv.MarketName = equityInstrumentIntraDayTimeBar.Market.Name;
            }

            // Intraday Prices
            if (equityInstrumentIntraDayTimeBar.DailySummaryTimeBar.IntradayPrices != null)
            {
                financialInstrumentTimeBarCsv.Open = equityInstrumentIntraDayTimeBar.DailySummaryTimeBar.IntradayPrices
                                                     .Open?.Value.ToString();
                financialInstrumentTimeBarCsv.Close = equityInstrumentIntraDayTimeBar.DailySummaryTimeBar.IntradayPrices
                                                      .Close?.Value.ToString();
                financialInstrumentTimeBarCsv.Low = equityInstrumentIntraDayTimeBar.DailySummaryTimeBar.IntradayPrices
                                                    .Low?.Value.ToString();
                financialInstrumentTimeBarCsv.High = equityInstrumentIntraDayTimeBar.DailySummaryTimeBar.IntradayPrices
                                                     .High?.Value.ToString();
            }

            // Security Identifiers
            if (equityInstrumentIntraDayTimeBar.Security != null)
            {
                // Security
                financialInstrumentTimeBarCsv.SecurityName     = equityInstrumentIntraDayTimeBar.Security.Name;
                financialInstrumentTimeBarCsv.Cfi              = equityInstrumentIntraDayTimeBar.Security.Cfi;
                financialInstrumentTimeBarCsv.IssuerIdentifier =
                    equityInstrumentIntraDayTimeBar.Security.IssuerIdentifier;

                // Security Identifiers
                financialInstrumentTimeBarCsv.SecurityClientIdentifier =
                    equityInstrumentIntraDayTimeBar.Security.Identifiers.ClientIdentifier;
                financialInstrumentTimeBarCsv.Sedol          = equityInstrumentIntraDayTimeBar.Security.Identifiers.Sedol;
                financialInstrumentTimeBarCsv.Isin           = equityInstrumentIntraDayTimeBar.Security.Identifiers.Isin;
                financialInstrumentTimeBarCsv.Figi           = equityInstrumentIntraDayTimeBar.Security.Identifiers.Figi;
                financialInstrumentTimeBarCsv.Cusip          = equityInstrumentIntraDayTimeBar.Security.Identifiers.Cusip;
                financialInstrumentTimeBarCsv.ExchangeSymbol =
                    equityInstrumentIntraDayTimeBar.Security.Identifiers.ExchangeSymbol;
                financialInstrumentTimeBarCsv.Lei             = equityInstrumentIntraDayTimeBar.Security.Identifiers.Lei;
                financialInstrumentTimeBarCsv.BloombergTicker =
                    equityInstrumentIntraDayTimeBar.Security.Identifiers.BloombergTicker;
            }

            return(financialInstrumentTimeBarCsv);
        }
 private EquityInstrumentIntraDayTimeBar TickSecurity(EquityInstrumentIntraDayTimeBar tick)
 {
     return(this._dataStrategy.AdvanceFrame(tick, DateTime.UtcNow, true));
 }
        public void Add_ExchangeFrame_InDateRange_GetMarkets_DoesNotCall()
        {
            var cache = new UniverseEquityIntraDayCache(
                TimeSpan.FromMinutes(15),
                this._requestRepository,
                this._logger);

            var securityIdentifiers = new InstrumentIdentifiers(
                string.Empty,
                "reddeer id",
                string.Empty,
                "client id",
                "1234567",
                "12345678912",
                "figi",
                "cusip",
                "test",
                "test lei",
                "ticker",
                "ric");

            var security = new FinancialInstrument(
                InstrumentTypes.Equity,
                securityIdentifiers,
                "Test Security",
                "CFI",
                "USD",
                "Issuer Identifier");

            var securityTick = new EquityInstrumentIntraDayTimeBar(
                security,
                new SpreadTimeBar(new Money(0, "gbp"), new Money(0, "gbp"), new Money(0, "gbp"), new Volume(1000)),
                new DailySummaryTimeBar(
                    1000,
                    "USD",
                    new IntradayPrices(null, null, null, null),
                    1000,
                    new Volume(2000),
                    DateTime.UtcNow),
                DateTime.UtcNow,
                new Market("1", "XLON", "London Stock Exchange", MarketTypes.STOCKEXCHANGE));

            var frame = new EquityIntraDayTimeBarCollection(
                new Market("1", "XLON", "London Stock Exchange", MarketTypes.STOCKEXCHANGE),
                DateTime.UtcNow,
                new[] { securityTick });

            var marketData = new MarketDataRequest(
                "XLON",
                "e",
                securityIdentifiers,
                DateTime.UtcNow.Subtract(TimeSpan.FromDays(1)),
                DateTime.UtcNow,
                "0",
                DataSource.AnyIntraday);

            cache.Add(frame);

            var result = cache.GetMarkets(marketData).Response;

            Assert.AreEqual(result.FirstOrDefault(), securityTick);
            A.CallTo(() => this._requestRepository.CreateDataRequest(marketData)).MustNotHaveHappened();
        }