Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Just How Does SetTrailStop() Work?

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

    Just How Does SetTrailStop() Work?

    I've read the documentation. I think I understand how trailing stops generally work, but whenever I set a trailing stop in my strategy, the results are never what I expect.
    How does the calculation work when using currency in the trailing stop?
    My assumption was that you would enter a dollar amount for which you want the stop to trail, 3.50 for example to set a stop that trails the price by $3.50.
    The documentation states: The value the trail stop order is offset from the position entry price (exception is using .Price mode where 'value' will represent the actual price)
    This seems to suggest that the value attribute should be set to the actual starting(?) price for the point at which you want the trailing stop to start, but this doesn't calculate as expected either.
    Even when I set to Tick or Percent mode the results are not what I expect. Again, when set to percent, my assumption would have been that the stop will trail the price by a certain percent based on the entry price, but this doesn't calculate as expected either.
    When set to Ticks, I would expect that an 800 tick trailing stop for a stock would trail the price by $8.00 since each tick is .01, but it just doesn't seem to work that way.
    Could someone please explain how the trailing stops are calculated?
    Thanks in advance.
    Last edited by jwitt98; 09-21-2013, 10:38 PM.

    #2
    SetStopLoss() Confusion As Well

    So my confusion also caries over to SetStopLoss() as well. Here is an example of what I am talking about using SetStop Loss()
    Here is my code where I set the stop loss:
    Since this is based on ATR, it is called within OnBarUpdate
    Code:
    if(Position.MarketPosition == MarketPosition.Flat)
    			{
    				SetStopLoss(CalculationMode.Percent, 1000000);
    			}else if(Position.MarketPosition == MarketPosition.Short)
    			{
    				StopAmount = Position.AvgPrice + (ATR(14)[BarsSinceEntry()] * 4);
    				Print(StopAmount);
    				SetStopLoss(StopAmount);
    			}
    My entry point can be seen in the attached "entry point.png" file:
    The entry point is 91.49 with and ATR of 5.71. This puts the StopAmount at 91.49 + (5.71 * 4) or 114.33. This is confirmed by the output window as can bee seen in the attached file "output window.png" This value stays consistent during the duration of the short position.
    So, I expected the stop loss to be hit at or around 114.33, but instead it is triggered at 99.68 as can bee seen in the attached file "StopLoss triggered.png). The blue horizontal line is set at 114.33, where I expected the stop loss to be triggered. As can be seen, the price is nowhere near that value.
    Maybe I am doing something wrong or maybe I'm just not understanding how NT calculates Stop Losses. I'm hoping someone can help me figure this out...
    Thanks
    Attached Files

    Comment


      #3
      Hello jwitt98,

      Thank you for your post.

      With SetTrailStop() price is irrelevant as the CalculationMode.Price is absolute price not the amount of currency from the average entry price. So 3.50 is literally submitting the Stop Loss order at 3.50 on the price scale for the instrument. Only Percent and Ticks work for SetTrailStop().

      For information on SetTrailStop() please visit the following link: http://www.ninjatrader.com/support/h...ttrailstop.htm

      I tested your code out on my end for the SetStopLoss() and I do not see the same behavior on my end. Can you provide your strategy or a toy version in your response so I may test this matter further on my end?

      I look forward to assisting you further.

      Comment


        #4
        Thank you Patrick.
        So what you are saying is that setting the trailing stop using currency to 3.50 is the same as setting a stop loss at 3.50. Does the stop not trail the price when using currency?

        Here is a stripped down version of the strategy I am toying with:
        Code:
        #region Using declarations
        using System;
        using System.ComponentModel;
        using System.Diagnostics;
        using System.Drawing;
        using System.Drawing.Drawing2D;
        using System.Xml.Serialization;
        using NinjaTrader.Cbi;
        using NinjaTrader.Data;
        using NinjaTrader.Indicator;
        using NinjaTrader.Gui.Chart;
        using NinjaTrader.Strategy;
        #endregion
        
        // This namespace holds all strategies and is required. Do not change it.
        namespace NinjaTrader.Strategy
        {
            /// <summary>
            /// Breakout strategy using bollinger bands
            /// </summary>
            [Description("Breakout strategy using bollinger bands")]
            public class BollingerBreakoutStrategy : Strategy
            {
                #region Variables
        		
                private double standardDeviations = 2.5; // Default setting for StandarDeviations
                private int bollingerPeriod = 300; // Default setting for BollingerPeriod
        		
        		private bool enableLongPositions = true;
        		private bool enableShortPositions = true;
        		
                private double accountRiskPercent = 0.01; // Default setting for AccountRiskPercent
        		
        		double StopAmount;
        		
                #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(Bollinger(StandardDeviations, BollingerPeriod));
        			Add(ATR(14));
        			AccountSize = 30000;
        			BarsRequired = 	BollingerPeriod;
                    CalculateOnBarClose = false;
                }
        
                /// <summary>
                /// Called on each bar update event (incoming tick)
                /// </summary>
                protected override void OnBarUpdate()
                {
        			double Risk = Math.Abs(Close[0] - Bollinger(StandardDeviations, BollingerPeriod).Middle[0]);
        			int PositionQuantity = (int)((AccountSize * AccountRiskPercent) / Risk); 
        			
        			if(Position.MarketPosition == MarketPosition.Flat)
        			{
        				SetStopLoss(CalculationMode.Percent, 1000000);
        			}else if(Position.MarketPosition == MarketPosition.Short)
        			{
        				StopAmount = Position.AvgPrice + (ATR(14)[BarsSinceEntry()] * 4);
        				Print(StopAmount);
        				SetStopLoss(StopAmount);
        			}
        			
        			//Conditions to Enter Long positions
                    if (EnableLongPositions == true
        				&& Position.MarketPosition == MarketPosition.Flat
        				&& PositionQuantity > 0
        				&& Close[0] > Bollinger(StandardDeviations, BollingerPeriod).Upper[0])
                    {
                        EnterLong(PositionQuantity, "Enter Long");
        				
                    }
        
                    // Conditions to Exit Long positions
                    if (Close[0] < Bollinger(StandardDeviations, BollingerPeriod).Middle[0])
                    {
                        ExitLong("Exit Long", "");
                    }
        
                    // Conditions to Enter Short positions
                    if (EnableShortPositions == true 
        				&& Position.MarketPosition == MarketPosition.Flat
        				&& PositionQuantity > 0
        				&& (BarsSinceExit() > 65 || BarsSinceExit() == -1)
        				&& Close[0] < Bollinger(StandardDeviations, BollingerPeriod).Lower[0])
                    {
                        EnterShort(PositionQuantity, "Enter Short");
                    }
        
                    // Conditions to Exit Short positions
                    if (Close[0] > Bollinger(StandardDeviations, BollingerPeriod).Middle[0])
                    {
                        ExitShort("Exit Short", "");
                    }	
                }
        
                #region Properties
        		
                [Description("The number of devaitions to offfset the upper and lower Bollinger bands")]
                [GridCategory("Parameters")]
                public double StandardDeviations
                {
                    get { return standardDeviations; }
                    set { standardDeviations = Math.Max(0.25, value); }
                }
        
                [Description("The period of the moving average of the Bolliger band")]
                [GridCategory("Parameters")]
                public int BollingerPeriod
                {
                    get { return bollingerPeriod; }
                    set { bollingerPeriod = Math.Max(1, value); }
                }
        		
        		[Description("Enable or disable whether the strategy takes long positions")]
                [GridCategory("Parameters")]
                public bool EnableLongPositions
                {
                    get { return enableLongPositions; }
                    set { enableLongPositions = value; }
                }
        		
        		[Description("Enable or disable whether the strategy takes short positions")]
                [GridCategory("Parameters")]
                public bool EnableShortPositions
                {
                    get { return enableShortPositions; }
                    set { enableShortPositions = value; }
                }
        
                [Description("The pecentage of the account to risk per trade")]
                [GridCategory("Parameters")]
                public double AccountRiskPercent
                {
                    get { return accountRiskPercent; }
                    set { accountRiskPercent = Math.Max(0.005, value); }
                }
                #endregion
            }
        }
        Please let me know if you can see why my stop loss is not calculating correctly.

        Comment


          #5
          Hello jwitt98,

          Thank you for your response.

          The price value is the literal price not price away from the current price. An example would be let's say I enter at 500 and my Stop Loss is set to Price for CalculationMode and the value is 450, my Stop Loss would be submitted 50 away from the entry of 500 as it was submitted at 450. The Stop Loss would not be submitted 450 away from the entry price.

          If the ES 12-13 is at 1639.5 and I enter at that price and my Stop Loss is set to CalculationMode.Price and the value is 3.5, the Stop Loss will be submitted to 3.5 not 1636.00.

          With SetTrailStop() CalculationMode.Price is useless as this is a set value that never changes so it will not "trail' the current market price.

          For your strategy, are you running this on the Strategy Analyzer for the IBM Daily? Or are you just viewing the Historical Performance on your chart?

          If you are using the Strategy Analyzer please take a screenshot of the Backtest properties used and attach the screenshot to your response.

          Comment


            #6
            Yes, I am running the strategy analyzer on the daily time frame. Attached is the screen shot. In the attached screen shot you can see the BA chart where the stop loss was hit at 82.46.
            I expected it to not be triggered until 88.35
            Position.AvgPrice + (ATR(14)[BarsSinceEntry()] * 4)
            77.79 + (2.64 * 4) = 88.35
            The output window once again confirms the StopAmount variable as being set to 88.359160286671

            The above is using StopLoss(), but going back to the subject of TrailingStop(), I understand that using CalculateMode.Price is of no use which means that percent or ticks are the only valid options. Now that I understand this, I should be able to do some calculations to come up with the correct percent where I want the trailing stop to begin.
            I guess my next question would be about how the percent trailing stop works. Say you have an entry price of 10.00 and you set a trailing stop at 10%. Does the stop then trail the price by 1.00 (10% of 10.00) for the duration of the position or does the trailing stop recalculate on every bar so that when the price moves to 11.00, does the trailing stop move to 9.90 (11.00 - (10% of 11) or does it move to 10.00 (11 - (10% of 10)?
            Attached Files

            Comment


              #7
              Hello jwitt98,

              Thank you for your patience.

              I am seeing the same item on my end. I will test this further on my end and follow up with you further on this matter.

              The CalculationMode.Percent will always be the set number of percent behind the last traded price with SetTrailStop(). So it will calculate it's value for the stop based off of the last traded price as the price moves.

              I look forward to assisting you further.

              Comment


                #8
                Just wondering if you've had a chance to test this. I can't seem to get either SetStopLoss() or SetTrailingStop() to work as expected no matter how I use them. Even when I use them in the initialize section they don't seem to work right.

                Comment


                  #9
                  I just figured this out the problem with SetStopLoss()...
                  Apparently it doesn't like more than two decimal places. The way I was calculating the results was setting the stop value to more than two decimal places. Once I rounded off, it started working as expected.
                  Math.Round(StopAmount, 2); //this did the trick
                  Now to see if the same applies to SetTrailingStop()

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                  0 responses
                  650 views
                  0 likes
                  Last Post Geovanny Suaza  
                  Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                  0 responses
                  370 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by Mindset, 02-09-2026, 11:44 AM
                  0 responses
                  109 views
                  0 likes
                  Last Post Mindset
                  by Mindset
                   
                  Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                  0 responses
                  574 views
                  1 like
                  Last Post Geovanny Suaza  
                  Started by RFrosty, 01-28-2026, 06:49 PM
                  0 responses
                  577 views
                  1 like
                  Last Post RFrosty
                  by RFrosty
                   
                  Working...
                  X