コード例 #1
0
        public void PerformsMarketFillBuy()
        {
            var model    = new ImmediateFillModel();
            var order    = new MarketOrder(Symbols.SPY, 100, Noon);
            var config   = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance
                );

            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m));

            var fill = model.Fill(new FillModelParameters(
                                      security,
                                      order,
                                      new MockSubscriptionDataConfigProvider(config))).OrderEvent;

            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Price, fill.FillPrice);
            Assert.AreEqual(OrderStatus.Filled, fill.Status);
        }
コード例 #2
0
        public void AddingDuplicateTimeZoneDoesntAdd()
        {
            var reference       = new DateTime(2000, 01, 01);
            var timeKeeper      = new TimeKeeper(reference, new[] { TimeZones.NewYork });
            var localTimeKeeper = timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);

            timeKeeper.AddTimeZone(TimeZones.NewYork);

            Assert.AreEqual(localTimeKeeper, timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
        }
コード例 #3
0
ファイル: TimeKeeperTests.cs プロジェクト: skyfyl/Lean
        public void AddingDuplicateTimeZoneDoesntAdd()
        {
            var reference = new DateTime(2000, 01, 01);
            var timeKeeper = new TimeKeeper(reference, new[] { TimeZones.NewYork });
            var localTimeKeeper = timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);

            timeKeeper.AddTimeZone(TimeZones.NewYork);

            Assert.AreEqual(localTimeKeeper, timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
        }
コード例 #4
0
        public void MinuteResolutionSelectedForFuturesOptions()
        {
            const int periods          = 5;
            var       reference        = new DateTime(2016, 04, 06, 12, 0, 0);
            var       referenceUtc     = reference.ConvertToUtc(TimeZones.Chicago);
            var       timeKeeper       = new TimeKeeper(referenceUtc);
            var       underlyingSymbol = Symbol.Create("ES", SecurityType.Future, Market.CME);
            var       futureOption     = Symbol.CreateOption(
                underlyingSymbol,
                Market.CME,
                OptionStyle.American,
                OptionRight.Call,
                0,
                SecurityIdentifier.DefaultDate);

            var underlyingConfig   = new SubscriptionDataConfig(typeof(TradeBar), underlyingSymbol, Resolution.Minute, TimeZones.Chicago, TimeZones.Chicago, true, false, false);
            var futureOptionConfig = new SubscriptionDataConfig(typeof(TradeBar), futureOption, Resolution.Minute, TimeZones.Chicago, TimeZones.Chicago, true, false, false);

            var underlyingSecurity = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.Chicago),
                underlyingConfig,
                new Cash(Currencies.USD, 0, 0),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );
            var futureOptionSecurity = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.Chicago),
                futureOptionConfig,
                new Cash(Currencies.USD, 0, 0),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            underlyingSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.Chicago));
            futureOptionSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.Chicago));

            var mock = new MockSubscriptionDataConfigProvider();

            mock.SubscriptionDataConfigs.Add(underlyingConfig);
            mock.SubscriptionDataConfigs.Add(futureOptionConfig);
            var model = new StandardDeviationOfReturnsVolatilityModel(periods, Resolution.Minute, TimeSpan.FromMinutes(1));

            model.SetSubscriptionDataConfigProvider(mock);

            var futureHistoryRequirements = model.GetHistoryRequirements(underlyingSecurity, referenceUtc);
            var optionHistoryRequirements = model.GetHistoryRequirements(futureOptionSecurity, referenceUtc);

            Assert.IsTrue(futureHistoryRequirements.All(x => x.Resolution == Resolution.Minute));
            Assert.IsTrue(optionHistoryRequirements.All(x => x.Resolution == Resolution.Minute));
        }
コード例 #5
0
        private Security GetSecurity <T>(Symbol symbol, Resolution resolution)
        {
            var subscriptionDataConfig = new SubscriptionDataConfig(
                typeof(T),
                symbol,
                resolution,
                TimeZones.Utc,
                TimeZones.Utc,
                true,
                true,
                false);

            var security = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.Utc),
                subscriptionDataConfig,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(subscriptionDataConfig.DataTimeZone);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(subscriptionDataConfig.DataTimeZone));

            return(security);
        }
