Ejemplo n.º 1
0
        /// <summary>
        /// Get an instance of the data feed handler we're requesting for this work.
        /// </summary>
        /// <param name="job">Algorithm Node Packet</param>
        /// <returns>Class Matching IResultHandler Inteface</returns>
        private static IResultHandler GetResultHandler(AlgorithmNodePacket job)
        {
            var rh = default(IResultHandler);

            if (IsLocal)
            {
                return(new ConsoleResultHandler(job));
            }

            switch (job.ResultEndpoint)
            {
            //Local backtesting and live trading result handler route messages to the local console.
            case ResultHandlerEndpoint.Console:
                Log.Trace("Engine.GetResultHandler(): Selected Console Output.");
                rh = new ConsoleResultHandler((BacktestNodePacket)job);
                break;

            // Backtesting route messages to user browser.
            case ResultHandlerEndpoint.Backtesting:
                Log.Trace("Engine.GetResultHandler(): Selected Backtesting API Result Endpoint.");
                rh = new BacktestingResultHandler((BacktestNodePacket)job);
                break;

            // Live trading route messages to user's browser.
            case ResultHandlerEndpoint.LiveTrading:
                Log.Trace("Engine.GetResultHandler(): Selected Live Trading API Result Endpoint.");
                rh = new LiveTradingResultHandler((LiveNodePacket)job);
                break;
            }
            return(rh);
        }
Ejemplo n.º 2
0
        public void AppliesDividendsOnce()
        {
            // init algorithm
            var algorithm = new AlgorithmStub();

            algorithm.SetLiveMode(true);
            var dividend    = new Dividend(Symbols.SPY, DateTime.UtcNow, 10m, 100m);
            var feed        = new TestDividendDataFeed(algorithm, dividend);
            var dataManager = new DataManager(feed, new UniverseSelection(feed, algorithm), algorithm.Settings, algorithm.TimeKeeper);

            algorithm.SubscriptionManager.SetDataManager(dataManager);
            algorithm.AddSecurities(equities: new List <string> {
                "SPY"
            });
            algorithm.Securities[Symbols.SPY].Holdings.SetHoldings(100m, 1);
            algorithm.PostInitialize();

            var initializedCash = algorithm.Portfolio.CashBook["USD"].Amount;

            // init algorithm manager
            var manager = new AlgorithmManager(true);
            var job     = new LiveNodePacket
            {
                UserId    = 1,
                ProjectId = 2,
                DeployId  = $"{nameof(PaperBrokerageTests)}.{nameof(AppliesDividendsOnce)}"
            };
            var results      = new LiveTradingResultHandler();
            var transactions = new BacktestingTransactionHandler();
            var brokerage    = new PaperBrokerage(algorithm, job);

            // initialize results and transactions
            results.Initialize(job, new EventMessagingHandler(), new Api.Api(), feed, new BrokerageSetupHandler(), transactions);
            results.SetAlgorithm(algorithm);
            transactions.Initialize(algorithm, brokerage, results);

            // run algorithm manager
            manager.Run(job,
                        algorithm,
                        dataManager,
                        transactions,
                        results,
                        new BacktestingRealTimeHandler(),
                        new AlgorithmManagerTests.NullLeanManager(),
                        new AlgorithmManagerTests.NullAlphaHandler(),
                        new CancellationToken()
                        );

            var postDividendCash = algorithm.Portfolio.CashBook["USD"].Amount;

            Assert.AreEqual(initializedCash + dividend.Distribution, postDividendCash);
        }
        public void DailySampleValueBasedOnMarketHour(bool extendedMarketHoursEnabled)
        {
            var referenceDate = new DateTime(2020, 11, 25);
            var resultHandler = new LiveTradingResultHandler();

            resultHandler.Initialize(new LiveNodePacket(),
                                     new QuantConnect.Messaging.Messaging(),
                                     new Api.Api(),
                                     new BacktestingTransactionHandler());

            var algo = new AlgorithmStub(createDataManager: false);

            algo.SetFinishedWarmingUp();
            var dataManager = new DataManagerStub(new TestDataFeed(), algo);

            algo.SubscriptionManager.SetDataManager(dataManager);
            var aapl = algo.AddEquity("AAPL", extendedMarketHours: extendedMarketHoursEnabled);

            algo.PostInitialize();
            resultHandler.SetAlgorithm(algo, 100000);
            resultHandler.OnSecuritiesChanged(SecurityChangesTests.AddedNonInternal(aapl));

            // Add values during market hours, should always update
            algo.Portfolio.CashBook["USD"].AddAmount(1000);
            algo.Portfolio.InvalidateTotalPortfolioValue();

            resultHandler.Sample(referenceDate.AddHours(15));
            Assert.IsTrue(resultHandler.Charts.ContainsKey("Strategy Equity"));
            Assert.AreEqual(1, resultHandler.Charts["Strategy Equity"].Series["Equity"].Values.Count);

            var currentEquityValue = resultHandler.Charts["Strategy Equity"].Series["Equity"].Values.Last().y;

            Assert.AreEqual(101000, currentEquityValue);

            // Add value to portfolio, see if portfolio updates with new sample
            // will be changed to 'extendedMarketHoursEnabled' = true
            algo.Portfolio.CashBook["USD"].AddAmount(10000);
            algo.Portfolio.InvalidateTotalPortfolioValue();

            resultHandler.Sample(referenceDate.AddHours(22));
            Assert.AreEqual(2, resultHandler.Charts["Strategy Equity"].Series["Equity"].Values.Count);

            currentEquityValue = resultHandler.Charts["Strategy Equity"].Series["Equity"].Values.Last().y;
            Assert.AreEqual(extendedMarketHoursEnabled ? 111000 : 101000, currentEquityValue);

            resultHandler.Exit();
        }
