Пример #1
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();
        }
Пример #2
0
        /// <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);
        }
        /// <summary>
        ///     Loads an Indicator
        /// </summary>
        private void TrvIndicatorsLoadIndicator()
        {
            Indicator indicator = IndicatorManager.ConstructIndicator(TrvIndicators.SelectedNode.Text);

            indicator.Initialize(SlotType);
            UpdateFromIndicatorParam(indicator.IndParam);
            SetDefaultGroup();
            CalculateIndicator();
        }
        /// <summary>
        ///     Loads the defaults parameters for the selected indicator.
        /// </summary>
        private void BtnDefaultClick(object sender, EventArgs e)
        {
            Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);

            indicator.Initialize(SlotType);
            UpdateFromIndicatorParam(indicator.IndParam);
            SetDefaultGroup();
            CalculateIndicator();
        }
        /// <summary>
        ///     Calculates the indicator in the designated slot.
        /// </summary>
        private void CalculateIndicator(int slot)
        {
            IndicatorParam ip = Data.Strategy.Slot[slot].IndParam;

            Indicator indicator = IndicatorManager.ConstructIndicator(ip.IndicatorName);

            indicator.Initialize(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(Data.DataSet);

            // 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();
        }
Пример #6
0
        /// <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);
        }
Пример #7
0
        /// <summary>
        ///     Shows the loaded custom indicators.
        /// </summary>
        public static void ShowLoadedCustomIndicators()
        {
            var loadedIndicators = new StringBuilder();

            loadedIndicators.AppendLine("<h1>" + Language.T("Custom Indicators") + "</h1>");
            loadedIndicators.AppendLine("<p>Loaded " + IndicatorManager.CustomIndicatorNames.Count + " indicators.</p>");
            loadedIndicators.AppendLine("<p>");
            foreach (string indicatorName in IndicatorManager.CustomIndicatorNames)
            {
                Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);
                indicator.Initialize(SlotTypes.NotDefined);
                string dll = indicator.LoaddedFromDll ? " (dll)" : " (cs)";
                loadedIndicators.AppendLine(indicatorName + dll + "</br>");
            }
            loadedIndicators.AppendLine("</p>");

            var msgBox = new FancyMessageBox(loadedIndicators.ToString(), Language.T("Custom Indicators"))
            {
                BoxWidth = 480, BoxHeight = 260, TopMost = true
            };

            msgBox.Show();
        }
Пример #8
0
        /// <summary>
        ///     Show indicators in the selected bars.
        /// </summary>
        private void ShowIndicators(string input)
        {
            const string pattern    = @"^ind (?<numb>\d+)$";
            var          expression = new Regex(pattern, RegexOptions.Compiled);
            Match        match      = expression.Match(input);

            if (match.Success)
            {
                int bar = int.Parse(match.Groups["numb"].Value);
                if (bar < 1 || bar > Data.Bars)
                {
                    return;
                }

                bar--;

                var sb = new StringBuilder();
                for (int slot = 0; slot < Data.Strategy.Slots; slot++)
                {
                    Indicator indicator = IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                    indicator.Initialize(Data.Strategy.Slot[slot].SlotType);

                    sb.Append(Environment.NewLine + indicator + Environment.NewLine + "Logic: " +
                              indicator.IndParam.ListParam[0].Text + Environment.NewLine + "-----------------" +
                              Environment.NewLine);
                    foreach (IndicatorComp indComp in Data.Strategy.Slot[slot].Component)
                    {
                        sb.Append(indComp.CompName + "    ");
                        sb.Append(indComp.Value[bar] + Environment.NewLine);
                    }
                }

                TbxOutput.Text += Environment.NewLine + "Indicators for bar " + (bar + 1) + Environment.NewLine +
                                  "-----------------" + Environment.NewLine + sb;
            }
        }
