Ejemplo n.º 1
0
        /// <summary>
        /// Show indicators in the selected bars.
        /// </summary>
        void ShowIndicators(string input)
        {
            string pattern    = @"^ind (?<numb>\d+)$";
            Regex  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--;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                for (int iSlot = 0; iSlot < Data.Strategy.Slots; iSlot++)
                {
                    Indicator indicator = Indicator_Store.ConstructIndicator(Data.Strategy.Slot[iSlot].IndicatorName, Data.Strategy.Slot[iSlot].SlotType);

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

                tbxOutput.Text += Environment.NewLine + "Indicators for bar " + (bar + 1).ToString() + Environment.NewLine +
                                  "-----------------" + Environment.NewLine + sb.ToString();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Calculates the strategy.
        /// </summary>
        /// <param name="recalcIndicators">true - to recalculate all the indicators.</param>
        void Calculate(bool recalcIndicators)
        {
            bool isUPBVChanged = Data.Strategy.AdjustUsePreviousBarValue();

            // Calculates the indicators by slots if it's necessary
            if (recalcIndicators)
            {
                foreach (IndicatorSlot indSlot in Data.Strategy.Slot)
                {
                    string    indicatorName = indSlot.IndicatorName;
                    SlotTypes slotType      = indSlot.SlotType;
                    Indicator indicator     = Indicator_Store.ConstructIndicator(indicatorName, slotType);

                    indicator.IndParam = indSlot.IndParam;

                    indicator.Calculate(slotType);

                    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;
                }
            }

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

            // Logging
            Data.Log("Calculate the strategy");

            // Calculates the backtest
            Backtester.Calculate();
            Backtester.CalculateAccountStats();

            Data.IsResult = true;
            if (isUPBVChanged)
            {
                RebuildStrategyLayout();
            }
            smallIndicatorChart.InitChart();
            smallIndicatorChart.Invalidate();
            smallBalanceChart.SetChartData();
            smallBalanceChart.InitChart();
            smallBalanceChart.Invalidate();
            SetupJournal();
            infpnlAccountStatistics.Update(
                Backtester.AccountStatsParam,
                Backtester.AccountStatsValue,
                Backtester.AccountStatsFlags,
                Language.T("Account Statistics"));

            return;
        }
        /// <summary>
        /// Loads the default parameters for the selected indicator.
        /// </summary>
        void BtnDefault_Click(object sender, EventArgs e)
        {
            Indicator indicator = Indicator_Store.ConstructIndicator(indicatorName, slotType);

            UpdateFromIndicatorParam(indicator.IndParam);
            SetDefaultGroup();
            CalculateIndicator(true);
            UpdateBalanceChart();

            return;
        }
        /// <summary>
        /// Loads an Indicator
        /// </summary>
        void TrvIndicatorsLoadIndicator(TreeNode treeNode)
        {
            Indicator indicator = Indicator_Store.ConstructIndicator(trvIndicators.SelectedNode.Text, slotType);

            UpdateFromIndicatorParam(indicator.IndParam);
            SetDefaultGroup();
            CalculateIndicator(true);
            UpdateBalanceChart();

            return;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Sets Use prv bar value automaticaly
        /// </summary>
        public bool AdjustUsePreviousBarValue()
        {
            bool isSomethingChanged = false;

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

            for (int slot = 0; slot < Slots; slot++)
            {
                isSomethingChanged = SetUsePrevBarValueCheckBox(slot) ? true : isSomethingChanged;
            }

            // Reclaculates 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      = Indicator_Store.ConstructIndicator(sIndicatorName, slotType);

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

                    indicator.Calculate(slotType);

                    // 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);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// The default constructor
        /// </summary>
        public Actions()
        {
            StartPosition     = FormStartPosition.CenterScreen;
            Size              = new Size(790, 590);
            MinimumSize       = new Size(500, 375);
            Icon              = Data.Icon;
            Text              = Data.ProgramName;
            FormClosing      += new FormClosingEventHandler(Actions_FormClosing);
            Application.Idle += new EventHandler(Application_Idle);

            // Load a data file
            UpdateStatusLabel("Loading historical data...");
            if (LoadInstrument(false) != 0)
            {
                LoadInstrument(true);
                string messageText = Language.T("Forex Strategy Builder cannot load a historical data file and is going to use integrated data!");
                MessageBox.Show(messageText, Language.T("Data File Loading"), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            // Prepare custom indicators
            if (Configs.LoadCustomIndicators)
            {
                UpdateStatusLabel("Loading custom indicators...");
                Custom_Indicators.LoadCustomIndicators();
            }
            else
            {
                Indicator_Store.CombineAllIndicators();
            }

            // Load a strategy
            UpdateStatusLabel("Loading strategy...");
            string sStrategyPath = Data.StrategyPath;

            if (Configs.RememberLastStr && Configs.LastStrategy != "")
            {
                string sLastStrategy = Path.GetDirectoryName(Configs.LastStrategy);
                if (sLastStrategy != "")
                {
                    sLastStrategy = Configs.LastStrategy;
                }
                else
                {
                    string sPath = Path.Combine(Data.ProgramDir, Data.DefaultStrategyDir);
                    sLastStrategy = Path.Combine(sPath, Configs.LastStrategy);
                }
                if (File.Exists(sLastStrategy))
                {
                    sStrategyPath = sLastStrategy;
                }
            }

            if (OpenStrategy(sStrategyPath) == 0)
            {
                AfterStrategyOpening(false);
            }

            Calculate(false);

            Check_Update liveContent = new Check_Update(Data.SystemDir, miLiveContent, miForex);

            Registrar registrar = new Registrar();

            registrar.Register();

            // Starting tips
            if (Configs.ShowStartingTip)
            {
                Starting_Tips startingTips = new Starting_Tips();
                startingTips.Show();
            }

            UpdateStatusLabel("Loading user interface...");

            return;
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Load Source Files
        /// </summary>
        public static void LoadCustomIndicators()
        {
            _indicatorManager = new Indicator_Compilation_Manager();

            if (!Directory.Exists(Data.SourceFolder))
            {
                System.Windows.Forms.MessageBox.Show("Custom indicators folder does not exist!", Language.T("Custom Indicators"));
                Indicator_Store.ResetCustomIndicators(null);
                Indicator_Store.CombineAllIndicators();
                return;
            }

            string[] pathInputFiles = Directory.GetFiles(Data.SourceFolder, "*.cs");
            if (pathInputFiles.Length == 0)
            {
                System.Windows.Forms.MessageBox.Show("No custom indicator files found out!", Language.T("Custom Indicators"));
                Indicator_Store.ResetCustomIndicators(null);
                Indicator_Store.CombineAllIndicators();
                return;
            }

            StringBuilder errorReport = new StringBuilder();

            errorReport.AppendLine("<h1>" + Language.T("Custom Indicators") + "</h1>");
            bool isError = false;

            foreach (string filePath in pathInputFiles)
            {
                string errorMessages;
                _indicatorManager.LoadCompileSourceFile(filePath, out errorMessages);

                if (!string.IsNullOrEmpty(errorMessages))
                {
                    isError = true;

                    errorReport.AppendLine("<h2>File name: " + Path.GetFileName(filePath) + "</h2>");
                    string error = errorMessages.Replace(Environment.NewLine, "</br>");
                    error = error.Replace("\t", "&nbsp; &nbsp; &nbsp;");
                    errorReport.AppendLine("<p>" + error + "</p>");
                }
            }

            // Adds the custom indicators
            Indicator_Store.ResetCustomIndicators(_indicatorManager.CustomIndicatorsList);
            Indicator_Store.CombineAllIndicators();

            if (isError)
            {
                Fancy_Message_Box msgBox = new Fancy_Message_Box(errorReport.ToString(), Language.T("Custom Indicators"));
                msgBox.BoxWidth  = 550;
                msgBox.BoxHeight = 340;
                msgBox.TopMost   = true;
                msgBox.Show();
            }

            if (Configs.ShowCustomIndicators)
            {
                ShowLoadedCustomIndicators();
            }

            return;
        }
Ejemplo n.º 8
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.IsProgramRC)
            {
                stage = " " + "RC";
            }

            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.ToString() + 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 iSlot = 0; iSlot < Data.Strategy.Slots; iSlot++)
            {
                string strSlotType = "";
                switch (Data.Strategy.Slot[iSlot].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;

                default:
                    break;
                }

                sb.Append(strSlotType + "\t");
                foreach (IndicatorComp indComp in Data.Strategy.Slot[iSlot].Component)
                {
                    sb.Append("\t");
                }
            }
            sb.Append(Environment.NewLine);


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

            for (int iSlot = 0; iSlot < Data.Strategy.Slots; iSlot++)
            {
                Indicator indicator = Indicator_Store.ConstructIndicator(Data.Strategy.Slot[iSlot].IndicatorName,
                                                                         Data.Strategy.Slot[iSlot].SlotType);

                sb.Append(indicator.ToString() + "\t");
                foreach (IndicatorComp indComp in Data.Strategy.Slot[iSlot].Component)
                {
                    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 iSlot = 0; iSlot < Data.Strategy.Slots; iSlot++)
            {
                sb.Append("\t");
                foreach (IndicatorComp indComp in Data.Strategy.Slot[iSlot].Component)
                {
                    sb.Append(indComp.CompName + "\t");
                }
            }
            sb.Append(Environment.NewLine);

            for (int bar = 0; bar < Data.Bars; bar++)
            {
                sb.Append(Data.Time[bar].ToString(sDF) + "\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].ToString() + "\t");

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

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

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

            StringBuilder 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 = Indicator_Store.ConstructIndicator(indicatorName, slotType);

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

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

                try
                {
                    indicator.Calculate(slotType);
                }
                catch (System.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(slotType);
                }
                catch (System.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;

                        default:
                            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);
        }
Ejemplo n.º 10
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.
            Strategy tempStrategy = new Strategy(openFilters, closeFilters);

            // 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;
            tempStrategy.DataPeriod = (DataPeriods)Enum.Parse(typeof(DataPeriods), xmlDocStrategy.GetElementsByTagName("instrumentPeriod")[0].InnerText);

            // Permanent Stop Loss
            tempStrategy.PermanentSL    = Math.Abs(int.Parse(xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].InnerText)); // Math.Abs() removes the negative sign from previous versions.
            tempStrategy.UsePermanentSL = bool.Parse(xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].Attributes["usePermanentSL"].InnerText);
            try
            {
                tempStrategy.PermanentSLType = (PermanentProtectionType)Enum.Parse(typeof(PermanentProtectionType), xmlDocStrategy.GetElementsByTagName("permanentStopLoss")[0].Attributes["permanentSLType"].InnerText);
            }
            catch
            {
                tempStrategy.PermanentSLType = PermanentProtectionType.Relative;
            }

            // Permanent Take Profit
            tempStrategy.PermanentTP    = int.Parse(xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].InnerText);
            tempStrategy.UsePermanentTP = bool.Parse(xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].Attributes["usePermanentTP"].InnerText);
            try
            {
                tempStrategy.PermanentTPType = (PermanentProtectionType)Enum.Parse(typeof(PermanentProtectionType), xmlDocStrategy.GetElementsByTagName("permanentTakeProfit")[0].Attributes["permanentTPType"].InnerText);
            }
            catch
            {
                tempStrategy.PermanentTPType = PermanentProtectionType.Relative;
            }

            // Break Even
            try
            {
                tempStrategy.BreakEven    = int.Parse(xmlDocStrategy.GetElementsByTagName("breakEven")[0].InnerText);
                tempStrategy.UseBreakEven = bool.Parse(xmlDocStrategy.GetElementsByTagName("breakEven")[0].Attributes["useBreakEven"].InnerText);
            }
            catch { }

            // 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);

            // 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;

                SlotTypes slotType = (SlotTypes)Enum.Parse(typeof(SlotTypes), xmlSlotList[slot].Attributes["slotType"].InnerText);

                // Logical group
                if (slotType == SlotTypes.OpenFilter || slotType == SlotTypes.CloseFilter)
                {
                    XmlAttributeCollection attributes = xmlSlotList[slot].Attributes;
                    XmlNode nodeGroup = attributes.GetNamedItem("logicalGroup");
                    string  defGroup  = GetDefaultGroup(slotType, slot, tempStrategy.CloseSlot);
                    if (nodeGroup != null)
                    {
                        string group = nodeGroup.InnerText;
                        tempStrategy.Slot[slot].LogicalGroup = group;
                        if (group != defGroup && group.ToLower() != "all" && !Configs.UseLogicalGroups)
                        {
                            System.Windows.Forms.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"),
                                System.Windows.Forms.MessageBoxButtons.OK,
                                System.Windows.Forms.MessageBoxIcon.Information);
                            Configs.UseLogicalGroups = true;
                        }
                    }
                    else
                    {
                        tempStrategy.Slot[slot].LogicalGroup = defGroup;
                    }
                }

                // Indicator name.
                string    indicatorName = xmlSlotTagList[0].InnerText;
                Indicator indicator     = Indicator_Store.ConstructIndicator(indicatorName, slotType);

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

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

                        xmlListParamNode = xmlListParamNode.NextSibling;
                        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;
                        int     numParam        = int.Parse(xmlSlotTagList[tag].Attributes["paramNumber"].InnerText);
                        indicator.IndParam.NumParam[numParam].Caption = xmlNumParamNode.InnerText;

                        xmlNumParamNode = xmlNumParamNode.NextSibling;
                        string sNumParamValue = xmlNumParamNode.InnerText;
                        sNumParamValue = sNumParamValue.Replace(',', Data.PointChar);
                        sNumParamValue = sNumParamValue.Replace('.', Data.PointChar);
                        float fValue = float.Parse(sNumParamValue);

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

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

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

                // Calculate the indicator.
                indicator.Calculate(slotType);
                tempStrategy.Slot[slot].IndicatorName  = indicator.IndicatorName;
                tempStrategy.Slot[slot].IndParam       = indicator.IndParam;
                tempStrategy.Slot[slot].Component      = indicator.Component;
                tempStrategy.Slot[slot].SeparatedChart = indicator.SeparatedChart;
                tempStrategy.Slot[slot].SpecValue      = indicator.SpecialValues;
                tempStrategy.Slot[slot].MinValue       = indicator.SeparatedChartMinValue;
                tempStrategy.Slot[slot].MaxValue       = indicator.SeparatedChartMaxValue;
                tempStrategy.Slot[slot].IsDefined      = true;
            }

            return(tempStrategy);
        }
        /// <summary>
        /// Calculates the selected indicator.
        /// </summary>
        void CalculateIndicator(bool bCalculateStrategy)
        {
            if (!Data.IsData || !Data.IsResult || !isPaint)
            {
                return;
            }

            SetOppositeSignalBehaviour();
            SetClosingLogicConditions();

            Indicator indicator = Indicator_Store.ConstructIndicator(indicatorName, 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;
                if (CheckParam[i].Text == "Use previous bar value")
                {
                    indicator.IndParam.CheckParam[i].Enabled = true;
                }
                else
                {
                    indicator.IndParam.CheckParam[i].Enabled = 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;

            return;
        }
        /// <summary>
        /// Sets the trvIndicators nodes
        /// </summary>
        void SetTreeViewIndicators()
        {
            TreeNode trnAll = new TreeNode();

            trnAll.Name = "trnAll";
            trnAll.Text = Language.T("All");
            trnAll.Tag  = false;

            TreeNode trnIndicators = new TreeNode();

            trnIndicators.Name = "trnIndicators";
            trnIndicators.Text = Language.T("Indicators");
            trnIndicators.Tag  = false;

            TreeNode trnAdditional = new TreeNode();

            trnAdditional.Name = "trnAdditional";
            trnAdditional.Text = Language.T("Additional");
            trnAdditional.Tag  = false;

            TreeNode trnOscillatorOfIndicators = new TreeNode();

            trnOscillatorOfIndicators.Name = "trnOscillatorOfIndicators";
            trnOscillatorOfIndicators.Text = Language.T("Oscillator of Indicators");
            trnOscillatorOfIndicators.Tag  = false;

            TreeNode trnIndicatorsMAOscillator = new TreeNode();

            trnIndicatorsMAOscillator.Name = "trnIndicatorMA";
            trnIndicatorsMAOscillator.Text = Language.T("Indicator's MA Oscillator");
            trnIndicatorsMAOscillator.Tag  = false;

            TreeNode trnDateTime = new TreeNode();

            trnDateTime.Name = "trnDateTime";
            trnDateTime.Text = Language.T("Date/Time Functions");
            trnDateTime.Tag  = false;

            TreeNode trnCustomIndicators = new TreeNode();

            trnCustomIndicators.Name = "trnCustomIndicators";
            trnCustomIndicators.Text = Language.T("Custom Indicators");
            trnCustomIndicators.Tag  = false;

            trvIndicators.Nodes.AddRange(new TreeNode[]
            {
                trnAll, trnIndicators, trnAdditional, trnOscillatorOfIndicators,
                trnIndicatorsMAOscillator, trnDateTime, trnCustomIndicators
            });

            foreach (string indicatorName in Indicator_Store.GetIndicatorNames(slotType))
            {
                TreeNode trn = new TreeNode();
                trn.Tag  = true;
                trn.Name = indicatorName;
                trn.Text = indicatorName;
                trnAll.Nodes.Add(trn);

                Indicator       indicator = Indicator_Store.ConstructIndicator(indicatorName, slotType);
                TypeOfIndicator type      = indicator.IndParam.IndicatorType;

                if (indicator.CustomIndicator)
                {
                    TreeNode trnCustom = new TreeNode();
                    trnCustom.Tag  = true;
                    trnCustom.Name = indicatorName;
                    trnCustom.Text = indicatorName;
                    trnCustomIndicators.Nodes.Add(trnCustom);
                }

                TreeNode trnGroups = new TreeNode();
                trnGroups.Tag  = true;
                trnGroups.Name = indicatorName;
                trnGroups.Text = indicatorName;

                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);
                }
            }

            return;
        }