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

Trailing a stop once price moves in your favor.

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

    Trailing a stop once price moves in your favor.

    I am working on a strategy that includes a trailing stop. I am currently using

    > ExitShortStopMarket(DefaultQuantity,(High[1]+(1*TickSize))

    And that works well.

    However, I want to add a logical step so that the stop loss remains static until a position has moved in my favor. If I take a short at 4000, my stop loss is the previous candle's high at 4005, and the ATR is 5, I would like for that stop to remain at the high of the candle prior to entry UNTIL the price has moved 1.5 ATR in my favor. The stop would stay at 4005.25 until price has moved to 3992.5.

    That leaves me with two questions.

    1. How can I create a static stop loss in the strategy builder at the High of the candle prior to my entry?

    This part I have no idea how to make work.

    2. What logic would implement the trailing stop?

    I think the correct logic would be
    IF ALL
    Position.MarketPosition = MarketPosition.Short
    Position.GetUnrealizedProfitLoss(PerformanceUnit.T icks,DefaultInput[0]) = (ATR(14)[0]*1.5)

    Do the following

    > ExitShortStopMarket(DefaultQuantity,(High[1]+(1*TickSize))

    I've attached a screenshot of the strategy in action using only the trailing stop with a drawing that shows what I want to happen. Click image for larger version

Name:	Trailing Stop Dilemma.png
Views:	560
Size:	112.8 KB
ID:	1225465

    #2
    Hello RallySquirrel,

    Thanks for your post.

    "How can I create a static stop loss in the strategy builder at the High of the candle prior to my entry?"

    Exit() order methods should be placed after an Entry() order method has been called to place an order, not before the entry is called.

    If you enable TraceOrders and try to submit an Exit() order before an Entry(), the Exit() order will be ignored and you will see something like the message below in a NinjaScript Output window.

    Ignored SubmitOrderManaged() method at 11/29/2022 10:56:00 AM: BarsInProgress=0 Action=Sell OrderType=StopLimit Quantity=1 LimitPrice=3955.00 StopPrice=3955.00 SignalName='' FromEntrySignal='' Reason='This was an exit order but no position exists to exit'

    Please see the attached example script that demonstrates using Exit() methods to place profit target and stop loss orders.

    "What logic would implement the trailing stop?"

    You could view the TrailBuilderExample_NT8 sample strategy on the forum thread linked below to see how to implement a trailing stop using Exit() methods in the Strategy Builder.

    https://ninjatrader.com/support/foru...der#post806596

    Let me know if you have further questions.​
    Last edited by NinjaTrader_BrandonH; 11-29-2022, 11:58 AM.
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Originally posted by NinjaTrader_BrandonH View Post
      Hello RallySquirrel,

      Thanks for your post.

      "How can I create a static stop loss in the strategy builder at the High of the candle prior to my entry?"

      Exit() order methods should be placed after an Entry() order method has been called to place an order, not before the entry is called.

      If you enable TraceOrders and try to submit an Exit() order before an Entry(), the Exit() order will be ignored and you will see something like the message below in a NinjaScript Output window.

      Ignored SubmitOrderManaged() method at 11/29/2022 10:56:00 AM: BarsInProgress=0 Action=Sell OrderType=StopLimit Quantity=1 LimitPrice=3955.00 StopPrice=3955.00 SignalName='' FromEntrySignal='' Reason='This was an exit order but no position exists to exit'

      Please see the attached example script that demonstrates using Exit() methods to place profit target and stop loss orders.

      "What logic would implement the trailing stop?"

      You could view the TrailBuilderExample_NT8 sample strategy on the forum thread linked below to see how to implement a trailing stop using Exit() methods in the Strategy Builder.

      https://ninjatrader.com/support/foru...der#post806596

      Let me know if you have further questions.​
      Hey Brandon, thanks for the response.

      I think I need to clarify what I am asking. I know how to trail a stop using the logic in the strategy builder. I am looking to have a dynamic stop on these positions.

      - In the above example, when I enter short at 3949.75, I want to place the stop loss at the previous candle's high. This stop placement is illustrated by the horizontal line at 3951.50.
      - I want this to remain the stop until a certain criteria is met.
      - Once the criteria is met, I want to trail the stop.

      The criteria for trailing the stop is price moving in favor of my entry by a certain number of ticks. I'd like to use the ATR for this criteria. An example would be once price has moved 1 ATR in favor of the entry, then trail the stop. So the execution would look like this:

      - Enter short 3949.75, stop loss previous candle high of 3951.5. This will remain true until the price has either stopped me out or moved 1 ATR in my favor.
      - If price moves 1 ATR in my favor, which in this example would be a move down to 3946.25 (estimating a 2.5 ATR upon entry), then the stop will trail at the previous candle's high.

      The current form of my strategy starts with this trailing stop at the previous candle's high. The logic here is

      IF ALL
      - Position.MarketPosition = MarketPosition.Short
      Do the following
      - ExitShortStopMarket(DefaultQuantity,(High[1]+(1*TickSize)),@"",@"")

      My goal is to postpone this trailing stop until after the position has moved in favor of my entry. The result will prevent the strategy from taking too many entry/exit signals. In my example, the first entry at 3949.75 would not have trailed the stop because the price did not move to 3946.25. It would have kept the stop loss at 3951.5, and it would have been stopped out in the circle I drew.

      Since I know the condition for trailing the stop, my question is how can I set the stop loss at the high of the candle prior to my entry? I am stuck there. Going back to my original post, I think that this logic:

      IF ALL
      > Position.MarketPosition = MarketPosition.Short
      > Position.GetUnrealizedProfitLoss(PerformanceUnit.T icks,DefaultInput[0]) = (ATR(14)[0]*1)

      Do the following

      > ExitShortStopMarket(DefaultQuantity,(High[1]+(1*TickSize))

      trails the stop once the price has moved ATR(14)[0]*1 ticks in my favor. BUT that is irrelevant until I can set the original stop.

      TLDR:

      How can I set a stop loss at the high of the candle prior to my entry using conditions and actions? I can successfully trail a stop loss at the previous candle's high using

      - ExitShortStopMarket(DefaultQuantity,(High[1]+(1*TickSize)),@"",@"")

      But I cannot set a stop that remains at the high of the candle prior to my entry. ​

      Comment


        #4
        Hello RallySquirrel,

        Thanks for your note.

        In the TrailBuilderExample script, you could use the TriggerPrice variable to control the frequency that the trailing of the stop happens and at what price.

        If you wanted to use the ATR value, you would need to do that in Set 2 to set an initial trail target price and then again in Set 3 once the trail target is hit. This is where you would make it move the price up again to whatever the next offset is that you wanted.

        Since the ATR is not a price value, you would need to convert it to something usable when working with the Strategy Builder. You could view this forum post for a demonstration video about how you can set up logic to build trailing stops using the ATRTrailing indicator from the User App Share.

        Dear all, I would like to create ATR profit target and stop loss using Strategy Builder. May u know how to do it? by the way, i dont know anything about coding. :) thanks, Polar


        As for your question about setting the stop loss at the high of the candle prior to your entry order, you could consider creating a double variable and saving the High[1] value to that variable when your Entry order is called. By passing in a BarsAgo value of 1 for the High price, you would get the previous candle's High price. This would mean that when your entry order is submitted, the previous candle's High price would be saved to that variable. The variable could then be referenced later in the script.

        Please let me know if I may further assist.
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Originally posted by NinjaTrader_BrandonH View Post
          Hello RallySquirrel,

          Thanks for your note.

          In the TrailBuilderExample script, you could use the TriggerPrice variable to control the frequency that the trailing of the stop happens and at what price.

          If you wanted to use the ATR value, you would need to do that in Set 2 to set an initial trail target price and then again in Set 3 once the trail target is hit. This is where you would make it move the price up again to whatever the next offset is that you wanted.

          Since the ATR is not a price value, you would need to convert it to something usable when working with the Strategy Builder. You could view this forum post for a demonstration video about how you can set up logic to build trailing stops using the ATRTrailing indicator from the User App Share.

          Dear all, I would like to create ATR profit target and stop loss using Strategy Builder. May u know how to do it? by the way, i dont know anything about coding. :) thanks, Polar


          As for your question about setting the stop loss at the high of the candle prior to your entry order, you could consider creating a double variable and saving the High[1] value to that variable when your Entry order is called. By passing in a BarsAgo value of 1 for the High price, you would get the previous candle's High price. This would mean that when your entry order is submitted, the previous candle's High price would be saved to that variable. The variable could then be referenced later in the script.

          Please let me know if I may further assist.
          Could you provide an example of creating a double variable? I've browsed the NT youtube videos and forums but cannot find any examples. Thanks in advance.

          Comment


            #6
            Hello RallySquirrel,

            Thanks for your note.

            Something you could do to see how variables are created is to use the Strategy Builder window (New > Strategy Builder). Variables can be added on the Inputs and Variables screen of the Strategy Builder. After creating the variable on the Inputs and Variables screen, you could click the 'View code' button to see the generated code that accomplishes this.

            See this help guide page about using the Inputs and Variables screen: https://ninjatrader.com/support/help...ariablesScreen

            Note that creating variables is not NinjaScript-specific code. This is considered C# education and would go beyond the support we can provide in the Engineering Support department at NinjaTrader.

            You could do a Google search for something like 'creating double variables C#' to find more information about how to create double variables using the C# programming language.

            And, here is a link to the Basic Syntax help guide page which you might find helpful: https://ninjatrader.com/support/help...sic_syntax.htm

            Let me know if I may assist further.
            Brandon H.NinjaTrader Customer Service

            Comment


              #7
              Originally posted by NinjaTrader_BrandonH View Post
              Hello RallySquirrel,

              Thanks for your note.

              In the TrailBuilderExample script, you could use the TriggerPrice variable to control the frequency that the trailing of the stop happens and at what price.

              If you wanted to use the ATR value, you would need to do that in Set 2 to set an initial trail target price and then again in Set 3 once the trail target is hit. This is where you would make it move the price up again to whatever the next offset is that you wanted.

              Since the ATR is not a price value, you would need to convert it to something usable when working with the Strategy Builder. You could view this forum post for a demonstration video about how you can set up logic to build trailing stops using the ATRTrailing indicator from the User App Share.

              https://ninjatrader.com/support/foru...pt#post1121015

              As for your question about setting the stop loss at the high of the candle prior to your entry order, you could consider creating a double variable and saving the High[1] value to that variable when your Entry order is called. By passing in a BarsAgo value of 1 for the High price, you would get the previous candle's High price. This would mean that when your entry order is submitted, the previous candle's High price would be saved to that variable. The variable could then be referenced later in the script.

              Please let me know if I may further assist.
              How do I pass through the BarsSinceEntryExecution to the High price? If I can figure out how to save that variable correctly, then I should be able to fix the rest. I've tried a few things such as the picture below but I haven't been able to get it to work. Click image for larger version

Name:	image.png
Views:	355
Size:	29.2 KB
ID:	1226293
              Last edited by RallySquirrel; 12-05-2022, 03:46 PM.

              Comment


                #8
                Hello RallySquirrel,

                Thanks for your note.

                BarsSinceEntryExecution cannot be passed into the High price. This property would be used in a condition to check if a certain number of bars have passed since your last Entry execution.

                BarsSinceEntryExecution returns the number of bars that have elapsed since the last entry order that was placed.

                An example of using this property could be seen in the sample script attached.

                More information about BarsSinceEntryExecution could be found on this help guide page: https://ninjatrader.com/support/help...yexecution.htm

                For an example about saving the previous candle's High price and the previous candle's Low price to double variables, see the reply to your post on this forum thread.
                Hello, I'm recently working on an automated strategy that involves using super trend indicators (attached). I have difficulties adding my stop loss. I have 2 types of entry, 1stEntryLong, and 2ndEntryLong. For 1stEntryLong: 1) Stop loss to be set at the swing low. 2) Once the low and high of the candle is above the entry


                If you want to save the previous candle's High price to a variable when an Entry order is placed, you could assign the High price with a BarsAgo value of 1 to a double variable in the same Set that your Entry method is called.

                Let me know if I may assist further.
                Attached Files
                Brandon H.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_BrandonH View Post
                  Hello RallySquirrel,

                  Thanks for your note.

                  BarsSinceEntryExecution cannot be passed into the High price. This property would be used in a condition to check if a certain number of bars have passed since your last Entry execution.

                  BarsSinceEntryExecution returns the number of bars that have elapsed since the last entry order that was placed.

                  An example of using this property could be seen in the sample script attached.

                  More information about BarsSinceEntryExecution could be found on this help guide page: https://ninjatrader.com/support/help...yexecution.htm

                  For an example about saving the previous candle's High price and the previous candle's Low price to double variables, see the reply to your post on this forum thread.
                  https://ninjatrader.com/support/foru...85#post1226285

                  If you want to save the previous candle's High price to a variable when an Entry order is placed, you could assign the High price with a BarsAgo value of 1 to a double variable in the same Set that your Entry method is called.

                  Let me know if I may assist further.
                  Hey Brandon, that tip has gotten me one step closer to figuring this out.

                  When I enter a trade, the stop is saved as the previous candle's high using the variable.

                  When a new sell signal is generated, the strategy builder automatically moves the stop to the NEW SIGNAL'S previous high.

                  So it keeps the stop at that previous candle's high when there is no new sell signal, but when there is a new signal, it trails it.

                  Is there a step I'm missing to keep the stop in the same location? Maybe another variable somewhere.

                  Thanks in advance.

                  Click image for larger version

Name:	image.png
Views:	351
Size:	19.6 KB
ID:	1226376

                  Comment


                    #10
                    Hell RallySquirrel,

                    Thanks for your note.

                    I am not sure I fully understand what you are reporting.

                    Please thoroughly review the TrailBuilderExample script located on the forum thread linked below.

                    TrailBuilderExample: https://ninjatrader.com/support/foru...596#post806596

                    When enabling the script as is to a chart, we can see that an Entry order is placed. In Set 2 of the Builder, we see a value is saved to the CurrentTriggerPrice variable and CurrentStopPrice variable when the Entry order is submitted. In Set 3 of the Builder, we check if we are in a long position and if the current Close price is greater than our CurrentTriggerPrice variable and we assign our new price to the CurrentTriggerPrice and CurrentStopPrice variables. Then, a stop loss order is placed using ExitLongStopMarket() at the CurrentStopPrice value (Close[0] + TrailStopDistance) when the CurrentStopPrice is not 0. When the price moves 5 ticks in your favor from that current Close price (defined by CurrentTriggerPrice) the stop loss trails to the new price (defined by CurrentStopPrice).

                    The CurrentTriggerPrice is assigned a value (the current Close price plus the TrailFrequency). The TrailFrequency determines how often the trailing action triggers. By default, this value is 5 ticks. This means that for every 5 ticks in your favor that occur above that Close price, the stop loss order will move to the new price (defined by CurrentStopPrice). If the TrailFrequency variable is set to 10, this means for every 10 ticks in your favor, the stop loss order will move to the new price (CurrentStopPrice).

                    CurrentStopPrice is the stop price used for the ExitLongStopMarket() method to place a stop at that price. CurrentStopPrice is set to the current Close price minus TrailStopDistance. TrailStopDistance represents how far away the stop will be placed. By default, TrailStopDistance is set to -5 and in Set 2 we see that CurrentStopPrice is set to the Close price + TrailStopDistance (-5 ticks). If the TrailStopDistance value is changed to 10, the stop loss order will be placed 10 ticks below the Close price.

                    You would need to implement similar logic in your strategy to have the stop loss trail after the price has moved a certain value in your favor.

                    Please let me know if I may assist further.


                    Brandon H.NinjaTrader Customer Service

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by rhyminkevin, Today, 04:58 PM
                    3 responses
                    47 views
                    0 likes
                    Last Post Anfedport  
                    Started by iceman2018, Today, 05:07 PM
                    0 responses
                    5 views
                    0 likes
                    Last Post iceman2018  
                    Started by lightsun47, Today, 03:51 PM
                    0 responses
                    7 views
                    0 likes
                    Last Post lightsun47  
                    Started by 00nevest, Today, 02:27 PM
                    1 response
                    14 views
                    0 likes
                    Last Post 00nevest  
                    Started by futtrader, 04-21-2024, 01:50 AM
                    4 responses
                    50 views
                    0 likes
                    Last Post futtrader  
                    Working...
                    X