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

Target and Stop Loss Management

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

    Target and Stop Loss Management

    Good day,

    I am developing my first strategy in which I want to manage the Target and Stop according to the movement of the price and the% established in my variables to make the adjustments.

    Where I can find examples of handling Stop Loss to manage a trade automatically, that is, when the trade exceeds 50% of the expected Profit, that the Stop is placed at a certain point to protect the operation (either 10% or ox %).

    Likewise, I also want that when it reaches the expected Profit, it does not exit the operation, but to establish a Trailing Stop of a certain% (example 10%) ... behind the price ... in case of continuing trend ... exit as soon as that percentage of the highest price is returned.

    or in your case ... how to manage it with ATM?


    #2
    Welcome to the forums SamuelO!

    For NinjaScript Strategies:

    I would recommend starting with the SamplePriceModification strategy which demonstrates how you can update the stop loss dynamically so you create auto breakeven functionality. The sample teaches you how to update the stop loss in OnBarUpdate with your own logic and can also be used for customized auto trails or moving your stop how you specify.

    In essence, you can check Position.AveragePrice and compare it to the current market price (Close[0]) when the position is long, and if it exceeds half of your Profit Target, then you can move the stop loss to a specific price level with CalaulationMode.Price, or you can use a CalculationMode of Percent.

    When using SetStopLoss dynamically in OnBarUpdate, you will want to make sure that the stop is reset to an initial level when the strategy is flat and before the next entry is made.

    SamplePriceModification - https://ninjatrader.com/support/help...of_stop_lo.htm

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

    Likewise, I also want that when it reaches the expected Profit, it does not exit the operation, but to establish a Trailing Stop of a certain% (example 10%) ... behind the price ... in case of continuing trend ... exit as soon as that percentage of the highest price is returned.
    In this case, you would want to have a profit target order, but you would want to trigger auto trail functionality once the market has hit an expected level and you are in position.

    For ATM Strategies:

    or in your case ... how to manage it with ATM?
    For the first part, an Auto Breakeven stop strategy can be used to move the stop loss to a certain level once the Auto Breakeven's Profit Trigger has been reached. Using CalculationMode of Percent here will move the stop loss to a percentage measured from the average entry price, so it may behalf a little bit differently than a "percentage of desired profit"

    For the second part, this would be done with an Auto Trail added to your Stop Strategy, and leaving the Profit Target order at 0 so the ATM strategy is a runner. The Profit Trigger for the Breakeven and Auto Trail is based on favorable gain and not based on a percentage of desired profit.

    You can reference the examples and Help Guide documentation for more information on setting up ATM strategies and Stop Strategies. I would suggest the ATM 301 webinar for a walk through for using Stop strategies.

    Stop Strategies - https://ninjatrader.com/support/help...p_strategy.htm

    Auto Breakeven (examples included) - https://ninjatrader.com/support/help..._breakeven.htm

    Auto Trail (examples included) - https://ninjatrader.com/support/help...auto_trail.htm

    ATM 301 - https://www.youtube.com/watch?v=DH9y-j64X1U

    I suggest connecting to the Simulated Data Feed so you can control the market when testing your ATM strategies and Stop Strategies.

    We look forward to assisting.
    JimNinjaTrader Customer Service

    Comment


      #3
      Excellent

      Thank you very much, I am going to review all the information that I envy, one more question ... All this of the handling of stop loss and trainling stop can be developed from the Bulding Strategies or is it necessary to do it directly in the code?

      and the organization of the variables (grouped) for the user's SET ... can be organized from the Bulder? or just from the code?
      I mean assigning groupname for variables and order

      Thanks.
      Last edited by SamuelO; 05-22-2020, 02:02 PM.

      Comment


        #4
        Hello SamuelO,

        It is possible to create your own Auto Breakeven and Auto Trail logic using Exit methods in the Conditions and Actions section of the Strategy Builder. I have attached an example that can demonstrate moving a stop market order for the stop loss using logic in Conditions and Actions.

        To get more acquainted with building strategies with the Strategy Builder, I suggest starting with the Strategy Builder 301 tutorial and testing our Conditions and Actions examples. Once you are familiar with how to set up logic with the Strategy Builder, I would then suggest building a simple strategy, and then to add complexity after creating smaller test strategies.

        Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE

        Live webinar - https://ninjatrader.com/Webinar/Strategy-Builder-301

        Conditions examples —https://ninjatrader.com/support/help...on_builder.htm

        Actions examples — https://ninjatrader.com/support/help...us/actions.htm

        We look forward to assisting.
        Attached Files
        JimNinjaTrader Customer Service

        Comment


          #5
          Thank you very much for the support you are giving me.
          I have some doubts.

          In my strategy, I am managing the StopLoss, and I have a defined Profit, but it is not to take profit by touching it.
          I want to activate a TrailingStop by touching the expected Profit ... and from then on follow it with Trailing Stop.
          Any example that can help me?

          Also if you could support me with examples:
          1. How to activate and deactivate the strategy by hourly sessions
          2. How to deactivate the strategy when it reaches a maximum expected profit or maximum daily loss.

          Thank you

          Comment


            #6
            Hello SamuelO,

            Thanks for your reply.

            In my strategy, I am managing the StopLoss, and I have a defined Profit, but it is not to take profit by touching it.
            I want to activate a TrailingStop by touching the expected Profit ... and from then on follow it with Trailing Stop.
            Any example that can help me?
            You would need to set up logic in Conditions and Actions similar to the example script provided to control your Trailing Stop with your own trigger. For example, you could check if the current market price (Close[0]) is equal to your profit target's price (if you have a variable for it's price level,) or to see if the price has risen X number of ticks from the the Average Entry Price when you are in a Long position. When this condition is true, set a bool variable to true or set an integer variable (like StopLossMode in the example) to set an "AutoTrail Mode."

            When the script is in "AutoTrail Mode", move the stop loss in association to the Average Entry Price.

            To keep the stop loss from adjusting if price is going down, you can keep track of the current market price when you move the stop loss.

            For example, you could check something like if (StopLossMode == 4 && Close[0] > LastSavedPrice)

            and then move the stop loss and save the current market price (Close[0]) to your LastSavedPrice variable.

            Daily Loss limit strategies cannot be programmed in the Stratetgy Builder since the Strategy Builder is limited in performing mathematical offsets to user variables. An example for doing this with unlocked code can be found below.

            Hello, I've updated the DailyLossLimit and DailyLosLimitMultiTrade examples that were posted on the forum for NinjaTrader 7 for NinjaTrader 8. These are often requested and I felt they are good examples to have for NT8. DailyLossLimitExample_NT7 - http://ninjatrader.com/support/forum...241#post451241 (http://ninjatrader


            For controlling when the strategy will be allowed to trade, you can use the time filters to control when strategy actions should be taken. Please see How to create a Time Filter in our Strategy Builder conditions examples.



            You can then create the time filter, enable the strategy, and then it will only tke the actions you specify within those time time filters.

            We look forward to assisting.
            JimNinjaTrader Customer Service

            Comment


              #7
              Can you support me with videos of the use of the Ninja debugger? The NinjaScript Output

              Thanks

              Comment


                #8
                Since I find confusing to look at tables with hundreds of rows of homogeneous gray numbers with many decimals each, I prefer to carry out simple debugging by drawing on the chart lines and/or text rather than using prints on the NinjaScript Output, as shown on the attached video.
                The problem here is that I do not know either how to draw all the various (green, red, yellow, …) vertical lines only on a specific additional panel, or how to draw the lines and the text only on a limited zone at the bottom of the price panel, rather than n_ticks above or below price.

                If the possibility “to add/send any one/or/many drawing only on a specific additional/existing panel” is not already available, could you please consider this as a new feature request?

                Another feature to add to the draw command that I think would be interesting is the possibility of selecting a transparency degree of the drawings, this way one could draw them also over the price panel, without hiding everything else is already on the price panel. Thx.




                Click image for larger version  Name:	ES 06-20 (500 Tick) 2020_05_28 (09_34_08).png Views:	0 Size:	138.7 KB ID:	1102345

                Last edited by guidoisot; 05-29-2020, 01:57 AM.

                Comment


                  #9
                  with regard to the attached image and to the MultiStepBreakevenStrategy discussed here, how would it be possible to avoid that the SL goes down to -38 ticks, instead of being executed at -12 ticks, as it would be expected according to Set 2?
                  When price reached BE trigger levels, this last position was not exited to let it possibly become a “runner”, always maintaining active its Default_SL_long, ie at -12 ticks. However the actual exit was at -38 ticks.
                  Strategy is set to cycle “onpricechange” and it includes a 1 tick additional data series.

                  thx

                  Click image for larger version  Name:	ES 06-20 (10 Minute) 2020_05_13 (10_24_47).png Views:	0 Size:	132.0 KB ID:	1102351
                  Last edited by guidoisot; 05-29-2020, 03:03 AM.

                  Comment


                    #10
                    Hello,

                    For debugging tips with the Strategy Builder, please see the resources below. The Playback Connection can help to repeat cases that have happened with realtime data so you can take debugging steps to analyze how your logic executes at that time.

                    Debugging Tips - https://ninjatrader.com/support/help...script_cod.htm
                    TraceOrders - https://ninjatrader.com/support/help...aceorders2.htm
                    Debugging in the Strategy Builder - https://drive.google.com/file/d/1mTq...w?usp=drivesdk
                    Playback Connection - https://ninjatrader.com/support/help...connection.htm
                    Debugging Demo - https://drive.google.com/file/d/1rOz...w?usp=drivesdk

                    guidoisot The MultiStepBreakeven strategy works by setting a StopLossMode for each level we want to move the stop loss to. It sets the StopLossMode to 0 once we enter, and then on the next bar, the stop will be placed 10 ticks away from the average entry price. If you want to place the stop loss sooner to protect the position as soon as an entry is made, OnExecutionUpdate can be used. (OnExecutionUpdate will occur whenever a strategy order is filled. This will not depend on another bar formation as it will be processed as a separate event when NinjaTrader sees a strategy order executed.)

                    The SampleOnOrderUpdate strategy demonstrates using OnOrderUpdate and OnExecutionUpdate for handling profit target and stop loss. You can then add your own logic to update these orders to new levels similar to the MultiStepBreakeven strategy which modifies Exit orders in OnBarUpdate.

                    SampleOnOrderUpdate - https://ninjatrader.com/support/help...and_onexec.htm

                    In regards to your feature requests, could you email me at platformsupport [at] ninjatrader [dot] com with the text "Attn Jim 2569284" and include a link to this thread? I would like to discuss these further with you but would like to keep this thread on topic.

                    We look forward to assisting.
                    JimNinjaTrader Customer Service

                    Comment


                      #11
                      Hello, I continue working with my strategy and I have it in tests.

                      In MarketReplay it works very well, however in the Strategy Analyzer the results are not reliable.
                      Do I have to add any code to my strategy so that the Strategy Analzer will give me more reliable results?

                      Comment


                        #12
                        Hello SamuelO,

                        There is no intrabar data in a historical backtest (Strategy Analyzer.) Historical orders are filled estimating how the market would move from the Open High Low and Close values of the bar used to fill the order. Logic is also forced to calculate using Calculate.OnBarClose.

                        Discrepancies between realtime and backtesting — https://ninjatrader.com/support/help...ime_vs_bac.htm

                        Understanding Historical Fill Processing - https://ninjatrader.com/support/help...ical_fill_.htm

                        Additional steps can be taken to get Strategy Analyzer results closer to realtime simulations.

                        Tick Replay allows for intrabar logical processing so OnBarUpdate can be processed with historical data following Calculate.OnEachTick or Calculate.OnPriceChange.

                        High Order Fill resolution allows for having orders filled with intrabar data. This is the same effect as adding a single tick data series and then submitting orders to that data series. Set methods do not allow for specifying the data series used to fill the order. I would recommend using Exit methods if you want to specify which data series should be used to fill the order.

                        High Order Fill Resolution is not compatible with Multi Time Frame strategies or Tick Replay strategies. Those strategies should then submit orders to a single tick data series to have them filled intrabar. The example below can demonstrate.

                        Backtesting with intrabar granularity (can be used in place of High Order Fill Resolution) — https://ninjatrader.com/support/help...ipt_strate.htm

                        Further detail on comparing historical and realtime processing can be found below.

                        Comparing real-time, historical, and replay performance — https://ninjatrader.com/support/foru...mance?t=102504

                        Please let us know if we can be of further assistance.
                        JimNinjaTrader Customer Service

                        Comment


                          #13
                          Hello.
                          How do I get the strategy name to be saved in all my orders when I see Trade Performance, Orders in Strategy Column.
                          Thanks

                          Comment


                            #14
                            Hello SamuelO,

                            For new inquires, please feel free to open a new thread as it can help other users searching the forum to quickly find answers.

                            We currently do not save the Strategy with the order in the database, but you can see this in Trade Performance if the strategy is currently running.

                            I have added a vote on your behalf to SFT-1817 for consideration to have the strategy also saved with the order in the database.

                            Feature Request Disclaimer

                            We receive many requests and cannot reasonably implement all requested features or changes. Interest is tracked internally and if enough interest is tracked, it would be weighed against how feasible it would be to make those changes to consider implementing.

                            When new features are implemented, they will be listed in the Release Notes page of the Help Guide. The ID number will be different than the internal feature request tracking ID, but the description of the feature will let you know if that feature has been implemented.

                            Release Notes -
                            https://ninjatrader.com/support/help...ease_notes.htm

                            Please let us know if there is anything else we can do to help.
                            JimNinjaTrader Customer Service

                            Comment


                              #15
                              Originally posted by NinjaTrader_Jim View Post
                              Hello SamuelO,

                              It is possible to create your own Auto Breakeven and Auto Trail logic using Exit methods in the Conditions and Actions section of the Strategy Builder. I have attached an example that can demonstrate moving a stop market order for the stop loss using logic in Conditions and Actions.

                              To get more acquainted with building strategies with the Strategy Builder, I suggest starting with the Strategy Builder 301 tutorial and testing our Conditions and Actions examples. Once you are familiar with how to set up logic with the Strategy Builder, I would then suggest building a simple strategy, and then to add complexity after creating smaller test strategies.

                              Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE

                              Live webinar - https://ninjatrader.com/Webinar/Strategy-Builder-301

                              Conditions examples —https://ninjatrader.com/support/help...on_builder.htm

                              Actions examples — https://ninjatrader.com/support/help...us/actions.htm

                              We look forward to assisting.
                              Hi Jim,

                              Wondering if we can extend the logic to include the Short side in your code.

                              Would a simple else if structure do?

                              I saw this NT7 code includes both Long and Short that way:




                              Could you please tell if it would work with your code?

                              The use is for a strategy that auto-manages manually placed trades, either long or short ones.
                              The references I've used:

                              https://ninjatrader.com/support/foru...ons#post675767
                              https://ninjatrader.com/support/help...runmanaged.htm
                              https://ninjatrader.com/support/help...d_approach.htm
                              https://ninjatrader.com/support/help...er_methods.htm
                              https://ninjatrader.com/support/help...d_approach.htm
                              https://ninjatrader.com/support/help...rderupdate.htm
                              https://ninjatrader.com/support/help...nt8/?order.htm
                              https://ninjatrader.com/support/help...d_approach.htm

                              CancelOrder()
                              OnOrderUpdate()
                              Order
                              ChangeOrder()
                              if(PositionAccount.MarketPosition != MarketPosition.Flat)
                              IsAdoptAccountPositionAware = true;
                              StartBehavior = StartBehavior.AdoptAccountPosition;
                              unmanaged SubmitOrderUnmanaged()
                              Remember to set IsUnmanaged = true in State.SetDefaults




                              Would something like:

                              if (PositionAccount.MarketPosition == MarketPosition.Long)
                              {
                              //manage the Long Position multi steps breakeven logic
                              // Sets 1 to 6



                              }
                              else if (PositionAccount.MarketPosition == MarketPosition.Short)
                              {
                              //manage the Short Position multi steps breakeven logic
                              // Sets 7 to 12



                              }

                              I ask because it seems not that straightforward with the multiple if statements of the embedded Sets.
                              I previously had the issue that only the 2nd part of the if ... else if statement would execute on another strategy here:

                              Do you know if we can do the embedding and both parts still execute?
                              Else do you see a workaround if we can't do it with the simple if ... else if structure.

                              I attached back your code unchanged.
                              Thanks.
                              Attached Files
                              Last edited by Cormick; 07-19-2021, 06:00 AM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by maybeimnotrader, Yesterday, 05:46 PM
                              4 responses
                              23 views
                              0 likes
                              Last Post maybeimnotrader  
                              Started by frankthearm, Today, 09:08 AM
                              6 responses
                              25 views
                              0 likes
                              Last Post frankthearm  
                              Started by adeelshahzad, Today, 03:54 AM
                              5 responses
                              33 views
                              0 likes
                              Last Post NinjaTrader_BrandonH  
                              Started by stafe, 04-15-2024, 08:34 PM
                              7 responses
                              32 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by merzo, 06-25-2023, 02:19 AM
                              10 responses
                              824 views
                              1 like
                              Last Post NinjaTrader_ChristopherJ  
                              Working...
                              X