Example #1
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol using SecurityIdentifier.
        /// </summary>
        /// <param name="underlyingSymbol">The underlying security symbol</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from diferent markets</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(Symbol underlyingSymbol, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null)
        {
            var sid = SecurityIdentifier.GenerateOption(expiry, underlyingSymbol.ID, market, strike, right, style);

            if (expiry == SecurityIdentifier.DefaultDate)
            {
                alias = alias ?? $"?{underlyingSymbol.Value.LazyToUpper()}";
            }
            else
            {
                var sym = underlyingSymbol.Value;
                if (sid.Symbol != underlyingSymbol.ID.Symbol)
                {
                    // If we have changed the SID and it does not match the underlying,
                    // we've mapped a future into another Symbol. We want to have a value
                    // representing the mapped ticker, not of the underlying.
                    // e.g. we want:
                    //     OG  C3200...|GC18Z20
                    // NOT
                    //     GC  C3200...|GC18Z20
                    sym = sid.Symbol;
                }

                if (sym.Length > 5)
                {
                    sym += " ";
                }

                alias = alias ?? SymbolRepresentation.GenerateOptionTickerOSI(sym, sid.OptionRight, sid.StrikePrice, sid.Date);
            }

            return(new Symbol(sid, alias, underlyingSymbol));
        }
Example #2
0
        /// <summary>
        /// Converts an Zerodha symbol to a Lean symbol instance
        /// </summary>
        /// <param name="brokerageSymbol">The Zerodha symbol</param>
        /// <param name="securityType">The security type</param>
        /// <param name="market">The market</param>
        /// <param name="expirationDate">Expiration date of the security(if applicable)</param>
        /// <param name="strike">The strike of the security (if applicable)</param>
        /// <param name="optionRight">The option right of the security (if applicable)</param>
        /// <returns>A new Lean Symbol instance</returns>
        public Symbol GetLeanSymbol(string brokerageSymbol, SecurityType securityType, string market, DateTime expirationDate = default(DateTime), decimal strike = 0, OptionRight optionRight = OptionRight.Call)
        {
            if (string.IsNullOrWhiteSpace(brokerageSymbol))
            {
                throw new ArgumentException($"Invalid Zerodha symbol: {brokerageSymbol}");
            }

            //if (!IsKnownBrokerageSymbol(brokerageSymbol))
            //   throw new ArgumentException($"Unknown Zerodha symbol: {brokerageSymbol}");

            if (securityType == SecurityType.Forex || securityType == SecurityType.Cfd || securityType == SecurityType.Commodity || securityType == SecurityType.Crypto)
            {
                throw new ArgumentException($"Invalid security type: {securityType}");
            }

            if (!Market.Encode(market).HasValue)
            {
                throw new ArgumentException($"Invalid market: {market}");
            }


            switch (securityType)
            {
            case SecurityType.Option:
                OptionStyle optionStyle = OptionStyle.European;
                return(Symbol.CreateOption(brokerageSymbol.Replace(" ", "").Trim(), market, optionStyle, optionRight, strike, expirationDate));

            case SecurityType.Future:
                return(Symbol.CreateFuture(brokerageSymbol.Replace(" ", "").Trim(), market, expirationDate));

            default:
                return(Symbol.Create(brokerageSymbol.Replace(" ", "").Trim(), securityType, market));
            }
        }
Example #3
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol.
        /// </summary>
        /// <param name="underlying">The underlying ticker</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from different markets</param>
        /// <param name="mapSymbol">Specifies if symbol should be mapped using map file provider</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(string underlying, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null, bool mapSymbol = true)
        {
            var underlyingSid    = SecurityIdentifier.GenerateEquity(underlying, market, mapSymbol);
            var underlyingSymbol = new Symbol(underlyingSid, underlying);

            return(CreateOption(underlyingSymbol, market, style, right, strike, expiry, alias));
        }
