Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Stop execution if less than supertrend line

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

    Stop execution if less than supertrend line

    I have attached a photo, the top half is the strategy analzyer chart, and the bottom half is the regular chart. On the bottom chart I have circled where I would like the stop should trigger.
    I have CalculateOnBarClose = false; because I want it to calculate at current price.

    And this is my codeline....

    if Close[0] < SuperTrend(14, 2.618, true).UpTrend[0]
    { ExitLong(" ", " ");}

    The problem is that the supertrend line is switching to the downtrend side, so price is never crossing down through the supertrend technically. Is there any way to have it execute the stop at the point I have circled on the photo when it crosses below the green supertrend dots?
    Attached Files

    #2
    Hi zachj,

    The timing of strategy analyzer orders is always: Condition evaluates true, then order is submitted to next bar following the condition. CalculateOnBarClose will always be true in historical/backtest. In your screenshot it looks like this is what's taking place.

    You could run this in real time or market replay if you would like to test out COBC = false behavior. If you want to simulate this in your backtest, you can add a secondary series and submit orders to this series. The following sample can help you backtest with intrabar granularity:
    You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by
    Last edited by NinjaTrader_RyanM1; 02-02-2012, 01:24 PM.
    Ryan M.NinjaTrader Customer Service

    Comment


      #3
      The code that is actually stoping it out, which i should have posted before, is the downtrending supertrend...
      if Close[0] < SuperTrend(14, 2.618, true).DownTrend[0]
      { ExitLong(" ", " ");}

      So when the downtrend or the supertrend black dots move to the opposite side above the price it stops out on the start of the next bar. I would like it to stop out when the price moves below the previous bars super trend green dot and intrabar.

      But im getting confused by your response, you said.. "CalculateOnBarClose will always be false in historical/backtest." So if it is set to false then it should calculate intrabar shouldn't it?

      Comment


        #4
        Sorry about that -- It's been corrected. You're right that it should have read "COBC is always true in historical /backtest." Please let me know if you have any additional questions.
        Ryan M.NinjaTrader Customer Service

        Comment


          #5
          oh ok I see, so COBC=false alone does actually cause executions intrabar, as long as its live.
          But do I have this code correct.

          If intrabar price < supertrend value of the last bar.... than exit long.
          code equivalent..
          if Close[0] < SuperTrend(14, 2.618, true).UpTrend[0]
          { ExitLong(" ", " ");}

          Or should I Not be using Close to represent intrabar price? Cause it seems like Close[0] means close price of previous bar.

          Comment


            #6
            Close[0] is not the previous bar, but in a historical sense all orders follow the same timing: Orders are submitted to the bar following when the condition evaluates true.

            There's really no concept of "intrabar price" in historical setting. You only have four data points per bar: OHLC. You may be looking instead to check anytime Low[0] crosses below that indicator value.

            Crossing will look at two points of time and two values, and then identifies when one values crosses above or below another.
            Ryan M.NinjaTrader Customer Service

            Comment


              #7
              ok i will experiment with it but the price never actually "crosses" down through the supertrend green dots if you look at the photo, because on that bar where it would cross down through, the supertrend flips to the upper side. So i believe i need to calculate based on the intrabar becoming less than supertrend green dot of the previous bar. I like the idea of the primary and secondary bar time frames. Using that method can I get it to do 1min bar close < supertrend of previous 10min bar close. Then Exit long?
              Last edited by zachj; 02-02-2012, 03:09 PM.

              Comment


                #8
                I had edited my last post, so not sure if my last question was seen.

                can I get it to do... 1min bar close < supertrend of previous 10min bar close...Exit long?

                Comment


                  #9
                  Zach, Yes NinjaScript strategies support multiple time frames. You can find this detailed in our help guide here:


                  There is also a SampleMultiTimeFrame available under Tools > Edit NinjaScript > Strategy menu.
                  Ryan M.NinjaTrader Customer Service

                  Comment


                    #10
                    Im getting stuck on code below, getting erors. Im trying do... when Close of the secondary bar(which is 1min bar) closes below the previous bars supertrend line on the primary bar time frame, exit long.


                    Code:
                    if (BarsInProgress != 0)
                    		return;
                    		
                    if  SuperTrend(14, 2.618, true).UpTrend[1] > Closes[1][0]
                    	
                    
                    {ExitLong("", "");}

                    I assume the Closes[1][0] is not the proper code, but that's what Ive found in the help guide. Not sure how I would set this up properly? I tried to use BarsArray[1] with Close but that's not right either.

                    Update(please read quoted text above first), think I fixed the line of code, this correct?
                    if (SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1] > Closes[1][0]

                    Only thing is im looking at the backtest chart and its all wacked out and executing tons of orders. I have a bunch of other code in this strategy and I think its interfering with it, I wanted to try and keep this secondary time frame local to just this piece of code associated with the ExitLong. Im not sure if things have to be in a certain order under OnBarUpdate?
                    Last edited by zachj; 02-04-2012, 07:52 AM.

                    Comment


                      #11
                      Originally posted by zachj View Post
                      Update(please read quoted text above first), think I fixed the line of code, this correct?
                      if (SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1] > Closes[1][0]

                      Only thing is im looking at the backtest chart and its all wacked out and executing tons of orders. I have a bunch of other code in this strategy and I think its interfering with it, I wanted to try and keep this secondary time frame local to just this piece of code associated with the ExitLong. Im not sure if things have to be in a certain order under OnBarUpdate?
                      to prevent executing a ton of previous orders, put this before your BarsInProgress statement.

                      Code:
                      if (Historical) return;
                      I modified this print statement, it should help you see your values and timeframes of candles they are coming from. I think I got all the parenthesis correct. But you should get the idea.


                      Code:
                      Print ( " ["+BarsInProgress+"]=" + String.Format( "{0,7}" , String.Format( "{0:####.00}" ,Close[0])) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Time[0]) +
                                  " Closes [0][0]=" + String.Format( "{0:0.00}" ,Closes[0][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[0][0]) + 
                                  " Closes[1][0]=" + String.Format( "{0:0.00}" ,Closes[1][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[1][0]) +
                                  " SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1]" + String.Format( "{0:0.00}" ,SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1]) ) ;

                      Comment


                        #12
                        That's not really making much of a change it doesn't appear. I already had this code line in below above the BarsInProgress but I just didn't post it...

                        if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired) return;

                        I think that does the same thing im not sure. Either way if I leave both in, leave one in, or leave both out it doesn't appear to be making much of a difference.

                        I feel like the issue is with this code below, I think something is incorrect and likely in the part I have bolded below...

                        // If SuperTrend line of previous 10minute bar > Close of current 1minute bar then Exit Long //
                        if (SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1] > Closes[1][0]
                        {ExitLong("", "");}

                        Comment


                          #13
                          Using a Print statement and looking at the console for the output, you'll see what the value of SuperTrend is compared to Closes..

                          You probably want BarsArray

                          Here is how I used it with ZLEMA indicator: ZLEMA(BarsArray[0],3)[0]

                          I don't have SuperTrend.

                          Originally posted by zachj View Post
                          That's not really making much of a change it doesn't appear. I already had this code line in below above the BarsInProgress but I just didn't post it...

                          if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired) return;

                          I think that does the same thing im not sure. Either way if I leave both in, leave one in, or leave both out it doesn't appear to be making much of a difference.

                          I feel like the issue is with this code below, I think something is incorrect and likely in the part I have bolded below...

                          // If SuperTrend line of previous 10minute bar > Close of current 1minute bar then Exit Long //
                          if (SuperTrend(Closes[0], 14, 2.618, true).UpTrend[1] > Closes[1][0]
                          {ExitLong("", "");}

                          Comment


                            #14
                            Ya im a bit lost at this point. And im not farmiliar with the print statements or how to interpret them. I will look into that. Ive tried to change the code around all sorts of ways with the BarsArray, (Historical) etc. and its just executing all over the place. I will just post my entire strategy code not sure if that will help. Its Condition Set 4, the long exit, is where im experimenting with the primary secondary bars.
                            Again im just trying to do If price on 1minute Closes below supertrend dot for previous bar of 10minute, exit long.


                            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>
                                /// Enter the description of your strategy here
                                /// </summary>
                                [Description("Enter the description of your strategy here")]
                                public class SpitfireTargetTest : Strategy
                                {
                                    #region Variables
                                    // Wizard generated variables
                                    // User defined variables (add any user defined variables below)
                            		private int     bigmoemalong       =79;
                            		private int     bigmoemashort       =114;
                            		private int		longmacdfast		= 12;
                            		private int		shortmacdfast		= 20;
                            		private int		longstoplossticks		= 70;
                            		private int		shortstoplossticks		= 45;
                            		private int		profittargetticks	= 1000;
                            		private double  atrtargetx  = 2.5;
                            		private double  atrlongstopx  = 2;
                            		private double  atrshortstopx  = 4.5;
                            		private bool    mybool = true;
                            		private int  timestart = 9;
                            		private int  timeend = 17;
                                    #endregion
                            
                            protected override void Initialize()  
                            {Add(PeriodType.Minute, 1);
                            CalculateOnBarClose = true; }
                            
                            protected override void OnBarUpdate()
                            		
                            {
                            	
                            // Condition set 1  Long Entry
                            if (MACD(longmacdfast, 26, 5)[0]  >= 0
                            && Close[0] > BigMO(bigmoemalong).EMAline[0]
                            && SuperTrend(14, 2.618, true).UpTrend[0] < Close[0]
                            && MACD(longmacdfast, 26, 9)[0] > MACD(longmacdfast, 26, 9)[1]
                            && Close[0] < (BigMO(bigmoemalong).EMAline[0] + (ATR(14)[0] * 10))
                            && ToTime(Time[0]) > ToTime(timestart, 0, 0)
                            && ToTime(Time[0]) < ToTime(16, 0, 0))	
                            { EnterLong(DefaultQuantity, ""); }
                            
                            
                            // Condition set 2  Short Entry
                            if (MACD(shortmacdfast, 32, 3)[0] <= -.5
                            && Close[0] < BigMO(bigmoemashort).EMAline[0]
                            && Close[0] < Open[1]
                            && MACD(shortmacdfast, 32, 3)[0] < MACD(shortmacdfast, 32, 3)[1]
                            && Close[0] > (BigMO(bigmoemashort).EMAline[0] - (ATR(14)[0] * 7))
                            && ToTime(Time[0]) > ToTime(9, 0, 0)
                            && ToTime(Time[0]) < ToTime(16, 0, 0))	
                            { EnterShort(DefaultQuantity, ""); }
                            
                            
                            // Condition set 3  Profit Targets, Stop Loss Modification and Max Stop Loss.  Long & Short.
                            if (Position.MarketPosition == MarketPosition.Flat)
                            { mybool = true; }
                            // Long, Target stop loss modification. Once price greater than (entry price + (2.5*ATR)), set stop loss to (highest close of last 10bars - (2* ATR)) 
                            else if (Position.MarketPosition == MarketPosition.Long && Close[0] > Position.AvgPrice + (ATR(14)[0]) * atrtargetx)  
                            {	SetStopLoss(CalculationMode.Price, Close[HighestBar(Close,10)] - (ATR(14)[0] * atrlongstopx)); }
                            // Max Long stoploss allowed if price goes below entry price
                            else if (Position.MarketPosition == MarketPosition.Long && Close[0] < Position.AvgPrice)	
                            { SetStopLoss(CalculationMode.Ticks, longstoplossticks); }
                            // Color bar blue when target reached 	
                            if (Position.MarketPosition == MarketPosition.Long && CrossAbove(Close, Position.AvgPrice + (ATR(14)[0]) * atrtargetx, 1) && mybool)
                            {BarColorSeries[0] = Color.Blue; mybool = false;} 
                            				
                            // Short, Target stop loss modification.  Once price less than (entry price - (2.5*ATR)), set stop loss to (lowest close of last 10bars + (4.5* ATR)) 
                            else if (Position.MarketPosition == MarketPosition.Short && Close[0] < Position.AvgPrice - (ATR(14)[0]) * atrtargetx)
                            { SetStopLoss(CalculationMode.Price, Close[LowestBar(Close,10)] + (ATR(14)[0] * atrshortstopx)); }	
                            // Max Short stoploss allowed 
                            else if (Position.MarketPosition == MarketPosition.Short)	
                            { SetStopLoss(CalculationMode.Ticks, shortstoplossticks); }
                            // Color bar yellow when target reached 
                            if (Position.MarketPosition == MarketPosition.Short && CrossBelow(Close, Position.AvgPrice - (ATR(14)[0]) * atrtargetx, 1) && mybool)
                            {BarColorSeries[0] = Color.Yellow; mybool = false;}
                            
                            
                            // Condition set 4   Long Exit.  If price Closes below supertrend for previous bar, exit long.
                            if (CurrentBars[0] <= BarsRequired || CurrentBars[1] <= BarsRequired) return;
                            if (BarsInProgress == 0) 
                            if  (SuperTrend(BarsArray[0], 14, 2.618, true).UpTrend[1] > Closes[1][0]
                            && ToTime(Time[0]) > ToTime(timestart, 0, 0)
                            && ToTime(Time[0]) < ToTime(timeend, 0, 0))
                            { ExitLong("", ""); }
                            
                            
                            // Condition set 5  Short Exit.  If price Closes within ATR*.5 of supertrend for previous bar, exit short.
                            if (Close[0] > (SuperTrend(14, 2.618, true).DownTrend[1] - ((ATR(14)[0]) * .5))
                            && ToTime(Time[0]) > ToTime(timestart, 0, 0)
                            && ToTime(Time[0]) < ToTime(timeend, 0, 0))
                            { ExitShort("", ""); }
                            
                            }
                                    #region Properties
                            	/// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int TimeStart
                            		{
                            			get { return timestart; }
                            			set { timestart = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int TimeEnd
                            		{
                            			get { return timeend; }
                            			set { timeend = Math.Max(0, value); }
                            		}
                            		
                            /// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int LongMacdFast
                            		{
                            			get { return longmacdfast; }
                            			set { longmacdfast = Math.Max(0, value); }
                            		}
                            		
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int ShortMacdFast
                            		{
                            			get { return shortmacdfast; }
                            			set { shortmacdfast = Math.Max(0, value); }
                            		}
                            
                                    /// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int LongStopLossTicks
                            		{
                            			get { return longstoplossticks; }
                            			set { longstoplossticks = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("Numbers of ticks away from entry price for the Trail Stop order")]
                            		[Category("Parameters")]
                            		public int ShortStopLossTicks
                            		{
                            			get { return shortstoplossticks; }
                            			set { shortstoplossticks = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("Number of ticks away from entry price for the Profit Target order")]
                            		[Category("Parameters")]
                            		public int ProfitTargetTicks
                            		{
                            			get { return profittargetticks; }
                            			set { profittargetticks = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("AtrTargetMultiple")]
                            		[Category("Parameters")]
                            		public double AtrTargetMultiple
                            		{
                            			get { return atrtargetx; }
                            			set { atrtargetx = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("AtrTargetMultiple")]
                            		[Category("Parameters")]
                            		public double AtrLongStopMultiple
                            		{
                            			get { return atrlongstopx; }
                            			set { atrlongstopx = Math.Max(0, value); }
                            		}
                            		
                            		/// <summary>
                            		/// </summary>
                            		[Description("AtrTargetMultiple")]
                            		[Category("Parameters")]
                            		public double AtrShortStopMultiple
                            		{
                            			get { return atrshortstopx; }
                            			set { atrshortstopx = Math.Max(0, value); }
                            		}
                            		
                            			/// <summary>
                            		/// </summary>
                            		[Description("AtrTargetMultiple")]
                            		[Category("Parameters")]
                            		public int Bigmoemalong
                            		{
                            			get { return bigmoemalong; }
                            			set { bigmoemalong = Math.Max(0, value); }
                            		}
                            			/// <summary>
                            		/// </summary>
                            		[Description("AtrTargetMultiple")]
                            		[Category("Parameters")]
                            		public int Bigmoemashort
                            		{
                            			get { return bigmoemashort; }
                            			set { bigmoemashort = Math.Max(0, value); }
                            		}
                            	
                                    #endregion
                                }
                            	}

                            Comment


                              #15
                              In NT, Tools->Output Window

                              You really should split stuff out with BarsInProgress.

                              NT_Bertrand set me straight a couple years ago.



                              Koganam also had helped me out a while ago too.

                              Also the help for BarsArray:





                              Definition
                              BarsArray is an array holding Bars objects that are added via the Add() method. Bars objects can be used as input for indicator methods. This property is of primary value when working with multi-time frame or multi-instrument scripts.





                              Code:
                                      protected override void Initialize()
                                      {
                                          Add(PeriodType.Minute, 1);
                                          CalculateOnBarClose = true;
                                      }
                              
                                      /// <summary>
                                      /// Called on each bar update event (incoming tick)
                                      /// </summary>
                                      protected override void OnBarUpdate()
                                      {
                                          
                                          if (Historical) return;
                                          
                                          if ( BarsInProgress == 0 )
                                          {
                                              Print ( "10 minute bar" );
                                              Print ( " ["+BarsInProgress+"]=" + String.Format( "{0,7}" , String.Format( "{0:####.00}" ,Close[1])) 
                                                  + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Time[1]) + 
                                                  " Closes [0][1]=" + String.Format( "{0:0.00}" ,Closes[0][1]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[0][1]) + 
                                                  " Closes [1][1]=" + String.Format( "{0:0.00}" ,Closes[1][1]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[1][1]) );
                                              Print ( " ["+BarsInProgress+"]=" + String.Format( "{0,7}" , String.Format( "{0:####.00}" ,Close[0])) 
                                                  + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Time[0]) + 
                                                  " Closes [0][0]=" + String.Format( "{0:0.00}" ,Closes[0][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[0][0]) + 
                                                  " Closes [1][0]=" + String.Format( "{0:0.00}" ,Closes[1][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[1][0]) );
                                              
                                              
                                          }
                                          else if ( BarsInProgress == 1 )
                                          {
                                              Print ( "1 minute bar  "  );
                                              Print ( " ["+BarsInProgress+"]=" + String.Format( "{0,7}" , String.Format( "{0:####.00}" ,Close[1])) 
                                                  + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Time[1]) + 
                                                  " Closes [0][1]=" + String.Format( "{0:0.00}" ,Closes[0][1]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[0][1]) + 
                                                  " Closes [1][1]=" + String.Format( "{0:0.00}" ,Closes[1][1]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[1][1]) );
                                              Print ( " ["+BarsInProgress+"]=" + String.Format( "{0,7}" , String.Format( "{0:####.00}" ,Close[0])) 
                                                  + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Time[0]) + 
                                                  " Closes [0][0]=" + String.Format( "{0:0.00}" ,Closes[0][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[0][0]) + 
                                                  " Closes [1][0]=" + String.Format( "{0:0.00}" ,Closes[1][0]) + " ," + String.Format( "{0:MM/dd HH:mm:ss}",Times[1][0]) );
                                              
                                              
                                          }
                                          
                                          
                                      }
                              Originally posted by zachj View Post
                              Ya im a bit lost at this point. And im not farmiliar with the print statements or how to interpret them. I will look into that. Ive tried to change the code around all sorts of ways with the BarsArray, (Historical) etc. and its just executing all over the place. I will just post my entire strategy code not sure if that will help. Its Condition Set 4, the long exit, is where im experimenting with the primary secondary bars.
                              Again im just trying to do If price on 1minute Closes below supertrend dot for previous bar of 10minute, exit long.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              657 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              373 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              109 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              574 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              579 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X