Ejemplo n.º 1
0
        public void SetPortofolio(StockPortofolio portofolio)
        {
            this.stockPortofolio = portofolio;

             // Initialise list view
             InitializeListView();
        }
        public StockbrokersOrderCreationDlg(StockPortofolio stockPortofolio, StockDictionary stockDictionary)
        {
            InitializeComponent();

             this.stockPortofolio = stockPortofolio;
             this.stockDictionary = stockDictionary;
        }
        public StrategySimulatorDlg(StockDictionary stockDictionary, StockPortofolioList stockPortofolioList, string stockName)
        {
            InitializeComponent();

             // Initialize portofolio combo
             this.stockDictionary = stockDictionary;
             this.portofolioComboBox.Enabled = true;
             this.portofolioComboBox.Items.Clear();
             if (stockPortofolioList.Count == 0)
             {
            StockPortofolio portofolio = new StockPortofolio("SIMULATION");
            stockPortofolioList.Add(portofolio);
             }
             foreach (string name in stockPortofolioList.GetPortofolioNames())
             {
            this.portofolioComboBox.Items.Add(name);
             }
             this.portofolioComboBox.SelectedItem = this.portofolioComboBox.Items[0];

             // Initialize stock combo
             this.stockPortofolioList = stockPortofolioList;
             this.stockComboBox.Enabled = true;
             this.stockComboBox.Items.Clear();
             foreach (StockSerie stockSerie in stockDictionary.Values)
             {
            this.stockComboBox.Items.Add(stockSerie.StockName);
             }
             this.stockComboBox.SelectedItem = this.stockComboBox.Items[0];
        }
Ejemplo n.º 4
0
        public PortofolioDlg(StockDictionary stockDictionary, StockPortofolio stockPortofolio)
        {
            InitializeComponent();

             this.stockDictionary = stockDictionary;
             this.stockPortofolio = stockPortofolio;

             // Initialise list view
             InitializeListView();
        }
 public static IStockPortfolioStrategy CreateStrategy(string name, List<StockSerie> stockSeries, StockPortofolio portfolio, StockDictionary stockDictionary)
 {
     IStockPortfolioStrategy strategy = null;
      if (strategyList == null)
      {
     GetStrategyList();
      }
      if (strategyList.Contains(name))
      {
     PortfolioStrategyManager sm = new PortfolioStrategyManager();
     strategy = (IStockPortfolioStrategy)sm.GetType().Assembly.CreateInstance("StockAnalyzer.StockPortfolioStrategy." + name);
     strategy.Initialise(stockSeries, portfolio, stockDictionary);
      }
      return strategy;
 }
Ejemplo n.º 6
0
        public StockMarketReplay()
        {
            InitializeComponent();

            portfolio = new StockPortofolio("Replay_P");
            portfolio.TotalDeposit = 1000;

            this.TopMost = true;

            this.Position = new PositionViewModel();
            this.position.OnPositionClosed += OnPositionClosed;
            this.position.OnStopTouched += Position_OnStopTouched;
            this.position.OnTargetTouched += Position_OnTargetTouched;
            this.Positions = new ObservableCollection<PositionViewModel>();
            this.Positions.Add(this.Position);
            this.stockPositionUserControl1.DataContext = this;
        }
        public PortfolioSimulatorDlg(StockDictionary stockDictionary, StockPortofolioList stockPortofolioList,
          string stockName, List<StockWatchList> watchLists)
        {
            InitializeComponent();

             foreach (var val in Enum.GetValues(typeof(UpdatePeriod)))
             {
            this.frequencyComboBox.Items.Add(val);
             }
             this.frequencyComboBox.SelectedIndex = 0;

             // Initialize portofolio combo
             this.stockDictionary = stockDictionary;
             this.portofolioComboBox.Enabled = true;
             this.stockPortofolioList = stockPortofolioList;
             this.portofolioComboBox.Items.Clear();
             if (stockPortofolioList.Count == 0)
             {
            StockPortofolio portofolio = new StockPortofolio("SIMULATION");
            stockPortofolioList.Add(portofolio);
             }
             foreach (string name in stockPortofolioList.GetPortofolioNames())
             {
            this.portofolioComboBox.Items.Add(name);
             }
             this.portofolioComboBox.SelectedItem = this.portofolioComboBox.Items[0];

             // Initialise input series
             this.watchLists = watchLists;
             this.portfolioStockSeries = new List<StockSerie>();
             foreach (string wlName in this.watchLists.Select(wl => wl.Name))
             {
            this.watchListComboBox.Items.Add(wlName);
             }
             this.watchListComboBox.SelectedIndex = 1;

             // Initialize Strategy combo
             this.strategyComboBox.Enabled = true;
             this.strategyComboBox.Items.Clear();
             foreach (string name in PortfolioStrategyManager.GetStrategyList())
             {
            this.strategyComboBox.Items.Add(name);
             }
             this.strategyComboBox.SelectedIndex = 0;
        }