Пример #9
0
        /// <summary>
        ///     Generates a HTML report about the opening logic.
        /// </summary>
        private StringBuilder OpeningLogicHtmlReport()
        {
            var    sb            = new StringBuilder();
            string indicatorName = Data.Strategy.Slot[0].IndicatorName;

            Indicator indOpen = IndicatorManager.ConstructIndicator(indicatorName);

            indOpen.Initialize(SlotTypes.Open);
            indOpen.IndParam = Data.Strategy.Slot[0].IndParam;
            indOpen.SetDescription();

            // Logical groups of the opening conditions.
            var opengroups = new List <string>();

            for (int slot = 1; slot <= Data.Strategy.OpenFilters; slot++)
            {
                string group = Data.Strategy.Slot[slot].LogicalGroup;
                if (!opengroups.Contains(group) && group != "All")
                {
                    opengroups.Add(group); // Adds all groups except "All"
                }
            }
            if (opengroups.Count == 0 && Data.Strategy.OpenFilters > 0)
            {
                opengroups.Add("All"); // If all the slots are in "All" group, adds "All" to the list.
            }
            // Long position
            string openLong = "<p>";

            if (Data.Strategy.SameSignalAction == SameDirSignalAction.Add)
            {
                openLong = Language.T("Open a new long position or add to an existing position");
            }
            else if (Data.Strategy.SameSignalAction == SameDirSignalAction.Winner)
            {
                openLong = Language.T("Open a new long position or add to a winning position");
            }
            else if (Data.Strategy.SameSignalAction == SameDirSignalAction.Nothing)
            {
                openLong = Language.T("Open a new long position");
            }

            if (OppSignalAction == OppositeDirSignalAction.Close)
            {
                openLong += " " + Language.T("or close a short position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Reduce)
            {
                openLong += " " + Language.T("or reduce a short position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Reverse)
            {
                openLong += " " + Language.T("or reverse a short position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Nothing)
            {
                openLong += "";
            }

            openLong += " " + indOpen.EntryPointLongDescription;

            if (Data.Strategy.OpenFilters == 0)
            {
                openLong += ".</p>";
            }
            else if (Data.Strategy.OpenFilters == 1)
            {
                openLong += " " + Language.T("when the following logic condition is satisfied") + ":</p>";
            }
            else if (opengroups.Count > 1)
            {
                openLong += " " + Language.T("when") + ":</p>";
            }
            else
            {
                openLong += " " + Language.T("when all the following logic conditions are satisfied") + ":</p>";
            }

            sb.AppendLine(openLong);

            // Open Filters
            if (Data.Strategy.OpenFilters > 0)
            {
                int groupnumb = 1;
                if (opengroups.Count > 1)
                {
                    sb.AppendLine("<ul>");
                }

                foreach (string group in opengroups)
                {
                    if (opengroups.Count > 1)
                    {
                        sb.AppendLine("<li>" + (groupnumb == 1 ? "" : Language.T("or") + " ") +
                                      Language.T("logical group [#] is satisfied").Replace("#", group) + ":");
                        groupnumb++;
                    }

                    sb.AppendLine("<ul>");
                    int indInGroup = 0;
                    for (int slot = 1; slot <= Data.Strategy.OpenFilters; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup == group ||
                            Data.Strategy.Slot[slot].LogicalGroup == "All")
                        {
                            indInGroup++;
                        }
                    }

                    int indnumb = 1;
                    for (int slot = 1; slot <= Data.Strategy.OpenFilters; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup != group &&
                            Data.Strategy.Slot[slot].LogicalGroup != "All")
                        {
                            continue;
                        }

                        Indicator indOpenFilter =
                            IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                        indOpenFilter.Initialize(SlotTypes.Open);
                        indOpenFilter.IndParam = Data.Strategy.Slot[slot].IndParam;
                        indOpenFilter.SetDescription();

                        if (indnumb < indInGroup)
                        {
                            sb.AppendLine("<li>" + indOpenFilter.EntryFilterLongDescription + "; " + Language.T("and") +
                                          "</li>");
                        }
                        else
                        {
                            sb.AppendLine("<li>" + indOpenFilter.EntryFilterLongDescription + ".</li>");
                        }

                        indnumb++;
                    }
                    sb.AppendLine("</ul>");

                    if (opengroups.Count > 1)
                    {
                        sb.AppendLine("</li>");
                    }
                }

                if (opengroups.Count > 1)
                {
                    sb.AppendLine("</ul>");
                }
            }

            // Short position
            string openShort = "<p>";

            if (Data.Strategy.SameSignalAction == SameDirSignalAction.Add)
            {
                openShort = Language.T("Open a new short position or add to an existing position");
            }
            else if (Data.Strategy.SameSignalAction == SameDirSignalAction.Winner)
            {
                openShort = Language.T("Open a new short position or add to a winning position");
            }
            else if (Data.Strategy.SameSignalAction == SameDirSignalAction.Nothing)
            {
                openShort = Language.T("Open a new short position");
            }

            if (OppSignalAction == OppositeDirSignalAction.Close)
            {
                openShort += " " + Language.T("or close a long position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Reduce)
            {
                openShort += " " + Language.T("or reduce a long position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Reverse)
            {
                openShort += " " + Language.T("or reverse a long position");
            }
            else if (OppSignalAction == OppositeDirSignalAction.Nothing)
            {
                openShort += "";
            }

            openShort += " " + indOpen.EntryPointShortDescription;

            if (Data.Strategy.OpenFilters == 0)
            {
                openShort += ".</p>";
            }
            else if (Data.Strategy.OpenFilters == 1)
            {
                openShort += " " + Language.T("when the following logic condition is satisfied") + ":</p>";
            }
            else if (opengroups.Count > 1)
            {
                openShort += " " + Language.T("when") + ":</p>";
            }
            else
            {
                openShort += " " + Language.T("when all the following logic conditions are satisfied") + ":</p>";
            }

            sb.AppendLine(openShort);

            // Open Filters
            if (Data.Strategy.OpenFilters > 0)
            {
                int groupnumb = 1;
                if (opengroups.Count > 1)
                {
                    sb.AppendLine("<ul>");
                }

                foreach (string group in opengroups)
                {
                    if (opengroups.Count > 1)
                    {
                        sb.AppendLine("<li>" + (groupnumb == 1 ? "" : Language.T("or") + " ") +
                                      Language.T("logical group [#] is satisfied").Replace("#", group) + ":");
                        groupnumb++;
                    }

                    sb.AppendLine("<ul>");
                    int indInGroup = 0;
                    for (int slot = 1; slot <= Data.Strategy.OpenFilters; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup == group ||
                            Data.Strategy.Slot[slot].LogicalGroup == "All")
                        {
                            indInGroup++;
                        }
                    }

                    int indnumb = 1;
                    for (int slot = 1; slot <= Data.Strategy.OpenFilters; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup != group &&
                            Data.Strategy.Slot[slot].LogicalGroup != "All")
                        {
                            continue;
                        }

                        Indicator indOpenFilter =
                            IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                        indOpenFilter.Initialize(SlotTypes.Open);
                        indOpenFilter.IndParam = Data.Strategy.Slot[slot].IndParam;
                        indOpenFilter.SetDescription();

                        if (indnumb < indInGroup)
                        {
                            sb.AppendLine("<li>" + indOpenFilter.EntryFilterShortDescription + "; " + Language.T("and") +
                                          "</li>");
                        }
                        else
                        {
                            sb.AppendLine("<li>" + indOpenFilter.EntryFilterShortDescription + ".</li>");
                        }

                        indnumb++;
                    }
                    sb.AppendLine("</ul>");

                    if (opengroups.Count > 1)
                    {
                        sb.AppendLine("</li>");
                    }
                }
                if (opengroups.Count > 1)
                {
                    sb.AppendLine("</ul>");
                }
            }

            return(sb);
        }
Пример #10
0
        /// <summary>
        ///     Normalizes the numeric parameters.
        /// </summary>
        private void ReduceTheValuesOfNumericParams(BackgroundWorker worker)
        {
            for (int slot = 0; slot < Data.Strategy.Slots; slot++)
            {
                if (bestValue < 500)
                {
                    break;
                }
                if (Data.Strategy.Slot[slot].SlotStatus == StrategySlotStatus.Locked)
                {
                    continue;
                }

                // Numeric parameters
                for (int param = 0; param < 6; param++)
                {
                    if (!Data.Strategy.Slot[slot].IndParam.NumParam[param].Enabled)
                    {
                        continue;
                    }

                    bool isDoAgain;
                    do
                    {
                        if (worker.CancellationPending)
                        {
                            break;
                        }

                        IndicatorSlot indSlot = Data.Strategy.Slot[slot];
                        NumericParam  num     = Data.Strategy.Slot[slot].IndParam.NumParam[param];
                        if (num.Caption == "Level" && !indSlot.IndParam.ListParam[0].Text.Contains("Level"))
                        {
                            break;
                        }

                        Indicator indicator = IndicatorManager.ConstructIndicator(indSlot.IndicatorName);
                        indicator.Initialize(indSlot.SlotType);
                        double defaultValue = indicator.IndParam.NumParam[param].Value;

                        double numOldValue = num.Value;
                        if (Math.Abs(num.Value - defaultValue) < 0.00001)
                        {
                            break;
                        }

                        double value = num.Value;
                        double delta = (defaultValue - value) * 3 / 4;
                        value += delta;
                        value  = Math.Round(value, num.Point);

                        if (Math.Abs(value - numOldValue) < value)
                        {
                            break;
                        }

                        num.Value = value;

                        RecalculateSlots();
                        isDoAgain = CalculateTheResult(true);
                        if (!isDoAgain)
                        {
                            RestoreFromBest();
                        }
                    } while (isDoAgain);
                }
            }
        }
        /// <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);
        }
Пример #12
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);
        }
        /// <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>
        ///     Calculates the selected indicator.
        /// </summary>
        private void CalculateIndicator(bool bCalculateStrategy)
        {
            if (!Data.IsData || !Data.IsResult || !isPaint)
            {
                return;
            }

            SetOppositeSignalBehaviour();
            SetClosingLogicConditions();

            Indicator indicator = IndicatorManager.ConstructIndicator(indicatorName);

            indicator.Initialize(slotType);

            // List parameters
            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 parameters
            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 parameters
            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;
            }

            if (!CalculateIndicator(slotType, indicator))
            {
                return;
            }

            if (bCalculateStrategy)
            {
                //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;

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

                // Check "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")
                        {
                            AChbCheck[i].Checked = Data.Strategy.Slot[slot].IndParam.CheckParam[i].Checked;
                        }
                    }
                }

                Backtester.Calculate();
                Backtester.CalculateAccountStats();
            }

            SetIndicatorNotification(indicator);

            Data.IsResult = true;
        }
