Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Does SetTrailStop work with StrategyAnalyzer?

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

    Does SetTrailStop work with StrategyAnalyzer?

    I'm trying to add trailing stops to a multi-instrument strategy and having trouble getting it to work, when backtesting the strategy. Here is basically what the code looks like:

    OnBarUpdate() {
    ....
    SetTrailStop("[0] Buy 1729 XLY", CalculationMode.Percent, 0.1, false);
    EnterLong(0, 1729, "[0] Buy 1729 XLY");
    }

    When the code was executed in StrategyAnalyzer, it appears that the trailing stop price was set to the filled price of EnterLong() rather than 10% below. Consequently, the trailing stop order was triggered and filled exactly at the entry price, as soon as the buy order was filled. See the attached image.
    Here is the log:
    -----------------------------------
    1/29/2010 9:00:00 PM Entered internal SetStopTarget() method: Type=TrailStop FromEntrySignal='[0] BUY 1729 XLY' Mode=Percent Value=0.1 Currency=0 Simulated=False
    1/29/2010 enterLongPosition (20, SHY) on bar[270] EnterLong (cash= 50000.00 size= 1.00 price= 28.91 stop= 28.87 '[0] BUY 1729 XLY')
    1/29/2010 1:00:00 PM Entered internal PlaceOrder() method at 1/29/2010 1:00:00 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1,729 LimitPrice=0 StopPrice=0 SignalName='[0] BUY 1729 XLY' FromEntrySignal=''
    1/29/2010 OnExecution (0, XLY) on bar[270] Order='NT-00000/Backtest' Name='[0] BUY 1729 XLY' State=Filled Instrument='XLY' Action=Buy Limit price=0 Stop price=0 Quantity=1,729 Strategy='MyRS' Type=Market Tif=Gtc Oco='' Filled=1729 Fill price=28.97 Token='90abae11480b4e28a1bacef794714fc2' Gtd='12/1/2099 12:00:00 AM'
    1/29/2010 OnExecution (0, XLY) on bar[270] Order='NT-00002/Backtest' Name='Trail stop' State=Filled Instrument='XLY' Action=Sell Limit price=0 Stop price=75.17 Quantity=1,729 Strategy='MyRS' Type=Stop Tif=Gtc Oco='NT-00000-743' Filled=1729 Fill price=28.97 Token='1fcabbbab6e447539c756722a01d11b4' Gtd='12/1/2099 12:00:00 AM'
    ------------------------------------------------------------
    The reason why I have SetTrailStop() in OnBarUpdate() is that I want to eventually set the stop based on ATR of the instrument - so, it's not static. I tried that with CalculationMode.Ticks and had the same problem. I don't have SetStopLoss() anywhere in the strategy. The strategy runs on the daily timeframe.
    Attached Files
    Last edited by cartoosh; 09-17-2013, 11:37 PM. Reason: more details

    #2
    Hello cartoosh,

    Thank you for your post.

    The Stop Loss order was submitted at 75.17 which was above the price it filled at 28.97. As this was a Sell Stop Order it was filled at market as it was above the market price. Sell Stop Orders must be submitted below the market price.

    This can occur when you do not reset the SetTrailStop() when flat, you should always reset the trail stop price/offset value when your strategy is flat otherwise, the last price/offset value set will be used to generate your trail stop order on your next open position

    You can find an example of resetting a Stop Loss when flat at the following link: http://www.ninjatrader.com/support/f...ead.php?t=3222

    Please let me know if you have any questions.

    Comment


      #3
      Hi,
      Thank you for helping.
      You brought up a good point on the stop price. I was wondering where the price of 75.17 came from. There are still things to clarify:

      1. The reason why I didn't reset the stop price, when the position went flat, was because SetTrailStop() was called right before EnterLong(). So, I thought the stop price was therefore "reset". No?
      2. Since I set the trail stop at 10% below the entry price, I assumed NT would record the "10%" setting rather than a specific price. In fact, CalculationMode.Price can't be used for SetTrailStop(). Right?
      3. The trace I included was the 1st order made by the strategy. If re-running the backtest was supposed to start from a clean sheet, then the only call that set the trail stop was SetTrailStop() right before EnterLong() and NT should calculate the new stop price 10% below, unless the backtest did not start "clean." That is, during the last run of the backtest, the strategy might have used 75.17 as the stop price. Somehow, that stop price "sneaked" into the next run of backtest. If this was true, then it would be a bug in NT.

      Comment


        #4
        Hello cartoosh,

        Thank you for your response.

        The SetTrailStop() should be reset when flat no matter what, without this in place you could see this item in backtesting as you detailed and in live trading. The 10% value was likely used from the last time SetTrailStop() was called.

        Please let me know if resetting the SetTrailStop() when flat resolves this matter.

        Comment


          #5
          In my case, SetTrailStop() is always called with a specific fromEntrySignal. Using the above example, are you saying, when that specific XLY position goes flat, I should reset the stop as follows?

          if (Positions[0].MarketPosition == MarketPosition.Flat)
          SetTrailStop("[0] Buy 1729 XLY", CalculationMode.Percent, 0.1, false);

          But, my next long position will be entered with a different fromEntrySignal. I'm confused.

          Comment


            #6
            Hello cartoosh,

            Thank you for your response.

            In that case you will be resetting to SetTrailStop()s, one for each fromEntrySignal.

            Please let me know if I may be of further assistance.

            Comment


              #7
              Hi,

              I added the following code to the strategy and it still doesn't work. Neither did I try SetTrailStop() with a specific fromEntrySignal. Not sure it matters, but just want to point out that this is a multi-instrument strategy where it adds several instruments in Initialize().

              -----------------------------------
              Initialize() { ...
              // add additional instruments
              Add(..);
              Add(..);
              ...
              if (typeStop == StopType.TrailStopATR)
              SetTrailStop(CalculationMode.Ticks, 1000);
              else if (typeStop == StopType.TrailStopPercentage)
              SetTrailStop(CalculationMode.Percent, trailStopInput);
              }

              OnBarUpdate() {
              Position p = ...
              if (p.MarketPosition == MarketPosition.Flat) {
              if (typeStop == StopType.TrailStopATR)
              SetTrailStop(CalculationMode.Ticks, 1000);
              else if (typeStop == StopType.TrailStopPercentage)
              SetTrailStop(CalculationMode.Percent, trailStopInput);
              }
              ...
              }
              ---------------------------------

              Comment


                #8
                Hello cartoosh,

                Thank you for your response.

                Can you provide details on what is not working with this code?

                And if possible could you provide the strategy or a toy version to test on my end with instructions to reproduce this matter?

                I look forward to your response.

                Comment


                  #9
                  SetTrailStop() on an instrument that is not being updated by OnBarUpdate()

                  Hi,

                  I've finally found the root cause of the problem. I've attached a simple strategy to reproduce the problem and the output traces. To reproduce the problem, you must run the strategy against QQQ. Once run, you can see in the chart where all the QQQ long positions are exited immediately after filled.

                  The simple strategy deals with two instruments: SPY and QQQ. It will enter a long position on QQQ and set the trailing stop upon a buy signal of SPY. Both the buy and trailing stop orders are set, when OnBarUpdate() is called on SPY. The buy orders functioned as designed. But, the trailing stops were set using the price of SPY instead of QQQ!

                  I believe that there are missing SetTrailStop() and other stop related APIs to support multi-instance use cases. At least, I didn't find them.
                  Attached Files

                  Comment


                    #10
                    Hello cartoosh,

                    So the reason why this is happening is because SetTrailStop() is using the price of the SPY instrument which is why the stop price is being set so high and then being filled right away.

                    You may want to use Closes[][] to get the EMAs for SPY and then submit the orders inside of the Primary bar if you want to use SetTrailStop(). You may view our Help Guide at the following link for an example of how to use Closes to get the indicator values of another Bar Series.


                    Note that you can also use SetStopLoss and the change Set Stop Loss.
                    JCNinjaTrader Customer Service

                    Comment


                      #11
                      Hi,

                      I understand how to use Closes[][] to work around this particular scenario implemented in this sample, but it wouldn't work for the more sophisticated strategy I'm working on. I was just trying to make up a simple test case to point out the discrepancies in stop related APIs as compared to order APIs.

                      In other words, the order APIs support the case where an order can be submitted on instrument B, while OnBarUpdate() is being called on instrument A. The stop APIs don't support this case. There should be new stop-related APIs that takes barsInProgressIndex as a parameter.

                      Do you agree?

                      Comment


                        #12
                        Hi,

                        The Set..() methods are working under a convenience layer and have some limitations. We appreciate your feedback here and will submit as a use case to improve the logic handling of the Set methods.

                        In the meantime time you can always use the Managed methods to specify an order type on a specific bars in progress which gives you more control.
                        MatthewNinjaTrader Product Management

                        Comment


                          #13
                          Improving these methods by adding a barsInProgressIndex is on our feedback list using ID # 1813
                          MatthewNinjaTrader Product Management

                          Comment


                            #14
                            Hi,

                            Thank you for submitting the feedback. In your last reply, did you mean to say that I may implement trailing stops using "un-managed" methods?

                            Comment


                              #15
                              Hi,

                              No, you do not need to quite as far as unmanaged. In addition to SetStopLoss,etc, we have ExitLongStop/ExitShortStop which has a property to assign a barsInProgress index:



                              Of course there is not an auto trail function of these methods, so you would need to emulate the resubmission of the code under certain conditions.
                              MatthewNinjaTrader Product Management

                              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