Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

Error on calling 'OnStateChange' method: You are accessing an index with a value

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Error on calling 'OnStateChange' method: You are accessing an index with a value

    Hi,

    Let me start off by saying that I have no idea how to code or use NinjaScript, but I have been getting the below error in the log when I try to enable my strategy.

    Error on calling 'OnStateChange' method: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

    I want to create a bot that does the following:

    The bot should continuously check if the previous candle crossed above or below the 20 day SMA. If it crossed above, I want to place a buy limit order at the high of that candle; if it crossed below, then I want the to short at the low of the candle. When the trade is entered, I want to set my stop loss at the high (if crossing below) or the low (if crossing above) of the previous candle. The profit target should be set to a 1:1 risk reward ratio.

    I've tried to follow the other numerous forum suggestions for this exact issue, but none of them have worked for me. I have no idea how to use Visual Studio or debug code, so that isn't particularly helpful either. I began using the strategy builder, but could not figure out how to set the profit target equal to my stop loss, so I tried to code it manually from there.

    My code is as follows:

    region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion

    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class MyCustomStrategy : Strategy
    {
    private SMA SMA1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "MyCustomStrategy";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    SMA1 = SMA(Close, 20);
    SetStopLoss(@"BuyHigh", CalculationMode.Currency, Low[1], false);
    SetStopLoss(@"SellLow", CalculationMode.Currency, High[1], false);
    SetProfitTarget(@"BuyHigh", CalculationMode.Price, Position.AveragePrice + (Position.AveragePrice - Low[1]));
    SetProfitTarget(@"SellLow", CalculationMode.Price, Position.AveragePrice - (High[1] - Position.AveragePrice));
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if (CrossAbove(Close, SMA1[0], 1)
    && (Position.MarketPosition == MarketPosition.Flat))
    {
    EnterLongLimit(Convert.ToInt32(DefaultQuantity), High[1], @"BuyHigh");
    }

    // Set 2
    if (CrossBelow(Close, SMA1[0], 1)
    && (Position.MarketPosition == MarketPosition.Flat))
    {
    EnterShortLimit(Convert.ToInt32(DefaultQuantity), Low[1], @"SellLow");
    }

    }
    }
    }


    Thanks for any help you can provide!

    #2
    Hello anarchyturtle,

    Thank you for your post.

    Please see this forum post on getting started with NinjaScript:
    https://forum.ninjatrader.com/forum/...040#post786040

    And also this post on indexing errors:
    https://forum.ninjatrader.com/forum/...13#post10485133


    Additionally, in State.DataLoaded you are using Low[1] and High[1] to calculate your profit targets / stop losses. This is likely the cause of the indexing error.

    When no bars have been processed yet, you are trying to access a value from 1 bars ago when no bars exist yet.

    You will need to set the profit target / stop loss to an initial number of ticks before the entry, and then after the position is long or short call the profit target and stop loss again to use Positon.AveragePrice and access Low[1] and High[1] values.

    Position - https://ninjatrader.com/support/helpGuides/nt8/position.htm

    Please see the sample script linked below which demonstrate modifying the price of your stops and targets:
    https://ninjatrader.com/support/help...of_stop_lo.htm

    I recommend doing this from recommend from OnPositionUpdate() after calling TriggerCustomEvent().

    OnPositionUpdate() - https://ninjatrader.com/support/help...tionupdate.htm
    TriggerCustomEvent() - https://ninjatrader.com/support/help...ustomevent.htm

    Please see this sample script as well, which demonstrates using TriggerCustomEvent():
    https://ninjatrader.com/support/help...to_output_.htm

    Please let me know if you have any other questions.
    Gaby V.NinjaTrader Customer Service

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by YongJane, Today, 01:00 AM
    0 responses
    2 views
    0 likes
    Last Post YongJane  
    Started by MSerag, 05-06-2024, 11:52 PM
    4 responses
    25 views
    0 likes
    Last Post MSerag
    by MSerag
     
    Started by TraderCro, Today, 12:13 AM
    0 responses
    2 views
    0 likes
    Last Post TraderCro  
    Started by Skifree, Yesterday, 11:47 PM
    0 responses
    7 views
    0 likes
    Last Post Skifree
    by Skifree
     
    Started by Skifree, Yesterday, 11:41 PM
    0 responses
    6 views
    0 likes
    Last Post Skifree
    by Skifree
     
    Working...
    X