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

Help with moving stop loss based on if statement with bars since entry

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

    Help with moving stop loss based on if statement with bars since entry

    Hi all,

    I'll just start out by saying I am new to Ninja Script and have been trying to read the help guides to understand it. I am trying to move my stop loss if the high since entry of my Long1 signal is above 'X' ticks from my average position price. I think the best way to do this would be using the MAX function.

    I tried adding this to the OnBarUpdate() method:

    double myEntryHigh = MAX(High, BarsSinceEntry("Long1"));

    if (myEntryHigh >= Position.AveragePrice + (6 * TickSize))

    This returns the error "The name 'BarsSinceEntry' does not exist in the current context." I also tried this as mentioned in another old thread:

    double myEntryHigh = MAX(High, BarsSinceEntry("Long1")[0]);

    Same result.

    Any help would be greatly appreciated.

    #2
    Hello Deterministic J,

    Thanks for your post and welcome to the NinjaTrader forums!

    The error message,"error "The name 'BarsSinceEntry' does not exist in the current context."" is advising that the method name is not recognized. In NT8 the method name to use is BarsSinceEntryExecution() Reference: https://ninjatrader.com/support/help...yexecution.htm

    In addition, for the MAX() method you will need to specify a BarsAgo index to use, reference: https://ninjatrader.com/support/help...aximum_max.htm

    Here is what it should look like with the correct method name and bars ago index:

    double myEntryHigh = MAX(High, BarsSinceEntryExecution("Long1"))[0];

    Depending on how you are using this, it is likely that you will need to first verify that BarsSinceEntryExecution("Long1") does not return a -1 value before using in the MAX() method as this will cause a run time error with the MAX method, something on the order of a bars ago reference issue. As the help guide advises, if the entry does not exist, the method will return a -1 value. Something like:

    if (BarsSinceEntryExecution("Long1") > -1) // check to see if we first have an entry with the name Long1
    {
    double myEntryHigh = MAX(High, BarsSinceEntryExecution("Long1"))[0]; // if so then we can get the max high value since the entry.
    }


    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Thanks Paul.

      All compiled after that.I added my stop loss change as needed and everything seems to be right. When I go to enable the Strategy on a chart, it gives this error "You must use the overload that has a 'BarsInProgress' parameter when calling the BarsSinceEntryExecution() method in the context of a multi-time frame and instrument strategy."

      I looked at the help guide for BarsSinceEntryExecution and this only seems to be needed on a multi-time frame and instrument strategy. I am only adding a 1 min ES Futures data series. Any idea why I would get this error?

      Here's the code:

      if (BarsSinceEntryExecution("Long1") > -1) // Check to see if we have an entry with the name Long1
      {
      double myEntryHigh = MAX(High, BarsSinceEntryExecution("Long1"))[0]; //If so then we can get the max high value since entry
      Print("Max High: " + myEntryHigh); //Output max high value since entry

      if (myEntryHigh >= Position.AveragePrice + (6 * TickSize)) //If entry since high is >= 6 ticks above our entry
      {
      SetStopLoss(CalculationMode.Price, (Position.AveragePrice + (1* TickSize))); //Move stop to breakeven
      }
      }
      Last edited by Deterministic J; 05-28-2019, 08:26 AM.

      Comment


        #4
        Hello Deterministic J,

        Thanks for your reply.

        If you have any AddDataSeries() statements in your script then you are in the multi series or multi time frame mode and in that case then yes you would need to modify per the help guide. You also may need to review your code structure to avoid further unexpected complications when the added data series call the OnBarUpdate(), referencing: https://ninjatrader.com/support/help...nstruments.htm

        NOTE: If your intent is to apply and run the strategy on the charts 1 minute bars, then you do not need to use AddDataSeries and removing that statement would remove that and other issues. For clarity, a script will automatically use the charts data series and there is no need to add another data series unless you have specific reasons too.



        Paul H.NinjaTrader Customer Service

        Comment


          #5
          That did it Paul! That's great to know for the future. I removed the Data series from the code.

          Now it's getting an error "Value of 'Period' of Ninjascript 'MAX' is 0 and not in valid range between 1 and 2147483647."

          This happens the instant I enable the strategy and it auto disables. It makes sense that MAX is 0 since there is no entry yet, but that's why we had that check to make sure there was the Long1 entry before calculating max, right? (I also added the Marketposition IF to see if that would help but no luck)

          Here's all the code:

          if(Position.MarketPosition == MarketPosition.Long) //If Market position long
          {
          if (BarsSinceEntryExecution("Long1") > -1) // Check to see if we have an entry with the name Long1
          {
          double myEntryHigh = MAX(High, BarsSinceEntryExecution("Long1"))[0]; //If so then we can get the max high value since entry
          Print("Max High: " + myEntryHigh); //Output max high value since entry

          if (myEntryHigh >= Position.AveragePrice + (6 * TickSize)) //If entry since high is >= 6 ticks above our entry
          {
          SetStopLoss(CalculationMode.Price, (Position.AveragePrice + (1* TickSize))); //Move stop to breakeven
          }
          }
          }

          Comment


            #6
            Hello Deterministic J ,

            Thanks for your reply.

            Try changing the > -1 to > 0 as that should cover both the case of no entry (-1) and the case of an entry on the current bar (0) meaning that on the next bar close the method would provide a 1 to the MAX() method.

            Paul H.NinjaTrader Customer Service

            Comment


              #7
              Hi Paul,

              I should have mentioned I did try that and that works, but then it does not calculate the high since the entry, it only calculates the high one bar after entry. Since Max needs to be at least 1. Do you know of a way around this?

              I tried a workaround on my own which basically uses the same if statement for BarsSinceEntryExecution but includes an else statement if there's a long position and bars since entry is not > 0 then sets the stop loss for each statement. This compiles, but it doesn't move my stop loss. All the outputs are correct and the Max High First Bar (myEntryHighFirstBar) >= the position price + 5 ticks. No errors in the Log either for the stop loss orders.

              if(Position.MarketPosition == MarketPosition.Long) //If Market position long
              {

              if (BarsSinceEntryExecution("Long1") > 0) // Check to see if we have an entry with the name Long1
              {
              double myEntryHigh = MAX(High, BarsSinceEntryExecution("Long1"))[0]; //If so then we can get the max high value since 1 bar after entry
              Print("Max High: " + myEntryHigh); //Output max high value since entry
              if (myEntryHigh >= (Position.AveragePrice + (5 * TickSize))) //If entry since high is >= 5 ticks above our entry
              {
              SetStopLoss(CalculationMode.Price, (Position.AveragePrice + (1* TickSize))); //Move stop to breakeven
              }
              }
              else
              {
              double myEntryHighFirstBar = High[BarsSinceEntryExecution()]; //Find high of first bar since entry
              Print("Max High First Bar: " + myEntryHighFirstBar); //Output high of first bar to verify it is correct
              if (myEntryHighFirstBar >= (Position.AveragePrice + (5 * TickSize))) //If entry first bar high is >= 5 ticks above our entry
              Print("Position Price + 5 ticks: " + (Position.AveragePrice + (5 * TickSize))); //Output to verify 5 ticks above entry calculates correctly
              {
              SetStopLoss(CalculationMode.Price, (Position.AveragePrice + (1* TickSize))); //Move stop to breakeven
              }
              }

              }

              Click image for larger version  Name:	StratOutput.PNG Views:	2 Size:	3.6 KB ID:	1059095
              Attached Files
              Last edited by Deterministic J; 05-28-2019, 07:07 PM.

              Comment


                #8
                Hi
                thank you for your interesting posts showing the code you are using.
                With regard to the sketch diagram attached (where, using the free tool https://online.visual-paradigm.com/f...gram-software/ .... I attempt (!) to schematize the logic of the above code) could you confirm/explain
                - whether the “Long1” entry can be an “intrabar” execution, for example triggered on a 5 min chart (with an additional one min. data feed ? since my IB data feed does not include historical tick data for backtesting),
                and whether at
                - point 1 “myEntryHigh” is the high of the 5 min bar when the entry was executed ?
                - point 2 “myEntryHighFirstBar” is the high of just the first 5 min. bar next to the entry bar?
                What happens if in neither bar of points 1 and 2 the high is not greater by 6 ticks the avg position? If the MAX method in the code considers the highs of the next bars could you call point 2 high as "myEntryHighFromFirstBar" ?
                Thank you.

                Click image for larger version

Name:	check the high diagram.jpg
Views:	272
Size:	90.9 KB
ID:	1059115

                Comment


                  #9
                  Hello Deterministic J,

                  Thanks for your reply.

                  I have been trying to help you with the errors to get your code functional and at this point perhaps you should reconsider what you want to do as perhaps using MAX() and BarsSinceEntryExecution() may not be the best approach overall and it is certainly adding more complication to your code and often a simpler approach is better from a functional and debugging point of view.

                  Going back to your first post, the stated goal is: "I am trying to move my stop loss if the high since entry of my Long1 signal is above 'X' ticks from my average position price."

                  A simpler approach is to code something like this:

                  if (Position.MarketPosition == MarketPosition.Long && stopAdjusted == false && High[0] >= (Position.AveragePrice + 6 * TickSize))
                  {
                  SetStopLoss(CalculationMode.Price, (Position.AveragePrice + (1* TickSize))); //Move stop to breakeven
                  stopAdjusted = true; // set the bool to true so we do not continue to resend the stop
                  }


                  In the above example, on the first occurrence where the High[0] >= entry + 6 ticks the stop is moved to breakeven and I think this meets your requirements. I have used a bool that would need to be created and as false. I named the bool as "stopAdjusted" as that seems to convey the intent, you can of course use any name for the bool you wish. When the overall condition set is true, the stop would be adjusted and the bool is changed to true so that the code doesn't continue to resend the stop. Note that in this example you would also need to find a condition to reset the bool to false (for example when you place the entry order).

                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi guidoisot,

                    Basically my code was a convoluted way of doing what Paul's code above does. As soon as I entered a position long, I wanted to set my stop loss to breakeven after the high had reached 6 ticks above my original position. The problem was that the Max() method I was trying to use would only calculate after 1 bar so I added a High() method that would calculate the first bar and another Max that would calculate the max high of all bars after the first one since my entry. It was adding extra unneeded code.

                    Paul's code is much better because it's simple and the code will stop processing after moving the stop giving you a much cleaner output actions.It's also not continually trying to process the stop. If you are looking for a similar type of thing for your own strategy, definitely take a look at Paul's last post.

                    Thanks again, Paul!
                    Last edited by Deterministic J; 05-29-2019, 10:43 PM.

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by Jonafare, 12-06-2012, 03:48 PM
                    5 responses
                    3,985 views
                    0 likes
                    Last Post rene69851  
                    Started by Fitspressorest, Today, 01:38 PM
                    0 responses
                    2 views
                    0 likes
                    Last Post Fitspressorest  
                    Started by Jonker, Today, 01:19 PM
                    0 responses
                    2 views
                    0 likes
                    Last Post Jonker
                    by Jonker
                     
                    Started by futtrader, Today, 01:16 PM
                    0 responses
                    7 views
                    0 likes
                    Last Post futtrader  
                    Started by Segwin, 05-07-2018, 02:15 PM
                    14 responses
                    1,792 views
                    0 likes
                    Last Post aligator  
                    Working...
                    X