コード例 #6
0
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol           = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours    = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash        = new Cash("USD", 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault("USD");
            var config           = new SubscriptionDataConfig(typeof(Tick), symbol, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security         = new Forex(exchangeHours, quoteCash, config, symbolProperties);

            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel      = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order    = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill     = fillModel.MarketFill(security, order);

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;

            Assert.AreEqual(expected, fill.FillPrice);
        }
コード例 #7
0
        public void ConstructsLocalTimeKeepers()
        {
            var reference  = new DateTime(2000, 01, 01);
            var timeKeeper = new TimeKeeper(reference, new[] { TimeZones.NewYork });

            Assert.IsNotNull(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
        }
コード例 #8
0
        private Security GetSecurity(Symbol symbol, DataNormalizationMode mode)
        {
            var symbolProperties = SymbolPropertiesDatabase.FromDataFolder()
                .GetSymbolProperties(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType, CashBook.AccountCurrency);

            Security security;
            if (symbol.ID.SecurityType == SecurityType.Equity)
            {
                security = new QuantConnect.Securities.Equity.Equity(
                    SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                    new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false),
                    new Cash(CashBook.AccountCurrency, 0, 1m),
                    symbolProperties);
            }
            else
            {
                security = new QuantConnect.Securities.Forex.Forex(
                   SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                   new Cash(CashBook.AccountCurrency, 0, 1m),
                   new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false),
                   symbolProperties);
            }

            var TimeKeeper = new TimeKeeper(DateTime.Now.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });
            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetDataNormalizationMode(mode);

            return security;
        }
コード例 #9
0
        public void OldBaseFillModel_MarketOnCloseFill(bool isMarketAlwaysOpen)
        {
            var model        = new TestFillModelInheritBaseClass();
            var security     = SecurityTests.GetSecurity(isMarketAlwaysOpen);
            var reference    = new DateTime(2022, 4, 5, 10, 0, 0);
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var args = new FillModelParameters(security, new MarketOnCloseOrder(security.Symbol, 1, orderDateTime),
                                               new MockSubscriptionDataConfigProvider(_config), Time.OneHour);

            if (isMarketAlwaysOpen)
            {
                Assert.Throws <InvalidOperationException>(() => model.Fill(args));
            }
            else
            {
                var result = model.Fill(args);

                Assert.True(model.MarketOnCloseFillWasCalled);
                Assert.IsNotNull(result);
                Assert.True(model.GetPricesWasCalled);
                Assert.AreEqual(12345, result.OrderEvent.FillPrice);
            }
        }
        public void UpdatesAfterCorrectPeriodElapses()
        {
            const int periods = 3;
            var periodSpan = Time.OneMinute;
            var reference = new DateTime(2016, 04, 06, 12, 0, 0);
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper = new TimeKeeper(referenceUtc);
            var config = new SubscriptionDataConfig(typeof (TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), config, new Cash("USD", 0, 0), SymbolProperties.GetDefault("USD"));
            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var model = new RelativeStandardDeviationVolatilityModel(periodSpan, periods);
            security.VolatilityModel = model;

            var first = new IndicatorDataPoint(reference, 1);
            security.SetMarketPrice(first);

            Assert.AreEqual(0m, model.Volatility);

            const decimal value = 0.471404520791032M; // std of 1,2 is ~0.707 over a mean of 1.5
            var second = new IndicatorDataPoint(reference.AddMinutes(1), 2);
            security.SetMarketPrice(second);
            Assert.AreEqual(value, model.Volatility);

            // update should not be applied since not enough time has passed
            var third = new IndicatorDataPoint(reference.AddMinutes(1.01), 1000);
            security.SetMarketPrice(third);
            Assert.AreEqual(value, model.Volatility);

            var fourth = new IndicatorDataPoint(reference.AddMinutes(2), 3m);
            security.SetMarketPrice(fourth);
            Assert.AreEqual(0.5m, model.Volatility);
        }