Example #4
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol.
        /// </summary>
        /// <param name="underlying">The underlying ticker</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from diferent markets</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(string underlying, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null)
        {
            var sid = SecurityIdentifier.GenerateOption(expiry, underlying, market, strike, right, style);

            alias = alias ?? string.Format("{0}_{1}_{2}_{3}", underlying, right.ToString()[0], strike.SmartRounding(), expiry.ToString("yyyyMMdd"));
            return(new Symbol(sid, alias));
        }
 /// <summary>
 /// Generates a new <see cref="SecurityIdentifier"/> for an option
 /// </summary>
 /// <param name="expiry">The date the option expires</param>
 /// <param name="underlying">The underlying security's symbol</param>
 /// <param name="market">The market</param>
 /// <param name="strike">The strike price</param>
 /// <param name="optionRight">The option type, call or put</param>
 /// <param name="optionStyle">The option style, American or European</param>
 /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified option security</returns>
 public static SecurityIdentifier GenerateOption(DateTime expiry,
                                                 SecurityIdentifier underlying,
                                                 string market,
                                                 decimal strike,
                                                 OptionRight optionRight,
                                                 OptionStyle optionStyle)
 {
     return(Generate(expiry, underlying.Symbol, SecurityType.Option, market, strike, optionRight, optionStyle, underlying));
 }
Example #6
0
 /// <summary>
 /// Generates a new <see cref="SecurityIdentifier"/> for an option
 /// </summary>
 /// <param name="expiry">The date the option expires</param>
 /// <param name="underlying">The underlying security's symbol</param>
 /// <param name="market">The market</param>
 /// <param name="strike">The strike price</param>
 /// <param name="optionRight">The option type, call or put</param>
 /// <param name="optionStyle">The option style, American or European</param>
 /// <returns>A new <see cref="SecurityIdentifier"/> representing the specified option security</returns>
 public static SecurityIdentifier GenerateOption(DateTime expiry,
                                                 SecurityIdentifier underlying,
                                                 string market,
                                                 decimal strike,
                                                 OptionRight optionRight,
                                                 OptionStyle optionStyle)
 {
     return(Generate(expiry, underlying.Symbol, QuantConnect.Symbol.GetOptionTypeFromUnderlying(underlying.SecurityType), market, strike, optionRight, optionStyle, underlying));
 }
Example #7
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol.
        /// </summary>
        /// <param name="underlying">The underlying ticker</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from diferent markets</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(string underlying, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null)
        {
            var sid = SecurityIdentifier.GenerateOption(expiry, underlying, market, strike, right, style);
            var sym = sid.Symbol;

            if (sym.Length > 5)
            {
                sym += " ";
            }
            // format spec: http://www.optionsclearing.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf
            alias = alias ?? string.Format("{0,-6}{1}{2}{3:00000000}", sym, sid.Date.ToString(DateFormat.SixCharacter), sid.OptionRight.ToString()[0], sid.StrikePrice * 1000m);
            return(new Symbol(sid, alias));
        }
Example #8
0
        public void SymbolHashForOptionsBackwardsCompatibilityWholeNumber(OptionStyle style, OptionRight right, string expected)
        {
            var equity = Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
            var option = Symbol.CreateOption(
                equity,
                Market.USA,
                style,
                right,
                100m,
                new DateTime(2020, 5, 21));

            Assert.AreEqual(expected, option.ID.ToString());
            Assert.AreEqual(100m, option.ID.StrikePrice);
        }
