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

How to include the Short Logic to a Long only Trailing Stop Strategy Builder code?

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

    How to include the Short Logic to a Long only Trailing Stop Strategy Builder code?

    NinjaTrader_Jim from post https://ninjatrader.com/support/foru...56#post1079156

    When trying to import the script at the bottom, I get the error this ninjascript archive was made from an older, incompatible version of Ninja trader
    Therefore I can't share an exported version, nor test it.

    Here's your OnBarUpdate snippet:

    Code:
    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;
    
    if (CurrentBars[0] < 1)
    return;
    
    // Set 1
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (Close[0] > Open[0]))
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    StopLossMode = 0;
    }
    
    // Set 2
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 0))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (-10 * TickSize)) , "", "");
    }
    
    // Set 3
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 1))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), Position.AveragePrice, "", "");
    }
    
    // Set 4
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 2))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (10 * TickSize)) , "", "");
    }
    
    // Set 5
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Close[0] >= (Position.AveragePrice + (10 * TickSize)) )
    && (StopLossMode == 0))
    {
    StopLossMode = 1;
    }
    
    // Set 6
    if ((Position.MarketPosition == MarketPosition.Long)
    && (Close[0] >= (Position.AveragePrice + (20 * TickSize)) )
    && (StopLossMode == 1))
    {
    StopLossMode = 2;
    }
    
    }


    I've replaced all the 'MultiStepBreakeven' instances with 'MultiStepTrailingStop',
    and I've completed your code to include the Short logic below:

    What's wrong?

    How to fix it?

    What about the StopLossMode statements for the Short Logic?



    Code:
    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;
    
    if (CurrentBars[0] < 2)
    return;
    
    [B]//LONG ORDERS[/B]
    // Set 1
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (High[0] > High[1])
    && (High[1] > High[2])
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0)))
    {
    EnterLongLimit(Convert.ToInt32(DefaultQuantity), 0, "");
    StopLossMode = 0;
    }
    
    // Set 2
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 0)
    && (High[1] > High[2])
    && (High[0] > High[1])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (-10 * TickSize)) , "", "");
    }
    
    // Set 3
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 1)
    && (High[1] > High[2])
    && (High[0] > High[1])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), Position.AveragePrice, "", "");
    }
    
    // Set 4
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 2)
    && (High[1] > High[2])
    && (High[0] > High[1])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (10 * TickSize)) , "", "");
    }
    
    
    // Set 5
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 0)
    && (Close[0] >= (Position.AveragePrice + (10 * TickSize)) )
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    StopLossMode = 1;
    }
    
    
    // Set 6
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossMode == 1)
    && (Close[0] >= (Position.AveragePrice + (20 * TickSize)) )
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    StopLossMode = 2;
    }
    
    
    [B]//SHORT ORDERS[/B]
    // Set 7
    if ((Position.MarketPosition == MarketPosition.Flat)
    && (Low[0] < Low[1])
    && (Low[1] < Low[2])
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0)))
    {
    EnterShortLimit(Convert.ToInt32(DefaultQuantity), 0, "");
    StopLossMode = 0;
    }
    
    // Set 8
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossMode == 0)
    && (Low[0] < Low[1])
    && (Low[1] < Low[2])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (10 * TickSize)) , "", "");
    }
    
    // Set 9
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossMode == 1)
    && (Low[0] < Low[1])
    && (Low[1] < Low[2])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), Position.AveragePrice, "", "");
    }
    
    // Set 10
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossMode == 2)
    && (Low[0] < Low[1])
    && (Low[1] < Low[2])
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (-10 * TickSize)) , "", "");
    }
    
    
    // Set 11
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossMode == 0)
    && (Close[0] >= (Position.AveragePrice + (-10 * TickSize)) )
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    StopLossMode = 1;
    }
    
    
    // Set 12
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossMode == 1)
    && (Close[0] >= (Position.AveragePrice + (-20 * TickSize)) )
    && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
    && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
    {
    StopLossMode = 2;
    }
    
    }

    Full unaltered format code:

    Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
    Last edited by Cormick; 05-25-2021, 05:40 AM.

    #2
    Hello Cormick,

    Thank you for your post.

    What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 7.0.1000.? or 8.0.?.?)

    I have tested importing the MultiStepBreakevenStrategyBuilder script located in the forum link your shared. The script imported without any issue.

    Please ensure that you are updated to the latest version of NinjaTrader (8.0.24.2). Then, download the MultiStepBreakevenStrategyBuilder script attached and import it to NinjaTrader by navigating to Tools > Import > NinjaScript AddOn and select the attached MultiStepBreakevenStrategyBuilder script you downloaded.

    Are you able to successfully import the strategy to NinjaTrader?

    If not, please send a screenshot of the error you receive when trying to import the script.

    Let us know if we may assist further.
    Attached Files
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      NinjaTrader_Jim from post https://ninjatrader.com/support/foru...56#post1079156

      did import successfully on my end too.

      However my code update (https://pastebin.com/fJkhw5wQ) does return the importing error.

      HI Brandon,

      Thank you for the reply.

      My NT8 Version:

      8.0.24.2 64-bit

      Here's a screenshot:


      Here's a video:


      Zip attached.
      Attached Files
      Last edited by Cormick; 05-25-2021, 09:19 AM.

      Comment


        #4
        Hello Cormick,

        Thank you for your note.

        After testing the attached MultiStepTrailingStop script I see the same behavior that you are reporting.

        After removing the #region Wizard settings section (lines 211-2341) from your script, the strategy imports successfully.

        Please remove the section mentioned above from your script and try importing the strategy again.

        I have attached an example script that removes this section of the script and imports successfully into NinjaTrader 8.

        Let us know if we may assist further.
        Attached Files
        Brandon H.NinjaTrader Customer Service

        Comment


          #5
          Hi Brandon,

          Thank you for the reply and shared code.
          The #region needs to be put in a separate .xml file before import?

          I did import your .zip successfully.

          After testing, the script seems to execute only the Shorts trades.
          And for some reasons, it doesn't execute on the correct time (outside of the 9:30 to 11:30 AM windows set in the code).

          Here's a short demo video:
          https://drive.google.com/file/d/133s...ew?usp=sharing

          How to make it execute on the right time window only (9:30 to 11:30 AM)?

          How to make the Trailing Stop execute as per set in the code?

          Initial + 10 ticks from entry:
          Code:
           //SHORT ORDERS
          // Set 7
          if ((Position.MarketPosition == MarketPosition.Flat)
          && (Low[0] < Low[1])
          && (Low[1] < Low[2])
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0))
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0)))
          {
          EnterShortLimit(Convert.ToInt32(DefaultQuantity), 0, "");
          StopLossMode = 0;
          }
          
          // Set 8
          if ((Position.MarketPosition == MarketPosition.Short)
          && (StopLossMode == 0)
          && (Low[0] < Low[1])
          && (Low[1] < Low[2])
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
          {
          ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (10 * TickSize)) , "", "");
          }


          Then Entry Price:
          Code:
           // Set 9
          if ((Position.MarketPosition == MarketPosition.Short)
          && (StopLossMode == 1)
          && (Low[0] < Low[1])
          && (Low[1] < Low[2])
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
          {
          ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), Position.AveragePrice, "", "");
          }



          Then Entry price - 10 ticks:
          Code:
           // Set 10
          if ((Position.MarketPosition == MarketPosition.Short)
          && (StopLossMode == 2)
          && (Low[0] < Low[1])
          && (Low[1] < Low[2])
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
          {
          ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (-10 * TickSize)) , "", "");
          }



          StopLossMode Set to 1:
          Code:
           // Set 11
          if ((Position.MarketPosition == MarketPosition.Short)
          && (StopLossMode == 0)
          && (Close[0] >= (Position.AveragePrice + (-10 * TickSize)) )
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
          {
          StopLossMode = 1;
          }



          StopLossMode set to 2:
          Code:
           // Set 12
          if ((Position.MarketPosition == MarketPosition.Short)
          && (StopLossMode == 1)
          && (Close[0] >= (Position.AveragePrice + (-20 * TickSize)) )
          && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
          && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))
          {
          StopLossMode = 2;
          }


          How to execute the Long part of the script?

          I'll add the day of week conditions now.
          Last edited by Cormick; 05-25-2021, 10:00 AM.

          Comment


            #6
            Here's the new code with Days of week filters:
            Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.


            I added the following logic to all sets:

            Code:
             && ((Time[0].DayOfWeek == DayOfWeek.Monday)
            || (Time[0].DayOfWeek == DayOfWeek.Tuesday))


            Is the code correct to allow trading only on Mondays and Tuesdays?

            How do I import the updated code?

            Do I need to adjust the separate .xml?

            If so, how?
            Last edited by Cormick; 05-25-2021, 10:30 AM.

            Comment


              #7
              From NinjaTrader_Jim post here https://ninjatrader.com/support/foru...01#post1157501

              Is the ToTime() function
              Code:
              [B]Examples[/B]


              Code:
               [TABLE]
              [TR]
              [/TR]
              [TR]
              [TD] 			[INDENT]// Only trade between 7:45 AM and 1:45 PM
              			if (ToTime(Time[0]) >= 74500 && ToTime(Time[0]) <= 134500)
              			{
              			 // Strategy logic goes here
              			}[/INDENT]
               			[/TD]
               		[/TR]
              [/TABLE]
              [TABLE]
              [TR]
              [TD] 			[INDENT][B][IMG2=JSON]{"data-align":"none","data-size":"full","src":"https:\/\/ninjatrader.com\/de\/support\/helpGuides\/nt8\/ns.png"}[/IMG2][/B][/INDENT]
               			[/TD]
               		[/TR]
              [TR]
              [TD] 			[INDENT]//store start time as an int variable to be compared
              			int startTime = ToTime(9, 30, 00); // 93000
              
              			//only trade after 9:30AM
              			if (ToTime(Time[0]) >= startTime)
              			{
              			 // Strategy logic goes here
              			}[/INDENT]
               			[/TD]
               		[/TR]
              [/TABLE]

              the correct one in place of the default Strategy Builder code
              Code:
              && (Times[0][0].TimeOfDay <= new TimeSpan(11, 50, 0))
              && (Times[0][0].TimeOfDay >= new TimeSpan(9, 30, 0)))



              to delimit the start time and end time?

              Or are the


              the right ones?

              What are the differences?

              Can we specify seconds as suggested here?

              https://ninjatrader.com/support/help...t8/?totime.htm
              Code:
              Note:  Integer representation of time is in the format Hmmss where 7:30 AM would be 73000 and 2:15:12 PM would be 141512.
              Last edited by Cormick; 05-25-2021, 12:21 PM.

              Comment


                #8
                From NinjaTrader_Jim post here https://ninjatrader.com/support/foru...01#post1157501

                Is the ToDay() function

                https://ninjatrader.com/de/support/h...nt8/?today.htm
                Code:
                [B]Examples[/B]
                Code:
                  [TABLE]
                [TR]
                [/TR]
                [TR]
                [TD] 			[INDENT]protected override void OnBarUpdate()
                			{  
                			  // Compare the date of the current bar to September 15, 2014
                			  if (ToDay(Time[0]) > 20140915)
                			  {
                			      // Do something      
                			  }
                			}[/INDENT]
                 			[/TD]
                 		[/TR]
                [/TABLE][INDENT][/INDENT]

                the correct one in place of the default Strategy Builder code
                Code:
                && ((Time[0].DayOfWeek == DayOfWeek.Monday)
                || (Time[0].DayOfWeek == DayOfWeek.Tuesday))

                to delimit the days of week to trade?

                If so, how to specify the days of week with the ToDay() function?

                Comment


                  #9
                  Hi Cormick, thanks for your post. For future posts please edit all questions into one post as it's easier to read the questions that way.

                  The best resource for Strategy Builder condition making is documented here:
                  https://ninjatrader.com/support/help...on_builder.htm

                  The two links from there that you posted are the best example of creating a time filter and detecting the day of the week in a condition:
                  https://ninjatrader.com/support/help...imeComparisons
                  https://ninjatrader.com/support/help...ateTimeFilters

                  If your running on a tick based chart you can unlock the script to access the second portion of the time variable. It's not possible to access seconds using the builder.

                  how to specify the days of week with the ToDay() function?

                  The ToDay function can not be used in the builder, the script would need to be unlocked to directly use it. There are algorithms that find a day of the week given a calendar date output. See this publicly available link:
                  https://www.hackerearth.com/blog/dev...day-of-a-week/

                  Best regards,
                  -ChrisL
                  Chris L.NinjaTrader Customer Service

                  Comment


                    #10
                    Hi Chris,

                    Thank you for your reply.

                    All the still unanswered questions in one post from posts #5 to #7 above:
                    The latest code version:
                    https://pastebin.com/835tRV4Z


                    How to make it execute on the right time window only (9:30 to 11:30 AM)?

                    How to make the Trailing Stop execute as per set in the code (post #5 above)?

                    The trailing stop does not execute correctly.


                    How to execute the Long part of the script?
                    The long snippet does not execute.

                    See the video:
                    https://drive.google.com/file/d/133s...ew?usp=sharing


                    How do I import the updated code?

                    How do I generate the .xml separate file for the .zip to import?

                    Comment


                      #11
                      Hi Cormick, thanks for your reply.

                      I apologize but I will not be able to fix or debug any custom code. There are many examples of the strategy builder and unlocked script that execute long and short orders. If you would like NinjaScript teaching or consultation a NinjaScript developer can be found here from this publicly available list:
                      https://ninjatraderecosystem.com/sea...mming-services

                      For debugging tools the best thing to use in the Strategy Builder is the Print method. With this, you can print out data from the script and check the conditions to confirm why they are becoming true by printing out each variable from the condition in the action.

                      Our colleague Paul has made an example of a strategy builder time filter here:
                      https://ninjatrader.com/support/foru...es#post1112291

                      There is an example here on making a trailing stop in the builder as well:
                      https://ninjatrader.com/support/foru...er#post1088239

                      Best regards,
                      -ChrisL

                      The NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The add-ons listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.
                      Chris L.NinjaTrader Customer Service

                      Comment


                        #12
                        Hi Chris,

                        Thanks for the reply.

                        There are many examples of the strategy builder and unlocked script that execute long and short orders.
                        Where?

                        I don't need NinjaScript teaching or consultation for strategy builder matters and didn't ask for it. Thank you for suggesting it anyways.

                        Thanks for the Print tool mention. I'll check it tomorrow.

                        Thanks for the Paul example. I'll check it.

                        Thanks for the trailing stop example. I'll check it tomorrow.

                        The issue is I still don't know how to generate the .zip archive to import the code.
                        And without it I cannot test if it works or debug it.


                        My previous last question, if it escaped your attention.
                        How do I import the updated code?

                        How do I generate the .xml separate file for the .zip to import?




                        Thanks a lot!

                        Comment


                          #13
                          Hi Cormick, thanks for your reply.

                          The script you posted appears to not be Exported properly because it does not contain the info.xml file. Exporting will add the required .xml file to the .zip automatically.

                          Best regards,
                          -ChrisL
                          Chris L.NinjaTrader Customer Service

                          Comment


                            #14
                            Hi Chris,

                            Thanks for the reply.

                            The script was not exported. I copied the .cs file and edited it outside of Ninjatrader (in a syntax highlight friendly text editor).

                            Therefore what I would need and asked is importing the edited version back into Ninjatrader.

                            Problem is if I do it without the .xml file it returns the importing error I mentioned above:
                            https://ninjatrader.com/support/foru...98#post1157498


                            How do I import it (not export it) from the updated .cs file only?

                            If I need the .xml file how do I generate it from outside of Ninjatrader? or if I just copy the .xml from the original version of the .cs file will it work?

                            What do you suggest?

                            How do you do it? What is the correct way to do it? Any documentation reference?

                            Else, do I need to to do it the other way around?
                            Export the original code, then make the edit to the .cs file outside Ninjatrader, and then import it back to Ninjatrader?

                            If I do it that way, do I need to make edits to the .xml or not?

                            Comment


                              #15
                              Hi Cormick, thanks for your reply.

                              You can not edit a strategy builder strategy by hand without unlocking it first. If you want to unlock it, do so through the strategy builder interface, then you can open up the strategy in an external text editor or the NinjaScript editor. Once you want to export it for others to use, use the Exporting instructions I sent earlier this will allow others to Import through Tools>Import. There's no supported way to generate the info.xml file outside of NinjaTrader.

                              Best regards,
                              -ChrisL
                              Chris L.NinjaTrader Customer Service

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by tkaboris, Today, 05:13 PM
                              0 responses
                              2 views
                              0 likes
                              Last Post tkaboris  
                              Started by GussJ, 03-04-2020, 03:11 PM
                              16 responses
                              3,281 views
                              0 likes
                              Last Post Leafcutter  
                              Started by WHICKED, Today, 12:45 PM
                              2 responses
                              19 views
                              0 likes
                              Last Post WHICKED
                              by WHICKED
                               
                              Started by Tim-c, Today, 02:10 PM
                              1 response
                              9 views
                              0 likes
                              Last Post NinjaTrader_ChelseaB  
                              Started by Taddypole, Today, 02:47 PM
                              0 responses
                              5 views
                              0 likes
                              Last Post Taddypole  
                              Working...
                              X