Lean  $LEAN_TAG$
QuantConnect.Extensions Class Reference

Extensions function collections - group all static extensions functions here. More...

Static Public Member Functions

static T TryGetPropertyValue< T > (this JObject jObject, string name)
 Helper method to get a property in a jobject if available More...
 
static bool IsOutOfDate (this string filepath)
 Determine if the file is out of date according to our download period. Date based files are never out of date (Files with YYYYMMDD) More...
 
static bool IsDirectoryEmpty (this string directoryPath)
 Helper method to check if a directory exists and is not empty More...
 
static MarketHoursDatabase.Entry GetEntry (this MarketHoursDatabase marketHoursDatabase, Symbol symbol, IEnumerable< Type > dataTypes)
 Helper method to get a market hours entry More...
 
static List< string > DeserializeList (this string jsonArray)
 Helper method to deserialize a json array into a list also handling single json values More...
 
static List< T > DeserializeList< T > (this string jsonArray)
 Helper method to deserialize a json array into a list also handling single json values More...
 
static string DownloadData (this HttpClient client, string url, Dictionary< string, string > headers=null)
 Helper method to download a provided url as a string More...
 
static string DownloadData (this string url, Dictionary< string, string > headers=null)
 Helper method to download a provided url as a string More...
 
static byte[] DownloadByteArray (this string url)
 Helper method to download a provided url as a byte array More...
 
static decimal SafeMultiply100 (this decimal value)
 Safe multiplies a decimal by 100 More...
 
static MemoryStream GetMemoryStream (Guid guid)
 Will return a memory stream using the RecyclableMemoryStreamManager instance. More...
 
static byte[] ProtobufSerialize (this List< Tick > ticks, Guid guid)
 Serialize a list of ticks using protobuf More...
 
static byte[] ProtobufSerialize (this IBaseData baseData, Guid guid)
 Serialize a base data instance using protobuf More...
 
static void ProtobufSerialize (this IBaseData baseData, Stream stream)
 Serialize a base data instance using protobuf More...
 
static string GetZeroPriceMessage (this Symbol symbol)
 Extension method to get security price is 0 messages for users More...
 
static string ToCamelCase (this string value)
 Converts the provided string into camel case notation More...
 
static AlphaResultPacket Batch (this List< AlphaResultPacket > resultPackets)
 Helper method to batch a collection of AlphaResultPacket into 1 single instance. Will return null if the provided list is empty. Will keep the last Order instance per order id, which is the latest. Implementations trusts the provided 'resultPackets' list to batch is in order More...
 
static void StopSafely (this Thread thread, TimeSpan timeout, CancellationTokenSource token=null)
 Helper method to safely stop a running thread More...
 
static string GetHash (this IDictionary< int, Order > orders)
 Generates a hash code from a given collection of orders More...
 
static Func< DateTime, DateTime?> ToFunc (this IDateRule dateRule)
 Converts a date rule into a function that receives current time and returns the next date. More...
 
static bool IsEmpty (this BaseSeries series)
 Returns true if the specified BaseSeries instance holds no ISeriesPoint More...
 
static bool IsEmpty (this Chart chart)
 Returns if the specified Chart instance holds no Series or they are all empty Extensions.IsEmpty(BaseSeries) More...
 
static dynamic GetPythonMethod (this PyObject instance, string name)
 Gets a python method by name More...
 
static dynamic GetPythonBoolProperty (this PyObject instance, string name)
 Gets a python property by name More...
 
static dynamic GetPythonBoolPropertyWithChecks (this PyObject instance, string name)
 Gets a python property by name More...
 
static dynamic GetPythonMethodWithChecks (this PyObject instance, string name)
 Gets a python method by name More...
 
static dynamic GetMethod (this PyObject instance, string name)
 Gets a method from a PyObject instance by name. First, it tries to get the snake-case version of the method name, in case the user is using that style. Else, it tries to get the method with the original name, regardless of whether the class has a Python overload or not. More...
 
static int GetPythonArgCount (this PyObject method)
 Get a python methods arg count More...
 
static IEnumerable< IPortfolioTargetOrderTargetsByMarginImpact (this IEnumerable< IPortfolioTarget > targets, IAlgorithm algorithm, bool targetIsDelta=false)
 Returns an ordered enumerable where position reducing orders are executed first and the remaining orders are executed in decreasing order value. Will NOT return targets during algorithm warmup. Will NOT return targets for securities that have no data yet. Will NOT return targets for which current holdings + open orders quantity, sum up to the target quantity More...
 
static BaseData GetBaseDataInstance (this Type type)
 Given a type will create a new instance using the parameterless constructor and assert the type implements BaseData More...
 
static T GetAndDispose< T > (this PyObject instance)
 Helper method that will cast the provided PyObject to a T type and dispose of it. More...
 
static void Move< T > (this List< T > list, int oldIndex, int newIndex)
 Extension to move one element from list from A to position B. More...
 
static byte[] GetBytes (this string str)
 Extension method to convert a string into a byte array More...
 
static byte[] GetBytes (this Stream stream)
 Reads the entire content of a stream and returns it as a byte array. More...
 
static void Clear< T > (this ConcurrentQueue< T > queue)
 Extentsion method to clear all items from a thread safe queue More...
 
static string GetString (this byte[] bytes, Encoding encoding=null)
 Extension method to convert a byte array into a string. More...
 
static string ToMD5 (this string str)
 Extension method to convert a string to a MD5 hash. More...
 
static string ToSHA256 (this string data)
 Encrypt the token:time data to make our API hash. More...
 
static string EncodeBase36 (this ulong data)
 Converts a long to an uppercase alpha numeric string More...
 
static ulong DecodeBase36 (this string symbol)
 Converts an upper case alpha numeric string into a long More...
 
static string EncodeBase64 (this string text)
 Convert a string to Base64 Encoding More...
 
static string DecodeBase64 (this string base64EncodedText)
 Decode a Base64 Encoded string More...
 
static string LazyToUpper (this string data)
 Lazy string to upper implementation. Will first verify the string is not already upper and avoid the call to string.ToUpperInvariant() if possible. More...
 
static string LazyToLower (this string data)
 Lazy string to lower implementation. Will first verify the string is not already lower and avoid the call to string.ToLowerInvariant() if possible. More...
 
static void AddOrUpdate< K, V > (this ConcurrentDictionary< K, V > dictionary, K key, V value)
 Extension method to automatically set the update value to same as "add" value for TryAddUpdate. This makes the API similar for traditional and concurrent dictionaries. More...
 
static TValue AddOrUpdate< TKey, TValue > (this ConcurrentDictionary< TKey, Lazy< TValue >> dictionary, TKey key, Func< TKey, TValue > addValueFactory, Func< TKey, TValue, TValue > updateValueFactory)
 Extension method to automatically add/update lazy values in concurrent dictionary. More...
 
static void Add< TKey, TElement, TCollection > (this IDictionary< TKey, TCollection > dictionary, TKey key, TElement element)
 Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created. More...
 
static ImmutableDictionary< TKey, ImmutableHashSet< TElement > > Add< TKey, TElement > (this ImmutableDictionary< TKey, ImmutableHashSet< TElement >> dictionary, TKey key, TElement element)
 Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created. More...
 
static ImmutableSortedDictionary< TKey, ImmutableHashSet< TElement > > Add< TKey, TElement > (this ImmutableSortedDictionary< TKey, ImmutableHashSet< TElement >> dictionary, TKey key, TElement element)
 Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created. More...
 
static void Add (this Ticks dictionary, Symbol key, Tick tick)
 Adds the specified Tick to the Ticks collection. If an entry does not exist for the specified key then one will be created. More...
 
static decimal RoundToSignificantDigits (this decimal d, int digits)
 Extension method to round a double value to a fixed number of significant figures instead of a fixed decimal places. More...
 
static string ToFinancialFigures (this decimal number)
 Converts a decimal into a rounded number ending with K (thousands), M (millions), B (billions), etc. More...
 
static decimal DiscretelyRoundBy (this decimal value, decimal quanta, MidpointRounding mode=MidpointRounding.AwayFromZero)
 Discretizes the value to a maximum precision specified by quanta . Quanta can be an arbitrary positive number and represents the step size. Consider a quanta equal to 0.15 and rounding a value of 1.0. Valid values would be 0.9 (6 quanta) and 1.05 (7 quanta) which would be rounded up to 1.05. More...
 
static decimal TruncateTo3DecimalPlaces (this decimal value)
 Will truncate the provided decimal, without rounding, to 3 decimal places More...
 
static ? decimal SmartRounding (this decimal? input)
 Provides global smart rounding, numbers larger than 1000 will round to 4 decimal places, while numbers smaller will round to 7 significant digits More...
 
static decimal SmartRounding (this decimal input)
 Provides global smart rounding, numbers larger than 1000 will round to 4 decimal places, while numbers smaller will round to 7 significant digits More...
 
static decimal SafeDecimalCast (this double input)
 Casts the specified input value to a decimal while acknowledging the overflow conditions More...
 
static decimal Normalize (this decimal input)
 Will remove any trailing zeros for the provided decimal input More...
 
static string NormalizeToStr (this decimal input)
 Will remove any trailing zeros for the provided decimal and convert to string. Uses Normalize(decimal). More...
 
static int GetDecimalPlaces (this decimal input)
 Helper method to determine the amount of decimal places associated with the given decimal More...
 
static decimal ToDecimal (this string str)
 Extension method for faster string to decimal conversion. More...
 
static decimal ToNormalizedDecimal (this string str)
 Extension method for faster string to normalized decimal conversion, i.e. 20.0% should be parsed into 0.2 More...
 
static decimal ToDecimalAllowExponent (this string str)
 Extension method for string to decimal conversion where string can represent a number with exponent xe-y More...
 
static int ToInt32 (this string str)
 Extension method for faster string to Int32 conversion. More...
 
static long ToInt64 (this string str)
 Extension method for faster string to Int64 conversion. More...
 
static bool ImplementsStreamReader (this Type baseDataType)
 Helper method to determine if a data type implements the Stream reader method More...
 
static List< string > ToCsv (this string str, int size=4)
 Breaks the specified string into csv components, all commas are considered separators More...
 
static List< string > ToCsvData (this string str, int size=4, char delimiter=',')
 Breaks the specified string into csv components, works correctly with commas in data fields More...
 
static bool TryGetFromCsv (this string csvLine, int index, out ReadOnlySpan< char > result)
 Gets the value at the specified index from a CSV line. More...
 
static bool TryGetDecimalFromCsv (this string csvLine, int index, out decimal value)
 Gets the value at the specified index from a CSV line, converted into a decimal. More...
 
static decimal GetDecimalFromCsv (this string csvLine, int index)
 Gets the value at the specified index from a CSV line, converted into a decimal. More...
 
static bool IsNaNOrInfinity (this double value)
 Check if a number is NaN or infinity More...
 
static bool IsNaNOrZero (this double value)
 Check if a number is NaN or equal to zero More...
 
static decimal GetDecimalEpsilon ()
 Gets the smallest positive number that can be added to a decimal instance and return a new value that does not == the old value More...
 
static string GetExtension (this string str)
 Extension method to extract the extension part of this file name if it matches a safe list, or return a ".custom" extension for ones which do not match. More...
 
static Stream ToStream (this string str)
 Extension method to convert strings to stream to be read. More...
 
static TimeSpan Round (this TimeSpan time, TimeSpan roundingInterval, MidpointRounding roundingType)
 Extension method to round a timeSpan to nearest timespan period. More...
 
static TimeSpan Round (this TimeSpan time, TimeSpan roundingInterval)
 Extension method to round timespan to nearest timespan period. More...
 
static DateTime RoundDown (this DateTime dateTime, TimeSpan interval)
 Extension method to round a datetime down by a timespan interval. More...
 
static DateTime RoundDownInTimeZone (this DateTime dateTime, TimeSpan roundingInterval, DateTimeZone sourceTimeZone, DateTimeZone roundingTimeZone)
 Rounds the specified date time in the specified time zone. Careful with calling this method in a loop while modifying dateTime, check unit tests. More...
 
static DateTime ExchangeRoundDown (this DateTime dateTime, TimeSpan interval, SecurityExchangeHours exchangeHours, bool extendedMarketHours)
 Extension method to round a datetime down by a timespan interval until it's within the specified exchange's open hours. This works by first rounding down the specified time using the interval, then producing a bar between that rounded time and the interval plus the rounded time and incrementally walking backwards until the exchange is open More...
 
static DateTime ExchangeRoundDownInTimeZone (this DateTime dateTime, TimeSpan interval, SecurityExchangeHours exchangeHours, DateTimeZone roundingTimeZone, bool extendedMarketHours)
 Extension method to round a datetime down by a timespan interval until it's within the specified exchange's open hours. The rounding is performed in the specified time zone More...
 
static bool IsMarketOpen (this Security security, bool extendedMarketHours)
 Helper method to determine if a specific market is open More...
 
static bool IsMarketOpen (this Symbol symbol, DateTime utcTime, bool extendedMarketHours)
 Helper method to determine if a specific market is open More...
 
static DateTime Round (this DateTime datetime, TimeSpan roundingInterval)
 Extension method to round a datetime to the nearest unit timespan. More...
 
static DateTime RoundUp (this DateTime time, TimeSpan interval)
 Extension method to explicitly round up to the nearest timespan interval. More...
 
