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

Moving stop loss below entry candle

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

    Moving stop loss below entry candle

    Hello. I'm trying to simply move my stop loss 2 points below the entry candle, or the previous few entry candles.

    Here is what I've tried...

    SetStopLoss(@"Long", CalculationMode.Ticks, Low[1] - 8 * TickSize, false);

    SetStopLoss(@"Long", CalculationMode.Ticks, (MIN(Low,3)[0] + (-8 * TickSize)), false);

    I can't seem to get it to work, I either get errors or the stop gets placed hundreds of ticks away from the price. What am I doing wrong? Thank you for the time.

    #2
    Hello augustfay,

    Thanks for your post.

    Are you working with the Strategy Builder or directly in Ninjascript code?

    If coding where in the code are you placing the stoploss code?

    What specific errors do you see?

    Is "Long" the specific entry name and is the capitalization the same in both the entry and the stop loss?

    How are you testing? (On live data, Strategy Analyzer, Playback with market replay data)

    What calculate setting is used for the Strategy? (Calculate.OnBarClose, Calculate.OnPriceChange, Calculate.OnEachTick)

    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Hi Paul, thanks for your response. I started things off in the strategy builder but unlocked the code and am doing things that route now. Using the builder I just entered a long order with a profit target and a stop loss, and vice versa for the short. I haven't messed around with this part of the script really so it's just in the same place the builder would put it. Yes @Long is spelled the same for both SetProfitTarget and SetStopLoss. I am testing on Playback with replay data. The strategy is using calculate on bar close.

      The errors I keep getting are what I mentioned before, as well as right at the entry I get the popup that stop orders can't me moved past price. I'm not trying to move it past price though, I just want the stop to go one tick below the lowest point of the swing I enter on, or the MIN/MAX, right at the time of entry, not any sort of breakeven trigger.

      If this is possible to do in the builder I'd gladly start the strategy over, but I thought this would be a simple line of code.. please advise, thanks.

      Comment


        #4
        Hello augustfay,

        Thanks for your reply.

        The Startegy Builder puts the code for the set methods in State.Configure and in that location the set methods cannot access the bar data (such as Low). You would have to move the code for set profit and set stop loss just ahead of the entry coding, something like:

        if (your conditions to enter long)
        {
        SetProfitTarget(.. whatever you used here);
        SetStopLoss(@"Long", CalculationMode.Ticks, (MIN(Low,3)[0] + (-8 * TickSize)), false);
        EnterLong();
        }


        It is critical that the set methods are set to the new values before the trade entry is made because they retain the last value used and are deployed immediately on a fill of the entry order.


        It would be possible to do what you want in the strategy builder but you would not be able to use the Set methods at all (because they don't have access to the bar data). You would instead use other Exit orders as found in the Order Management folder in a set. For example (Long) you would use "Exit long by a limit order" as the profit target and "Exit long by a stop order" as the stop loss. There are other order types you can use as well but those two are the most commonly used.

        The consideration in using these orders is to understand that they are automatically canceled if they are not filled on the bar they are submitted. This means you must resubmit these orders on each new bar. This can be done but requires an additional set with two double-type variables.

        For example, in set 1 you would have the conditions to place an entry order, for the action you place the entry order and save the (MIN(Low,3)[0] + (-8 * TickSize) (or Low[0]- 8 * TickSize) into the variable for your stop loss and similarly the price value for your profit target variable.
        In set 2 you would check to see that you are in a long position. In the actions, you would submit the two orders.

        When one or the other fills the market position changes back to flat and the remaining order would be canceled.



        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Thank you for the explanation Paul, seems like it makes more sense to just do it via the code rather than the builder in that case. I've tried moving the set profit and set stop loss code ahead of the entry coding as you suggested but I am still getting the same results as shown here. Regardless of how many ticks I specify the order ends up hundreds of ticks away. Both the MIN/MAX and the High/LOW code seems to produce the same results. Any idea what could be going wrong?

          HTML Code:
           // Set 6
          if ((Buy_Price > 0)
          && (Cancel_Order > 0))
          {
          SetProfitTarget(@"Long", CalculationMode.Ticks, Target);
          SetStopLoss(@"Long", CalculationMode.Ticks, (MIN(Low,3)[1] + (-8 * TickSize)), false);
          
          EnterLongMIT(Convert.ToInt32(Order_Qty), Buy_Price, @"Long");
          Cancel_Order = Cancel_Order -1;
          }
          
          // Set 7
          if ((Sell_Price > 0)
          && (Cancel_Order > 0))
          {
          SetProfitTarget(@"Short", CalculationMode.Ticks, Target);
          SetStopLoss(@"Short", CalculationMode.Ticks, (MAX(High,3)[1] + (8 * TickSize)), false);
          
          EnterShortMIT(Convert.ToInt32(Order_Qty), Buy_Price, @"Short");
          Cancel_Order = Cancel_Order -1;
          }
          Attached Files

          Comment


            #6
            Okay update, I changed the calculation mode to price as shown below and it seems to be working. Great! Couple of questions to clarify though. Why exactly doesn't it work in calculation mode ticks? I see the SetProfitTarget seems to work fine with that mode. Is there any reason I would have to change it to price there as well? Also, are there any other additional considerations to take into account when doing it the manual way as there are if attempting this by using the builder? It seems to be working fine so far. Thank you so much and best!


            PHP Code:
            SetProfitTarget(@"Long"CalculationMode.TicksTarget);
            SetStopLoss(@"Long"CalculationMode.Price, (MIN(Low,3)[1] + (-TickSize)), false); 

            Comment


              #7
              Hello augustfay,

              Thanks for your post.

              That was my error that missed using CalculationMode.ticks so using CalculationMode.Price was the correct move there because you are calculating a price level and not the number of ticks.

              When you use CalculationMode.Ticks, whatever value is determined will be based on the integer value which then would be converted to ticks and added (or subtracted) to the enrty price. For example, if you are trading ES which is currently around 4200, then that mode would produce an addition (or subtraction) of 4200 ticks to the entry price.

              Your profit target is using CalculationMode.Ticks and it is fine because you are specifying the number of ticks (from the entry price).

              There is no issue using the different modes (as long as you pay attention to which mode is being used!)

              The set methods are easier to use but in the strategy builder should only be used with a fixed value that would be the same on every trade. In a Ninjascript strategy, you can use them in OnBarUpdate() which allows you to use them with price-based data. The main concern would be to make sure that they are set before placing your entry order.

              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Thank you Paul. Just to make sure I completely understand, when you say "the main concern would be to make sure that they are set before placing your entry order"...do you mean as in the actual line of code should be written before?

                While I have you, I also have another issue. I'm trying to set another condition so that an order is canceled once price moves 20 ticks into profit and a supertrend is crossed. This isn't working either and is just canceling my order immediately after entry. What is wrong here? Thanks again!
                [CODE
                ]if ((Position.MarketPosition == MarketPosition.Long)
                && (Position.GetUnrealizedProfitLoss(PerformanceUnit. Ticks, Close[0]) > 20)
                && (Low[0] <= AuSuperTrendU111.StopDot[0]))
                BackBrush = Brushes.Gold;
                {
                ExitLong(Convert.ToInt32(DefaultQuantity), "Trail", "");
                }
                [/CODE]

                Comment


                  #9
                  Hello augustfay,

                  Thanks for your reply.

                  "Thank you Paul. Just to make sure I completely understand, when you say "the main concern would be to make sure that they are set before placing your entry order"...do you mean as in the actual line of code should be written before?" Correct. The set methods retain the last price used so it is critical that before the next entry that they are set to a value suitable for the next trade (When using CalculationMode.Price).

                  In your code example it appears you have your if statement, then coloring the back brush, then the exit order. The if statement will only affect the next line/statement which is the backbrush. The exitlong is not tied to anything so it will fire immediately.

                  What you want is to make sure that immediately after the if statement you have an opening { and that all the things you want to do are inside of the opening and this closing }. When using the { } all of the actions will be executed when the if statement is true. When you do not use { immediately after the if statement, then only the very next line would be affected by the if statement.

                  This is more of a C# syntax error than a ninjscript question. You may want to look into a C# tutorial online.
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Ah okay, thank you for bearing with me. I was just trying to put the brushes there to make it easily identifiable while I worked on the script. That makes sense, they just belong inside the {}.

                    The various parameters inside my strategy properties are beginning to get a little unorganized. How do I add the subsections or folders inside that menu? Is there documentation somewhere on that? Thank you so much for your help!

                    Comment


                      #11
                      Hello augustfay,

                      Thanks for your reply.

                      You can use #region Name and #endregion to create a collapsible region that does not effect the coding but does provide you some control over the view. using #region will create small [] by the line number that you can then click to collapse or expand. #region Properties is a common one.

                      I'm not sure if that is what you are looking for. Your question is more of a C# than a Ninjascript so our recommendation would be to find an on-line source on C#.

                      Paul H.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Paul I've noticed another problem, maybe you can point me in the right direction. It appears that sometimes the stop order now changes its position, as in it moves itself farther away as price moves towards it and should be getting stopped out. Any ideas on what could be causing this? I'm guessing the MIN/MAX settings keep getting a applied as price moves in the wrong direction and new candles form.

                        Comment


                          #13
                          Hello augustfay,

                          Thanks for your reply.

                          I would agree with your assessment concerning the MIN./MAX updating.

                          You would need to determine a condition that is true only once where you are setting the stop-loss values so that they are set once and then not again until you are flat. Perhaps checking that the marketPosition is flat would work for you because once you are in a position then you would no longer be flat.

                          Reference: https://ninjatrader.com/support/help...etposition.htm
                          Paul H.NinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by GussJ, 03-04-2020, 03:11 PM
                          15 responses
                          3,271 views
                          0 likes
                          Last Post xiinteractive  
                          Started by Tim-c, Today, 02:10 PM
                          1 response
                          8 views
                          0 likes
                          Last Post NinjaTrader_ChelseaB  
                          Started by Taddypole, Today, 02:47 PM
                          0 responses
                          2 views
                          0 likes
                          Last Post Taddypole  
                          Started by chbruno, 04-24-2024, 04:10 PM
                          4 responses
                          51 views
                          0 likes
                          Last Post chbruno
                          by chbruno
                           
                          Started by TraderG23, 12-08-2023, 07:56 AM
                          10 responses
                          403 views
                          1 like
                          Last Post beobast
                          by beobast
                           
                          Working...
                          X