/// <summary>
        ///     Calculates the strategy indicators and returns the first meaningful bar number.
        /// </summary>
        /// <returns>First bar</returns>
        public int Calculate()
        {
            FirstBar = 0;
            foreach (IndicatorSlot slot in Slot)
            {
                string    sndicatorName = slot.IndicatorName;
                SlotTypes slotType      = slot.SlotType;
                Indicator indicator     = IndicatorManager.ConstructIndicator(sndicatorName);
                indicator.Initialize(slotType);

                indicator.IndParam = slot.IndParam;
                indicator.Calculate(new DataSet());

                slot.IndicatorName  = indicator.IndicatorName;
                slot.IndParam       = indicator.IndParam;
                slot.Component      = indicator.Component;
                slot.SeparatedChart = indicator.SeparatedChart;
                slot.SpecValue      = indicator.SpecialValues;
                slot.MinValue       = indicator.SeparatedChartMinValue;
                slot.MaxValue       = indicator.SeparatedChartMaxValue;
                slot.IsDefined      = true;

                foreach (IndicatorComp comp in slot.Component)
                {
                    if (comp.FirstBar > FirstBar)
                    {
                        FirstBar = comp.FirstBar;
                    }
                }
            }

            return(FirstBar);
        }
Exemple #2
0
        /// <summary>
        /// Calculates an indicator and returns OK status.
        /// </summary>
        bool CalculateIndicator(SlotTypes slotType, Indicator indicator)
        {
            bool okStatus;

            try
            {
                indicator.Calculate(slotType);
                okStatus = true;
            }
            catch (Exception excaption)
            {
                string message = "Please report this error in the support forum!";
                if (indicator.CustomIndicator)
                {
                    message = "Please report this error to the author of the indicator!<br />" +
                              "You may remove this indicator from the Custom Indicators folder.";
                }

                string text =
                    "<h1>Error: " + excaption.Message + "</h1>" +
                    "<p>" +
                    "Slot type: <strong>" + slotType.ToString() + "</strong><br />" +
                    "Indicator: <strong>" + indicator.ToString() + "</strong>" +
                    "</p>" +
                    "<p>" +
                    message +
                    "</p>";

                string caption = "Indicator Calculation Error";
                ReportIndicatorError(text, caption);
                indicatorBlackList.Add(indicator.IndicatorName);
                okStatus = false;
            }
            return(okStatus);
        }
Exemple #3
0
        private void CalculateStrategy()
        {
            foreach (IndicatorSlot indSlot in Data.Strategy.Slot)
            {
                string    indicatorName = indSlot.IndicatorName;
                SlotTypes slotType      = indSlot.SlotType;
                Indicator indicator     = IndicatorManager.ConstructIndicator(indicatorName);
                indicator.Initialize(slotType);
                indicator.IndParam = indSlot.IndParam;
                indicator.Calculate(Data.DataSet);

                indSlot.IndicatorName  = indicator.IndicatorName;
                indSlot.IndParam       = indicator.IndParam;
                indSlot.Component      = indicator.Component;
                indSlot.SeparatedChart = indicator.SeparatedChart;
                indSlot.SpecValue      = indicator.SpecialValues;
                indSlot.MinValue       = indicator.SeparatedChartMinValue;
                indSlot.MaxValue       = indicator.SeparatedChartMaxValue;
                indSlot.IsDefined      = true;
            }

            Data.FirstBar = Data.Strategy.SetFirstBar();
            Backtester.Calculate();
            Backtester.CalculateAccountStats();
            Data.IsResult = true;
            StatsBuffer.UpdateStatsBuffer();
        }
 private void CalculateIndicators()
 {
     if (!IsHeatMap && _recalc)
     {
         lock (_series)
         {
             List <Indicator> toBeRemoved = new List <Indicator>();
             for (int i = 0; i < _series.Count; i++)
             {
                 Indicator indicator = _series[i] as Indicator;
                 if (indicator == null || indicator._indicatorType == IndicatorType.Unknown)
                 {
                     continue;
                 }
                 if (indicator._recycleFlag)
                 {
                     toBeRemoved.Add(indicator);
                     continue;
                 }
                 _chartX._updatingIndicator = true;
                 indicator.Calculate();
                 if (!indicator._calculateResult)
                 {
                     toBeRemoved.Add(indicator);
                 }
             }
             foreach (Indicator indicator in toBeRemoved)
             {
                 _chartX.FireSeriesRemoved(indicator.FullName);
                 RemoveSeries(indicator, true);
             }
         }
     }
 }
Exemple #5
0
        private IndicatorResult EvaluateIndicator(StockHandle stock, DateTime dateUnderAnalysis)
        {
            var context = CreateIndicatorContext(dateUnderAnalysis);

            context.Stock = stock;

            return(Indicator.Calculate(context));
        }
Exemple #6
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Excel         ex    = new Excel();
                List <Candle> input = ex.ReadFile(openFileDialog.FileName);
                Drawer        dr    = new Drawer(input, Graph_image.DesiredSize.Width, Graph_image.DesiredSize.Height);
                Indicator     ind   = new Indicator(input, Graph_image.DesiredSize.Width, Graph_image.DesiredSize.Height);
                Graph_image.Source    = Converter.ToBitmapImage(dr.DrawOne(150));
                IndicatorImage.Source = Converter.ToBitmapImage(ind.Calculate());
            }
        }
