public void DefaultDataFeeds_CanBeOverwritten_Successfully()
        {
            Config.Set("security-data-feeds", "{ Forex: [\"Trade\"] }");
            var algo = new QCAlgorithm();

            // forex defult - should be tradebar
            var forexTrade = algo.AddForex("EURUSD");

            Assert.IsTrue(forexTrade.Subscriptions.Count() == 1);
            Assert.IsTrue(GetMatchingSubscription(forexTrade, typeof(QuoteBar)) != null);

            // Change
            var dataFeedsConfigString = Config.Get("security-data-feeds");
            Dictionary <SecurityType, List <TickType> > dataFeeds = new Dictionary <SecurityType, List <TickType> >();

            if (dataFeedsConfigString != string.Empty)
            {
                dataFeeds = JsonConvert.DeserializeObject <Dictionary <SecurityType, List <TickType> > >(dataFeedsConfigString);
            }

            algo.SetAvailableDataTypes(dataFeeds);

            // new forex - should be quotebar
            var forexQuote = algo.AddForex("EURUSD");

            Assert.IsTrue(forexQuote.Subscriptions.Count() == 1);
            Assert.IsTrue(GetMatchingSubscription(forexQuote, typeof(TradeBar)) != null);
        }
Ejemplo n.º 2
0
        public void DuplicateSecuritiesAreNotAllowed()
        {
            var algorithm = new QCAlgorithm();

            algorithm.AddForex("EURUSD");

            Assert.Throws <Exception>(() => algorithm.AddForex("EURUSD"));
        }
Ejemplo n.º 3
0
        public void DefaultBrokerageModel_IsOanda_ForForex()
        {
            var forex = _algo.AddForex(ForexSym);


            Assert.IsTrue(forex.Symbol.ID.Market == Market.Oanda);
            Assert.IsTrue(_algo.BrokerageModel.GetType() == typeof(DefaultBrokerageModel));
        }
        public void LotSizeIsRespected(Language language, int side)
        {
            var actualOrdersSubmitted = new List <SubmitOrderRequest>();

            var algorithm = new QCAlgorithm();

            algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
            algorithm.SetPandasConverter();

            var security = algorithm.AddForex(Symbols.EURUSD.Value);

            algorithm.Portfolio.SetCash("EUR", 1, 1);
            security.SetMarketPrice(new TradeBar {
                Value = 250
            });

            algorithm.SetFinishedWarmingUp();

            var orderProcessor = new Mock <IOrderProcessor>();

            orderProcessor.Setup(m => m.Process(It.IsAny <SubmitOrderRequest>()))
            .Returns((SubmitOrderRequest request) => new OrderTicket(algorithm.Transactions, request))
            .Callback((OrderRequest request) => actualOrdersSubmitted.Add((SubmitOrderRequest)request));
            algorithm.Transactions.SetOrderProcessor(orderProcessor.Object);

            var model = GetExecutionModel(language);

            algorithm.SetExecution(model);

            model.Execute(algorithm,
                          new IPortfolioTarget[] { new PortfolioTarget(Symbols.EURUSD, security.SymbolProperties.LotSize * 1.5m * side) });

            Assert.AreEqual(1, actualOrdersSubmitted.Count);
            Assert.AreEqual(security.SymbolProperties.LotSize * side, actualOrdersSubmitted.Single().Quantity);
        }
