Exemplo n.º 1
0
        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns>A new value for this indicator</returns>
        protected override decimal ComputeNextValue(TradeBar input)
        {
            // Save the bar for summing
            Bars.Add(input);

            // check if it is not ready add a 0 to the RviWindow
            if (!Bars.IsReady)
            {
                RviWindow.Add(new IndicatorDataPoint(input.EndTime, 0.0m));
            }
            else
            {
                // Bars have been added, so Bars[0] is the current value of the input


                // Filter the Close - Open with a four-bar symetical FIR filter before the terms are summed.
                var v1 = ((Bars[0].Close - Bars[0].Open) + 2 * (Bars[1].Close - Bars[1].Open) +
                          2 * (Bars[2].Close - Bars[3].Open) + (Bars[3].Close - Bars[3].Open) / 6);
                value1.Add(new IndicatorDataPoint(input.EndTime, v1));

                // Filter the High - Low with a four-bar symetical FIR filter before the terms are summed.
                var v2 = ((Bars[0].High - Bars[0].Low) + 2 * (Bars[1].High - Bars[1].Low) +
                          2 * (Bars[2].High - Bars[3].Low) + (Bars[3].High - Bars[3].Low) / 6);
                value2.Add(new IndicatorDataPoint(input.EndTime, v2));

                // The numerator and denominator are summed independently
                decimal num   = value1.Sum(point => point.Value);
                decimal denom = value2.Sum(point => point.Value);

                try
                {
                    // The RVI is the ratio of the numerator to the denominator.  Since
                    //  they are lagged by the same amount, due to the filtering,
                    //  the lag is removed by taking the ratio.
                    RviWindow.Add(new IndicatorDataPoint(input.EndTime, num / denom));
                }
                catch (DivideByZeroException zex)
                {
                    throw new Exception(zex.Message + zex.StackTrace);
                }
            }
            return(RviWindow[0].Value);
        }