Example #9
0
        public void SymbolHashForOptionsBackwardsCompatibilityFractionalNumber(OptionStyle style, OptionRight right, string expected)
        {
            var equity = Symbol.Create("AAPL", SecurityType.Equity, Market.USA);
            var option = Symbol.CreateOption(
                equity,
                Market.USA,
                style,
                right,
                0.01m, // strike decimal precision is limited to 4 decimal places only
                new DateTime(2020, 5, 21));

            Assert.AreEqual(expected, option.ID.ToString());
            Assert.AreEqual(0.01m, option.ID.StrikePrice);
        }
        /// <summary>
        /// Generic generate method. This method should be used carefully as some parameters are not required and
        /// some parameters mean different things for different security types
        /// </summary>
        private static SecurityIdentifier Generate(DateTime date,
                                                   string symbol,
                                                   SecurityType securityType,
                                                   string market,
                                                   decimal strike                = 0,
                                                   OptionRight optionRight       = 0,
                                                   OptionStyle optionStyle       = 0,
                                                   SecurityIdentifier?underlying = null,
                                                   bool forceSymbolToUpper       = true)
        {
            if ((ulong)securityType >= SecurityTypeWidth || securityType < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(securityType), "securityType must be between 0 and 99");
            }
            if ((int)optionRight > 1 || optionRight < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(optionRight), "optionType must be either 0 or 1");
            }

            // normalize input strings
            market = market.ToLowerInvariant();
            symbol = forceSymbolToUpper ? symbol.LazyToUpper() : symbol;

            var marketIdentifier = QuantConnect.Market.Encode(market);

            if (!marketIdentifier.HasValue)
            {
                throw new ArgumentOutOfRangeException(nameof(market), "The specified market wasn't found in the  markets lookup. " +
                                                      $"Requested: {market}. You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)"
                                                      );
            }

            var days       = (ulong)date.ToOADate() * DaysOffset;
            var marketCode = (ulong)marketIdentifier * MarketOffset;

            ulong strikeScale;
            var   strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset;

            strikeScale *= StrikeScaleOffset;
            var style   = (ulong)optionStyle * OptionStyleOffset;
            var putcall = (ulong)optionRight * PutCallOffset;

            var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType;

            return(new SecurityIdentifier(symbol, otherData, underlying ?? Empty));
        }
Example #11
0
 public OptionData(OptionType optType, OptionStyle optStyle, String baseActive,
                   DateTime countDate, DateTime dateExpiration,
                   float strikePrice,
                   float contractHigh, float contractLow, float contractClose,
                   int openInterest, int volume)
 {
     Type           = optType;
     Style          = optStyle;
     BaseActive     = baseActive;
     DatePublished  = countDate;
     DateExpiration = dateExpiration;
     StrikePrice    = strikePrice;
     ContractHigh   = contractHigh;
     ContractLow    = contractLow;
     ContractClose  = contractClose;
     OpenInterest   = openInterest;
     Volume         = volume;
 }
Example #12
0
        private News MakeOptionLevelNews(DateTime curDate,
                                         string curSymbol, ExpirationMonth expMonth,
                                         OptionStyle optStyle, OptionType optType, decimal strike, int volume,
                                         int OI, decimal closeRange, decimal openRange, decimal high, decimal low,
                                         decimal delta, decimal settPrice)
        {
            //[#fmt]#&newstype=option#&type=Call#&style=American#&baseactive=EURUSD#&
            //publishdate=09.03.2011 02:34:00#&dateexpiration=11.06.2011#&strikeprice=1.4550#&
            //high=0.0140#&low=0.0090#&close=0.0110#&oi=948#&volume=0
            var newsBody = string.Format(CultureProvider.Common,
                                         "[#fmt]#&newstype=option#&type={0}#&style={1}#&baseactive={2}#&" +
                                         "publishdate={3:dd.MM.yyyy HH:mm:ss}#&dateexpiration={4:dd.MM.yyyy}#&strikeprice={5}#&" +
                                         "high={6}#&low={7}#&close={8}#&oi={9}#&volume={10}",
                                         optType, optStyle, curSymbol, curDate, new DateTime(expMonth.Year, expMonth.Month, 11),
                                         strike, high, low, closeRange, OI, volume);

            return(new News(newsChannelId, curDate, titleNewsOption, newsBody));
        }
Example #13
0
 public OptionData(OptionType optType, OptionStyle optStyle, String baseActive, 
     DateTime countDate, DateTime dateExpiration,
     float strikePrice,
     float contractHigh, float contractLow, float contractClose,
     int openInterest, int volume)
 {
     Type = optType;
     Style = optStyle;
     BaseActive = baseActive;
     DatePublished = countDate;
     DateExpiration = dateExpiration;
     StrikePrice = strikePrice;
     ContractHigh = contractHigh;
     ContractLow = contractLow;
     ContractClose = contractClose;
     OpenInterest = openInterest;
     Volume = volume;
 }
