public OptionChainViewModel GetOptionChains(string underlying)
        {
            OptionChain          optionChain = _marketDataService.GetOptionChain(underlying);
            OptionChainViewModel result      = Mapper.Map <OptionChainViewModel>(optionChain);

            return(result);
        }
Ejemplo n.º 2
0
        private OptionChain GetOptionChainWithPredefinedVolatility(string underlying, double?volatility)
        {
            OptionChain optionChain = _marketDataService.GetOptionChain(underlying);

            optionChain.SetPredefinedVolatility(volatility);
            return(optionChain);
        }
        private double?GetStrikePriceForLegOld(OptionChain chain, StrategyLeg leg, DateAndNumberOfDaysUntil date)
        {
            if (leg == null || leg.LegType == LegType.Security)
            {
                return(null);
            }
            IList <double> strikePrices = chain.GetStrikePrices(date);

            if (leg.BuyOrSell == BuyOrSell.Buy)
            {
                double strikePrice = leg.LegType == LegType.Call ?
                                     strikePrices.LastAndIndex(d => d < chain.UnderlyingCurrentPrice).Item2 :
                                     strikePrices.FirstAndIndex(d => d > chain.UnderlyingCurrentPrice).Item2;
                return(strikePrice);
            }
            else
            {
                List <DateAndStandardDeviation> stdDevs = _predictionAndStdDevService.GetExpiriesAndStandardDeviations(chain, chain.ExpirationDates, 1.0);
                DateAndStandardDeviation        stdDevPricesForCurrentExpiry = stdDevs.Single(d => d.DateAndNumberOfDaysUntil.FutureDate.Equals(date.FutureDate));
                double strikePrice = leg.LegType == LegType.Call
                                        ? strikePrices.GetClosest(stdDevPricesForCurrentExpiry.StdDev.UpPrice)
                                        : strikePrices.GetClosest(stdDevPricesForCurrentExpiry.StdDev.DownPrice);
                return(strikePrice);
            }
        }
Ejemplo n.º 4
0
        public List <CoveredCall> GetOptimalCoveredCalls(OptionChain data, LegType?legType = null, double?minimumPremium = null, double?minimumReturn = null)
        {
            IEnumerable <CoveredCall> coveredCalls        = GetAllCoveredCalls(data, legType, minimumPremium, minimumReturn);
            List <CoveredCall>        optimalCoveredCalls = coveredCalls.Where(m => m.RiskTolerance == RiskTolerance.Optimal).ToList();

            return(optimalCoveredCalls);
        }
Ejemplo n.º 5
0
        public static OptionChain GetOpcOptionChain(Security security)
        {
            int tries      = 5;
            int currentTry = 1;

            while (currentTry < tries)
            {
                var client  = new RestClient("https://www.optionsprofitcalculator.com/ajax/getOptions");
                var request = new RestRequest(Method.GET);
                request.AddParameter("stock", security.Symbol);
                request.AddParameter("reqId", 1);

                IRestResponse response = client.Execute(request);
                try
                {
                    String contentMassaged = response.Content.Replace(",\"_data_source\":\"c0\"", String.Empty);
                    OpcGetOptionChainResponse opcGetOptionChainResponse = JsonConvert.DeserializeObject <OpcGetOptionChainResponse>(contentMassaged);
                    OptionChain optionChain = new OptionChain(opcGetOptionChainResponse);

                    return(optionChain);
                }
                catch (Exception ex)
                {
                    currentTry += 1;
                }
            }

            return(null);
        }
Ejemplo n.º 6
0
        public void UnsubscribeOptionChains(string underlying)
        {
            OptionChain optionChain   = _marketDataService.GetOptionChain(underlying);
            var         optionNumbers = FlattenOptionNumbers(optionChain);

            _marketDataPusher.UnsubscribeOptions(Context.ConnectionId, optionNumbers);
        }