static DateTime ConvertTo (this DateTime time, DateTimeZone from, DateTimeZone to, bool strict=false)
 Converts the specified time from the from time zone to the to time zone More...
 
static DateTime ConvertFromUtc (this DateTime time, DateTimeZone to, bool strict=false)
 Converts the specified time from UTC to the to time zone More...
 
static DateTime ConvertToUtc (this DateTime time, DateTimeZone from, bool strict=false)
 Converts the specified time from the from time zone to TimeZones.Utc More...
 
static bool IsCommonBusinessDay (this DateTime date)
 Business day here is defined as any day of the week that is not saturday or sunday More...
 
static void Reset (this Timer timer)
 Add the reset method to the System.Timer class. More...
 
static bool MatchesTypeName (this Type type, string typeName)
 Function used to match a type against a string type name. This function compares on the AssemblyQualfiedName, the FullName, and then just the Name of the type. More...
 
static bool IsSubclassOfGeneric (this Type type, Type possibleSuperType)
 Checks the specified type to see if it is a subclass of the possibleSuperType . This method will crawl up the inheritance heirarchy to check for equality using generic type definitions (if exists) More...
 
static string GetBetterTypeName (this Type type)
 Gets a type's name with the generic parameters filled in the way they would look when defined in code, such as converting Dictionary<1,2> to Dictionary<string,int> More...
 
static TimeSpan ToTimeSpan (this Resolution resolution)
 Converts the Resolution instance into a TimeSpan instance More...
 
static Resolution ToHigherResolutionEquivalent (this TimeSpan timeSpan, bool requireExactMatch)
 Converts the specified time span into a resolution enum value. If an exact match is not found and requireExactMatch is false, then the higher resoluion will be returned. For example, timeSpan=5min will return Minute resolution. More...
 
static bool TryParseSecurityType (this string value, out SecurityType securityType, bool ignoreCase=true)
 Attempts to convert the string into a SecurityType enum value More...
 
static T ConvertTo< T > (this string value)
 Converts the specified string value into the specified type More...
 
static object ConvertTo (this string value, Type type)
 Converts the specified string value into the specified type More...
 
static bool WaitOne (this WaitHandle waitHandle, CancellationToken cancellationToken)
 Blocks the current thread until the current T:System.Threading.WaitHandle receives a signal, while observing a T:System.Threading.CancellationToken. More...
 
static bool WaitOne (this WaitHandle waitHandle, TimeSpan timeout, CancellationToken cancellationToken)
 Blocks the current thread until the current T:System.Threading.WaitHandle is set, using a T:System.TimeSpan to measure the time interval, while observing a T:System.Threading.CancellationToken. More...
 
static bool WaitOne (this WaitHandle waitHandle, int millisecondsTimeout, CancellationToken cancellationToken)
 Blocks the current thread until the current T:System.Threading.WaitHandle is set, using a 32-bit signed integer to measure the time interval, while observing a T:System.Threading.CancellationToken. More...
 
static byte[] GetMD5Hash (this Stream stream)
 Gets the MD5 hash from a stream More...
 
static string WithEmbeddedHtmlAnchors (this string source)
 Convert a string into the same string with a URL! :) More...
 
static string GetStringBetweenChars (this string value, char left, char right)
 Get the first occurence of a string between two characters from another string More...
 
static string SingleOrAlgorithmTypeName (this List< string > names, string algorithmTypeName)
 Return the first in the series of names, or find the one that matches the configured algorithmTypeName More...
 
static string ToLower (this Enum @enum)
 Converts the specified enum value to its corresponding lower-case string representation More...
 
static bool IsValid (this SecurityType securityType)
 Asserts the specified securityType value is valid More...
 
static bool IsOption (this SecurityType securityType)
 Determines if the provided SecurityType is a type of Option. Valid option types are: Equity Options, Futures Options, and Index Options. More...
 
static bool HasOptions (this SecurityType securityType)
 Determines if the provided SecurityType has a matching option SecurityType, used to represent the current SecurityType as a derivative. More...
 
static OptionStyle DefaultOptionStyle (this SecurityType securityType)
 Gets the default OptionStyle for the provided SecurityType More...
 
static OptionStyle ParseOptionStyle (this string optionStyle)
 Converts the specified string to its corresponding OptionStyle More...
 
static OptionRight ParseOptionRight (this string optionRight)
 Converts the specified string to its corresponding OptionRight More...
 
static string ToStringPerformance (this OptionRight optionRight)
 Converts the specified optionRight value to its corresponding string representation More...
 
static string OptionRightToLower (this OptionRight optionRight)
 Converts the specified optionRight value to its corresponding lower-case string representation More...
 
static string OptionStyleToLower (this OptionStyle optionStyle)
 Converts the specified optionStyle value to its corresponding lower-case string representation More...
 
static ? DataMappingMode ParseDataMappingMode (this string dataMappingMode)
 Converts the specified string to its corresponding DataMappingMode More...
 
static string SecurityTypeToLower (this SecurityType securityType)
 Converts the specified securityType value to its corresponding lower-case string representation More...
 
static string TickTypeToLower (this TickType tickType)
 Converts the specified tickType value to its corresponding lower-case string representation More...
 
static string ResolutionToLower (this Resolution resolution)
 Converts the specified resolution value to its corresponding lower-case string representation More...
 
static OrderTicket ToOrderTicket (this Order order, SecurityTransactionManager transactionManager)
 Turn order into an order ticket More...
 
static void ProcessUntilEmpty< T > (this IProducerConsumerCollection< T > collection, Action< T > handler)
 Process all items in collection through given handler More...
 
static string ToSafeString (this PyObject pyObject)
 Returns a string that represents the current PyObject More...
 
static bool TryConvert< T > (this PyObject pyObject, out T result, bool allowPythonDerivative=false)
 Tries to convert a PyObject into a managed object More...
 
static bool TryConvertToDelegate< T > (this PyObject pyObject, out T result)
 Tries to convert a PyObject into a managed object More...
 
static dynamic SafeAsManagedObject (this PyObject pyObject, Type typeToConvertTo=null)
 Safely convert PyObject to ManagedObject using Py.GIL Lock If no type is given it will convert the PyObject's Python Type to a ManagedObject Type in a attempt to resolve the target type to convert to. More...
 
static Func< IEnumerable< T >, IEnumerable< Symbol > > ConvertPythonUniverseFilterFunction< T > (this PyObject universeFilterFunc)
 Converts a Python function to a managed function returning a Symbol More...
 
static Func< IEnumerable< T >, IEnumerable< Symbol > > ConvertToUniverseSelectionSymbolDelegate< T > (this Func< IEnumerable< T >, object > selector)
 Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<Symbol> More...
 
static Func< T, IEnumerable< Symbol > > ConvertSelectionSymbolDelegate< T > (this Func< T, object > selector)
 Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<Symbol> More...
 
static Func< T, IEnumerable< string > > ConvertToUniverseSelectionStringDelegate< T > (this Func< T, object > selector)
 Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<String> More...
 
static T ConvertToDelegate< T > (this PyObject pyObject)
 Convert a PyObject into a managed object More...
 
static Dictionary< TKey, TValue > ConvertToDictionary< TKey, TValue > (this PyObject pyObject)
 Convert a PyObject into a managed dictionary More...
 
static IEnumerable< SymbolConvertToSymbolEnumerable (this PyObject pyObject)
 Gets Enumerable of Symbol from a PyObject More...
 
static PyList ToPyList (this IEnumerable enumerable)
 Converts an IEnumerable to a PyList More...
 
static PyList ToPyListUnSafe (this IEnumerable enumerable)
 Converts an IEnumerable to a PyList More...
 
static string GetEnumString (this int value, PyObject pyObject)
 Converts the numeric value of one or more enumerated constants to an equivalent enumerated string. More...
 
static bool TryCreateType (this PyObject pyObject, out Type type)
 Try to create a type with a given name, if PyObject is not a CLR type. Otherwise, convert it. More...
 
static Type CreateType (this PyObject pyObject)
 Creates a type with a given name, if PyObject is not a CLR type. Otherwise, convert it. More...
 
static AssemblyName GetAssemblyName (this PyObject pyObject)
 Helper method to get the assembly name from a python type More...
 
static IEnumerable< List< T > > BatchBy< T > (this IEnumerable< T > enumerable, int batchSize)
 Performs on-line batching of the specified enumerator, emitting chunks of the requested batch size More...
 
static TResult SynchronouslyAwaitTaskResult< TResult > (this Task< TResult > task)
 Safely blocks until the specified task has completed executing More...
 
static void SynchronouslyAwaitTask (this Task task)
 Safely blocks until the specified task has completed executing More...
 
static T SynchronouslyAwaitTask< T > (this Task< T > task)
 Safely blocks until the specified task has completed executing More...
 
static string ToQueryString (this IDictionary< string, object > pairs)
 Convert dictionary to query string More...
 
static string RemoveFromEnd (this string s, string ending)
 Returns a new string in which specified ending in the current instance is removed. More...
 
static string RemoveFromStart (this string s, string start)
 Returns a new string in which specified start in the current instance is removed. More...
 
static bool TryGetLiveSubscriptionSymbol (this Symbol symbol, out Symbol mapped)
 Helper method to determine symbol for a live subscription More...
 
static DateTime GetDelistingDate (this Symbol symbol, MapFile mapFile=null)
 Gets the delisting date for the provided Symbol More...
 
static bool IsCustomDataType< T > (this Symbol symbol)
 Helper method to determine if a given symbol is of custom data More...
 
static Symbol AdjustSymbolByOffset (this Symbol symbol, uint offset)
 Helper method that will return a back month, with future expiration, future contract based on the given offset More...
 
static void UnsubscribeWithMapping (this IDataQueueHandler dataQueueHandler, SubscriptionDataConfig dataConfig)
 Helper method to unsubscribe a given configuration, handling any required mapping More...
 
static IEnumerator< BaseDataSubscribeWithMapping (this IDataQueueHandler dataQueueHandler, SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler, Func< SubscriptionDataConfig, bool > isExpired, out SubscriptionDataConfig subscribedConfig)
 Helper method to subscribe a given configuration, handling any required mapping More...
 
static IEnumerable< string > ReadLines (this IDataProvider dataProvider, string file)
 Helper method to stream read lines from a file More...
 
static BaseData Scale (this BaseData data, Func< decimal, decimal, decimal, decimal > factorFunc, decimal volumeFactor, decimal factor, decimal sumOfDividends)
 Scale data based on factor function More...
 
static BaseData Normalize (this BaseData data, decimal factor, DataNormalizationMode normalizationMode, decimal sumOfDividends)
 Normalize prices based on configuration More...
 
static DateTime GetUpdatePriceScaleFrontier (this BaseData data)
 Helper method to determine if price scales need an update based on the given data point More...
 
static IOrderedEnumerable< KeyValuePair< TSource, TKey > > OrderBySafe< TSource, TKey > (this ConcurrentDictionary< TSource, TKey > source, Func< KeyValuePair< TSource, TKey >, TSource > keySelector)
 Thread safe concurrent dictionary order by implementation by using SafeEnumeration<TSource,TKey> More...
 
static IOrderedEnumerable< KeyValuePair< TSource, TKey > > OrderBySafe< TSource, TKey > (this ConcurrentDictionary< TSource, TKey > source, Func< KeyValuePair< TSource, TKey >, TKey > keySelector)
 Thread safe concurrent dictionary order by implementation by using SafeEnumeration<TSource,TKey> More...
 
static IEnumerable< KeyValuePair< TSource, TKey > > SafeEnumeration< TSource, TKey > (this ConcurrentDictionary< TSource, TKey > source)
 Force concurrent dictionary enumeration using a thread safe implementation More...
 
static DataNormalizationMode GetUniverseNormalizationModeOrDefault (this UniverseSettings universeSettings, SecurityType securityType)
 Helper method to determine the right data normalization mode to use by default More...
 
static string ToHexString (this byte[] source)
 Returns a hex string of the byte array. More...
 