Example #14
0
        /// <summary>
        /// Generic generate method. This method should be used carefully as some parameters are not required and
        /// some parameters mean different things for different security types
        /// </summary>
        private static SecurityIdentifier Generate(DateTime date,
                                                   string symbol,
                                                   SecurityType securityType,
                                                   string market,
                                                   decimal strike          = 0,
                                                   OptionRight optionRight = 0,
                                                   OptionStyle optionStyle = 0)
        {
            if ((ulong)securityType >= SecurityTypeWidth || securityType < 0)
            {
                throw new ArgumentOutOfRangeException("securityType", "securityType must be between 0 and 99");
            }
            if ((int)optionRight > 1 || optionRight < 0)
            {
                throw new ArgumentOutOfRangeException("optionRight", "optionType must be either 0 or 1");
            }

            // normalize input strings
            market = market.ToLower();
            symbol = symbol.ToUpper();

            var marketIdentifier = QuantConnect.Market.Encode(market);

            if (!marketIdentifier.HasValue)
            {
                throw new ArgumentOutOfRangeException("market", string.Format("The specified market wasn't found in the markets lookup. Requested: {0}. " +
                                                                              "You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)", market));
            }

            var days       = ((ulong)date.ToOADate()) * DaysOffset;
            var marketCode = (ulong)marketIdentifier * MarketOffset;

            ulong strikeScale;
            var   strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset;

            strikeScale *= StrikeScaleOffset;
            var style   = ((ulong)optionStyle) * OptionStyleOffset;
            var putcall = (ulong)(optionRight) * PutCallOffset;

            var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType;

            return(new SecurityIdentifier(symbol, otherData));
        }
Example #15
0
            /// <summary>
            /// Creates a new option.
            /// </summary>
            /// <param name="options">Cli arguments that use this option.</param>
            /// <param name="description">Description of this option.</param>
            /// <param name="func">Action to perform when this option is specified.</param>
            /// <param name="style">Style of option to use.</param>
            /// <param name="optionalArgs">If this is true, arguments will be treated as non compulsary ones.</param>
            public Option(string options, string description, Action <string> func, OptionStyle style, bool optionalArgs = false)
            {
                Action = func;
                var spl = options.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                Arguments = spl.Select(s => OptionsPrefixes[(int)style + ((s.Length == 1) ? 0 : 1)] + s).ToArray();
                var opts = new List <string>();

                foreach (Match match in Regex.Matches(description, "{[^}]*}"))
                {
                    var val = match.Value.Substring(1, match.Length - 2);
                    opts.Add(val.ToUpper());
                    description = description.Substring(0, match.Index) + val +
                                  description.Substring(match.Index + match.Length);
                }
                Description      = description;
                Options          = opts.ToArray();
                ExpectsArguments = opts.Count > 0 && !optionalArgs;
            }
Example #16
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol using SecurityIdentifier.
        /// </summary>
        /// <param name="underlyingSymbol">The underlying security symbol</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from diferent markets</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(Symbol underlyingSymbol, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null)
        {
            var sid = SecurityIdentifier.GenerateOption(expiry, underlyingSymbol.ID, market, strike, right, style);

            if (expiry == SecurityIdentifier.DefaultDate)
            {
                alias = alias ?? "?" + underlyingSymbol.Value.ToUpper();
            }
            else
            {
                var sym = underlyingSymbol.Value;
                if (sym.Length > 5)
                {
                    sym += " ";
                }

                alias = alias ?? SymbolRepresentation.GenerateOptionTickerOSI(sym, sid.OptionRight, sid.StrikePrice, sid.Date);
            }

            return(new Symbol(sid, alias, underlyingSymbol));
        }