Ejemplo n.º 8
0
 private void CreateSimulationPortofolio(float portofolioDeposit)
 {
     // Create new simulation portofolio
     if (CurrentPortofolio == null)
     {
         CurrentPortofolio = this.StockPortofolioList.Find(p => p.Name == this.CurrentStockSerie.StockName + "_P");
         if (CurrentPortofolio == null)
         {
             CurrentPortofolio = new StockPortofolio(this.CurrentStockSerie.StockName + "_P");
             CurrentPortofolio.IsSimulation = true;
             CurrentPortofolio.TotalDeposit = portofolioDeposit;
             this.StockPortofolioList.Add(CurrentPortofolio);
         }
     }
 }
 public void GenerateReportLine(string fileName, StockSerie stockSerie, StockPortofolio portofolio)
 {
     using (StreamWriter sr = new StreamWriter(StockAnalyzerSettings.Properties.Settings.Default.RootFolder + "\\Report\\" + fileName, true))
      {
     sr.WriteLine(stockSerie.StockName + ";" + portofolio.TotalAddedValue.ToString() + ";" + this.SelectedStrategyName + ";" +
         this.StartDate.ToShortDateString() + ";" + this.EndDate.ToShortDateString() + ";" + this.amount.ToString() +
         ";" + this.reinvest.ToString() + ";" + this.amendOrders.ToString() + ";" +
         this.takeProfit.ToString() + ";" + this.profitRate.ToString() + ";" +
         this.stopLoss.ToString() + ";" + this.stopLossRate.ToString() + ";" +
         this.fixedFee.ToString() + ";" + this.taxRate.ToString());
      }
 }
Ejemplo n.º 10
0
        private void generateOrderBtn_Click(object sender, EventArgs e)
        {
            // Manage selected Stock and portofolio
             // Get selected Stock
             StockSerie stockSerie = this.stockDictionary[this.SelectedStockName];
             stockSerie.Initialise();

             // Create dedicated portofolio
             StockPortofolio portofolio = this.stockPortofolioList.Get(this.portofolioComboBox.SelectedItem.ToString());
             StockPortofolio tmpPortofolio = this.stockPortofolioList.Find(p => p.Name == stockSerie.StockName + "_P");
             if (tmpPortofolio == null)
             {
            tmpPortofolio = new StockPortofolio(stockSerie.StockName + "_P");
            this.portofolioComboBox.Items.Add(tmpPortofolio.Name);
            this.stockPortofolioList.Add(tmpPortofolio);
             }
             this.portofolioComboBox.SelectedIndex = this.portofolioComboBox.Items.IndexOf(tmpPortofolio.Name);
             tmpPortofolio.OrderList = portofolio.OrderList.GetSummaryOrderList(stockSerie.StockName, true);

             StockOrder lastOrder = stockSerie.GenerateOrder(this.SelectedStrategy, simulationParameterControl.StartDate, simulationParameterControl.EndDate.AddHours(18),
            simulationParameterControl.amount, simulationParameterControl.reinvest,
            simulationParameterControl.amendOrders, simulationParameterControl.supportShortSelling,
             this.simulationParameterControl.takeProfit, this.simulationParameterControl.profitRate,
             this.simulationParameterControl.stopLoss, this.simulationParameterControl.stopLossRate,
            simulationParameterControl.fixedFee, simulationParameterControl.taxRate,
            tmpPortofolio);

             //// Do a bit of cleanup @@@@
             //if (lastOrder != null && this.simulationParameterControl.removePendingOrders)
             //{
             //    if (lastOrder.IsBuyOrder())
             //    {
             //        lastOrder = null;
             //    }
             //    else
             //    {
             //        if (lastOrder.UpDownState != StockOrder.OrderStatus.Executed)
             //        {
             //            portofolio.OrderList.Remove(portofolio.OrderList.Last());
             //            lastOrder = null;
             //        }
             //    }
             //}

             if (this.simulationParameterControl.displayPendingOrders && lastOrder != null && lastOrder.State == StockOrder.OrderStatus.Pending)
             {
            OrderEditionDlg orderEditionDlg = new OrderEditionDlg(lastOrder);
            orderEditionDlg.StartPosition = FormStartPosition.Manual;
            orderEditionDlg.Location = new Point(0, 0);
            orderEditionDlg.ShowDialog();
             }
             // Send event
             if (SimulationCompleted != null)
             {
            SimulationCompleted();
             }
        }