コード例 #11
0
        public void PerformsMarketFillBuy()
        {
            var model    = new SecurityTransactionModel();
            var order    = new MarketOrder(Symbol, 100, Noon, type: SecurityType.Equity);
            var config   = CreateTradeBarConfig(Symbol);
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, 1);

            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbol, Noon, 101.123m));

            var fill = model.MarketFill(security, order);

            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Price, fill.FillPrice);
            Assert.AreEqual(OrderStatus.Filled, fill.Status);
        }
        public void GetHistoryRequirementsWorks()
        {
            const int periods      = 3;
            var       reference    = new DateTime(2016, 04, 06, 12, 0, 0);
            var       referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var       timeKeeper   = new TimeKeeper(referenceUtc);
            var       config       = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            var       security     = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                config,
                new Cash("USD", 0, 0),
                SymbolProperties.GetDefault("USD"),
                ErrorCurrencyConverter.Instance
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var model = new StandardDeviationOfReturnsVolatilityModel(periods);

            model.SetSubscriptionDataConfigProvider(new MockSubscriptionDataConfigProvider(config));
            var result = model.GetHistoryRequirements(security, DateTime.UtcNow).First();

            Assert.AreEqual(config.DataNormalizationMode, result.DataNormalizationMode);
            Assert.AreEqual(config.Symbol, result.Symbol);
            Assert.AreEqual(config.DataTimeZone, result.DataTimeZone);
            Assert.AreEqual(config.IsCustomData, result.IsCustomData);
            Assert.AreEqual(config.FillDataForward, result.FillForwardResolution != null);
            Assert.AreEqual(config.ExtendedMarketHours, result.IncludeExtendedMarketHours);
            // the StandardDeviationOfReturnsVolatilityModel always uses daily
            Assert.AreEqual(Resolution.Daily, result.Resolution);
        }
コード例 #13
0
        /// <summary>
        /// QCAlgorithm Base Class Constructor - Initialize the underlying QCAlgorithm components.
        /// QCAlgorithm manages the transactions, portfolio, charting and security subscriptions for the users algorithms.
        /// </summary>
        public QCAlgorithm()
        {
            //Initialise the Algorithm Helper Classes:
            //- Note - ideally these wouldn't be here, but because of the DLL we need to make the classes shared across
            //  the Worker & Algorithm, limiting ability to do anything else.

            //Initialise Start and End Dates:
            _startDate = new DateTime(1998, 01, 01);
            _endDate   = DateTime.Now.AddDays(-1);

            // intialize our time keeper with only new york
            _timeKeeper = new TimeKeeper(_startDate, new[] { TimeZones.NewYork });
            // set our local time zone
            _localTimeKeeper = _timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);

            //Initialise Data Manager
            SubscriptionManager = new SubscriptionManager(_timeKeeper);

            Securities     = new SecurityManager(_timeKeeper);
            Transactions   = new SecurityTransactionManager(Securities);
            Portfolio      = new SecurityPortfolioManager(Securities, Transactions);
            BrokerageModel = new DefaultBrokerageModel();
            Notify         = new NotificationManager(false); // Notification manager defaults to disabled.

            //Initialise Algorithm RunMode to Series - Parallel Mode deprecated:
            _runMode = RunMode.Series;

            //Initialise to unlocked:
            _locked = false;

            // get exchange hours loaded from the market-hours-database.csv in /Data/market-hours
            _exchangeHoursProvider = SecurityExchangeHoursProvider.FromDataFolder();
        }
コード例 #14
0
        public void MarketOrderFillsAtBidAsk(OrderDirection direction)
        {
            var symbol = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm");
            var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork);
            var quoteCash = new Cash("USD", 1000, 1);
            var symbolProperties = SymbolProperties.GetDefault("USD");
            var security = new Forex(symbol, exchangeHours, quoteCash, symbolProperties);

            var reference = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper = new TimeKeeper(referenceUtc);
            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var brokerageModel = new FxcmBrokerageModel();
            var fillModel = brokerageModel.GetFillModel(security);

            const decimal bidPrice = 1.13739m;
            const decimal askPrice = 1.13746m;

            security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice));

            var quantity = direction == OrderDirection.Buy ? 1 : -1;
            var order = new MarketOrder(symbol, quantity, DateTime.Now);
            var fill = fillModel.MarketFill(security, order);

            var expected = direction == OrderDirection.Buy ? askPrice : bidPrice;
            Assert.AreEqual(expected, fill.FillPrice);
        }