Ejemplo n.º 7
0
        private void FillPanelChain(OptionChain dateChain)
        {
            panelChain.Controls.Clear();
            if (dateChain.Options.Count > 0)
            {
                for (int i = 0; i < _strikes.Length; i++)
                {
                    OptionChainDataPoint  call = dateChain.FindOption(Options.OptionType.Call, _experation, _strikes[i]);
                    OptionChainDataPoint  put  = dateChain.FindOption(Options.OptionType.Put, _experation, _strikes[i]);
                    OptionChainStrikeLine line = new OptionChainStrikeLine(call, put);
                    line.Location = new Point(0, 32 * i);

                    line.CallClicked       += new MouseEventHandler(FireCallClickEvent);
                    line.PutClicked        += new MouseEventHandler(FirePutClickEvent);
                    line.CallDoubleClicked += new MouseEventHandler(FireCallDoubleClickEvent);
                    line.PutDoubleClicked  += new MouseEventHandler(FirePutDoubleClickEvent);
                    line.CallEntered       += new EventHandler(FireCallEnteredEvent);
                    line.PutEntered        += new EventHandler(FirePutEnteredEvent);
                    line.CallMouseUp       += new MouseEventHandler(FireCallMouseUpEvent);
                    line.PutMouseUp        += new MouseEventHandler(FirePutMouseUpEvent);
                    line.CallMouseMove     += new MouseEventHandler(FireCallMouseMoveEvent);
                    line.PutMouseMove      += new MouseEventHandler(FirePutMouseMoveEvent);

                    panelChain.Controls.Add(line);
                }
            }
        }
Ejemplo n.º 8
0
 private void PrintChain(OptionChain chain)
 {
     foreach (var contract in chain)
     {
         Debug($"Time: {contract.Time}, symbol: {chain.Underlying.Symbol} contract expried: {contract.Expiry}, strike: {contract.Strike}, stock price: {chain.Underlying.Price}, bid: {contract.BidPrice}, ask: {contract.AskPrice}, call/put: {contract.Right}, IV: {contract.ImpliedVolatility}");
     }
 }
Ejemplo n.º 9
0
        private OptionChain GenerateFinalData(string textForChain)
        {
            OptionChain obj = new OptionChain();

            string[] text1 = textForChain.Split(new[] { "</b></td>" }, StringSplitOptions.None);
            int      j     = 0;

            for (int i = 0; i <= text1.Count() - 1; i++)
            {
                string[] text2 = text1[i].Split(new[] { "<b>" }, StringSplitOptions.None);
                if (j == 0 && text2[1] != "Total" && text2[1] != null && text2[1] != string.Empty)
                {
                    obj.total_cal_OI = Convert.ToInt64(text2[1].Replace(",", "").Trim()); j++;
                }
                else if (j == 1 && text2[1] != "Total" && text2[1] != null && text2[1] != string.Empty)
                {
                    obj.total_cal_Volume = Convert.ToInt64(text2[1].Replace(",", "").Trim()); j++;
                }
                else if (j == 2 && text2[1] != "Total" && text2[1] != null && text2[1] != string.Empty)
                {
                    obj.total_put_Volume = Convert.ToInt64(text2[1].Replace(",", "").Trim()); j++;
                }
                else if (j == 3 && text2[1] != "Total" && text2[1] != null && text2[1] != string.Empty)
                {
                    obj.total_put_OI = Convert.ToInt64(text2[1].Replace(",", "").Trim()); j++;
                }
            }
            return(obj);
        }