Example #17
0
        /// <summary>
        /// Gets a formatted description of the contract class defined by <typeparamref name="T"/>
        /// </summary>
        /// <typeparam name="T">The contract class type</typeparam>
        /// <param name="executableName">The name of the executable; if not given, defaults to Process.GetCurrentProcess().MainModule.FileName</param>
        /// <param name="lineLength">The length at which to start wrapping lines</param>
        /// <param name="optionStyle">The command line syntax style, default is <see cref="OptionStyle.Unix"/></param>
        public static string GetDescription <T>(string executableName = null, int lineLength = 100, OptionStyle optionStyle = OptionStyle.Unix)
        {
            executableName = executableName ?? Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);
            var       properties         = GetProperties <T>();
            var       descriptionBuilder = new StringBuilder(properties.Count() * 50);
            const int aliasIndent        = 1;
            var       aliasPrefix        = optionStyle == OptionStyle.Unix ? "-" : "/";
            var       prefix             = optionStyle == OptionStyle.Unix ? "--" : "/";
            var       valuePrefix        = optionStyle == OptionStyle.Unix ? "=" : ":";

            //first print the command summary

            descriptionBuilder.Append(executableName);
            foreach (var property in properties.Where(p => !p.IsValueProperty).OrderByDescending(p => p.Required).ThenBy(p => p.Name))
            {
                var format = property.Required ? " {0}{1}{2}{3}" : " [{0}{1}{2}{3}]";
                descriptionBuilder.Append(string.Format(format, prefix, property.Name, property.ValueName != null ? valuePrefix : "", property.ValueName));
            }
            var valueProperty = properties.FirstOrDefault(p => p.IsValueProperty);

            if (valueProperty != null)
            {
                descriptionBuilder.Append(" " + valueProperty.ValueName ?? valueProperty.Name);
            }

            var summaryLines = WordWrap(descriptionBuilder.ToString(), lineLength);

            descriptionBuilder.Clear();
            descriptionBuilder.AppendLine();
            descriptionBuilder.AppendLine("USAGE");
            descriptionBuilder.Append(string.Join(Environment.NewLine, summaryLines));

            descriptionBuilder.AppendLine();
            descriptionBuilder.AppendLine();

            var descriptionStartColumn = properties.Max(property => {
                if (property.IsValueProperty)
                {
                    return(property.ValueName != null ? property.ValueName.Length : property.Name.Length);
                }

                var length = property.Name.Length + prefix.Length;
                if (property.ValueName != null)
                {
                    length += 1 + property.ValueName.Length;                     //+1 for "=" or ":"
                }

                if (property.IsComplexFlag)
                {
                    length += 5;                     //appends [+|-]
                }

                if (property.Aliases.Any())
                {
                    length = Math.Max(length, property.Aliases.Max(alias => alias.Length + aliasPrefix.Length + aliasIndent));
                }

                return(length);
            }) + 1;             //+1 for padding


            var adjustedLineLength = lineLength - descriptionStartColumn;

            //first render the value property stuff
            if (valueProperty != null)
            {
                var name = valueProperty.ValueName ?? valueProperty.Name;
                descriptionBuilder.AppendLine("ARGUMENTS");
                descriptionBuilder.Append(name);
                descriptionBuilder.Append(new string(' ', descriptionStartColumn - name.Length));
                var lines = WordWrap(valueProperty.Description, adjustedLineLength);
                if (lines.Count > 0)
                {
                    var spaceLength = 0;
                    foreach (var line in lines)
                    {
                        descriptionBuilder.AppendLine(new string(' ', spaceLength) + line);
                        spaceLength = descriptionStartColumn;
                    }
                }
                else
                {
                    descriptionBuilder.AppendLine();
                }

                descriptionBuilder.AppendLine();
            }

            descriptionBuilder.AppendLine("OPTIONS");
            foreach (var property in properties.Where(p => !p.IsValueProperty).OrderBy(p => p.Name))
            {
                descriptionBuilder.Append(prefix + property.Name);

                var indent = property.Name.Length + prefix.Length;
                if (property.IsComplexFlag)
                {
                    descriptionBuilder.Append("[+|-]");
                    indent += 5;
                }

                if (property.ValueName != null)
                {
                    descriptionBuilder.Append(valuePrefix + property.ValueName);
                    indent += valuePrefix.Length + property.ValueName.Length;
                }

                descriptionBuilder.Append(new string(' ', descriptionStartColumn - indent));

                var lines   = WordWrap(property.Description, adjustedLineLength);
                var aliases = property.Aliases.OrderBy(alias => alias).ToList();
                var i       = 1;

                if (lines.Count > 0)
                {
                    var spaceLength = 0;
                    for (i = 0; i < lines.Count; i++)
                    {
                        if (i > 0)
                        {
                            var alias = aliases.ElementAtOrDefault(i - 1);
                            if (alias != null)
                            {
                                descriptionBuilder.Append(new string(' ', aliasIndent) + aliasPrefix + alias);
                                spaceLength = spaceLength - (aliasIndent + alias.Length + aliasPrefix.Length);
                            }
                        }

                        descriptionBuilder.Append(new string(' ', spaceLength));
                        descriptionBuilder.AppendLine(lines[i]);
                        spaceLength = descriptionStartColumn;
                    }
                }
                else
                {
                    descriptionBuilder.AppendLine();
                }

                for (i = i - 1; i < aliases.Count; i++)
                {
                    descriptionBuilder.AppendLine(new string(' ', aliasIndent) + aliasPrefix + aliases[i]);
                }
            }

            return(descriptionBuilder.ToString());
        }
