Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Fixed StopLoss & Trailing StopLoss

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

    Fixed StopLoss & Trailing StopLoss

    Hello

    I am creating a strategy that has 2 entries. The first one (Entry A) is a fixed stop loss with a fixed profit target.

    The second entry (Entry B) has a stop loss that is fixed until Entry A hits its profit target. After Entry A hits its profit target, the stop loss for Entry B moves closer to the price.

    The Entry B stop loss will then remain at this level until the SMA (or PSAR or another chosen indicator) "catches up" with it. As soon as the indicator catches up with it, the stop loss begins to trail this indicator after every bar has closed.

    According to the documentation about SetStopLoss(), I can not use SetStopLoss() and SetTrailStop() on the same order - so I do not know how to set this logic for the Entry B stop loss.

    Thank you in advance for any help.

    #2
    Hello jg123,

    Thank you for your post.

    You will want to take a look at the reference sample below on modifying your Set() orders.
    http://www.ninjatrader.com/support/f...ead.php?t=3222
    Cal H.NinjaTrader Customer Service

    Comment


      #3
      Thank you for your reply.

      I have now been studying this one that you provided as well as the SampleScaleOut doc is that is provided in this forum.

      Now I am running into some confusion.

      In Initialize() I have:

      Code:
      {
      	    EntriesPerDirection = 2;
      	    EntryHandling = EntryHandling.UniqueEntries;
      	    TargetPriceLong = High[0]+((High[0]-Low[0])*TargetPerc);
      	    StopPriceLong = SMA(sMAPeriod)[0]-((High[0]-Low[0])*StopPerc);
                  CalculateOnBarClose = true;
      }
      I expect that should allow ninjatrader to pay attention to 2 distinct long orders.

      Then I have the following for the entry and stop logic

      Code:
      if (xyz)
                  {	
      				//Order Entries A & B as well as Order for Initial Stop Loss
                      EnterLongStop(DefaultQuantity, TrendPilotPricesLong(EntryPerc, StopPerc, TargetPerc).LongEntry[0], "LongEntryA");
                      EnterLongStop(DefaultQuantity, TrendPilotPricesLong(EntryPerc, StopPerc, TargetPerc).LongEntry[0], "LongEntryB");
      				SetProfitTarget("LongEntryA",CalculationMode.Price,TargetPriceLong);
      				SetProfitTarget("LongEntryB",CalculationMode.Price,StopPriceLong);
      				barResetUp = true;
                  }
      			
      
      			// This should cause the stop loss to be reset where it is supposed to be when a trade is executed
      			if (Position.MarketPosition == MarketPosition.Flat)
      			{
      				SetStopLoss("LongEntryA",CalculationMode.Price,StopPriceLong);
      				SetStopLoss("LongEntryB",CalculationMode.Price,StopPriceLong);
      			}
      Can you at least check to see if I am on the right track? I am doing the above based on the way that I am understanding the two documents listed above - but just can't seem to figure out what I am doing based on this.

      At this point, I have not entered any information for the trailing stop. I will do that as soon as I know that this has been entered correctly. What I hope to have been accomplished up until now is:
      "if (xyz) then enter 2 long buy stop orders. When that happens, create a profit target for LongEntryA and a stop loss order for LongEntryA and LongEntry B."

      Thank you for your help
      Last edited by jg123; 03-10-2014, 05:50 AM. Reason: further clarification

      Comment


        #4
        TargetPriceLong = High[0]+((High[0]-Low[0])*TargetPerc);
        StopPriceLong = SMA(sMAPeriod)[0]-((High[0]-Low[0])*StopPerc);
        You actually cannot access bar data from Initialize() and your strategy will throw an error when its started if you attempt to set these values at this point. You need to move this logic to OnBarUpdate.

        Where you are using SetStopLoss, under MarketPosition.Flat, it would only calculate that when you're flat. If I understand you correctly, you would want to change this to MarketPosition.Long or != MarketPosition.Flat, for example.
        MatthewNinjaTrader Product Management

        Comment


          #5
          Ah, thank you very much for that information. I have fixed it.

          Here is now the issue that I am running into with the trailing stop:

          When Entry A has hit its profit target (assuming long), I want to move my stop for Entry B closer to the price. Here is what it will look like

          If Entry A hits profit target, then move Entry B stop to (Entry Price - (Entry A Profit Target - Entry Price)).

          With this, if Entry B gets stopped out after Entry A has hit its profit target, then the entire trade closes at breakeven. (not counting commissions).

          Here is what it would be numerically

          Entry = 50
          Initial Stop = 30
          Entry A Target = 60

          When Entry A hits the target then move Entry B stop to 40
          50 - (60 - 50) = 40.

          I have created a separate indicator to provide the initial Stop, Entry, & Target prices - but naturally, I can not use those indicator values moving forward because they will have changed with every bar update.

          Now I am struggling finding the variables to use in order to make the calculation for where to move the Entry B stop to.

          Also, how do I tell ninjatrader to do this when Entry A has closed out at a profit? Currently I have used the following (but I don't think that this will work anymore because the variable updates every bar)

          if(CrossesAbove(Bid,TargetPriceLong,1
          || Bid[0] = TargetPriceLong);

          So, in review, here is what I need:
          • Access the Entry & Profit target prices for calculation of initial moving of Entry B Stop
          • Having NinjaTrader check to see if Entry A has closed at the profit target so that it can move Entry B Stop to the appropriate place


          I think that there will be another question that I will have after this, but I will wait to see what your response is in case it is answered already.

          Thank you very much for your help.
          Last edited by jg123; 03-10-2014, 09:49 AM. Reason: clarifiying

          Comment


            #6
            Originally posted by jg123 View Post
            Ah, thank you very much for that information. I have fixed it.


            Now I am struggling finding the variables to use in order to make the calculation for where to move the Entry B stop to.
            You can use the Position.AvgPrice to get the entry price of your position. That can then be used as a variable to calculate where you'd like to move the stop in relation to your entry price:



            Also, how do I tell ninjatrader to do this when Entry A has closed out at a profit? Currently I have used the following (but I don't think that this will work anymore because the variable updates every bar)
            You can use the IOrder object to track the state of the ProfitTarget, and when that order has been filled, then do something. This could be done in OnBarUpdate by reference an IOrder object:



            Or you can also use an event handler such as OnOrderUpdate or OnExecution which can do something when the order is filled. An example of how to use these can be found below:

            The OnOrderUpdate() and OnExecution() methods are reserved for experienced programmers. Instead of using Set() methods to submit stop-loss and profit target orders, you can submit and update them manually through the use of IOrder and IExecution objects in the OnOrderUpdate() and OnExecution() methods. The OnOrderUpdate()
            MatthewNinjaTrader Product Management

            Comment


              #7
              Thank you for this. I am actively studying what you have provided and it is greatly appreciated!

              You can use the Position.AvgPrice to get the entry price of your position. That can then be used as a variable to calculate where you'd like to move the stop in relation to your entry price:
              From what I understand, this will give me the information for the entry price, but I now need to compare that with the price at which Entry A exited so that I can subtract that difference from the Entry Price.

              Am I able to accomplish that by doing something like this?
              Code:
              SetStopLoss("LongEntryB", CalculationMode.Price, Position.GetProfitLoss - Position.AvgPrice)

              Comment


                #8
                A more accurate way to do this is with tracking the object of the target itself. For example, you can find the IExecution price of the exact target order you're trying to calculate from:

                MatthewNinjaTrader Product Management

                Comment


                  #9
                  So does this mean that I need to have a name for my target order?

                  I have the Entry Order named "LongEntryA"

                  For example, I have this in OnBarUpdate()
                  Code:
                  if ()
                  {
                   EnterLongStop(DefaultQuantity, TrendPilotPricesLong(EntryPerc, StopPerc, TargetPerc).LongEntry[0], "LongEntryA");
                  SetProfitTarget("LongEntryA",CalculationMode.Price,TargetPriceLong);
                  I have created a new method and now have:

                  Code:
                   
                  protected override void OnExecution(IExecution execution)
                  {
                  But honestly, this is where I am starting to get confused. I am reading the documentation that you are sending me and I think that I understand it up to the point that it is for an entry order. But I don't understand how to translate this to a profit target order.

                  Comment


                    #10
                    Yes, you'd have to give it a name. SetProfitTarget/StopLoss are convenient methods that do not return anything. If you want this more advanced approach, you'd need to use ExitLongStop and ExitLongLimit for your profit targets and stop losses. This will give you the ability to uniquely name the orders and return an IOrder/Execution property, such as the avg fill price.

                    Otherwise if you want to keep using SetProfitTarget, you'd need to come up with some method to calculate the fill price, which could be complicated and inaccurate. The IOrder approach will gurantee that you have the actual execution price.
                    MatthewNinjaTrader Product Management

                    Comment


                      #11
                      Thank you

                      That helps to clear some up.

                      Here is my update.

                      I have added the following to OnBarUpdate()
                      Code:
                      ExitLongLimit(targetPriceLong,"LongLimit","LongEntryA");
                      ExitLongStop(StopPriceLong,"LongStopA","LongEntryA");
                      ExitLongStop(StopPriceLong,"LongStopB","LongEntryB");
                      and the following below that
                      Code:
                      protected override void OnExecution(IExecution execution)
                      {
                      if (LongLimit != null && LongLimit == execution.Order)
                      {
                      if (execution.Order.OrderState == OrderState.Filled)
                      {
                      ExitLongStop(AvgPrice-(execution.Price - AvgPrice)),"LongStopB","LongEntryB");
                      }
                      }
                      }
                      Can you please check to see if I am on the right track.

                      From this point, I expect that I have:
                      Told NinjaTrader that after the Profit Target has been reached, that it should change my stop for Entry B from its original position to a new place, closer to the price.

                      Thank you for your help!

                      Comment


                        #12
                        Just to be sure, you want to ensure you're mapping the ExitLongStop/Limit to the IOrder object

                        Code:
                        			if(someCondition)
                        			{
                        
                                                       ExitLongLimit(targetPriceLong,"LongLimit","LongEntryA");
                                                       ExitLongStop(StopPriceLong,"LongStopA","LongEntryA");
                                                       ExitLongStop(StopPriceLong,"LongStopB","LongEntryB");
                        			}
                        Your logic in OnExecution works from my testing. Glad to see you're getting closer to your goal!
                        MatthewNinjaTrader Product Management

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                        0 responses
                        647 views
                        0 likes
                        Last Post Geovanny Suaza  
                        Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                        0 responses
                        368 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by Mindset, 02-09-2026, 11:44 AM
                        0 responses
                        108 views
                        0 likes
                        Last Post Mindset
                        by Mindset
                         
                        Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                        0 responses
                        571 views
                        1 like
                        Last Post Geovanny Suaza  
                        Started by RFrosty, 01-28-2026, 06:49 PM
                        0 responses
                        573 views
                        1 like
                        Last Post RFrosty
                        by RFrosty
                         
                        Working...
                        X