コード例 #15
0
        public void ImmediateFillModelUsesPriceForTicksWhenBidAskSpreadsAreNotAvailable()
        {
            var noon       = new DateTime(2014, 6, 24, 12, 0, 0);
            var timeKeeper = new TimeKeeper(noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });
            var symbol     = Symbol.Create("SPY", SecurityType.Equity, Market.USA);
            var config     = new SubscriptionDataConfig(typeof(Tick), Symbols.SPY, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security   = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency),
                ErrorCurrencyConverter.Instance
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, noon, 101.123m));

            // Add both a tradebar and a tick to the security cache
            // This is the case when a tick is seeded with minute data in an algorithm
            security.Cache.AddData(new TradeBar(DateTime.MinValue, symbol, 1.0m, 1.0m, 1.0m, 1.0m, 1.0m));
            security.Cache.AddData(new Tick(config, "42525000,1000000,100,A,@,0", DateTime.MinValue));

            var fillModel = new ImmediateFillModel();
            var order     = new MarketOrder(symbol, 1000, DateTime.Now);
            var fill      = fillModel.MarketFill(security, order);

            // The fill model should use the tick.Price
            Assert.AreEqual(fill.FillPrice, 100m);
            Assert.AreEqual(0, fill.OrderFee);
        }
コード例 #16
0
        public void PerformsMarketFillBuy()
        {
            var model    = new SecurityTransactionModel();
            var order    = new MarketOrder(Symbols.SPY, 100, Noon);
            var config   = CreateTradeBarConfig(Symbols.SPY);
            var security = new Security(SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m));

            var fill = model.MarketFill(security, order);

            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Price, fill.FillPrice);
            Assert.AreEqual(OrderStatus.Filled, fill.Status);
        }
コード例 #17
0
        private Security GetSecurity(Symbol symbol, DataNormalizationMode mode)
        {
            var symbolProperties = SymbolPropertiesDatabase.FromDataFolder()
                                   .GetSymbolProperties(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType, CashBook.AccountCurrency);

            Security security;

            if (symbol.ID.SecurityType == SecurityType.Equity)
            {
                security = new QuantConnect.Securities.Equity.Equity(
                    SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                    new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false),
                    new Cash(CashBook.AccountCurrency, 0, 1m),
                    symbolProperties);
            }
            else
            {
                security = new QuantConnect.Securities.Forex.Forex(
                    SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                    new Cash(CashBook.AccountCurrency, 0, 1m),
                    new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false),
                    symbolProperties);
            }

            var TimeKeeper = new TimeKeeper(DateTime.Now.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });

            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetDataNormalizationMode(mode);

            return(security);
        }
コード例 #18
0
        public void TestMarginForSymbolWithOneLinerHistory()
        {
            const decimal price   = 1.2345m;
            var           time    = new DateTime(2016, 1, 1);
            var           expDate = new DateTime(2017, 1, 1);
            var           tz      = TimeZones.NewYork;

            // For this symbol we dont have any history, but only one date and margins line
            var ticker = QuantConnect.Securities.Futures.Softs.Coffee;
            var symbol = Symbol.CreateFuture(ticker, Market.ICE, expDate);

            var futureSecurity = new Future(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
                new Cash(Currencies.USD, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            futureSecurity.BuyingPowerModel = new FutureMarginModel(security: futureSecurity);
            futureSecurity.SetMarketPrice(new Tick {
                Value = price, Time = time
            });
            futureSecurity.Holdings.SetHoldings(1.5m, 1);
            var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));

            futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));

            var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel);

            Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
        }
コード例 #19
0
        public void TestMarginForSymbolWithNoHistory()
        {
            const decimal price   = 1.2345m;
            var           time    = new DateTime(2016, 1, 1);
            var           expDate = new DateTime(2017, 1, 1);
            var           tz      = TimeZones.NewYork;

            // For this symbol we dont have any history at all
            var ticker = "NOT-A-SYMBOL";
            var symbol = Symbol.CreateFuture(ticker, Market.USA, expDate);

            var futureSecurity = new Future(SecurityExchangeHours.AlwaysOpen(tz),
                                            new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
                                            new Cash(Currencies.USD, 0, 1m),
                                            new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                                            ErrorCurrencyConverter.Instance,
                                            RegisteredSecurityDataTypesProvider.Null);

            futureSecurity.SetMarketPrice(new Tick {
                Value = price, Time = time
            });
            futureSecurity.Holdings.SetHoldings(1.5m, 1);
            var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));

            futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));

            var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel, timeKeeper: timeKeeper);

            Assert.AreEqual(0m, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
        }