Ejemplo n.º 5
0
        public override void Initialize()
        {
            SetStartDate(2014, 5, 7);  //Set Start Date
            SetEndDate(2014, 5, 15);   //Set End Date
            SetCash(100000);           //Set Strategy Cash
            // Find more symbols here: http://quantconnect.com/data
            //AddForex("EURUSD", Resolution.Minute);
            //AddForex("EURUSD", Resolution.Minute);

            //var dailyHistory = History(5, Resolution.Daily);
            //var hourHistory = History(5, Resolution.Hour);
            //var minuteHistory = History(5, Resolution.Minute);
            //var secondHistory = History(5, Resolution.Second);
            algorithm = new QCAlgorithm();
            //algorithm.Initialize();


            // new forex - should be quotebar
            algorithm.SubscriptionManager = SubscriptionManager;
            //algorithm.Securities.SetSecurityService(Securities.SetSecurityService);
            var symbolPropertiesDatabase = SymbolPropertiesDatabase.FromDataFolder();
            //var mapFilePrimaryExchangeProvider = new MapFilePrimaryExchangeProvider(AlgorithmHandlers.MapFileProvider);
            var registeredTypesProvider = new RegisteredSecurityDataTypesProvider();

            Type      typSecurityManager        = typeof(SecurityManager);
            FieldInfo typeAccessSecurityManager = typSecurityManager.GetField("_securityService", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            var       sm = (SecurityService)typeAccessSecurityManager.GetValue(Securities);


            // Type typSecurityService = typeof(SecurityService);
            // FieldInfo typeAccessSecurityService = typSecurityService.GetField("_primaryExchangeProvider", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            // var ss = typeAccessSecurityService.GetValue(sm);

            //algorithm.Securities.SetSecurityService(sm);
            algorithm.Securities           = Securities;
            algorithm.Portfolio.Securities = Securities;


            /*
             * var securityService = new SecurityService(algorithm.Portfolio.CashBook,
             *  marketHoursDatabase,
             *  symbolPropertiesDatabase,
             *  algorithm,
             *  registeredTypesProvider,
             *  new SecurityCacheProvider(algorithm.Portfolio),
             *  mapFilePrimaryExchangeProvider);*/

            AddForex("EURUSD", Resolution.Minute);
            var forexQuote = algorithm.AddForex("EURUSD", Resolution.Minute);

            // Assert.IsTrue(forexQuote.Subscriptions.Count() == 1);
            // Assert.IsTrue(GetMatchingSubscription(forexQuote, typeof(TradeBar)) != null);
            algorithm.Transactions.SetOrderProcessor(new BacktestingTransactionHandler());
            algorithm.Portfolio.Transactions = algorithm.Transactions;
            algorithm.PostInitialize();
        }
Ejemplo n.º 6
0
        public void QuoteBarToQuoteBar()
        {
            var algorithm    = new QCAlgorithm();
            var security     = algorithm.AddForex("EURUSD");
            var consolidator = algorithm.ResolveConsolidator("EURUSD", Resolution.Minute);

            var inputType  = security.SubscriptionDataConfig.Type;
            var outputType = consolidator.OutputType;

            Assert.AreEqual(inputType, outputType);
        }
Ejemplo n.º 7
0
        public void TickTypeQuoteToQuoteBar()
        {
            var algorithm    = new QCAlgorithm();
            var security     = algorithm.AddForex("EURUSD", Resolution.Tick);
            var consolidator = algorithm.ResolveConsolidator("EURUSD", Resolution.Minute);

            var tickType   = security.SubscriptionDataConfig.TickType;
            var outputType = consolidator.OutputType;

            Assert.AreEqual(TickType.Quote, tickType);
            Assert.AreEqual(typeof(QuoteBar), outputType);
        }
Ejemplo n.º 8
0
        public void Validates_SetBrokerageModel_IB_AddForex()
        {
            var algorithm = new QCAlgorithm();

            algorithm.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage);
            var security = algorithm.AddForex(Ticker, Resolution, Market);

            // Leverage and FeeModel from BrokerageModel
            Assert.AreEqual(50, Math.Round(security.Leverage, RoundingPrecision));
            Assert.IsInstanceOf(typeof(InteractiveBrokersFeeModel), security.FeeModel);
            Assert.AreEqual(2, security.FeeModel.GetOrderFee(security, _order));
        }
Ejemplo n.º 9
0
        public void Validates_SetBrokerageModel_AddForexWithLeverage()
        {
            var algorithm = new QCAlgorithm();

            algorithm.SetBrokerageModel(BrokerageName);
            var security = algorithm.AddForex(Ticker, Resolution, Market, true, 25);

            // Leverage passed to AddForex always takes precedence
            // Leverage from AddForex, FeeModel from BrokerageModel
            Assert.AreEqual(25, Math.Round(security.Leverage, RoundingPrecision));
            Assert.IsInstanceOf(typeof(FxcmFeeModel), security.FeeModel);
            Assert.AreEqual(0.04, security.FeeModel.GetOrderFee(security, _order));
        }