Ejemplo n.º 10
0
        public decimal FindMaxPain(QCAlgorithmFramework algorithm, OptionChain chain)
        {
            //get all ITM
            var options = GetOptionsForExpiry(algorithm, chain.Underlying.Symbol, 0);
            var calls   = options.Where((o) => o.Right == OptionRight.Call && o.Strike < chain.Underlying.Price)
                          .OrderBy((o) => o.Strike);
            var puts = options.Where((o) => o.Right == OptionRight.Put && o.Strike > chain.Underlying.Price)
                       .OrderBy((o) => - o.Strike);

            //walk up the chain until both sides balance
            int openCalls = 0;
            int openPuts  = 0;

            List <int>     runningCalls     = new List <int>();
            List <int>     runningPuts      = new List <int>();
            OptionContract largestBidOption = null;
            int            pi = 0;  //put incrementor

            for (int ci = 0; ci < calls.Count() && pi < puts.Count(); ci++)
            {
                var call = calls.Skip(ci).First();
                var put  = puts.Skip(pi++).First();

                if (Math.Round((put.Strike - chain.Underlying.Price)) > Math.Round((chain.Underlying.Price - call.Strike)))
                {
                    //try again, re-align
                    ci--;
                    continue;
                }

                //TODO: OpenInterest????!!!!!!!!!!!!!!!!!
                openCalls += (int)call.BidSize;
                openPuts  += (int)put.BidSize;

                runningCalls.Add(openCalls);
                runningPuts.Add(openPuts);

                //for now, doing a hack where it finds the option contract with the most interest (largest bid size)
                if (largestBidOption == null)
                {
                    largestBidOption = call;
                }
                if (call.BidSize > largestBidOption.BidSize)
                {
                    largestBidOption = call;
                }
                if (put.BidSize > largestBidOption.BidSize)
                {
                    largestBidOption = put;
                }
            }

            if (largestBidOption == null)
            {
                return(0);
            }

            return(largestBidOption.Strike);
        }
Ejemplo n.º 11
0
        public PredictionViewModel GetPrediction(string underlying, int daysInFuture, double?volatility = null)
        {
            OptionChain         optionChain = GetOptionChainWithPredefinedVolatility(underlying, volatility);
            Prediction          result      = _predictionAndStdDevService.GetPrediction(optionChain, daysInFuture);
            PredictionViewModel viewModel   = Mapper.Map <Prediction, PredictionViewModel>(result);

            return(viewModel);
        }
Ejemplo n.º 12
0
 private void Init(Stock stock, DateTime date)
 {
     InitializeComponent();
     _chain = OptionDataBase.Get(stock, date);
     FillChainExpandables();
     FillSymbolLabel();
     ClearPreviewTrade();
 }
Ejemplo n.º 13
0
        private static List <string> FlattenOptionNumbers(OptionChain optionChain)
        {
            IEnumerable <string> calls         = optionChain.Select(x => x.CallOption.OptionNumber);
            IEnumerable <string> puts          = optionChain.Select(x => x.PutOption.OptionNumber);
            List <string>        optionNumbers = new List <string>(calls);

            optionNumbers.AddRange(puts);
            return(optionNumbers);
        }
Ejemplo n.º 14
0
 public void Fill(OptionChain dateChain)
 {
     _experation = dateChain.Options[0].Experation;
     _dataDate   = dateChain.Options[0].DataDate;
     _strikes    = dateChain.Strikes();
     FillPanelChain(dateChain);
     FillLabels(dateChain);
     AddPriceLine(dateChain);
 }
        public List <CoveredCallViewModel> GetAll(string underlying, LegType?legType = null, double?minimumReturn = null, double?minimumPremium = null, double?volatility = null)
        {
            OptionChain chain = GetOptionChainWithPredefinedVolatility(underlying, volatility);

            List <CoveredCall>          coveredCalls = _coveredCallService.GetAllCoveredCalls(chain, legType, minimumPremium, minimumReturn);
            List <CoveredCallViewModel> viewModels   = Mapper.Map <List <CoveredCall>, List <CoveredCallViewModel> >(coveredCalls);

            return(viewModels);
        }
Ejemplo n.º 16
0
        public List <PredictionViewModel> GetPredictions(string underlying)
        {
            OptionChain       optionChain = GetOptionChainWithPredefinedVolatility(underlying, null);
            List <Prediction> predictions =
                optionChain.ExpirationDates.Select(x => _predictionAndStdDevService.GetPrediction(optionChain, x.TotalNumberOfDaysUntilExpiry)).ToList();

            List <PredictionViewModel> results = Mapper.Map <List <Prediction>, List <PredictionViewModel> >(predictions);

            return(results);
        }
Ejemplo n.º 17
0
 public void ChangeStock(Stock stock, DateTime date)
 {
     _chain = OptionDataBase.Get(stock, date);
     if (_chain != null)
     {
         FillChainExpandables();
         FillSymbolLabel();
         ClearPreviewTrade();
     }
 }