コード例 #20
0
        private Security GetSecurity <T>(Symbol symbol, Resolution resolution)
        {
            var subscriptionDataConfig = new SubscriptionDataConfig(
                typeof(T),
                symbol,
                resolution,
                TimeZones.Utc,
                TimeZones.Utc,
                true,
                true,
                false);

            var security = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.Utc),
                subscriptionDataConfig,
                new Cash(CashBook.AccountCurrency, 0, 1m),
                SymbolProperties.GetDefault(CashBook.AccountCurrency));

            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(subscriptionDataConfig.DataTimeZone);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(subscriptionDataConfig.DataTimeZone));

            return(security);
        }
コード例 #21
0
ファイル: ForexHoldingTest.cs プロジェクト: zhenpingfeng/Lean
        public void TotalProfitIsCorrectlyEstimated(string ticker, decimal conversionRate,
                                                    decimal minimumPriceVariation,
                                                    int lotSize, decimal entryPrice, decimal pips, int entryQuantity)
        {
            // Arrange
            var timeKeeper = new TimeKeeper(DateTime.Now, TimeZones.NewYork);

            var symbol            = Symbol.Create(ticker, SecurityType.Forex, Market.FXCM);
            var pairQuoteCurrency = symbol.Value.Substring(startIndex: 3);
            var cash         = new Cash(pairQuoteCurrency, amount: 100000, conversionRate: conversionRate);
            var subscription = new SubscriptionDataConfig(typeof(QuoteBar), symbol, Resolution.Daily,
                                                          TimeZones.NewYork, TimeZones.NewYork, fillForward: true,
                                                          extendedHours: true, isInternalFeed: true);

            var pair = new QuantConnect.Securities.Forex.Forex(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                                                               cash, subscription,
                                                               new SymbolProperties("", pairQuoteCurrency, 1,
                                                                                    minimumPriceVariation, lotSize));

            pair.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            pair.SetFeeModel(new ConstantFeeModel(decimal.Zero));
            var forexHolding = new ForexHolding(pair);

            // Act
            forexHolding.SetHoldings(entryPrice, entryQuantity);
            var priceVariation = pips * 10 * minimumPriceVariation;

            forexHolding.UpdateMarketPrice(entryPrice + priceVariation);
            pair.SetMarketPrice(new Tick(DateTime.Now, pair.Symbol, forexHolding.Price, forexHolding.Price));
            var actualPips = forexHolding.TotalCloseProfitPips();

            // Assert
            Assert.AreEqual(pips, actualPips);
        }
コード例 #22
0
        public void ImmediateFillModelDoesNotUseTicksWhenThereIsNoTickSubscription()
        {
            var noon       = new DateTime(2014, 6, 24, 12, 0, 0);
            var timeKeeper = new TimeKeeper(noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork });
            var symbol     = Symbol.Create("SPY", SecurityType.Equity, Market.USA);
            // Minute subscription
            var config   = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, noon, 101.123m));


            // This is the case when a tick is seeded with minute data in an algorithm
            security.Cache.AddData(new TradeBar(DateTime.MinValue, symbol, 1.0m, 1.0m, 1.0m, 1.0m, 1.0m));
            security.Cache.AddData(new Tick(config, "42525000,1000000,100,A,@,0", DateTime.MinValue));

            var fillModel = new ImmediateFillModel();
            var order     = new MarketOrder(symbol, 1000, DateTime.Now);
            var fill      = fillModel.Fill(new FillModelParameters(
                                               security,
                                               order,
                                               new MockSubscriptionDataConfigProvider(config),
                                               Time.OneHour)).OrderEvent;

            // The fill model should use the tick.Price
            Assert.AreEqual(fill.FillPrice, 1.0m);
            Assert.AreEqual(0, fill.OrderFee.Value.Amount);
        }
コード例 #23
0
 /// <summary>
 /// Add a new security with this symbol to the collection.
 /// </summary>
 /// <remarks>IDictionary implementation</remarks>
 /// <param name="symbol">symbol for security we're trading</param>
 /// <param name="security">security object</param>
 /// <seealso cref="Add(Security)"/>
 public void Add(Symbol symbol, Security security)
 {
     if (_securityManager.TryAdd(symbol, security))
     {
         security.SetLocalTimeKeeper(_timeKeeper.GetLocalTimeKeeper(security.Exchange.TimeZone));
         OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, security));
     }
 }
