Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Need a Hand Setting Stop Loss to Low of Previous Entry Bar and Set Profit Target too

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

    Need a Hand Setting Stop Loss to Low of Previous Entry Bar and Set Profit Target too

    Hi All, been a long time. I would love a hand with this. Attached are a strategy and screenshot to help illustrate my need for help.

    Not being able to figure this out has been quite the unsuccessful challenge as of late.

    I am trying to create a strategy that has a simple enough EnterLong set up:

    // Set 1 - Go Long
    if ((Close[0] > Open[0])
    && (Close[0] > Close[1])
    && (Close[1] > Open[1])
    && (Open[2] > Close[2])
    && (EMA1[0] > (EMA2[0] + (8 * TickSize)) )
    && (EMA1[1] > (EMA2[1] + (8 * TickSize)) )
    && (EMA1[2] > (EMA2[2] + (8 * TickSize)) )
    && ( Math.Abs(Close[1] - Open[1] ) >= Math.Abs(Close[2] - Open[2] )*0.75
    || Math.Abs(Close[0] - Open[0] ) >= Math.Abs(Close[2] - Open[2] )*0.75 )
    )
    {
    BackBrush = Brushes.CornflowerBlue;
    SetStopLoss("", CalculationMode.Price, Low[BarsSinceEntryExecution()+1]-1*TickSize, false);
    SetProfitTarget("", CalculationMode.Price, Position.AveragePrice + ( Position.AveragePrice - Low[BarsSinceEntryExecution()+2] ));

    EnterLong(Convert.ToInt32(DefaultQuantity), "");

    However, I am very obviously doing something wrong that my stops and Targets are way off, or just not working at all.

    As wrong as my code is, I hope everyone can understand that I am wanting my SetStopLoss to be static (i.e. fixed price) at a Tick below Low of the Previous Signal Bar.

    I would like to have my SetProfitTarget, be the my Position.AveragePrice Plus ( the Close of my Signal Bar minus the Low of the Previous bar to the Signal Bar), also a static (i.e. fixed price)

    I would also like to have my Stop move to Breakeven when price reaches 50% of my target price.

    In my 'simplistic', 'Gorilla Math' mind, I thought my attached strategy would work, but not a chance...haha.

    Any help or insight to get this working the way I described would be GREATLY appreciated!

    Hope everyone has a Great Holiday and Merry Christmas!


    Attached Files

    #2
    Here is the zip file of the strategy. sorry I didn't add that from the start.
    Attached Files

    Comment


      #3
      Anyone have any insight on how to create a target based on the length of the signal bar's body and down to the signal bar's previous bar's low as the Target Length from entry for Long Set Ups?

      Comment


        #4
        I just submitted this to the ecosystem. Usually takes a couple days for approval.

        You can enter trades and set targets based on RR targets.(Range of the candles selected)

        This may be what you need, the code is open source:


        Hope it helps!
        TradeSaber Inc.NinjaTrader Ecosystem Vendor - TradeSaber Inc.

        Comment


          #5
          Hello grimmer01,

          Thank you for your patience while we were away for the weekend and the observed holiday yesterday.

          In order to check the prices to see if BarsSinceEntryExecution() is what you will need to calculate the low from the previous signal bar, I recommend adding print statements to debug and better understand your strategy's behavior. For example, when the signal is reached you could print the value for Low[0] and also compare that to the printed value of Low[BarsSinceEntryExecution()+1] to see if the values match what you are looking for. We have a more in-depth guide for using prints to debug here:


          Additionally, we have a reference sample that demonstrates how to modify the price of stop loss and profit target orders (i.e. set the stop to breakeven) here:


          As for your next question, "Anyone have any insight on how to create a target based on the length of the signal bar's body and down to the signal bar's previous bar's low as the Target Length from entry for Long Set Ups?" I am not sure that I understand fully what you are asking. Please provide additional details or an example so I may better understand what exactly you are referring to and what value you are looking for when creating the target.

          I look forward to your reply.

          Comment


            #6
            Thanks Emily.

            Apologize in advance for my severe lack of coding skills.

            bottom line, I'm simply trying to figure out how to write a simple Target and Stop for my strategy. When I enter Long, I just want my target to be the Difference of my Signal Bar Close and Its previous bar Low added onto my Average Position Price. I really don't understand why I feel like I need to be a rocket scientist to write that code. Any help would be World Changing and GREATLY appreciated... For my stop on my Long Entries, I simply want it to be 1 tick below the Low of the bar Before the Signal Bar.

            Comment


              #7
              Wow, Thanks TradeSaber! Great Video too! Was trying out your strategy it this morning. Appreciate your feedback very much!


              Originally posted by TradeSaber View Post
              I just submitted this to the ecosystem. Usually takes a couple days for approval.

              You can enter trades and set targets based on RR targets.(Range of the candles selected)

              This may be what you need, the code is open source:


              Hope it helps!

              Comment


                #8
                Hello grimmer01,

                Thank you for your reply. I appreciate the alternate explanation of what you are looking for.

                One way to do this would be to save the bar number when the signal is triggered so you are able to reference the correct bar to get the Close of that bar and the Low of the bar before that. This could be done with an int variable, called signalBar in this example. I also created a double called targetLength to show how the calculation is done for the target. I added the parts in bold below based on your original post:

                private int signalBar
                private double targetLength



                if ((Close[0] > Open[0])
                && (Close[0] > Close[1])
                && (Close[1] > Open[1])
                && (Open[2] > Close[2])
                && (EMA1[0] > (EMA2[0] + (8 * TickSize)) )
                && (EMA1[1] > (EMA2[1] + (8 * TickSize)) )
                && (EMA1[2] > (EMA2[2] + (8 * TickSize)) )
                && ( Math.Abs(Close[1] - Open[1] ) >= Math.Abs(Close[2] - Open[2] )*0.75
                || Math.Abs(Close[0] - Open[0] ) >= Math.Abs(Close[2] - Open[2] )*0.75 )
                )
                {
                BackBrush = Brushes.CornflowerBlue;
                SetStopLoss("", CalculationMode.Price, Low[BarsSinceEntryExecution()+1]-1*TickSize, false);
                // using the signalBar saved from the last time the signal was met, we get the barsAgo for how many bars ago the signal ocurred by subtracting that signalBar index from the CurrentBar index. We use that Close price for the signal bar, then for the Low of the bar before that we get the difference of CurrentBar index minus the signalBar index then add 1 to go back one more barsAgo:
                targetLength = Math.Abs(Close[CurrentBar - signalBar] - Low[CurrentBar - signalBar + 1]);
                // the price for the profit target is the average position price + targetLength that we just calculated

                SetProfitTarget("", CalculationMode.Price, Position.AveragePrice + targetLength);

                EnterLong(Convert.ToInt32(DefaultQuantity), "");​
                // when the signal is hit we need to save that CurrentBar index to use the next time we calculate a profit target for the next entry
                signalBar = CurrentBar;
                }

                I hope this helps to get a better understanding of how to reference the proper barsAgo value to get the signalBar info. For your stop "1 tick below the Low of the bar Before the Signal Bar" it would look something like:
                Low[CurrentBar - signalBar + 1] - 1 * TickSize

                Please let me know if I may be of further assistance.

                Comment


                  #9
                  Thanks for your great insight Emily. I updated my strategy with your suggestions. Unfortunately, when I try to enable the strategy on the chart, it does not "enable". Any idea what I did wrong? Attached is the updated strategy.

                  thanks Again Emily!!!
                  Attached Files

                  Comment


                    #10
                    Hello grimmer01,

                    Thank you for your reply.

                    Please check the Log tab of the Control Center for error messages that offer more information as to why it is not enabling. While we do not offer hands-on debugging services, we are glad to offer suggestions and guide you through the debugging process so you may modify your script to behave as you'd like. If you are unsure of what any error messages mean, please provide a screenshot or copy the message into your reply so we may better assist you.
                    • To send a screenshot with Windows 10 or newer I would recommend using the Windows Snipping Tool.
                    • Alternatively to send a screenshot press Alt + PRINT SCREEN to take a screenshot of the selected window. Then go to Start--> Accessories--> Paint, and press CTRL + V to paste the image. Lastly, save it as a jpeg file and send the file as an attachment.
                    ​Thank you for your patience.

                    Comment


                      #11
                      Hi Emily, yeah, I should have done the log screenshot first. Sorry.

                      Here it is.

                      I'm thinking that I put the 'private int and private double in the wrong spot in the previously attached strategy file.

                      "show how the calculation is done for the target. I added the parts in bold below based on your original post:

                      private int signalBar
                      private double targetLength



                      if ((Close[0] > Open[0])​"

                      Click image for larger version

Name:	
Views:	0
Size:	204.0 KB
ID:	1229155
                      Last edited by NinjaTrader_Emily; 12-28-2022, 11:51 AM.

                      Comment


                        #12
                        Hello grimmer01,

                        Thank you for your patience.

                        I apologize for the inconvenience; I forgot you are working in the Strategy Builder which puts the Set() methods for stop losses and profit targets into State.Configure of OnStateChange(). This only allows for static values for the price and will not let you use a barsAgo reference for a dynamic price as explained in the thread here:
                        Below is my code so far. If i change the buy order to just buy long, then i have no issues. If i have the buy order as market or limit or stop, then i get this same error. 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


                        Your options to achieve your desired result would be to use Exit() methods rather than SetStopLoss and SetProfitTarget, yet you will need to create conditions that continue to resubmit the orders and keep the orders alive, or you could work with an unlocked strategy in the NinjaScript Editor to use the Set() methods with dynamic prices outside of OnStateChange. This is all due to limitations of the Strategy Builder that you would need to work around with one of the options that were mentioned.

                        I appreciate your time and understanding. Please let us know if we may be of further assistance.

                        Comment


                          #13
                          Thanks Again Emily!

                          I did unlock the strategy. It just will not enable when I try to 'enable' it. I think I have some of the script in the incorrect location. Any insight as to where I need to put them would be appreciated.

                          Comment


                            #14
                            Hello grimmer01,

                            Thank you for your reply.

                            For this particular error message, please make sure that you do not have SetStopLoss() or SetProfitTarget() in the OnStateChange method unless they are using static values. As noted in the help guide pages for the Set() methods, they may NOT be called from OnStateChange() during State.SetDefaults. See the warning on the pages here:



                            If they are using a dynamic price, such as the examples we have discussed, the SetStopLoss() and SetProfitTarget() methods will need to be set up in your script before an entry method is called, such as in OnBarUpdate() within your entry condition. Essentially, please review your script to make sure that the Set() methods are not being used with dynamic values inside of OnStateChange().

                            Please let us know if we may be of further assistance.

                            Comment


                              #15
                              Thanks again Emily for your feedback.

                              I feel like we're going down a rabbit hole and this is getting a bit far field.

                              I am really baffled that writing this code is taking this many replies...haha.

                              With an 'unlocked' strategy, why is writing the code this complex? I've contacted 3, third party vendors, none of which have replied to me. I've written 4 or 5 replies to this thread.so far. What am I missing about this part of the strategy that no one can figure out? I am really surprised.

                              Emily, please lend some insight that is not extremely vague. I am kind of desperate for any help that I can use in my strategy. TradeSaber gave a decent reply and I can use for manual entries. I am trying to make this a fully automated strategy. It's as simple as Target = AveragePositionPrice + ( close of Signal Bar - Low of Bar prior to Signal Bar).

                              thanks in advance.
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              57 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              133 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              73 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              45 views
                              0 likes
                              Last Post Deep42
                              by Deep42
                               
                              Started by TheRealMorford, 03-05-2026, 06:15 PM
                              0 responses
                              50 views
                              0 likes
                              Last Post TheRealMorford  
                              Working...
                              X