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

how use trailing stop at strategy builder

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

    #31
    Originally posted by NinjaTrader_PaulH View Post
    Hello Michael,

    Thanks for your reply.

    The PDF was not attached. If you don't mind, please attach the strategy directly. It will be found in the Documents>NinjaTrader8>bin>Custom>Strategies> and will be named as you named it with a .cs extension.
    Paul,

    Oooops.. sorry about that...

    I get an error message when attaching the strategy.. It dosen't happen when attaching a different .cs Strategy.. See attachment..

    Maybe I should email it..??

    Michael

    Click image for larger version  Name:	Upload Error Message.jpg Views:	0 Size:	81.2 KB ID:	1112958

    Last edited by Mykro; 08-05-2020, 11:14 AM.

    Comment


      #32
      Hello Michael,

      Thanks for your reply.

      Please write to us at PlatformSupport[at]NinjaTrader[dot]Com. Mark the e-mail Atten Paul, Ticket # 2428801. Please attach your strategy to your e-mail and include a link to this thread in your e-mail for reference.

      Paul H.NinjaTrader Customer Service

      Comment


        #33
        Hello all,

        Just to close this thread, forum member Mykro and I were able to resolve his strategy concerns as we found that the default values in his startegy for TrailFreqShort and TrailDistShort were backwards.

        In addition, we found that the example strategy we posted in post #5 would not work on certain instruments and this is because the user variables were set to an Int type (whole number) and should be set to a double type to best represent price. Using an Int type for price would round the price to a whole number which forum member Mykro observed in the movements of the stop and we can be more easily see on an instrument such as CL. We will remove and replace the example with one that corrects that.
        Paul H.NinjaTrader Customer Service

        Comment


          #34
          Hello,
          Was playing around with this trailbuilder example. Was wondering why every time I add a set profit target, the trail never starts working? Any thoughts why?

          Comment


            #35
            Hello Neilpacc76,

            Thanks for your post and welcome to the NinjaTrader forums!

            Please advise which specific post you downloaded the Trailbuilder example from as there is more than one post with an attached file on this topic.
            Paul H.NinjaTrader Customer Service

            Comment


              #36
              It was the very first one TrailBuilderExample_NT8

              Comment


                #37
                Hello Neilpacc76,

                Thanks for your reply.

                Just wanted to make sure we are looking at the same thing.

                The Strategy Builder offers a standard trailing stop called SetTrailStop() and would be part of the "stops and Targets" window of the Strategy Builder. This trailing stop will trail the current price by the specified distance and will not move backward. For every tick of profit, the trail stop will move a tick forward. If you want to use the standard trailing stop then you would be able to use the SetProfitTarget() as well. Please note that you cannot use a SetStopLoss and a SetTrailStop on the same order as in that case the trail stop is ignored.

                In this custom strategy builder example, the Set methods, when used will cause the other exit methods to be ignored. If you check your "Log" tab of the control center, you would see error messages to that effect. This is based on the "Internal Order Handling Rules that Reduce Unwanted Positions" which are covered under the "Managed Approach". You can review these documents here:



                The custom example is provided to demonstrate how you can create your own custom trailing stop. You can add a profit target to it if you wish, however you would have to use a similar exit order such as "exit long position by a limit order" in set#4 with a specified target price.

                Paul H.NinjaTrader Customer Service

                Comment


                  #38
                  OK I will mess around with a few of those things, thanks.

                  Comment


                    #39
                    Originally posted by NinjaTrader_PaulH View Post
                    Hello Michael,

                    Thanks for your reply.

                    I took a closer look at the strategy which I understand is a copy of NinjaTrader_Kate's example.

                    In the case of a trailstop for a short order, the trail stop would need to be a positive value of ticks above the price and the trigger would need to be a negative value to trigger as price drops. So you would need to set the Trailfreq to be a negative value and the TrailDist to be a positive value. As you are setting the value to be a negative, in both cases you can add to the Close value the same as the long side shows but with the short variables.

                    Michael, the strategy Kate provided is merely an example, you will not be successful in just duplicating it on the short side because of the Entry conditions. The only entry condition is that you are flat and in state realtime. So if you duplicate a short set with the long set they will both enter at the same time because of the strategy being flat. I would suggest that you create, for set 2 an actual entry condition that can only be unique for long entries and the same but short for short entry in set 6. If you do not do this then the strategy is as is will error out.





                    Hi Paul,

                    I've generated a code TrailingStopExample20210528.zip and attached screenshot that seems to be working for Long and Short from Kate's original script.

                    See below and attached.
                    https://pastebin.com/yTiQGh9k

                    The customization snippets in bold:

                    New Variables Initializations:
                    Code:
                    [LIST=1][*]public class TrailBuilderExample : Strategy[*]{[*]private double CurrentTriggerPrice[B]Long[/B];[*]private double CurrentStopPrice[B]Long[/B];[*][B]private double CurrentTriggerPriceShort;[/B][*][B]       private double CurrentStopPriceShort;[/B][*]...[/LIST]
                    New Variables Declarations:
                    Code:
                    [LIST=1][*]protected override void OnStateChange()[*]{[*]if (State == State.SetDefaults)[*]{[*]Description                                 = @"Demonstrates changing the price of a Stop Market Order similar to a trailing stop loss";[*]Name                                        = "TrailBuilderExample";[*]Calculate                                   = Calculate.OnEachTick;[*]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;[*]TrailFrequency                  = 5;[*]TrailStopDistance                   = -5;[*]CurrentTriggerPrice[B]Long[/B]   = 0;[*]CurrentStopPrice[B]Long[/B]      = 0;[*]CurrentTriggerPrice[B]Short[/B]  = 0;[*]CurrentStopPrice[B]Short[/B]     = 0;[/LIST]
                    New Long Trailing Stop Orders Logic:
                    Code:
                    [LIST=1][*]protected override void OnBarUpdate()[*]{[*]if (BarsInProgress != 0)[*]return;[*][B]// LONG ORDERS (Sets #1 to #4)[/B][*]// Set 1[*]if (Position.MarketPosition == MarketPosition.Flat)[*]{[*]CurrentStopPrice[B]Long[/B] = 0;[*]}[*]if (CurrentBars[0] < 1)[*]return;[*]// Set 2[*]if ((Position.MarketPosition == MarketPosition.Flat)[*]&& (State == State.Realtime)[*][B]&& (High[0] > High[1])[/B])[*]{[*]EnterLong(Convert.ToInt32(DefaultQuantity), @"longEntry");[*]CurrentTriggerPrice[B]Long[/B] = (Close[0] + (TrailFrequency * TickSize)) ;[*]CurrentStopPrice[B]Long[/B]= (Close[0] + (TrailStopDistance * TickSize)) ;[*]}[*]// Set 3[*]if ((Position.MarketPosition == MarketPosition.Long)[*]&& (Close[0] > CurrentTriggerPrice[B]Long[/B]))[*]{[*]CurrentTriggerPrice[B]Long[/B] = (Close[0] + (TrailFrequency * TickSize)) ;[*]CurrentStopPrice[B]Long[/B] = (Close[0] + (TrailStopDistance * TickSize)) ;[*]}[*]// Set 4[*]if (CurrentStopPrice[B]Long[/B] != 0)[*]{[*]ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), CurrentStopPrice[B]Long[/B], @"", "");[*]}[/LIST]
                    Added Short Trailing Stop Orders Logic:
                    Code:
                    [LIST=1][*][B]// SHORT ORDERS (Sets #5 to #8)[/B][*]// Set 5[*]if (Position.MarketPosition == MarketPosition.Flat)[*]{[*]CurrentStopPrice[B]Short[/B] = 0;[*]}[*]if (CurrentBars[0] < 1)[*]return;[*]// Set 6[*]if ((Position.MarketPosition == MarketPosition.Flat)[*]&& (State == State.Realtime)[*][B]&& (Low[0] < Low[1])[/B])[*]{[*]EnterShort(Convert.ToInt32(DefaultQuantity), @"shortEntry");[*]CurrentTriggerPrice[B]Short[/B] = (Close[0] - (TrailFrequency * TickSize)) ;[*]CurrentStopPrice[B]Short[/B] = (Close[0] - (TrailStopDistance * TickSize)) ;[*]}[*]// Set 7[*]if ((Position.MarketPosition == MarketPosition.Long)[*]&& (Close[0] > CurrentTriggerPrice[B]Short[/B]))[*]{[*]CurrentTriggerPrice[B]Short[/B] = (Close[0] - (TrailFrequency * TickSize)) ;[*]CurrentStopPrice[B]Short[/B] = (Close[0] - (TrailStopDistance * TickSize)) ;[*]}[*]// Set 8[*]if (CurrentStopPrice[B]Short[/B] != 0)[*]{[*]ExitShortStopMarket(Convert.ToInt32(DefaultQuantity), CurrentStopPrice[B]Short[/B], @"", "");[*]}[/LIST]

                    For some reason similar logic for my other strategy MultiStepBreakevenStrategy5.zip only executes the short trades (short logic is at the end of the code):

                    Could you tell why it's not executing the Long trades from the start of the OnBarUpdate()?

                    I suspected a scope error so I changed the if statements structure to if () ... else if structure but it doesn't help.


                    I followed the Nested if...else Statement tutorials from here:
                    The original simpler if statement structure MultiStepBreakevenStrategy4.zip is also attached if need be but it too doesn't execute the Long trades.

                    I cannot see what's causing the issue.
                    Since the structure works with Kate's code update TrailingStopExample20210528.zip, I don't see why it shouldn't with the MultiStepBreakevenStrategy4.zip code at least work too.
                    Thanks for you insights.





                    Attached Files

                    Comment


                      #40
                      Hello Cormick,

                      Thanks for your post.

                      I would recommend following a debugging approach that you can perform to resolve your questions. Part of creating a script is debugging it when it does not perform as expected. As a small team we cannot provide debugging services for everyone's script so learning to debug is what we can help with.

                      Working in the Strategy Builder there are two ways to debug and you may want to use both.

                      You can visually provide an indication on the chart that the conditions of a set are true by using the drawing tools found in the Drawing folder in the "do the following" section of a set. In there you can draw dots, arrows, vertical lines, text, etc. For example, by drawing a dot when a set is true you can see on the chart when that sets condition is true. By using a different colored dot in each set, drawn at a different Y value, you can then see on each bar when one or more sets are true. Here is a short video on how you can adjust the Y value of the draw object as well as how you can display all of the draw objects as by default you will only see the latest occurrence: https://paul-ninjatrader.tinytake.co...MF8xMTMwNTc0MA

                      Traditional type debugging usually involves print statements. Print statements can be used to print out specific variables so that you can see if the conditions you expect to be true and are not are caused by which variable value. In the Strategy Builder, you can construct a print statement in the "do the following" section of a set in the Misc Folder. Typically you would put the print statement in an "empty" set so that the print statement is print on every OnBarUpdate(0 which means a lot of information. By using the bar time stamp in the print statement you will be able to see what the values of the variables were on each bar. From this information, you can best understand what is happening with your strategy. Here is a link to a short video that walks through constructing a print statement and then reviewing the information: https://paul-ninjatrader.tinytake.co...NV8xMDk5MDc5Nw

                      This process will remove the mystery of the script performance and will allow you to effect changes to get the desired performance.
                      Paul H.NinjaTrader Customer Service

                      Comment


                        #41
                        Hi Paul,

                        Thanks for the reply and debug videos.

                        I've used the
                        Code:
                        [INDENT]TraceOrders = true;[/INDENT]
                        and
                        Code:
                        [INDENT]Draw.Dot(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red);[/INDENT]

                        methods.


                        Below the output with Buy Orders highlighted in lime color: And demo video:
                        I've checked to see if any Long orders are rejected or anything else.

                        The output shows some Buy Orders. But those don't appear on the chart.

                        Neither the dots from the
                        Code:
                        Draw.Dot(this, "tag1", true, 0, Low[0] - TickSize, Brushes.Red);
                        methods appear on the chart.


                        What help I can't isolate does the TraceOrders debug output give?

                        Do you see anything helpful in the TraceOrders debug output?

                        How to use what the debug output tells to make the Long orders execute/work?

                        It seems to only tell that some Buy Orders get executed on the output.
                        But that doesn't let us know why they don't execute on the chart/how to make them execute no the chart.

                        What am I missing?

                        Thank you for your insights.



                        Comment


                          #42
                          I've generated the following from the prints:

                          Code:
                          @"Time/Date " + Convert.ToString(Times[0][0]) + @" Long Orders = " + Convert.ToString(StopLossModeLong)

                          The end of the Prints:
                          Code:
                          Enabling NinjaScript strategy 'MultiStepBreakeven/232268716' : On starting a real-time strategy - StartBehavior=WaitUntilFlat Position=ES 06-21 1S EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On each tick IsUnmanaged=False MaxRestarts=4 in 5 minutes


                          It doesn't seem to execute the long orders after all.

                          The StopLossModeLong output is always Long Orders = 0

                          I don't see why it doesn't execute the Long orders.

                          Here's is the new simpler code adapted from Jim's:


                          Can you or Jim have a quick glance and see why it only executes the short trades?
                          The Long logic is replicated from the short logic with opposite settings.

                          The strategy export is attached.

                          A short video of my Strategy Builder configuration.



                          Thank you.
                          Attached Files

                          Comment


                            #43
                            I tested the the Long code alone and then the Short code alone.
                            The long code alone (48 lines) doesn't execute while the short code alone (48 lines) does execute.

                            I checked both the Long Code and The Short on a text comparator.

                            See the Codes texts comparison Screenshots:


                            See the NinjaScript Editor test Video:




                            The Long Code seems exactly the same as the Short but for the Long and positive values.

                            What do you think?

                            It seems there is a fundamental missing piece I'm not aware of you guys could pinpoint at a glance.
                            Maybe something inherent to C# I'm not familiar with.


                            Attached the Long Code exported .zip.

                            Attached the Short Code exported .zip.

                            Attached the text comparison screenshots.




                            Thank you for your next reply and hand.
                            Attached Files
                            Last edited by Cormick; 05-30-2021, 12:44 PM.

                            Comment


                              #44
                              Hi Cormick,
                              The profit lies in the purchasing, but you take it to the extreme.
                              How realistic is a EnterLongLimit at zero or below?
                              EnterLongLimit(Convert.ToInt32(DefaultQuantity), 0, "");
                              NT-Roland

                              Comment


                                #45
                                Hi Roland,

                                Thank you for the observation.

                                Why does zero with
                                Code:
                                Enter[B]Short[/B]Limit(Convert.ToInt32(DefaultQuantity), [B]0[/B], "");
                                work for short,

                                but zero with
                                Code:
                                Enter[B]Long[/B]Limit(Convert.ToInt32(DefaultQuantity), [B]0[/B], "");
                                Long does not?

                                I tested with 2
                                Code:
                                Enter[B]Long[/B]Limit(Convert.ToInt32(DefaultQuantity), [B]2[/B], "");
                                and it's not working.

                                Thanks for the zero observation for later uses, but it's not helping with the issue at hand.
                                Do you have any other helping observation?


                                Beside question:

                                For some reason my previously .zip attachments from posts #40 and #44 above are not showing.
                                Do you have any idea why they aren't showing anymore?

                                Thank you.

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by Christopher_R, Today, 12:29 AM
                                0 responses
                                9 views
                                0 likes
                                Last Post Christopher_R  
                                Started by sidlercom80, 10-28-2023, 08:49 AM
                                166 responses
                                2,235 views
                                0 likes
                                Last Post sidlercom80  
                                Started by thread, Yesterday, 11:58 PM
                                0 responses
                                3 views
                                0 likes
                                Last Post thread
                                by thread
                                 
                                Started by jclose, Yesterday, 09:37 PM
                                0 responses
                                8 views
                                0 likes
                                Last Post jclose
                                by jclose
                                 
                                Started by WeyldFalcon, 08-07-2020, 06:13 AM
                                10 responses
                                1,415 views
                                0 likes
                                Last Post Traderontheroad  
                                Working...
                                X