Ejemplo n.º 11
0
        private void OnCurrentPortofolioChanged(StockPortofolio portofolio, bool activate)
        {
            if (portofolio != null)
            {
                CurrentPortofolio = portofolio;
                this.StockPortofolioList.Remove(portofolio.Name);
                this.StockPortofolioList.Add(portofolio);
            }

            this.OnNeedReinitialise(true);

            if (activate)
            {
                this.Activate();
            }
        }
        private void UpdateBestForValue(StockSerie stockSerie, FloatPropertyRange range, bool refreshGUI,
            ref StockPortofolio bestPortofolio, ref StockPersonality bestPersonality, float currentValue)
        {
            stockSerie.StockAnalysis.StockPersonality.SetFloatPropertyValue(range, currentValue);
            stockSerie.ResetSAREX();

            //Console.WriteLine("Fixed Fee:" + this.simulationParameterControl.fixedFee + " Tax Rate:" + this.simulationParameterControl.taxRate);

            StockPortofolio currentPortofolio = GenerateTradingSimulation(stockSerie, this.simulationParameterControl.StartDate, this.simulationParameterControl.EndDate.AddHours(18),
                this.simulationParameterControl.amount, this.simulationParameterControl.reinvest,
                this.simulationParameterControl.amendOrders, this.simulationParameterControl.supportShortSelling,
                this.simulationParameterControl.fixedFee, this.simulationParameterControl.taxRate);

            //if (generateReportCheckBox.Checked)
            //{
            //    this.simulationParameterControl.Personality = currentPersonality;
            //    this.simulationParameterControl.GenerateReportLine("TuningReport_"+stockSerie.StockName+".csv", stockSerie, currentPortofolio);
            //}
            if ((bestPortofolio == null || bestPortofolio.TotalAddedValue < currentPortofolio.TotalAddedValue) && currentPortofolio.OrderList.Count != 0)
            {
                bestPersonality = stockSerie.StockAnalysis.StockPersonality.Clone();
                //Console.WriteLine("new best" + bestPersonality.ToString());
                //Console.WriteLine("new best" + currentPortofolio.ToString());

                // Update new best portofolio
                bestPortofolio = currentPortofolio;

                // Refresh GUI
                if (refreshGUI)
                {
                    this.simulationParameterControl.Personality = bestPersonality;
                }
            }
            if (!this.allStocksCheckBox.Checked)
            {
                if (this.progressBar.Value < this.progressBar.Maximum)
                {
                    this.progressBar.Value++;
                }
                else
                {
                    this.progressBar.Value = 0;
                }
            }
        }
        private StockPortofolio GenerateTradingSimulation(StockSerie stockSerie, System.DateTime startDate, System.DateTime endDate, float amount, bool reinvest, bool amendOrders, bool supportShortSelling, float fixedFee, float taxRate)
        {
            // Manage selected Stock and portofolio
            stockPortofolioList.RemoveAll(p => p.Name == (stockSerie.StockName + "_P"));

            StockPortofolio portofolio = new StockPortofolio(stockSerie.StockName + "_P");
            portofolio.TotalDeposit = amount;
            stockPortofolioList.Add(portofolio);

            stockSerie.GenerateSimulation(SelectedStrategy, startDate, endDate, amount, reinvest,
                                    amendOrders, supportShortSelling, fixedFee, taxRate, portofolio);

            // Create Portofoglio serie
            portofolio.Initialize(stockDictionary);

            return portofolio;
        }
        private void TuneProperty(StockSerie stockSerie, FloatPropertyRange range, bool refreshGUI,
            ref StockPortofolio bestPortofolio, ref StockPersonality bestPersonality)
        {
            float mediumValue = (range.Max + range.Min) / 2.0f;
            float maxWidth = (range.Max - range.Min) / 2.0f;

            UpdateBestForValue(stockSerie, range, refreshGUI, ref bestPortofolio, ref bestPersonality, mediumValue);

            float precision = range.Step / -100.0f;
            for (float currentWidth = range.Step; (maxWidth - currentWidth) > precision; currentWidth += range.Step)
            {
                UpdateBestForValue(stockSerie, range, refreshGUI, ref bestPortofolio, ref bestPersonality, mediumValue + currentWidth);
                UpdateBestForValue(stockSerie, range, refreshGUI, ref bestPortofolio, ref bestPersonality, mediumValue - currentWidth);
            }
        }
        private void TuneSarexParams(StockSerie stockSerie, List<FloatPropertyRange> propertyRangeList,
            ref StockPortofolio bestPortofolio, ref StockPersonality bestPersonality)
        {
            try
            {
                int nbIterations = 1;
                if (this.allStocksCheckBox.Checked)
                {
                    nbIterations = this.stockComboBox.Items.Count;
                }
                else
                {
                    foreach (FloatPropertyRange propRange in propertyRangeList)
                    {
                        nbIterations *= propRange.NbStep();
                    }
                }
                this.progressBar.Maximum = nbIterations;
                this.progressBar.Value = 0;

                TuneIndicatorList(stockSerie, propertyRangeList, true, ref bestPortofolio, ref bestPersonality);

            }
            catch (Exception exception)
            {
                System.Windows.Forms.MessageBox.Show(exception.Message, "Check input parameters");
            }
        }