コード例 #24
0
        private static Security CreateSecurity(DateTime newLocalTime)
        {
            var security = new Security(CreateUsEquitySecurityExchangeHours(), CreateTradeBarConfig(), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency));

            security.Exchange.SetLocalDateTimeFrontier(newLocalTime);
            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, newLocalTime, 100m));
            return(security);
        }
コード例 #25
0
        public void StopLimitOrderDoesNotFillUsingDataBeforeSubmitTime(decimal orderQuantity, decimal stopPrice, decimal limitPrice)
        {
            var time       = new DateTime(2018, 9, 24, 9, 30, 0);
            var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork);
            var symbol     = Symbol.Create("SPY", SecurityType.Equity, Market.USA);

            var config   = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var security = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                config,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345);

            security.SetMarketPrice(tradeBar);

            time += TimeSpan.FromMinutes(1);
            timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));

            var fillForwardBar = (TradeBar)tradeBar.Clone(true);

            security.SetMarketPrice(fillForwardBar);

            var fillModel = new ImmediateFillModel();
            var order     = new StopLimitOrder(symbol, orderQuantity, stopPrice, limitPrice, time.ConvertToUtc(TimeZones.NewYork));

            var fill = fillModel.Fill(new FillModelParameters(
                                          security,
                                          order,
                                          new MockSubscriptionDataConfigProvider(config),
                                          Time.OneHour)).OrderEvent;

            Assert.AreEqual(0, fill.FillQuantity);
            Assert.AreEqual(0, fill.FillPrice);
            Assert.AreEqual(OrderStatus.None, fill.Status);

            time += TimeSpan.FromMinutes(1);
            timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork));

            tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345);
            security.SetMarketPrice(tradeBar);

            fill = fillModel.StopLimitFill(security, order);

            Assert.AreEqual(orderQuantity, fill.FillQuantity);
            Assert.AreEqual(limitPrice, fill.FillPrice);
            Assert.AreEqual(OrderStatus.Filled, fill.Status);
            Assert.AreEqual(0, fill.OrderFee.Value.Amount);
        }
コード例 #26
0
        public void SetUp()
        {
            _security     = SecurityTests.GetSecurity();
            orderDateTime = new DateTime(2017, 2, 2, 13, 0, 0);
            var reference    = DateTime.Now;
            var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var timeKeeper   = new TimeKeeper(referenceUtc);

            _security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
        }
コード例 #27
0
        public void DoesntUpdateOnZeroPrice()
        {
            const int periods      = 3;
            var       reference    = new DateTime(2016, 04, 06, 12, 0, 0);
            var       referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var       timeKeeper   = new TimeKeeper(referenceUtc);
            var       config       = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            var       security     = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                config,
                new Cash(Currencies.USD, 0, 0),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var model = new StandardDeviationOfReturnsVolatilityModel(periods);

            security.VolatilityModel = model;

            var first = new IndicatorDataPoint(reference, 1);

            security.SetMarketPrice(first);

            Assert.AreEqual(0m, model.Volatility);

            var second = new IndicatorDataPoint(reference.AddDays(1), 2);

            security.SetMarketPrice(second);
            Assert.AreEqual(0, model.Volatility);

            // update should not be applied since not enough time has passed
            var third = new IndicatorDataPoint(reference.AddDays(1.01), 1000);

            security.SetMarketPrice(third);
            Assert.AreEqual(0, model.Volatility);

            var fourth = new IndicatorDataPoint(reference.AddDays(2), 3);

            security.SetMarketPrice(fourth);
            Assert.AreEqual(5.6124, (double)model.Volatility, 0.0001);

            // update should not be applied as price is 0
            var fifth = new IndicatorDataPoint(reference.AddDays(3), 0m);

            security.SetMarketPrice(fifth);
            Assert.AreEqual(5.6124, (double)model.Volatility, 0.0001);
        }