static OrderDirection GetExerciseDirection (this OptionRight right, bool isShort)
 Gets the option exercise order direction resulting from the specified right and whether or not we wrote the option (isShort is More...
 
static OrderDirection GetOrderDirection (decimal quantity)
 Gets the OrderDirection for the specified quantity More...
 
static void ProcessSecurityChanges (this IAlgorithm algorithm, SecurityChanges securityChanges)
 Helper method to process an algorithms security changes, will add and remove securities according to them More...
 
static void SetRuntimeError (this IAlgorithm algorithm, Exception exception, string context)
 Helper method to set an algorithm runtime exception in a normalized fashion More...
 
static OptionChainUniverse CreateOptionChain (this IAlgorithm algorithm, Symbol symbol, PyObject filter, UniverseSettings universeSettings=null)
 Creates a OptionChainUniverse for a given symbol More...
 
static OptionChainUniverse CreateOptionChain (this IAlgorithm algorithm, Symbol symbol, Func< OptionFilterUniverse, OptionFilterUniverse > filter, UniverseSettings universeSettings=null)
 Creates a OptionChainUniverse for a given symbol More...
 
static IEnumerable< UniverseCreateFutureChain (this IAlgorithm algorithm, Symbol symbol, PyObject filter, UniverseSettings universeSettings=null)
 Creates a FuturesChainUniverse for a given symbol More...
 
static IEnumerable< UniverseCreateFutureChain (this IAlgorithm algorithm, Symbol symbol, Func< FutureFilterUniverse, FutureFilterUniverse > filter, UniverseSettings universeSettings=null)
 Creates a FuturesChainUniverse for a given symbol More...
 
static bool GetOrAddUnrequestedSecurity (this IAlgorithm algorithm, Symbol symbol, out Security security, Action< IReadOnlyCollection< SecurityType >> onError=null)
 Gets the security for the specified symbol from the algorithm's securities collection. In case the security is not found, it will be created using the IAlgorithm.UniverseSettings and a best effort configuration setup. More...
 
static OptionRight Invert (this OptionRight right)
 Inverts the specified right More...
 
static bool Compare< T > (this ComparisonOperatorTypes op, T arg1, T arg2)
 Compares two values using given operator More...
 
static SubscriptionDataConfig ToSubscriptionDataConfig (this Data.HistoryRequest request, bool isInternalFeed=false, bool isFilteredSubscription=true)
 Converts a Data.HistoryRequest instance to a SubscriptionDataConfig instance More...
 
static bool ShouldEmitData (this SubscriptionDataConfig config, BaseData data, bool isUniverse=false)
 Centralized logic used at the top of the subscription enumerator stacks to determine if we should emit base data points based on the configuration for this subscription and the type of data we are handling. More...
 
static OrderDirection ToOrderDirection (this PositionSide side)
 Gets the OrderDirection that corresponds to the specified side More...
 
static bool Closes (this OrderDirection direction, PositionSide side)
 Determines if an order with the specified direction would close a position with the specified side More...
 
static bool ListEquals< T > (this IReadOnlyList< T > left, IReadOnlyList< T > right)
 Determines if the two lists are equal, including all items at the same indices. More...
 
static int GetListHashCode< T > (this IReadOnlyList< T > list)
 Computes a deterministic hash code based on the items in the list. This hash code is dependent on the ordering of items. More...
 
static bool RequiresMapping (this Symbol symbol)
 Determine if this SecurityType requires mapping More...
 
static bool IsWin (this OrderEvent fill, Security security, decimal profitLoss)
 Checks whether the fill event for closing a trade is a winning trade More...
 
static ConvertibleCashAmount InTheMoneyAmount (this Option option, decimal quantity)
 Gets the option's ITM amount for the given quantity. More...
 
static int GreatestCommonDivisor (this IEnumerable< int > values)
 Gets the greatest common divisor of a list of numbers More...
 
static decimal SafeDivision (this decimal numerator, decimal denominator, decimal failValue=0)
 Safe method to perform divisions avoiding DivideByZeroException and Overflow/Underflow exceptions More...
 
static Type GetCustomDataTypeFromSymbols (Symbol[] symbols)
 Retrieve a common custom data types from the given symbols if any More...
 
static bool IsCustomDataType (Symbol symbol, Type type)
 Determines if certain data type is custom More...
 
static CashAmount GetMarketOrderFees (Security security, decimal quantity, DateTime time, out MarketOrder marketOrder)
 Returns the amount of fee's charged by executing a market order with the given arguments More...
 

Properties

static TimeSpan DelistingMarketCloseOffsetSpan = TimeSpan.FromMinutes(-15) [get, set]
 The offset span from the market close to liquidate or exercise a security on the delisting date More...
 

Detailed Description

Extensions function collections - group all static extensions functions here.

Definition at line 69 of file Extensions.cs.

Member Function Documentation

◆ TryGetPropertyValue< T >()

static T QuantConnect.Extensions.TryGetPropertyValue< T > ( this JObject  jObject,
string  name 
)
static

Helper method to get a property in a jobject if available

Template Parameters
TThe property type
Parameters
jObjectThe jobject source
nameThe property name
Returns
The property value if present or it's default value

Definition at line 106 of file Extensions.cs.

◆ IsOutOfDate()

static bool QuantConnect.Extensions.IsOutOfDate ( this string  filepath)
static

Determine if the file is out of date according to our download period. Date based files are never out of date (Files with YYYYMMDD)

Parameters
filepathPath to the file
Returns
True if the file is out of date

Definition at line 128 of file Extensions.cs.

◆ IsDirectoryEmpty()

static bool QuantConnect.Extensions.IsDirectoryEmpty ( this string  directoryPath)
static

Helper method to check if a directory exists and is not empty

Parameters
directoryPathThe path to check
Returns
True if the directory does not exist or is empty

Will cache results

Definition at line 141 of file Extensions.cs.

Here is the call graph for this function:

◆ GetEntry()

static MarketHoursDatabase.Entry QuantConnect.Extensions.GetEntry ( this MarketHoursDatabase  marketHoursDatabase,
Symbol  symbol,
IEnumerable< Type >  dataTypes 
)
static

Helper method to get a market hours entry

Parameters
marketHoursDatabaseThe market hours data base instance
symbolThe symbol to get the entry for
dataTypesFor custom data types can optionally provide data type so that a new entry is added

Definition at line 178 of file Extensions.cs.

Here is the call graph for this function:

◆ DeserializeList()

static List<string> QuantConnect.Extensions.DeserializeList ( this string  jsonArray)
static

Helper method to deserialize a json array into a list also handling single json values

Parameters
jsonArrayThe value to deserialize

Definition at line 212 of file Extensions.cs.

◆ DeserializeList< T >()

static List<T> QuantConnect.Extensions.DeserializeList< T > ( this string  jsonArray)
static

Helper method to deserialize a json array into a list also handling single json values

Parameters
jsonArrayThe value to deserialize

Definition at line 221 of file Extensions.cs.

◆ DownloadData() [1/2]

static string QuantConnect.Extensions.DownloadData ( this HttpClient  client,
string  url,
Dictionary< string, string >  headers = null 
)
static

Helper method to download a provided url as a string

Parameters
clientThe http client to use
urlThe url to download data from
headersAdd custom headers for the request

Definition at line 252 of file Extensions.cs.

Here is the call graph for this function:

◆ DownloadData() [2/2]

static string QuantConnect.Extensions.DownloadData ( this string  url,
Dictionary< string, string >  headers = null 
)
static

Helper method to download a provided url as a string

Parameters
urlThe url to download data from
headersAdd custom headers for the request

Definition at line 283 of file Extensions.cs.

◆ DownloadByteArray()

static byte [] QuantConnect.Extensions.DownloadByteArray ( this string  url)
static

Helper method to download a provided url as a byte array

Parameters
urlThe url to download data from

Definition at line 293 of file Extensions.cs.

Here is the call graph for this function:

◆ SafeMultiply100()

static decimal QuantConnect.Extensions.SafeMultiply100 ( this decimal  value)
static

Safe multiplies a decimal by 100

Parameters
valueThe decimal to multiply
Returns
The result, maxed out at decimal.MaxValue

Definition at line 314 of file Extensions.cs.

◆ GetMemoryStream()

static MemoryStream QuantConnect.Extensions.GetMemoryStream ( Guid  guid)
static

Will return a memory stream using the RecyclableMemoryStreamManager instance.

Parameters
guidUnique guid
Returns
A memory stream

Definition at line 327 of file Extensions.cs.

Here is the caller graph for this function:

◆ ProtobufSerialize() [1/3]

static byte [] QuantConnect.Extensions.ProtobufSerialize ( this List< Tick ticks,
Guid  guid 
)
static

Serialize a list of ticks using protobuf

Parameters
ticksThe list of ticks to serialize
guidUnique guid
Returns
The resulting byte array

Definition at line 338 of file Extensions.cs.

Here is the call graph for this function:

◆ ProtobufSerialize() [2/3]

static byte [] QuantConnect.Extensions.ProtobufSerialize ( this IBaseData  baseData,
Guid  guid 
)
static

Serialize a base data instance using protobuf

Parameters
baseDataThe data point to serialize
guidUnique guid
Returns
The resulting byte array

Definition at line 355 of file Extensions.cs.

Here is the call graph for this function:

◆ ProtobufSerialize() [3/3]

static void QuantConnect.Extensions.ProtobufSerialize ( this IBaseData  baseData,
Stream  stream 
)
static

Serialize a base data instance using protobuf

Parameters
baseDataThe data point to serialize
streamThe destination stream

Definition at line 372 of file Extensions.cs.

◆ GetZeroPriceMessage()

static string QuantConnect.Extensions.GetZeroPriceMessage ( this Symbol  symbol)
static

Extension method to get security price is 0 messages for users

The value of this method is normalization

Definition at line 395 of file Extensions.cs.

Here is the call graph for this function:

◆ ToCamelCase()

static string QuantConnect.Extensions.ToCamelCase ( this string  value)
static

Converts the provided string into camel case notation

Definition at line 403 of file Extensions.cs.

◆ Batch()

static AlphaResultPacket QuantConnect.Extensions.Batch ( this List< AlphaResultPacket resultPackets)
static

Helper method to batch a collection of AlphaResultPacket into 1 single instance. Will return null if the provided list is empty. Will keep the last Order instance per order id, which is the latest. Implementations trusts the provided 'resultPackets' list to batch is in order

Definition at line 422 of file Extensions.cs.

◆ StopSafely()

static void QuantConnect.Extensions.StopSafely ( this Thread  thread,
TimeSpan  timeout,
CancellationTokenSource  token = null 
)
static

Helper method to safely stop a running thread

Parameters
threadThe thread to stop
timeoutThe timeout to wait till the thread ends after which abort will be called
tokenCancellation token source to use if any

Definition at line 483 of file Extensions.cs.

Here is the call graph for this function:

◆ GetHash()

static string QuantConnect.Extensions.GetHash ( this IDictionary< int, Order orders)
static

Generates a hash code from a given collection of orders

Parameters
ordersThe order collection
Returns
The hash value

Definition at line 513 of file Extensions.cs.

◆ ToFunc()

static Func<DateTime, DateTime?> QuantConnect.Extensions.ToFunc ( this IDateRule  dateRule)
static

Converts a date rule into a function that receives current time and returns the next date.

Parameters
dateRuleThe date rule to convert
Returns
A function that will enumerate the provided date rules

Definition at line 565 of file Extensions.cs.

Here is the call graph for this function:

◆ IsEmpty() [1/2]

static bool QuantConnect.Extensions.IsEmpty ( this BaseSeries  series)
static

Returns true if the specified BaseSeries instance holds no ISeriesPoint

Definition at line 602 of file Extensions.cs.

◆ IsEmpty() [2/2]

static bool QuantConnect.Extensions.IsEmpty ( this Chart  chart)
static

Returns if the specified Chart instance holds no Series or they are all empty Extensions.IsEmpty(BaseSeries)

Definition at line 611 of file Extensions.cs.

◆ GetPythonMethod()

static dynamic QuantConnect.Extensions.GetPythonMethod ( this PyObject  instance,
string  name 
)
static

Gets a python method by name

Parameters
instanceThe object instance to search the method in
nameThe name of the method
Returns
The python method or null if not defined or CSharp implemented

Definition at line 622 of file Extensions.cs.

◆ GetPythonBoolProperty()

static dynamic QuantConnect.Extensions.GetPythonBoolProperty ( this PyObject  instance,
string  name 
)
static

Gets a python property by name

Parameters
instanceThe object instance to search the property in
nameThe name of the property
Returns
The python property or null if not defined or CSharp implemented

Definition at line 658 of file Extensions.cs.

◆ GetPythonBoolPropertyWithChecks()

static dynamic QuantConnect.Extensions.GetPythonBoolPropertyWithChecks ( this PyObject  instance,
string  name 
)
static

Gets a python property by name

Parameters
instanceThe object instance to search the property in
nameThe name of the method
Returns
The python property or null if not defined or CSharp implemented

Definition at line 687 of file Extensions.cs.

◆ GetPythonMethodWithChecks()

static dynamic QuantConnect.Extensions.GetPythonMethodWithChecks ( this PyObject  instance,
string  name 
)
static

Gets a python method by name

Parameters
instanceThe object instance to search the method in
nameThe name of the method
Returns
The python method or null if not defined or CSharp implemented

Definition at line 706 of file Extensions.cs.

◆ GetMethod()

static dynamic QuantConnect.Extensions.GetMethod ( this PyObject  instance,
string  name 
)
static

Gets a method from a PyObject instance by name. First, it tries to get the snake-case version of the method name, in case the user is using that style. Else, it tries to get the method with the original name, regardless of whether the class has a Python overload or not.

Parameters
instanceThe object instance to search the method in
nameThe name of the method
Returns
The method matching the name

Definition at line 727 of file Extensions.cs.

◆ GetPythonArgCount()

static int QuantConnect.Extensions.GetPythonArgCount ( this PyObject  method)
static

Get a python methods arg count

Parameters
methodThe Python method
Returns
Count of arguments

Definition at line 738 of file Extensions.cs.

◆ OrderTargetsByMarginImpact()

static IEnumerable<IPortfolioTarget> QuantConnect.Extensions.OrderTargetsByMarginImpact ( this IEnumerable< IPortfolioTarget targets,
IAlgorithm  algorithm,
bool  targetIsDelta = false 
)
static

Returns an ordered enumerable where position reducing orders are executed first and the remaining orders are executed in decreasing order value. Will NOT return targets during algorithm warmup. Will NOT return targets for securities that have no data yet. Will NOT return targets for which current holdings + open orders quantity, sum up to the target quantity

Parameters
targetsThe portfolio targets to order by margin
algorithmThe algorithm instance
targetIsDeltaTrue if the target quantity is the delta between the desired and existing quantity

Definition at line 765 of file Extensions.cs.

Here is the call graph for this function:

◆ GetBaseDataInstance()

static BaseData QuantConnect.Extensions.GetBaseDataInstance ( this Type  type)
static

Given a type will create a new instance using the parameterless constructor and assert the type implements BaseData

One of the objectives of this method is to normalize the creation of the BaseData instances while reducing code duplication

Definition at line 810 of file Extensions.cs.

Here is the call graph for this function:

◆ GetAndDispose< T >()

static T QuantConnect.Extensions.GetAndDispose< T > ( this PyObject  instance)
static

Helper method that will cast the provided PyObject to a T type and dispose of it.

Template Parameters
TThe target type
Parameters
instanceThe PyObject instance to cast and dispose
Returns
The instance of type T. Will return default value if provided instance is null

Definition at line 843 of file Extensions.cs.

◆ Move< T >()

static void QuantConnect.Extensions.Move< T > ( this List< T >  list,
int  oldIndex,
int  newIndex 
)
static

Extension to move one element from list from A to position B.

Template Parameters
TType of list
Parameters
listList we're operating on.
oldIndexIndex of variable we want to move.
newIndexNew location for the variable

Definition at line 862 of file Extensions.cs.

◆ GetBytes() [1/2]

static byte [] QuantConnect.Extensions.GetBytes ( this string  str)
static

Extension method to convert a string into a byte array

Parameters
strString to convert to bytes.
Returns
Byte array

Definition at line 875 of file Extensions.cs.

◆ GetBytes() [2/2]

static byte [] QuantConnect.Extensions.GetBytes ( this Stream  stream)
static

Reads the entire content of a stream and returns it as a byte array.

Parameters
streamStream to read bytes from
Returns
The bytes read from the stream

Definition at line 887 of file Extensions.cs.

◆ Clear< T >()

static void QuantConnect.Extensions.Clear< T > ( this ConcurrentQueue< T >  queue)
static

Extentsion method to clear all items from a thread safe queue

Small risk of race condition if a producer is adding to the list.

Template Parameters
TQueue type
Parameters
queuequeue object

Definition at line 900 of file Extensions.cs.

◆ GetString()

static string QuantConnect.Extensions.GetString ( this byte[]  bytes,
Encoding  encoding = null 
)
static

Extension method to convert a byte array into a string.

Parameters
bytesByte array to convert.
encodingThe encoding to use for the conversion. Defaults to Encoding.ASCII
Returns
String from bytes.

Definition at line 914 of file Extensions.cs.

◆ ToMD5()

static string QuantConnect.Extensions.ToMD5 ( this string  str)
static

Extension method to convert a string to a MD5 hash.

Parameters
strString we want to MD5 encode.
Returns
MD5 hash of a string

Definition at line 926 of file Extensions.cs.

◆ ToSHA256()

static string QuantConnect.Extensions.ToSHA256 ( this string  data)
static

Encrypt the token:time data to make our API hash.

Parameters
dataData to be hashed by SHA256
Returns
Hashed string.

Definition at line 945 of file Extensions.cs.

◆ EncodeBase36()

static string QuantConnect.Extensions.EncodeBase36 ( this ulong  data)
static

Converts a long to an uppercase alpha numeric string

Definition at line 962 of file Extensions.cs.

◆ DecodeBase36()

static ulong QuantConnect.Extensions.DecodeBase36 ( this string  symbol)
static

Converts an upper case alpha numeric string into a long

Definition at line 981 of file Extensions.cs.

◆ EncodeBase64()

static string QuantConnect.Extensions.EncodeBase64 ( this string  text)
static

Convert a string to Base64 Encoding

Parameters
textText to encode
Returns
Encoded result

Definition at line 1006 of file Extensions.cs.

◆ DecodeBase64()

static string QuantConnect.Extensions.DecodeBase64 ( this string  base64EncodedText)
static

Decode a Base64 Encoded string

Parameters
base64EncodedTextText to decode
Returns
Decoded result

Definition at line 1022 of file Extensions.cs.

◆ LazyToUpper()

static string QuantConnect.Extensions.LazyToUpper ( this string  data)
static

Lazy string to upper implementation. Will first verify the string is not already upper and avoid the call to string.ToUpperInvariant() if possible.

Parameters
dataThe string to upper
Returns
The upper string

Definition at line 1040 of file Extensions.cs.

◆ LazyToLower()

static string QuantConnect.Extensions.LazyToLower ( this string  data)
static

Lazy string to lower implementation. Will first verify the string is not already lower and avoid the call to string.ToLowerInvariant() if possible.

Parameters
dataThe string to lower
Returns
The lower string

Definition at line 1058 of file Extensions.cs.

◆ AddOrUpdate< K, V >()

static void QuantConnect.Extensions.AddOrUpdate< K, V > ( this ConcurrentDictionary< K, V >  dictionary,
key,
value 
)
static

Extension method to automatically set the update value to same as "add" value for TryAddUpdate. This makes the API similar for traditional and concurrent dictionaries.

Template Parameters
KKey type for dictionary
VValue type for dictonary
Parameters
dictionaryDictionary object we're operating on
keyKey we want to add or update.
valueValue we want to set.

Definition at line 1078 of file Extensions.cs.

◆ AddOrUpdate< TKey, TValue >()

static TValue QuantConnect.Extensions.AddOrUpdate< TKey, TValue > ( this ConcurrentDictionary< TKey, Lazy< TValue >>  dictionary,
TKey  key,
Func< TKey, TValue >  addValueFactory,
Func< TKey, TValue, TValue >  updateValueFactory 
)
static

Extension method to automatically add/update lazy values in concurrent dictionary.

Template Parameters
TKeyKey type for dictionary
TValueValue type for dictonary
Parameters
dictionaryDictionary object we're operating on
keyKey we want to add or update.
addValueFactoryThe function used to generate a value for an absent key
updateValueFactoryThe function used to generate a new value for an existing key based on the key's existing value

Definition at line 1092 of file Extensions.cs.

◆ Add< TKey, TElement, TCollection >()

static void QuantConnect.Extensions.Add< TKey, TElement, TCollection > ( this IDictionary< TKey, TCollection >  dictionary,
TKey  key,
TElement  element 
)
static

Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created.

Template Parameters
TKeyThe key type
TElementThe collection element type
TCollectionThe collection type
Parameters
dictionaryThe source dictionary to be added to
keyThe key
elementThe element to be added
Type Constraints
TCollection :ICollection<TElement> 
TCollection :new() 

Definition at line 1108 of file Extensions.cs.

◆ Add< TKey, TElement >() [1/2]

static ImmutableDictionary<TKey, ImmutableHashSet<TElement> > QuantConnect.Extensions.Add< TKey, TElement > ( this ImmutableDictionary< TKey, ImmutableHashSet< TElement >>  dictionary,
TKey  key,
TElement  element 
)
static

Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created.

Template Parameters
TKeyThe key type
TElementThe collection element type
Parameters
dictionaryThe source dictionary to be added to
keyThe key
elementThe element to be added

Definition at line 1129 of file Extensions.cs.

◆ Add< TKey, TElement >() [2/2]

static ImmutableSortedDictionary<TKey, ImmutableHashSet<TElement> > QuantConnect.Extensions.Add< TKey, TElement > ( this ImmutableSortedDictionary< TKey, ImmutableHashSet< TElement >>  dictionary,
TKey  key,
TElement  element 
)
static

Adds the specified element to the collection with the specified key. If an entry does not exist for the specified key then one will be created.

Template Parameters
TKeyThe key type
TElementThe collection element type
Parameters
dictionaryThe source dictionary to be added to
keyThe key
elementThe element to be added

Definition at line 1154 of file Extensions.cs.

◆ Add()

static void QuantConnect.Extensions.Add ( this Ticks  dictionary,
Symbol  key,
Tick  tick 
)
static

Adds the specified Tick to the Ticks collection. If an entry does not exist for the specified key then one will be created.

Parameters
dictionaryThe ticks dictionary
keyThe symbol
tickThe tick to add

For performance we implement this method based on Add<TKey,TElement,TCollection>

Definition at line 1177 of file Extensions.cs.

◆ RoundToSignificantDigits()

static decimal QuantConnect.Extensions.RoundToSignificantDigits ( this decimal  d,
int  digits 
)
static

Extension method to round a double value to a fixed number of significant figures instead of a fixed decimal places.

Parameters
dDouble we're rounding
digitsNumber of significant figures
Returns
New double rounded to digits-significant figures

Definition at line 1193 of file Extensions.cs.

◆ ToFinancialFigures()

static string QuantConnect.Extensions.ToFinancialFigures ( this decimal  number)
static

Converts a decimal into a rounded number ending with K (thousands), M (millions), B (billions), etc.

Parameters
numberNumber to convert
Returns
Formatted number with figures written in shorthand form

Definition at line 1205 of file Extensions.cs.

◆ DiscretelyRoundBy()

static decimal QuantConnect.Extensions.DiscretelyRoundBy ( this decimal  value,
decimal  quanta,
MidpointRounding  mode = MidpointRounding.AwayFromZero 
)
static

Discretizes the value to a maximum precision specified by quanta . Quanta can be an arbitrary positive number and represents the step size. Consider a quanta equal to 0.15 and rounding a value of 1.0. Valid values would be 0.9 (6 quanta) and 1.05 (7 quanta) which would be rounded up to 1.05.

Parameters
valueThe value to be rounded by discretization
quantaThe maximum precision allowed by the value
modeSpecifies how to handle the rounding of half value, defaulting to away from zero.
Returns

Definition at line 1255 of file Extensions.cs.

◆ TruncateTo3DecimalPlaces()

static decimal QuantConnect.Extensions.TruncateTo3DecimalPlaces ( this decimal  value)
static

Will truncate the provided decimal, without rounding, to 3 decimal places

Parameters
valueThe value to truncate
Returns
New instance with just 3 decimal places

Definition at line 1274 of file Extensions.cs.

◆ SmartRounding() [1/2]

static ? decimal QuantConnect.Extensions.SmartRounding ( this decimal?  input)
static

Provides global smart rounding, numbers larger than 1000 will round to 4 decimal places, while numbers smaller will round to 7 significant digits

Definition at line 1291 of file Extensions.cs.

◆ SmartRounding() [2/2]

static decimal QuantConnect.Extensions.SmartRounding ( this decimal  input)
static

Provides global smart rounding, numbers larger than 1000 will round to 4 decimal places, while numbers smaller will round to 7 significant digits

Definition at line 1304 of file Extensions.cs.

◆ SafeDecimalCast()

static decimal QuantConnect.Extensions.SafeDecimalCast ( this double  input)
static

Casts the specified input value to a decimal while acknowledging the overflow conditions

Parameters
inputThe value to be cast
Returns
The input value as a decimal, if the value is too large or to small to be represented as a decimal, then the closest decimal value will be returned

Definition at line 1325 of file Extensions.cs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ Normalize() [1/2]

static decimal QuantConnect.Extensions.Normalize ( this decimal  input)
static

Will remove any trailing zeros for the provided decimal input

Parameters
inputThe decimal to remove trailing zeros from
Returns
Provided input with no trailing zeros

Will not have the expected behavior when called from Python, since the returned decimal will be converted to python float, NormalizeToStr

Definition at line 1349 of file Extensions.cs.

◆ NormalizeToStr()

static string QuantConnect.Extensions.NormalizeToStr ( this decimal  input)
static

Will remove any trailing zeros for the provided decimal and convert to string. Uses Normalize(decimal).

Parameters
inputThe decimal to convert to string
Returns
Input converted to string with no trailing zeros

Definition at line 1361 of file Extensions.cs.

◆ GetDecimalPlaces()

static int QuantConnect.Extensions.GetDecimalPlaces ( this decimal  input)
static

Helper method to determine the amount of decimal places associated with the given decimal

Parameters
inputThe value to get the decimal count from
Returns
The quantity of decimal places

Definition at line 1371 of file Extensions.cs.

◆ ToDecimal()

static decimal QuantConnect.Extensions.ToDecimal ( this string  str)
static

Extension method for faster string to decimal conversion.

Parameters
strString to be converted to positive decimal value

Leading and trailing whitespace chars are ignored

Returns
Decimal value of the string

Definition at line 1384 of file Extensions.cs.

◆ ToNormalizedDecimal()

static decimal QuantConnect.Extensions.ToNormalizedDecimal ( this string  str)
static

Extension method for faster string to normalized decimal conversion, i.e. 20.0% should be parsed into 0.2

Parameters
strString to be converted to positive decimal value

Leading and trailing whitespace chars are ignored

Returns
Decimal value of the string

Definition at line 1435 of file Extensions.cs.

◆ ToDecimalAllowExponent()

static decimal QuantConnect.Extensions.ToDecimalAllowExponent ( this string  str)
static

Extension method for string to decimal conversion where string can represent a number with exponent xe-y

Parameters
strString to be converted to decimal value
Returns
Decimal value of the string

Definition at line 1452 of file Extensions.cs.

◆ ToInt32()

static int QuantConnect.Extensions.ToInt32 ( this string  str)
static

Extension method for faster string to Int32 conversion.

Parameters
strString to be converted to positive Int32 value

Method makes some assuptions - always numbers, no "signs" +,- etc.

Returns
Int32 value of the string

Definition at line 1463 of file Extensions.cs.

◆ ToInt64()

static long QuantConnect.Extensions.ToInt64 ( this string  str)
static

Extension method for faster string to Int64 conversion.

Parameters
strString to be converted to positive Int64 value

Method makes some assuptions - always numbers, no "signs" +,- etc.

Returns
Int32 value of the string

Definition at line 1482 of file Extensions.cs.

◆ ImplementsStreamReader()

static bool QuantConnect.Extensions.ImplementsStreamReader ( this Type  baseDataType)
static

Helper method to determine if a data type implements the Stream reader method

Definition at line 1498 of file Extensions.cs.

◆ ToCsv()

static List<string> QuantConnect.Extensions.ToCsv ( this string  str,
int  size = 4 
)
static

Breaks the specified string into csv components, all commas are considered separators

Parameters
strThe string to be broken into csv
sizeThe expected size of the output list
Returns
A list of the csv pieces

Definition at line 1521 of file Extensions.cs.

◆ ToCsvData()

static List<string> QuantConnect.Extensions.ToCsvData ( this string  str,
int  size = 4,
char  delimiter = ',' 
)
static

Breaks the specified string into csv components, works correctly with commas in data fields

Parameters
strThe string to be broken into csv
sizeThe expected size of the output list
delimiterThe delimiter used to separate entries in the line
Returns
A list of the csv pieces

Definition at line 1546 of file Extensions.cs.

◆ TryGetFromCsv()

static bool QuantConnect.Extensions.TryGetFromCsv ( this string  csvLine,
int  index,
out ReadOnlySpan< char >  result 
)
static

Gets the value at the specified index from a CSV line.

Parameters
csvLineThe CSV line
indexThe index of the value to be extracted from the CSV line
resultThe value at the given index
Returns
Whether there was a value at the given index and could be extracted

Definition at line 1585 of file Extensions.cs.

◆ TryGetDecimalFromCsv()

static bool QuantConnect.Extensions.TryGetDecimalFromCsv ( this string  csvLine,
int  index,
out decimal  value 
)
static

Gets the value at the specified index from a CSV line, converted into a decimal.

Parameters
csvLineThe CSV line
indexThe index of the value to be extracted from the CSV line
valueThe decimal value at the given index
Returns
Whether there was a value at the given index and could be extracted and converted into a decimal

Definition at line 1622 of file Extensions.cs.

◆ GetDecimalFromCsv()

static decimal QuantConnect.Extensions.GetDecimalFromCsv ( this string  csvLine,
int  index 
)
static

Gets the value at the specified index from a CSV line, converted into a decimal.

Parameters
csvLineThe CSV line
indexThe index of the value to be extracted from the CSV line
Returns
The decimal value at the given index. If the index is invalid or conversion fails, it will return zero

Definition at line 1640 of file Extensions.cs.

◆ IsNaNOrInfinity()

static bool QuantConnect.Extensions.IsNaNOrInfinity ( this double  value)
static

Check if a number is NaN or infinity

Parameters
valueThe double value to check

Definition at line 1651 of file Extensions.cs.

◆ IsNaNOrZero()

static bool QuantConnect.Extensions.IsNaNOrZero ( this double  value)
static

Check if a number is NaN or equal to zero

Parameters
valueThe double value to check

Definition at line 1661 of file Extensions.cs.

◆ GetDecimalEpsilon()

static decimal QuantConnect.Extensions.GetDecimalEpsilon ( )
static

Gets the smallest positive number that can be added to a decimal instance and return a new value that does not == the old value

Definition at line 1670 of file Extensions.cs.

◆ GetExtension()

static string QuantConnect.Extensions.GetExtension ( this string  str)
static

Extension method to extract the extension part of this file name if it matches a safe list, or return a ".custom" extension for ones which do not match.

Parameters
strString we're looking for the extension for.
Returns
Last 4 character string of string.

Definition at line 1680 of file Extensions.cs.

◆ ToStream()

static Stream QuantConnect.Extensions.ToStream ( this string  str)
static

Extension method to convert strings to stream to be read.

Parameters
strString to convert to stream
Returns
Stream instance

Definition at line 1695 of file Extensions.cs.

◆ Round() [1/3]

static TimeSpan QuantConnect.Extensions.Round ( this TimeSpan  time,
TimeSpan  roundingInterval,
MidpointRounding  roundingType 
)
static

Extension method to round a timeSpan to nearest timespan period.

Parameters
timeTimeSpan To Round
roundingIntervalRounding Unit
roundingTypeRounding method
Returns
Rounded timespan

Definition at line 1712 of file Extensions.cs.

◆ Round() [2/3]

static TimeSpan QuantConnect.Extensions.Round ( this TimeSpan  time,
TimeSpan  roundingInterval 
)
static

Extension method to round timespan to nearest timespan period.

Parameters
timeBase timespan we're looking to round.
roundingIntervalTimespan period we're rounding.
Returns
Rounded timespan period

Definition at line 1735 of file Extensions.cs.

◆ RoundDown()

static DateTime QuantConnect.Extensions.RoundDown ( this DateTime  dateTime,
TimeSpan  interval 
)
static

Extension method to round a datetime down by a timespan interval.

Parameters
dateTimeBase DateTime object we're rounding down.
intervalTimespan interval to round to
Returns
Rounded datetime

Using this with timespans greater than 1 day may have unintended consequences. Be aware that rounding occurs against ALL time, so when using timespan such as 30 days we will see 30 day increments but it will be based on 30 day increments from the beginning of time.

Definition at line 1751 of file Extensions.cs.

◆ RoundDownInTimeZone()

static DateTime QuantConnect.Extensions.RoundDownInTimeZone ( this DateTime  dateTime,
TimeSpan  roundingInterval,
DateTimeZone  sourceTimeZone,
DateTimeZone  roundingTimeZone 
)
static

Rounds the specified date time in the specified time zone. Careful with calling this method in a loop while modifying dateTime, check unit tests.

Parameters
dateTimeDate time to be rounded
roundingIntervalTimespan rounding period
sourceTimeZoneTime zone of the date time
roundingTimeZoneTime zone in which the rounding is performed
Returns
The rounded date time in the source time zone

Definition at line 1776 of file Extensions.cs.

◆ ExchangeRoundDown()

static DateTime QuantConnect.Extensions.ExchangeRoundDown ( this DateTime  dateTime,
TimeSpan  interval,
SecurityExchangeHours  exchangeHours,
bool  extendedMarketHours 
)
static

Extension method to round a datetime down by a timespan interval until it's within the specified exchange's open hours. This works by first rounding down the specified time using the interval, then producing a bar between that rounded time and the interval plus the rounded time and incrementally walking backwards until the exchange is open

Parameters
dateTimeTime to be rounded down
intervalTimespan interval to round to.
exchangeHoursThe exchange hours to determine open times
extendedMarketHoursTrue for extended market hours, otherwise false
Returns
Rounded datetime

Definition at line 1796 of file Extensions.cs.

Here is the call graph for this function:

◆ ExchangeRoundDownInTimeZone()

static DateTime QuantConnect.Extensions.ExchangeRoundDownInTimeZone ( this DateTime  dateTime,
TimeSpan  interval,
SecurityExchangeHours  exchangeHours,
DateTimeZone  roundingTimeZone,
bool  extendedMarketHours 
)
static

Extension method to round a datetime down by a timespan interval until it's within the specified exchange's open hours. The rounding is performed in the specified time zone

Parameters
dateTimeTime to be rounded down
intervalTimespan interval to round to.
exchangeHoursThe exchange hours to determine open times
roundingTimeZoneThe time zone to perform the rounding in
extendedMarketHoursTrue for extended market hours, otherwise false
Returns
Rounded datetime

Definition at line 1821 of file Extensions.cs.

Here is the call graph for this function:

◆ IsMarketOpen() [1/2]

static bool QuantConnect.Extensions.IsMarketOpen ( this Security  security,
bool  extendedMarketHours 
)
static

Helper method to determine if a specific market is open

Parameters
securityThe target security
extendedMarketHoursTrue if should consider extended market hours
Returns
True if the market is open

Definition at line 1850 of file Extensions.cs.

Here is the call graph for this function:

◆ IsMarketOpen() [2/2]

static bool QuantConnect.Extensions.IsMarketOpen ( this Symbol  symbol,
DateTime  utcTime,
bool  extendedMarketHours 
)
static

Helper method to determine if a specific market is open

Parameters
symbolThe target symbol
utcTimeThe current UTC time
extendedMarketHoursTrue if should consider extended market hours
Returns
True if the market is open

Definition at line 1862 of file Extensions.cs.

Here is the call graph for this function:

◆ Round() [3/3]

static DateTime QuantConnect.Extensions.Round ( this DateTime  datetime,
TimeSpan  roundingInterval 
)
static

Extension method to round a datetime to the nearest unit timespan.

Parameters
datetimeDatetime object we're rounding.
roundingIntervalTimespan rounding period.
Returns
Rounded datetime

Definition at line 1878 of file Extensions.cs.

◆ RoundUp()

static DateTime QuantConnect.Extensions.RoundUp ( this DateTime  time,
TimeSpan  interval 
)
static

Extension method to explicitly round up to the nearest timespan interval.

Parameters
timeBase datetime object to round up.
intervalTimespan interval to round to
Returns
Rounded datetime

Using this with timespans greater than 1 day may have unintended consequences. Be aware that rounding occurs against ALL time, so when using timespan such as 30 days we will see 30 day increments but it will be based on 30 day increments from the beginning of time.

Definition at line 1893 of file Extensions.cs.

◆ ConvertTo() [1/2]

static DateTime QuantConnect.Extensions.ConvertTo ( this DateTime  time,
DateTimeZone  from,
DateTimeZone  to,
bool  strict = false 
)
static

Converts the specified time from the from time zone to the to time zone

Parameters
timeThe time to be converted in terms of the from time zone
fromThe time zone the specified time is in
toThe time zone to be converted to
strictTrue for strict conversion, this will throw during ambiguitities, false for lenient conversion
Returns
The time in terms of the to time zone

Definition at line 1913 of file Extensions.cs.

◆ ConvertFromUtc()

static DateTime QuantConnect.Extensions.ConvertFromUtc ( this DateTime  time,
DateTimeZone  to,
bool  strict = false 
)
static

Converts the specified time from UTC to the to time zone

Parameters
timeThe time to be converted expressed in UTC
toThe destinatio time zone
strictTrue for strict conversion, this will throw during ambiguitities, false for lenient conversion
Returns
The time in terms of the to time zone

Definition at line 1934 of file Extensions.cs.

◆ ConvertToUtc()

static DateTime QuantConnect.Extensions.ConvertToUtc ( this DateTime  time,
DateTimeZone  from,
bool  strict = false 
)
static

Converts the specified time from the from time zone to TimeZones.Utc

Parameters
timeThe time to be converted in terms of the from time zone
fromThe time zone the specified time is in
strictTrue for strict conversion, this will throw during ambiguitities, false for lenient conversion
Returns
The time in terms of the to time zone

Definition at line 1947 of file Extensions.cs.

◆ IsCommonBusinessDay()

static bool QuantConnect.Extensions.IsCommonBusinessDay ( this DateTime  date)
static

Business day here is defined as any day of the week that is not saturday or sunday

Parameters
dateThe date to be examined
Returns
A bool indicating wether the datetime is a weekday or not

Definition at line 1965 of file Extensions.cs.

◆ Reset()

static void QuantConnect.Extensions.Reset ( this Timer  timer)
static

Add the reset method to the System.Timer class.

Parameters
timerSystem.timer object

Definition at line 1974 of file Extensions.cs.

◆ MatchesTypeName()

static bool QuantConnect.Extensions.MatchesTypeName ( this Type  type,
string  typeName 
)
static

Function used to match a type against a string type name. This function compares on the AssemblyQualfiedName, the FullName, and then just the Name of the type.

Parameters
typeThe type to test for a match
typeNameThe name of the type to match
Returns
True if the specified type matches the type name, false otherwise

Definition at line 1987 of file Extensions.cs.

◆ IsSubclassOfGeneric()

static bool QuantConnect.Extensions.IsSubclassOfGeneric ( this Type  type,
Type  possibleSuperType 
)
static

Checks the specified type to see if it is a subclass of the possibleSuperType . This method will crawl up the inheritance heirarchy to check for equality using generic type definitions (if exists)

Parameters
typeThe type to be checked as a subclass of possibleSuperType
possibleSuperTypeThe possible superclass of type
Returns
True if type is a subclass of the generic type definition possibleSuperType

Definition at line 2011 of file Extensions.cs.

◆ GetBetterTypeName()

static string QuantConnect.Extensions.GetBetterTypeName ( this Type  type)
static

Gets a type's name with the generic parameters filled in the way they would look when defined in code, such as converting Dictionary<1,2> to Dictionary<string,int>

Parameters
typeThe type who's name we seek
Returns
A better type name

Definition at line 2039 of file Extensions.cs.

◆ ToTimeSpan()

static TimeSpan QuantConnect.Extensions.ToTimeSpan ( this Resolution  resolution)
static

Converts the Resolution instance into a TimeSpan instance

Parameters
resolutionThe resolution to be converted
Returns
A TimeSpan instance that represents the resolution specified

Definition at line 2057 of file Extensions.cs.

◆ ToHigherResolutionEquivalent()

static Resolution QuantConnect.Extensions.ToHigherResolutionEquivalent ( this TimeSpan  timeSpan,
bool  requireExactMatch 
)
static

Converts the specified time span into a resolution enum value. If an exact match is not found and requireExactMatch is false, then the higher resoluion will be returned. For example, timeSpan=5min will return Minute resolution.

Parameters
timeSpanThe time span to convert to resolution
requireExactMatchTrue to throw an exception if an exact match is not found
Returns
The resolution

Definition at line 2085 of file Extensions.cs.

Here is the call graph for this function:

◆ TryParseSecurityType()

static bool QuantConnect.Extensions.TryParseSecurityType ( this string  value,
out SecurityType  securityType,
bool  ignoreCase = true 
)
static

Attempts to convert the string into a SecurityType enum value

Parameters
valuestring value to convert to SecurityType
securityTypeSecurityType output
ignoreCaseIgnore casing
Returns
true if parsed into a SecurityType successfully, false otherwise

Logs once if we've encountered an invalid SecurityType

Definition at line 2116 of file Extensions.cs.

Here is the call graph for this function:

◆ ConvertTo< T >()

static T QuantConnect.Extensions.ConvertTo< T > ( this string  value)
static

Converts the specified string value into the specified type

Template Parameters
TThe output type
Parameters
valueThe string value to be converted
Returns
The converted value

Definition at line 2138 of file Extensions.cs.

◆ ConvertTo() [2/2]

static object QuantConnect.Extensions.ConvertTo ( this string  value,
Type  type 
)
static

Converts the specified string value into the specified type

Parameters
valueThe string value to be converted
typeThe output type
Returns
The converted value

Definition at line 2149 of file Extensions.cs.

◆ WaitOne() [1/3]

static bool QuantConnect.Extensions.WaitOne ( this WaitHandle  waitHandle,
CancellationToken  cancellationToken 
)
static

Blocks the current thread until the current T:System.Threading.WaitHandle receives a signal, while observing a T:System.Threading.CancellationToken.

Parameters
waitHandleThe wait handle to wait on
cancellationTokenThe T:System.Threading.CancellationToken to observe.
Exceptions
T:System.InvalidOperationExceptionThe maximum number of waiters has been exceeded.
T:System.OperationCanceledExceptoncancellationToken was canceled.
T:System.ObjectDisposedExceptionThe object has already been disposed or the T:System.Threading.CancellationTokenSource that created cancellationToken has been disposed.

Definition at line 2180 of file Extensions.cs.

◆ WaitOne() [2/3]

static bool QuantConnect.Extensions.WaitOne ( this WaitHandle  waitHandle,
TimeSpan  timeout,
CancellationToken  cancellationToken 
)
static

Blocks the current thread until the current T:System.Threading.WaitHandle is set, using a T:System.TimeSpan to measure the time interval, while observing a T:System.Threading.CancellationToken.

Returns
true if the T:System.Threading.WaitHandle was set; otherwise, false.
Parameters
waitHandleThe wait handle to wait on
timeoutA T:System.TimeSpan that represents the number of milliseconds to wait, or a T:System.TimeSpan that represents -1 milliseconds to wait indefinitely.
cancellationTokenThe T:System.Threading.CancellationToken to observe.
Exceptions
T:System.Threading.OperationCanceledExceptioncancellationToken was canceled.
T:System.ArgumentOutOfRangeExceptiontimeout is a negative number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than F:System.Int32.MaxValue.
T:System.InvalidOperationExceptionThe maximum number of waiters has been exceeded.
T:System.ObjectDisposedExceptionThe object has already been disposed or the T:System.Threading.CancellationTokenSource that created cancellationToken has been disposed.

Definition at line 2198 of file Extensions.cs.

◆ WaitOne() [3/3]

static bool QuantConnect.Extensions.WaitOne ( this WaitHandle  waitHandle,
int  millisecondsTimeout,
CancellationToken  cancellationToken 
)
static

Blocks the current thread until the current T:System.Threading.WaitHandle is set, using a 32-bit signed integer to measure the time interval, while observing a T:System.Threading.CancellationToken.

Returns
true if the T:System.Threading.WaitHandle was set; otherwise, false.
Parameters
waitHandleThe wait handle to wait on
millisecondsTimeoutThe number of milliseconds to wait, or F:System.Threading.Timeout.Infinite(-1) to wait indefinitely.
cancellationTokenThe T:System.Threading.CancellationToken to observe.
Exceptions
T:System.Threading.OperationCanceledExceptioncancellationToken was canceled.
T:System.ArgumentOutOfRangeExceptionmillisecondsTimeout is a negative number other than -1, which represents an infinite time-out.
T:System.InvalidOperationExceptionThe maximum number of waiters has been exceeded.
T:System.ObjectDisposedExceptionThe object has already been disposed or the T:System.Threading.CancellationTokenSource that created cancellationToken has been disposed.

Definition at line 2217 of file Extensions.cs.

◆ GetMD5Hash()

static byte [] QuantConnect.Extensions.GetMD5Hash ( this Stream  stream)
static

Gets the MD5 hash from a stream

Parameters
streamThe stream to compute a hash for
Returns
The MD5 hash

Definition at line 2227 of file Extensions.cs.

◆ WithEmbeddedHtmlAnchors()

static string QuantConnect.Extensions.WithEmbeddedHtmlAnchors ( this string  source)
static

Convert a string into the same string with a URL! :)