Ejemplo n.º 16
0
        private void bestReturnStrategySimulationMenuItem_Click(object sender, EventArgs e)
        {
            int maxPositions = 2;
            float maxPositionValue = 10000f;

            string portofolioName = "BestReturn";

            float portofolioValue = 10000;
            float cashValue = portofolioValue;

            #region CreatePortofolio

            // Create new simulation portofolio
            if (CurrentPortofolio == null)
            {
                CurrentPortofolio = this.StockPortofolioList.Find(p => p.Name == portofolioName);
                if (CurrentPortofolio == null)
                {
                    CurrentPortofolio = new StockPortofolio(portofolioName);
                    CurrentPortofolio.IsSimulation = true;
                    CurrentPortofolio.TotalDeposit = portofolioValue;
                    this.StockPortofolioList.Add(CurrentPortofolio);
                }
            }

            #endregion

            StockSerie referenceSerie = this.StockDictionary["CAC40"];
            referenceSerie.Initialise();
            referenceSerie.BarDuration = StockSerie.StockBarDuration.Monthly;
            List<StockSerie> stockSeries =
               this.StockDictionary.Values.Where(s => s.BelongsToGroup(StockSerie.Groups.CAC40) && s.Initialise()).ToList();

            // Switch to monthly values
            foreach (StockSerie serie in stockSeries)
            {
                serie.BarDuration = StockSerie.StockBarDuration.Monthly;
            }

            DateTime startDate = referenceSerie.Keys.First();
            List<StockDailyValue> values = new List<StockDailyValue>();
            List<Position> portofolio = new List<Position>();

            DateTime lastDate = referenceSerie.Keys.Last();
            foreach (DateTime date in referenceSerie.Keys)
            {
                StockLog.Write(date.ToShortDateString());

                values.Clear();

                // Find matching values
                foreach (StockSerie serie in stockSeries)
                {
                    int index = serie.IndexOf(date);
                    if (index > 0)
                    {
                        values.Add(serie[date]);
                    }
                }

                // Select positives + order by return
                List<StockDailyValue> selectedValues =
                   values.Where(s => s.VARIATION > 0).OrderByDescending(s => s.VARIATION).ToList();

                // Close not listed names.
                foreach (Position pos in portofolio.Where(p => float.IsNaN(p.Close)))
                {
                    if (!selectedValues.Any(s => s.NAME == pos.Name))
                    {
                        cashValue += pos.EndPosition(stockSeries.First(s => s.StockName == pos.Name)[date].OPEN);
                        portofolioValue += pos.Gain;

                        StockLog.Write("Selling: " + pos.ToString() + " gain: " + pos.Gain.ToString());
                    }
                    else
                    {
                        selectedValues.RemoveAll(s => s.NAME == pos.Name);
                    }
                }

                // Open new positions
                int openPositionsCount = portofolio.Count(p => p.IsOpened);
                int candidateCount = selectedValues.Count();

                int nbPositionsToOpen = maxPositions - openPositionsCount;

                float consumedCash = 0;
                for (int i = 0; i < nbPositionsToOpen && i < candidateCount; i++)
                {
                    StockDailyValue value = selectedValues[i];
                    int size = (int)((Math.Min(cashValue / nbPositionsToOpen, maxPositionValue)) / value.CLOSE);
                    Position pos = new Position(value.NAME, value.CLOSE, size);
                    portofolio.Add(pos);
                    consumedCash = value.CLOSE * size;

                    StockLog.Write("Buying: " + pos.ToString() + " at: " + pos.Open.ToString());
                }
                cashValue -= consumedCash;

                if (date == lastDate)
                {
                    foreach (Position pos in portofolio.Where(p => p.IsOpened))
                    {
                        cashValue += pos.EndPosition(stockSeries.First(s => s.StockName == pos.Name)[date].CLOSE);
                        portofolioValue += pos.Gain;

                        StockLog.Write("Selling: " + pos.ToString() + " gain: " + pos.Gain.ToString());
                    }
                }

                // Display Open Positions
                StockLog.Write("Portofolio Value =" + portofolioValue);
                //foreach (Variation pos in portofolio.Where(p => p.IsOpened))
                //{
                //    StockLog.Write(pos.ToString());
                //}
            }
            StockLog.Write("Cash Value: " + cashValue);
        }
Ejemplo n.º 17
0
        private void RefreshPortofolioMenu()
        {
            // Create default portofolio if not exist
            if (this.StockPortofolioList.Count == 0)
            {
                StockPortofolio portofolio = new StockPortofolio("Default_P");
                portofolio.TotalDeposit = 10000;

                this.StockPortofolioList.Add(portofolio);
            }

            // Clean existing menus
            this.portofolioDetailsMenuItem.DropDownItems.Clear();
            this.orderListMenuItem.DropDownItems.Clear();
            this.portofolioFilterMenuItem.DropDownItems.Clear();

            System.Windows.Forms.ToolStripItem[] portofolioMenuItems =
               new System.Windows.Forms.ToolStripItem[this.StockPortofolioList.Count];
            System.Windows.Forms.ToolStripItem[] portofolioFilterMenuItems =
               new System.Windows.Forms.ToolStripItem[this.StockPortofolioList.Count];
            System.Windows.Forms.ToolStripItem[] orderListMenuItems =
               new System.Windows.Forms.ToolStripItem[this.StockPortofolioList.Count];
            ToolStripMenuItem portofolioDetailsSubMenuItem;
            ToolStripMenuItem portofolioFilterSubMenuItem;
            ToolStripMenuItem orderListSubMenuItem;

            int i = 0;
            foreach (StockPortofolio portofolio in this.StockPortofolioList)
            {
                // Create portofoglio menu items
                portofolioDetailsSubMenuItem = new ToolStripMenuItem(portofolio.Name);
                portofolioDetailsSubMenuItem.Click += new EventHandler(this.viewPortogolioMenuItem_Click);
                portofolioMenuItems[i] = portofolioDetailsSubMenuItem;

                // Create portofoglio menu items
                portofolioFilterSubMenuItem = new ToolStripMenuItem(portofolio.Name);
                portofolioFilterSubMenuItem.CheckOnClick = true;
                portofolioFilterSubMenuItem.Click += new EventHandler(portofolioFilterSubMenuItem_Click);
                portofolioFilterMenuItems[i] = portofolioFilterSubMenuItem;

                // create order list menu items
                orderListSubMenuItem = new ToolStripMenuItem(portofolio.Name);
                orderListSubMenuItem.Click += new EventHandler(this.orderListMenuItem_Click);
                orderListMenuItems[i++] = orderListSubMenuItem;
            }
            this.portofolioDetailsMenuItem.DropDownItems.AddRange(portofolioMenuItems);
            this.orderListMenuItem.DropDownItems.AddRange(orderListMenuItems);
            this.portofolioFilterMenuItem.DropDownItems.AddRange(portofolioFilterMenuItems);
        }
