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

Setting Dynamic ATR Stop

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

    Setting Dynamic ATR Stop

    Hello I am trying to develop a simple trend strategy which includes a stop loss based on ATR*2 from the entry signal. Below is my code but it doesnt seem to be working correct. Any feedback would be appreciated.

    public class ShortTermBreakOutATR : Strategy
    {
    #region Variables
    // Wizard generated variables
    private int myInput0 = 1; // Default setting for MyInput0
    // 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()
    {


    if (Position.MarketPosition == MarketPosition.Long)
    {
    //Print ATRStopLoss
    double value = Position.AvgPrice-(ATR(14)[1]*2);
    Print ("The Current value is " + value.ToString());
    SetStopLoss(CalculationMode.Price,(Position.AvgPri ce-(ATR(14)[1]*2)));
    }

    if (Position.MarketPosition == MarketPosition.Short)
    {
    //Print ATRStopLoss
    double value = Position.AvgPrice-(ATR(14)[1]*2);
    Print ("The Current value is " + value.ToString());
    SetStopLoss(CalculationMode.Price,(Position.AvgPri ce+(ATR(14)[1]*2)));
    }


    CalculateOnBarClose = true;
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Condition set 1
    if (GetCurrentBid() > Close[15]
    && RSI(14, 3).Avg[0] < 70)
    {
    EnterLong(DefaultQuantity, "Long");
    DrawDot("My dot" + CurrentBar, false, 0, 0, Color.Green);
    }

    // Condition set 2
    if (Close[0] < Close[7])
    {
    ExitLong("Exit", "Long");
    }

    // Condition set 3
    if (GetCurrentBid() < Close[15]
    && RSI(14, 3).Avg[0] > 30)
    {
    EnterShort(DefaultQuantity, "Short");
    DrawDot("My dot" + CurrentBar, false, 0, 0, Color.Red);
    }

    // Condition set 4
    if (Close[0] > Close[7])
    {
    ExitShort("Exit", "Short");
    }

    }

    #2
    Hello smwolf85,
    Thanks for posting today.

    The area you have highlighted is what is causing your strategy to not enable.
    • if (Position.MarketPosition == MarketPosition.Long)

    The position object can not be called in the intialize method as this is going to return the strategy position which is has not taken yet.

    This would need to be moved to another method, such as the OnBarUpdate() method.

    Please let us know if we may be of further assistance for anything NinjaTrader.
    Alex G.NinjaTrader Customer Service

    Comment


      #3
      Thank you for the response: I have changed it so it is as follows with the stop coding in red again. It seems like the stop loss is initiated immediately and the exit price is the same as the entry price. Do you know why this would be? Thanks!

      /// </summary>
      protected override void OnBarUpdate()
      {
      // Condition set 1
      if (GetCurrentBid() > Close[15]
      && RSI(14, 3).Avg[0] < 70)
      {
      EnterLong(DefaultQuantity, "Long");
      DrawDot("My dot" + CurrentBar, false, 0, 0, Color.Green);

      if (Position.MarketPosition == MarketPosition.Long)
      {
      //Print ATRStopLoss
      double value = Position.AvgPrice-(ATR(14)[1]*2);
      Print ("The Current value is " + value.ToString());
      SetStopLoss(CalculationMode.Price,(Position.AvgPri ce-(ATR(14)[1]*2)));
      }


      }

      // Condition set 2
      if (Close[0] < Close[7])
      {
      ExitLong("Exit", "Long");
      }



      // Condition set 3
      if (GetCurrentBid() < Close[15]
      && RSI(14, 3).Avg[0] > 30)
      {
      EnterShort(DefaultQuantity, "Short");
      DrawDot("My dot" + CurrentBar, false, 0, 0, Color.Red);

      if (Position.MarketPosition == MarketPosition.Short)
      {
      //Print ATRStopLoss
      double value = Position.AvgPrice-(ATR(14)[1]*2);
      Print ("The Current value is " + value.ToString());
      SetStopLoss(CalculationMode.Price,(Position.AvgPri ce+(ATR(14)[1]*2)));

      }

      }

      // Condition set 4
      if (Close[0] > Close[7])
      {
      ExitShort("Exit", "Short");
      }

      }

      Comment


        #4
        Hello,
        Thanks for the reply.

        To debug what is occurring you can use print statements to determine what your stop loss is being set too.

        For example:
        Code:
        Print("Stop Loss value: " +Position.AvgPrice-(ATR(14)[1]*2))
        Use this to compare the values and see what your stop loss is being set too. Is it set to the value you desire or is it set to low and filling immediately.

        Also the
        Code:
        if (Position.MarketPosition == MarketPosition.Long)
        will not immediately show a market position until the next OnBarUpdate().

        If you want it to immediately set the market position I would recommend placing the set stop loss in the entry condition so that it immediately sets the stop loss before the next OnBarUpdate() call.

        Please let us know if we may be of further assistance for anything NinjaTrader.
        Alex G.NinjaTrader Customer Service

        Comment


          #5
          Set dynamic stop loss until position is exited

          Hello and thank you for your earlier posts. I am also struggling with a simple stop loss (I am a beginner). I have attached the code I am working with for reference. I would like to set a stop loss price that once triggered, is held until either the stop loss at the entry price is triggered or another exit condition is met.

          The code I have attached needs to be corrected because when I'm in a position (with an earlier SetStopLoss value) and all 3 entry conditions are re-triggered, a new stop price is set and applied to the earlier entry.

          I've attached a screen shot of the bust. The entry at 63.20 has a corresponding stop of 58.19, I would like that to be held until the exit conditions are met (either the stop loss @ 58.19 is triggered or the Donchian channel is crossed-far right blue arrow.) As you can see, since the entry at 63.20, all 3 entry conditions were re-triggered (third arrow from the right) which set a new Stop Loss value of 68.45 and then the position was exited.

          I have been unsuccessfully working with the MarketPostion.Flat language and I'm wondering if it has something to do with that?

          I would greatly appreciate any guidance you have to offer and thank you for your consideration.
          Attached Files

          Comment


            #6
            Hello ashlantz,

            Thanks for writing in.

            You are using Position.MarketPosition to correctly detect if you are in a long position before you exit your position.

            The issue you are experiencing is likely to do with a lack of signalName tags.

            Code:
            if (channelEntry && MAEntry && lastBreachUp)
            {
                EnterLong();
                SetStopLoss(CalculationMode.Price, stopPrice);
                Print("Close = " + Close[0] + "stop price = " + stopPrice.ToString("F") + " Stop = " + stop.ToString("F") + "date = " + Time[0]);
            }
            When EnterLong() is called, an order is submitted. This order can be identifiable by adding a signalName tag to the order.

            For example you can use the following syntax to define an signalName for that order entry.

            Code:
            EnterLong(string signalName)
            EnterLong(int quantity, string signalName)
            You can place orders with unique names by referencing the CurrentBar in the string.

            Code:
            EnterLong("MySignal+"CurrentBar);
            This will create entries with a unique signalName. You can use these unique symbol names to set unique stop losses for each entry.

            Code:
            SetStopLoss("MySignal+"CurrentBar, CalculationMode.Price, stopPrice, false);
            If the above two lines are submitted on the same bar a unique entry will have a unique stop loss assigned to it.

            When a signalName is not provided the order method assumes that it should be applied for all entries.

            Please refer to the documentation below for complete syntax and understanding.

            EnterLong() - https://ninjatrader.com/support/help.../enterlong.htm

            SetStopLoss() - https://ninjatrader.com/support/help...etstoploss.htm

            You may wish to use EntriesPerDirection and EntryHandling to control how often you want the strategy to re-enter your position.

            EntriesPerDirection - https://ninjatrader.com/support/help...rdirection.htm

            EntryHandling - https://ninjatrader.com/support/help...ryhandling.htm

            Please let me know if you have any questions on the material.
            JimNinjaTrader Customer Service

            Comment

            Latest Posts

            Collapse

            Topics Statistics Last Post
            Started by arvidvanstaey, Today, 02:19 PM
            4 responses
            11 views
            0 likes
            Last Post arvidvanstaey  
            Started by samish18, 04-17-2024, 08:57 AM
            16 responses
            61 views
            0 likes
            Last Post samish18  
            Started by jordanq2, Today, 03:10 PM
            2 responses
            9 views
            0 likes
            Last Post jordanq2  
            Started by traderqz, Today, 12:06 AM
            10 responses
            18 views
            0 likes
            Last Post traderqz  
            Started by algospoke, 04-17-2024, 06:40 PM
            5 responses
            48 views
            0 likes
            Last Post NinjaTrader_Jesse  
            Working...
            X