コード例 #28
0
        public void TestMarginForSymbolWithHistory()
        {
            const decimal price   = 1.2345m;
            var           time    = new DateTime(2013, 1, 1);
            var           expDate = new DateTime(2017, 1, 1);
            var           tz      = TimeZones.NewYork;

            // For this symbol we dont have history
            var ticker = QuantConnect.Securities.Futures.Financials.EuroDollar;
            var symbol = Symbol.CreateFuture(ticker, Market.CME, expDate);

            var futureSecurity = new Future(
                SecurityExchangeHours.AlwaysOpen(tz),
                new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, tz, tz, true, false, false),
                new Cash(Currencies.USD, 0, 1m),
                new OptionSymbolProperties(SymbolProperties.GetDefault(Currencies.USD)),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null
                );

            futureSecurity.SetMarketPrice(new Tick {
                Value = price, Time = time
            });
            futureSecurity.Holdings.SetHoldings(1.5m, 1);
            futureSecurity.BuyingPowerModel = new FutureMarginModel(security: futureSecurity);
            var timeKeeper = new TimeKeeper(time.ConvertToUtc(tz));

            futureSecurity.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(tz));

            var buyingPowerModel = GetModel(futureSecurity, out _futureMarginModel, timeKeeper: timeKeeper);

            Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement,
                            buyingPowerModel.GetMaintenanceMargin(futureSecurity));

            // now we move forward to exact date when margin req changed
            time = new DateTime(2014, 06, 13);
            timeKeeper.SetUtcDateTime(time.ConvertToUtc(tz));
            futureSecurity.SetMarketPrice(new Tick {
                Value = price, Time = time
            });
            Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));

            // now we fly beyond the last line of the history file (currently) to see how margin model resolves future dates
            time = new DateTime(2016, 06, 04);
            timeKeeper.SetUtcDateTime(time.ConvertToUtc(tz));
            futureSecurity.SetMarketPrice(new Tick {
                Value = price, Time = time
            });
            Assert.AreEqual(_futureMarginModel.MaintenanceOvernightMarginRequirement, buyingPowerModel.GetMaintenanceMargin(futureSecurity));
        }
コード例 #29
0
        /// <summary>
        /// Sets the time zone of the <see cref="Time"/> property in the algorithm
        /// </summary>
        /// <param name="timeZone">The desired time zone</param>
        public void SetTimeZone(DateTimeZone timeZone)
        {
            if (_locked)
            {
                throw new Exception("Algorithm.SetTimeZone(): Cannot change time zone after algorithm running.");
            }

            if (timeZone == null)
            {
                throw new ArgumentNullException("timeZone");
            }
            _timeKeeper.AddTimeZone(timeZone);
            _localTimeKeeper = _timeKeeper.GetLocalTimeKeeper(timeZone);
        }
コード例 #30
0
        public void LocalTimeKeepersGetTimeUpdates()
        {
            var reference       = new DateTime(2000, 01, 01);
            var timeKeeper      = new TimeKeeper(reference, new[] { TimeZones.NewYork });
            var localTimeKeeper = timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);
            var localTime       = localTimeKeeper.LocalTime;

            timeKeeper.SetUtcDateTime(reference.AddDays(1));

            Assert.AreEqual(localTime.AddDays(1), localTimeKeeper.LocalTime);

            timeKeeper.SetUtcDateTime(reference.AddDays(2));

            Assert.AreEqual(localTime.AddDays(2), localTimeKeeper.LocalTime);
        }
コード例 #31
0
ファイル: TimeKeeperTests.cs プロジェクト: skyfyl/Lean
        public void LocalTimeKeepersGetTimeUpdates()
        {
            var reference = new DateTime(2000, 01, 01);
            var timeKeeper = new TimeKeeper(reference, new[] { TimeZones.NewYork });
            var localTimeKeeper = timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork);
            var localTime = localTimeKeeper.LocalTime;

            timeKeeper.SetUtcDateTime(reference.AddDays(1));

            Assert.AreEqual(localTime.AddDays(1), localTimeKeeper.LocalTime);

            timeKeeper.SetUtcDateTime(reference.AddDays(2));

            Assert.AreEqual(localTime.AddDays(2), localTimeKeeper.LocalTime);
        }