Example #18
0
        /// <summary>
        /// Generic generate method. This method should be used carefully as some parameters are not required and
        /// some parameters mean different things for different security types
        /// </summary>
        private static SecurityIdentifier Generate(DateTime date,
                                                   string symbol,
                                                   SecurityType securityType,
                                                   string market,
                                                   decimal strike                = 0,
                                                   OptionRight optionRight       = 0,
                                                   OptionStyle optionStyle       = 0,
                                                   SecurityIdentifier underlying = null,
                                                   bool forceSymbolToUpper       = true)
        {
            if ((ulong)securityType >= SecurityTypeWidth || securityType < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(securityType), "securityType must be between 0 and 99");
            }
            if ((int)optionRight > 1 || optionRight < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(optionRight), "optionType must be either 0 or 1");
            }

            // normalize input strings
            market = market.ToLowerInvariant();
            symbol = forceSymbolToUpper ? symbol.LazyToUpper() : symbol;

            if (securityType == SecurityType.FutureOption)
            {
                // Futures options tickers might not match, so we need
                // to map the provided future Symbol to the actual future option Symbol.
                symbol = FuturesOptionsSymbolMappings.Map(symbol);
            }

            var marketIdentifier = QuantConnect.Market.Encode(market);

            if (!marketIdentifier.HasValue)
            {
                throw new ArgumentOutOfRangeException(nameof(market), "The specified market wasn't found in the  markets lookup. " +
                                                      $"Requested: {market}. You can add markets by calling QuantConnect.Market.AddMarket(string,ushort)"
                                                      );
            }

            var days       = (ulong)date.ToOADate() * DaysOffset;
            var marketCode = (ulong)marketIdentifier * MarketOffset;

            ulong strikeScale;
            var   strk = NormalizeStrike(strike, out strikeScale) * StrikeOffset;

            strikeScale *= StrikeScaleOffset;
            var style   = (ulong)optionStyle * OptionStyleOffset;
            var putcall = (ulong)optionRight * PutCallOffset;

            var otherData = putcall + days + style + strk + strikeScale + marketCode + (ulong)securityType;

            var result = new SecurityIdentifier(symbol, otherData, underlying ?? Empty);

            // we already have these so lets set them
            switch (securityType)
            {
            case SecurityType.Base:
            case SecurityType.Equity:
            case SecurityType.Future:
                result._date = date;
                break;

            case SecurityType.Option:
            case SecurityType.FutureOption:
                result._date        = date;
                result._strikePrice = strike;
                result._optionRight = optionRight;
                result._optionStyle = optionStyle;
                break;
            }
            return(result);
        }
Example #19
0
        public void OptionUserFriendlyDeserialization(string jsonValue, SecurityType type, string underlying, OptionRight optionRight, OptionStyle optionStyle, int expirationYear)
        {
            var symbol = JsonConvert.DeserializeObject <Symbol>(jsonValue);

            Assert.IsNotNull(symbol);
            Assert.AreEqual(type, symbol.SecurityType);
            Assert.AreEqual(underlying, symbol.ID.Underlying.Symbol);
            Assert.AreEqual(optionRight, symbol.ID.OptionRight);
            Assert.AreEqual(optionStyle, symbol.ID.OptionStyle);
            Assert.AreEqual(expirationYear, symbol.ID.Date.Year);
        }
