/// Prediction Algo via Technical Indicators
        public List <Results> MathPredictsTheFuture(DownloadEngine download, MACD macd, Stochastic stochastic,
                                                    Transactions transactions, TechnicalIndicators indicators, string stock)
        {
            DateTime date = transactions.DatabaseDateQuery(database, stock)[0];
            // 50 Day Average - queries database and calculates the 50 day average
            double FiftyDayAverage = indicators.FiftyDayAvg(stock, transactions);

            // MACD - determines if a stock is bearish or bullish. Uses 12 and 26 period exponental moving average
            List <MACD> todaysMACD = macd.TodaysMACD(stock, transactions);
            // Stochastic
            List <Stochastic> todayStoch = stochastic.StochasticToday(Database, stock);

            List <Results> results = new List <Results>()
            {
                new Results
                {
                    Date             = date,
                    CIK              = download.DatabaseCIKQuery(Database, stock),
                    Symbol           = stock,
                    LastClose        = transactions.CloseQuery(Database, stock),
                    FiftyDayAvg      = FiftyDayAverage,
                    mACD             = todaysMACD[0].MACDValue,
                    MACDSignal       = todaysMACD[0].MACDSignal,
                    EMA12            = todaysMACD[0].EMA12,
                    EMA26            = todaysMACD[0].EMA26,
                    StochasticFast   = todayStoch[0].Fast,
                    StochasticSlow   = todayStoch[0].Slow,
                    StochasticSignal = todayStoch[0].Signal
                }
            };

            return(results);
        }
        private void DownloadTimer(DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic,
                                   TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database, string downloadTime)
        {
            var DailyTime = downloadTime;  //Time when method needs to be called

            var timeParts = DailyTime.Split(new char[1] {
                ':'
            });

            var dateNow = DateTime.Now;
            var date    = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
                                       int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
            TimeSpan ts;

            if (date > dateNow)
            {
                ts = date - dateNow;
            }
            else
            {
                date = date.AddDays(1);
                ts   = date - dateNow;
            }
            while (date != dateNow)
            {
                Console.WriteLine($"Waiting for {downloadTime}");
                //waits certan time and run the code
                Task.Delay(ts).ContinueWith((x) => Download(date, download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database));
                Console.Read();
            }
        }
        public void Run(string downloadTime)
        {
            DateTime           date          = DateTime.Now;
            DownloadEngine     download      = new DownloadEngine();
            Formatting         formatting    = new Formatting();
            PeregrineOperation peregrine     = new PeregrineOperation();
            MACD                macd         = new MACD();
            Stochastic          stochastic   = new Stochastic();
            TechnicalIndicators indicators   = new TechnicalIndicators();
            Transactions        transactions = new Transactions();
            WebClient           web          = new WebClient(); // provides the ability to download from the internet
            WebURIs             uRIs         = new WebURIs();   // refers to an instance of the Wall Street Journal URL

            DownloadTimer(download, formatting, peregrine, macd, stochastic, indicators, transactions, web, uRIs, Database, downloadTime);
        }
