Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Hard Stop, But is "Replaced" by a Trailing Stop once a Target is hit

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

    Hard Stop, But is "Replaced" by a Trailing Stop once a Target is hit

    hi all,

    I want to improve a present code that I have. it currently only has a hard stop. The strategy has targets built into it, but those targets are almost never reached, so therefore so many of my trades stop out at the eight tick stop.

    Instead of messing around with the logic of the targets on the existing code (which I don't rightly understand), I'd like to simply add a trailing stop that kicks in when a three tick profit has been reached. If the three tick profit is never reached, the trade stays open until it hits the hard stop. But if the three tick profit is reached, the trailing stop kicks in, the hard stop is set aside, and trades rides out till the trailing stop is it. Basically an OCO type exit.

    I know this can be done with an ATM in superdom, in fact I have an ATM that does this well. But I am no where near figuring out how to have ninjascript reference ATM strategies. I'm thinking it might be easier just to code it.

    Here's what I have so far:

    Code:
    {
    	
                SetStopLoss("", CalculationMode.Ticks, 8, false);
                SetTrailStop("", CalculationMode.Ticks, 3, false);
    
                CalculateOnBarClose = true;
    }
    any advice on how to code this?
    Last edited by outstretchedarm; 11-13-2011, 07:30 PM.

    #2
    outstretchedarm,

    I am happy to assist you.

    SetStopLoss() will over-ride your SetTrailingStop() commands. You essentially have two options. You can either use an ATM strategy or the unmanaged approach. For more information please see the following link.

    Unmanaged approach : http://www.ninjatrader.com/support/h...d_approach.htm

    For the ATM strategy, you can use the sample that comes with NinjaTrader named SampleATMStrategy.

    Please let us know if you require additional assistance.
    Adam P.NinjaTrader Customer Service

    Comment


      #3
      thank you.

      I'm not really sure what to do with that SampleATMstrategy that comes with NT.

      Am I supposed to edit it to taste, and then copy and paste it into my existing code?

      Comment


        #4
        outstrechedarm,

        Essentially yes. You can copy/paste the code into your strategy and work with the ATM strategies following the example I provided. We also have some helpful entries in our help guide on ATM strategies.



        Here is another helpful link to a forum with a similar goal : http://www.ninjatrader.com/support/f...t=food+thought

        Another option you have is "Simulated Stops", please see the following link.



        Please let me know if I may assist further.
        Adam P.NinjaTrader Customer Service

        Comment


          #5
          I'll see f I can manage that. I guess I am copying this whole bit:

          Code:
          if (orderId.Length == 0 && atmStrategyId.Length == 0 && Close[0] > Open[0])
          			{
          				atmStrategyId = GetAtmStrategyUniqueId();
          				orderId = GetAtmStrategyUniqueId();
          				AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
          			}
          
          
          			// Check for a pending entry order
          			if (orderId.Length > 0)
          			{
          				string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                          
          				// If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
          				if (status.GetLength(0) > 0)
          				{
          					// Print out some information about the order to the output window
          					Print("The entry order average fill price is: " + status[0]);
          					Print("The entry order filled amount is: " + status[1]);
          					Print("The entry order order state is: " + status[2]);
          
          					// If the order state is terminal, reset the order id value
          					if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
          						orderId = string.Empty;
          				}
          			} // If the strategy has terminated reset the strategy id
          			else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
          				atmStrategyId = string.Empty;
          
          
          			if (atmStrategyId.Length > 0)
          			{
          				// You can change the stop price
          				if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
          					AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
          
          				// Print some information about the strategy to the output window
          				Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
          				Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
          				Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
          				Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
          			}
                  }

          Comment


            #6
            outstretchedarm,

            Yes. Please let us know if you require additional assistance.

            Also, here is a post that has someone using stops and trailing stops : http://www.ninjatrader.com/support/f...t=food+thought
            Adam P.NinjaTrader Customer Service

            Comment


              #7
              Well, I've pasted the code onto my existing code, and I get the same bug about 15 times:

              The name 'orderID' does not exist in the current context.


              The same for 'atmstrategyID''. ( I made sure I created the ATM strategy with that name)

              Any thoughts? is it that those variables are declared somewhere in the sample strategy that I don't see?

              Here is my whole code so far:

              Code:
              #region Using declarations
              using System;
              using System.ComponentModel;
              using System.Diagnostics;
              using System.Drawing;
              using System.Drawing.Drawing2D;
              using System.Xml.Serialization;
              using NinjaTrader.Cbi;
              using NinjaTrader.Data;
              using NinjaTrader.Indicator;
              using NinjaTrader.Gui.Chart;
              using NinjaTrader.Strategy;
              #endregion
              
              // This namespace holds all strategies and is required. Do not change it.
              namespace NinjaTrader.Strategy
              {
                  /// <summary>
                  /// Identify divergence of selected indicator with Price
                  /// </summary>
                  [Description("Identify divergence of selected indicator with Price. I use CCI, MACD & Ergodic indicator, two indicators forming divergence provides confirmation")]
                  public class DivergenceLongWithATMExit : Strategy
                  {
                      #region Variables
                      // Wizard generated variables
                      private string positiveD = @"YES"; // Default setting for PositiveD
                      //private string indicatorType = @"MACD"; // Default setting for IndicatorType
                      private int macdfastPeriod = 12; // Default setting for FastPeriod
                      private int macdslowPeriod = 26; // Default setting for SlowPeriod
                      private int macdsignalPeriod = 9; // Default setting for SignalPeriod
                      private int ergodicfastPeriod = 20; // Default setting for Ergodic FastPeriod
                      private int ergodicslowPeriod = 12; // Default setting for Ergodic SlowPeriod	
                      private int cciPeriod = 40; // Default setting for CCI Period		
                      private double stopLossPct = 0.020; // Default setting for StopLossPct
                      private double trailingStopPct = 0.020; // Default setting for TrailingStopPct		
                      // User defined variables (add any user defined variables below)
              		private double trailStop = 0; // Default setting for TrailStop
              		private double StopLoss = 0;
                      private double prevValue = 0; // Default setting for PrevValue
                      private bool justEntered = false; // Default setting for JustEntered		
                      #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()
                      {
              
                          CalculateOnBarClose = true;
                      }
              
                      /// <summary>
                      /// Called on each bar update event (incoming tick)
                      /// </summary>
                      protected override void OnBarUpdate()
                      {
                          // Condition set 1 - Positive Divergence
                          if (((Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == 2 && Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == 2) ||
              				(Divergence(ergodicfastPeriod, "ergodic", positiveD, 1,ergodicslowPeriod).Plot0[0] == 2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == 2) ||
              				(Divergence(cciPeriod, "cci", positiveD, 9,26).Plot0[0] == 2 && Divergence(macdfastPeriod, "macd", positiveD, macdsignalPeriod,macdslowPeriod).Plot0[0] == 2)) &&
              				Position.MarketPosition == MarketPosition.Flat &&
                              (LinRegSlope(60)[0] > 0
                              && ADX(5)[0] > 10) )
                          {
              			// Submits an entry limit order at the current low price to initiate an ATM Strategy if both order id and strategy id are in a reset state
                          // **** YOU MUST HAVE AN ATM STRATEGY TEMPLATE NAMED 'AtmStrategyTemplate' CREATED IN NINJATRADER (SUPERDOM FOR EXAMPLE) FOR THIS TO WORK ****
              			if (orderId.Length == 0 && atmStrategyId.Length == 0 && Close[0] > Open[0])
              			{
              				atmStrategyId = GetAtmStrategyUniqueId();
              				orderId = GetAtmStrategyUniqueId();
              				AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
              			}
              
              
              			// Check for a pending entry order
              			if (orderId.Length > 0)
              			{
              				string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                              
              				// If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
              				if (status.GetLength(0) > 0)
              				{
              					// Print out some information about the order to the output window
              					Print("The entry order average fill price is: " + status[0]);
              					Print("The entry order filled amount is: " + status[1]);
              					Print("The entry order order state is: " + status[2]);
              
              					// If the order state is terminal, reset the order id value
              					if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
              						orderId = string.Empty;
              				}
              			} // If the strategy has terminated reset the strategy id
              			else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
              				atmStrategyId = string.Empty;
              
              
              			if (atmStrategyId.Length > 0)
              			{
              				// You can change the stop price
              				if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
              					AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
              
              				// Print some information about the strategy to the output window
              				Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
              				Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
              				Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
              				Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
              			}
                      }
                             
              }

              Comment


                #8
                outstretchedarm,

                There are a couple variable declarations you may be missing.
                Code:
                		private string	atmStrategyId		= string.Empty;
                		private string	orderId				= string.Empty;
                Please let me know if I may assist further.
                Adam P.NinjaTrader Customer Service

                Comment


                  #9
                  ahh that did it.

                  Hey whatdayaknow? It compiled right away. I thought I had a lot more debugging it do. Well, maybe I still do.

                  Thanks!

                  Comment


                    #10
                    outstretchedarm,

                    I am happy that worked.

                    Please don't hesitate to contact us should your require additional assistance.
                    Adam P.NinjaTrader Customer Service

                    Comment


                      #11
                      hmmm, now this new strategy won't trade (all green lights, no yellows). Furthermore, I have the old strategy, with the old stop, enabled alongside of this new one, and it has traded a few times already.

                      so let me get this straight. When I copy and paste that sampleATM code, am I replacing my old stop code with the new stop code? Because the sampleATM code also has instructions about how to enter, so I replaced the line of my code that says to enter long. (I din't want to enter long twice)

                      Comment


                        #12
                        outstretchedarm

                        Could you please clarify? The ATM strategy doesn't have a EnterLong() segment in the sample.

                        ATM strategies only manages stops/take profits. You will still need to enter a long or short position.

                        Please let me know if I may assist further.
                        Adam P.NinjaTrader Customer Service

                        Comment


                          #13
                          this line:

                          Code:
                          AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
                          seems to indicate a purchase is being made. is it?

                          Comment


                            #14
                            Hello outstretchedarm, to clarify here: yes correct, the AtmStrategyCreate() place an entry order with an ATM strategy template for exit management tied to it.

                            Comment


                              #15
                              Okay. So the task at hand seems to be to make this line, which creates the order:

                              Code:
                              {
                              EnterLong(1, "Long");
                              justEntered = true;
                              }
                              "talk" to this line of code, so that the ATM Strategy will know what entry it is managing:

                              Code:
                              orderId = GetAtmStrategyUniqueId();
                              AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "AtmStrategyTemplate", atmStrategyId);
                              Am I on the right track?

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              647 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              369 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              108 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              572 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              573 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X