Exemplo n.º 2
0
        public void TestDivByZero()
        {
            var dem = new DeMarkerIndicator("DEM", 3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                // Should handle High = Low case by returning 0m.
                var tradeBar = new TradeBar
                {
                    Open   = data.Value,
                    Close  = data.Value,
                    High   = 1,
                    Low    = 1,
                    Volume = 1
                };
                dem.Update(tradeBar);
            }
            Assert.AreEqual(dem.Current.Value, 0m);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Compare the specified indicator against external data using the specificied comma delimited tet file.
        /// The 'Close' column will be fed to the indicator as input
        /// </summary>
        /// <param name="indicator">The indicator under test</param>
        /// <param name="externalDataFilename"></param>
        /// <param name="targetColumn">The column with the correct answers</param>
        /// <param name="customAssertion">Sets custom assertion logic, parameter is the indicator, expected value from the file</param>
        public static void TestIndicator(IndicatorBase <TradeBar> indicator, string externalDataFilename, string targetColumn, Action <IndicatorBase <TradeBar>, double> customAssertion)
        {
            bool first       = true;
            int  targetIndex = -1;

            foreach (var line in File.ReadLines(Path.Combine("TestData", externalDataFilename)))
            {
                var parts = line.Split(',');
                if (first)
                {
                    first = false;
                    for (int i = 0; i < parts.Length; i++)
                    {
                        if (parts[i].Trim() == targetColumn)
                        {
                            targetIndex = i;
                            break;
                        }
                    }
                    continue;
                }

                var tradebar = new TradeBar
                {
                    Time  = Time.ParseDate(parts[0]),
                    Open  = parts[1].ToDecimal(),
                    High  = parts[2].ToDecimal(),
                    Low   = parts[3].ToDecimal(),
                    Close = parts[4].ToDecimal(),
                    //Volume = long.Parse(parts[5])
                };

                indicator.Update(tradebar);

                if (!indicator.IsReady || parts[targetIndex].Trim() == string.Empty)
                {
                    continue;
                }

                double expected = double.Parse(parts[targetIndex]);
                customAssertion.Invoke(indicator, expected);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Computes the next value of this indicator from the given state
        /// </summary>
        /// <param name="input">The input given to the indicator</param>
        /// <returns> A new value for this indicator </returns>
        protected override decimal ComputeNextValue(TradeBar input)
        {
            if (!IsReady)
            {
                Open.Update(new IndicatorDataPoint(input.Time, (input.Open + input.Close) / 2));
                Close.Update(new IndicatorDataPoint(input.Time, (input.Open + input.High + input.Low + input.Close) / 4));
                High.Update(new IndicatorDataPoint(input.Time, input.High));
                Low.Update(new IndicatorDataPoint(input.Time, input.Low));
            }
            else
            {
                Open.Update(new IndicatorDataPoint(input.Time, (Open + Close) / 2));
                Close.Update(new IndicatorDataPoint(input.Time, (input.Open + input.High + input.Low + input.Close) / 4));
                High.Update(new IndicatorDataPoint(input.Time, Math.Max(input.High, Math.Max(Open, Close))));
                Low.Update(new IndicatorDataPoint(input.Time, Math.Min(input.Low, Math.Min(Open, Close))));
            }

            return(Close);
        }
        /// <summary>
        /// Get historical data enumerable for Bitfinex from Quandl
        /// </summary>
        /// <param name="symbol">Symbol for the data we're looking for.</param>
        /// <param name="resolution">Only Daily is supported</param>
        /// <param name="startUtc">Start time of the data in UTC</param>
        /// <param name="endUtc">End time of the data in UTC</param>
        /// <returns>Enumerable of base data for this symbol</returns>
        public IEnumerable <BaseData> Get(Symbol symbol, Resolution resolution, DateTime startUtc, DateTime endUtc)
        {
            if (resolution != Resolution.Daily)
            {
                throw new ArgumentException("Only daily data is currently supported.");
            }

            const string collapse = "daily";

            var url = "https://www.quandl.com/api/v3/datasets/BCHARTS/BITFINEXUSD.csv?order=asc&collapse=" + collapse + "&api_key=" + _apiKey + "&start_date="
                      + startUtc.ToStringInvariant("yyyy-MM-dd");

            using (var cl = new WebClient())
            {
                var data = cl.DownloadString(url);

                // skip the header line
                foreach (var item in data.Split('\n').Skip(1))
                {
                    var line = item.Split(',');
                    if (line.Length != 8)
                    {
                        continue;
                    }

                    var bar = new TradeBar
                    {
                        Time     = Parse.DateTime(line[0]),
                        Open     = Parse.Decimal(line[1]),
                        High     = Parse.Decimal(line[2]),
                        Low      = Parse.Decimal(line[3]),
                        Close    = Parse.Decimal(line[4]),
                        Value    = Parse.Decimal(line[7]),
                        Volume   = (long)Parse.Decimal(line[5]),
                        Symbol   = symbol,
                        DataType = MarketDataType.TradeBar,
                        Period   = Time.OneDay
                    };

                    yield return(bar);
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// Creates an enumerable of Slice to update the alpha model
        /// </summary>
        protected virtual IEnumerable <Slice> CreateSlices()
        {
            var timeSliceFactory = new TimeSliceFactory(TimeZones.NewYork);
            var changes          = SecurityChanges.None;
            var sliceDateTimes   = GetSliceDateTimes(MaxSliceCount);

            for (var i = 0; i < sliceDateTimes.Count; i++)
            {
                var utcDateTime = sliceDateTimes[i];

                var packets = new List <DataFeedPacket>();

                // TODO : Give securities different values -- will require updating all derived types
                var last = Convert.ToDecimal(100 + 10 * Math.Sin(Math.PI * i / 180.0));
                var high = last * 1.005m;
                var low  = last / 1.005m;
                foreach (var kvp in Algorithm.Securities)
                {
                    var security = kvp.Value;
                    var exchange = security.Exchange.Hours;
                    var configs  = Algorithm.SubscriptionManager.SubscriptionDataConfigService
                                   .GetSubscriptionDataConfigs(security.Symbol);
                    var extendedMarket = configs.IsExtendedMarketHours();
                    var localDateTime  = utcDateTime.ConvertFromUtc(exchange.TimeZone);
                    if (!exchange.IsOpen(localDateTime, extendedMarket))
                    {
                        continue;
                    }
                    var configuration = security.Subscriptions.FirstOrDefault();
                    var period        = configs.GetHighestResolution().ToTimeSpan();
                    var time          = (utcDateTime - period).ConvertFromUtc(configuration.DataTimeZone);
                    var tradeBar      = new TradeBar(time, security.Symbol, last, high, low, last, 1000, period);
                    packets.Add(new DataFeedPacket(security, configuration, new List <BaseData> {
                        tradeBar
                    }));
                }

                if (packets.Count > 0)
                {
                    yield return(timeSliceFactory.Create(utcDateTime, packets, changes, new Dictionary <Universe, BaseDataCollection>()).Slice);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Calculates the split factor of a <see cref="Split"/>
        /// </summary>
        /// <param name="split">The next <see cref="Split"/></param>
        /// <param name="previousFactorFileRow">The previous <see cref="FactorFileRow"/> generated</param>
        /// <returns><see cref="FactorFileRow"/>  that represents the split event</returns>
        private FactorFileRow CalculateNextSplitFactor(BaseData split, FactorFileRow previousFactorFileRow)
        {
            var eventDayData = GetDailyDataForDate(split.Time);

            // If you don't have the equity data nothing can be done
            if (eventDayData == null)
            {
                return(null);
            }

            TradeBar previousClosingPrice = FindPreviousTradableDayClosingPrice(eventDayData.Time);

            return(new FactorFileRow(
                       previousClosingPrice.Time,
                       previousFactorFileRow.PriceFactor,
                       (previousFactorFileRow.SplitFactor / split.Value).RoundToSignificantDigits(6),
                       previousClosingPrice.Close
                       ));
        }
Exemplo n.º 8
0
        public void TestDivByZero() // Should give 0 (default) to avoid div by zero errors.
        {
            var rvi = CreateIndicator();

            for (int i = 0; i < 13; i++)
            {
                var tradeBar = new TradeBar
                {
                    Open   = 0m,
                    Close  = 0m,
                    High   = 0m,
                    Low    = 0m,
                    Volume = 1
                };
                rvi.Update(tradeBar);
            }
            Assert.AreEqual(rvi.Current.Value, 0m);
            Assert.AreEqual(((RelativeVigorIndex)rvi).Signal.Current.Value, 0m);
        }
Exemplo n.º 9
0
        private IEnumerator <BaseData> DataTradeBarEnumerator(DateTime startTimeLocal, DateTime endTimeLocal, TimeSpan increment)
        {
            var currentDataStartTime = startTimeLocal - increment;
            var currentDataEndTime   = startTimeLocal;

            while (currentDataEndTime <= endTimeLocal)
            {
                var data = new TradeBar
                {
                    Time    = currentDataStartTime,
                    EndTime = currentDataEndTime
                };

                yield return(data);

                currentDataStartTime = currentDataEndTime;
                currentDataEndTime   = currentDataEndTime + increment;
            }
        }
Exemplo n.º 10
0
        public void GentlyHandlesPeriodAndDataAreSameResolution()
        {
            TradeBar consolidated = null;

            using var consolidator         = new TradeBarConsolidator(Time.OneDay);
            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);

            consolidator.Update(new TradeBar {
                Time = reference, Period = Time.OneDay
            });

            Assert.IsNotNull(consolidated);
            Assert.AreEqual(reference, consolidated.Time);
        }
Exemplo n.º 11
0
        public void TestTradeBarsWithNoVolume()
        {
            var mfi = new MoneyFlowIndex(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                var tradeBar = new TradeBar
                {
                    Open   = data.Value,
                    Close  = data.Value,
                    High   = data.Value,
                    Low    = data.Value,
                    Volume = 0
                };
                mfi.Update(tradeBar);
            }

            Assert.AreEqual(mfi.Current.Value, 100.0m);
        }
Exemplo n.º 12
0
        public void ExpectedConsolidatedTradeBarsInPeriodMode(TimeSpan barSpan, TimeSpan updateSpan)
        {
            TradeBar consolidated = null;

            using var consolidator         = new BaseDataConsolidator(barSpan);
            consolidator.DataConsolidated += (sender, bar) =>
            {
                Assert.AreEqual(barSpan, bar.Period);              // The period matches our span
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);
            var dataTime  = reference;

            var nextBarTime = reference + barSpan;
            var lastBarTime = reference;

            // First data point
            consolidator.Update(new Tick {
                Time = dataTime
            });
            Assert.IsNull(consolidated);

            for (var i = 0; i < 10; i++)
            {
                // Add data on the given interval until we expect a new bar
                while (dataTime < nextBarTime)
                {
                    dataTime = dataTime.Add(updateSpan);
                    consolidator.Update(new Tick {
                        Time = dataTime
                    });
                }

                // Our asserts
                Assert.IsNotNull(consolidated);                               // We have a bar
                Assert.AreEqual(dataTime, consolidated.EndTime);              // New bar time should be dataTime
                Assert.AreEqual(barSpan, consolidated.EndTime - lastBarTime); // The difference between the bars is the span

                nextBarTime = dataTime + barSpan;
                lastBarTime = consolidated.EndTime;
            }
        }
Exemplo n.º 13
0
        public void CreateTotalNotZeroDividends(Type type, decimal?scale)
        {
            var config = new SubscriptionDataConfig(
                typeof(TradeBar),
                Symbols.SPY,
                Resolution.Hour,
                TimeZones.Utc,
                TimeZones.Utc,
                false,
                false,
                false
                );

            config.SumOfDividends        = 100;
            config.DataNormalizationMode = DataNormalizationMode.TotalReturn;

            var tb = new TradeBar
            {
                Time   = new DateTime(2020, 5, 21, 8, 9, 0),
                Period = TimeSpan.FromHours(1),
                Symbol = Symbols.SPY,
                Open   = 100,
                High   = 200,
                Low    = 300,
                Close  = 400
            };

            var data = SubscriptionData.Create(
                config,
                SecurityExchangeHours.AlwaysOpen(TimeZones.Utc),
                new TimeZoneOffsetProvider(TimeZones.NewYork, new DateTime(2015, 1, 1), new DateTime(2016, 1, 1)),
                tb,
                config.DataNormalizationMode,
                scale);

            Assert.True(data.GetType() == type);

            Assert.AreEqual(tb.Open * scale + config.SumOfDividends, (data.Data as TradeBar).Open);
            Assert.AreEqual(tb.High * scale + config.SumOfDividends, (data.Data as TradeBar).High);
            Assert.AreEqual(tb.Low * scale + config.SumOfDividends, (data.Data as TradeBar).Low);
            Assert.AreEqual(tb.Close * scale + config.SumOfDividends, (data.Data as TradeBar).Close);
        }
Exemplo n.º 14
0
        public void AdjustTradeBar()
        {
            var tb = new TradeBar
            {
                Time   = new DateTime(2020, 5, 21, 8, 9, 0),
                Period = TimeSpan.FromHours(1),
                Symbol = Symbols.SPY,
                Open   = 100,
                High   = 200,
                Low    = 300,
                Close  = 400
            };

            var adjustedTb = tb.Clone(tb.IsFillForward).Adjust(_factor);

            Assert.AreEqual(tb.Open * _factor, (adjustedTb as TradeBar).Open);
            Assert.AreEqual(tb.High * _factor, (adjustedTb as TradeBar).High);
            Assert.AreEqual(tb.Low * _factor, (adjustedTb as TradeBar).Low);
            Assert.AreEqual(tb.Close * _factor, (adjustedTb as TradeBar).Close);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Event Handing for new trade bar - this is used by the inheriting algo's and is called from the IDataReader.
        /// </summary>
        public virtual void OnTradeBar(TradeBar data, EventArgs e)
        {
            //Note do not change the order of events
            _currentTradebar = data;

            //Step 1: Update indicators
            foreach (IIndicator item in Indicators)
            {
                item.UpdateIndicator(data.Close);
            }

            //Step 2: Update queued orders in the broker queue
            Broker.ProcessNewTradebar(data);

            //Step 3: Update the inheriting class OnData events
            if (OnTradeBarEvent != null)
            {
                OnTradeBarEvent(data, e);
            }
        }
Exemplo n.º 16
0
        public void TestTradeBarsWithNoVolume()
        {
            var mfi = new MoneyFlowIndex(3);

            foreach (var data in TestHelper.GetDataStream(4))
            {
                var tradeBar = new TradeBar
                {
                    Open     = data.Price,
                    Close    = data.Price,
                    High     = data.Price,
                    Low      = data.Price,
                    TimeZone = TimeZone.Utc,
                    Volume   = 0
                };
                mfi.Update(tradeBar);
            }

            Assert.Equal(100.0m, mfi.Current.Price);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Logs the transaction into a csv for review
        /// </summary>
        private void logTransacton(TradeBar data, Action action)
        {
            if (_transactionLogBuilder == null)
            {
                _transactionLogBuilder = new StringBuilder();
                _transactionLogBuilder.AppendLine("Date,Symbol,Action,Open,Close,RSI,SMA,Comments");
            }

            _transactionLogBuilder.AppendLine(string.Format
                                                  ("{0},{1},{2},{3},{4},{5},{6},{7}",
                                                  data.Day,
                                                  Symbol,
                                                  action.ToString().Replace("na", ""),
                                                  Math.Round(data.Open, 2),
                                                  Math.Round(data.Close, 2),
                                                  Math.Round(_rsi.Value),
                                                  Math.Round(_sma.Value),
                                                  _logComments
                                                  ));
        }
Exemplo n.º 18
0
        public void AggregatesPeriodInPeriodModeWithDailyDataAndRoundedTime()
        {
            TradeBar consolidated = null;
            var      period       = TimeSpan.FromDays(1);
            var      consolidator = new TradeBarConsolidator(period);

            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);

            consolidator.Update(new TradeBar {
                Time = reference.AddSeconds(45), Period = period
            });
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(1).AddMinutes(1), Period = period
            });
            Assert.IsNotNull(consolidated);
            Assert.AreEqual(period, consolidated.Period);
            Assert.AreEqual(reference, consolidated.Time);
            consolidated = null;

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(2).AddHours(1), Period = period
            });
            Assert.IsNotNull(consolidated);
            Assert.AreEqual(period, consolidated.Period);
            Assert.AreEqual(reference.AddDays(1), consolidated.Time);
            consolidated = null;

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(3).AddMinutes(1).AddSeconds(1), Period = period
            });
            Assert.IsNotNull(consolidated);
            Assert.AreEqual(period, consolidated.Period);
            Assert.AreEqual(reference.AddDays(2), consolidated.Time);
        }
Exemplo n.º 19
0
        public void AggregatesPeriodInPeriodModeWithDailyData()
        {
            TradeBar consolidated = null;
            var      period       = TimeSpan.FromDays(2);

            using var consolidator         = new TradeBarConsolidator(period);
            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);

            consolidator.Update(new TradeBar {
                Time = reference, Period = Time.OneDay
            });
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(1), Period = Time.OneDay
            });
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(2), Period = Time.OneDay
            });
            Assert.IsNotNull(consolidated);
            Assert.AreEqual(period, consolidated.Period);
            consolidated = null;

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(3), Period = Time.OneDay
            });
            Assert.IsNull(consolidated);

            consolidator.Update(new TradeBar {
                Time = reference.AddDays(4), Period = Time.OneDay
            });
            Assert.IsNotNull(consolidated);
            Assert.AreEqual(period, consolidated.Period);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Aggregates the new 'data' into the 'workingBar'. The 'workingBar' will be
        /// null following the event firing
        /// </summary>
        /// <param name="workingBar">The bar we're building, null if the event was just fired and we're starting a new trade bar</param>
        /// <param name="data">The new data</param>
        protected override void AggregateBar(ref TradeBar workingBar, DynamicData data)
        {
            // grab the properties, if they don't exist just use the .Value property
            var open  = GetNamedPropertyOrValueProperty(data, "Open");
            var high  = GetNamedPropertyOrValueProperty(data, "High");
            var low   = GetNamedPropertyOrValueProperty(data, "Low");
            var close = GetNamedPropertyOrValueProperty(data, "Close");

            // if we have volume, use it, otherwise just use zero
            var volume = data.HasProperty("Volume")
                ? (long)Convert.ChangeType(data.GetProperty("Volume"), typeof(long))
                : 0L;

            if (workingBar == null)
            {
                workingBar = new TradeBar
                {
                    Symbol = data.Symbol,
                    Time   = GetRoundedBarTime(data.Time),
                    Open   = open,
                    High   = high,
                    Low    = low,
                    Close  = close,
                    Volume = volume
                };
            }
            else
            {
                //Aggregate the working bar
                workingBar.Close   = close;
                workingBar.Volume += volume;
                if (low < workingBar.Low)
                {
                    workingBar.Low = low;
                }
                if (high > workingBar.High)
                {
                    workingBar.High = high;
                }
            }
        }