Пример #15
0
        /// <summary>
        ///     Generates a HTML report about the closing logic.
        /// </summary>
        private StringBuilder ClosingLogicHTMLReport()
        {
            var sb = new StringBuilder();

            int    closingSlotNmb = Data.Strategy.CloseSlot;
            string indicatorName  = Data.Strategy.Slot[closingSlotNmb].IndicatorName;

            Indicator indClose = IndicatorManager.ConstructIndicator(indicatorName);

            indClose.Initialize(SlotTypes.Close);
            indClose.IndParam = Data.Strategy.Slot[closingSlotNmb].IndParam;
            indClose.SetDescription();

            bool isGroups    = false;
            var  closegroups = new List <string>();

            if (Data.Strategy.CloseFilters > 0)
            {
                foreach (IndicatorSlot slot in Data.Strategy.Slot)
                {
                    if (slot.SlotType == SlotTypes.CloseFilter)
                    {
                        if (slot.LogicalGroup == "all" && Data.Strategy.CloseFilters > 1)
                        {
                            isGroups = true;
                        }

                        if (closegroups.Contains(slot.LogicalGroup))
                        {
                            isGroups = true;
                        }
                        else if (slot.LogicalGroup != "all")
                        {
                            closegroups.Add(slot.LogicalGroup);
                        }
                    }
                }
            }

            if (closegroups.Count == 0 && Data.Strategy.CloseFilters > 0)
            {
                closegroups.Add("all"); // If all the slots are in "all" group, adds "all" to the list.
            }
            // Long position
            string closeLong = "<p>" + Language.T("Close an existing long position") + " " +
                               indClose.ExitPointLongDescription;

            if (Data.Strategy.CloseFilters == 0)
            {
                closeLong += ".</p>";
            }
            else if (Data.Strategy.CloseFilters == 1)
            {
                closeLong += " " + Language.T("when the following logic condition is satisfied") + ":</p>";
            }
            else if (isGroups)
            {
                closeLong += " " + Language.T("when") + ":</p>";
            }
            else
            {
                closeLong += " " + Language.T("when at least one of the following logic conditions is satisfied") +
                             ":</p>";
            }

            sb.AppendLine(closeLong);

            // Close Filters
            if (Data.Strategy.CloseFilters > 0)
            {
                int groupnumb = 1;
                sb.AppendLine("<ul>");

                foreach (string group in closegroups)
                {
                    if (isGroups)
                    {
                        sb.AppendLine("<li>" + (groupnumb == 1 ? "" : Language.T("or") + " ") +
                                      Language.T("logical group [#] is satisfied").Replace("#", group) + ":");
                        sb.AppendLine("<ul>");
                        groupnumb++;
                    }

                    int indInGroup = 0;
                    for (int slot = closingSlotNmb + 1; slot < Data.Strategy.Slots; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup == group ||
                            Data.Strategy.Slot[slot].LogicalGroup == "all")
                        {
                            indInGroup++;
                        }
                    }

                    int indnumb = 1;
                    for (int slot = closingSlotNmb + 1; slot < Data.Strategy.Slots; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup != group &&
                            Data.Strategy.Slot[slot].LogicalGroup != "all")
                        {
                            continue;
                        }

                        Indicator indCloseFilter =
                            IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                        indCloseFilter.Initialize(SlotTypes.CloseFilter);
                        indCloseFilter.IndParam = Data.Strategy.Slot[slot].IndParam;
                        indCloseFilter.SetDescription();

                        if (isGroups)
                        {
                            if (indnumb < indInGroup)
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterLongDescription + "; " +
                                              Language.T("and") + "</li>");
                            }
                            else
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterLongDescription + ".</li>");
                            }
                        }
                        else
                        {
                            if (slot < Data.Strategy.Slots - 1)
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterLongDescription + "; " +
                                              Language.T("or") + "</li>");
                            }
                            else
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterLongDescription + ".</li>");
                            }
                        }
                        indnumb++;
                    }

                    if (isGroups)
                    {
                        sb.AppendLine("</ul>");
                        sb.AppendLine("</li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            // Short position
            string closeShort = "<p>" + Language.T("Close an existing short position") + " " +
                                indClose.ExitPointShortDescription;

            if (Data.Strategy.CloseFilters == 0)
            {
                closeShort += ".</p>";
            }
            else if (Data.Strategy.CloseFilters == 1)
            {
                closeShort += " " + Language.T("when the following logic condition is satisfied") + ":</p>";
            }
            else if (isGroups)
            {
                closeShort += " " + Language.T("when") + ":</p>";
            }
            else
            {
                closeShort += " " + Language.T("when at least one of the following logic conditions is satisfied") +
                              ":</p>";
            }

            sb.AppendLine(closeShort);

            // Close Filters
            if (Data.Strategy.CloseFilters > 0)
            {
                int groupnumb = 1;
                sb.AppendLine("<ul>");

                foreach (string group in closegroups)
                {
                    if (isGroups)
                    {
                        sb.AppendLine("<li>" + (groupnumb == 1 ? "" : Language.T("or") + " ") +
                                      Language.T("logical group [#] is satisfied").Replace("#", group) + ":");
                        sb.AppendLine("<ul>");
                        groupnumb++;
                    }

                    int indInGroup = 0;
                    for (int slot = closingSlotNmb + 1; slot < Data.Strategy.Slots; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup == group ||
                            Data.Strategy.Slot[slot].LogicalGroup == "all")
                        {
                            indInGroup++;
                        }
                    }

                    int indnumb = 1;
                    for (int slot = closingSlotNmb + 1; slot < Data.Strategy.Slots; slot++)
                    {
                        if (Data.Strategy.Slot[slot].LogicalGroup != group &&
                            Data.Strategy.Slot[slot].LogicalGroup != "all")
                        {
                            continue;
                        }

                        Indicator indCloseFilter =
                            IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                        indCloseFilter.Initialize(SlotTypes.CloseFilter);
                        indCloseFilter.IndParam = Data.Strategy.Slot[slot].IndParam;
                        indCloseFilter.SetDescription();

                        if (isGroups)
                        {
                            if (indnumb < indInGroup)
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterShortDescription + "; " +
                                              Language.T("and") + "</li>");
                            }
                            else
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterShortDescription + ".</li>");
                            }
                        }
                        else
                        {
                            if (slot < Data.Strategy.Slots - 1)
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterShortDescription + "; " +
                                              Language.T("or") + "</li>");
                            }
                            else
                            {
                                sb.AppendLine("<li>" + indCloseFilter.ExitFilterShortDescription + ".</li>");
                            }
                        }
                        indnumb++;
                    }

                    if (isGroups)
                    {
                        sb.AppendLine("</ul>");
                        sb.AppendLine("</li>");
                    }
                }

                sb.AppendLine("</ul>");
            }

            return(sb);
        }
        /// <summary>
        ///     Sets the trvIndicators nodes
        /// </summary>
        private void SetTreeViewIndicators()
        {
            var trnAll = new TreeNode {
                Name = "trnAll", Text = Language.T("All"), Tag = false
            };

            var trnIndicators = new TreeNode {
                Name = "trnIndicators", Text = Language.T("Indicators"), Tag = false
            };

            var trnAdditional = new TreeNode {
                Name = "trnAdditional", Text = Language.T("Additional"), Tag = false
            };

            var trnOscillatorOfIndicators = new TreeNode
            {
                Name = "trnOscillatorOfIndicators",
                Text = Language.T("Oscillator of Indicators"),
                Tag  = false
            };

            var trnIndicatorsMaOscillator = new TreeNode
            {
                Name = "trnIndicatorMA",
                Text = Language.T("Indicator's MA Oscillator"),
                Tag  = false
            };

            var trnDateTime = new TreeNode {
                Name = "trnDateTime", Text = Language.T("Date/Time Functions"), Tag = false
            };

            var trnCustomIndicators = new TreeNode
            {
                Name = "trnCustomIndicators",
                Text = Language.T("Custom Indicators"),
                Tag  = false
            };

            TrvIndicators.Nodes.AddRange(new[]
            {
                trnAll, trnIndicators, trnAdditional, trnOscillatorOfIndicators,
                trnIndicatorsMaOscillator, trnDateTime, trnCustomIndicators
            });

            foreach (string name in IndicatorManager.GetIndicatorNames(SlotType))
            {
                // Checks the indicator name in the list of forbidden indicators.
                bool toContinue = false;
                foreach (string forbiden in Data.IndicatorsForBacktestOnly)
                {
                    if (name == forbiden)
                    {
                        toContinue = true;
                        break;
                    }
                }
                if (toContinue)
                {
                    continue;
                }

                Indicator indicator = IndicatorManager.ConstructIndicator(name);
                indicator.Initialize(SlotType);
                TypeOfIndicator type = indicator.IndParam.IndicatorType;

                Color nodeColor = LayoutColors.ColorControlText;
                if (indicator.OverrideMainIndicator)
                {
                    nodeColor = Color.Brown;
                }

                var trn = new TreeNode {
                    Tag = true, Name = name, Text = name, ForeColor = nodeColor
                };
                trnAll.Nodes.Add(trn);

                if (indicator.CustomIndicator)
                {
                    var trnCustom = new TreeNode {
                        Tag = true, Name = name, Text = name, ForeColor = nodeColor
                    };
                    trnCustomIndicators.Nodes.Add(trnCustom);
                }

                var trnGroups = new TreeNode {
                    Tag = true, Name = name, Text = name, ForeColor = nodeColor
                };

                if (type == TypeOfIndicator.Indicator)
                {
                    trnIndicators.Nodes.Add(trnGroups);
                }
                else if (type == TypeOfIndicator.Additional)
                {
                    trnAdditional.Nodes.Add(trnGroups);
                }
                else if (type == TypeOfIndicator.OscillatorOfIndicators)
                {
                    trnOscillatorOfIndicators.Nodes.Add(trnGroups);
                }
                else if (type == TypeOfIndicator.IndicatorsMA)
                {
                    trnIndicatorsMaOscillator.Nodes.Add(trnGroups);
                }
                else if (type == TypeOfIndicator.DateTime)
                {
                    trnDateTime.Nodes.Add(trnGroups);
                }
            }
        }
