Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Error with Alternate Way of Setting Stop Loss

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

    Error with Alternate Way of Setting Stop Loss

    Hi NT,

    For various reasons (mainly since I eventually plan to send Stop Loss orders to different BarsArrays) I have been trying to build a way to do Stop Loss orders without using your SetStopLoss() method.

    Using your Strategy Wizard, I built a strategy that is supposed to exit a Long trade once it has a loss of 10 ticks.
    For some reason, when I test it out in the Strategy Analyzer, it immediately exits a trade after the order is filled, rather then waiting for a 10 tick loss.

    Any idea why this is?

    The relevant part of the strategy's code is below. The attached ExitExample.zip contains the full strategy.

    Thanks!

    Code:
        public class ExitExample : Strategy
        {
            #region Variables
            // Wizard generated variables
            private int stopLoss1 = -10; // Default setting for StopLoss1
            // User defined variables (add any user defined variables below)
            #endregion
    
            /// <summary>
            /// This method is used to configure the strategy and is called once before any strategy method is called.
            /// </summary>
            protected override void Initialize()
            {
                Add(MACD(12, 26, 9));
                Add(MACD(12, 26, 9));
    
                CalculateOnBarClose = true;
            }
    
            /// <summary>
            /// Called on each bar update event (incoming tick)
            /// </summary>
            protected override void OnBarUpdate()
            {
                // Condition set 1
                if (Position.MarketPosition == MarketPosition.Flat
                    && CrossAbove(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))
                {
                    EnterLong(DefaultQuantity, "");
                }
    
                // Condition set 2
                if (Position.MarketPosition == MarketPosition.Long
                    && Open[0] + StopLoss1 * TickSize <= Position.AvgPrice)
                {
                    ExitLong("", "");
                }
    ]
    Attached Files

    #2
    Hello,
    I have tested the strategy on my end and I am seeing that the Open[0] is consistently less than the Position.AvgPrice thus submitting the exit order.
    The most effective way to have the stop loss would be to use the SetStopLoss() method and set it for 10 ticks.
    If you are using the strategy wizard you can do this from the stops and targets menu.
    Cody B.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the response Cody.

      Attached is a screenshot from the Strategy Analyzer after I ran the strategy on 1 tick Last bars. Notice that the exit happens immidiatly after the entry, even though the price of the 1 tick Last bar did not change.

      Why is this?

      From what I understand, if I buy 1 contract for 1941.50 then the Position.AvgPrice should equal 1941.50. Or have I misunderstood how Position.AvgPrice works?

      Regarding SetStopLoss() please see below quote from my original post on why I don't want to use it. To elaborate a little further on why I don't want to use it is because it only works on BarsInProgress == 0 and I'd like to be able to calculate/execute stop losses on multiple different BarsArrays a strategy contains (such as BarsInProgress == 1 and BarsInProgress == 2).

      For various reasons (mainly since I eventually plan to send Stop Loss orders to different BarsArrays) I have been trying to build a way to do Stop Loss orders without using your SetStopLoss() method.
      Thanks again!
      Attached Files
      Last edited by Matheyas5; 03-31-2016, 06:08 PM.

      Comment


        #4
        Originally posted by Matheyas5 View Post
        Hi NT,

        For various reasons (mainly since I eventually plan to send Stop Loss orders to different BarsArrays) I have been trying to build a way to do Stop Loss orders without using your SetStopLoss() method.

        Using your Strategy Wizard, I built a strategy that is supposed to exit a Long trade once it has a loss of 10 ticks.
        For some reason, when I test it out in the Strategy Analyzer, it immediately exits a trade after the order is filled, rather then waiting for a 10 tick loss.

        Any idea why this is?

        The relevant part of the strategy's code is below. The attached ExitExample.zip contains the full strategy.

        Thanks!

        Code:
            public class ExitExample : Strategy
            {
                #region Variables
                // Wizard generated variables
                private int stopLoss1 = -10; // Default setting for StopLoss1
                // User defined variables (add any user defined variables below)
                #endregion
        
                /// <summary>
                /// This method is used to configure the strategy and is called once before any strategy method is called.
                /// </summary>
                protected override void Initialize()
                {
                    Add(MACD(12, 26, 9));
                    Add(MACD(12, 26, 9));
        
                    CalculateOnBarClose = true;
                }
        
                /// <summary>
                /// Called on each bar update event (incoming tick)
                /// </summary>
                protected override void OnBarUpdate()
                {
                    // Condition set 1
                    if (Position.MarketPosition == MarketPosition.Flat
                        && CrossAbove(MACD(12, 26, 9).Avg, MACD(12, 26, 9), 1))
                    {
                        EnterLong(DefaultQuantity, "");
                    }
        
                    // Condition set 2
                    if (Position.MarketPosition == MarketPosition.Long
                        && Open[0] + StopLoss1 * TickSize <= Position.AvgPrice)
                    {
                        ExitLong("", "");
                    }
        ]
        ExitLong(...) is a Market Order to exit the position, not a Stop Loss order. A Stop Loss Market Order would be ExitLongStop(...).

        Comment


          #5
          Originally posted by koganam View Post
          ExitLong(...) is a Market Order to exit the position, not a Stop Loss order. A Stop Loss Market Order would be ExitLongStop(...).
          Koganam is correct here, you would use ExitLongStop() rather than ExitLong().

          Comment


            #6
            Hi Patrick,


            Rather then setting a stop price within ExitLongStop(), you'll see that I coded my strategy to detect if the position lost 10 ticks via simply checking if the Open is 10 ticks lower then the Position.AvgPrice (and then exiting the long position via ExitLong() accordingly).

            I still don't understand why ExitLong() does not work in this situation.

            Thanks

            Comment


              #7
              Originally posted by Matheyas5 View Post
              Hi Patrick,


              Rather then setting a stop price within ExitLongStop(), you'll see that I coded my strategy to detect if the position lost 10 ticks via simply checking if the Open is 10 ticks lower then the Position.AvgPrice (and then exiting the long position via ExitLong() accordingly).

              I still don't understand why ExitLong() does not work in this situation.

              Thanks
              It is doing exactly what you told it to do that you are describing above. The Open is more than 10 ticks lower than the entry, so it exits. You are entering on the Close of the bar (COBC = true), so if the Open to Close range of the bar equals or exceeds 10 ticks, voila.

              Appropos of which, my initial response would result in a rejected stop loss order too, as it would be placing a sell stop ahead of the market.

              Comment


                #8
                Hi Kognam,

                You said
                The Open is more than 10 ticks lower than the entry, so it exits.
                I do not think this is correct.

                Please see screenshot in post #3 of this thread, which shows it exits even though the Open price is exactly the same as the entry price.

                thanks.

                Comment


                  #9
                  Originally posted by Matheyas5 View Post
                  .
                  For some reason, when I test it out in the Strategy Analyzer, it immediately exits a trade after the order is filled, rather then waiting for a 10 tick loss.
                  In the Strategy Analyzer backtest the results are base don the Open, High, Low, and Close of the bar. So the calculations for the fills occur on the close of the bar if the open of the current bar is less than the average price of the position - 10 ticks it exits.

                  You may want to try the following instead and see if the results are a bit closer to what you expect:
                  Code:
                              if (Position.MarketPosition == MarketPosition.Long
                                  && [B]Close[0][/B] + StopLoss1 * TickSize <= Position.AvgPrice)
                              {
                                  ExitLong("", "");
                              }

                  Comment


                    #10
                    Originally posted by Matheyas5 View Post
                    Hi Kognam,

                    You said


                    I do not think this is correct.

                    Please see screenshot in post #3 of this thread, which shows it exits even though the Open price is exactly the same as the entry price.

                    thanks.
                    My mistake. I did not realize that you are using a 1-tick DataSeries. However, that actually pretty much guarantees that your exit condition is instantly met. Your picture is showing that your Open is pretty much the same as your Close, so let us see what your exit condition really means:

                    Your condition examines Open[0] + StopLoss1 * TickSize in comparison to the entry price. Which is saying that if the Open minus 10 ticks is less than the Open (==Close), then Exit(). That is an identically true statement. Anything minus 10 ticks is less than itself.

                    Which means that I have to reverse myself again, and say that on a 1-tick BarSeries, a 10-tick Stop Loss will not be rejected.

                    For what you seem to want to write as opposed to what you wrote, you want to examine your inequality and your StopLoss1 value declaration. Either:
                    • Make the latter positive instead of negative,
                    • Or if that is less intuitive to you, then shift the StopLoss1 value and its tick multiplier to the other side of the inequality
                    • Or leave the StopLoss1 value and its tick multiplier where it is but subtract it instead of adding it (which makes it even less intuitive, it would seem to me).

                    Comment


                      #11
                      Thanks for pointing that out Kognam. Now I see why the logic of my original code did not make any sense. I'm a fool for not realizing the logic issue right away

                      Anyway, to accomplish what I was trying I should have written the code as this:

                      Code:
                                  if (Position.MarketPosition == MarketPosition.Long
                                      && Open[0] <= Position.AvgPrice + StopLoss1 * TickSize)
                                  {
                                      ExitLong("", "");
                                  }
                      Instead of this:

                      Code:
                                  if (Position.MarketPosition == MarketPosition.Long
                                      && Open[0] + StopLoss1 * TickSize <= Position.AvgPrice)
                                  {
                                      ExitLong("", "");
                                  }
                      thanks again everyone, have a great weekend.

                      Comment

                      Latest Posts

                      Collapse

                      Topics Statistics Last Post
                      Started by lorem, Today, 09:18 AM
                      1 response
                      4 views
                      0 likes
                      Last Post lorem
                      by lorem
                       
                      Started by bmartz, Today, 09:30 AM
                      0 responses
                      1 view
                      0 likes
                      Last Post bmartz
                      by bmartz
                       
                      Started by GussJ, 03-04-2020, 03:11 PM
                      14 responses
                      3,244 views
                      0 likes
                      Last Post GussJ
                      by GussJ
                       
                      Started by ArkansasClint, Today, 09:28 AM
                      0 responses
                      0 views
                      0 likes
                      Last Post ArkansasClint  
                      Started by hazylizard, Today, 08:38 AM
                      4 responses
                      12 views
                      0 likes
                      Last Post hazylizard  
                      Working...
                      X