Parameters
sourceThe source string to be converted
Returns
The same source string but with anchor tags around substrings matching a link regex

Definition at line 2240 of file Extensions.cs.

◆ GetStringBetweenChars()

static string QuantConnect.Extensions.GetStringBetweenChars ( this string  value,
char  left,
char  right 
)
static

Get the first occurence of a string between two characters from another string

Parameters
valueThe original string
leftLeft bound of the substring
rightRight bound of the substring
Returns
Substring from original string bounded by the two characters

Definition at line 2258 of file Extensions.cs.

◆ SingleOrAlgorithmTypeName()

static string QuantConnect.Extensions.SingleOrAlgorithmTypeName ( this List< string >  names,
string  algorithmTypeName 
)
static

Return the first in the series of names, or find the one that matches the configured algorithmTypeName

Parameters
namesThe list of class names
algorithmTypeNameThe configured algorithm type name from the config
Returns
The name of the class being run

Definition at line 2277 of file Extensions.cs.

◆ ToLower()

static string QuantConnect.Extensions.ToLower ( this Enum @  enum)
static

Converts the specified enum value to its corresponding lower-case string representation

Parameters
enumThe enumeration value
Returns
A lower-case string representation of the specified enumeration value

Definition at line 2294 of file Extensions.cs.

◆ IsValid()