Example #20
0
 private News MakeOptionLevelNews(DateTime curDate,
    string curSymbol, ExpirationMonth expMonth,
    OptionStyle optStyle, OptionType optType, decimal strike, int volume,
    int OI, decimal closeRange, decimal openRange, decimal high, decimal low,
    decimal delta, decimal settPrice)
 {
     //[#fmt]#&newstype=option#&type=Call#&style=American#&baseactive=EURUSD#&
     //publishdate=09.03.2011 02:34:00#&dateexpiration=11.06.2011#&strikeprice=1.4550#&
     //high=0.0140#&low=0.0090#&close=0.0110#&oi=948#&volume=0
     var newsBody = string.Format(CultureProvider.Common,
                          "[#fmt]#&newstype=option#&type={0}#&style={1}#&baseactive={2}#&" +
                          "publishdate={3:dd.MM.yyyy HH:mm:ss}#&dateexpiration={4:dd.MM.yyyy}#&strikeprice={5}#&" +
                          "high={6}#&low={7}#&close={8}#&oi={9}#&volume={10}",
                          optType, optStyle, curSymbol, curDate, new DateTime(expMonth.Year, expMonth.Month, 11),
                          strike, high, low, closeRange, OI, volume);
     return new News(newsChannelId, curDate, titleNewsOption, newsBody);
 }
Example #21
0
        /// <summary>
        /// Parses command line options, injecting values into the given instance of the option contract
        /// </summary>
        /// <typeparam name="T">The type of the option contract</typeparam>
        /// <param name="args">The command line arguments to parse</param>
        /// <param name="contract">An instance of the option contract</param>
        /// <param name="optionStyle">The command line syntax style, default is <see cref="OptionStyle.Unix"/></param>
        /// <seealso cref="Parse{T}(string[],OptionStyle)"/>
        public static IOptionParseResult <T> Parse <T>(string[] args, T contract, OptionStyle optionStyle = OptionStyle.Unix)
        {
            var properties = GetProperties <T>();

            var nonOptionValues = new List <string>();
            var errors          = new List <ParsingError>();

            for (var i = 0; i < args.Length; i++)
            {
                var arg = args[i];

                var name = (optionStyle == OptionStyle.Windows ? windowsRegex : unixRegex).Match(arg);
                if (!name.Success)
                {
                    nonOptionValues.Add(arg);
                    continue;
                }

                var    optionName = name.Groups[1].Value;
                string value      = null;
                if (optionName.EndsWith("+") || optionName.EndsWith("-"))
                {
                    //handle on/off switches, e.g. /debug+ or /debug-
                    value      = optionName.Last() == '+' ? bool.TrueString : bool.FalseString;
                    optionName = optionName.Substring(0, optionName.Length - 1);
                }

                var property = properties.FirstOrDefault(p => p.NameMatches(optionName));
                if (property == null)
                {
                    //no contract for this option, so it's a value
                    nonOptionValues.Add(arg);
                    continue;
                }

                if (value != null && property.IsFlag)
                {
                    //this won't throw because the only possible values are bool.TrueString and bool.FalseString
                    property.SetValue(contract, value);

                    if (property.IsComplexFlag)
                    {
                        //complex flags are options with boolean switches, but also take values
                        //e.g. /warnaserror+:1400,1456,1680
                        property = new OptionProperty(property.ComplexValueProperty);
                    }
                    else
                    {
                        continue;
                    }
                }

                if (arg.Length > name.Length)
                {
                    //the value is given after = or :
                    value = arg.Substring(name.Length + 1);
                }
                else if (property.IsFlag && !property.IsComplexFlag)
                {
                    value = bool.TrueString;
                }
                else if (i + 1 < args.Length)
                {
                    //value is the next arg
                    value = args[++i];
                }

                try {
                    property.SetValue(contract, value);
                } catch (Exception e) {
                    errors.Add(new ParsingError {
                        Argument = arg, ThrownException = e
                    });
                }
            }

            //inject values into ValueProperty property, if given
            var valueProperty = properties.FirstOrDefault(p => p.IsValueProperty);

            if (valueProperty != null)
            {
                valueProperty.SetNonOptionValues(contract, nonOptionValues.ToArray());
            }

            return(new OptionParseResult <T>(contract, errors));
        }
        public void ThrowsIfOptionStyleIsNotSupportedByQLPricingModel(string qlModelName, OptionStyle optionStyle, bool shouldThrow)
        {
            const decimal underlyingPrice = 200m;
            const decimal underlyingVol   = 0.15m;
            var           tz                    = TimeZones.NewYork;
            var           evaluationDate        = new DateTime(2015, 2, 19);
            var           spy                   = Symbols.SPY;
            var           SPY_C_192_Feb19_2016E = GetOptionSymbol(spy, optionStyle, OptionRight.Call);
            var           SPY_P_192_Feb19_2016E = GetOptionSymbol(spy, optionStyle, OptionRight.Put);

            // setting up underlying
            var equity = GetEquity(spy, underlyingPrice, underlyingVol, tz);

            // setting up European style call option
            var contractCall = GetOptionContract(SPY_C_192_Feb19_2016E, spy, evaluationDate);
            var optionCall   = GetOption(SPY_C_192_Feb19_2016E, equity, tz);

            // setting up European style put option
            var contractPut = GetOptionContract(SPY_P_192_Feb19_2016E, spy, evaluationDate);
            var optionPut   = GetOption(SPY_P_192_Feb19_2016E, equity, tz);

            // running evaluation
            var          priceModel = (IOptionPriceModel)typeof(OptionPriceModels).GetMethod(qlModelName).Invoke(null, new object[] {});
            TestDelegate call       = () => priceModel.Evaluate(optionCall, null, contractCall);
            TestDelegate put        = () => priceModel.Evaluate(optionPut, null, contractPut);

            if (shouldThrow)
            {
                Assert.Throws <ArgumentException>(call);
                Assert.Throws <ArgumentException>(put);
            }
            else
            {
                Assert.DoesNotThrow(call);
                Assert.DoesNotThrow(put);

                var results = priceModel.Evaluate(optionCall, null, contractCall);
                var greeks  = results.Greeks;

                Assert.That(greeks.Delta, Is.InRange(0, 1m));
                Assert.Less(greeks.Theta, 0);
                Assert.Greater(greeks.Rho, 0m);
                Assert.Greater(greeks.Vega, 0m);

                results = priceModel.Evaluate(optionPut, null, contractPut);
                greeks  = results.Greeks;

                Assert.That(greeks.Delta, Is.InRange(-1m, 0));
                Assert.Less(greeks.Theta, 0);
                Assert.Less(greeks.Rho, 0m);
                Assert.Greater(greeks.Vega, 0m);
            }
        }
 private Symbol GetOptionSymbol(Symbol underlying, OptionStyle optionStyle, OptionRight optionRight)
 {
     return(Symbol.CreateOption(underlying.Value, Market.USA, optionStyle, optionRight, 192m, new DateTime(2016, 02, 19)));
 }
