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 Builder: Add ATR-value as TakeProfit and StopLoss

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

    Strategy Builder: Add ATR-value as TakeProfit and StopLoss

    Hi,

    I feel somewhat sorry for spamming these forums for help but here goes..

    I tried to follow this video guide for NT7 for adding TP & SL from ATR:


    I tried to "translate" the parameters and process to NT8 to no avail. Can this be done in NT8 through the Wizard?

    Thanks again in advance!

    br,
    Chris

    #2
    Hello suroot,

    Thank you for the post.

    I am reviewing your inquiry and will be back with a reply shortly.

    I look forward to assisting further.
    Chris L.NinjaTrader Customer Service

    Comment


      #3
      Hello suroot,

      Thank you for your patience.

      I have made a video for you on how to replicate this strategy in NinjaTrader 8.



      If we may be of any further assistance, please let us know.
      Chris L.NinjaTrader Customer Service

      Comment


        #4
        Thank You for the video!

        Actually that is more or less what I did figure out on my own after playing around. However, I could not get the ATR working as a SL nor TP. Tested tick/pips/percent/price but nothing worked.

        I will try to post the code for my simple test strategy tomorrow when I'm at the office.

        Thanks!

        br,
        Chris

        Comment


          #5
          Hi,

          I made a video that might show better what I'm doing instead of just pasting the code here:
          video, sharing, camera phone, video phone, free, upload


          I'm guessing the issue is with the variable not being set by ATR but keeps it value of "1,00". As you can see when I backtest the test strategy, it will exit the position within the same bar +1pip instead of using the daily ATR value that is obviously a dynamic value/variable.

          Am I doing something wrong here, should the ATR variable be set to something else instead of arithmetic?

          Thanks for any help on this!

          br,
          Chris

          Comment


            #6
            Hi again,

            Question nr 2: is it after all necessary to declare a variable, why can't ATR (or any indicator) work directly from the "Stops and Targets" in NT8?


            br,
            Chris

            Comment


              #7
              I've given up trying to accomplish this through the Strategy Builder Wizard; there is either a bug (with user defined variable always being 1) or not designed to take needed input parameters (or I'm too stupid figuring it out..).

              My best guess is, that I have to open up the code and add something similar to this for NT8:


              If someone already has done this and can shed some light on the proper code for NT8, I'll buy you a virtual beer!

              br,
              Chris

              Comment


                #8
                Hello suroot,

                Thank you for the reply.

                You can not add this logic through the Strategy Builder. The code will need to be unlocked and you will add this statement to the OnBarUpdate method.

                Code:
                OnBarUpdate(){
                
                    if(Close[0] > Close[1]){
                   
                        EnterLong(Convert.ToInt32(DefaultQuantity));
                        SetProfitTarget(CalculationMode.Pips, ATR1[0]); 
                
                    }
                
                }
                If we may be of any further assistance, please let us know.
                Last edited by NinjaTrader_ChrisL; 08-02-2017, 04:45 PM.
                Chris L.NinjaTrader Customer Service

                Comment


                  #9
                  Thank You, I'll try that instead of the wizard!

                  Below is BTW code generated by the wizard:

                  namespace NinjaTrader.NinjaScript.Strategies
                  {
                  public class ATRVARIABLETEST : Strategy
                  {
                  private double ATRVALUE1;

                  private ATR ATR1;

                  protected override void OnStateChange()
                  {
                  if (State == State.SetDefaults)
                  {
                  Description = @"Enter the description for your new custom Strategy here.";
                  Name = "ATRVARIABLETEST";
                  Calculate = Calculate.OnBarClose;
                  EntriesPerDirection = 1;
                  EntryHandling = EntryHandling.AllEntries;
                  IsExitOnSessionCloseStrategy = true;
                  ExitOnSessionCloseSeconds = 30;
                  IsFillLimitOnTouch = false;
                  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;
                  ATRVALUE1 = 1;
                  }
                  else if (State == State.Configure)
                  {
                  SetProfitTarget("", CalculationMode.Pips, ATR1[0]);
                  }
                  else if (State == State.DataLoaded)
                  {
                  ATR1 = ATR(Close, 14);
                  }
                  }

                  protected override void OnBarUpdate()
                  {
                  if (CurrentBars[0] < 1)
                  return;

                  // Set 1
                  if (Close[0] > Close[1])
                  {
                  EnterLong(Convert.ToInt32(DefaultQuantity), "");
                  ATRVALUE1 = ATR(Close, 14)[0];
                  }

                  }
                  }
                  }

                  Comment


                    #10
                    Now I have the ATR indicator populating TP & SL dynamically. I had a static TP & SL defined previously, that moved SL to BE when x pips of profit open.

                    The problem is now, my ATR attempt now broke the BE SL somehow and I can not figure out what I'm doing wrong here?

                    Below complete code of simple RSI strategy. Can anyone point me in the right direction, getting BE SL working with my ATR TP & SL, thanks!

                    namespace NinjaTrader.NinjaScript.Strategies
                    {
                    public class RSIATR : Strategy
                    {
                    private RSI RSI1;

                    // private Series<double> ATR1;

                    protected override void OnStateChange()
                    {
                    if (State == State.SetDefaults)
                    {
                    Description = @"Enter the description for your new custom Strategy here.";
                    Name = "RSIATR";
                    Calculate = Calculate.OnBarClose;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    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;
                    ATRPeriod = 14;
                    TPMultiplier = 2;
                    SLMultiplier = 2;

                    }
                    else if (State == State.Configure)
                    {
                    }
                    else if (State == State.DataLoaded)
                    {
                    RSI1 = RSI(Close, 14, 1);
                    RSI1.Plots[0].Brush = Brushes.DodgerBlue;
                    RSI1.Plots[1].Brush = Brushes.Goldenrod;
                    AddChartIndicator(RSI1);
                    }
                    }

                    protected override void OnBarUpdate()
                    {
                    if (CurrentBars[0] < 1)
                    return;

                    if (Position.MarketPosition == MarketPosition.Flat)
                    {
                    //Set initial stop - ATR Stop in pips
                    int StopLoss = Convert.ToInt32(ATR(ATRPeriod)[0] * SLMultiplier / TickSize);
                    int TakeProfit = Convert.ToInt32(ATR(ATRPeriod)[0] * TPMultiplier / TickSize);
                    SetStopLoss("LONG",CalculationMode.Pips, StopLoss, false);
                    SetProfitTarget("LONG", CalculationMode.Pips, TakeProfit);
                    //Set Short TP SL
                    SetStopLoss("SHORT",CalculationMode.Pips, StopLoss, false);
                    SetProfitTarget("SHORT", CalculationMode.Pips, TakeProfit);

                    }

                    //Set long stop loss to break even when n profit
                    else if (Position.MarketPosition == MarketPosition.Long)
                    {
                    if (Close[0] > Position.AveragePrice + 10 * TickSize)
                    {
                    SetStopLoss(CalculationMode.Price, Position.AveragePrice * TickSize);
                    }

                    }
                    //Set short stop loss to break even n profit
                    else if (Position.MarketPosition == MarketPosition.Short)
                    {
                    if (Close[0] < Position.AveragePrice - 10 * TickSize)
                    {
                    SetStopLoss(CalculationMode.Price, Position.AveragePrice * TickSize);
                    }
                    }

                    // Set 1
                    if (CrossBelow(RSI1.Default, 45, 1))
                    {
                    EnterLong(Convert.ToInt32(DefaultQuantity), "LONG");
                    }

                    // Set 2
                    if (CrossAbove(RSI1.Default, 55, 1))
                    {
                    EnterShort(Convert.ToInt32(DefaultQuantity), "SHORT");
                    }

                    }

                    #region Properties
                    [NinjaScriptProperty]
                    [Range(1, int.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="ATRPeriod", Order=1, GroupName="NinjaScriptStrategyParameters")]
                    public int ATRPeriod
                    { get; set; }

                    [NinjaScriptProperty]
                    [Range(1, int.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="TPMultiplier", Order=2, GroupName="NinjaScriptStrategyParameters")]
                    public int TPMultiplier
                    { get; set; }

                    [NinjaScriptProperty]
                    [Range(1, int.MaxValue)]
                    [Display(ResourceType = typeof(Custom.Resource), Name="SLMultiplier", Order=3, GroupName="NinjaScriptStrategyParameters")]
                    public int SLMultiplier
                    { get; set; }

                    #endregion
                    }
                    }

                    Comment


                      #11
                      Hello suroot,

                      Thank you for the follow-up.

                      Could you please clarify on the specific problem you are having with this script?

                      I look forward to you reply.
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi,

                        The problem is, that the "SetStopLoss" is not being updated to BreakEven (BE), when the BE conditions have been met.

                        I think it has something to do with "SetStopLoss("LONG"..) since when I add it to the BE conditions, error CS1501 is thrown.

                        Can not understand what I'm doing wrong here.

                        Thanks for any help!

                        br,
                        Chris

                        Comment


                          #13
                          Hello suroot,

                          If you pass the fromEntrySignal name into your SetSTopLoss method, does the BE work as expected?
                          For example, using the following syntax,

                          Code:
                          SetStopLoss(string fromEntrySignal, CalculationMode mode, double value, bool isSimulatedStop)
                          From our helpguide,


                          I look forward to your reply.
                          Alan P.NinjaTrader Customer Service

                          Comment


                            #14
                            Thanks for Your reply!

                            No it didn't, I then got error code CS1501 when passing the string.

                            Could it have anything to do with "Convert.ToInt32" in the ATR declaration and not in the BreakEven code?

                            Thanks!

                            br,
                            Chris

                            Comment


                              #15
                              Hello Chris,

                              If you remove the "Convert.ToInt32" do you experience the same issue?

                              I look forward to your reply.
                              Alan P.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by PhillT, Today, 02:16 PM
                              2 responses
                              3 views
                              0 likes
                              Last Post PhillT
                              by PhillT
                               
                              Started by Kaledus, Today, 01:29 PM
                              3 responses
                              9 views
                              0 likes
                              Last Post NinjaTrader_Jesse  
                              Started by frankthearm, Yesterday, 09:08 AM
                              14 responses
                              47 views
                              0 likes
                              Last Post NinjaTrader_Clayton  
                              Started by gentlebenthebear, Today, 01:30 AM
                              2 responses
                              14 views
                              0 likes
                              Last Post gentlebenthebear  
                              Started by PaulMohn, Today, 12:36 PM
                              2 responses
                              17 views
                              0 likes
                              Last Post PaulMohn  
                              Working...
                              X