Ejemplo n.º 10
0
        public void TickTypeQuoteToTick()
        {
            var algorithm = new QCAlgorithm();

            algorithm.SubscriptionManager.SetDataManager(new DataManagerStub());
            var security     = algorithm.AddForex("EURUSD", Resolution.Tick);
            var consolidator = algorithm.ResolveConsolidator("EURUSD", Resolution.Tick);

            var tickType   = security.SubscriptionDataConfig.TickType;
            var inputType  = security.SubscriptionDataConfig.Type;
            var outputType = consolidator.OutputType;

            Assert.AreEqual(TickType.Quote, tickType);
            Assert.AreEqual(inputType, outputType);
        }
Ejemplo n.º 11
0
        public void TickTypeQuoteToQuoteBar()
        {
            var algorithm = new QCAlgorithm();

            algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm));
            var security     = algorithm.AddForex("EURUSD", Resolution.Tick);
            var consolidator = algorithm.ResolveConsolidator("EURUSD", Resolution.Minute);

            var tickType = security.Subscriptions.Single(s => s.TickType == LeanData.GetCommonTickType(SecurityType.Forex)).TickType;

            var outputType = consolidator.OutputType;

            Assert.AreEqual(TickType.Quote, tickType);
            Assert.AreEqual(typeof(QuoteBar), outputType);
        }
Ejemplo n.º 12
0
        public void Validates_SetSecurityInitializer_AddForex()
        {
            var algorithm = new QCAlgorithm();

            algorithm.SetSecurityInitializer(x =>
            {
                x.SetLeverage(100);
                x.FeeModel = new InteractiveBrokersFeeModel();
            });
            var security = algorithm.AddForex(Ticker, Resolution, Market);

            // Leverage and FeeModel from SecurityInitializer
            Assert.AreEqual(100, Math.Round(security.Leverage, RoundingPrecision));
            Assert.IsInstanceOf(typeof(InteractiveBrokersFeeModel), security.FeeModel);
            Assert.AreEqual(2, security.FeeModel.GetOrderFee(security, _order));
        }
Ejemplo n.º 13
0
        public void Validates_AddForex_SetSecurityInitializer()
        {
            var algorithm = new QCAlgorithm();

            var security = algorithm.AddForex(Ticker, Resolution, Market);

            algorithm.SetSecurityInitializer(x =>
            {
                x.SetLeverage(100);
                x.FeeModel = new InteractiveBrokersFeeModel();
            });

            // SetSecurityInitializer does not apply to securities added before the call
            // Leverage and FeeModel from DefaultBrokerageModel
            Assert.AreEqual(50, Math.Round(security.Leverage, RoundingPrecision));
            Assert.IsInstanceOf(typeof(ConstantFeeModel), security.FeeModel);
            Assert.AreEqual(0, security.FeeModel.GetOrderFee(security, _order));
        }
Ejemplo n.º 14
0
        public void Validates_AddForexWithLeverage_SetSecurityInitializer_SetBrokerageModel()
        {
            var algorithm = new QCAlgorithm();

            var security = algorithm.AddForex(Ticker, Resolution, Market, true, 25);

            algorithm.SetSecurityInitializer(x =>
            {
                x.SetLeverage(100);
                x.FeeModel = new InteractiveBrokersFeeModel();
            });
            algorithm.SetBrokerageModel(BrokerageName);

            // Leverage passed to AddForex always takes precedence
            // Leverage from AddForex, FeeModel from DefaultBrokerageModel
            Assert.AreEqual(25, Math.Round(security.Leverage, RoundingPrecision));
            Assert.IsInstanceOf(typeof(ConstantFeeModel), security.FeeModel);
            Assert.AreEqual(0, security.FeeModel.GetOrderFee(security, _order));
        }