Beispiel #4
0
        private double?Calculate20PointEMA(Quote quote)
        {
            double?sma = TechnicalIndicators.SMA(quoteList[quote.Symbol].Select(q => q.LTP).ToList(), quote.LTP, 20);
            double previousEMA;

            if (twentyEMAs[quote.Symbol].Count > 0)
            {
                previousEMA = twentyEMAs[quote.Symbol].Last();
            }
            else
            {
                previousEMA = sma.Value;
            }
            double?ema = TechnicalIndicators.EMA(quoteList[quote.Symbol].Select(q => q.LTP).ToList(), quote.LTP, 20, previousEMA);

            return(ema);
        }
        /// Download and save to Database
        private void Download(DateTime date, DownloadEngine download, Formatting formatting, PeregrineOperation peregrine, MACD macd, Stochastic stochastic, TechnicalIndicators indicators, Transactions transactions, WebClient web, WebURIs uRIs, string Database)
        {
            List <string> Symbols = transactions.DatabaseSymbolListQuery(Database, stocks);

            transactions.TruncateStockTable(Database, "Clean Data"); // clears data from the clean data table.
            int count = 1;

            foreach (var stock in Symbols)
            {
                Console.Clear();
                Console.WriteLine($"Downloading {stock} || {count} of {Symbols.Count}");
                download.ToDatabase(date, formatting, peregrine, transactions, web, uRIs, stock, Database);
                count++;
            }
            Console.WriteLine("I'm Done");
            //count = 1;
            //calls the list of stocks that have been data verified
            //List<string> CleanData = transactions.DatabaseSymbolListQuery(Database, stocks);
            //foreach (var stock in CleanData)
            //{
            //    Console.Clear();
            //    Console.WriteLine($"Doing Math {stock} || {count} of {CleanData.Count}");
            //    List<Results> results = MathPredictsTheFuture(download, macd, stochastic, transactions, indicators, stock);
            //    transactions.SaveToTableResult(Database, results); // saves the calculations to the Results table in the database
            //    count++;
            //}


            //// calls the stocks from the results list
            //List<PeregrineResults> todaysResults = transactions.DailyResultsQuery(peregrine.Database);
            //transactions.TruncateStockTable(database, peregrineresults); // clears the web results table. This table feeds the model for the ASP.Net interface.
            //transactions.SaveToTableWebResult(peregrine.Database, todaysResults);
            //Console.WriteLine("Peregrine Results Updated");
        }
    //**************************************************************************************

    /// <summary>
    /// Returns calculated parameters.
    /// </summary>
    /// <param name="iCurrentPrice">Last known price.</param>
    /// <param name="iCandlestickIndex">Provides index (current time) for each candlestick list. If this value is set to null, the most recent entry will be used.</param>
    /// <param name="iCandlesticks">Maximum amount of daily candlesticks: 270; 12H: 25; 6H: 50; 3H: 100; 2H: 150; 1H: 300; 30m: 600; 15m: 0; 5m: 0; 1m:0</param>
    public static float[] CalculateParameters(List <ClassifierParameter> iParameters, CandlestickCollection iCandlesticks, Candlestick.Period iPeriod, float iCurrentPrice, CandlestickIndexCollection iCandlestickIndex)
    {
        var candlesticks     = iCandlesticks[iPeriod];
        int candlestickIndex = iCandlestickIndex == null ? candlesticks.Count - 1 : iCandlestickIndex[iPeriod];

        if (candlestickIndex >= iCandlesticks[iPeriod].Count)
        {
            throw new Exception("Candlestick index is higher than total number of candlesticks");
        }

        // Make sure we have enough periods
        for (int i = 0; i < iParameters.Count; i++)
        {
            if (candlesticks.Count < iParameters[i].Periods + 10)
            {
                return(null);
            }
        }

        float[] results = new float[iParameters.Count];

        var macd             = new SortedDictionary <int, MACD>();
        var macdCurrentPrice = new SortedDictionary <int, MACD>();

        for (int i = 0; i < iParameters.Count; i++)
        {
            //int candlestickIndex = Candlestick.GetIndex(iParameters[i].Candlesticks, iCandlesticks, iCandlestickIndex);
            int periods = iParameters[i].Periods;

            switch (iParameters[i].Type)
            {
            case ParameterType.RSI:
                results[i] = TechnicalIndicators.CalculateRSI(candlesticks, periods, candlestickIndex);
                break;

            case ParameterType.RSIWithCurrentPrice:
                results[i] = TechnicalIndicators.CalculateRSI(candlesticks, periods, candlestickIndex, iCurrentPrice);
                break;

            case ParameterType.RSIInt:
                results[i] = TechnicalIndicators.RSIToInt(TechnicalIndicators.CalculateRSI(candlesticks, periods, candlestickIndex));
                break;

            case ParameterType.RSIIntWithCurrentPrice:
                results[i] = TechnicalIndicators.RSIToInt(TechnicalIndicators.CalculateRSI(candlesticks, periods, candlestickIndex, iCurrentPrice));
                break;

            case ParameterType.LastCriticalRSI:
                int startIndex      = Math.Max(candlestickIndex - 270 + iParameters[i].Periods, iParameters[i].Periods);
                int lastCriticalRSI = 0;

                for (int k = startIndex; k >= candlestickIndex; k++)
                {
                    lastCriticalRSI = TechnicalIndicators.CalculateLastCriticalRSI(TechnicalIndicators.RSIToInt(TechnicalIndicators.CalculateRSI(candlesticks, periods, k)), lastCriticalRSI);
                }

                results[i] = lastCriticalRSI;
                break;

            case ParameterType.LastCriticalRSIWithCurrentPrice:
                startIndex      = Math.Max(candlestickIndex - 270 + iParameters[i].Periods, iParameters[i].Periods);
                lastCriticalRSI = 0;

                for (int k = startIndex; k >= candlestickIndex; k++)
                {
                    lastCriticalRSI = TechnicalIndicators.CalculateLastCriticalRSI(TechnicalIndicators.RSIToInt(TechnicalIndicators.CalculateRSI(candlesticks, periods, k, iCurrentPrice)), lastCriticalRSI);
                }

                results[i] = lastCriticalRSI;
                break;

            case ParameterType.MeanToStd:
                results[i] = TechnicalIndicators.CalculateMeanToStdDev(candlesticks, periods, candlestickIndex, iCurrentPrice);
                break;

            case ParameterType.MeanToStdInt:
                results[i] = (float)Math.Floor(TechnicalIndicators.CalculateMeanToStdDev(candlesticks, periods, candlestickIndex, iCurrentPrice));
                break;

            case ParameterType.LinearRegressionSlope:
                results[i] = (float)TechnicalIndicators.CalculateLinearRegressionSlope(candlesticks, periods, candlestickIndex);
                break;

            case ParameterType.LinearRegressionSlopePN:
                results[i] = TechnicalIndicators.CalculateLinearRegressionSlope(candlesticks, periods, candlestickIndex) >= 0 ? 1 : -1;
                break;

            case ParameterType.MarginSlope:
                results[i] = TechnicalIndicators.CalculateMarginSlope(candlesticks, periods, candlestickIndex, iCurrentPrice, iParameters[i].Attributes[0]);
                break;

            case ParameterType.MarginSlopePN:
                results[i] = TechnicalIndicators.CalculateMarginSlopePN(candlesticks, periods, candlestickIndex, iCurrentPrice, iParameters[i].Attributes[0]);
                break;

            case ParameterType.MACDSign:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                results[i] = macd[periods].Signal;
                break;

            case ParameterType.MACDSignWithCurrentPrice:
                if (!macdCurrentPrice.ContainsKey(periods))
                {
                    macdCurrentPrice.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex, iCurrentPrice));
                }

                results[i] = macdCurrentPrice[periods].Signal;
                break;

            case ParameterType.MACDHist:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                results[i] = macd[periods].Hist;
                break;

            case ParameterType.MACDHistWithCurrentPrice:
                if (!macdCurrentPrice.ContainsKey(periods))
                {
                    macdCurrentPrice.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex, iCurrentPrice));
                }

                results[i] = macdCurrentPrice[periods].Hist;
                break;

            case ParameterType.MACDHistChange:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                MACD macd90         = macd[periods];
                MACD previousMACD90 = TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex - 1);

                results[i] = previousMACD90.Hist == 0 ? 0 : (macd90.Hist / previousMACD90.Hist - 1);
                break;

            case ParameterType.MACDHistChangeWithCurrentPrice:
                if (!macdCurrentPrice.ContainsKey(periods))
                {
                    macdCurrentPrice.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex, iCurrentPrice));
                }

                macd90         = macdCurrentPrice[periods];
                previousMACD90 = TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex - 1);

                results[i] = previousMACD90.Hist == 0 ? 0 : (macd90.Hist / previousMACD90.Hist - 1);
                break;

            case ParameterType.MACDHistSlope:
                float[] hist = new float[(int)iParameters[i].Attributes[0]];
                for (int k = hist.Length - 1; k >= 0; k--)
                {
                    hist[hist.Length - 1 - k] = TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex - k).Hist;
                }

                results[i] = new LinearRegression(hist).Slope;
                break;

            case ParameterType.MACDHistPN:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                results[i] = macd[periods].Hist >= 0 ? 1 : -1;
                break;

            case ParameterType.MACDHistCrossed:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                macd90         = macd[periods];
                previousMACD90 = TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex - 1);

                if (macd90.Hist >= 0)
                {
                    results[i] = previousMACD90.Hist >= 0 ? 0 : 1;
                }
                else
                {
                    results[i] = previousMACD90.Hist < 0 ? 0 : -1;
                }
                break;

            case ParameterType.MACDHistDifference:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                macd90         = macd[periods];
                previousMACD90 = TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex - 1);

                results[i] = macd90.Hist - previousMACD90.Hist;
                break;

            case ParameterType.MACD:
                if (!macd.ContainsKey(periods))
                {
                    macd.Add(periods, TechnicalIndicators.CalculateMACD(candlesticks, periods, candlestickIndex));
                }

                results[i] = macd[periods].Macd;
                break;

            case ParameterType.SlopesEMA:
                List <float> slopes = new List <float>();

                for (int k = 0; k < iParameters[i].Attributes.Count; k++)
                {
                    int periodLength = (int)iParameters[i].Attributes[k];
                    slopes.Add(new LinearRegression(TechnicalIndicators.CreatePriceArray(candlesticks, periodLength, candlestickIndex)).Slope);
                }

                results[i] = Utils.Last(Statistics.EMA(slopes.ToArray(), slopes.Count));
                break;

            case ParameterType.ABAverage:
                results[i] = (TechnicalIndicators.CalculatePriceABaverage(candlesticks, periods, candlestickIndex, iCurrentPrice) ? 1.0f : 0.0f);
                break;

            case ParameterType.PercentMargin:
                results[i] = (TechnicalIndicators.CalculateOnePercentMargin(candlesticks, periods, candlestickIndex, iCurrentPrice, iParameters[i].Attributes[0]) ? 1.0f : 0.0f);
                break;

            case ParameterType.Classifier:
                results[i] = WekaClassifier.Find((int)iParameters[i].Attributes[0]).PredictDFP(iCandlesticks, iCurrentPrice, iCandlestickIndex);
                break;

            case ParameterType.ClassifierTargetChangeOldest:
                var classifier = WekaClassifier.Find((int)iParameters[i].Attributes[0]);
                var targetTime = iCandlesticks[WekaClassifier.kTrainingPeriod][iCandlestickIndex[WekaClassifier.kTrainingPeriod] - classifier.ProfitTime].StartTime;

                var pastIndex = new CandlestickIndexCollection();
                for (int k = (int)WekaClassifier.kTrainingPeriod; k >= 0; k--)
                {
                    pastIndex[k] = Math.Max(0, Math.Min(iCandlesticks[k].Count - 1, Candlestick.FindIndex(iCandlesticks[k], targetTime)));
                }

                var priceBefore = iCandlesticks[WekaClassifier.kTrainingPeriod][pastIndex[WekaClassifier.kTrainingPeriod]].MedianPrice;

                var wfp = classifier.PredictDFP(iCandlesticks, priceBefore, pastIndex);
                var targetPriceChange = (float)Math.Exp(wfp);

                results[i] = priceBefore * targetPriceChange / iCurrentPrice - 1.0f;
                break;
            }
        }

        return(results);
    }