static bool QuantConnect.Extensions.IsValid ( this SecurityType  securityType)
static

Asserts the specified securityType value is valid

This method provides faster performance than Enum.IsDefined which uses reflection

Parameters
securityTypeThe SecurityType value
Returns
True if valid security type value

Definition at line 2305 of file Extensions.cs.

◆ IsOption()

static bool QuantConnect.Extensions.IsOption ( this SecurityType  securityType)
static

Determines if the provided SecurityType is a type of Option. Valid option types are: Equity Options, Futures Options, and Index Options.

Parameters
securityTypeThe SecurityType to check if it's an option asset
Returns
true if the asset has the makings of an option (exercisable, expires, and is a derivative of some underlying), false otherwise.

Definition at line 2336 of file Extensions.cs.

◆ HasOptions()

static bool QuantConnect.Extensions.HasOptions ( this SecurityType  securityType)
static

Determines if the provided SecurityType has a matching option SecurityType, used to represent the current SecurityType as a derivative.

Parameters
securityTypeThe SecurityType to check if it has options available
Returns
true if there are options for the SecurityType, false otherwise

Definition at line 2356 of file Extensions.cs.

◆ DefaultOptionStyle()

static OptionStyle QuantConnect.Extensions.DefaultOptionStyle ( this SecurityType  securityType)
static

