Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Swing causing strategy error

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

    Swing causing strategy error

    I have included the code for a strategy that relies on the Swing indicator. Regardless the time frame, if I try to use a "Strength" more than 2 I get the following error: "Error on calling "OnBarUpdate" method on bar ###, you are accessing an index with a invalid value." If I just add the Swing indicator to a chart, I can choose any strength. I've adjusted everything I can think of in the strategy to no avail. If someone would take a gander and let me know if anything sticks out, I'd appreciate it. I apoligize for all the junk in there, it's how I track the process. Thanks.

    Code:
    
    #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 A00530swing : Strategy
    
    {
    
    private BOP BOP1;
    
    // private BOP BOP2;
    
    // private ATR ATR1;
    
    // private OBV OBV1;
    
    private ATRTrailingStopHiLo ATRTrailingStop1;
    
    private bool TradeSwitch;
    
    private double MyLongStop;
    
    private double MyShortStop;
    
    // private StdDev StdDev1;
    
    private Range Range1;
    
    private EMA SMA1;
    
    // private SMA SMA2;
    
    private VMA VMA1;
    
    // private MIN MIN1;
    
    // private MAX MAX1;
    
    private Swing Swing1;
    
    private ATRTrailingStopHiLo ATRTrailingStop2;
    
    private MAMA MAMA1;
    
    private Account myAccount;
    
    private Order stopOrder = null;
    
    
    
    protected override void OnStateChange()
    
    {
    
    if (State == State.SetDefaults)
    
    {
    
    Description = @"Enter the description for your new custom Strategy here.";
    
    Name = "A00530swing";
    
    Calculate = Calculate.OnEachTick;
    
    EntriesPerDirection = 1;
    
    EntryHandling = EntryHandling.AllEntries;
    
    IsExitOnSessionCloseStrategy = false;
    
    ExitOnSessionCloseSeconds = 30;
    
    IsFillLimitOnTouch = false;
    
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    
    OrderFillResolution = OrderFillResolution.Standard;
    
    // OrderFillResolutionType = BarsPeriodType.Tick;
    
    // OrderFillResolutionValue = 1;
    
    Slippage = 1;
    
    StartBehavior = StartBehavior.AdoptAccountPosition;
    
        IsAdoptAccountPositionAware = true;
    
    IncludeCommission = true;
    
    TimeInForce = TimeInForce.Day;
    
    TraceOrders = true;
    
    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;
    
    
    
    StopLoss = 100;
    
    // ProfitTarget = 10;
    
    ProfitMultiplier = 4;
    
    // BeginningLoss = 20;
    
    // ProfitMultiplier = 1.5;
    
    // BeginningLoss = .3;
    
    // ATRRange = 14;
    
    // Period1 = 3.5;
    
    // Period2 = 1.5;
    
    // FastLimit = .5;
    
    // SlowLimit = .05;
    
    // Acceleration = .02;
    
    // AccelerationMax = .2;
    
    // AccelerationStep = .02;
    
    Strength = 1;
    
    // Multi = 3.5;
    
    TradeSwitch = false;
    
    // MyLongStop = 1;
    
    // MyShortStop = 1;
    
    // Indi = 4;
    
    // MyProfit = 1;
    
    }
    
    else if (State == State.Configure)
    
    {
    
    
    
    AddDataSeries(Data.BarsPeriodType.Second, 1);
    
    // AddDataSeries(Data.BarsPeriodType.Minute, 180);
    
    
    
    
    
    }
    
    else if (State == State.DataLoaded)
    
    {
    
    BOP1 = BOP(Close, 3);
    
    // BOP2 = BOP(Close, 9);
    
    // ATR1 = ATR(Close, Period);
    
    // OBV1 = OBV(Closes[1]);
    
    // ATRTrailingStop1 = ATRTrailingStopHiLo(Range1, 1, Period1);
    
    // StdDev1 = StdDev(Close, Period);
    
    Range1 = Range(Close);
    
    SMA1 = EMA(Close, 9);
    
    // SMA2 = SMA(Close, 105);
    
    VMA1 = VMA(Range1, 5, 5);
    
    // MIN1 = MIN(Low, 3);
    
    // MAX1 = MAX(High, 3);
    
    // ATRTrailingStop2 = ATRTrailingStopHiLo(Range1, 1, Period2);
    
    // MAMA1 = MAMA(FastLimit, SlowLimit);
    
    Swing1 = Swing(Strength);
    
    
    
    // BOP1.Plots[0].PlotStyle = PlotStyle.Hash;
    
    // SMA1.Plots[0].Brush = Brushes.Green;
    
    // SMA2.Plots[0].Brush = Brushes.Red;
    
    // AddChartIndicator(BOP1);
    
    // AddChartIndicator(ATRTrailingStop1);
    
    // AddChartIndicator(ATRTrailingStop2);
    
    // AddChartIndicator(MIN1);
    
    // AddChartIndicator(MAX1);
    
    AddChartIndicator(SMA1);
    
    // AddChartIndicator(MAMA1);
    
    AddChartIndicator(Swing1);
    
    // AddChartIndicator(SMA2);
    
    
    
    
    
    
    
    }
    
    }
    
    
    
    
    // protected override void OnConnectionStatusUpdate(ConnectionStatusEventArgs connectionStatusUpdate)
    
    // {
    
    // if(connectionStatusUpdate.Status == ConnectionStatus.ConnectionLost)
    
      // {
    
        // SendMail("[email protected]", "connectionlost", "connectionlost");
    
      // }
    
    // if(connectionStatusUpdate.Status == ConnectionStatus.Disconnected)
    
      // {
    
        // SendMail("[email protected]", "disconnected", "disconnected");
    
      // }
    
    // if(connectionStatusUpdate.Status == ConnectionStatus.Connected)
    
      // {
    
        // SendMail("[email protected]", "reconnected", "reconnected");
    
      // }
    
    //
    
    // }
    
    protected override void OnBarUpdate()
    
    {
    
    // if (BarsInProgress != 0)
    
    // return;
    
    
    
    
    
    if (CurrentBars[0] < 20 || CurrentBars[1] < 20)
    
    return;
    
    
    
    
    
    SetProfitTarget(CalculationMode.Ticks, ProfitMultiplier * (VMA1[1]/TickSize));
    
    //
    
    if (Swing1.SwingHigh[1] != 0)
    
    {
    
    SetStopLoss("Long", CalculationMode.Price, Swing1.SwingLow[1] - TickSize, false);
    
    }
    
    else
    
    {
    
    SetStopLoss("Long", CalculationMode.Ticks, StopLoss, false);
    
    }
    
    
    
    if (Swing1.SwingLow[1] != 0)
    
    {
    
    SetStopLoss("Short", CalculationMode.Price, Swing1.SwingHigh[1] + TickSize, false);
    
    }
    
    else
    
    {
    
    SetStopLoss("Short", CalculationMode.Ticks, StopLoss, false);
    
    }
    
    
    
    
    
    // Set 1
    
    if ((ToTime(Time[0]) < 135500  || ToTime(Time[0]) > 150000)
    
    
    
    && Position.MarketPosition != MarketPosition.Long
    
    && Closes[1][0] > SMA1[0]
    
    && BarsInProgress == 0
    
    && Swing1.SwingHigh[1] != 0
    
    // && CrossAbove(Closes[1], Swing1.SwingHigh[1] + TickSize, 1))
    
    // && Closes[1][0] > (Swing1.SwingHigh[0] - (5 * TickSize))
    
    && IsFirstTickOfBar == true)
    
    // && TradeSwitch == true)
    
    {
    
    // EnterLong("Long") ;
    
    EnterLongStopLimit(0, false, Convert.ToInt32(DefaultQuantity), High[Math.Max(0, Swing1.SwingHighBar(0, 1, 20))] + (2 * TickSize), High[Math.Max(0, Swing1.SwingHighBar(0, 1, 20))] + TickSize,  "Long");
    
    // TradeSwitch = false;
    
    }
    
    
    
    if ((ToTime(Time[0]) < 135500  || ToTime(Time[0]) > 150000)
    
    
    
    && Position.MarketPosition != MarketPosition.Short
    
    && Swing1.SwingLow[1] != 0
    
    && Closes[1][0] < SMA1[0]
    
    // && CrossBelow(Closes[1], Swing1.SwingLow[1] - TickSize, 1)
    
    && BarsInProgress == 0
    
    // && Closes[1][0] < (Swing1.SwingLow[0] + (5 * TickSize))
    
    && IsFirstTickOfBar == true)
    
    // && TradeSwitch == true)
    
    {
    
    // EnterShort("Short");
    
    EnterShortStopLimit(0, false, Convert.ToInt32(Position.Quantity), Low[Math.Min(0, Swing1.SwingHighBar(0, 1, 20))] - (2 * TickSize), Low[Math.Min(0, Swing1.SwingHighBar(0, 1, 20))] - TickSize, "Short");
    
    // TradeSwitch = false;
    
    }
    
    
    
    
    
    
    
    
    // Time
    
    if ((ToTime(Time[0]) > 135500 && ToTime(Time[0]) < 150000)
    
    && (Position.MarketPosition != MarketPosition.Flat)
    
    && BarsInProgress == 1)
    
    {
    
    if (Position.MarketPosition == MarketPosition.Long)
    
    {
    
    ExitLong(1, Position.Quantity, "time", "");
    
    }
    
    else if (Position.MarketPosition == MarketPosition.Short)
    
    {
    
    ExitShort(1, Position.Quantity, "time", "");
    
    }
    
    }
    
    
    
    
    
    
    
    
    
    
    }
    
    
    
    
    #region Properties
    
    // [NinjaScriptProperty]
    
    // [Range(1, int.MaxValue)]
    
    // [Display(Name="BeginningLoss", Order=1, GroupName="Parameters")]
    
    // public int BeginningLoss
    
    // { get; set; }
    
    
    
    [NinjaScriptProperty]
    
    [Range(0.0001, double.MaxValue)]
    
    [Display(Name="StopLoss", Order=2, GroupName="Parameters")]
    
    public double StopLoss
    
    { get; set; }
    
    
    
    // [NinjaScriptProperty]
    
    // [Range(0.0001, double.MaxValue)]
    
    // [Display(Name="ProfitTarget", Order=3, GroupName="Parameters")]
    
    // public double ProfitTarget
    
    // { get; set; }
    
    
    
    
    [NinjaScriptProperty]
    
    [Range(0.01, double.MaxValue)]
    
    [Display(Name="ProfitMultiplier", Order=4, GroupName="Parameters")]
    
    public double ProfitMultiplier
    
    { get; set; }
    
    
    
    
    
    
    [NinjaScriptProperty]
    
    [Range(1, int.MaxValue)]
    
    [Display(Name="Strength", Description="ATR period", Order=11, GroupName="Parameters")]
    
    public int Strength
    
    { get; set; }
    
    
    
    
    #endregion
    
    
    
    
    }
    
    }
    ​

    #2
    Hello zrobfrank,

    Thanks for your post.

    I do not see anything specifically wrong standing out in the script you shared.

    To identify the exact line of code causing the error to occur, you should debug the script by reducing the code and adding prints throughout the script that print out all the indexes that you are accessing and the CurrentBar one line above where you are accessing the index.

    When identifying an issue, it is extremely important to have extremely simple test scripts and very simple steps to reproduce that only have the bare minimum code necessary to reproduce the behavior without any other code

    First, its great to create a copy of the script so that the original work is kept safe. To create a copy of a script, right-click in the code of the script in the NinjaScript Editor window and select 'Save as'. Once the copy is created, the copy can be modified in any way without losing the original work.

    The next step is to start commenting out code.Comment out a section of code to see if the behavior persists. If you see the error stop after commenting out a section of code, the error is likely caused by something in that section of code. Then, you could narrow in on the offending code using prints.

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    https://ninjatrader.com/support/foru...121#post791121

    Here is a forum thread about this error which you might find helpful: https://forum.ninjatrader.com/forum/...234#post844234
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      Its this type of logic "Low[Math.Max(0, Swing1.SwingHighBar(0, 1, 20))]" That causes an error, where if I strip everything else back it thinks I'm trying to access Bar -1. The following logic will creat the error as well " if (Swing2.SwingLow[1] > 0)

      {

      SetStopLoss("Long", CalculationMode.Price, Swing2.SwingLow[1] - TickSize, false);

      }

      I have tried some prints to debug, but the strategy shuts down as soon as it's started and I haven't found anything to print that would give me a clue how to fix it. Thank you.

      Comment


        #4
        Hello zrobfrank,

        Thanks for your notes.

        I do not see where Swing2 is being defined in the code you previously shared so I am unsure how that is set up.

        I have tested printing out Low[Math.Max(0, Swing1.SwingHighBar(0, 1, 20))] in a very simple indicator and see that the prints are appearing in the output window without an error. See the attached screenshot. I have also attached the script used to test this so that you could test it on your end.

        I suggest that you make a very simple test script similar to the one attached that includes only those Swing1 and Swing2 values to see if that is in fact the code causing the error. If you see the simple test script working for the Swing1 and Swing2 variables, compare the simple test script to your original script to see if they are the same. If they are the same and the simple test script works without error, the error is likely coming from somewhere else in the original script.

        In that case, you would need to further debug the script by reducing code and adding prints. See post # 2 for information about reducing and adding prints to debug.
        Attached Files
        <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

        Comment


          #5
          Brandon,
          Thank you. Sometimes the platform frustrates me a little, and I it's a steep learning curve learning a new language having switched over from Tradestation, but the customer service has been impeccable. Thank you.
          Rob

          Comment


            #6
            I read the post you suggested, and tried your indicator. The indicator worked. I check my language and it was the same as what was in your indicator. Just for fun I cut and pasted from you indicator, and although it was the same language, it worked after that. I also redid my strategy so it didn't have multiple data series. I read somewhere that multi data series would make recent occurences not work. My question now is, what language can I get to get the stop losses to work so that it will defer to whichever is the smallest loss. If I'm long, "SetStopLoss("Long", CalculationMode.Price, Math.Max(Position.AveragePrice - (StopLoss * TickSize), Low[Math.Max(0, Swing1.SwingLowBar(0, 1, 20))] - TickSize), false);" works fine. But if I'm short, the reverse of that "SetStopLoss("Short", CalculationMode.Price, Math.Min(Position.AveragePrice + (StopLoss * TickSize), High[Math.Max(0, Swing1.SwingHighBar(0, 1, 20))] + TickSize, false);" obviously doesn't work because it isn't referencing the current position. Any help would be greatly appreciated. Thanks

            Comment


              #7
              Hello zrobfrank,

              Thanks for your note.

              Position.AveragePrice does refer to the average price of the current short strategy position if you are in a short position.

              Position.AveragePrice: https://ninjatrader.com/support/help...erageprice.htm

              You should add prints to your script one line above your SetStopLoss() method that prints out the value being passed to the stop loss and the current market price to see exactly how your logic is behaving and submitting orders.

              Below is a link to a forum post that demonstrates how to use prints to understand behavior.
              https://ninjatrader.com/support/foru...121#post791121
              <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by NullPointStrategies, Yesterday, 05:17 AM
              0 responses
              66 views
              0 likes
              Last Post NullPointStrategies  
              Started by argusthome, 03-08-2026, 10:06 AM
              0 responses
              141 views
              0 likes
              Last Post argusthome  
              Started by NabilKhattabi, 03-06-2026, 11:18 AM
              0 responses
              76 views
              0 likes
              Last Post NabilKhattabi  
              Started by Deep42, 03-06-2026, 12:28 AM
              0 responses
              47 views
              0 likes
              Last Post Deep42
              by Deep42
               
              Started by TheRealMorford, 03-05-2026, 06:15 PM
              0 responses
              51 views
              0 likes
              Last Post TheRealMorford  
              Working...
              X