Ejemplo n.º 18
0
            public bool HistoricData(DateTime date)
            {
                OptionChain chain = OptionDataBase.Get(_stock, date);

                if (chain != null)
                {
                    return(true);
                }
                return(false);
            }
Ejemplo n.º 19
0
        public List <DateAndDefaultStandardDeviationsViewModel> GetExpiriesAndDefaultStandardDeviations(string symbol, double?volatility)
        {
            OptionChain optionChain = GetOptionChainWithPredefinedVolatility(symbol, volatility);
            List <DateAndStandardDeviations> expiryAndStandardDeviation = _predictionAndStdDevService.GetExpiriesAndDefaultStandardDeviations(optionChain,
                                                                                                                                              optionChain.ExpirationDates);
            List <DateAndDefaultStandardDeviationsViewModel> viewModel =
                Mapper.Map <List <DateAndStandardDeviations>, List <DateAndDefaultStandardDeviationsViewModel> >(expiryAndStandardDeviation);

            return(viewModel);
        }
Ejemplo n.º 20
0
        public List <DateAndStandardDeviationViewModel> GetProbabilityCone(string symbol, double sd = 1, double?volatility = null)
        {
            OptionChain optionChain = GetOptionChainWithPredefinedVolatility(symbol, volatility);
            List <DateAndStandardDeviation> expiryAndStandardDeviations = _predictionAndStdDevService.GetStandardDeviationsForDates(optionChain,
                                                                                                                                    optionChain.ExpirationDates, sd);
            List <DateAndStandardDeviationViewModel> viewModel =
                Mapper.Map <List <DateAndStandardDeviation>, List <DateAndStandardDeviationViewModel> >(expiryAndStandardDeviations);

            return(viewModel);
        }
