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

Strategy: Moving StopLoss

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

    Strategy: Moving StopLoss

    Here's yet another question regarding moving StopLoss in a strategy after a price has reached 20 ticks above the entry price. I can't get the initial stop of 32 ticks to move for the life of me and was wondering if someone can help me figure this out?

    The initial default StopLoss is set to 32 ticks

    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class LongEntry0Cross : Strategy
    {
    private MACD MACD1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Original";
    Name = "LongEntry";
    Calculate = Calculate.OnEachTick;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = true;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    }
    else if (State == State.Configure)
    {
    SetProfitTarget("", CalculationMode.Ticks, 64);
    SetStopLoss("", CalculationMode.Ticks, 32, false);
    }
    else if (State == State.DataLoaded)
    {
    MACD1 = MACD(Close, 12, 26, 11);
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Enters Long on a 0 point cross
    if (CrossAbove(MACD1.Diff, 0, 1))
    {
    EnterLong(Convert.ToInt32(Position.Quantity), @"Long Zero");
    }

    // Resets the stop loss to the original value when all positions are closed
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss("", CalculationMode.Ticks, 32, false);
    }

    // If a long position is open, allow for stop loss modification to +5 ticks above entry else if (Position.MarketPosition == MarketPosition.Long)
    {
    // Once the price is greater or equal to entry price +20 ticks, set stop loss to +5 above entry price
    if (Close[0] > Position.AveragePrice + 20 * TickSize)
    {
    SetStopLoss("", CalculationMode.Ticks, Position.AveragePrice + 1 * TickSize, false);
    }
    }



    }
    }
    }

    #2
    Hello Rogue_Two,

    Thanks for your post.

    In this method: SetStopLoss("", CalculationMode.Ticks, Position.AveragePrice + 1 * TickSize, false); you are specifying the stoploss mode in ticks however you are referencing price with Position.AveragePrice + 1 * TickSize which the method would take the price value as the number of ticks +1.

    Try changing the mode to CalculationMode.Price IE:

    SetStopLoss("", CalculationMode.Price, Position.AveragePrice + 1 * TickSize, false);
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Thank you Paul.

      I implemented the change you suggested and the StopLoss seems to be moving in the opposite direction I need it to and very far away at that. However, at least something is happening now!
      Last edited by Rogue_Two; 04-13-2018, 08:43 AM.

      Comment


        #4
        Hello,

        Thanks for your reply.

        I've created a short video of how this works: https://Paul-ninjaTrader.tinytake.co...I3Ml83NTc0Mjg5

        If your strategy is not moving the stop then there is likely some other reason for this and you would need to debug your strategy. You may wish to replicate my strategy to test for your self.

        Are you running the strategy on live data, replay data or historical data in the analyzer?

        Do you see any error messages in the "log" tab of the control center when you run your strategy?
        Paul H.NinjaTrader Customer Service

        Comment


          #5
          Thanks for the video Paul! Hopefully I can get this figured out now. It seems to be moving now but for some reason it's moving way too far away.

          I am running the strategy on live data.

          Comment


            #6
            Is it possible to have the stop move the instant the price hits 20 ticks away from entry price?

            I just noticed the bar currently has to close before the stop will move.

            Comment


              #7
              Hello Rogue_Two,

              Thanks for your reply.

              In the strategy that you posted in the original post it showed you were using "Calculate = Calculate.OnEachTick;" which would allow a quicker response than waiting for the bar to close.

              You can run your strategy in Calculate.OnEachTick and have some parts still run in OnBaRClose type mode. Here is a link to an example of how to do this: https://ninjatrader.com/support/foru...ad.php?t=19387
              Paul H.NinjaTrader Customer Service

              Comment


                #8
                Oh! Thanks for that Paul.

                This should theoretically move the stops in respective to a long or short position right and then reset the original stop loss when flat right?

                // Resets the stop loss to the original value when all positions are closed
                if (Position.MarketPosition == MarketPosition.Flat)
                {
                SetStopLoss("", CalculationMode.Ticks, 32, false);
                }

                // If a long position is open, allow for stop loss modification to breakeven
                else if (Position.MarketPosition == MarketPosition.Long)
                {
                // Once the price is greater than entry price +20 ticks, set stop loss to breakeven
                if (Close[0] > Position.AveragePrice + 20 * TickSize)
                {
                SetStopLoss("", CalculationMode.Price, Position.AveragePrice + 1 * TickSize, false);
                }
                }

                // If a long position is open, allow for stop loss modification to breakeven
                else if (Position.MarketPosition == MarketPosition.Short)
                {
                // Once the price is less than entry price -20 ticks, set stop loss to breakeven
                if (Close[0] < Position.AveragePrice - 20 * TickSize)
                {
                SetStopLoss("", CalculationMode.Price, Position.AveragePrice - 1 * TickSize, false);
                }
                }

                Comment


                  #9
                  Hello Rogue_Two,

                  Thanks for your reply.

                  Yes.
                  Paul H.NinjaTrader Customer Service

                  Comment


                    #10
                    Great! I'm headed in the right direction thanks to your help.

                    Now I just have to figure out why my break even stop is getting moved 2000 points in the wrong direction and have the cross of the 0 calculating only on bar close while keeping the break even stops calculating on each tick.

                    Comment


                      #11
                      Alright! Stops are moving correctly now!

                      Now I just need to get stops to calculate on tick while a cross of the 0 MACD differential line calculates on bar close.

                      Getting there!

                      Comment


                        #12
                        Hello Rogue_Two,

                        Thanks for your replies and glad to hear of your successes.

                        The secret sauce here would be the use IsFirstTickOfBar which only occurs one per bar.

                        So while your entire code will run Calculate.OnEachTick, code that is encased like this will run once per bars:

                        if (IsFirstTickOfBar)
                        {
                        // anything in here will only run once per bar
                        }
                        //anything out here will run on every tick.


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

                        Comment


                          #13
                          Okay, looks like stops are moving property now!

                          Can this be taken even further and have the stop move once again when 40 ticks is achieved?
                          Last edited by Rogue_Two; 04-14-2018, 02:58 AM.

                          Comment


                            #14
                            Hello Rogue_Two,

                            Yes, you can add as many conditions to move the stop loss as you would like to the script.

                            Below is a public link to an example script.
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Thanks a lot Chelsea! I'm going to go over these and hopefully learn a thing or two

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by manitshah915, Today, 12:59 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post manitshah915  
                              Started by ursavent, Today, 12:54 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post ursavent  
                              Started by Mizzouman1, Today, 07:35 AM
                              3 responses
                              17 views
                              0 likes
                              Last Post NinjaTrader_Gaby  
                              Started by RubenCazorla, Today, 09:07 AM
                              2 responses
                              13 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by i019945nj, 12-14-2023, 06:41 AM
                              7 responses
                              82 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Working...
                              X