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

StopLoss below the lowest bar since...

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

    StopLoss below the lowest bar since...

    Hello,

    I was wondering if someone could help me out with some NinjaTrader Strategy coding.

    I'm trying to code the following;

    Set Stoploss 10 pips below/above the highest/lowest price of the last 96 bars before the entry bar.



    For example; the moment the strategy gets me LONG;
    Look back 96 bars, get the lowest price, set stoploss 10 pips below this price.

    I don't want it to keep counting 96 bars back when I'm in a position. It has to remain at the same spot.

    I have tried the following coding, but it doesn't work.
    ExitLongStop(0, true, 30000, LowestBar(Close, 96) - 10 * TickSize, "StoppedOutLong", "");




    Note that I'm a beginner in coding and this is my first strategy I'm trying to put together.

    Many many thanks in advance!

    #2
    Originally posted by Aqua-Life View Post
    Hello,

    I was wondering if someone could help me out with some NinjaTrader Strategy coding.

    I'm trying to code the following;

    Set Stoploss 10 pips below/above the highest/lowest price of the last 96 bars before the entry bar.



    For example; the moment the strategy gets me LONG;
    Look back 96 bars, get the lowest price, set stoploss 10 pips below this price.

    I don't want it to keep counting 96 bars back when I'm in a position. It has to remain at the same spot.

    I have tried the following coding, but it doesn't work.
    ExitLongStop(0, true, 30000, LowestBar(Close, 96) - 10 * TickSize, "StoppedOutLong", "");




    Note that I'm a beginner in coding and this is my first strategy I'm trying to put together.

    Many many thanks in advance!
    When you ask for help, it might be best if you also include details of what error messages you are getting and when.

    In this particular case though, in the statement that you have posted, you seem to have a syntax error. The correct syntax would be:
    Code:
    ExitLongStop(0, true, 30000, Low[LowestBar(Low, 96)] - 10 * TickSize, "StoppedOutLong", "");

    Comment


      #3
      Hello Aqua-Life,

      Koganam is correct. You would want to pass the LowestBar() method to get the bar it occurred on in the Low[] index.

      Let me know if I can be of further assistance.
      Cal H.NinjaTrader Customer Service

      Comment


        #4
        Thanks for the reply's!
        I actually didn't get any coding errors, it just didn't do anything when I ran the backtest.
        I just used the line of coding from koganam and it works, but not 100% as I want it.

        It looks like it takes the lows of the most recent 96 bars, while I want it to only look at the 96 bars previous to the entry bar.

        I have attached an image to this message to clarify what I mean.
        Attached Files
        Last edited by Aqua-Life; 10-19-2014, 03:20 AM.

        Comment


          #5
          Here is another example of a trade where price moves up slowly but steadily. The stoploss is moved up on every new high, causing it not to be hit. (red line = stoploss)
          Attached Files

          Comment


            #6
            Thanks for the reply's!
            I actually didn't get any coding errors, it just didn't do anything when I ran the backtest.
            I just used the line of coding from koganam and it works, but not 100% as I want it.

            It looks like it takes the lows of the most recent 96 bars, while I want it to only look at the 96 bars previous to the entry bar.

            I have attached an image to this message to clarify what I mean.
            To find the highest price in the previous n bars (esp. if it doesn't matter when the maximum occurred), I feel you'd need the MAX (or MIN) function:

            Code:
            MAX(High, n)[0]
            If you have a strategy with CalculateOnBarClose = true, I think this finds the max price for the last n fully-formed bars.

            If you're entering on the close of a fully-formed bar - but wish to exclude it - I believe this will do the trick:

            Code:
            MAX(High, n)[1]
            (I'm not quite sure of the situation with CalculateOnBarClose = false and I stand to be corrected abut the nuances of which bars are taken into account.)

            Comment


              #7
              Originally posted by Aqua-Life View Post
              Here is another example of a trade where price moves up slowly but steadily. The stoploss is moved up on every new high, causing it not to be hit. (red line = stoploss)
              You provided a single line of code, which was defective and corrected. How that line fits into your larger purpose was not disclosed.

              From the totality of your posts, we can say for certain that you asked for help with a line that regarded exiting a long position. Next you show a chart that has you entering a short position. Based on that evidence alone, I would be very surprised if a long stop would behave correctly relative to a short entry.

              If your code is such that it cannot be disclosed, so as to understand your intent, the only advice that can realistically given is that you need to bring your code into line with your intent: they surely seem to be at cross-purposes now.

              The first step would be to put into writing a full specification of what you want to do, then code exactly that.

              Such a process helps avoid such faux pas as coding long stops to short entries.

              Comment


                #8
                Thanks for the reply's.

                You are correct I posted a line of coding that was ment for a long position. I use the same logic but I've changed it for a short position. To clear things up I've added the coding to this message.

                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
                
                namespace NinjaTrader.Strategy
                {
                    /// <summary>
                    /// Enter the description of your strategy here
                    /// </summary>
                    [Description("Enter the description of your strategy here")]
                    public class CCItest : Strategy
                    {
                        #region Variables
                        // Wizard generated variables
                        // 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()
                        {
                            CalculateOnBarClose = true;
                            ExitOnClose = false;
                            EntriesPerDirection = 1;
                            Add(CCI(256));
                            Add(EMA(100));
                        }
                
                        /// <summary>
                        /// Called on each bar update event (incoming tick)
                        /// </summary>
                        protected override void OnBarUpdate()
                        {
                            // LONG entry condition set 
                            if (CCI(256)[0] > -50 && CCI(256)[1] > -50 && CCI(256)[2] > -50 && CrossAbove(CCI(256), -50, 3))
                            {        
                                EnterLong(30000, "LongEntry");
                                DrawArrowUp("My up arrow" + CurrentBar, false, 0, Low[0] - 5 * TickSize, Color.Lime);
                            }
                            // SHORT entry condition set
                            if (CCI(256)[0] < 50 && CCI(256)[1] < 50 && CCI(256)[2] < 50 && CrossBelow(CCI(256), 50, 3))
                            {    
                                EnterShort(30000, "ShortEntry");
                                DrawArrowDown("My down arrow" + CurrentBar, false, 0, High[0] + 5 * TickSize, Color.Lime);
                            }
                
                
                // LONG StopLoss condition set
                            if (Position.MarketPosition == MarketPosition.Long)
                            {
                                if (Position.Quantity == 30000)
                                {
                                    ExitLongStop(0, true, 30000, Low[LowestBar(Low, 96)] - 10 * TickSize, "StoppedOutLong", "");
                                }
                                if (Position.Quantity == 20000)
                                {
                                    ExitLongStop(0, true, 20000, Position.AvgPrice + 1 * TickSize, "StopLossLong", "");
                                }
                                if (Position.Quantity == 10000)
                                {
                                    ExitLongStop(0, true, 10000, Position.AvgPrice + 1 * TickSize, "StopLossLong", "");
                                }
                            }
                                
                          
                
                // SHORT StopLoss condition set
                            if (Position.MarketPosition == MarketPosition.Short)
                            {
                                if (Position.Quantity == 30000)
                                {
                                    ExitLongStop(0, true, 30000, High[HighestBar(High, 96)] + 10 * TickSize, "StoppedOutLong", "");
                                }
                                if (Position.Quantity == 20000)
                                {
                                    ExitShortStop(0, true, 20000, Position.AvgPrice - 1 * TickSize, "StopLossShort", "");
                                }
                                if (Position.Quantity == 10000)
                                {
                                    ExitShortStop(0, true, 10000, Position.AvgPrice - 1 * TickSize, "StopLossShort", "");
                                }
                            }
                            }
                            }
                        #region Properties
                        #endregion
                    }
                }
                So I would like the strategy to look back 96 bars the moment it enters a trade, and put the stop loss 10 pips below the lowest low of that period. I don't want it to look back 96 bars every new bar after the entry bar and adjust the stoploss.
                Last edited by Aqua-Life; 10-20-2014, 10:52 AM.

                Comment


                  #9
                  I notice from the code you're using:

                  CalculateOnBarClose = true

                  so I would say your stop would be at:

                  MIN(Low, 96)[0] - 10 * TickSize

                  or

                  MAX(High, 96)[0] + 10 * TickSize

                  (MIN is the lowest low in that range and you're not interested in where the low occurred, which is when you'd use LowestBar.)

                  Comment


                    #10
                    Thanks for the input. Whichever of the 2 options I use, it still keeps counting back 96 bars on every new bar and it keeps adjusting my stops. It does not "stop counting" after the entry bar.

                    Comment


                      #11
                      Originally posted by Aqua-Life View Post
                      Thanks for the input. Whichever of the 2 options I use, it still keeps counting back 96 bars on every new bar and it keeps adjusting my stops. It does not "stop counting" after the entry bar.
                      The problem you're having is because of the way variables work in Ninja. This is quite a sophisticated matter and the way they operate and are declared is different between Indicators and Strategies (I think!).

                      I'd be very interested myself how to see how one of the brilliant Ninja staff experts answers this one if they're reading this.

                      Comment


                        #12
                        // LONG StopLoss condition set
                        if (Position.MarketPosition == MarketPosition.Long)
                        {
                        if (Position.Quantity == 30000)
                        {
                        ExitLongStop(0, true, 30000, Low[LowestBar(Low, 96)] - 10 * TickSize, "StoppedOutLong", "");
                        }
                        if (Position.Quantity == 20000)
                        {
                        ExitLongStop(0, true, 20000, Position.AvgPrice + 1 * TickSize, "StopLossLong", "");
                        }
                        if (Position.Quantity == 10000)
                        {
                        ExitLongStop(0, true, 10000, Position.AvgPrice + 1 * TickSize, "StopLossLong", "");
                        }
                        }
                        That code says: "If I am long, do the fancy math and set stops". IOW, it is doing exactly as you asked: you are long, as soon as you enter the position, and until you exit said position.

                        What you intend on the other hand, is: "If I have just entered a position, do the fancy math and set the Stop"

                        As soon as you do as I suggested, and write these out that way, it is almost obvious that you need to use an event that happens only once, and after you enter the position. That just begs to use OnExecution().

                        Comment


                          #13
                          Thanks for the input. That means I should use IOrder objects if i'm right?

                          Comment


                            #14
                            Originally posted by Aqua-Life View Post
                            Thanks for the input. That means I should use IOrder objects if i'm right?
                            http://www.ninjatrader.com/support/h...nexecution.htm
                            Not really. You do not need to use IOrders, albeit they do make tracking orders much easier. If in doubt, use them.

                            An IOrder exists independently of whether it is assigned to a trackable variable.
                            Last edited by koganam; 10-25-2014, 03:38 PM.

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by Segwin, 05-07-2018, 02:15 PM
                            14 responses
                            1,789 views
                            0 likes
                            Last Post aligator  
                            Started by Jimmyk, 01-26-2018, 05:19 AM
                            6 responses
                            837 views
                            0 likes
                            Last Post emuns
                            by emuns
                             
                            Started by jxs_xrj, 01-12-2020, 09:49 AM
                            6 responses
                            3,294 views
                            1 like
                            Last Post jgualdronc  
                            Started by Touch-Ups, Today, 10:36 AM
                            0 responses
                            13 views
                            0 likes
                            Last Post Touch-Ups  
                            Started by geddyisodin, 04-25-2024, 05:20 AM
                            11 responses
                            63 views
                            0 likes
                            Last Post halgo_boulder  
                            Working...
                            X