コード例 #32
0
        public void PerformsMarketFillBuy()
        {
            var model    = new ForexTransactionModel();
            var security = CreateSecurity();
            var order    = new MarketOrder(Symbols.USDJPY, 100, DateTime.Now, type: SecurityType.Forex);

            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.USDJPY, DateTime.Now, 101.123m));

            var fill = model.MarketFill(security, order);

            var slip = model.GetSlippageApproximation(security, order);

            Assert.AreEqual(order.Quantity, fill.FillQuantity);
            Assert.AreEqual(security.Price + slip, fill.FillPrice);
            Assert.AreEqual(OrderStatus.Filled, fill.Status);
        }
コード例 #33
0
        private static Security CreateSecurity(DateTime newLocalTime)
        {
            var security = new Security(
                CreateUsEquitySecurityExchangeHours(),
                CreateTradeBarConfig(),
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance
                );

            TimeKeeper.SetUtcDateTime(newLocalTime.ConvertToUtc(security.Exchange.TimeZone));
            security.Exchange.SetLocalDateTimeFrontier(newLocalTime);
            security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
            security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, newLocalTime, 100m));
            return(security);
        }
コード例 #34
0
        public void PriceReturnsQuoteBarsIfPresent(OrderDirection orderDirection, decimal expected)
        {
            var time       = new DateTime(2018, 9, 24, 9, 30, 0);
            var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork);
            var symbol     = Symbol.Create("SPY", SecurityType.Equity, Market.USA);

            var configTradeBar = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false);
            var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar));
            var security       = new Security(
                SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(),
                configQuoteBar,
                new Cash(Currencies.USD, 0, 1m),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345);

            security.SetMarketPrice(tradeBar);

            var quoteBar = new QuoteBar(time, symbol,
                                        new Bar(10, 15, 5, 11),
                                        100,
                                        new Bar(20, 25, 15, 21),
                                        100);

            security.SetMarketPrice(quoteBar);

            var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar);

            configProvider.SubscriptionDataConfigs.Add(configTradeBar);

            var testFillModel = new TestFillModel();

            testFillModel.SetParameters(new FillModelParameters(security,
                                                                null,
                                                                configProvider,
                                                                TimeSpan.FromDays(1)));

            var result = testFillModel.GetPricesPublic(security, orderDirection);

            Assert.AreEqual(expected, result.Close);
        }
コード例 #35
0
        public void DoesntUpdateOnZeroPrice()
        {
            const int periods      = 3;
            var       periodSpan   = Time.OneMinute;
            var       reference    = new DateTime(2016, 04, 06, 12, 0, 0);
            var       referenceUtc = reference.ConvertToUtc(TimeZones.NewYork);
            var       timeKeeper   = new TimeKeeper(referenceUtc);
            var       config       = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, false, false);
            var       security     = new Security(
                SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork),
                config,
                new Cash(Currencies.USD, 0, 0),
                SymbolProperties.GetDefault(Currencies.USD),
                ErrorCurrencyConverter.Instance,
                RegisteredSecurityDataTypesProvider.Null,
                new SecurityCache()
                );

            security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));

            var model = new RelativeStandardDeviationVolatilityModel(periodSpan, periods);

            security.VolatilityModel = model;

            var first = new IndicatorDataPoint(reference, 1);

            security.SetMarketPrice(first);

            Assert.AreEqual(0m, model.Volatility);

            const decimal value  = 0.471404520791032M; // std of 1,2 is ~0.707 over a mean of 1.5
            var           second = new IndicatorDataPoint(reference.AddMinutes(1), 2);

            security.SetMarketPrice(second);
            Assert.AreEqual(value, model.Volatility);

            var third = new IndicatorDataPoint(reference.AddMinutes(2), 3m);

            security.SetMarketPrice(third);
            Assert.AreEqual(0.5m, model.Volatility);

            // update should not be applied as price is 0
            var forth = new IndicatorDataPoint(reference.AddMinutes(3), 0m);

            security.SetMarketPrice(forth);
            Assert.AreEqual(0.5m, model.Volatility);
        }
コード例 #36
0
ファイル: TimeKeeperTests.cs プロジェクト: skyfyl/Lean
 public void ConstructsLocalTimeKeepers()
 {
     var reference = new DateTime(2000, 01, 01);
     var timeKeeper = new TimeKeeper(reference, new[] { TimeZones.NewYork });
     Assert.IsNotNull(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork));
 }