Ejemplo n.º 15
0
        public void AddDataSecurityTickerNoUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped)
        {
            SymbolCache.Clear();
            var qcAlgorithm = new QCAlgorithm();

            qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));

            Security asset;

            switch (securityType)
            {
            case SecurityType.Cfd:
                asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily);
                break;

            case SecurityType.Crypto:
                asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily);
                break;

            case SecurityType.Equity:
                asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily);
                break;

            case SecurityType.Forex:
                asset = qcAlgorithm.AddForex(ticker, Resolution.Daily);
                break;

            case SecurityType.Future:
                asset = qcAlgorithm.AddFuture(ticker, Resolution.Daily);
                break;

            default:
                throw new Exception($"SecurityType {securityType} is not valid for this test");
            }

            // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
            // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
            // This covers the case where two idential data subscriptions are created.
            var dummy      = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
            var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);

            // Check to see if we have an underlying symbol when we shouldn't
            Assert.IsFalse(customData.Symbol.HasUnderlying, $"{customDataType.Name} has underlying symbol for SecurityType {securityType} with ticker {ticker}");
            Assert.AreEqual(customData.Symbol.Underlying, null, $"{customDataType.Name} - Custom data underlying Symbol for SecurityType {securityType} is not null");

            var assetSubscription      = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First();
            var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();

            var assetShouldBeMapped  = assetSubscription.TickerShouldBeMapped();
            var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped();

            Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped);
            Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped);

            Assert.AreNotEqual(assetSubscription, customDataSubscription);

            if (assetShouldBeMapped == customShouldBeMapped)
            {
                // Would fail with CL future without this check because MappedSymbol returns "/CL" for the Future symbol
                if (assetSubscription.SecurityType == SecurityType.Future)
                {
                    Assert.AreNotEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
                    Assert.AreNotEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
                }
                else
                {
                    Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
                    Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
                }
            }
        }
Ejemplo n.º 16
0
        public void AddDataSecurityTickerWithUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped)
        {
            SymbolCache.Clear();
            var qcAlgorithm = new QCAlgorithm();

            qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm));

            Security asset;

            switch (securityType)
            {
            case SecurityType.Cfd:
                asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily);
                break;

            case SecurityType.Crypto:
                asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily);
                break;

            case SecurityType.Equity:
                asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily);
                break;

            case SecurityType.Forex:
                asset = qcAlgorithm.AddForex(ticker, Resolution.Daily);
                break;

            case SecurityType.Future:
                asset = qcAlgorithm.AddFuture(ticker, Resolution.Daily);
                break;

            default:
                throw new Exception($"SecurityType {securityType} is not valid for this test");
            }

            // Aliased value for Futures contains a forward-slash, which causes the
            // lookup in the SymbolCache to fail
            if (securityType == SecurityType.Future)
            {
                ticker = asset.Symbol.Value;
            }

            // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority
            // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it.
            // This covers the case where two idential data subscriptions are created.
            var dummy      = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);
            var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone);

            Assert.IsTrue(customData.Symbol.HasUnderlying, $"Custom data added as {ticker} Symbol with SecurityType {securityType} does not have underlying");
            Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol, $"Custom data underlying does not match {securityType} Symbol for {ticker}");

            var assetSubscription      = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First();
            var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single();

            var assetShouldBeMapped  = assetSubscription.TickerShouldBeMapped();
            var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped();

            if (securityType == SecurityType.Equity)
            {
                Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped);
                Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped);

                Assert.AreNotEqual(assetSubscription, customDataSubscription);

                if (assetShouldBeMapped == customShouldBeMapped)
                {
                    Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol);
                    Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First());
                }
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Creates and adds a new <see cref="Forex"/> security to the algorithm
 /// </summary>
 /// <param name="ticker">The currency pair</param>
 /// <param name="resolution">The <see cref="Resolution"/> of market data, Tick, Second, Minute, Hour, or Daily. Default is <see cref="Resolution.Minute"/></param>
 /// <param name="market">The foreign exchange trading market, <seealso cref="Market"/>. Default value is null and looked up using BrokerageModel.DefaultMarkets in <see cref="AddSecurity{T}"/></param>
 /// <param name="fillDataForward">If true, returns the last available data even if none in that timeslice. Default is <value>true</value></param>
 /// <param name="leverage">The requested leverage for this equity. Default is set by <see cref="SecurityInitializer"/></param>
 /// <returns>The new <see cref="Forex"/> security</returns>
 public Forex AddForex(string ticker, Resolution resolution = Resolution.Minute, string market = null, bool fillDataForward = true, decimal leverage = 0m)
 {
     return(_algorithm.AddForex(ticker, resolution, market, fillDataForward, leverage));
 }