Gets the default OptionStyle for the provided SecurityType

Parameters
securityTypeSecurityType to get default OptionStyle for
Returns
Default OptionStyle for the SecurityType
Exceptions
ArgumentExceptionThe SecurityType has no options available for it or it is not an option

Definition at line 2376 of file Extensions.cs.

Here is the call graph for this function:

◆ ParseOptionStyle()

static OptionStyle QuantConnect.Extensions.ParseOptionStyle ( this string  optionStyle)
static

Converts the specified string to its corresponding OptionStyle

This method provides faster performance than enum parse

Parameters
optionStyleThe OptionStyle string value
Returns
The OptionStyle value

Definition at line 2400 of file Extensions.cs.

Here is the call graph for this function:

◆ ParseOptionRight()

static OptionRight QuantConnect.Extensions.ParseOptionRight ( this string  optionRight)
static

Converts the specified string to its corresponding OptionRight

This method provides faster performance than enum parse

Parameters
optionRightThe optionRight string value
Returns
The OptionRight value

Definition at line 2419 of file Extensions.cs.

Here is the call graph for this function:

◆ ToStringPerformance()

static string QuantConnect.Extensions.ToStringPerformance ( this OptionRight  optionRight)
static

Converts the specified optionRight value to its corresponding string representation

This method provides faster performance than enum Object.ToString

Parameters
optionRightThe optionRight value
Returns
A string representation of the specified OptionRight value

Definition at line 2438 of file Extensions.cs.

◆ OptionRightToLower()

static string QuantConnect.Extensions.OptionRightToLower ( this OptionRight  optionRight)
static

Converts the specified optionRight value to its corresponding lower-case string representation

This method provides faster performance than ToLower

Parameters
optionRightThe optionRight value
Returns
A lower case string representation of the specified OptionRight value

Definition at line 2458 of file Extensions.cs.

Here is the call graph for this function:

◆ OptionStyleToLower()

static string QuantConnect.Extensions.OptionStyleToLower ( this OptionStyle  optionStyle)
static

Converts the specified optionStyle value to its corresponding lower-case string representation

This method provides faster performance than ToLower

Parameters
optionStyleThe optionStyle value
Returns
A lower case string representation of the specified optionStyle value

Definition at line 2477 of file Extensions.cs.

Here is the call graph for this function:

◆ ParseDataMappingMode()

static ? DataMappingMode QuantConnect.Extensions.ParseDataMappingMode ( this string  dataMappingMode)
static

Converts the specified string to its corresponding DataMappingMode

This method provides faster performance than enum parse

Parameters
dataMappingModeThe dataMappingMode string value
Returns
The DataMappingMode value

Definition at line 2496 of file Extensions.cs.

Here is the call graph for this function:

◆ SecurityTypeToLower()

static string QuantConnect.Extensions.SecurityTypeToLower ( this SecurityType  securityType)
static

Converts the specified securityType value to its corresponding lower-case string representation

This method provides faster performance than ToLower

Parameters
securityTypeThe SecurityType value
Returns
A lower-case string representation of the specified SecurityType value

Definition at line 2527 of file Extensions.cs.

◆ TickTypeToLower()

static string QuantConnect.Extensions.TickTypeToLower ( this TickType  tickType)
static

Converts the specified tickType value to its corresponding lower-case string representation

This method provides faster performance than ToLower

Parameters
tickTypeThe tickType value
Returns
A lower-case string representation of the specified tickType value

Definition at line 2567 of file Extensions.cs.

◆ ResolutionToLower()

static string QuantConnect.Extensions.ResolutionToLower ( this Resolution  resolution)
static

Converts the specified resolution value to its corresponding lower-case string representation

This method provides faster performance than ToLower

Parameters
resolutionThe resolution value
Returns
A lower-case string representation of the specified resolution value

Definition at line 2589 of file Extensions.cs.

◆ ToOrderTicket()

static OrderTicket QuantConnect.Extensions.ToOrderTicket ( this Order  order,
SecurityTransactionManager  transactionManager 
)
static

Turn order into an order ticket

Parameters
orderThe Order being converted
transactionManagerThe transaction manager, SecurityTransactionManager
Returns

Definition at line 2615 of file Extensions.cs.

◆ ProcessUntilEmpty< T >()

static void QuantConnect.Extensions.ProcessUntilEmpty< T > ( this IProducerConsumerCollection< T >  collection,
Action< T >  handler 
)
static

Process all items in collection through given handler

Template Parameters
T
Parameters
collectionCollection to process
handlerHandler to process those items with

Definition at line 2694 of file Extensions.cs.

◆ ToSafeString()

static string QuantConnect.Extensions.ToSafeString ( this PyObject  pyObject)
static

Returns a string that represents the current PyObject

Parameters
pyObjectThe PyObject being converted
Returns
string that represents the current PyObject

Definition at line 2708 of file Extensions.cs.

◆ TryConvert< T >()

static bool QuantConnect.Extensions.TryConvert< T > ( this PyObject  pyObject,
out T  result,
bool  allowPythonDerivative = false 
)
static

Tries to convert a PyObject into a managed object

This method is not working correctly for a wrapped TimeSpan instance, probably because it is a struct, using PyObject.As<T> is a valid work around. Not used here because it caused errors

Template Parameters
TTarget type of the resulting managed object
Parameters
pyObjectPyObject to be converted
resultManaged object
allowPythonDerivativeTrue will convert python subclasses of T
Returns
True if successful conversion

Definition at line 2755 of file Extensions.cs.

◆ TryConvertToDelegate< T >()

static bool QuantConnect.Extensions.TryConvertToDelegate< T > ( this PyObject  pyObject,
out T  result 
)
static