Beispiel #7
0
        private void RadButton2_Click_1(object sender, EventArgs e)
        {
            // ConcurrentBag<List<Model.PNL>> consolidated = new ConcurrentBag<List<Model.PNL>>();
            try
            {
                Parallel.ForEach((radDropDownList1.Items), (x) =>
                {
                    ProgressDelegate myProgres = ShowMyProgress;
                    List <Model.Idea> myideas  = Common.GetIdeas();

                    Model.Idea selectedIdea = myideas.Where(a => a.Name == x.Text).First();
                    StockOHLC stockOHLC     = new StockOHLC();
                    int year = 2019;
                    //for (int year = 2015; year <= 2019; year++)
                    //{
                    //Load Data
                    Task <Dictionary <string, List <Model.Candle> > > loadmydata = Task.Run <Dictionary <string, List <Model.Candle> > >(() => stockOHLC.GetOHLC(new DateTime(year, Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(year + 1, Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text)), selectedIdea.Interval, myProgres));

                    //Apply indicators

                    loadmydata.ContinueWith((t0) =>
                    {
                        SetText("Applying indicators");
                        Task <Dictionary <string, List <Model.Candle> > > withIndicators = Task.Run <Dictionary <string, List <Model.Candle> > >(() => TechnicalIndicators.AddIndicators(t0.Result, selectedIdea.TI, new DateTime(year, Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text))));
                        Task getTradingStocks = withIndicators.ContinueWith((t1) =>
                        {
                            Task <Dictionary <Guid, Model.StrategyModel> > getTradedStocks = Task.Run <Dictionary <Guid, Model.StrategyModel> >(() => stockOHLC.GetTopMostSolidGapOpenerDayWise(t1.Result, selectedIdea, myProgres));
                            Task tradeMyStocks = getTradedStocks.ContinueWith((t2) =>
                            {
                                Task <List <Model.PNL> > calculation = Task <List <Model.PNL> > .Run(() => stockOHLC.TradeStocks(t2.Result, t1.Result, selectedIdea, myProgres));
                                calculation.ContinueWith((t3) =>
                                {
                                    consolidated.Add(t3.Result);
                                    //SetDataSource(t3.Result);
                                    //SetText("Idea ran successfully");
                                });
                            });
                        });
                    });
                    //}
                });
                //while(consolidated.Count()< radDropDownList1.Items.Count)
                //{
                //    Thread.Sleep(10000);
                //}
            }
            catch (Exception ex)
            {
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", Environment.NewLine);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.Message);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.StackTrace);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.InnerException);
            }
        }
Beispiel #8
0
        private void btnLoad_Click(object sender, EventArgs e)
        {
            l.Clear();
            //rgvStocks.DataSource = null;
            try
            {
                ProgressDelegate  myProgres = ShowMyProgress;
                List <Model.Idea> myideas   = null;
                if (checkBox1.Checked)
                {
                    myideas = Common.GetIdeas().OrderBy(a => a.runOrder).ToList();
                }
                else
                {
                    myideas = Common.GetIdeas().Where(a => a.Name == radDropDownList1.SelectedItem.Text).ToList();
                }

                List <Task> allTask = new List <Task>();
                //Model.Idea selectedIdea = myideas.Where(a => a.Name == radDropDownList1.SelectedItem.Text).First();
                foreach (var selectedIdea in myideas.OrderBy(a => a.runOrder))
                {
                    if (selectedIdea.Name == "Dual_Time_Frame_Momentum")
                    {
                        StockOHLC stockOHLC = new StockOHLC();

                        //Load Data
                        Task <Dictionary <string, List <Model.Candle> > > loadmydata = Task.Run <Dictionary <string, List <Model.Candle> > >(() => stockOHLC.GetOHLC(new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text)), selectedIdea.Interval, myProgres));
                        allTask.Add(loadmydata);
                        loadmydata.ContinueWith((t0) =>
                        {
                            SetText("Applying stochastic indicators to small timeframe");
                            Task <Dictionary <string, List <Model.Candle> > > withIndicators = Task.Run <Dictionary <string, List <Model.Candle> > >(() => TechnicalIndicators.AddIndicators(t0.Result, selectedIdea.TI, new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text))));
                            withIndicators.ContinueWith((t1) =>
                            {
                                Task <Dictionary <string, List <Model.Candle> > > loadmydata2 = Task.Run <Dictionary <string, List <Model.Candle> > >(() => stockOHLC.GetOHLC(new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text)), selectedIdea.Interval2, myProgres));
                                allTask.Add(loadmydata2);
                                loadmydata2.ContinueWith((t2) =>
                                {
                                    SetText("Applying stochastic indicators to large time frame");
                                    Task <Dictionary <string, List <Model.Candle> > > withIndicators2 = Task.Run <Dictionary <string, List <Model.Candle> > >(() => TechnicalIndicators.AddIndicators(t2.Result, selectedIdea.TI, new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text))));
                                    allTask.Add(withIndicators2);

                                    withIndicators2.ContinueWith((t3) =>
                                    {
                                        Task <Dictionary <Guid, Model.StrategyModel> > getTradedStocks = Task.Run <Dictionary <Guid, Model.StrategyModel> >(() => stockOHLC.ApplyDualMomentumStrategyModel(DateTime.Now, t1.Result, t3.Result, selectedIdea, myProgres));
                                        allTask.Add(getTradedStocks);
                                        Task tradeMyStocks = getTradedStocks.ContinueWith((t4) =>
                                        {
                                            var stocksList = t4.Result;
                                            List <PNL> p   = new List <PNL>();
                                            foreach (var s in stocksList)
                                            {
                                                p.Add(new PNL {
                                                    Stock = s.Value.Stock, Date = s.Value.Date, Direction = Enum.GetName(typeof(Model.Trade), s.Value.Trade)
                                                });
                                            }
                                            l.Add(new CustomizedPNL {
                                                order = selectedIdea.runOrder, selectedIdea = selectedIdea, Strategyoutput = p
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    }
                    else
                    {
                        StockOHLC stockOHLC = new StockOHLC();

                        //Load Data
                        Task <Dictionary <string, List <Model.Candle> > > loadmydata = Task.Run <Dictionary <string, List <Model.Candle> > >(() => stockOHLC.GetOHLC(new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text)), selectedIdea.Interval, myProgres));
                        allTask.Add(loadmydata);
                        //loadmydata.Wait();
                        //Apply indicators
                        loadmydata.ContinueWith((t0) =>
                        {
                            SetText("Applying indicators");
                            Task <Dictionary <string, List <Model.Candle> > > withIndicators = Task.Run <Dictionary <string, List <Model.Candle> > >(() => TechnicalIndicators.AddIndicators(t0.Result, selectedIdea.TI, new DateTime(Convert.ToInt32(ddlStartYear.SelectedItem.Text), Convert.ToInt32(ddlStartMonth.SelectedItem.Text), Convert.ToInt32(ddlStartDate.SelectedItem.Text)), new DateTime(Convert.ToInt32(ddlEndYear.SelectedItem.Text), Convert.ToInt32(ddlEndMonth.SelectedItem.Text), Convert.ToInt32(ddlEndDate.SelectedItem.Text))));
                            allTask.Add(withIndicators);
                            Task getTradingStocks = withIndicators.ContinueWith((t1) =>
                            {
                                Task <Dictionary <Guid, Model.StrategyModel> > getTradedStocks = Task.Run <Dictionary <Guid, Model.StrategyModel> >(() => stockOHLC.GetTopMostSolidGapOpenerDayWise(t1.Result, selectedIdea, myProgres));
                                allTask.Add(getTradedStocks);
                                Task tradeMyStocks = getTradedStocks.ContinueWith((t2) =>
                                {
                                    Task <List <Model.PNL> > calculation = Task <List <Model.PNL> > .Run(() => stockOHLC.TradeStocks(t2.Result, t1.Result, selectedIdea, myProgres));
                                    allTask.Add(getTradedStocks);
                                    calculation.ContinueWith((t3) =>
                                    {
                                        l.Add(new CustomizedPNL {
                                            order = selectedIdea.runOrder, selectedIdea = selectedIdea, Strategyoutput = t3.Result
                                        });
                                    });
                                    //calculation.Wait();
                                });
                            });
                        });


                        //loadmydata.Wait();
                        //Task.WaitAll();
                    }
                    Task.Factory.ContinueWhenAll(allTask.ToArray(), FinalWork);
                }
            }
            catch (Exception ex)
            {
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", Environment.NewLine);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.Message);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.StackTrace);
                File.AppendAllText(@"C:\Jai Sri Thakur Ji\Nifty Analysis\errors.txt", System.Reflection.MethodBase.GetCurrentMethod() + " :- " + ex.InnerException);
            }
        }