Ejemplo n.º 21
0
 private static void AddChain(OptionChain chain)
 {
     if (chain != null && !dataBase.Contains(chain))
     {
         dataBase.Add(chain);
         if (dataBase.Count > 20)
         {
             RemoveChain(0);
         }
     }
 }
        public async Task DownloadOptionChains()
        {
            Thread.Sleep(1000);

            DateTime monday = DateTime.Now.GetPreviousDayOfWeekOccurrence(DayOfWeek.Monday);
            DateTime friday = DateTime.Now.GetPreviousDayOfWeekOccurrence(DayOfWeek.Friday);

            Query query = new Query();

            query.SortPropertyName = Security.PropertyNames.Symbol;
            query.QuerySingleFilters.Add(new QuerySingleFilter()
            {
                PropertyName  = Security.PropertyNames.PairEligible,
                Parameter     = "true",
                QueryOperator = QueryOperators.Equals
            });

            List <Security> securities = SecurityService.GetCollection(query);

            securities.RemoveAll(x => (x.NextEarningsDate.HasValue && x.NextEarningsDate >= monday && x.NextEarningsDate <= friday));
            securities.RemoveAll(x => (x.ExDividendDate.HasValue && x.ExDividendDate >= monday && x.ExDividendDate <= friday));

            for (int i = 0; i < securities.Count; i++)
            {
                Security security = securities[i];

                OnProgressMessageRaised(new HtmlTag("li").Class("list-group-item").Class("active")
                                        .Append(HtmlTags.Span.Append("Processing security:&nbsp;"))
                                        .Append(HtmlTags.B.Append(security.Symbol)).ToHtml().ToString(), this.JobId);

                if (SecurityService.GetCurrentPrice(security))
                {
                    SecurityService.Save(security);

                    OnProgressMessageRaised(new HtmlTag("li").Class("list-group-item")
                                            .Append(HtmlTags.B.Append(security.Symbol))
                                            .Append(HtmlTags.Span.Append($"&nbsp;current price: {security.CurrentPrice:C}"))
                                            .ToHtml().ToString(), this.JobId);

                    OptionChain optionChain = OptionChainService.GetOpcOptionChain(security);
                    if (optionChain != null)
                    {
                        OnProgressMessageRaised(new HtmlTag("li").Class("list-group-item")
                                                .Append(HtmlTags.B.Append(security.Symbol))
                                                .Append(HtmlTags.Span.Append("&nbsp;option chain retrieved"))
                                                .ToHtml().ToString(), this.JobId);

                        optionChain.SecurityIdentifier = security.Identifier;

                        OptionChainService.Save(optionChain);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        public OptionChain GetOptionChain(Slice slice)
        {
            OptionChain chain = null;

            slice.OptionChains.TryGetValue(_OptionSymbol, out chain);
            if (chain == null)
            {
                //Console.WriteLine("<{0}> No option chain here!", slice.Time.ToString());
            }

            return(chain);
        }
        private Option GetOptionMatchToStrategyLeg(OptionChain chain, SuggestedStrategyLeg strategyLeg)
        {
            if (!strategyLeg.StrikePrice.HasValue || strategyLeg.LegType == LegType.Security)
            {
                throw new InvalidOperationException();
            }

            Option targetOptionChain = chain[strategyLeg.ExpirationDate.FutureDate, strategyLeg.StrikePrice.Value, strategyLeg.LegType == LegType.Put
                                ? LegType.Put
                                : LegType.Call];

            return(targetOptionChain);
        }
Ejemplo n.º 25
0
 private void LoadStock(Stock stock)
 {
     if (stock.StockSymbol.Length > 0)
     {
         if (OptionChain.DataAvailible(stock, _sim.SimulationDate))
         {
             _sim.ChangeStock(stock);
             chartPanel1.LoadStockData(_sim.StockData);
             chainPanel1.LoadStock(stock, _sim.SimulationDate);
             FillStockInfoUI(stock);
         }
     }
 }
        private bool MeetMinBidResctictions(OptionChain chain, SuggestedStrategyLeg strategyLeg)
        {
            Option targetOption = GetOptionMatchToStrategyLeg(chain, strategyLeg);

            if (targetOption == null)
            {
                return(false);
            }
            double minimalBidPrice = AppConfigManager.MinimalBidForTradingStrategies;
            double currentBid      = targetOption.Bid == 0 ? targetOption.PreviousSettlementPrice : targetOption.Bid;

            return(currentBid > minimalBidPrice);
        }
 public static void Delete(int identifier)
 {
     using (TradeProAssistantContext context = new TradeProAssistantContext())
     {
         try
         {
             OptionChain optionchain = context.OptionChains.Find(identifier);
             context.Entry(optionchain).State = EntityState.Deleted;
             context.SaveChanges();
         }
         catch { }
     }
 }
        public static int Save(OptionChain optionchain)
        {
            using (TradeProAssistantContext context = new TradeProAssistantContext())
            {
                context.Entry(optionchain).State = optionchain.IsNew ?
                                                   EntityState.Added :
                                                   EntityState.Modified;

                context.SaveChanges();

                return(optionchain.Identifier);
            }
        }
        public List <SuggestedStrategy> GetSuggestedTradingStrategies(string symbol, bool opposite = false)
        {
            List <Strategy> strategies = new List <Strategy>();

            strategies.Add(_strategyService.GetAll().Single(x => x.Name == DefaultFirstStrategyName));
            strategies.Add(_strategyService.GetAll().Single(x => x.Name == DefaultSecondStrategyName));
            strategies.Add(_strategyService.GetAll().Single(x => x.Name == DefaultThirdStrategyName));

            OptionChain chain = _marketDataService.GetOptionChain(symbol);

            List <SuggestedStrategy> result = strategies.Select(x => FullfillStrategy(chain, x, opposite)).ToList();

            return(result);
        }
        public void CheckGreeks(OptionChain contracts)
        {
            if (!_checkGreeks || !contracts.Any())
            {
                return;
            }

            _checkGreeks            = false;
            _triedGreeksCalculation = true;

            foreach (var contract in contracts)
            {
                Greeks greeks = new Greeks();
                try
                {
                    greeks = contract.Greeks;

                    // Greeks should have not been successfully accessed if the option style is not supported
                    if (!_optionStyleIsSupported)
                    {
                        throw new Exception($"Expected greeks not to be calculated for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, which does not support them, but they were");
                    }
                }
                catch (ArgumentException)
                {
                    // ArgumentException is only expected if the option style is not supported
                    if (_optionStyleIsSupported)
                    {
                        throw new Exception($"Expected greeks to be calculated for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, which supports them, but they were not");
                    }
                }

                // Greeks shpould be valid if they were successfuly accessed for supported option style
                if (_optionStyleIsSupported)
                {
                    if (greeks.Delta == 0m && greeks.Gamma == 0m && greeks.Theta == 0m && greeks.Vega == 0m && greeks.Rho == 0m)
                    {
                        throw new Exception($"Expected greeks to not be zero simultaneously for {contract.Symbol.Value}, an {_option.Style} style option, using {_option?.PriceModel.GetType().Name}, but they were");
                    }

                    if (((contract.Right == OptionRight.Call && (greeks.Delta < 0m || greeks.Delta > 1m || greeks.Rho < 0m)) ||
                         (contract.Right == OptionRight.Put && (greeks.Delta < -1m || greeks.Delta > 0m || greeks.Rho > 0m)) ||
                         greeks.Vega < 0m || greeks.Gamma < 0m))
                    {
                        throw new Exception($"Expected greeks to have valid values. Greeks were: Delta: {greeks.Delta}, Rho: {greeks.Rho}, Theta: {greeks.Theta}, Vega: {greeks.Vega}, Gamma: {greeks.Gamma}");
                    }
                }
            }
        }
Ejemplo n.º 31
0
        private static bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, Security security, Lazy<Slice> sliceFuture)
        {
            var symbol = baseData.Symbol;
            
            OptionChain chain;
            var canonical = Symbol.Create(symbol.ID.Symbol, SecurityType.Option, symbol.ID.Market);
            if (!optionChains.TryGetValue(canonical, out chain))
            {
                chain = new OptionChain(canonical, algorithmTime);
                optionChains[canonical] = chain;
            }

            var universeData = baseData as OptionChainUniverseDataCollection;
            if (universeData != null)
            {
                if (universeData.Underlying != null)
                {
                    chain.Underlying = universeData.Underlying;
                }
                foreach (var contractSymbol in universeData.FilteredContracts)
                {
                    chain.FilteredContracts.Add(contractSymbol);
                }
                return false;
            }

            OptionContract contract;
            if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
            {
                var underlyingSymbol = Symbol.Create(baseData.Symbol.ID.Symbol, SecurityType.Equity, baseData.Symbol.ID.Market);
                contract = new OptionContract(baseData.Symbol, underlyingSymbol)
                {
                    Time = baseData.EndTime,
                    LastPrice = security.Close,
                    BidPrice = security.BidPrice,
                    BidSize = security.BidSize,
                    AskPrice = security.AskPrice,
                    AskSize = security.AskSize,
                    UnderlyingLastPrice = chain.Underlying != null ? chain.Underlying.Price : 0m
                };
                chain.Contracts[baseData.Symbol] = contract;
                var option = security as Option;
                if (option != null)
                {
                    contract.SetOptionPriceModel(() => option.PriceModel.Evaluate(option, sliceFuture.Value, contract));
                }
            }

            // populate ticks and tradebars dictionaries with no aux data
            switch (baseData.DataType)
            {
                case MarketDataType.Tick:
                    var tick = (Tick)baseData;
                    chain.Ticks.Add(tick.Symbol, tick);
                    UpdateContract(contract, tick);
                    break;

                case MarketDataType.TradeBar:
                    var tradeBar = (TradeBar)baseData;
                    chain.TradeBars[symbol] = tradeBar;
                    contract.LastPrice = tradeBar.Close;
                    break;

                case MarketDataType.QuoteBar:
                    var quote = (QuoteBar)baseData;
                    chain.QuoteBars[symbol] = quote;
                    UpdateContract(contract, quote);
                    break;

                case MarketDataType.Base:
                    chain.AddAuxData(baseData);
                    break;
            }
            return true;
        }