Tries to convert a PyObject into a managed object

Template Parameters
TTarget type of the resulting managed object
Parameters
pyObjectPyObject to be converted
resultManaged object
Returns
True if successful conversion

Definition at line 2851 of file Extensions.cs.

Here is the call graph for this function:

◆ SafeAsManagedObject()

static dynamic QuantConnect.Extensions.SafeAsManagedObject ( this PyObject  pyObject,
Type  typeToConvertTo = null 
)
static

Safely convert PyObject to ManagedObject using Py.GIL Lock If no type is given it will convert the PyObject's Python Type to a ManagedObject Type in a attempt to resolve the target type to convert to.

Parameters
pyObjectPyObject to convert to managed
typeToConvertToThe target type to convert to
Returns
The resulting ManagedObject

Definition at line 2916 of file Extensions.cs.

◆ ConvertPythonUniverseFilterFunction< T >()

static Func<IEnumerable<T>, IEnumerable<Symbol> > QuantConnect.Extensions.ConvertPythonUniverseFilterFunction< T > ( this PyObject  universeFilterFunc)
static

Converts a Python function to a managed function returning a Symbol

Parameters
universeFilterFuncUniverse filter function from Python
Returns
Function that provides T and returns an enumerable of Symbols
Type Constraints
T :BaseData 

Definition at line 2934 of file Extensions.cs.

◆ ConvertToUniverseSelectionSymbolDelegate< T >()

static Func<IEnumerable<T>, IEnumerable<Symbol> > QuantConnect.Extensions.ConvertToUniverseSelectionSymbolDelegate< T > ( this Func< IEnumerable< T >, object >  selector)
static

Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<Symbol>

This method is a work around for the fact that currently we can not create a delegate which returns an IEnumerable<Symbol> from a python method returning an array, plus the fact that Universe.Unchanged can not be cast to an array

Type Constraints
T :BaseData 

Definition at line 2954 of file Extensions.cs.

◆ ConvertSelectionSymbolDelegate< T >()

static Func<T, IEnumerable<Symbol> > QuantConnect.Extensions.ConvertSelectionSymbolDelegate< T > ( this Func< T, object >  selector)
static

Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<Symbol>

This method is a work around for the fact that currently we can not create a delegate which returns an IEnumerable<Symbol> from a python method returning an array, plus the fact that Universe.Unchanged can not be cast to an array

Definition at line 2970 of file Extensions.cs.

Here is the call graph for this function:

◆ ConvertToUniverseSelectionStringDelegate< T >()

static Func<T, IEnumerable<string> > QuantConnect.Extensions.ConvertToUniverseSelectionStringDelegate< T > ( this Func< T, object >  selector)
static

Wraps the provided universe selection selector checking if it returned Universe.Unchanged and returns it instead, else enumerates result as IEnumerable<String>

This method is a work around for the fact that currently we can not create a delegate which returns an IEnumerable<String> from a python method returning an array, plus the fact that Universe.Unchanged can not be cast to an array

Definition at line 2995 of file Extensions.cs.

◆ ConvertToDelegate< T >()

static T QuantConnect.Extensions.ConvertToDelegate< T > ( this PyObject  pyObject)
static

Convert a PyObject into a managed object

Template Parameters
TTarget type of the resulting managed object
Parameters
pyObjectPyObject to be converted
Returns
Instance of type T

Definition at line 3011 of file Extensions.cs.

Here is the call graph for this function:

◆ ConvertToDictionary< TKey, TValue >()

static Dictionary<TKey, TValue> QuantConnect.Extensions.ConvertToDictionary< TKey, TValue > ( this PyObject  pyObject)
static

Convert a PyObject into a managed dictionary

Template Parameters
TKeyTarget type of the resulting dictionary key
TValueTarget type of the resulting dictionary value
Parameters
pyObjectPyObject to be converted
Returns
Dictionary of TValue keyed by TKey

Definition at line 3031 of file Extensions.cs.

Here is the call graph for this function:

◆ ConvertToSymbolEnumerable()

static IEnumerable<Symbol> QuantConnect.Extensions.ConvertToSymbolEnumerable ( this PyObject  pyObject)
static

Gets Enumerable of Symbol from a PyObject

Parameters
pyObjectPyObject containing Symbol or Array of Symbol
Returns
Enumerable of Symbol

Definition at line 3070 of file Extensions.cs.

◆ ToPyList()

static PyList QuantConnect.Extensions.ToPyList ( this IEnumerable  enumerable)
static

Converts an IEnumerable to a PyList

Parameters
enumerableIEnumerable object to convert
Returns
PyList

Definition at line 3137 of file Extensions.cs.

◆ ToPyListUnSafe()

static PyList QuantConnect.Extensions.ToPyListUnSafe ( this IEnumerable  enumerable)
static

Converts an IEnumerable to a PyList

Parameters
enumerableIEnumerable object to convert

Requires the caller to own the GIL

Returns
PyList

Definition at line 3151 of file Extensions.cs.

◆ GetEnumString()

static string QuantConnect.Extensions.GetEnumString ( this int  value,
PyObject  pyObject 
)
static

Converts the numeric value of one or more enumerated constants to an equivalent enumerated string.

Parameters
valueNumeric value
pyObjectPython object that encapsulated a Enum Type
Returns
String that represents the enumerated object

Definition at line 3171 of file Extensions.cs.

◆ TryCreateType()

static bool QuantConnect.Extensions.TryCreateType ( this PyObject  pyObject,
out Type  type 
)
static

Try to create a type with a given name, if PyObject is not a CLR type. Otherwise, convert it.

Parameters
pyObjectPython object representing a type.
typeType object
Returns
True if was able to create the type

Definition at line 3193 of file Extensions.cs.

◆ CreateType()

static Type QuantConnect.Extensions.CreateType ( this PyObject  pyObject)
static

Creates a type with a given name, if PyObject is not a CLR type. Otherwise, convert it.

Parameters
pyObjectPython object representing a type.
Returns
Type object

Definition at line 3224 of file Extensions.cs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetAssemblyName()

static AssemblyName QuantConnect.Extensions.GetAssemblyName ( this PyObject  pyObject)
static

Helper method to get the assembly name from a python type

Parameters
pyObjectPython object pointing to the python type. PyObject.GetPythonType
Returns
The python type assembly name

Definition at line 3257 of file Extensions.cs.

◆ BatchBy< T >()

static IEnumerable<List<T> > QuantConnect.Extensions.BatchBy< T > ( this IEnumerable< T >  enumerable,
int  batchSize 
)
static

Performs on-line batching of the specified enumerator, emitting chunks of the requested batch size

Template Parameters
TThe enumerable item type
Parameters
enumerableThe enumerable to be batched
batchSizeThe number of items per batch
Returns
An enumerable of lists

Definition at line 3272 of file Extensions.cs.

◆ SynchronouslyAwaitTaskResult< TResult >()

static TResult QuantConnect.Extensions.SynchronouslyAwaitTaskResult< TResult > ( this Task< TResult >  task)
static

Safely blocks until the specified task has completed executing

Template Parameters
TResultThe task's result type
Parameters
taskThe task to be awaited
Returns
The result of the task

Definition at line 3307 of file Extensions.cs.

◆ SynchronouslyAwaitTask()

static void QuantConnect.Extensions.SynchronouslyAwaitTask ( this Task  task)
static

Safely blocks until the specified task has completed executing

Parameters
taskThe task to be awaited
Returns
The result of the task

Definition at line 3317 of file Extensions.cs.

◆ SynchronouslyAwaitTask< T >()

static T QuantConnect.Extensions.SynchronouslyAwaitTask< T > ( this Task< T >  task)
static

Safely blocks until the specified task has completed executing

Parameters
taskThe task to be awaited
Returns
The result of the task

Definition at line 3327 of file Extensions.cs.

◆ ToQueryString()

static string QuantConnect.Extensions.ToQueryString ( this IDictionary< string, object >  pairs)
static

Convert dictionary to query string

Parameters
pairs
Returns

Definition at line 3337 of file Extensions.cs.

◆ RemoveFromEnd()

static string QuantConnect.Extensions.RemoveFromEnd ( this string  s,
string  ending 
)
static

Returns a new string in which specified ending in the current instance is removed.

Parameters
soriginal string value
endingthe string to be removed
Returns

Definition at line 3348 of file Extensions.cs.

◆ RemoveFromStart()

static string QuantConnect.Extensions.RemoveFromStart ( this string  s,
string  start 
)
static

Returns a new string in which specified start in the current instance is removed.

Parameters
soriginal string value
startthe string to be removed
Returns
Substring with start removed

Definition at line 3366 of file Extensions.cs.

◆ TryGetLiveSubscriptionSymbol()

static bool QuantConnect.Extensions.TryGetLiveSubscriptionSymbol ( this Symbol  symbol,
out Symbol  mapped 
)
static

Helper method to determine symbol for a live subscription

Useful for continuous futures where we subscribe to the underlying

Definition at line 3382 of file Extensions.cs.

Here is the call graph for this function:

◆ GetDelistingDate()

static DateTime QuantConnect.Extensions.GetDelistingDate ( this Symbol  symbol,
MapFile  mapFile = null 
)
static

Gets the delisting date for the provided Symbol

Parameters
symbolThe symbol to lookup the last trading date
mapFileMap file to use for delisting date. Defaults to SID.DefaultDate if no value is passed and is equity.
Returns

Definition at line 3399 of file Extensions.cs.

Here is the call graph for this function:

◆ IsCustomDataType< T >()

static bool QuantConnect.Extensions.IsCustomDataType< T > ( this Symbol  symbol)
static

Helper method to determine if a given symbol is of custom data

Definition at line 3422 of file Extensions.cs.

Here is the call graph for this function:

◆ AdjustSymbolByOffset()

static Symbol QuantConnect.Extensions.AdjustSymbolByOffset ( this Symbol  symbol,
uint  offset 
)
static

Helper method that will return a back month, with future expiration, future contract based on the given offset

Parameters
symbolThe none canonical future symbol
offsetThe quantity of contracts to move into the future expiration chain
Returns
A new future expiration symbol instance

Definition at line 3435 of file Extensions.cs.

Here is the call graph for this function:

◆ UnsubscribeWithMapping()

static void QuantConnect.Extensions.UnsubscribeWithMapping ( this IDataQueueHandler  dataQueueHandler,
SubscriptionDataConfig  dataConfig 
)
static

Helper method to unsubscribe a given configuration, handling any required mapping

Definition at line 3465 of file Extensions.cs.

Here is the call graph for this function:

◆ SubscribeWithMapping()

static IEnumerator<BaseData> QuantConnect.Extensions.SubscribeWithMapping ( this IDataQueueHandler  dataQueueHandler,
SubscriptionDataConfig  dataConfig,
EventHandler  newDataAvailableHandler,
Func< SubscriptionDataConfig, bool >  isExpired,
out SubscriptionDataConfig  subscribedConfig 
)
static

Helper method to subscribe a given configuration, handling any required mapping

Definition at line 3477 of file Extensions.cs.

Here is the call graph for this function:

◆ ReadLines()

static IEnumerable<string> QuantConnect.Extensions.ReadLines ( this IDataProvider  dataProvider,
string  file 
)
static

Helper method to stream read lines from a file

Parameters
dataProviderThe data provider to use
fileThe file path to read from
Returns
Enumeration of lines in file

Definition at line 3508 of file Extensions.cs.

Here is the call graph for this function:

◆ Scale()

static BaseData QuantConnect.Extensions.Scale ( this BaseData  data,
Func< decimal, decimal, decimal, decimal >  factorFunc,
decimal  volumeFactor,
decimal  factor,
decimal  sumOfDividends 
)
static

Scale data based on factor function

Parameters
dataData to Adjust
factorFuncFunction to factor prices by
volumeFactorFactor to multiply volume/askSize/bidSize/quantity by
factorPrice scale
sumOfDividendsThe current dividend sum

Volume values are rounded to the nearest integer, lot size purposefully not considered as scaling only applies to equities

Definition at line 3545 of file Extensions.cs.

◆ Normalize() [2/2]

static BaseData QuantConnect.Extensions.Normalize ( this BaseData  data,
decimal  factor,
DataNormalizationMode  normalizationMode,
decimal  sumOfDividends 
)
static

Normalize prices based on configuration

Parameters
dataData to be normalized
factorPrice scale
normalizationModeThe price scaling normalization mode
sumOfDividendsThe current dividend sum
Returns
The provided data point adjusted

Definition at line 3642 of file Extensions.cs.

◆ GetUpdatePriceScaleFrontier()

static DateTime QuantConnect.Extensions.GetUpdatePriceScaleFrontier ( this BaseData  data)
static

Helper method to determine if price scales need an update based on the given data point

Definition at line 3687 of file Extensions.cs.

◆ OrderBySafe< TSource, TKey >() [1/2]

static IOrderedEnumerable<KeyValuePair<TSource, TKey> > QuantConnect.Extensions.OrderBySafe< TSource, TKey > ( this ConcurrentDictionary< TSource, TKey >  source,
Func< KeyValuePair< TSource, TKey >, TSource >  keySelector 
)
static

◆ OrderBySafe< TSource, TKey >() [2/2]

static IOrderedEnumerable<KeyValuePair<TSource, TKey> > QuantConnect.Extensions.OrderBySafe< TSource, TKey > ( this ConcurrentDictionary< TSource, TKey >  source,
Func< KeyValuePair< TSource, TKey >, TKey >  keySelector 
)
static

