• Тинькофф Банк-лучшие банковские продукты еще выгоднее
    Выбирайте продукт от банка Тинькофф
  • Уважаемые форумчане, друзья и посетители!
    Поступило предложение ( ссылка на обсуждение ) на сбор средств поддержания форума в рабочем состоянии с 1 июня ( оплата хостинга, бэкап ежедневный на другой хостинг и тд), отчетность будет предоставляться ежемесячно. Пока на ЮMoney ( яндекс деньги), доступно картой перевод, далее добавлю другие способы. Сумму перевода указывайте на ваш выбор исходя из своих возможностей.
    Форум продолжает свою работу благодаря Вашим пожертвованиям.

Error on calling 'OnBarUpdate' method for indicator 'M2' on bar 0: Индекс находился вне границ

Papercut110

New Member
NinjaTrader
Написал индикатор, ошибок в скрипте нет, запускаю, на графике - ничего не показывает, а в логе пишет Error on calling 'OnBarUpdate' method for indicator 'M2' on bar 0: Индекс находился вне границ массива. Нашёл в интернете у человека похожую проблему, ему порекомендовали прописать "проверку существования необходимого кол-ва баров." Не знаю как эо сделать и решит ли это проблему...
Может кто сталкивался с такой ошибкой?
 
  • Like
Реакции: Iman
Код:
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    /// <summary>
    /// Enter the description of your new custom indicator here
    /// </summary>
    [Description("Enter the description of your new custom indicator here")]
    public class M2 : Indicator
    {
        #region Variables
        // Wizard generated variables
        private string second_instr = @"6E 09-15";
        private int periodSMA = 20; // Default setting for PeriodSMA
        // User defined variables (add any user defined variables below)
        #endregion

        /// <summary>
        /// This method is used to configure the indicator and is called once before any bar data is loaded.
        /// </summary>
        protected override void Initialize()
        {
            Add(new Plot(Color.FromKnownColor(KnownColor.Red), PlotStyle.Line, "Delta"));
            Add(Second_instr,BarsPeriod.Id, BarsPeriod.Value);
         
            Overlay                = false;
            CalculateOnBarClose = false;
            BarsRequired = periodSMA;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
       if (BarsInProgress != 0) return;
        if(Closes[0][0]<=0 || Closes[1][0]<=0) return;
        if(CurrentBar < 1000 ) return;
         
        Spread.Set(Closes[0][0]/Closes[1][0]);
       Moving_Average.Set(SMA(Spread,periodSMA)[0]);
        Delta.Set(Closes[0][0]-(Closes[1][0]*SMA(Spread,periodSMA)[0]));
        }

        #region Properties
        [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries Spread
        {
            get { return Values[0]; }
        }
     
        [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries Moving_Average
        {
            get { return Values[1]; }
        }

        [Browsable(false)]    // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
        [XmlIgnore()]        // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
        public DataSeries Delta
        {
            get { return Values[2]; }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public int PeriodSMA
        {
            get { return periodSMA; }
            set { periodSMA = Math.Max(1, value); }
        }

        [Description("")]
        [GridCategory("Parameters")]
        public string Second_instr
        {
            get { return second_instr; }
            set { second_instr = value; }
        }


        #endregion
    }
}

#region NinjaScript generated code. Neither change nor remove.
// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    public partial class Indicator : IndicatorBase
    {
        private M2[] cacheM2 = null;

        private static M2 checkM2 = new M2();

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public M2 M2(int periodSMA, string second_instr)
        {
            return M2(Input, periodSMA, second_instr);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public M2 M2(Data.IDataSeries input, int periodSMA, string second_instr)
        {
            if (cacheM2 != null)
                for (int idx = 0; idx < cacheM2.Length; idx++)
                    if (cacheM2[idx].PeriodSMA == periodSMA && cacheM2[idx].Second_instr == second_instr && cacheM2[idx].EqualsInput(input))
                        return cacheM2[idx];

            lock (checkM2)
            {
                checkM2.PeriodSMA = periodSMA;
                periodSMA = checkM2.PeriodSMA;
                checkM2.Second_instr = second_instr;
                second_instr = checkM2.Second_instr;

                if (cacheM2 != null)
                    for (int idx = 0; idx < cacheM2.Length; idx++)
                        if (cacheM2[idx].PeriodSMA == periodSMA && cacheM2[idx].Second_instr == second_instr && cacheM2[idx].EqualsInput(input))
                            return cacheM2[idx];

                M2 indicator = new M2();
                indicator.BarsRequired = BarsRequired;
                indicator.CalculateOnBarClose = CalculateOnBarClose;
#if NT7
                indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                indicator.MaximumBarsLookBack = MaximumBarsLookBack;
#endif
                indicator.Input = input;
                indicator.PeriodSMA = periodSMA;
                indicator.Second_instr = second_instr;
                Indicators.Add(indicator);
                indicator.SetUp();

                M2[] tmp = new M2[cacheM2 == null ? 1 : cacheM2.Length + 1];
                if (cacheM2 != null)
                    cacheM2.CopyTo(tmp, 0);
                tmp[tmp.Length - 1] = indicator;
                cacheM2 = tmp;
                return indicator;
            }
        }
    }
}

// This namespace holds all market analyzer column definitions and is required. Do not change it.
namespace NinjaTrader.MarketAnalyzer
{
    public partial class Column : ColumnBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.M2 M2(int periodSMA, string second_instr)
        {
            return _indicator.M2(Input, periodSMA, second_instr);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.M2 M2(Data.IDataSeries input, int periodSMA, string second_instr)
        {
            return _indicator.M2(input, periodSMA, second_instr);
        }
    }
}

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    public partial class Strategy : StrategyBase
    {
        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.M2 M2(int periodSMA, string second_instr)
        {
            return _indicator.M2(Input, periodSMA, second_instr);
        }

        /// <summary>
        /// Enter the description of your new custom indicator here
        /// </summary>
        /// <returns></returns>
        public Indicator.M2 M2(Data.IDataSeries input, int periodSMA, string second_instr)
        {
            if (InInitialize && input == null)
                throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");

            return _indicator.M2(input, periodSMA, second_instr);
        }
    }
}
#endregion
 
Последнее редактирование модератором:
Papercut110, будет удобно всем, если код заключать в соотвествующий тег, обратите внимание на это - ссылка , или прикладывайте текстовый файл с кодом.
 
Непонятно, что вы хотите получить этими 2 строчками:
Код:
Moving_Average.Set(SMA(Spread,periodSMA)[0]);
Delta.Set(Closes[0][0]-(Closes[1][0]*SMA(Spread,periodSMA)[0]));

Если еще две линии нарисовать, то не хватает их объявления в Initialize().
А если просто серию данных хотите иметь, то переменные надо явно объявлять.
Ну, или удалите эти строчки будет вам счастье. ))
 
NT8, я самоучка, поясните пожалуйста... Мне по сути нужна одна линия - Delta, которая находится по формуле Delta.Set(Closes[0][0]-(Closes[1][0]*SMA(Spread,periodSMA)[0]));
Сначала я пытался запрограммировать отношение одного инстр к другому и наложить на них сма вот этими двумя строками Spread.Set(Closes[0][0]/Closes[1][0]);
Moving_Average.Set(SMA(Spread,periodSMA)[0]); , а потом вычислить Дельту вычитая из одного инстр другой, умноженный на значение сма спреда... Это мой первый индикатор так что не судите строго...:sorry:
 
Назад
Верх Низ