Exemplo n.º 21
0
        public void AggregatesPeriodInPeriodModeWithDailyData()
        {
            //Arrange
            TradeBar tradeBar       = null;
            var      tickAggregator = new TickAggregator(TimeSpan.FromDays(1));

            tickAggregator.DataAggregated += (sender, bar) =>
            {
                tradeBar = bar;
            };

            //Act
            var reference = new DateTime(2015, 04, 13);

            tickAggregator.Feed(new Tick {
                Occured = reference
            });
            tradeBar.Should().BeNull();

            tickAggregator.Feed(new Tick {
                Occured = reference.AddDays(1)
            });
            tradeBar.Should().NotBeNull();
            tradeBar.Period.Should().Be(TimeSpan.FromDays(1));
            tradeBar = null;

            tickAggregator.Feed(new Tick {
                Occured = reference.AddDays(2)
            });
            tradeBar.Should().NotBeNull();
            tradeBar.Period.Should().Be(TimeSpan.FromDays(1));
            tradeBar = null;

            tickAggregator.Feed(new Tick {
                Occured = reference.AddDays(3)
            });

            //Assert
            tradeBar.Should().NotBeNull();
            tradeBar.Period.Should().Be(TimeSpan.FromDays(1));
        }
Exemplo n.º 22
0
        public void AccessesTradeBarAndQuoteBarForSameSymbol()
        {
            var tradeBar = new TradeBar(DateTime.Now, Symbols.BTCUSD,
                                        3000, 3000, 3000, 3000, 100, Time.OneMinute);

            var quoteBar = new QuoteBar(DateTime.Now, Symbols.BTCUSD,
                                        new Bar(3100, 3100, 3100, 3100), 0,
                                        new Bar(3101, 3101, 3101, 3101), 0,
                                        Time.OneMinute);

            var tradeBars = new TradeBars {
                { Symbols.BTCUSD, tradeBar }
            };
            var quoteBars = new QuoteBars {
                { Symbols.BTCUSD, quoteBar }
            };

            var slice = new Slice(DateTime.Now, new BaseData[] { tradeBar, quoteBar }, tradeBars, quoteBars, null, null, null, null, null, null, null);

            var tradeBarData = slice.Get <TradeBar>();

            Assert.AreEqual(1, tradeBarData.Count);
            Assert.AreEqual(3000, tradeBarData[Symbols.BTCUSD].Close);

            var quoteBarData = slice.Get <QuoteBar>();

            Assert.AreEqual(1, quoteBarData.Count);
            Assert.AreEqual(3100, quoteBarData[Symbols.BTCUSD].Bid.Close);
            Assert.AreEqual(3101, quoteBarData[Symbols.BTCUSD].Ask.Close);

            slice = new Slice(DateTime.Now, new BaseData[] { tradeBar, quoteBar });

            tradeBarData = slice.Get <TradeBar>();
            Assert.AreEqual(1, tradeBarData.Count);
            Assert.AreEqual(3000, tradeBarData[Symbols.BTCUSD].Close);

            quoteBarData = slice.Get <QuoteBar>();
            Assert.AreEqual(1, quoteBarData.Count);
            Assert.AreEqual(3100, quoteBarData[Symbols.BTCUSD].Bid.Close);
            Assert.AreEqual(3101, quoteBarData[Symbols.BTCUSD].Ask.Close);
        }