◆ SafeEnumeration< TSource, TKey >()

static IEnumerable<KeyValuePair<TSource, TKey> > QuantConnect.Extensions.SafeEnumeration< TSource, TKey > ( this ConcurrentDictionary< TSource, TKey >  source)
static

Force concurrent dictionary enumeration using a thread safe implementation

See https://stackoverflow.com/questions/47630824/is-c-sharp-linq-orderby-threadsafe-when-used-with-concurrentdictionarytkey-tva

Definition at line 3733 of file Extensions.cs.

◆ GetUniverseNormalizationModeOrDefault()

static DataNormalizationMode QuantConnect.Extensions.GetUniverseNormalizationModeOrDefault ( this UniverseSettings  universeSettings,
SecurityType  securityType 
)
static

Helper method to determine the right data normalization mode to use by default

Definition at line 3745 of file Extensions.cs.

◆ ToHexString()

static string QuantConnect.Extensions.ToHexString ( this byte[]  source)
static

Returns a hex string of the byte array.

Parameters
sourcethe byte array to be represented as string
Returns
A new string containing the items in the enumerable

Definition at line 3767 of file Extensions.cs.

◆ GetExerciseDirection()

static OrderDirection QuantConnect.Extensions.GetExerciseDirection ( this OptionRight  right,
bool  isShort 
)
static

Gets the option exercise order direction resulting from the specified right and whether or not we wrote the option (isShort is

true) or bought to option (isShort is false)

Parameters
rightThe option right
isShortTrue if we wrote the option, false if we purchased the option
Returns
The order direction resulting from an exercised option

Definition at line 3791 of file Extensions.cs.

◆ GetOrderDirection()

static OrderDirection QuantConnect.Extensions.GetOrderDirection ( decimal  quantity)
static

Gets the OrderDirection for the specified quantity

Definition at line 3805 of file Extensions.cs.

◆ ProcessSecurityChanges()

static void QuantConnect.Extensions.ProcessSecurityChanges ( this IAlgorithm  algorithm,
SecurityChanges  securityChanges 
)
static

Helper method to process an algorithms security changes, will add and remove securities according to them

Definition at line 3823 of file Extensions.cs.

◆ SetRuntimeError()

static void QuantConnect.Extensions.SetRuntimeError ( this IAlgorithm  algorithm,
Exception  exception,
string  context 
)
static

Helper method to set an algorithm runtime exception in a normalized fashion

Definition at line 3846 of file Extensions.cs.

Here is the call graph for this function:

◆ CreateOptionChain() [1/2]

static OptionChainUniverse QuantConnect.Extensions.CreateOptionChain ( this IAlgorithm  algorithm,
Symbol  symbol,
PyObject  filter,
UniverseSettings  universeSettings = null 
)
static

Creates a OptionChainUniverse for a given symbol

Parameters
algorithmThe algorithm instance to create universes for
symbolSymbol of the option
filterThe option filter to use
universeSettingsThe universe settings, will use algorithm settings if null
Returns
OptionChainUniverse for the given symbol

Definition at line 3862 of file Extensions.cs.

◆ CreateOptionChain() [2/2]

static OptionChainUniverse QuantConnect.Extensions.CreateOptionChain ( this IAlgorithm  algorithm,
Symbol  symbol,
Func< OptionFilterUniverse, OptionFilterUniverse filter,
UniverseSettings  universeSettings = null 
)
static

Creates a OptionChainUniverse for a given symbol

Parameters
algorithmThe algorithm instance to create universes for
symbolSymbol of the option
filterThe option filter to use
universeSettingsThe universe settings, will use algorithm settings if null
Returns
OptionChainUniverse for the given symbol

Definition at line 3877 of file Extensions.cs.

◆ CreateFutureChain() [1/2]

static IEnumerable<Universe> QuantConnect.Extensions.CreateFutureChain ( this IAlgorithm  algorithm,
Symbol  symbol,
PyObject  filter,
UniverseSettings  universeSettings = null 
)
static

Creates a FuturesChainUniverse for a given symbol

Parameters
algorithmThe algorithm instance to create universes for
symbolSymbol of the future
filterThe future filter to use
universeSettingsThe universe settings, will use algorithm settings if null

Definition at line 3913 of file Extensions.cs.

◆ CreateFutureChain() [2/2]

static IEnumerable<Universe> QuantConnect.Extensions.CreateFutureChain ( this IAlgorithm  algorithm,
Symbol  symbol,
Func< FutureFilterUniverse, FutureFilterUniverse filter,
UniverseSettings  universeSettings = null 
)
static

Creates a FuturesChainUniverse for a given symbol

Parameters
algorithmThe algorithm instance to create universes for
symbolSymbol of the future
filterThe future filter to use
universeSettingsThe universe settings, will use algorithm settings if null

Definition at line 3927 of file Extensions.cs.

◆ GetOrAddUnrequestedSecurity()

static bool QuantConnect.Extensions.GetOrAddUnrequestedSecurity ( this IAlgorithm  algorithm,
Symbol  symbol,
out Security  security,
Action< IReadOnlyCollection< SecurityType >>  onError = null 
)
static

Gets the security for the specified symbol from the algorithm's securities collection. In case the security is not found, it will be created using the IAlgorithm.UniverseSettings and a best effort configuration setup.

Parameters
algorithmThe algorithm instance
symbolThe symbol which security is being looked up
securityThe found or added security instance
onErrorCallback to invoke in case of unsupported security type
Returns
True if the security was found or added

Definition at line 3980 of file Extensions.cs.

Here is the call graph for this function:

◆ Invert()

static OptionRight QuantConnect.Extensions.Invert ( this OptionRight  right)
static

Inverts the specified right

Definition at line 4035 of file Extensions.cs.

◆ Compare< T >()

static bool QuantConnect.Extensions.Compare< T > ( this ComparisonOperatorTypes  op,
arg1,
arg2 
)
static

Compares two values using given operator

Template Parameters
T
Parameters
opComparison operator
arg1The first value
arg2The second value
Returns
Returns true if its left-hand operand meets the operator value to its right-hand operand, false otherwise
Type Constraints
T :IComparable 

Definition at line 4054 of file Extensions.cs.

◆ ToSubscriptionDataConfig()

static SubscriptionDataConfig QuantConnect.Extensions.ToSubscriptionDataConfig ( this Data.HistoryRequest  request,
bool  isInternalFeed = false,
bool  isFilteredSubscription = true 
)
static

Converts a Data.HistoryRequest instance to a SubscriptionDataConfig instance

Parameters
requestHistory request
isInternalFeedSet to true if this subscription is added for the sole purpose of providing currency conversion rates, setting this flag to true will prevent the data from being sent into the algorithm's OnData methods
isFilteredSubscriptionTrue if this subscription should have filters applied to it (market hours/user filters from security), false otherwise
Returns
Subscription data configuration

Definition at line 4069 of file Extensions.cs.

◆ ShouldEmitData()

static bool QuantConnect.Extensions.ShouldEmitData ( this SubscriptionDataConfig  config,
BaseData  data,
bool  isUniverse = false 
)
static

Centralized logic used at the top of the subscription enumerator stacks to determine if we should emit base data points based on the configuration for this subscription and the type of data we are handling.

Currently we only want to emit split/dividends/delisting events for non internal TradeBar configurations this last part is because equities also have QuoteBar subscriptions which will also subscribe to the same aux events and we don't want duplicate emits of these events in the TimeSliceFactory

The "TimeSliceFactory" does not allow for multiple dividends/splits per symbol in the same time slice but we don't want to rely only on that to filter out duplicated aux data so we use this at the top of our data enumerator stacks to define what subscription should emit this data.

We use this function to filter aux data at the top of the subscription enumerator stack instead of stopping the subscription stack from subscribing to aux data at the bottom because of a dependency with the FF enumerators requiring that they receive aux data to properly handle delistings. Otherwise we would have issues with delisted symbols continuing to fill forward after expiry/delisting. Reference PR #5485 and related issues for more.

Definition at line 4104 of file Extensions.cs.

◆ ToOrderDirection()

static OrderDirection QuantConnect.Extensions.ToOrderDirection ( this PositionSide  side)
static

Gets the OrderDirection that corresponds to the specified side

Parameters
sideThe position side to be converted
Returns
The order direction that maps from the provided position side

Definition at line 4155 of file Extensions.cs.

◆ Closes()

static bool QuantConnect.Extensions.Closes ( this OrderDirection  direction,
PositionSide  side 
)
static

Determines if an order with the specified direction would close a position with the specified side

Parameters
directionThe direction of the order, buy/sell
sideThe side of the position, long/short
Returns
True if the order direction would close the position, otherwise false

Definition at line 4174 of file Extensions.cs.

◆ ListEquals< T >()

static bool QuantConnect.Extensions.ListEquals< T > ( this IReadOnlyList< T >  left,
IReadOnlyList< T >  right 
)
static

Determines if the two lists are equal, including all items at the same indices.

Template Parameters
TThe element type
Parameters
leftThe left list
rightThe right list
Returns
True if the two lists have the same counts and items at each index evaluate as equal

Definition at line 4213 of file Extensions.cs.

◆ GetListHashCode< T >()

static int QuantConnect.Extensions.GetListHashCode< T > ( this IReadOnlyList< T >  list)
static

Computes a deterministic hash code based on the items in the list. This hash code is dependent on the ordering of items.

Template Parameters
TThe element type
Parameters
listThe list
Returns
A hash code dependent on the ordering of elements in the list

Definition at line 4239 of file Extensions.cs.

◆ RequiresMapping()

static bool QuantConnect.Extensions.RequiresMapping ( this Symbol  symbol)
static

Determine if this SecurityType requires mapping

Parameters
symbolType to check
Returns
True if it needs to be mapped

Definition at line 4258 of file Extensions.cs.

Here is the call graph for this function:

◆ IsWin()

static bool QuantConnect.Extensions.IsWin ( this OrderEvent  fill,
Security  security,
decimal  profitLoss 
)
static

Checks whether the fill event for closing a trade is a winning trade

Parameters
fillThe fill event
securityThe security being traded
profitLossThe profit-loss for the closed trade
Returns
Whether the trade is a win. For options assignments this depends on whether the option is ITM or OTM and the position side. See Trade.IsWin for more information.

Definition at line 4285 of file Extensions.cs.

◆ InTheMoneyAmount()

static ConvertibleCashAmount QuantConnect.Extensions.InTheMoneyAmount ( this Option  option,
decimal  quantity 
)
static

Gets the option's ITM amount for the given quantity.

Parameters
optionThe option security
quantityThe quantity
Returns
The ITM amount for the absolute quantity

The returned value can be negative, which would mean the option is actually OTM.

Definition at line 4313 of file Extensions.cs.

Here is the call graph for this function:

◆ GreatestCommonDivisor()

static int QuantConnect.Extensions.GreatestCommonDivisor ( this IEnumerable< int >  values)
static

Gets the greatest common divisor of a list of numbers

Parameters
valuesList of numbers which greatest common divisor is requested
Returns
The greatest common divisor for the given list of numbers

Definition at line 4323 of file Extensions.cs.

◆ SafeDivision()

static decimal QuantConnect.Extensions.SafeDivision ( this decimal  numerator,
decimal  denominator,
decimal  failValue = 0 
)
static

Safe method to perform divisions avoiding DivideByZeroException and Overflow/Underflow exceptions

Parameters
failValueValue to be returned if the denominator is zero
Returns
The numerator divided by the denominator if the denominator is not zero. Otherwise, the default failValue or the provided one

Definition at line 4367 of file Extensions.cs.

◆ GetCustomDataTypeFromSymbols()

static Type QuantConnect.Extensions.GetCustomDataTypeFromSymbols ( Symbol[]  symbols)
static

Retrieve a common custom data types from the given symbols if any

Parameters
symbolsThe target symbols to search
Returns
The custom data type or null

Definition at line 4384 of file Extensions.cs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsCustomDataType()

static bool QuantConnect.Extensions.IsCustomDataType ( Symbol  symbol,
Type  type 
)
static

Determines if certain data type is custom

Parameters
symbolSymbol associated with the data type
typeData type to determine if it's custom

Definition at line 4404 of file Extensions.cs.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ GetMarketOrderFees()

static CashAmount QuantConnect.Extensions.GetMarketOrderFees ( Security  security,
decimal  quantity,
DateTime  time,
out MarketOrder  marketOrder 
)
static

Returns the amount of fee's charged by executing a market order with the given arguments

Parameters
securitySecurity for which we would like to make a market order
quantityQuantity of the security we are seeking to trade
timeTime the order was placed
marketOrderThis out parameter will contain the market order constructed

Definition at line 4416 of file Extensions.cs.

Here is the call graph for this function:
Here is the caller graph for this function:

Property Documentation

◆ DelistingMarketCloseOffsetSpan

TimeSpan QuantConnect.Extensions.DelistingMarketCloseOffsetSpan = TimeSpan.FromMinutes(-15)
staticgetset

The offset span from the market close to liquidate or exercise a security on the delisting date

Will no be used in live trading

By default span is negative 15 minutes. We want to liquidate before market closes if not, in some cases like future options the market close would match the delisted event time and would cancel all orders and mark the security as non tradable and delisted.

Definition at line 97 of file Extensions.cs.


The documentation for this class was generated from the following file: