17 using System.Collections.Generic;
19 using System.Linq.Expressions;
20 using System.Globalization;
22 using NodaTime.TimeZones;
42 using System.Collections.Concurrent;
58 using Newtonsoft.Json;
70 #region Documentation Attribute Categories
71 const string AddingData =
"Adding Data";
72 const string AlgorithmFramework =
"Algorithm Framework";
73 const string Charting =
"Charting";
74 const string ConsolidatingData =
"Consolidating Data";
75 const string HandlingData =
"Handling Data";
76 const string HistoricalData =
"Historical Data";
77 const string Indicators =
"Indicators";
78 const string LiveTrading =
"Live Trading";
79 const string Logging =
"Logging";
80 const string MachineLearning =
"Machine Learning";
81 const string Modeling =
"Modeling";
82 const string ParameterAndOptimization =
"Parameter and Optimization";
83 const string ScheduledEvents =
"Scheduled Events";
84 const string SecuritiesAndPortfolio =
"Securities and Portfolio";
85 const string TradingAndOrders =
"Trading and Orders";
86 const string Universes =
"Universes";
87 const string StatisticsTag =
"Statistics";
103 private string _name;
104 private HashSet<string> _tags;
105 private bool _tagsLimitReachedLogSent;
106 private bool _tagsCollectionTruncatedLogSent;
107 private DateTime _start;
108 private DateTime _startDate;
109 private DateTime _endDate;
110 private bool _locked;
111 private bool _liveMode;
114 private string _algorithmId =
"";
115 private ConcurrentQueue<string> _debugMessages =
new ConcurrentQueue<string>();
116 private ConcurrentQueue<string> _logMessages =
new ConcurrentQueue<string>();
117 private ConcurrentQueue<string> _errorMessages =
new ConcurrentQueue<string>();
121 private readonly HashSet<string> _oneTimeCommandErrors =
new();
122 private readonly Dictionary<string, Func<CallbackCommand, bool?>> _registeredCommands =
new(StringComparer.InvariantCultureIgnoreCase);
125 private string _previousDebugMessage =
"";
126 private string _previousErrorMessage =
"";
139 private bool _checkedForOnDataSlice;
140 private Action<Slice> _onDataSlice;
143 private bool _userSetSecurityInitializer;
146 private TimeSpan? _warmupTimeSpan;
147 private int? _warmupBarCount;
148 private Dictionary<string, string> _parameters =
new Dictionary<string, string>();
161 Name = GetType().Name;
173 _startDate =
new DateTime(1998, 01, 01);
327 return _brokerageModel;
331 _brokerageModel = value;
334 BrokerageName = Brokerages.BrokerageModel.GetBrokerageName(_brokerageModel);
336 catch (ArgumentOutOfRangeException)
477 [Obsolete(
"OptionChainProvider property is will soon be deprecated. " +
478 "The new OptionChain() method should be used to fetch equity and index option chains, " +
479 "which will contain additional data per contract, like daily price data, implied volatility and greeks.")]
510 throw new InvalidOperationException(
"Cannot set algorithm name after it is initialized.");
513 if (!
string.IsNullOrEmpty(value))
524 public HashSet<string>
Tags
537 var tags = value.Where(x => !
string.IsNullOrEmpty(x?.Trim())).ToList();
539 if (tags.Count >
MaxTagsCount && !_tagsCollectionTruncatedLogSent)
541 Log($
"Warning: The tags collection cannot contain more than {MaxTagsCount} items. It will be truncated.");
542 _tagsCollectionTruncatedLogSent =
true;
572 get {
return _localTimeKeeper.
LocalTime; }
581 get {
return _timeKeeper.UtcTime; }
591 get {
return _localTimeKeeper.
TimeZone; }
649 return _algorithmMode;
660 return _deploymentTarget;
673 return _debugMessages;
677 _debugMessages = value;
694 _logMessages = value;
714 return _errorMessages;
718 _errorMessages = value;
758 throw new NotImplementedException(
"Please override the Initialize() method");
769 if (_endDate < _startDate)
771 throw new ArgumentException(
"Please select an algorithm end date greater than start date.");
775 if (portfolioConstructionModel !=
null)
785 portfolioConstructionModel.RebalanceOnInsightChanges
794 Debug(
"Warning: rebalance portfolio settings are set but not supported by the current IPortfolioConstructionModel type: " +
795 $
"{PortfolioConstruction.GetType()}");
813 securityBenchmark.Security.Symbol, securityBenchmark.Security.Type);
816 Log($
"QCAlgorithm.PostInitialize(): Warning: Using a security benchmark of a different timezone ({benchmarkTimeZone})" +
817 $
" than the algorithm TimeZone ({TimeZone}) may lead to skewed and incorrect statistics. Use a higher resolution than daily to minimize.");
821 if (TryGetWarmupHistoryStartTime(out var result))
832 Debug(
"Accurate daily end-times now enabled by default. See more at https://qnt.co/3YHaWHL. To disable it and use legacy daily bars set self.settings.daily_precise_end_time = False.");
857 return _parameters.TryGetValue(name, out var value) ? value : defaultValue;
870 return _parameters.TryGetValue(name, out var strValue) &&
int.TryParse(strValue, out var value) ? value : defaultValue;
883 return _parameters.TryGetValue(name, out var strValue) &&
884 double.TryParse(strValue, NumberStyles.Any, CultureInfo.InvariantCulture, out var value) ? value : defaultValue;
897 return _parameters.TryGetValue(name, out var strValue) &&
898 decimal.TryParse(strValue, NumberStyles.Any, CultureInfo.InvariantCulture, out var value) ? value : defaultValue;
907 return _parameters.ToReadOnlyDictionary();
918 _parameters = parameters.ToDictionary();
923 catch (Exception err)
925 Error(
"Error applying parameter values: " + err.Message);
936 if (availableDataTypes ==
null)
941 foreach (var dataFeed
in availableDataTypes)
958 throw new Exception(
"SetSecurityInitializer() cannot be called after algorithm initialization. " +
959 "When you use the SetSecurityInitializer() method it will apply to all universes and manually added securities.");
962 if (_userSetSecurityInitializer)
964 Debug(
"Warning: SetSecurityInitializer() has already been called, existing security initializers in all universes will be overwritten.");
968 _userSetSecurityInitializer =
true;
977 [Obsolete(
"This method is deprecated. Please use this overload: SetSecurityInitializer(Action<Security> securityInitializer)")]
1035 if (!_checkedForOnDataSlice)
1037 _checkedForOnDataSlice =
true;
1039 var method = GetType().GetMethods()
1040 .Where(x => x.Name ==
"OnData")
1041 .Where(x => x.DeclaringType != typeof(
QCAlgorithm))
1042 .Where(x => x.GetParameters().Length == 1)
1043 .FirstOrDefault(x => x.GetParameters()[0].ParameterType == typeof(
Slice));
1050 var
self = Expression.Constant(
this);
1051 var parameter = Expression.Parameter(typeof(
Slice),
"data");
1052 var call = Expression.Call(
self, method, parameter);
1053 var lambda = Expression.Lambda<Action<Slice>>(call, parameter);
1054 _onDataSlice = lambda.Compile();
1057 if (_onDataSlice !=
null)
1059 _onDataSlice(slice);
1134 [Obsolete(
"This method is deprecated and will be removed after August 2021. Please use this overload: OnEndOfDay(Symbol symbol)")]
1232 _timeKeeper.SetUtcDateTime(frontier);
1249 tz = DateTimeZoneProviders.Tzdb[timeZone];
1251 catch (DateTimeZoneNotFoundException)
1253 throw new ArgumentException($
"TimeZone with id '{timeZone}' was not found. For a complete list of time zones please visit: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones");
1268 throw new InvalidOperationException(
"Algorithm.SetTimeZone(): Cannot change time zone after algorithm running.");
1271 if (timeZone ==
null)
throw new ArgumentNullException(nameof(timeZone));
1272 _timeKeeper.AddTimeZone(timeZone);
1273 _localTimeKeeper = _timeKeeper.GetLocalTimeKeeper(timeZone);
1284 _start = _startDate;
1291 SetLiveModeStartDate();
1316 if (!_userSetSecurityInitializer)
1324 var security = kvp.Value;
1329 var leverage = security.Leverage;
1334 security.SetLeverage(leverage);
1371 [Obsolete(
"Symbol implicit operator to string is provided for algorithm use only.")]
1379 throw new InvalidOperationException(
"Algorithm.SetBenchmark(): Cannot change Benchmark after algorithm initialized.");
1382 var market = GetMarket(
null, symbol, securityType, defaultMarket:
Market.
USA);
1407 symbol =
Securities.FirstOrDefault(x => x.Key.Value == ticker).Key;
1412 Debug($
"Warning: SetBenchmark({ticker}): no existing symbol found, benchmark security will be added with {SecurityType.Equity} type.");
1432 throw new InvalidOperationException(
"Algorithm.SetBenchmark(): Cannot change Benchmark after algorithm initialized.");
1451 throw new InvalidOperationException(
"Algorithm.SetBenchmark(): Cannot change Benchmark after algorithm initialized.");
1486 if (!
string.IsNullOrEmpty(tag?.Trim()))
1490 if (!_tagsLimitReachedLogSent)
1492 Log($
"Warning: AddTag({tag}): Unable to add tag. Tags are limited to a maximum of {MaxTagsCount}.");
1493 _tagsLimitReachedLogSent =
true;
1528 throw new InvalidOperationException(
"Algorithm.SetAccountCurrency(): " +
1529 "Cannot change AccountCurrency after algorithm initialized.");
1532 if (startingCash ==
null)
1534 Debug($
"Changing account currency from {AccountCurrency} to {accountCurrency}...");
1538 Debug($
"Changing account currency from {AccountCurrency} to {accountCurrency}, with a starting cash of {startingCash}...");
1553 SetCash((decimal)startingCash);
1565 SetCash((decimal)startingCash);
1582 throw new InvalidOperationException(
"Algorithm.SetCash(): Cannot change cash available after algorithm initialized.");
1593 public void SetCash(
string symbol, decimal startingCash, decimal conversionRate = 0)
1601 throw new InvalidOperationException(
"Algorithm.SetCash(): Cannot change cash available after algorithm initialized.");
1620 var start =
new DateTime(year, month, day);
1627 catch (Exception err)
1629 throw new ArgumentException($
"Date Invalid: {err.Message}");
1646 var end =
new DateTime(year, month, day);
1649 end = end.Date.AddDays(1).Subtract(TimeSpan.FromTicks(1));
1653 catch (Exception err)
1655 throw new ArgumentException($
"Date Invalid: {err.Message}");
1667 _algorithmId = algorithmId;
1680 if (_liveMode)
return;
1683 start = start.RoundDown(TimeSpan.FromDays(1));
1687 if (start < (
new DateTime(1900, 01, 01)))
1689 throw new ArgumentOutOfRangeException(nameof(start),
"Please select a start date after January 1st, 1900.");
1693 var todayInAlgorithmTimeZone = DateTime.UtcNow.ConvertFromUtc(
TimeZone).Date;
1694 if (start > todayInAlgorithmTimeZone)
1696 throw new ArgumentOutOfRangeException(nameof(start),
"Please select start date less than today");
1702 _start = _startDate = start;
1707 throw new InvalidOperationException(
"Algorithm.SetStartDate(): Cannot change start date after algorithm initialized.");
1721 if (_liveMode)
return;
1726 throw new InvalidOperationException(
"Algorithm.SetEndDate(): Cannot change end date after algorithm initialized.");
1731 var yesterdayInAlgorithmTimeZone = DateTime.UtcNow.ConvertFromUtc(
TimeZone).Date.AddDays(-1);
1732 if (end > yesterdayInAlgorithmTimeZone)
1734 end = yesterdayInAlgorithmTimeZone;
1738 _endDate = end.RoundDown(TimeSpan.FromDays(1)).AddDays(1).AddTicks(-1);
1779 SetLiveModeStartDate();
1793 _algorithmMode = algorithmMode;
1806 _deploymentTarget = deploymentTarget;
1835 return AddSecurity(securityType, ticker, resolution, fillForward,
Security.
NullLeverage, extendedMarketHours, dataMappingMode, dataNormalizationMode);
1854 return AddSecurity(securityType, ticker, resolution,
null, fillForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode);
1876 return AddOption(ticker, resolution, market, fillForward, leverage);
1881 return AddFuture(ticker, resolution, market, fillForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode);
1886 market = GetMarket(market, ticker, securityType);
1890 symbol.ID.Market != market ||
1891 symbol.SecurityType != securityType)
1896 return AddSecurity(symbol, resolution, fillForward, leverage, extendedMarketHours, dataMappingMode, dataNormalizationMode);
1898 catch (Exception err)
1900 Error(
"Algorithm.AddSecurity(): " + err);
1923 var contractOffset = (uint)Math.Abs(contractDepthOffset);
1926 throw new ArgumentOutOfRangeException(nameof(contractDepthOffset), $
"'contractDepthOffset' current maximum value is {Futures.MaximumContractDepthOffset}." +
1927 $
" Front month (0) and only {Futures.MaximumContractDepthOffset} back month contracts are currently supported.");
1935 return AddOptionContract(symbol, resolution, fillForward, leverage, extendedMarketHours);
1938 var securityResolution = resolution;
1939 var securityFillForward = fillForward;
1944 securityFillForward =
false;
1947 var isFilteredSubscription = !isCanonical;
1948 List<SubscriptionDataConfig> configs;
1951 if (dataNormalizationMode.HasValue)
1955 securityFillForward,
1956 extendedMarketHours,
1957 isFilteredSubscription,
1958 dataNormalizationMode: dataNormalizationMode.
Value,
1959 contractDepthOffset: (uint)contractDepthOffset);
1965 securityFillForward,
1966 extendedMarketHours,
1967 isFilteredSubscription,
1968 contractDepthOffset: (uint)contractDepthOffset);
1982 var canonicalConfig = configs.First();
1983 var universeSettingsResolution = canonicalConfig.Resolution;
2001 GetResolution(symbol, resolution,
null), isCanonical:
false);
2004 ExtendedMarketHours = extendedMarketHours,
2007 ContractDepthOffset = (int)contractOffset,
2008 SubscriptionDataTypes = dataTypes,
2016 continuousContractSymbol.ID.Symbol,
2017 continuousContractSymbol.ID.SecurityType,
2018 security.Exchange.Hours);
2029 return AddToUserDefinedUniverse(security, configs);
2047 return AddSecurity<Equity>(
SecurityType.Equity, ticker, resolution, market, fillForward, leverage, extendedMarketHours, normalizationMode: dataNormalizationMode);
2062 market = GetMarket(market, underlying,
SecurityType.Option);
2065 return AddOption(underlyingSymbol, resolution, market, fillForward, leverage);
2083 return AddOption(underlying,
null, resolution, market, fillForward, leverage);
2105 market = GetMarket(market, targetOption, optionType);
2110 if (!
string.IsNullOrEmpty(targetOption))
2112 alias = $
"?{targetOption}";
2116 alias = $
"?{underlying.Value}";
2119 canonicalSymbol.ID.Market != market ||
2120 !canonicalSymbol.SecurityType.IsOption())
2144 bool fillForward =
true, decimal leverage =
Security.
NullLeverage,
bool extendedMarketHours =
false,
2147 market = GetMarket(market, ticker,
SecurityType.Future);
2150 var alias =
"/" + ticker;
2152 canonicalSymbol.ID.Market != market ||
2158 return (
Future)
AddSecurity(canonicalSymbol, resolution, fillForward, leverage, extendedMarketHours, dataMappingMode: dataMappingMode,
2159 dataNormalizationMode: dataNormalizationMode, contractDepthOffset: contractDepthOffset);
2175 return (
Future)
AddSecurity(symbol, resolution, fillForward, leverage, extendedMarketHours);
2190 throw new ArgumentException(
"Symbol provided must be canonical (i.e. the Symbol returned from AddFuture(), not AddFutureContract().");
2212 throw new ArgumentException(
"Expected non-canonical Symbol (i.e. a Symbol representing a specific Future contract");
2215 return AddOptionContract(symbol, resolution, fillForward, leverage, extendedMarketHours);
2229 return AddIndexOption(underlying,
null, resolution, market, fillForward);
2258 throw new ArgumentException(
"Symbol provided must be of type SecurityType.Index");
2278 targetOption, resolution, fillForward);
2294 throw new ArgumentException(
"Symbol provided must be non-canonical and of type SecurityType.IndexOption");
2315 throw new ArgumentException($
"Unexpected option symbol {symbol}. " +
2316 $
"Please provide a valid option contract with it's underlying symbol set.");
2322 List<SubscriptionDataConfig> underlyingConfigs;
2327 underlyingSecurity =
AddSecurity(underlying, resolution, fillForward, leverage, extendedMarketHours);
2331 else if (underlyingSecurity !=
null && underlyingSecurity.IsDelisted)
2333 throw new ArgumentException($
"The underlying {underlying.SecurityType} asset ({underlying.Value}) is delisted " +
2334 $
"(current time is {Time})");
2341 var dataNormalizationMode = underlyingConfigs.DataNormalizationMode();
2346 throw new ArgumentException($
"The underlying {underlying.SecurityType} asset ({underlying.Value}) is set to " +
2347 $
"{dataNormalizationMode}, please change this to DataNormalizationMode.Raw with the " +
2348 "SetDataNormalization() method"
2359 underlyingSecurity.RefreshDataNormalizationModeProperty();
2371 Resolution = underlyingConfigs.GetHighestResolution(),
2372 ExtendedMarketHours = extendedMarketHours
2379 if (optionUniverse !=
null)
2381 foreach (var subscriptionDataConfig
in configs.Concat(underlyingConfigs))
2383 optionUniverse.
Add(subscriptionDataConfig);
2402 return AddSecurity<Forex>(
SecurityType.Forex, ticker, resolution, market, fillForward, leverage,
false);
2417 return AddSecurity<Cfd>(
SecurityType.Cfd, ticker, resolution, market, fillForward, leverage,
false);
2432 var index = AddSecurity<Index>(
SecurityType.Index, ticker, resolution, market, fillForward, 1,
false);
2448 return AddSecurity<Crypto>(
SecurityType.Crypto, ticker, resolution, market, fillForward, leverage,
false);
2463 return AddSecurity<CryptoFuture>(
SecurityType.CryptoFuture, ticker, resolution, market, fillForward, leverage,
false);
2499 if (security.Invested)
2505 security.Cache.Reset();
2508 security.IsTradable =
false;
2512 foreach (var kvp
in UniverseManager.Where(x => x.Value.Configuration.Symbol == symbol
2515 var universe = kvp.Value;
2517 var otherUniverses =
UniverseManager.Select(ukvp => ukvp.Value).Where(u => !ReferenceEquals(u, universe)).ToList();
2521 if (!otherUniverses.Any(u => u.Members.ContainsKey(underlying.Symbol)))
2529 foreach (var child
in universe.Members.Values.OrderBy(security1 => security1.Symbol))
2531 if (!otherUniverses.Any(u => u.Members.ContainsKey(child.Symbol)) && !child.Symbol.IsCanonical())
2539 _universeSelectionUniverses.Remove(security.Symbol);
2544 lock (_pendingUniverseAdditionsLock)
2550 universe.Remove(symbol);
2553 _pendingUserDefinedUniverseSecurityAdditions.RemoveAll(addition => addition.Security.Symbol == symbol);
2576 return AddData<T>(ticker, resolution, fillForward:
false, leverage: 1m);
2595 return AddData<T>(underlying, resolution, fillForward:
false, leverage: 1m);
2613 return AddData<T>(ticker, resolution,
null, fillForward, leverage);
2630 return AddData<T>(underlying, resolution,
null, fillForward, leverage);
2647 return AddData(typeof(
T), ticker, resolution, timeZone, fillForward, leverage);
2664 return AddData(typeof(
T), underlying, resolution, timeZone, fillForward, leverage);
2686 SetDatabaseEntries(key, properties, exchangeHours);
2689 return AddData(typeof(
T), ticker, resolution,
null, fillForward, leverage);
2701 if (!_liveMode && (
string.IsNullOrEmpty(message) || _previousDebugMessage == message))
return;
2702 _debugMessages.Enqueue(message);
2703 _previousDebugMessage = message;
2715 Debug(message.ToStringInvariant());
2727 Debug(message.ToStringInvariant());
2739 Debug(message.ToStringInvariant());
2749 public void Log(
string message)
2751 if (!_liveMode &&
string.IsNullOrEmpty(message))
return;
2752 _logMessages.Enqueue(message);
2764 Log(message.ToStringInvariant());
2774 public void Log(
double message)
2776 Log(message.ToStringInvariant());
2786 public void Log(decimal message)
2788 Log(message.ToStringInvariant());
2800 if (!_liveMode && (
string.IsNullOrEmpty(message) || _previousErrorMessage == message))
return;
2801 _errorMessages.Enqueue(message);
2802 _previousErrorMessage = message;
2814 Error(message.ToStringInvariant());
2826 Error(message.ToStringInvariant());
2838 Error(message.ToStringInvariant());
2850 var message = error.Message;
2851 if (!_liveMode && (
string.IsNullOrEmpty(message) || _previousErrorMessage == message))
return;
2852 _errorMessages.Enqueue(message);
2853 _previousErrorMessage = message;
2861 public void Quit(
string message =
"")
2863 Debug(
"Quit(): " + message);
2912 private T AddSecurity<T>(
SecurityType securityType,
string ticker,
Resolution? resolution,
string market,
bool fillForward, decimal leverage,
bool extendedMarketHours,
2916 market = GetMarket(market, ticker, securityType);
2920 symbol.ID.Market != market ||
2921 symbol.SecurityType != securityType)
2931 return (
T)AddToUserDefinedUniverse(security, configs);
2938 [DocumentationAttribute(HistoricalData)]
2941 if (historyProvider ==
null)
2943 throw new ArgumentNullException(nameof(historyProvider),
"Algorithm.SetHistoryProvider(): Historical data provider cannot be null.");
2956 if (exception ==
null)
2958 throw new ArgumentNullException(nameof(exception),
"Algorithm.SetRunTimeError(): Algorithm.RunTimeError cannot be set to null.");
2982 public string Download(
string address) =>
Download(address, Enumerable.Empty<KeyValuePair<string, string>>());
2993 public string Download(
string address, IEnumerable<KeyValuePair<string, string>> headers) =>
Download(address, headers,
null,
null);
3006 public string Download(
string address, IEnumerable<KeyValuePair<string, string>> headers,
string userName,
string password)
3008 return _api.
Download(address, headers, userName, password);
3019 return Schedule.TrainingNow(trainingCode);
3032 return Schedule.Training(dateRule, timeRule, trainingCode);
3040 private void OnInsightsGenerated(
Insight[] insights)
3045 Log($
"{Time}: ALPHA: {string.Join(" |
", insights.Select(i => i.ToString()).OrderBy(i => i))}");
3057 [DocumentationAttribute(HandlingData)]
3109 var shortableQuantity = security.ShortableProvider.ShortableQuantity(symbol, security.LocalTime);
3110 if (shortableQuantity ==
null)
3117 order => order.Symbol == symbol && (!updateOrderId.HasValue || order.OrderId != updateOrderId.Value));
3119 var portfolioQuantity = security.Holdings.Quantity;
3122 if (portfolioQuantity + openOrderQuantity <= -shortableQuantity)
3127 shortQuantity = -Math.Abs(shortQuantity);
3128 return portfolioQuantity + shortQuantity + openOrderQuantity >= -shortableQuantity;
3142 return security.ShortableProvider.ShortableQuantity(symbol, security.LocalTime) ?? 0;
3158 return _securityDefinitionSymbolResolver.
ISIN(isin, GetVerifiedTradingDate(tradingDate));
3170 return _securityDefinitionSymbolResolver.
ISIN(symbol);
3190 return _securityDefinitionSymbolResolver.
CompositeFIGI(compositeFigi, GetVerifiedTradingDate(tradingDate));
3202 return _securityDefinitionSymbolResolver.
CompositeFIGI(symbol);
3218 return _securityDefinitionSymbolResolver.
CUSIP(cusip, GetVerifiedTradingDate(tradingDate));
3230 return _securityDefinitionSymbolResolver.
CUSIP(symbol);
3246 return _securityDefinitionSymbolResolver.
SEDOL(sedol, GetVerifiedTradingDate(tradingDate));
3258 return _securityDefinitionSymbolResolver.
SEDOL(symbol);
3274 return _securityDefinitionSymbolResolver.
CIK(cik, GetVerifiedTradingDate(tradingDate));
3286 return _securityDefinitionSymbolResolver.
CIK(symbol);
3310 return symbols.Select(symbol =>
Fundamentals(symbol)).ToList();
3332 return OptionChains(
new[] { symbol }, flatten).Values.SingleOrDefault() ??
3333 new OptionChain(GetCanonicalOptionSymbol(symbol),
Time.Date, flatten);
3351 var canonicalSymbols = symbols.Select(GetCanonicalOptionSymbol).ToList();
3352 var optionCanonicalSymbols = canonicalSymbols.Where(x => x.SecurityType !=
SecurityType.FutureOption);
3353 var futureOptionCanonicalSymbols = canonicalSymbols.Where(x => x.SecurityType ==
SecurityType.FutureOption);
3355 var optionChainsData =
History(optionCanonicalSymbols, 1).GetUniverseData()
3356 .Select(x => (x.Keys.Single(), x.Values.Single().Cast<
OptionUniverse>()));
3359 var futureOptionChainsData = futureOptionCanonicalSymbols.Select(symbol =>
3365 EndTime =
Time.Date,
3367 return (symbol, optionChainData);
3370 var time =
Time.Date;
3372 foreach (var (symbol, contracts) in optionChainsData.Concat(futureOptionChainsData))
3375 var optionChain =
new OptionChain(symbol, time, contracts, symbolProperties, flatten);
3376 chains.Add(symbol, optionChain);
3389 var typeName = command.GetType().Name;
3390 if (command is
Command || typeName.Contains(
"AnonymousType", StringComparison.InvariantCultureIgnoreCase))
3392 return CommandLink(typeName, command);
3394 return string.Empty;
3405 var commandInstance = JsonConvert.DeserializeObject<
T>(command.Payload);
3406 return commandInstance.Run(
this);
3417 bool? result =
null;
3418 if (_registeredCommands.TryGetValue(command.
Type, out var target))
3422 result = target.Invoke(command);
3424 catch (Exception ex)
3427 if (_oneTimeCommandErrors.Add(command.
Type))
3429 Log($
"Unexpected error running command '{command.Type}' error: '{ex.Message}'");
3435 if (_oneTimeCommandErrors.Add(command.
Type))
3437 Log($
"Detected unregistered command type '{command.Type}', will be ignored");
3456 private string GetMarket(
string market,
string ticker,
SecurityType securityType,
string defaultMarket =
null)
3458 if (
string.IsNullOrEmpty(market))
3470 if (!
BrokerageModel.DefaultMarkets.TryGetValue(securityType, out market))
3472 if (
string.IsNullOrEmpty(defaultMarket))
3474 throw new KeyNotFoundException($
"No default market set for security type: {securityType}");
3476 return defaultMarket;
3482 private string CommandLink(
string typeName,
object command)
3484 var payload =
new Dictionary<string, dynamic> { {
"projectId",
ProjectId }, {
"command", command } };
3485 if (_registeredCommands.ContainsKey(typeName))
3487 payload[
"command[$type]"] = typeName;
3489 return Api.Authentication.Link(
"live/commands/create", payload);
3492 private static Symbol GetCanonicalOptionSymbol(
Symbol symbol)
3495 if (symbol.SecurityType.HasOptions())
3500 if (symbol.SecurityType.IsOption())
3505 throw new ArgumentException($
"The symbol {symbol} is not an option or an underlying symbol.");
3533 private DateTime GetVerifiedTradingDate(DateTime? tradingDate)
3535 tradingDate ??=
Time.Date;
3536 if (tradingDate >
Time.Date)
3538 throw new ArgumentException($
"The trading date provided: \"{tradingDate:yyyy-MM-dd}\" is after the current algorithm's trading date: \"{Time:yyyy-MM-dd}\"");
3541 return tradingDate.Value;
3547 private void SetLiveModeStartDate()
3551 throw new InvalidOperationException(
"SetLiveModeStartDate should only be called during live trading!");
3553 _start = DateTime.UtcNow.ConvertFromUtc(
TimeZone);
3555 _startDate = _start.Date;
3565 if (_statisticsService ==
null)
3567 _statisticsService = statisticsService;