Ejemplo n.º 18
0
        private void simulationTuningDlg_SimulationCompleted(StockPortofolio newPortofolio)
        {
            // Refresh portofolio generated stock
            OnCurrentPortofolioChanged(newPortofolio, true);

            StockDictionary.CreatePortofolioSerie(CurrentPortofolio);

            // Refresh the screen
            OnNeedReinitialise(true);

            //Display portofolio window
            if (portofolioDlg == null)
            {
                portofolioDlg = new PortofolioDlg(StockDictionary, CurrentPortofolio);
                portofolioDlg.SelectedStockChanged += new SelectedStockChangedEventHandler(OnSelectedStockChanged);
                portofolioDlg.FormClosing += new FormClosingEventHandler(portofolioDlg_FormClosing);
                portofolioDlg.Show();
            }
            else
            {
                portofolioDlg.SetPortofolio(CurrentPortofolio);
                portofolioDlg.Activate();
                portofolioDlg.Refresh();
            }

            RefreshPortofolioMenu();
        }
        private void selectButton_Click(object sender, EventArgs e)
        {
            Cursor cursor = Cursor;
             Cursor = Cursors.WaitCursor;

             var stockInGroupList = stockDictionary.Values.Where(s => s.BelongsToGroup(groupComboBox.SelectedItem.ToString()) && !s.IsPortofolioSerie);
             try
             {
            selectedStockListBox.Items.Clear();
            selectedStockListBox.Refresh();

            if (progressBar != null)
            {
               progressBar.Minimum = 0;
               progressBar.Maximum = stockInGroupList.Count();
               progressBar.Value = 0;
            }

            foreach (StockSerie stockSerie in stockInGroupList)
            {
               bool selected = false;

               progressLabel.Text = stockSerie.StockName;
               progressLabel.Refresh();

               if (this.refreshDataCheckBox.Checked)
               {
                  stockSerie.IsInitialised = false;
                  StockDataProviderBase.DownloadSerieData(Settings.Default.RootFolder, stockSerie);
               }

               if (!stockSerie.Initialise()) { continue; }

               stockSerie.BarDuration = barDuration;

               int lastIndex = stockSerie.LastCompleteIndex;
               int firstIndex = lastIndex + 1 - (int)periodComboBox.SelectedItem;

               // Perform Strategy calculation
               // Create new simulation portofolio

               StockPortofolio currentPortofolio = new StockPortofolio(stockSerie.StockName + "_P");
               currentPortofolio.IsSimulation = true;
               currentPortofolio.TotalDeposit = 10000;

               if (!string.IsNullOrWhiteSpace(this.strategyComboBox.SelectedItem.ToString()))
               {
                  var selectedStrategy = StrategyManager.CreateStrategy(this.strategyComboBox.SelectedItem.ToString(), stockSerie,
                      null, true);

                  if (selectedStrategy != null)
                  {
                     float amount = stockSerie.GetMax(StockDataType.CLOSE) * 100f;

                     currentPortofolio.TotalDeposit = amount;
                     currentPortofolio.Clear();

                     stockSerie.GenerateSimulation(selectedStrategy, Settings.Default.StrategyStartDate,
                        stockSerie.Keys.Last(), amount, false, false, Settings.Default.SupportShortSelling,
                        false, 0.0f, false, 0.0f, 0.0f, 0.0f, currentPortofolio);

                     // Check if orders happened during the time frame
                     for (int i = firstIndex; i < lastIndex; i++)
                     {
                        if (currentPortofolio.OrderList.Any(o => o.ExecutionDate == stockSerie.Keys.ElementAt(i)))
                        {
                           selected = true;
                           break;
                        }
                     }
                  }
               }

               if (selected)
               {
                  selectedStockListBox.Items.Add(stockSerie.StockName);
                  selectedStockListBox.Refresh();
               }
            }
            if (progressBar != null)
            {
               progressBar.Value++;
            }
             }
             catch (Exception exception)
             {
            MessageBox.Show(exception.Message, "Script Error !!!");
             }
             finally
             {
            if (progressBar != null)
            {
               progressBar.Value = 0;
               progressLabel.Text = selectedStockListBox.Items.Count + "/" + stockInGroupList.Count();
            }
             }
             Cursor = cursor;
        }
        private StockPortofolio GenerateSimulation(StockSerie stockSerie)
        {
            stockSerie.Initialise();

             // Manage selected Stock and portofolio
             StockPortofolio portofolio = new StockPortofolio(stockSerie.StockName + "_P");
             portofolio.TotalDeposit = this.simulationParameterControl.amount;
             stockPortofolioList.Add(portofolio);

             this.SelectedStrategy = StrategyManager.CreateStrategy(this.simulationParameterControl.SelectedStrategyName, stockSerie, null, simulationParameterControl.supportShortSelling);

             // intialise the serie
             stockSerie.Initialise();

             StockOrder lastOrder = stockSerie.GenerateSimulation(SelectedStrategy, this.simulationParameterControl.StartDate, this.simulationParameterControl.EndDate.AddHours(18), this.simulationParameterControl.amount, this.simulationParameterControl.reinvest,
             this.simulationParameterControl.amendOrders, this.simulationParameterControl.supportShortSelling,
             this.simulationParameterControl.takeProfit, this.simulationParameterControl.profitRate,
             this.simulationParameterControl.stopLoss, this.simulationParameterControl.stopLossRate,
             this.simulationParameterControl.fixedFee, this.simulationParameterControl.taxRate, portofolio);

             // Do a bit of cleanup
             if (lastOrder != null && this.simulationParameterControl.removePendingOrders)
             {
            if (lastOrder.IsBuyOrder())
            {
               lastOrder = null;
            }
            else
            {
               if (lastOrder.State != StockOrder.OrderStatus.Executed)
               {
                  portofolio.OrderList.Remove(portofolio.OrderList.Last());
                  lastOrder = null;
               }
            }
             }

             // Display pending order
             if (this.simulationParameterControl.displayPendingOrders && lastOrder != null && lastOrder.State == StockOrder.OrderStatus.Pending)
             {
            if (SelectedStockChanged != null)
            {
               SelectedStockChanged(lastOrder.StockName, true);
            }
            OrderEditionDlg orderEditionDlg = new OrderEditionDlg(lastOrder);
            orderEditionDlg.StartPosition = FormStartPosition.Manual;
            orderEditionDlg.Location = new Point(0, 0);
            orderEditionDlg.ShowDialog();
             }

             // Create Portofoglio serie
             portofolio.Initialize(stockDictionary);
             if (stockDictionary.Keys.Contains(portofolio.Name))
             {
            stockDictionary.Remove(portofolio.Name);
             }
             stockDictionary.Add(portofolio.Name, portofolio.GeneratePortfolioStockSerie(portofolio.Name, stockSerie, stockSerie.StockGroup));

             // Generate report
             if (this.generateReportCheckBox.Checked)
             {
            this.simulationParameterControl.GenerateReportLine("BatchReport_" + SelectedStrategy + ".csv", stockSerie, portofolio);
             }

             return portofolio;
        }
        private void TuneIndicatorList(StockSerie stockSerie, List<FloatPropertyRange> rangeList,
            bool refreshGUI, ref StockPortofolio bestPortofolio, ref StockPersonality bestPersonality)
        {
            int rangeCount = rangeList.Count;
            if (rangeCount == 0)
            {
                return;
            }

            if (rangeCount == 1)
            {
                TuneProperty(stockSerie, rangeList[0], refreshGUI, ref bestPortofolio, ref bestPersonality);
            }
            else
            {
                FloatPropertyRange range = rangeList[0];
                List<FloatPropertyRange> subList = rangeList.GetRange(1, rangeCount - 1);

                float mediumValue = (range.Max + range.Min) / 2.0f;
                float maxWidth = (range.Max - range.Min) / 2.0f;

                stockSerie.StockAnalysis.StockPersonality.SetFloatPropertyValue(range, mediumValue);
                TuneIndicatorList(stockSerie, subList, refreshGUI, ref bestPortofolio, ref bestPersonality);

                float precision = range.Step / -100.0f;
                for (float currentWidth = range.Step; (maxWidth - currentWidth) > precision; currentWidth += range.Step)
                {
                    stockSerie.StockAnalysis.StockPersonality.SetFloatPropertyValue(range, mediumValue + currentWidth);
                    TuneIndicatorList(stockSerie, subList, refreshGUI, ref bestPortofolio, ref bestPersonality);

                    stockSerie.StockAnalysis.StockPersonality.SetFloatPropertyValue(range, mediumValue - currentWidth);
                    TuneIndicatorList(stockSerie, subList, refreshGUI, ref bestPortofolio, ref bestPersonality);
                }
            }
        }
