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 programming initial stop AND trailing stop?

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

    Strategy programming initial stop AND trailing stop?

    Is there a way to program in an initial stop of x ticks when trade is entered, and then later change the stop to a trailing stop once a certain level is hit? I know this is possible on an ATM strategy, just wondering if it can be manually programmed into a scripted strategy? If so, how? Is it possible to call on an ATM strategy via the scripted strategy? Would that make it easier? If not, then just need to know how to do this.

    Thank you.

    #2
    Hi gubbar924,

    Thanks for your note.

    Yes, this is possible to do in a NinjaScript strategy.

    Basically, when you want to move the stop, call SetStopLoss again and use a new price.
    Your logic will have to decide when to move the stop and at what price to place it.

    Attached is an example I have written for other clients.
    Attached Files
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Thanks Chelsea for the example, that will help greatly!
      I still have some questions about it though ...

      1) I do not see the purpose of the trail boolean, am I missing something? I dont understand how/why its being used.

      2) in the OnMarketData section, how is it calculating the initial 30 ticks move?

      3) in the OnMarketData section, how it is set to update every 2 ticks as noted in the comment section?


      thanks again!

      Comment


        #4
        Hi gubbar924,

        The idea of this strategy is to show multiple ways of moving the stop.

        You don't have to use OnMarketData, but I wanted to demonstrate how to do this in the same file.

        The idea behind the trail bool is that after the breakeven movements have been made, the bool is set to true, which is detected in the condition in OnMarketData. At that point, the trailing is managed by the action code in that branching command.

        The OnMarketData is not doing any of the first break even movements. The break even movements are handled in OnBarUpdate().


        The update in OnMarketData updates every 2 ticks and stays 10 ticks below the current because we check that the e.Price is 12 ticks greater and then move to 10 ticks below the e.Price.
        (&& e.Price > currentStop + 12 * TickSize)
        (currentStop = e.Price - 10 * TickSize)
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          oops I completely missed where trail = true in the 20 ticks section, so now that makes sense to me.

          As for everything else you explained, I see how that works as well.
          After rereading everything, this is what I'm seeing it as ...

          on bar closes
          from +10 to +14 ticks, move the stop loss to entry fill -10 ticks.
          from +15 to +20 ticks move, move the stop loss to entry fill - 5 ticks.
          at 20th tick, move the stop to break even.

          now in the OnMarketData section, one of the conditions is
          e.Price > currentStop + 12 * TickSize

          so initially when price hits 21 ticks profit, stop loss is set to current price - 10 ticks (aka + 11)
          then subsequent stop loss moves happen when price moves at least 12 ticks above the last stop loss (-10 stop, +12 move, net 2 ticks), so the next stop move would be when price is at (+11 + 12 = 23 ticks), when price hits +23, stop loss is moved to +13, and then again when price hits +25 stop will be moved to +15 etc etc

          do I have this correct? maybe just a type-o in the comments section where it says "After 30 ticks" rather than "After 20 ticks", or did I just completely miss something?

          thanks again for the clarification!

          Comment


            #6
            Hi gubbar924,

            You are correct. The comment was a mistake left behind after I've edited this script quite a bit.

            The trail will actually start immediately as the price will likely be at 20 ticks which is greater than Position.AvgPrice + 12 ticks.

            This could be modified to change the currentStop price without setting the SetStopLoss and this would allow for the trail to start at a specified tick amount.

            For example if you set currentStop to Position.AvgPrice + 10 * TickSize after the last break even moment without setting SetStopLoss again, then the trail would take over after 22 ticks.

            I've modified my code and comments to reflect this. Thank you for pointing that out.
            Attached Files
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Trying to get my version of the above example working

              Hi all (and especially ChelseaB)

              I've been coding my own version of a strategy with StopLoss, based on the example above. So far I did not get it running, even after hours of googling and debugging

              I slightly modified this part:
              protected override void OnBarUpdate()
              {
              // Resets the stop loss to the original value when all positions are closed
              if (Position.MarketPosition == MarketPosition.Flat)
              {
              currentStop = 0;
              trail = false;
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss") + "Trail = False");
              SetStopLoss(CalculationMode.Ticks, stoplossticks);
              }

              // If a long position is open, allow for stop loss modification to breakeven
              else if (Position.MarketPosition == MarketPosition.Long && trail == false)
              {
              // After 130 ticks set stop loss to BE-100
              if (Close[0] >= Position.AvgPrice + 130 * TickSize && Close[0] < Position.AvgPrice + 195 * TickSize && currentStop < Position.AvgPrice - 100 * TickSize)
              {
              currentStop = Position.AvgPrice - 100 * TickSize;
              SetStopLoss(CalculationMode.Price, currentStop);
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss")+ " +130 or 2 bars. SL = " + currentStop + " Close = " + Close[0] + " ");
              }

              // After 195 ticks set stop loss to BE-50
              else if (Close[0] >= Position.AvgPrice + 195 * TickSize && Close[0] < Position.AvgPrice + 260 * TickSize && currentStop < Position.AvgPrice - 50 * TickSize)
              {
              currentStop = Position.AvgPrice - 50 * TickSize;
              SetStopLoss(CalculationMode.Price, currentStop);
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss")+ " +195 or 3 bars. SL = " + currentStop + " Close = " + Close[0] + " ");
              }

              // After 20 ticks set stop loss to BE
              else if (Close[0] > Position.AvgPrice + 260 * TickSize && currentStop < Position.AvgPrice)
              {
              currentStop = Position.AvgPrice;
              SetStopLoss(CalculationMode.Price, currentStop);
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss")+ " +260 or 4 bars !!! SL = " + currentStop + " Close = " + Close[0] + " ");

              // after the trail is set to true, the stop loss trail in OnMarketData will take over
              trail = true;
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss")+ "Trail = True");
              }
              }
              But all is well there (I think) . After that my set of opening conditions follows, also running smooth.


              This part of the code seems to be the problem:

              protected override void OnMarketData(MarketDataEventArgs e)
              {

              if (e.MarketDataType == MarketDataType.Last && trail == true && e.Price > currentStop + 12 * TickSize)

              {

              currentStop = e.Price - 10 * TickSize;
              SetStopLoss(CalculationMode.Price, currentStop);
              Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss") + "Trailing Stop: Last = " + e.Price + " ");
              }
              It prints this line to output:

              28-03-2016, 16:49:08Trailing Stop: Last =
              and imo that shows that the code does run, but the trailing is not activated By that I mean that either the currentStop is not correctly set, or there is something wrong with the SetStopLoss. Price goes further up, and then down below the price where the SL should be, but the position is not closed.

              All help welcome. Thanks in advance !

              Comment


                #8
                Hi Spinn,

                The print is printing the market data event price which is not appearing in the output that you have posted.

                Print(Time[0].ToString("dd/MM/yyyy") + ", " + Time[0].ToString("HH:mm:ss") + "Trailing Stop: Last = " + e.Price + " ");

                If that entire Print line is being triggered at all, then the condition was true:
                if (e.MarketDataType == MarketDataType.Last && trail == true && e.Price > currentStop + 12 * TickSize)

                Somehow the market data event price (e.Price) is referenced in the condition and evaluated as true, but cannot be printed in the action block of a condition?

                This does not make sense.

                If you print the following outside of the condition does anything print?
                Code:
                Print(string.Format("{0} | {1} | {2}", e.Time, e.Price, e.MarketDataType));
                If you print that same line inside of the action block of that condition does anything print?
                Last edited by NinjaTrader_ChelseaB; 04-01-2016, 01:16 PM.
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Hi Chelsea,

                  First of all: thanks a lot for your assistance !! Truly appreciated

                  I added that line (first outside the brackets, then inside) and on both occasions see this in output:


                  1-4-2016 15:47:26 | 159,163 | Last
                  1-4-2016 15:47:27 | 159,174 | Ask
                  1-4-2016 15:47:27 | 159,162 | Bid
                  1-4-2016 15:47:27 | 159,162 | Last
                  1-4-2016 15:47:27 | 159,174 | Ask
                  1-4-2016 15:47:27 | 159,163 | Bid
                  1-4-2016 15:47:27 | 159,163 | Last
                  1-4-2016 15:47:28 | 159,174 | Ask
                  1-4-2016 15:47:28 | 159,162 | Bid
                  1-4-2016 15:47:28 | 159,162 | Last
                  1-4-2016 15:47:29 | 159,177 | Ask
                  1-4-2016 15:47:29 | 159,165 | Bid
                  1-4-2016 15:47:29 | 159,165 | Last
                  1-4-2016 15:47:30 | 159,173 | Ask
                  1-4-2016 15:47:30 | 159,16 | Bid
                  1-4-2016 15:47:30 | 159,16 | Last
                  1-4-2016 15:47:31 | 159,174 | Ask
                  1-4-2016 15:47:31 | 159,161 | Bid
                  and I guess this output is what we expected. But that makes the situation all but weirder to me. What should the next step be ??
                  Last edited by Spinn; 04-01-2016, 12:59 PM.

                  Comment


                    #10
                    Hi Spinn,

                    In that case try changing your print.

                    Comment the print you have (so you don't lose your work) and put this a line under.
                    Print(string.Format("{0} Trailing Stop: Last = {1}", Time[0].ToString("dd/MM/yyyy, HH:mm:ss"), e.Price));

                    I think this is equivalent of the string you were attempting to print. This print works on my end.

                    There isn't any code that is your script that is not in your post is there?
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      I tried your suggestion. This is the output:

                      03-03-2016, 22:28:08Trailing Stop: Last =
                      03-03-2016, 22:29:10Trailing Stop: Last =
                      03-03-2016, 22:36:43Trailing Stop: Last =
                      03-03-2016, 22:45:09Trailing Stop: Last =
                      03-03-2016, 22:59:59Trailing Stop: Last =
                      In attachment the full script (I changed the opening condition to something rather simple, that did not change the behaviour, so my opening conditions are not the issue)
                      Attached Files
                      Last edited by Spinn; 04-02-2016, 01:07 PM.

                      Comment


                        #12
                        Hello Spinn,

                        Please try running this simple script that has the same line of code added by itself.

                        What does this script print on your end.

                        Also, to export a NinjaTrader 7 NinjaScript to share with someone do the following:
                        1. Click File -> Utilities -> Export NinjaScript
                        2. Enter a unique name for the file in the value for 'File name:'
                        3. Select the strategy from the objects list on the left -> click the right facing arrow ">" to add the strategy to the export
                        4. Click the 'Export' button -> click 'yes' to add any referenced indicators to the export -> click OK to clear the export location message


                        By default your exported file will be in the following location:
                        • (My) Documents\NinjaTrader 7\bin\Custom\ExportNinjaScript\<export_file_name.z ip>


                        Below is a link to the help guide on Exporting NinjaScripts.
                        http://www.ninjatrader.com/support/h...nt7/export.htm
                        Attached Files
                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          I ran it, but nothing got printed in output.

                          I then inspected the code, but did not see that line anywhere ???

                          Comment


                            #14
                            Hello Spinn,

                            That line is on line 46 of the strategy in my previous post.

                            I have redownloaded this script from the forum to make sure that the script is the correct script and I am seeing that it is correct.

                            What line do you see on line 46 of the strategy that I have provided you in my previous post?
                            Chelsea B.NinjaTrader Customer Service

                            Comment


                              #15
                              Well, an accolade, nothing else (see screenshot)

                              Weird thing is that when I look at the raw code (in a text editor) that line is there. But when I import the script into NT, it disappears. Importing goes smooth, no errors.

                              Anyway, I added it manually and this is the output:

                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,738
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,738
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,763
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,738
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,738
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,762
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,734
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,734
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,763
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,736
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,736
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,765
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,737
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,737
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,763
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,736
                              04-04-2016, 21:59:58 Trailing Stop: Last = 158,736
                              Is it possible that the importing of OnMarketData(MarketDataEventArgs e) causes all the problems ??
                              Attached Files
                              Last edited by Spinn; 04-04-2016, 01:46 PM.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Angus7, Today, 06:03 AM
                              0 responses
                              1 view
                              0 likes
                              Last Post Angus7
                              by Angus7
                               
                              Started by Rhoamajhunm, Today, 05:15 AM
                              0 responses
                              3 views
                              0 likes
                              Last Post Rhoamajhunm  
                              Started by cannaleafzcoast, Yesterday, 11:46 PM
                              0 responses
                              16 views
                              0 likes
                              Last Post cannaleafzcoast  
                              Started by BiankaRidge, Yesterday, 11:37 PM
                              0 responses
                              19 views
                              0 likes
                              Last Post BiankaRidge  
                              Started by RodBlanda, Yesterday, 09:58 PM
                              0 responses
                              18 views
                              0 likes
                              Last Post RodBlanda  
                              Working...
                              X