Exemplo n.º 23
0
        protected override decimal ComputeNextValue(TradeBar input)
        {
            _fractal.Add(input);

            if (!_fractal.IsReady)
            {
                return(MidPoint);
            }

            if (_fractal.IndexOfMax((bar, index) => bar.High) == _fractalMidIndex)
            {
                _barryUp = input.High;
            }

            if (_fractal.IndexOfMin((bar, index) => bar.Low) == _fractalMidIndex)
            {
                _barryDown = input.Low;
            }

            return(MidPoint);
        }
Exemplo n.º 24
0
        private OrderTicket PlaceLimitOrder(TradeBar bar)
        {
            Debug("Sending limit order");
            OrderTicket limitTicket = LimitOrder(Symbol(BIST_SYMBOL), quantity, price); //int code = LimitOrder(BIST_SECURITY_NAME, 1, 9);
            int         code        = limitTicket;                                      //int code = Order(BIST_SECURITY_NAME, 1,OrderType.Limit);//SetHoldings("SPY", 1);

            _openLimitOrders.Add(limitTicket);


            if (code >= 0)
            {   //Notify.Email("*****@*****.**", "Test Subject", "Test Body: " + Time.ToString("u"), "Test Attachment");
                Debug("Limit Order sent" + Time.ToString("HH:mm:ss.ffffff"));
            }
            else
            {
                Debug("Limit Order send failed " + Time.ToString("HH:mm:ss.ffffff"));
                OrderError errorCode = (OrderError)code;
                DisplayOrderStatus(errorCode);
            }
            return(limitTicket);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Pushes the tick into this enumerator. This tick will be aggregated into a bar
        /// and emitted after the alotted time has passed
        /// </summary>
        /// <param name="data">The new data to be aggregated</param>
        public void ProcessData(BaseData data)
        {
            TradeBar working;
            var      tick = data as Tick;
            var      qty  = tick == null ? 0 : tick.Quantity;

            if (!_queue.TryPeek(out working))
            {
                // the consumer took the working bar, or time ticked over into next bar
                var marketPrice      = data.Value;
                var currentLocalTime = _timeProvider.GetUtcNow().ConvertFromUtc(_timeZone);
                var barStartTime     = currentLocalTime.RoundDown(_barSize);
                working = new TradeBar(barStartTime, data.Symbol, marketPrice, marketPrice, marketPrice, marketPrice, qty, _barSize);
                _queue.Enqueue(working);
            }
            else
            {
                // we're still within this bar size's time
                working.Update(data.Value, tick == null ? data.Value : tick.BidPrice, tick == null ? data.Value : tick.AskPrice, qty);
            }
        }
Exemplo n.º 26
0
        public void FiresEventAfterTimePassesViaScan()
        {
            TradeBar consolidated = null;
            var      period       = TimeSpan.FromDays(1);
            var      consolidator = new TradeBarConsolidator(period);

            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
            };

            var reference = new DateTime(2015, 04, 13);

            consolidator.Update(new TradeBar {
                Time = reference.AddSeconds(45), Period = period
            });
            Assert.IsNull(consolidated);

            consolidator.Scan(reference + period);
            Assert.IsNotNull(consolidated);
        }