Ejemplo n.º 4
0
        public void AppliesDividendsOnce()
        {
            // init algorithm
            var algorithm = new AlgorithmStub(new MockDataFeed());

            algorithm.SetLiveMode(true);
            var dividend = new Dividend(Symbols.SPY, DateTime.UtcNow, 10m, 100m);

            var feed = new MockDataFeed();

            var marketHoursDatabase      = MarketHoursDatabase.FromDataFolder();
            var symbolPropertiesDataBase = SymbolPropertiesDatabase.FromDataFolder();
            var dataPermissionManager    = new DataPermissionManager();
            var dataManager = new DataManager(feed,
                                              new UniverseSelection(
                                                  algorithm,
                                                  new SecurityService(algorithm.Portfolio.CashBook, marketHoursDatabase, symbolPropertiesDataBase, algorithm, RegisteredSecurityDataTypesProvider.Null, new SecurityCacheProvider(algorithm.Portfolio)),
                                                  dataPermissionManager,
                                                  new DefaultDataProvider()),
                                              algorithm,
                                              algorithm.TimeKeeper,
                                              marketHoursDatabase,
                                              true,
                                              RegisteredSecurityDataTypesProvider.Null,
                                              dataPermissionManager);
            var synchronizer = new NullSynchronizer(algorithm, dividend);

            algorithm.SubscriptionManager.SetDataManager(dataManager);
            algorithm.AddSecurities(equities: new List <string> {
                "SPY"
            });
            algorithm.Securities[Symbols.SPY].Holdings.SetHoldings(100m, 1);
            algorithm.PostInitialize();

            var initializedCash = algorithm.Portfolio.CashBook[Currencies.USD].Amount;

            // init algorithm manager
            var manager = new AlgorithmManager(true);
            var job     = new LiveNodePacket
            {
                UserId    = 1,
                ProjectId = 2,
                DeployId  = $"{nameof(PaperBrokerageTests)}.{nameof(AppliesDividendsOnce)}"
            };
            var results      = new LiveTradingResultHandler();
            var transactions = new BacktestingTransactionHandler();
            var brokerage    = new PaperBrokerage(algorithm, job);

            // initialize results and transactions
            results.Initialize(job, new EventMessagingHandler(), new Api.Api(), transactions);
            results.SetAlgorithm(algorithm, algorithm.Portfolio.TotalPortfolioValue);
            transactions.Initialize(algorithm, brokerage, results);

            var realTime = new BacktestingRealTimeHandler();

            // run algorithm manager
            manager.Run(job,
                        algorithm,
                        synchronizer,
                        transactions,
                        results,
                        realTime,
                        new AlgorithmManagerTests.NullLeanManager(),
                        new AlgorithmManagerTests.NullAlphaHandler(),
                        new CancellationToken()
                        );

            var postDividendCash = algorithm.Portfolio.CashBook[Currencies.USD].Amount;

            realTime.Exit();
            results.Exit();
            Assert.AreEqual(initializedCash + dividend.Distribution, postDividendCash);
        }