Пример #17
0
        private void GenerateStrategy()
        {
            var strategy = new Strategy(4, 2)
            {
                SameSignalAction     = SameDirSignalAction.Add,
                OppSignalAction      = OppositeDirSignalAction.Nothing,
                PermanentSL          = 500,
                UsePermanentSL       = true,
                PermanentTP          = 500,
                UsePermanentTP       = true,
                BreakEven            = 500,
                UseBreakEven         = true,
                EntryLots            = 0.1,
                AddingLots           = 0.2,
                UseMartingale        = true,
                MartingaleMultiplier = 2
            };

            Indicator indicator = IndicatorManager.ConstructIndicator("Bar Opening");

            indicator.Initialize(SlotTypes.Open);
            strategy.Slot[0].IndicatorName = indicator.IndicatorName;
            strategy.Slot[0].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[0].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("Moving Average");
            indicator.Initialize(SlotTypes.OpenFilter);
            strategy.Slot[1].IndicatorName = indicator.IndicatorName;
            strategy.Slot[1].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[1].LogicalGroup  = "A";
            strategy.Slot[1].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("MACD");
            indicator.Initialize(SlotTypes.OpenFilter);
            strategy.Slot[2].IndicatorName = indicator.IndicatorName;
            strategy.Slot[2].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[2].LogicalGroup  = "B";
            strategy.Slot[2].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("RSI");
            indicator.Initialize(SlotTypes.OpenFilter);
            strategy.Slot[3].IndicatorName = indicator.IndicatorName;
            strategy.Slot[3].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[3].LogicalGroup  = "C";
            strategy.Slot[3].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("ADX");
            indicator.Initialize(SlotTypes.OpenFilter);
            strategy.Slot[4].IndicatorName = indicator.IndicatorName;
            strategy.Slot[4].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[4].LogicalGroup  = "D";
            strategy.Slot[4].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("Bar Closing");
            indicator.Initialize(SlotTypes.Close);
            strategy.Slot[5].IndicatorName = indicator.IndicatorName;
            strategy.Slot[5].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[5].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("Moving Average");
            indicator.Initialize(SlotTypes.CloseFilter);
            strategy.Slot[6].IndicatorName = indicator.IndicatorName;
            strategy.Slot[6].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[6].LogicalGroup  = "a";
            strategy.Slot[6].IsDefined     = true;

            indicator = IndicatorManager.ConstructIndicator("RSI");
            indicator.Initialize(SlotTypes.CloseFilter);
            strategy.Slot[7].IndicatorName = indicator.IndicatorName;
            strategy.Slot[7].IndParam      = indicator.IndParam.Clone();
            strategy.Slot[7].LogicalGroup  = "b";
            strategy.Slot[7].IsDefined     = true;

            Data.Strategy = strategy;
        }