Exemplo n.º 27
0
        public void HandlesGappingAcrossDays()
        {
            var consolidator = new TradeBarConsolidator(TimeSpan.FromHours(1));

            TradeBar consolidated = null;

            consolidator.DataConsolidated += (sender, bar) =>
            {
                consolidated = bar;
                Console.WriteLine(bar.Time);
            };

            // from 1/1 9:30 to 1/2 12:00 by minute
            var start = new DateTime(2014, 01, 01, 09, 30, 00, 00);
            var end   = new DateTime(2014, 01, 02, 12, 00, 00, 00);

            foreach (var bar in StreamTradeBars(start, end, TimeSpan.FromMinutes(1)))
            {
                consolidator.Update(bar);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Calculates the price factor of a <see cref="Dividend"/>
        /// </summary>
        /// <param name="dividend">The next dividend</param>
        /// <param name="previousFactorFileRow">The previous <see cref="FactorFileRow"/> generated</param>
        /// <returns><see cref="FactorFileRow"/> that represents the dividend event</returns>
        private FactorFileRow CalculateNextDividendFactor(BaseData dividend, FactorFileRow previousFactorFileRow)
        {
            var eventDayData = GetDailyDataForDate(dividend.Time);

            // If you don't have the equity data nothing can be calculated
            if (eventDayData == null)
            {
                return(null);
            }

            TradeBar previousClosingPrice = FindPreviousTradableDayClosingPrice(eventDayData.Time);

            var priceFactor = previousFactorFileRow.PriceFactor - (dividend.Value / ((previousClosingPrice.Close) * previousFactorFileRow.SplitFactor));

            return(new FactorFileRow(
                       previousClosingPrice.Time,
                       priceFactor.RoundToSignificantDigits(7),
                       previousFactorFileRow.SplitFactor,
                       previousClosingPrice.Close
                       ));
        }
Exemplo n.º 29
0
        public void PythonSlice_update_success()
        {
            using (Py.GIL())
            {
                dynamic test = PythonEngine.ModuleFromString("testModule",
                                                             @"
from clr import AddReference
AddReference(""QuantConnect.Common"")
from QuantConnect import *
from QuantConnect.Data.Market import TradeBar

def Test(slice, symbol, bar):
    item = { symbol: bar }
    slice.Bars.update(item)").GetAttr("Test");

                var expected    = new TradeBar();
                var pythonSlice = GetPythonSlice();
                Assert.DoesNotThrow(() => test(pythonSlice, Symbols.SPY, expected));
                Assert.AreEqual(expected, pythonSlice.Bars[Symbols.SPY]);
            }
        }
Exemplo n.º 30
0
        private bool IsExit(TradeBar b, out decimal exitPrice)
        {
            exitPrice = 0;
            bool rtn = false;

            if (Portfolio.Invested && Portfolio[Symbol] != null)
            {
                if ( // for Long exit
                    Portfolio[Symbol].IsLong && b.Time.Hour == 10 && b.Time.Minute == 45
                    ||
                    // for short exit
                    Portfolio[Symbol].IsShort &&
                    _trlStop.IsTrailingExit(b, out exitPrice)
                    )
                {
                    rtn       = true;
                    exitPrice = b.Close;
                }
            }
            return(rtn);
        }