/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> /// <param name="seedSecurity">True to seed the security, false otherwise</param> public virtual void Initialize(Security security, bool seedSecurity) { // set leverage and models security.SetLeverage(_brokerageModel.GetLeverage(security)); security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security, _brokerageModel.AccountType); if (seedSecurity) { // Do not seed canonical symbols if (!security.Symbol.IsCanonical()) { BaseData seedData = _securitySeeder.GetSeedData(security); if (seedData != null) { security.SetMarketPrice(seedData); Log.Trace("BrokerageModelSecurityInitializer.Initialize(): Seeded security: " + seedData.Symbol.Value + ": " + seedData.Value); } else { Log.Trace("BrokerageModelSecurityInitializer.Initialize(): Unable to seed security: " + security.Symbol.Value); } } } }
/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> public virtual void Initialize(Security security) { // set leverage and models security.SetLeverage(_brokerageModel.GetLeverage(security)); security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security, _brokerageModel.AccountType); }
/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> public virtual void Initialize(Security security) { // set leverage and models security.SetLeverage(_brokerageModel.GetLeverage(security)); security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security); security.BuyingPowerModel = _brokerageModel.GetBuyingPowerModel(security); _securitySeeder.SeedSecurity(security); }
/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> public virtual void Initialize(Security security) { // Sets the security models security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security); security.BuyingPowerModel = _brokerageModel.GetBuyingPowerModel(security); // Sets the leverage after the buying power model. Otherwise we would set the leverage of the default model. security.SetLeverage(_brokerageModel.GetLeverage(security)); _securitySeeder.SeedSecurity(security); }
public void TestCashFills() { // this test asserts the portfolio behaves according to the Test_Cash algo, see TestData\CashTestingStrategy.csv // also "https://www.dropbox.com/s/oiliumoyqqj1ovl/2013-cash.csv?dl=1" const string fillsFile = "TestData\\test_cash_fills.xml"; const string equityFile = "TestData\\test_cash_equity.xml"; var fills = XDocument.Load(fillsFile).Descendants("OrderEvent").Select(x => new OrderEvent( x.Get<int>("OrderId"), SymbolMap[x.Get<string>("Symbol")], DateTime.MinValue, x.Get<OrderStatus>("Status"), x.Get<int>("FillQuantity") < 0 ? OrderDirection.Sell : x.Get<int>("FillQuantity") > 0 ? OrderDirection.Buy : OrderDirection.Hold, x.Get<decimal>("FillPrice"), x.Get<int>("FillQuantity"), 0m) ).ToList(); var equity = XDocument.Load(equityFile).Descendants("decimal") .Select(x => decimal.Parse(x.Value, CultureInfo.InvariantCulture)) .ToList(); Assert.AreEqual(fills.Count + 1, equity.Count); // we're going to process fills and very our equity after each fill var subscriptions = new SubscriptionManager(TimeKeeper); var securities = new SecurityManager(TimeKeeper); var security = new Security(SecurityExchangeHours, subscriptions.Add(CASH, Resolution.Daily, TimeZones.NewYork, TimeZones.NewYork), new Cash(CashBook.AccountCurrency, 0, 1m), SymbolProperties.GetDefault(CashBook.AccountCurrency)); security.SetLeverage(10m); securities.Add(CASH, security); var transactions = new SecurityTransactionManager(securities); var portfolio = new SecurityPortfolioManager(securities, transactions); portfolio.SetCash(equity[0]); for (int i = 0; i < fills.Count; i++) { // before processing the fill we must deduct the cost var fill = fills[i]; var time = DateTime.Today.AddDays(i); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // the value of 'CASH' increments for each fill, the original test algo did this monthly // the time doesn't really matter though security.SetMarketPrice(new IndicatorDataPoint(CASH, time, i + 1)); portfolio.ProcessFill(fill); Assert.AreEqual(equity[i + 1], portfolio.TotalPortfolioValue, "Failed on " + i); } }
/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> public virtual void Initialize(Security security) { // set leverage and models security.SetLeverage(_brokerageModel.GetLeverage(security)); security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security, _brokerageModel.AccountType); BaseData seedData = _securitySeeder.GetSeedData(security); if (seedData != null) { security.SetMarketPrice(seedData); } }
/// <summary> /// Initializes the specified security by setting up the models /// </summary> /// <param name="security">The security to be initialized</param> public virtual void Initialize(Security security) { // set leverage and models security.SetLeverage(_brokerageModel.GetLeverage(security)); security.FillModel = _brokerageModel.GetFillModel(security); security.FeeModel = _brokerageModel.GetFeeModel(security); security.SlippageModel = _brokerageModel.GetSlippageModel(security); security.SettlementModel = _brokerageModel.GetSettlementModel(security, _brokerageModel.AccountType); // Do not seed Options and Futures if (security.Symbol.SecurityType != SecurityType.Option && security.Symbol.SecurityType != SecurityType.Future) { BaseData seedData = _securitySeeder.GetSeedData(security); if (seedData != null) { security.SetMarketPrice(seedData); Log.Trace("BrokerageModelSecurityInitializer.Initialize(): Seeded security: " + seedData.Symbol.Value + ": " + seedData.Value); } else { Log.Trace("BrokerageModelSecurityInitializer.Initialize(): Unable to seed security: " + security.Symbol.Value); } } }
/// <summary> /// Creates a new security /// </summary> /// <remarks>Following the obsoletion of Security.Subscriptions, /// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks> public Security CreateSecurity(Symbol symbol, List <SubscriptionDataConfig> subscriptionDataConfigList, decimal leverage = 0, bool addToSymbolCache = true) { var configList = new SubscriptionDataConfigList(symbol); configList.AddRange(subscriptionDataConfigList); var exchangeHours = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours; var defaultQuoteCurrency = _cashBook.AccountCurrency; if (symbol.ID.SecurityType == SecurityType.Forex) { defaultQuoteCurrency = symbol.Value.Substring(3); } if (symbol.ID.SecurityType == SecurityType.Crypto && !_symbolPropertiesDatabase.ContainsKey(symbol.ID.Market, symbol, symbol.ID.SecurityType)) { throw new ArgumentException($"Symbol can't be found in the Symbol Properties Database: {symbol.Value}"); } // For Futures Options that don't have a SPDB entry, the futures entry will be used instead. var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties( symbol.ID.Market, symbol, symbol.SecurityType, defaultQuoteCurrency); // add the symbol to our cache if (addToSymbolCache) { SymbolCache.Set(symbol.Value, symbol); } // verify the cash book is in a ready state var quoteCurrency = symbolProperties.QuoteCurrency; if (!_cashBook.ContainsKey(quoteCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(quoteCurrency, 0, 0); } if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto) { // decompose the symbol into each currency pair string baseCurrency; if (symbol.ID.SecurityType == SecurityType.Forex) { Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency); } else { Crypto.Crypto.DecomposeCurrencyPair(symbol, symbolProperties, out baseCurrency, out quoteCurrency); } if (!_cashBook.ContainsKey(baseCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(baseCurrency, 0, 0); } if (!_cashBook.ContainsKey(quoteCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(quoteCurrency, 0, 0); } } var quoteCash = _cashBook[symbolProperties.QuoteCurrency]; var cache = _cacheProvider.GetSecurityCache(symbol); Security security; switch (symbol.ID.SecurityType) { case SecurityType.Equity: security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; case SecurityType.Option: if (addToSymbolCache) { SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying); } security = new Option.Option(symbol, exchangeHours, quoteCash, new Option.OptionSymbolProperties(symbolProperties), _cashBook, _registeredTypes, cache); break; case SecurityType.FutureOption: if (addToSymbolCache) { SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying); } var optionSymbolProperties = new Option.OptionSymbolProperties(symbolProperties); // Future options exercised only gives us one contract back, rather than the // 100x seen in equities. optionSymbolProperties.SetContractUnitOfTrade(1); security = new FutureOption.FutureOption(symbol, exchangeHours, quoteCash, optionSymbolProperties, _cashBook, _registeredTypes, cache); break; case SecurityType.Future: security = new Future.Future(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; case SecurityType.Forex: security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; case SecurityType.Cfd: security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; case SecurityType.Crypto: security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; default: case SecurityType.Base: security = new Security(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook, _registeredTypes, cache); break; } // if we're just creating this security and it only has an internal // feed, mark it as non-tradable since the user didn't request this data if (!configList.IsInternalFeed) { security.IsTradable = true; } security.AddData(configList); // invoke the security initializer _securityInitializerProvider.SecurityInitializer.Initialize(security); // if leverage was specified then apply to security after the initializer has run, parameters of this // method take precedence over the intializer if (leverage != Security.NullLeverage) { security.SetLeverage(leverage); } var isNotNormalized = configList.DataNormalizationMode() == DataNormalizationMode.Raw; // In live mode and non normalized data, equity assumes specific price variation model if ((_isLiveMode || isNotNormalized) && security.Type == SecurityType.Equity) { security.PriceVariationModel = new EquityPriceVariationModel(); } return(security); }
//[Test] //public void SetHoldings_LongToLonger_PriceRise() //{ // var algo = GetAlgorithm(); // //Set price to $25 // Update(msft, 25)); // //Half cash spent on 2000 MSFT shares. // algo.Portfolio.SetCash(50000); // algo.Portfolio[Symbols.MSFT].SetHoldings(25, 2000); // //Price rises to $50. // Update(msft, 50)); // //Now: 2000 * 50 = $100k Holdings, $50k Cash: $150k. MSFT is already 66% of holdings. // //Calculate the order for 75% MSFT: // var actual = algo.CalculateOrderQuantity(Symbols.MSFT, 0.75m); // //Need to buy to make position $112.5k == $12.5k / 50 = 250 shares // Assert.AreEqual(250, actual); //} //[Test] //public void SetHoldings_LongerToLong_PriceRise() //{ // var algo = GetAlgorithm(); // //Set price to $25 // Update(msft, 25)); // //75% cash spent on 3000 MSFT shares. // algo.Portfolio.SetCash(25000); // algo.Portfolio[Symbols.MSFT].SetHoldings(25, 3000); // //Price rises to $50. // Update(msft, 50)); // //Now: 3000 * 50 = $150k Holdings, $25k Cash: $175k. MSFT is 86% of holdings. // //Calculate the order for 50% MSFT: // var actual = algo.CalculateOrderQuantity(Symbols.MSFT, 0.5m); // //Need to sell to 50% = 87.5k target from $150k = 62.5 / $50-share = 1250 // Assert.AreEqual(-1250, actual); //} //[Test] //public void SetHoldings_LongToShort_PriceRise() //{ // var algo = GetAlgorithm(); // //Set price to $25 // Update(msft, 25)); // //Half cash spent on 2000 MSFT shares. // algo.Portfolio.SetCash(50000); // algo.Portfolio[Symbols.MSFT].SetHoldings(25, 2000); // //Price rises to $50. // Update(msft, 50)); // //Now: 2000 * 50 = $100k Holdings, $50k Cash: $150k. MSFT is 66% of holdings. // var actual = algo.CalculateOrderQuantity(Symbols.MSFT, -0.5m); // // Need to hold -75k from $100k = delta: $175k / $50-share = -3500 shares. // Assert.AreEqual(-3500, actual); //} //[Test] //public void SetHoldings_ShortToShorter_PriceRise() //{ // var algo = GetAlgorithm(); // //Set price to $25 // Update(msft, 25)); // //Half cash spent on -2000 MSFT shares. // algo.Portfolio.SetCash(50000); // algo.Portfolio[Symbols.MSFT].SetHoldings(25, -2000); // //Price rises to $50. // Update(msft, 50)); // //Now: 2000 * 50 = $0k Net Holdings, $50k Cash: $50k. MSFT is 0% of holdings. // var actual = algo.CalculateOrderQuantity(Symbols.MSFT, -0.75m); // //Want to hold -75% of MSFT: 50k total, -37.5k / $50-share = -750 TOTAL. // // Currently -2000, so net order +1250. // Assert.AreEqual(1250, actual); //} //[Test] //public void SetHoldings_ShortToLong_PriceRise() //{ // var algo = GetAlgorithm(); // //Set price to $25 // Update(msft, 25)); // //Half cash spent on -2000 MSFT shares. // algo.Portfolio.SetCash(50000); // algo.Portfolio[Symbols.MSFT].SetHoldings(25, -2000); // //Price rises to $50. // Update(msft, 50)); // //Now: 2000 * 50 = $0k Net Holdings, $50k Cash: $50k. MSFT is 0% of holdings. // var actual = algo.CalculateOrderQuantity(Symbols.MSFT, 0.5m); // //We want to be 50% long, this is currently +2000 holdings + 50% 50k = $25k/ $50-share=500 // Assert.AreEqual(2500, actual); //} private QCAlgorithm GetAlgorithm(out Security msft, decimal leverage, decimal fee) { //Initialize algorithm var algo = new QCAlgorithm(); algo.AddSecurity(SecurityType.Equity, "MSFT"); algo.SetCash(100000); algo.Securities[Symbols.MSFT].TransactionModel = new ConstantFeeTransactionModel(fee); msft = algo.Securities[Symbols.MSFT]; msft.SetLeverage(leverage); return algo; }
/// <summary> /// Creates a new security /// </summary> /// <remarks>Following the obsoletion of Security.Subscriptions, /// both overloads will be merged removing <see cref="SubscriptionDataConfig"/> arguments</remarks> public Security CreateSecurity(Symbol symbol, List <SubscriptionDataConfig> subscriptionDataConfigList, decimal leverage = 0, bool addToSymbolCache = true) { var configList = new SubscriptionDataConfigList(symbol); configList.AddRange(subscriptionDataConfigList); var exchangeHours = _marketHoursDatabase.GetEntry(symbol.ID.Market, symbol, symbol.ID.SecurityType).ExchangeHours; var defaultQuoteCurrency = _cashBook.AccountCurrency; if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto) { defaultQuoteCurrency = symbol.Value.Substring(3); } var symbolProperties = _symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol, symbol.ID.SecurityType, defaultQuoteCurrency); // add the symbol to our cache if (addToSymbolCache) { SymbolCache.Set(symbol.Value, symbol); } // verify the cash book is in a ready state var quoteCurrency = symbolProperties.QuoteCurrency; if (!_cashBook.ContainsKey(quoteCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(quoteCurrency, 0, 0); } if (symbol.ID.SecurityType == SecurityType.Forex || symbol.ID.SecurityType == SecurityType.Crypto) { // decompose the symbol into each currency pair string baseCurrency; Forex.Forex.DecomposeCurrencyPair(symbol.Value, out baseCurrency, out quoteCurrency); if (!_cashBook.ContainsKey(baseCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(baseCurrency, 0, 0); } if (!_cashBook.ContainsKey(quoteCurrency)) { // since we have none it's safe to say the conversion is zero _cashBook.Add(quoteCurrency, 0, 0); } } var quoteCash = _cashBook[symbolProperties.QuoteCurrency]; Security security; switch (symbol.ID.SecurityType) { case SecurityType.Equity: security = new Equity.Equity(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook); break; case SecurityType.Option: if (addToSymbolCache) { SymbolCache.Set(symbol.Underlying.Value, symbol.Underlying); } security = new Option.Option(symbol, exchangeHours, _cashBook[_cashBook.AccountCurrency], new Option.OptionSymbolProperties(symbolProperties), _cashBook); break; case SecurityType.Future: security = new Future.Future(symbol, exchangeHours, _cashBook[_cashBook.AccountCurrency], symbolProperties, _cashBook); break; case SecurityType.Forex: security = new Forex.Forex(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook); break; case SecurityType.Cfd: security = new Cfd.Cfd(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook); break; case SecurityType.Crypto: security = new Crypto.Crypto(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook); break; default: case SecurityType.Base: security = new Security(symbol, exchangeHours, quoteCash, symbolProperties, _cashBook); break; } // if we're just creating this security and it only has an internal // feed, mark it as non-tradable since the user didn't request this data if (!configList.IsInternalFeed) { security.IsTradable = true; } security.AddData(configList); // invoke the security initializer _securityInitializerProvider.SecurityInitializer.Initialize(security); // if leverage was specified then apply to security after the initializer has run, parameters of this // method take precedence over the intializer if (leverage > 0) { security.SetLeverage(leverage); } // In live mode, equity assumes specific price variation model if (_isLiveMode && security.Type == SecurityType.Equity) { security.PriceVariationModel = new EquityPriceVariationModel(); } return(security); }
/// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { // initialize algorithm level parameters SetStartDate(2013, 10, 07); SetEndDate(2013, 10, 11); //SetStartDate(2014, 01, 01); //SetEndDate(2014, 06, 01); SetCash(100000); // leverage tradier $1 traders SetBrokerageModel(BrokerageName.TradierBrokerage); // request high resolution equity data AddSecurity(SecurityType.Equity, Symbol, Resolution.Second); // save off our security so we can reference it quickly later Security = Securities[Symbol]; // Set our max leverage Security.SetLeverage(MaximumLeverage); // define our longer term indicators ADX14 = ADX(Symbol, 28, Resolution.Hour); STD14 = STD(Symbol, 14, Resolution.Daily); ATR14 = ATR(Symbol, 14, resolution: Resolution.Daily); PSARMin = new ParabolicStopAndReverse(Symbol, afStart: 0.0001m, afIncrement: 0.0001m); // smooth our ATR over a week, we'll use this to determine if recent volatilty warrants entrance var oneWeekInMarketHours = (int)(5*6.5); SmoothedATR14 = new ExponentialMovingAverage("Smoothed_" + ATR14.Name, oneWeekInMarketHours).Of(ATR14); // smooth our STD over a week as well SmoothedSTD14 = new ExponentialMovingAverage("Smoothed_"+STD14.Name, oneWeekInMarketHours).Of(STD14); // initialize our charts var chart = new Chart(Symbol); chart.AddSeries(new Series(ADX14.Name)); chart.AddSeries(new Series("Enter", SeriesType.Scatter)); chart.AddSeries(new Series("Exit", SeriesType.Scatter)); chart.AddSeries(new Series(PSARMin.Name, SeriesType.Scatter)); AddChart(chart); var history = History(Symbol, 20, Resolution.Daily); foreach (var bar in history) { ADX14.Update(bar); ATR14.Update(bar); STD14.Update(bar.EndTime, bar.Close); } // schedule an event to run every day at five minutes after our Symbol's market open Schedule.Event("MarketOpenSpan") .EveryDay(Symbol) .AfterMarketOpen(Symbol, minutesAfterOpen: OpeningSpanInMinutes) .Run(MarketOpeningSpanHandler); Schedule.Event("MarketOpen") .EveryDay(Symbol) .AfterMarketOpen(Symbol, minutesAfterOpen: -1) .Run(() => PSARMin.Reset()); }
public void SetLeverageTest() { var security = new Security(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork), CreateTradeBarConfig()); security.SetLeverage(4m); Assert.AreEqual(4m,security.Leverage); security.SetLeverage(5m); Assert.AreEqual(5m, security.Leverage); Assert.That(() => security.SetLeverage(0.1m), Throws.TypeOf<ArgumentException>().With.Message.EqualTo("Leverage must be greater than or equal to 1.")); }