Пример #18
0
        /// <summary>
        ///     Exports data and indicators values
        /// </summary>
        public void ExportIndicators()
        {
            string stage = String.Empty;

            if (Data.IsProgramBeta)
            {
                stage = " " + Language.T("Beta");
            }
            else if (Data.IsProgramReleaseCandidate)
            {
                stage = " " + "RC";
            }

            string ff = Data.Ff; // Format modifier to print float numbers
            string df = Data.Df; // Format modifier to print date
            var    sb = new StringBuilder();

            sb.Append("Forex Strategy Builder v" + Data.ProgramVersion + stage + Environment.NewLine);
            sb.Append("Strategy name: " + Data.Strategy.StrategyName + Environment.NewLine);
            sb.Append("Exported on " + DateTime.Now + Environment.NewLine);
            sb.Append(Data.Symbol + " " + Data.PeriodString + Environment.NewLine);
            sb.Append("Number of bars: " + Data.Bars);

            sb.Append("\t\t\t\t\t\t\t\t");

            for (int slot = 0; slot < Data.Strategy.Slots; slot++)
            {
                string strSlotType = "";
                switch (Data.Strategy.Slot[slot].SlotType)
                {
                case SlotTypes.Open:
                    strSlotType = "Opening point of the position";
                    break;

                case SlotTypes.OpenFilter:
                    strSlotType = "Opening logic condition";
                    break;

                case SlotTypes.Close:
                    strSlotType = "Closing point of the position";
                    break;

                case SlotTypes.CloseFilter:
                    strSlotType = "Closing logic condition";
                    break;
                }

                sb.Append(strSlotType + "\t");
                for (int i = 0; i < Data.Strategy.Slot[slot].Component.Length; i++)
                {
                    sb.Append("\t");
                }
            }
            sb.Append(Environment.NewLine);


            // Names of the indicator components
            sb.Append("\t\t\t\t\t\t\t\t");

            for (int slot = 0; slot < Data.Strategy.Slots; slot++)
            {
                Indicator indicator = IndicatorManager.ConstructIndicator(Data.Strategy.Slot[slot].IndicatorName);
                indicator.Initialize(Data.Strategy.Slot[slot].SlotType);

                sb.Append(indicator + "\t");
                for (int i = 0; i < Data.Strategy.Slot[slot].Component.Length; i++)
                {
                    sb.Append("\t");
                }
            }
            sb.Append(Environment.NewLine);

            // Data
            sb.Append("Date" + "\t");
            sb.Append("Hour" + "\t");
            sb.Append("Open" + "\t");
            sb.Append("High" + "\t");
            sb.Append("Low" + "\t");
            sb.Append("Close" + "\t");
            sb.Append("Volume" + "\t");

            for (int slot = 0; slot < Data.Strategy.Slots; slot++)
            {
                sb.Append("\t");
                foreach (IndicatorComp comp in Data.Strategy.Slot[slot].Component)
                {
                    sb.Append(comp.CompName + "\t");
                }
            }
            sb.Append(Environment.NewLine);

            for (int bar = 0; bar < Data.Bars; bar++)
            {
                sb.Append(Data.Time[bar].ToString(df) + "\t");
                sb.Append(Data.Time[bar].ToString("HH:mm") + "\t");
                sb.Append(Data.Open[bar].ToString(ff) + "\t");
                sb.Append(Data.High[bar].ToString(ff) + "\t");
                sb.Append(Data.Low[bar].ToString(ff) + "\t");
                sb.Append(Data.Close[bar].ToString(ff) + "\t");
                sb.Append(Data.Volume[bar] + "\t");

                for (int slot = 0; slot < Data.Strategy.Slots; slot++)
                {
                    sb.Append("\t");
                    foreach (IndicatorComp comp in Data.Strategy.Slot[slot].Component)
                    {
                        sb.Append(comp.Value[bar] + "\t");
                    }
                }
                sb.Append(Environment.NewLine);
            }

            string fileName = Data.Strategy.StrategyName + "-" + Data.Symbol + "-" + Data.Period;

            SaveData(fileName, sb);
        }
        /// <summary>
        ///     Sets the trvIndicators nodes
        /// </summary>
        private void SetTreeViewIndicators()
        {
            var trnAll = new TreeNode {
                Name = "trnAll", Text = Language.T("All"), Tag = false
            };
            var trnIndicators = new TreeNode {
                Name = "trnIndicators", Text = Language.T("Indicators"), Tag = false
            };
            var trnAdditional = new TreeNode {
                Name = "trnAdditional", Text = Language.T("Additional"), Tag = false
            };

            var trnOscillatorOfIndicators = new TreeNode
            {
                Name = "trnOscillatorOfIndicators",
                Text = Language.T("Oscillator of Indicators"),
                Tag  = false
            };

            var trnIndicatorsMaOscillator = new TreeNode
            {
                Name = "trnIndicatorMA",
                Text = Language.T("Indicator's MA Oscillator"),
                Tag  = false
            };

            var trnDateTime = new TreeNode {
                Name = "trnDateTime", Text = Language.T("Date/Time Functions"), Tag = false
            };

            var trnCustomIndicators = new TreeNode
            {
                Name = "trnCustomIndicators",
                Text = Language.T("Custom Indicators"),
                Tag  = false
            };

            TrvIndicators.Nodes.AddRange(new[]
            {
                trnAll, trnIndicators, trnAdditional, trnOscillatorOfIndicators,
                trnIndicatorsMaOscillator, trnDateTime, trnCustomIndicators
            });

            foreach (string name in IndicatorManager.GetIndicatorNames(slotType))
            {
                Indicator indicator = IndicatorManager.ConstructIndicator(name);
                indicator.Initialize(slotType);
                TypeOfIndicator type = indicator.IndParam.IndicatorType;

                Color nodeColor = LayoutColors.ColorControlText;
                if (indicator.OverrideMainIndicator)
                {
                    nodeColor = Color.Brown;
                }

                var trn = new TreeNode {
                    Tag = true, Name = name, Text = name, ForeColor = nodeColor
                };
                trnAll.Nodes.Add(trn);

                if (indicator.CustomIndicator)
                {
                    var trnCustom = new TreeNode {
                        Tag = true, Name = name, Text = name, ForeColor = nodeColor
                    };
                    trnCustomIndicators.Nodes.Add(trnCustom);
                }

                var trnGroups = new TreeNode {
                    Tag = true, Name = name, Text = name, ForeColor = nodeColor
                };

                switch (type)
                {
                case TypeOfIndicator.Indicator:
                    trnIndicators.Nodes.Add(trnGroups);
                    break;

                case TypeOfIndicator.Additional:
                    trnAdditional.Nodes.Add(trnGroups);
                    break;

                case TypeOfIndicator.OscillatorOfIndicators:
                    trnOscillatorOfIndicators.Nodes.Add(trnGroups);
                    break;

                case TypeOfIndicator.IndicatorsMA:
                    trnIndicatorsMaOscillator.Nodes.Add(trnGroups);
                    break;

                case TypeOfIndicator.DateTime:
                    trnDateTime.Nodes.Add(trnGroups);
                    break;
                }
            }
        }