Exemple #7
0
        /// <summary>
        /// Calculates the indicator in the designated slot.
        /// </summary>
        void CalculateIndicator(int slot)
        {
            IndicatorParam ip = Data.Strategy.Slot[slot].IndParam;

            Indicator indicator = Indicator_Store.ConstructIndicator(ip.IndicatorName, ip.SlotType);

            // List parameters
            for (int i = 0; i < 5; i++)
            {
                indicator.IndParam.ListParam[i].Index   = ip.ListParam[i].Index;
                indicator.IndParam.ListParam[i].Text    = ip.ListParam[i].Text;
                indicator.IndParam.ListParam[i].Enabled = ip.ListParam[i].Enabled;
            }

            // Numeric parameters
            for (int i = 0; i < 6; i++)
            {
                indicator.IndParam.NumParam[i].Value   = ip.NumParam[i].Value;
                indicator.IndParam.NumParam[i].Enabled = ip.NumParam[i].Enabled;
            }

            // Check parameters
            for (int i = 0; i < 2; i++)
            {
                indicator.IndParam.CheckParam[i].Checked = ip.CheckParam[i].Checked;
                indicator.IndParam.CheckParam[i].Enabled = ip.CheckParam[i].Enabled;
            }

            indicator.Calculate(ip.SlotType);

            // Sets Data.Strategy
            Data.Strategy.Slot[slot].IndicatorName  = indicator.IndicatorName;
            Data.Strategy.Slot[slot].IndParam       = indicator.IndParam;
            Data.Strategy.Slot[slot].Component      = indicator.Component;
            Data.Strategy.Slot[slot].SeparatedChart = indicator.SeparatedChart;
            Data.Strategy.Slot[slot].SpecValue      = indicator.SpecialValues;
            Data.Strategy.Slot[slot].MinValue       = indicator.SeparatedChartMinValue;
            Data.Strategy.Slot[slot].MaxValue       = indicator.SeparatedChartMaxValue;
            Data.Strategy.Slot[slot].IsDefined      = true;

            // Searches the indicators' components to determine the Data.FirstBar
            Data.FirstBar = Data.Strategy.SetFirstBar();

            return;
        }
        /// <summary>
        /// Recalculate all the indicator slots
        /// </summary>
        private void RecalculateSlots()
        {
            foreach (IndicatorSlot indSlot in Data.Strategy.Slot)
            {
                string    indicatorName = indSlot.IndicatorName;
                SlotTypes slotType      = indSlot.SlotType;
                Indicator indicator     = IndicatorStore.ConstructIndicator(indicatorName, slotType);

                indicator.IndParam = indSlot.IndParam;
                indicator.Calculate(slotType);

                indSlot.Component = indicator.Component;
                indSlot.IsDefined = true;
            }

            // Searches the indicators' components to determine the Data.FirstBar
            Data.FirstBar = Data.Strategy.SetFirstBar();
        }
        /// <summary>
        ///     Sets Use previous bar value automatically
        /// </summary>
        public bool AdjustUsePreviousBarValue()
        {
            bool isSomethingChanged = false;

            if (Data.AutoUsePrvBarValue == false)
            {
                return(false);
            }

            for (int slot = 0; slot < Slots; slot++)
            {
                isSomethingChanged = SetUsePrevBarValueCheckBox(slot) || isSomethingChanged;
            }

            // Recalculates the indicators.
            if (isSomethingChanged)
            {
                for (int slot = 0; slot < Slots; slot++)
                {
                    string    sIndicatorName = Data.Strategy.Slot[slot].IndicatorName;
                    SlotTypes slotType       = Data.Strategy.Slot[slot].SlotType;
                    Indicator indicator      = IndicatorManager.ConstructIndicator(sIndicatorName);
                    indicator.Initialize(slotType);

                    indicator.IndParam = Data.Strategy.Slot[slot].IndParam;

                    indicator.Calculate(new DataSet());

                    // Set the Data.Strategy
                    Slot[slot].IndicatorName  = indicator.IndicatorName;
                    Slot[slot].IndParam       = indicator.IndParam;
                    Slot[slot].Component      = indicator.Component;
                    Slot[slot].SeparatedChart = indicator.SeparatedChart;
                    Slot[slot].SpecValue      = indicator.SpecialValues;
                    Slot[slot].MinValue       = indicator.SeparatedChartMinValue;
                    Slot[slot].MaxValue       = indicator.SeparatedChartMaxValue;
                    Slot[slot].IsDefined      = true;
                }
            }

            return(isSomethingChanged);
        }
        /// <summary>
        ///     Calculates an indicator and returns OK status.
        /// </summary>
        private bool CalculateIndicator(SlotTypes type, Indicator indicator)
        {
            bool okStatus;

            try
            {
                indicator.Calculate(Data.DataSet);

                okStatus = true;
            }
            catch (Exception exception)
            {
                string request = "Please report this error in the support forum!";
                if (indicator.CustomIndicator)
                {
                    request = "Please report this error to the author of the indicator!<br />" +
                              "You may remove this indicator from the Custom Indicators folder.";
                }

                string text =
                    "<h1>Error: " + exception.Message + "</h1>" +
                    "<p>Slot type: <strong>" + type + "</strong><br />" +
                    "Indicator: <strong>" + indicator + "</strong></p>" +
                    "<p>" + request + "</p>";

                const string caption = "Indicator Calculation Error";
                var          msgBox  = new FancyMessageBox(text, caption)
                {
                    BoxWidth = 450, BoxHeight = 250
                };
                msgBox.Show();

                okStatus = false;
            }

            return(okStatus);
        }
        /// <summary>
        /// Calculates an indicator and returns OK status.
        /// </summary>
        private bool CalculateIndicator(SlotTypes slotType, Indicator indicator)
        {
#if !DEBUG
            try
            {
#endif
            indicator.Calculate(slotType);
            return(true);

#if !DEBUG
        }
        catch (Exception exception)
        {
            string message = "Please report this error in the support forum!";
            if (indicator.CustomIndicator)
            {
                message = "Please report this error to the author of the indicator!<br />" +
                          "You may remove this indicator from the Custom Indicators folder.";
            }

            string text =
                "<h1>Error: " + exception.Message + "</h1>" +
                "<p>" +
                "Slot type: <strong>" + slotType + "</strong><br />" +
                "Indicator: <strong>" + indicator + "</strong>" +
                "</p>" +
                "<p>" +
                message +
                "</p>";

            const string caption = "Indicator Calculation Error";
            ReportIndicatorError(text, caption);
            _indicatorBlackList.Add(indicator.IndicatorName);
            return(false);
        }
#endif
        }
        /// <summary>
        /// Calculates an indicator and returns OK status.
        /// </summary>
        bool CalculateIndicator(SlotTypes slotType, Indicator indicator)
        {
            bool okStatus;
            try
            {
                indicator.Calculate(slotType);
                okStatus = true;
            }
            catch (Exception excaption)
            {
                string message = "Please report this error in the support forum!";
                if (indicator.CustomIndicator)
                    message = "Please report this error to the author of the indicator!<br />" +
                        "You may remove this indicator from the Custom Indicators folder.";

                string text =
                    "<h1>Error: " + excaption.Message + "</h1>" +
                    "<p>" +
                        "Slot type: <strong>" + slotType.ToString()  + "</strong><br />" +
                        "Indicator: <strong>" + indicator.ToString() + "</strong>" +
                    "</p>" +
                    "<p>" +
                        message +
                    "</p>";

                string caption = "Indicator Calculation Error";
                ReportIndicatorError(text, caption);
                indicatorBlackList.Add(indicator.IndicatorName);
                okStatus = false;
            }
            return okStatus;
        }
        /// <summary>
        /// Calculates an indicator and returns OK status.
        /// </summary>
        private bool CalculateIndicator(SlotTypes slotType, Indicator indicator)
        {
            #if !DEBUG
            try
            {
            #endif
                indicator.Calculate(slotType);
                return true;
            #if !DEBUG
            }
            catch (Exception exception)
            {
                string message = "Please report this error in the support forum!";
                if (indicator.CustomIndicator)
                    message = "Please report this error to the author of the indicator!<br />" +
                        "You may remove this indicator from the Custom Indicators folder.";

                string text =
                    "<h1>Error: " + exception.Message + "</h1>" +
                    "<p>" +
                        "Slot type: <strong>" + slotType  + "</strong><br />" +
                        "Indicator: <strong>" + indicator + "</strong>" +
                    "</p>" +
                    "<p>" +
                        message +
                    "</p>";

                const string caption = "Indicator Calculation Error";
                ReportIndicatorError(text, caption);
                _indicatorBlackList.Add(indicator.IndicatorName);
                return false;
            }
            #endif
        }
        /// <summary>
        ///     Calculates the selected indicator chart.
        /// </summary>
        private void CalculateIndicator()
        {
            if (!Data.IsData || !isPaintAllowed)
            {
                return;
            }

            SetOppositeSignalBehaviour();
            SetClosingLogicConditions();

            Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);

            indicator.Initialize(SlotType);

            // List params
            for (int i = 0; i < 5; i++)
            {
                indicator.IndParam.ListParam[i].Index   = ListParam[i].SelectedIndex;
                indicator.IndParam.ListParam[i].Text    = ListParam[i].Text;
                indicator.IndParam.ListParam[i].Enabled = ListParam[i].Enabled;
            }

            // Numeric params
            for (int i = 0; i < 6; i++)
            {
                indicator.IndParam.NumParam[i].Value   = (double)NumParam[i].Value;
                indicator.IndParam.NumParam[i].Enabled = NumParam[i].Enabled;
            }

            // Check params
            for (int i = 0; i < 2; i++)
            {
                indicator.IndParam.CheckParam[i].Checked = CheckParam[i].Checked;
                indicator.IndParam.CheckParam[i].Enabled = CheckParam[i].Enabled;
                indicator.IndParam.CheckParam[i].Enabled = CheckParam[i].Text == "Use previous bar value" ||
                                                           CheckParam[i].Enabled;
            }

            indicator.Calculate(Data.DataSet);

            //Sets the Data.Strategy.
            Data.Strategy.Slot[slot].IndicatorName  = indicator.IndicatorName;
            Data.Strategy.Slot[slot].IndParam       = indicator.IndParam;
            Data.Strategy.Slot[slot].Component      = indicator.Component;
            Data.Strategy.Slot[slot].SeparatedChart = indicator.SeparatedChart;
            Data.Strategy.Slot[slot].SpecValue      = indicator.SpecialValues;
            Data.Strategy.Slot[slot].MinValue       = indicator.SeparatedChartMinValue;
            Data.Strategy.Slot[slot].MaxValue       = indicator.SeparatedChartMaxValue;
            Data.Strategy.Slot[slot].IsDefined      = true;

            // Searches the indicators' components to determine the Data.FirstBar.
            Data.FirstBar = Data.Strategy.SetFirstBar();

            // Checks "Use previous bar value".
            if (Data.Strategy.AdjustUsePreviousBarValue())
            {
                for (int i = 0; i < 2; i++)
                {
                    if (indicator.IndParam.CheckParam[i].Caption == "Use previous bar value")
                    {
                        CheckParam[i].Checked = Data.Strategy.Slot[slot].IndParam.CheckParam[i].Checked;
                    }
                }
            }

            SetIndicatorNotification(indicator);
        }
        /// <summary>
        ///     Performs thorough indicator test.
        /// </summary>
        /// <param name="indicatorName">The indicator name.</param>
        /// <param name="errorsList">Error message.</param>
        /// <returns>True, if the test succeed.</returns>
        public static bool CustomIndicatorThoroughTest(string indicatorName, out string errorsList)
        {
            bool isOk = true;

            var sb = new StringBuilder();

            sb.AppendLine("ERROR: Indicator test failed for the '" + indicatorName + "' indicator.");

            foreach (SlotTypes slotType in  Enum.GetValues(typeof(SlotTypes)))
            {
                if (slotType == SlotTypes.NotDefined)
                {
                    continue;
                }

                Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);
                indicator.Initialize(slotType);

                if (!indicator.TestPossibleSlot(slotType))
                {
                    continue;
                }

                foreach (NumericParam numParam in indicator.IndParam.NumParam)
                {
                    if (numParam.Enabled)
                    {
                        numParam.Value = numParam.Min;
                    }
                }

                try
                {
                    indicator.Calculate(Data.DataSet);
                }
                catch (Exception exc)
                {
                    sb.AppendLine("\tError when calculating with NumParams set to their minimal values. " + exc.Message);
                    isOk = false;
                    break;
                }

                foreach (NumericParam numParam in indicator.IndParam.NumParam)
                {
                    if (numParam.Enabled)
                    {
                        numParam.Value = numParam.Max;
                    }
                }

                try
                {
                    indicator.Calculate(Data.DataSet);
                }
                catch (Exception exc)
                {
                    sb.AppendLine("\tError when calculating with NumParams set to their maximal values. " + exc.Message);
                    isOk = false;
                    break;
                }

                try
                {
                    foreach (IndicatorComp component in indicator.Component)
                    {
                        switch (slotType)
                        {
                        case SlotTypes.Open:
                            if (component.DataType == IndComponentType.AllowOpenLong ||
                                component.DataType == IndComponentType.AllowOpenShort ||
                                component.DataType == IndComponentType.CloseLongPrice ||
                                component.DataType == IndComponentType.ClosePrice ||
                                component.DataType == IndComponentType.CloseShortPrice ||
                                component.DataType == IndComponentType.ForceClose ||
                                component.DataType == IndComponentType.ForceCloseLong ||
                                component.DataType == IndComponentType.ForceCloseShort ||
                                component.DataType == IndComponentType.NotDefined)
                            {
                                sb.AppendLine(
                                    "\tProbably wrong component type when SlotType is 'SlotTypes.Open' - '" +
                                    component.CompName + "' of type '" + component.DataType + "'.");
                                isOk = false;
                            }
                            break;

                        case SlotTypes.OpenFilter:
                            if (component.DataType == IndComponentType.OpenClosePrice ||
                                component.DataType == IndComponentType.OpenLongPrice ||
                                component.DataType == IndComponentType.OpenPrice ||
                                component.DataType == IndComponentType.OpenShortPrice ||
                                component.DataType == IndComponentType.CloseLongPrice ||
                                component.DataType == IndComponentType.ClosePrice ||
                                component.DataType == IndComponentType.CloseShortPrice ||
                                component.DataType == IndComponentType.ForceClose ||
                                component.DataType == IndComponentType.ForceCloseLong ||
                                component.DataType == IndComponentType.ForceCloseShort ||
                                component.DataType == IndComponentType.NotDefined)
                            {
                                sb.AppendLine(
                                    "\tProbably wrong component type when SlotType is 'SlotTypes.OpenFilter' - '" +
                                    component.CompName + "' of type '" + component.DataType + "'.");
                                isOk = false;
                            }
                            break;

                        case SlotTypes.Close:
                            if (component.DataType == IndComponentType.AllowOpenLong ||
                                component.DataType == IndComponentType.AllowOpenShort ||
                                component.DataType == IndComponentType.OpenLongPrice ||
                                component.DataType == IndComponentType.OpenPrice ||
                                component.DataType == IndComponentType.OpenShortPrice ||
                                component.DataType == IndComponentType.ForceClose ||
                                component.DataType == IndComponentType.ForceCloseLong ||
                                component.DataType == IndComponentType.ForceCloseShort ||
                                component.DataType == IndComponentType.NotDefined)
                            {
                                sb.AppendLine(
                                    "\tProbably wrong component type when SlotType is 'SlotTypes.Close' - '" +
                                    component.CompName + "' of type '" + component.DataType + "'.");
                                isOk = false;
                            }
                            break;

                        case SlotTypes.CloseFilter:
                            if (component.DataType == IndComponentType.AllowOpenLong ||
                                component.DataType == IndComponentType.AllowOpenShort ||
                                component.DataType == IndComponentType.OpenLongPrice ||
                                component.DataType == IndComponentType.OpenPrice ||
                                component.DataType == IndComponentType.OpenShortPrice ||
                                component.DataType == IndComponentType.CloseLongPrice ||
                                component.DataType == IndComponentType.ClosePrice ||
                                component.DataType == IndComponentType.CloseShortPrice ||
                                component.DataType == IndComponentType.NotDefined)
                            {
                                sb.AppendLine(
                                    "\tProbably wrong component type when SlotType is 'SlotTypes.CloseFilter' - '" +
                                    component.CompName + "' of type '" + component.DataType + "'.");
                                isOk = false;
                            }
                            break;
                        }
                        if (component.DataType == IndComponentType.AllowOpenLong ||
                            component.DataType == IndComponentType.AllowOpenShort ||
                            component.DataType == IndComponentType.ForceClose ||
                            component.DataType == IndComponentType.ForceCloseLong ||
                            component.DataType == IndComponentType.ForceCloseShort)
                        {
                            foreach (double value in component.Value)
                            {
                                if (value != 0 && value != 1)
                                {
                                    sb.AppendLine("\tWrong component values. The values of '" + component.CompName +
                                                  "' must be 0 or 1.");
                                    isOk = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception exc)
                {
                    sb.AppendLine("\tError when checking the indicator's components. " + exc.Message);
                    isOk = false;
                    break;
                }
            }

            errorsList = isOk ? string.Empty : sb.ToString();

            return(isOk);
        }
        /// <summary>
        ///     Tests general parameters of a custom indicator.
        /// </summary>
        /// <param name="indicator">The indicator.</param>
        /// <param name="errorsList">List of the errors</param>
        /// <returns>True, if the test succeed.</returns>
        public static bool CustomIndicatorFastTest(Indicator indicator, out string errorsList)
        {
            bool isOk = true;

            var sb = new StringBuilder();

            sb.AppendLine("ERROR: Indicator test failed for '" + indicator.IndicatorName + "' indicator.");

            // Tests the IndicatorName property.
            if (string.IsNullOrEmpty(indicator.IndicatorName))
            {
                sb.AppendLine("\tThe property 'IndicatorName' is not set.");
                isOk = false;
            }

            // Tests the PossibleSlots property.
            if (!indicator.TestPossibleSlot(SlotTypes.Open) &&
                !indicator.TestPossibleSlot(SlotTypes.OpenFilter) &&
                !indicator.TestPossibleSlot(SlotTypes.Close) &&
                !indicator.TestPossibleSlot(SlotTypes.CloseFilter))
            {
                sb.AppendLine("\tThe property 'PossibleSlots' is not set.");
                isOk = false;
            }

            // Tests the CustomIndicator property.
            if (!indicator.CustomIndicator)
            {
                sb.AppendLine("\tThe indicator '" + indicator.IndicatorName +
                              "' is not marked as custom. Set CustomIndicator = true;");
                isOk = false;
            }

            // Tests the SeparatedChartMaxValue properties.
            if (!indicator.SeparatedChart && Math.Abs(indicator.SeparatedChartMaxValue - double.MinValue) > 0.000001)
            {
                sb.AppendLine("\tSet SeparatedChart = true; or remove the property: SeparatedChartMaxValue = " +
                              indicator.SeparatedChartMaxValue);
                isOk = false;
            }

            // Tests the SeparatedChartMinValue properties.
            if (!indicator.SeparatedChart && Math.Abs(indicator.SeparatedChartMinValue - double.MaxValue) > 0.000001)
            {
                sb.AppendLine("\tSet SeparatedChart = true; or remove the property: SeparatedChartMinValue = " +
                              indicator.SeparatedChartMinValue);
                isOk = false;
            }

            // Tests the SpecialValues properties.
            if (!indicator.SeparatedChart && indicator.SpecialValues.Length > 0)
            {
                sb.AppendLine("\tSet SeparatedChart = true; or remove the property SpecialValues");
                isOk = false;
            }

            // Tests the IndParam properties.
            if (indicator.IndParam == null)
            {
                sb.AppendLine("\tThe property IndParam is not set. Set IndParam = new IndicatorParam();");
                isOk = false;
            }

            // Tests the IndParam.IndicatorName properties.
            if (indicator.IndParam != null && indicator.IndParam.IndicatorName != indicator.IndicatorName)
            {
                sb.AppendLine(
                    "\tThe property IndParam.IndicatorName is not set. Set IndParam.IndicatorName = IndicatorName;");
                isOk = false;
            }

            // Tests the IndParam.SlotType properties.
            if (indicator.IndParam != null && indicator.IndParam.SlotType != SlotTypes.NotDefined)
            {
                sb.AppendLine("\tThe property IndParam.SlotType is not set. Set IndParam.SlotType = slotType;");
                isOk = false;
            }

            // Tests the IndParam.ListParam properties.
            for (int param = 0; param < indicator.IndParam.ListParam.Length; param++)
            {
                ListParam listParam = indicator.IndParam.ListParam[param];
                if (!listParam.Enabled)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(listParam.Caption))
                {
                    sb.AppendLine("\tThe property IndParam.ListParam[" + param + "].Caption is not set.");
                    isOk = false;
                }

                if (listParam.ItemList.Length == 0)
                {
                    sb.AppendLine("\tThe property IndParam.ListParam[" + param + "].ItemList is not set.");
                    isOk = false;
                }

                if (listParam.ItemList[listParam.Index] != listParam.Text)
                {
                    sb.AppendLine("\tThe property IndParam.ListParam[" + param + "].Text is wrong." +
                                  " Set " + "IndParam.ListParam[" + param + "].Text = IndParam.ListParam[" + param +
                                  "].ItemList[IndParam.ListParam[" + param + "].Index];");
                    isOk = false;
                }

                if (string.IsNullOrEmpty(listParam.ToolTip))
                {
                    sb.AppendLine("\tThe property IndParam.ListParam[" + param + "].ToolTip is not set.");
                    isOk = false;
                }
            }

            // Tests the IndParam.NumParam properties.
            for (int param = 0; param < indicator.IndParam.NumParam.Length; param++)
            {
                NumericParam numParam = indicator.IndParam.NumParam[param];
                if (!numParam.Enabled)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(numParam.Caption))
                {
                    sb.AppendLine("\tThe property IndParam.NumParam[" + param + "].Caption is not set.");
                    isOk = false;
                }

                double value = numParam.Value;
                double min   = numParam.Min;
                double max   = numParam.Max;
                double point = numParam.Point;

                if (min > max)
                {
                    sb.AppendLine("\tIndParam.NumParam[" + param + "].Min > IndParam.NumParam[" + param + "].Max.");
                    isOk = false;
                }

                if (value > max)
                {
                    sb.AppendLine("\tIndParam.NumParam[" + param + "].Value > IndParam.NumParam[" + param + "].Max.");
                    isOk = false;
                }

                if (value < min)
                {
                    sb.AppendLine("\tIndParam.NumParam[" + param + "].Value < IndParam.NumParam[" + param + "].Min.");
                    isOk = false;
                }

                if (point < 0)
                {
                    sb.AppendLine("\tIndParam.NumParam[" + param + "].Point cannot be < 0");
                    isOk = false;
                }

                if (point > 6)
                {
                    sb.AppendLine("\tIndParam.NumParam[" + param + "].Point cannot be > 6");
                    isOk = false;
                }

                if (string.IsNullOrEmpty(numParam.ToolTip))
                {
                    sb.AppendLine("\tThe property IndParam.NumParam[" + param + "].ToolTip is not set.");
                    isOk = false;
                }
            }

            // Tests the IndParam.CheckParam properties.
            for (int param = 0; param < indicator.IndParam.CheckParam.Length; param++)
            {
                CheckParam checkParam = indicator.IndParam.CheckParam[param];
                if (!checkParam.Enabled)
                {
                    continue;
                }

                if (string.IsNullOrEmpty(checkParam.Caption))
                {
                    sb.AppendLine("\tThe property IndParam.CheckParam[" + param + "].Caption is not set.");
                    isOk = false;
                }

                if (string.IsNullOrEmpty(checkParam.ToolTip))
                {
                    sb.AppendLine("\tThe property IndParam.CheckParam[" + param + "].ToolTip is not set.");
                    isOk = false;
                }
            }

            try
            {
                indicator.Calculate(Data.DataSet);
            }
            catch (Exception exc)
            {
                sb.AppendLine("\tError when executing Calculate(). " + exc.Message);
                isOk = false;
            }

            try
            {
                indicator.SetDescription();
            }
            catch (Exception exc)
            {
                sb.AppendLine("\tError when executing SetDescription(SlotTypes.NotDefined). " + exc.Message);
                isOk = false;
            }

            try
            {
                string description = indicator.ToString();
                Console.WriteLine(description);
            }
            catch (Exception exc)
            {
                sb.AppendLine("\tError when executing ToString(). " + exc.Message);
                isOk = false;
            }

            errorsList = isOk ? string.Empty : sb.ToString();

            return(isOk);
        }
Exemple #17
0
        /// <summary>
        ///     Pareses a strategy from a xml document.
        /// </summary>
        public Strategy ParseXmlStrategy(XmlDocument xmlDocStrategy)
        {
            // Read the number of slots
            int openFilters  = int.Parse(xmlDocStrategy.GetElementsByTagName("openFilters")[0].InnerText);
            int closeFilters = int.Parse(xmlDocStrategy.GetElementsByTagName("closeFilters")[0].InnerText);

            // Create the strategy.
            // ReSharper disable UseObjectOrCollectionInitializer
            var tempStrategy = new Strategy(openFilters, closeFilters);

            // ReSharper restore UseObjectOrCollectionInitializer

            // Same and Opposite direction Actions
            tempStrategy.SameSignalAction =
                (SameDirSignalAction)
                Enum.Parse(typeof(SameDirSignalAction),
                           xmlDocStrategy.GetElementsByTagName("sameDirSignalAction")[0].InnerText);
            tempStrategy.OppSignalAction =
                (OppositeDirSignalAction)
                Enum.Parse(typeof(OppositeDirSignalAction),
                           xmlDocStrategy.GetElementsByTagName("oppDirSignalAction")[0].InnerText);

            // Market
            tempStrategy.Symbol = xmlDocStrategy.GetElementsByTagName("instrumentSymbol")[0].InnerText;
            string period = xmlDocStrategy.GetElementsByTagName("instrumentPeriod")[0].InnerText;

            tempStrategy.DataPeriod = ImportDataPeriod(period);

            // Permanent Stop Loss
            tempStrategy.PermanentSL =
                Math.Abs(int.Parse(xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].InnerText));
            // Math.Abs() removes the negative sign from previous versions.
            XmlAttributeCollection xmlAttributeCollection =
                xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].Attributes;

            if (xmlAttributeCollection != null)
            {
                tempStrategy.UsePermanentSL = bool.Parse(xmlAttributeCollection["usePermanentSL"].InnerText);
                try
                {
                    tempStrategy.PermanentSLType =
                        (PermanentProtectionType)
                        Enum.Parse(typeof(PermanentProtectionType), xmlAttributeCollection["permanentSLType"].InnerText);
                }
                catch
                {
                    tempStrategy.PermanentSLType = PermanentProtectionType.Relative;
                }
            }

            // Permanent Take Profit
            tempStrategy.PermanentTP = int.Parse(xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].InnerText);
            XmlAttributeCollection attributeCollection =
                xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].Attributes;

            if (attributeCollection != null)
            {
                tempStrategy.UsePermanentTP = bool.Parse(attributeCollection["usePermanentTP"].InnerText);
                try
                {
                    tempStrategy.PermanentTPType =
                        (PermanentProtectionType)
                        Enum.Parse(typeof(PermanentProtectionType), attributeCollection["permanentTPType"].InnerText);
                }
                catch
                {
                    tempStrategy.PermanentTPType = PermanentProtectionType.Relative;
                }
            }

            // Break Even
            try
            {
                tempStrategy.BreakEven = int.Parse(xmlDocStrategy.GetElementsByTagName("breakEven")[0].InnerText);
                XmlAttributeCollection attributes = xmlDocStrategy.GetElementsByTagName("breakEven")[0].Attributes;
                if (attributes != null)
                {
                    tempStrategy.UseBreakEven = bool.Parse(attributes["useBreakEven"].InnerText);
                }
            }
            catch (Exception exception)
            {
                Console.Write(exception.Message);
            }

            // Money Management
            try
            {
                tempStrategy.UseAccountPercentEntry =
                    bool.Parse(xmlDocStrategy.GetElementsByTagName("useAccountPercentEntry")[0].InnerText);
            }
            catch
            {
                tempStrategy.UseAccountPercentEntry =
                    bool.Parse(xmlDocStrategy.GetElementsByTagName("useAcountPercentEntry")[0].InnerText);
            }
            tempStrategy.MaxOpenLots  = StringToDouble(xmlDocStrategy.GetElementsByTagName("maxOpenLots")[0].InnerText);
            tempStrategy.EntryLots    = StringToDouble(xmlDocStrategy.GetElementsByTagName("entryLots")[0].InnerText);
            tempStrategy.AddingLots   = StringToDouble(xmlDocStrategy.GetElementsByTagName("addingLots")[0].InnerText);
            tempStrategy.ReducingLots = StringToDouble(xmlDocStrategy.GetElementsByTagName("reducingLots")[0].InnerText);
            try
            {
                tempStrategy.UseMartingale =
                    bool.Parse(xmlDocStrategy.GetElementsByTagName("useMartingale")[0].InnerText);
                tempStrategy.MartingaleMultiplier =
                    StringToDouble(xmlDocStrategy.GetElementsByTagName("martingaleMultiplier")[0].InnerText);
            }
            catch
            {
                tempStrategy.UseMartingale        = false;
                tempStrategy.MartingaleMultiplier = 2.0;
            }

            // Description
            tempStrategy.Description = xmlDocStrategy.GetElementsByTagName("description")[0].InnerText;

            // Strategy name.
            tempStrategy.StrategyName = xmlDocStrategy.GetElementsByTagName("strategyName")[0].InnerText;

            // Reading the slots
            XmlNodeList xmlSlotList = xmlDocStrategy.GetElementsByTagName("slot");

            for (int slot = 0; slot < xmlSlotList.Count; slot++)
            {
                XmlNodeList   xmlSlotTagList = xmlSlotList[slot].ChildNodes;
                IndicatorSlot tempSlot       = tempStrategy.Slot[slot];

                XmlAttributeCollection collection = xmlSlotList[slot].Attributes;
                if (collection != null)
                {
                    // Identify the Slot Type
                    var slotType = (SlotTypes)Enum.Parse(typeof(SlotTypes), collection["slotType"].InnerText);

                    // Logical group
                    if (slotType == SlotTypes.OpenFilter || slotType == SlotTypes.CloseFilter)
                    {
                        XmlAttributeCollection attributes = collection;
                        XmlNode nodeGroup = attributes.GetNamedItem("logicalGroup");
                        string  defGroup  = GetDefaultGroup(slotType, slot, tempStrategy.CloseSlot);
                        if (nodeGroup != null)
                        {
                            string group = nodeGroup.InnerText;
                            tempSlot.LogicalGroup = @group;
                            if (@group != defGroup && @group.ToLower() != "all" && !Configs.UseLogicalGroups)
                            {
                                MessageBox.Show(
                                    Language.T("The strategy requires logical groups.") + Environment.NewLine +
                                    Language.T("\"Use Logical Groups\" option was temporarily switched on."),
                                    Language.T("Logical Groups"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                                Configs.UseLogicalGroups = true;
                            }
                        }
                        else
                        {
                            tempSlot.LogicalGroup = defGroup;
                        }
                    }

                    // Indicator name.
                    string indicatorName = xmlSlotTagList[0].InnerText;
                    if (!IndicatorManager.AllIndicatorsNames.Contains(indicatorName))
                    {
                        string message = string.Format("Indicator \"{0}\" was not found.", indicatorName);
                        throw new MissingIndicatorException(message);
                    }

                    Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);
                    indicator.Initialize(slotType);

                    for (int tag = 1; tag < xmlSlotTagList.Count; tag++)
                    {
                        // List parameters
                        if (xmlSlotTagList[tag].Name == "listParam")
                        {
                            XmlAttributeCollection attributes = xmlSlotTagList[tag].Attributes;
                            if (attributes != null)
                            {
                                int     listParam        = int.Parse(attributes["paramNumber"].InnerText);
                                XmlNode xmlListParamNode = xmlSlotTagList[tag].FirstChild;

                                indicator.IndParam.ListParam[listParam].Caption = xmlListParamNode.InnerText;

                                xmlListParamNode = xmlListParamNode.NextSibling;
                                if (xmlListParamNode != null)
                                {
                                    int index = int.Parse(xmlListParamNode.InnerText);
                                    indicator.IndParam.ListParam[listParam].Index = index;
                                    indicator.IndParam.ListParam[listParam].Text  =
                                        indicator.IndParam.ListParam[listParam].ItemList[index];
                                }
                            }
                        }

                        // Numeric parameters
                        if (xmlSlotTagList[tag].Name == "numParam")
                        {
                            XmlNode xmlNumParamNode           = xmlSlotTagList[tag].FirstChild;
                            XmlAttributeCollection attributes = xmlSlotTagList[tag].Attributes;
                            if (attributes != null)
                            {
                                int numParam = int.Parse(attributes["paramNumber"].InnerText);
                                indicator.IndParam.NumParam[numParam].Caption = xmlNumParamNode.InnerText;

                                xmlNumParamNode = xmlNumParamNode.NextSibling;
                                if (xmlNumParamNode != null)
                                {
                                    string numParamValue = xmlNumParamNode.InnerText;
                                    numParamValue = numParamValue.Replace(',', Data.PointChar);
                                    numParamValue = numParamValue.Replace('.', Data.PointChar);
                                    float value = float.Parse(numParamValue);

                                    // Removing of the Stop Loss negative sign used in previous versions.
                                    string parCaption = indicator.IndParam.NumParam[numParam].Caption;
                                    if (parCaption == "Trailing Stop" ||
                                        parCaption == "Initial Stop Loss" ||
                                        parCaption == "Stop Loss")
                                    {
                                        value = Math.Abs(value);
                                    }
                                    indicator.IndParam.NumParam[numParam].Value = value;
                                }
                            }
                        }

                        // Check parameters
                        if (xmlSlotTagList[tag].Name == "checkParam")
                        {
                            XmlNode xmlCheckParamNode         = xmlSlotTagList[tag].FirstChild;
                            XmlAttributeCollection attributes = xmlSlotTagList[tag].Attributes;
                            if (attributes != null)
                            {
                                int checkParam = int.Parse(attributes["paramNumber"].InnerText);
                                indicator.IndParam.CheckParam[checkParam].Caption = xmlCheckParamNode.InnerText;

                                xmlCheckParamNode = xmlCheckParamNode.NextSibling;
                                if (xmlCheckParamNode != null)
                                {
                                    indicator.IndParam.CheckParam[checkParam].Checked =
                                        bool.Parse(xmlCheckParamNode.InnerText);
                                }
                            }
                        }
                    }

                    if (slotType == SlotTypes.OpenFilter || slotType == SlotTypes.CloseFilter)
                    {
                        // Signal shift type.
                        XmlNodeList signalShiftType = xmlSlotList[slot].SelectNodes("signalShiftType");
                        tempSlot.SignalShiftType = signalShiftType.Count == 0
                                                       ? SignalShiftType.At
                                                       : (SignalShiftType)
                                                   Enum.Parse(typeof(SignalShiftType),
                                                              signalShiftType[0].InnerText);

                        // Signal shift type.
                        XmlNodeList signalShift = xmlSlotList[slot].SelectNodes("signalShift");
                        tempSlot.SignalShift = signalShift.Count == 0
                                                   ? 0
                                                   : int.Parse(signalShift[0].InnerText);

                        // Symbol
                        XmlNodeList indicatorSymbol = xmlSlotList[slot].SelectNodes("indicatorSymbol");
                        tempSlot.IndicatorSymbol = indicatorSymbol.Count == 0
                                                       ? string.Empty
                                                       : indicatorSymbol[0].InnerText;

                        // Period
                        XmlNodeList indicatorPeriod = xmlSlotList[slot].SelectNodes("indicatorPeriod");
                        tempSlot.IndicatorPeriod = indicatorPeriod.Count == 0
                                                       ? DataPeriod.M1
                                                       : ImportDataPeriod(indicatorPeriod[0].InnerText);
                    }

                    // Calculate the indicator.
                    indicator.Calculate(Data.DataSet);
                    tempSlot.IndicatorName  = indicator.IndicatorName;
                    tempSlot.IndParam       = indicator.IndParam;
                    tempSlot.Component      = indicator.Component;
                    tempSlot.SeparatedChart = indicator.SeparatedChart;
                    tempSlot.SpecValue      = indicator.SpecialValues;
                    tempSlot.MinValue       = indicator.SeparatedChartMinValue;
                    tempSlot.MaxValue       = indicator.SeparatedChartMaxValue;
                }
                tempSlot.IsDefined = true;
            }

            return(tempStrategy);
        }