Ejemplo n.º 22
0
        private void ApplyTheme()
        {
            using (MethodLogger ml = new MethodLogger(this))
            {
                try
                {
                    if (this.CurrentTheme == null || this.CurrentStockSerie == null) return;
                    if (!this.CurrentStockSerie.IsInitialised)
                    {
                        this.statusLabel.Text = ("Loading data...");
                        this.Refresh();
                    }
                    if (!this.CurrentStockSerie.Initialise() || this.CurrentStockSerie.Count == 0)
                    {
                        this.DeactivateGraphControls("Data for " + this.CurrentStockSerie.StockName +
                                                     " cannot be initialised");
                        return;
                    }
                    if (this.CurrentStockSerie.StockAnalysis.DeleteTransientDrawings() > 0)
                    {
                        this.CurrentStockSerie.PaintBarCache = null;
                    }

                    // Build curve list from definition
                    if (!this.themeDictionary.ContainsKey(currentTheme))
                    {
                        // LoadTheme
                        LoadCurveTheme(currentTheme);
                    }

                    // Force resetting the secondary serie.
                    if (themeDictionary[currentTheme]["CloseGraph"].FindIndex(s => s.StartsWith("SECONDARY")) == -1)
                    {
                        if (this.graphCloseControl.SecondaryFloatSerie != null)
                        {
                            themeDictionary[currentTheme]["CloseGraph"].Add("SECONDARY|" +
                                                                            this.graphCloseControl.SecondaryFloatSerie
                                                                                .Name);
                        }
                        else
                        {
                            themeDictionary[currentTheme]["CloseGraph"].Add("SECONDARY|NONE");
                        }
                    }

                    DateTime[] dateSerie = CurrentStockSerie.Keys.ToArray();
                    GraphCurveTypeList curveList;
                    bool skipEntry = false;
                    foreach (string entry in themeDictionary[currentTheme].Keys)
                    {
                        if (entry.ToUpper().EndsWith("GRAPH"))
                        {
                            GraphControl graphControl = null;
                            curveList = new GraphCurveTypeList();
                            switch (entry.ToUpper())
                            {
                                case "CLOSEGRAPH":
                                    graphControl = this.graphCloseControl;
                                    this.graphCloseControl.ShowVariation = Settings.Default.ShowVariation;
                                    this.graphCloseControl.Comments = this.CurrentStockSerie.StockAnalysis.Comments;
                                    break;
                                case "SCROLLGRAPH":
                                    graphControl = this.graphScrollerControl;
                                    break;
                                case "INDICATOR1GRAPH":
                                    graphControl = this.graphIndicator1Control;
                                    break;
                                case "INDICATOR2GRAPH":
                                    graphControl = this.graphIndicator2Control;
                                    break;
                                case "INDICATOR3GRAPH":
                                    graphControl = this.graphIndicator3Control;
                                    break;
                                case "VOLUMEGRAPH":
                                    if (this.CurrentStockSerie.HasVolume)
                                    {
                                        graphControl = this.graphVolumeControl;
                                        curveList.Add(new GraphCurveType(
                                            CurrentStockSerie.GetSerie(StockDataType.VOLUME),
                                            Pens.Green, true));
                                    }
                                    else
                                    {
                                        this.graphVolumeControl.Deactivate("This serie has no volume data", false);
                                        skipEntry = true;
                                    }
                                    break;
                                default:
                                    continue;
                            }

                            if (skipEntry)
                            {
                                skipEntry = false;
                                continue;
                            }
                            try
                            {
                                List<HLine> horizontalLines = new List<HLine>();

                                foreach (string line in this.themeDictionary[currentTheme][entry])
                                {
                                    string[] fields = line.Split('|');
                                    switch (fields[0].ToUpper())
                                    {
                                        case "GRAPH":
                                            string[] colorItem = fields[1].Split(':');
                                            graphControl.BackgroundColor = Color.FromArgb(int.Parse(colorItem[0]),
                                                int.Parse(colorItem[1]), int.Parse(colorItem[2]), int.Parse(colorItem[3]));
                                            colorItem = fields[2].Split(':');
                                            graphControl.TextBackgroundColor = Color.FromArgb(int.Parse(colorItem[0]),
                                                int.Parse(colorItem[1]), int.Parse(colorItem[2]), int.Parse(colorItem[3]));
                                            graphControl.ShowGrid = bool.Parse(fields[3]);
                                            colorItem = fields[4].Split(':');
                                            graphControl.GridColor = Color.FromArgb(int.Parse(colorItem[0]),
                                                int.Parse(colorItem[1]), int.Parse(colorItem[2]), int.Parse(colorItem[3]));
                                            graphControl.ChartMode =
                                                (GraphChartMode)Enum.Parse(typeof(GraphChartMode), fields[5]);
                                            if (entry.ToUpper() == "CLOSEGRAPH")
                                            {
                                                if (fields.Length >= 7)
                                                {
                                                    this.graphCloseControl.SecondaryPen =
                                                        GraphCurveType.PenFromString(fields[6]);
                                                }
                                                else
                                                {
                                                    this.graphCloseControl.SecondaryPen = new Pen(Color.DarkGoldenrod, 1);
                                                }
                                            }
                                            break;
                                        case "SECONDARY":
                                            if (this.currentStockSerie.SecondarySerie != null)
                                            {
                                                CheckSecondarySerieMenu(fields[1]);
                                                this.graphCloseControl.SecondaryFloatSerie =
                                                    this.CurrentStockSerie.GenerateSecondarySerieFromOtherSerie(
                                                        this.currentStockSerie.SecondarySerie, StockDataType.CLOSE);
                                            }
                                            else
                                            {
                                                if (fields[1].ToUpper() == "NONE" ||
                                                    !this.StockDictionary.ContainsKey(fields[1]))
                                                {
                                                    ClearSecondarySerieMenu();
                                                    this.graphCloseControl.SecondaryFloatSerie = null;
                                                }
                                                else
                                                {
                                                    if (this.StockDictionary.ContainsKey(fields[1]))
                                                    {
                                                        CheckSecondarySerieMenu(fields[1]);
                                                        this.graphCloseControl.SecondaryFloatSerie =
                                                            this.CurrentStockSerie.GenerateSecondarySerieFromOtherSerie(
                                                                this.StockDictionary[fields[1]], StockDataType.CLOSE);
                                                    }
                                                }
                                            }
                                            break;
                                        case "DATA":
                                            curveList.Add(
                                                new GraphCurveType(
                                                    CurrentStockSerie.GetSerie(
                                                        (StockDataType)Enum.Parse(typeof(StockDataType), fields[1])),
                                             fields[2], bool.Parse(fields[3])));
                                            break;
                                        case "TRAIL":
                                        case "INDICATOR":
                                            {
                                                IStockIndicator stockIndicator =
                                                    (IStockIndicator)
                                                        StockViewableItemsManager.GetViewableItem(line,
                                                            this.CurrentStockSerie);
                                                if (stockIndicator != null)
                                                {
                                                    if (entry.ToUpper() != "CLOSEGRAPH")
                                                    {
                                                        if (stockIndicator.DisplayTarget ==
                                                            IndicatorDisplayTarget.RangedIndicator)
                                                        {
                                                            IRange range = (IRange)stockIndicator;
                                                            ((GraphRangedControl)graphControl).RangeMin = range.Min;
                                                            ((GraphRangedControl)graphControl).RangeMax = range.Max;
                                                        }
                                                        else
                                                        {
                                                            ((GraphRangedControl)graphControl).RangeMin = float.NaN;
                                                            ((GraphRangedControl)graphControl).RangeMax = float.NaN;
                                                        }
                                                    }
                                                    if (
                                                        !(stockIndicator.RequiresVolumeData &&
                                                          !this.CurrentStockSerie.HasVolume))
                                                    {
                                                        curveList.Indicators.Add(stockIndicator);
                                                    }
                                                }
                                            }
                                            break;
                                        case "PAINTBAR":
                                            {
                                                IStockPaintBar paintBar =
                                                    (IStockPaintBar)
                                                        StockViewableItemsManager.GetViewableItem(line,
                                                            this.CurrentStockSerie);
                                                curveList.PaintBar = paintBar;
                                            }
                                            break;
                                        case "DECORATOR":
                                            {
                                                IStockDecorator decorator =
                                                    (IStockDecorator)
                                                        StockViewableItemsManager.GetViewableItem(line,
                                                            this.CurrentStockSerie);
                                                curveList.Decorator = decorator;
                                                this.GraphCloseControl.CurveList.ShowMes.Add(decorator);
                                            }
                                            break;
                                        case "TRAILSTOP":
                                            {
                                                IStockTrailStop trailStop =
                                                    (IStockTrailStop)
                                                        StockViewableItemsManager.GetViewableItem(line,
                                                            this.CurrentStockSerie);
                                                curveList.TrailStop = trailStop;
                                            }
                                            break;
                                        case "LINE":
                                            horizontalLines.Add(new HLine(float.Parse(fields[1]),
                                                GraphCurveType.PenFromString(fields[2])));
                                            break;
                                        default:
                                            continue;
                                    }
                                }
                                if (curveList.FindIndex(c => c.DataSerie.Name == "CLOSE") < 0)
                                {
                                    curveList.Insert(0,
                                        new GraphCurveType(CurrentStockSerie.GetSerie(StockDataType.CLOSE), Pens.Black,
                                            false));
                                }
                                if (graphControl == this.graphCloseControl)
                                {
                                    if (curveList.FindIndex(c => c.DataSerie.Name == "LOW") < 0)
                                    {
                                        curveList.Insert(0,
                                            new GraphCurveType(CurrentStockSerie.GetSerie(StockDataType.LOW), Pens.Black,
                                                false));
                                    }
                                    if (curveList.FindIndex(c => c.DataSerie.Name == "HIGH") < 0)
                                    {
                                        curveList.Insert(0,
                                            new GraphCurveType(CurrentStockSerie.GetSerie(StockDataType.HIGH), Pens.Black,
                                                false));
                                    }
                                    if (curveList.FindIndex(c => c.DataSerie.Name == "OPEN") < 0)
                                    {
                                        curveList.Insert(0,
                                            new GraphCurveType(CurrentStockSerie.GetSerie(StockDataType.OPEN), Pens.Black,
                                                false));
                                    }
                                }
                                if (
                                    !this.CurrentStockSerie.StockAnalysis.DrawingItems.ContainsKey(
                                        this.CurrentStockSerie.BarDuration))
                                {
                                    this.CurrentStockSerie.StockAnalysis.DrawingItems.Add(
                                        this.CurrentStockSerie.BarDuration, new StockDrawingItems());
                                }
                                graphControl.Initialize(curveList, horizontalLines, dateSerie,
                                    CurrentStockSerie.StockName,
                                    CurrentStockSerie.StockAnalysis.DrawingItems[this.CurrentStockSerie.BarDuration],
                                    startIndex, endIndex);
                            }
                            catch (System.Exception e)
                            {
                                StockLog.Write("Exception londing theme: " + this.currentTheme);
                                foreach (string line in this.themeDictionary[currentTheme][entry])
                                {
                                    StockLog.Write(line);
                                }
                                StockLog.Write(e);
                            }
                        }
                    }

                    // Apply Strategy

                    // Create new simulation portofolio
                    if (this.currentStockSerie.BelongsToGroup(StockSerie.Groups.BREADTH) ||
                        this.currentStockSerie.BelongsToGroup(StockSerie.Groups.COT) ||
                        this.currentStockSerie.BelongsToGroup(StockSerie.Groups.INDICATOR) ||
                        this.currentStockSerie.BelongsToGroup(StockSerie.Groups.NONE))
                    {
                        this.CurrentPortofolio = null;

                        if (this.currentStockSerie.BelongsToGroup(StockSerie.Groups.BREADTH) && this.currentStockSerie.DataProvider != StockDataProvider.FINRA)
                        {
                            string[] fields = this.currentStockSerie.StockName.Split('.');
                            this.graphCloseControl.SecondaryFloatSerie =
                                this.CurrentStockSerie.GenerateSecondarySerieFromOtherSerie(
                                    this.StockDictionary[fields[1]], StockDataType.CLOSE);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(this.currentStrategy))
                        {
                            CurrentPortofolio =
                                this.StockPortofolioList.Find(p => p.Name == this.currentStockSerie.StockName + "_P");
                            if (CurrentPortofolio == null)
                            {
                                CurrentPortofolio = new StockPortofolio(this.currentStockSerie.StockName + "_P");
                                CurrentPortofolio.IsSimulation = true;
                                CurrentPortofolio.TotalDeposit = 1000;
                                this.StockPortofolioList.Add(CurrentPortofolio);

                                this.RefreshPortofolioMenu();
                            }

                            var selectedStrategy = StrategyManager.CreateStrategy(this.currentStrategy,
                                this.currentStockSerie,
                                null, true);
                            if (selectedStrategy != null)
                            {
                                float amount = this.currentStockSerie.GetMax(StockDataType.CLOSE) * 100f;

                                CurrentPortofolio.TotalDeposit = amount;
                                CurrentPortofolio.Clear();

                                this.currentStockSerie.GenerateSimulation(selectedStrategy,
                                    Settings.Default.StrategyStartDate, this.currentStockSerie.Keys.Last(),
                                    amount, false,
                                    false, Settings.Default.SupportShortSelling, false, 0.0f, false, 0.0f, 0.0f, 0.0f, CurrentPortofolio);
                            }

                            this.graphCloseControl.Portofolio = CurrentPortofolio;

                            if (portofolioDlg != null)
                            {
                                this.CurrentPortofolio.Initialize(this.StockDictionary);
                                portofolioDlg.SetPortofolio(this.CurrentPortofolio);
                                portofolioDlg.Activate();
                            }
                        }
                    }

                    // Reinitialise drawing
                    ResetZoom();
                    this.Cursor = Cursors.Arrow;
                }

                catch (Exception ex)
                {
                    StockAnalyzerException.MessageBox(ex);
                }
            }
        }