Example #24
0
        /// <summary>
        /// Provides a convenience method for creating an option Symbol using SecurityIdentifier.
        /// </summary>
        /// <param name="underlyingSymbol">The underlying security symbol</param>
        /// <param name="market">The market the underlying resides in</param>
        /// <param name="style">The option style (American, European, ect..)</param>
        /// <param name="right">The option right (Put/Call)</param>
        /// <param name="strike">The option strike price</param>
        /// <param name="expiry">The option expiry date</param>
        /// <param name="alias">An alias to be used for the symbol cache. Required when
        /// adding the same security from diferent markets</param>
        /// <returns>A new Symbol object for the specified option contract</returns>
        public static Symbol CreateOption(Symbol underlyingSymbol, string market, OptionStyle style, OptionRight right, decimal strike, DateTime expiry, string alias = null)
        {
            var sid = SecurityIdentifier.GenerateOption(expiry, underlyingSymbol.ID, market, strike, right, style);

            return(new Symbol(sid, alias ?? GetAlias(sid, underlyingSymbol), underlyingSymbol));
        }
Example #25
0
 /// <summary>
 /// Parses command line options, injecting values into a new instance of the option contract
 /// defined in <typeparamref name="T"/>
 /// </summary>
 /// <typeparam name="T">The type of the option contract</typeparam>
 /// <param name="args">The command line arguments to parse</param>
 /// <param name="optionStyle">The command line syntax style, default is <see cref="OptionStyle.Unix"/></param>
 /// <seealso cref="Parse{T}(string[],T,OptionStyle)"/>
 public static IOptionParseResult <T> Parse <T>(string[] args, OptionStyle optionStyle = OptionStyle.Unix) where T : new()
 {
     return(Parse(args, new T(), optionStyle));
 }