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

AtmStrategyChangeStopTarget()

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

    AtmStrategyChangeStopTarget()

    Can someone point me to a reference document or a sample script where AtmStrategyChangeStopTarget()

    I would like to have AtmStrategyChangeStopTarget() move like the SetStopLoss in OrderManagementExamples Script. I should be able to risk the same amount on every trade but the script in the SampleAtmStrategy the StopLoss with the Bearish bar; therefore, that increases your risk in the trade.

    Is there a solution, with AtmStrategyChangeStopTarget() of course, when the current bar is Bearish the stop loss does not move? The stop loss will exactly behave like the one in the OrderManagementExamples Script.

    Thanks

    #2
    Hello patdmoney,

    Thanks for your post.

    To clarify, what OrderManagementExamples script are you referring to?

    If possible, could you share a URL link to the example script you are referring to so I may take a look at it?

    The AtmStrategyChangeStopTarget() method will only change a stop or target order if this method is called within the script. Otherwise, the stop and target will not move unless specified in the Atm Strategy Template iteself.

    The AtmStrategyChangeStopTarget() help guide page linked here details how this method could be used in a script: https://ninjatrader.com/support/help...stoptarget.htm

    Further, the SampleAtmStrategy script that comes default with NinjaTrader is an example of using this method to move a stop when a certain condition becomes true.

    To understand exactly how your logic is behaving, it is necessary to add prints to the script that print out all the logic being used to call this method, print the price the order is being changed to, and print the time of the bar.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    https://ninjatrader.com/support/foru...121#post791121
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Sure.

      This is one of the OrderManagementExamples

      HTML Code:
      //
      // Copyright (C) 2021, NinjaTrader LLC <www.ninjatrader.com>
      // NinjaTrader reserves the right to modify or overwrite this NinjaScript component
      // Coded by NinjaTrader_ChelseaB
      //
      #region Using declarations
      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.ComponentModel.DataAnnotations;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows;
      using System.Windows.Input;
      using System.Windows.Media;
      using System.Xml.Serialization;
      using NinjaTrader.Cbi;
      using NinjaTrader.Gui;
      using NinjaTrader.Gui.Chart;
      using NinjaTrader.Gui.SuperDom;
      using NinjaTrader.Gui.Tools;
      using NinjaTrader.Data;
      using NinjaTrader.NinjaScript;
      using NinjaTrader.Core.FloatingPoint;
      using NinjaTrader.NinjaScript.Indicators;
      using NinjaTrader.NinjaScript.DrawingTools;
      #endregion
      
      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies.OrderManagementExamples
      {
          public class ProfitChaseStopTrailSetMethodsExample : Strategy
          {
              private double                currentPtPrice, currentSlPrice;
              private bool                exitOnCloseWait, exitOnCloseWait1;
              private SessionIterator        sessionIterator;
      
              protected override void OnStateChange()
              {
                  if (State == State.SetDefaults)
                  {
                      Description                                    = @"";
                      Name                                        = "ProfitChaseStopTrailSetMethodsExample";
                      EntriesPerDirection                            = 1;
                      EntryHandling                                = EntryHandling.AllEntries;
                      TraceOrders                                    = true;
                      BarsRequiredToTrade                            = 1;
                      IsInstantiatedOnEachOptimizationIteration    = false;
      
                      ChaseProfitTarget                            = true;
                      PrintDetails                                = false;
                      ProfitTargetDistance                        = 10;
                      StopLossDistance                            = 10;
                      TrailStopLoss                                = true;
                      UseProfitTarget                                 = true;
                      UseStopLoss                                    = true;
                  }
                  else if (State == State.Configure)
                  {
                      AddDataSeries(BarsPeriodType.Tick, 1);
                  }
                  else if (State == State.DataLoaded)
                  {
                      sessionIterator        = new SessionIterator(Bars);
                      exitOnCloseWait        = false;
                      exitOnCloseWait1    = false;
                  }
              }
      
              protected override void OnBarUpdate()
              {
                  if (CurrentBars[0] < BarsRequiredToTrade || CurrentBars[1] < BarsRequiredToTrade)
                      return;
      
                   // Check if the previous bar was bullish
                  bool isPreviousBarBullish = Close[1] > Open[1];
                  bool isPreviousBarBearish = Close[1] < Open[1];
      
                  // Check if the current bar is bullish
                  bool isCurrentBarBullish = Close[0] > Open[0];
                  bool isCurrentBarBearish = Close[0] < Open[0];
      
                  if (BarsInProgress == 0)
                  {
                      if (CurrentBar == 0 || Bars.IsFirstBarOfSession)
                          sessionIterator.GetNextSession(Time[0], true);
      
                      // if after the exit on close time, prevent new orders until the new session
                      if (Times[1][0] >= sessionIterator.ActualSessionEnd.AddSeconds(-ExitOnSessionCloseSeconds) && Times[1][0] <= sessionIterator.ActualSessionEnd)
                          exitOnCloseWait    = true;
      
                      // reset for a new entry on the first bar of a new session
                      else if (exitOnCloseWait && Bars.IsFirstBarOfSession)
                          exitOnCloseWait = false;
      
                      if (State == State.Historical && CurrentBar == BarsArray[0].Count - 2 && Position.MarketPosition == MarketPosition.Long)
                      {
                          ExitLong(1, 2, "exit to start flat", string.Empty);
                      }
      
                      else if (!exitOnCloseWait && Position.MarketPosition == MarketPosition.Flat && isPreviousBarBullish)
                      {
                              if(BarsInProgress == 0 && Volume[0] > Volume[1])
                          {
                              // Reset the stop loss to the original distance when all positions are closed before placing a new entry
      
                              currentPtPrice    = Close[0] + ProfitTargetDistance * TickSize;
                              currentSlPrice    = Close[0] - StopLossDistance * TickSize;
      
                              if (UseProfitTarget)
                                  SetProfitTarget(CalculationMode.Price, currentPtPrice);
      
                              if (UseStopLoss)
                                  SetStopLoss(CalculationMode.Price, currentSlPrice);
      
                              EnterLong(1, 2, string.Empty);
                          }
                      }
      
                      // reset for a new entry on the first bar of a new session
                      else if (exitOnCloseWait1 && Bars.IsFirstBarOfSession)
                          exitOnCloseWait1 = false;
      
                      if (State == State.Historical && CurrentBar == BarsArray[0].Count - 2 && Position.MarketPosition == MarketPosition.Short)
                      {
                          ExitShort(1, 2, "exit to start flat", string.Empty);
                      }
      
                      else if (!exitOnCloseWait1 && Position.MarketPosition == MarketPosition.Flat && isPreviousBarBearish)
                      {
                              if(BarsInProgress == 0 && Volume[0] > Volume[1])
                          {
                              // Reset the stop loss to the original distance when all positions are closed before placing a new entry
      
                              currentPtPrice    = Close[0] - ProfitTargetDistance * TickSize;
                              currentSlPrice    = Close[0] + StopLossDistance * TickSize;
      
                              if (UseProfitTarget)
                                  SetProfitTarget(CalculationMode.Price, currentPtPrice);
      
                              if (UseStopLoss)
                                  SetStopLoss(CalculationMode.Price, currentSlPrice);
      
                              EnterShort(1, 2, string.Empty);
                          }
                      }
                  }            
      
                  if (BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Long)
                      {
                          if (UseProfitTarget && ChaseProfitTarget && Close[0] < currentPtPrice - ProfitTargetDistance * TickSize)
                              {
                                  currentPtPrice = Close[0] + ProfitTargetDistance * TickSize;
                                  SetProfitTarget(CalculationMode.Price, currentPtPrice);
                              }
      
                          if (UseStopLoss && TrailStopLoss && Close[0] > currentSlPrice + StopLossDistance * TickSize)
                              {
                                  currentSlPrice = Close[0] - StopLossDistance * TickSize;
                                  SetStopLoss(CalculationMode.Price, currentSlPrice);
                              }
                      }
      
                  if (BarsInProgress == 1 && Position.MarketPosition == MarketPosition.Short)
                      {
                          if (UseProfitTarget && ChaseProfitTarget && Close[0] > currentPtPrice + ProfitTargetDistance * TickSize)
                              {
                                  currentPtPrice = Close[0] - ProfitTargetDistance * TickSize;
                                  SetProfitTarget(CalculationMode.Price, currentPtPrice);
                              }
      
                          if (UseStopLoss && TrailStopLoss && Close[0] < currentSlPrice - StopLossDistance * TickSize)
                              {
                                  currentSlPrice = Close[0] + StopLossDistance * TickSize;
                                  SetStopLoss(CalculationMode.Price, currentSlPrice);
                              }
                      }
              }
      
              #region Properties
              [NinjaScriptProperty]
              [Display(Name = "Chase profit target", Order = 2, GroupName = "NinjaScriptStrategyParameters")]
              public bool ChaseProfitTarget
              { get; set; }
      
              [NinjaScriptProperty]
              [Range(1, int.MaxValue)]
              [Display(Name = "Profit target distance", Description = "Distance for profit target (in ticks)", Order = 3, GroupName = "NinjaScriptStrategyParameters")]
              public int ProfitTargetDistance
              { get; set; }
      
              [NinjaScriptProperty]
              [Display(Name = "Print details", Order = 7, GroupName = "NinjaScriptStrategyParameters")]
              public bool PrintDetails
              { get; set; }
      
              [NinjaScriptProperty]
              [Range(1, int.MaxValue)]
              [Display(Name = "Stop loss distance", Description = "Distance for stop loss (in ticks)", Order = 6, GroupName = "NinjaScriptStrategyParameters")]
              public int StopLossDistance
              { get; set; }
      
              [NinjaScriptProperty]
              [Display(Name = "Trail stop loss", Order = 5, GroupName = "NinjaScriptStrategyParameters")]
              public bool TrailStopLoss
              { get; set; }
      
              [NinjaScriptProperty]
              [Display(Name = "Use profit target", Order = 1, GroupName = "NinjaScriptStrategyParameters")]
              public bool UseProfitTarget
              { get; set; }
      
              [NinjaScriptProperty]
              [Display(Name = "Use stop loss", Order = 4, GroupName = "NinjaScriptStrategyParameters")]
              public bool UseStopLoss
              { get; set; }
              #endregion
          }
      }
      ​
      I have modified it. I added the short order.

      Comment


        #4
        Hello patdmoney,

        Thanks for your notes.

        The way this strategy works is when the strategy is in flat market position, the profit target price is saved to the currentPtPrice variable and the stop loss price is saved to the currentSlPrice variable.

        Then script then calls the Set methods using those variables to place the profit target and stop at those calculated prices and places an entry order with EnterLong().

        When the added 1-tick series is processing and the market position is long, the script checks if the strategy should trail by checking UseStopLoss && TrailStopLoss. It also checks if the Close price is greater than the previous stop loss price plus a certain distance in ticks, calculates the new stop price and assigns the value to the currentSlPrice variable, and calls SetStopLoss() again using that calculated currentSlPrice variable.

        For short orders, instead of checking if the Close is greater than the currentSlPrice plus a certain number of ticks, you would check if the Close is less than the currentSlPrice plus a certain number of ticks, save the newly calculated value to the variable, and pass that into your method to change the stop price.

        You would need to try and implement similar logic in your script to move the stop loss similar to how that sample script does.

        Note that to accomplish your overall goal you may be better off using Set methods and Enter methods to control the entries, profit target, and stop loss instead of using Atm Strategy Methods which uses the ATM Strategy Template to control targets and stops.
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Yes, bus I like using the ATM because of the break even feature that I can easily manage.

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by lightsun47, Today, 03:51 PM
          0 responses
          5 views
          0 likes
          Last Post lightsun47  
          Started by 00nevest, Today, 02:27 PM
          1 response
          9 views
          0 likes
          Last Post 00nevest  
          Started by futtrader, 04-21-2024, 01:50 AM
          4 responses
          45 views
          0 likes
          Last Post futtrader  
          Started by Option Whisperer, Today, 09:55 AM
          1 response
          14 views
          0 likes
          Last Post bltdavid  
          Started by port119, Today, 02:43 PM
          0 responses
          9 views
          0 likes
          Last Post port119
          by port119
           
          Working...
          X