Announcement

Collapse
No announcement yet.

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

    #16
    Hi Chris,

    Thank you for the reply and helpful details.

    I've updated the code as below:
    https://pastebin.com/MbjUw1LV

    Code:
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class MultiStepBreakeven : Strategy
    {
    private int StopLossMode;
    
    
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "MultiStepBreakeven";
    Calculate = Calculate.OnEachTick;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    StopLossModeLong = 0;
    StopLossModeShort = 0;
    }
    else if (State == State.Configure)
    {
    }
    }
    
    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;
    
    if (CurrentBars[0] < 1)
    return;
    
    
    //LONG ORDERS
    // Set 1
    //When no trade is live yet (Flat Position),
    // and the current day is either Monday or Tuesday,
    // and the current bar's High Price is greater tha the previous bar's High Price, and the previous bar's High Price is also greater than the High Price 2 bars ago,
    // and the current time is between 9:30 AM and 11:50 AM, then
    // Place a LONG LIMIT order of default lot size (DefaultQuantity)
    if ((Position.MarketPosition == MarketPosition.Flat)
    && ((Time[0].DayOfWeek == DayOfWeek.Monday)
    || (Time[0].DayOfWeek == DayOfWeek.Tuesday))
    && (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, "");
    StopLossModeLong = 0;
    }
    
    // Set 2
    // If/When The Short position gets trigger (= Set 1 conditions get TRUE), then
    // ADD the INITIAL STOP to Breakeven + 10 ticks (= Position.AveragePrice (+ 10 ticks))
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossModeLong == 0))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (-10 * TickSize)) , @"INITIAL STOP", "");
    }
    
    // Set 3
    // If/When The Short position gets profitable by (Set 5 #/10) of ticks, then
    // MOVE the STOP to Breakeven (=Position.AveragePrice (*1/+ 0 ticks))
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossModeLong == 1))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), Position.AveragePrice, @"STOP MOVED FROM -10 TICKS (INITIAL STOP) TO BREAKEVEN", "");
    }
    
    // Set 4
    // If/When The Short position gets profitable by (Set 6 #/20) of ticks, then
    // MOVE the STOP to Breakeven + 10 ticks (=Position.AveragePrice (+ 10 ticks))
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossModeLong == 2))
    {
    ExitLongStopMarket(Convert.ToInt32(DefaultQuantity ), (Position.AveragePrice + (10 * TickSize)) , @"STOP MOVED FROM BREAKEVEN TO +10 TICKS PROFIT", "");
    }
    
    
    // Set 5
    // Once a/any Short Order is live (Set 2)
    //and the current/last price (Close[0]) gets 10 or more ticks in profit (Short entry - 10 ticks or more), then
    // ENABLE the Stop to be moved to Breakeven (StopLossMode = 1;) / but don't move it yet, just unlock it
    // Set 9 will move the Stop from -10 ticks to Breakeven
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossModeLong == 0)
    && (Close[0] >= (Position.AveragePrice + (10 * TickSize)) ))
    {
    StopLossModeLong = 1;
    }
    
    
    // Set 6
    // Once a/any Short Order has been MOVED to Breakeven (Set 3)
    //and the current/last price (Close[0]) gets 20 or more ticks in profit (Short entry - 20 ticks or more), then
    // ENABLE the Stop to be moved to Breakeven + 10 ticks (StopLossMode = 2;) / but don't move it yet, just unlock it
    // Set 10 will move the Stop from Breakeven to Breakeven + 10 ticks
    if ((Position.MarketPosition == MarketPosition.Long)
    && (StopLossModeLong == 1)
    && (Close[0] >= (Position.AveragePrice + (20 * TickSize)) ))
    {
    StopLossModeLong = 2;
    }
    
    
    
    //SHORT ORDERS
    // Set 7
    //When no trade is live yet (Flat Position),
    // and the current day is either Monday or Tuesday,
    // and the current bar's Low Price is lesser than the previous bar's Low Price, and the previous bar's Low Price is also lesser than the Low Price 2 bars ago,
    // and the current time is between 9:30 AM and 11:50 AM, then
    // Place a SHORT LIMIT order of default lot size (DefaultQuantity)
    if ((Position.MarketPosition == MarketPosition.Flat)
    && ((Time[0].DayOfWeek == DayOfWeek.Monday)
    || (Time[0].DayOfWeek == DayOfWeek.Tuesday))
    && (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, "");
    StopLossModeShort = 0;
    }
    
    // Set 8
    // If/When The Short position gets trigger (= Set 7 conditions get TRUE), then
    // ADD the INITIAL STOP to Breakeven + 10 ticks (= Position.AveragePrice (+ 10 ticks))
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossModeShort == 0))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (10 * TickSize)) , @"INITIAL STOP", "");
    }
    
    // Set 9
    // If/When The Short position gets profitable by (Set 11 #/10) of ticks, then
    // MOVE the STOP to Breakeven (=Position.AveragePrice (*1/+ 0 ticks))
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossModeShort == 1))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), Position.AveragePrice, @"STOP MOVED FROM +10 TICKS (INITIAL STOP) TO BREAKEVEN", "");
    }
    
    // Set 10
    // If/When The Short position gets profitable by (Set 12 #/20) of ticks, then
    // MOVE the STOP to Breakeven + 10 ticks (=Position.AveragePrice (+ 10 ticks))
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossModeShort == 2))
    {
    ExitShortStopMarket(Convert.ToInt32(DefaultQuantit y), (Position.AveragePrice + (-10 * TickSize)) , @"STOP MOVED FROM BREAKEVEN TO +10 TICKS PROFIT", "");
    }
    
    
    // Set 11
    // Once a/any Short Order is live (Set 8)
    //and the current/last price (Close[0]) gets 10 or more ticks in profit (Short entry - 10 ticks or more), then
    // ENABLE the Stop to be moved to Breakeven (StopLossMode = 1;) / but don't move it yet, just unlock it
    // Set 9 will move the Stop from -10 ticks to Breakeven
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossModeShort == 0)
    && (Close[0] <= (Position.AveragePrice + (-10 * TickSize)) ))
    {
    StopLossModeShort = 1;
    }
    
    
    // Set 12
    // Once a/any Short Order has been MOVED to Breakeven (Set 9)
    //and the current/last price (Close[0]) gets 20 or more ticks in profit (Short entry - 20 ticks or more), then
    // ENABLE the Stop to be moved to Breakeven + 10 ticks (StopLossMode = 2;) / but don't move it yet, just unlock it
    // Set 10 will move the Stop from Breakeven to Breakeven + 10 ticks
    if ((Position.MarketPosition == MarketPosition.Short)
    && (StopLossModeShort == 1)
    && (Close[0] <= (Position.AveragePrice + (-20 * TickSize)) ))
    {
    StopLossModeShort = 2;
    }
    
    }
    }
    }






    I can't export the script because of the errors below:





    In order to prevent executions conflict and distinguish the Long and Shot Stop Losses
    (so that when the Short conditions get to true, the code does not overwrite any previous live Long order and vice-versa)





    I changed the default statement
    Code:
    StopLossMode = 0;
    to

    Code:
    StopLossModeLong = 0;
    and added

    Code:
    StopLossModeShort = 0;
    But now I get the compiling errors:
    The name 'StopLossModeLong' does not exist in the current context

    The name 'StopLossModeShort' does not exist in the current context

    https://i.imgur.com/s6WFoY9.png







    Why does it not compile?

    Is it because the StopLossMode is a reserved variable (I searched for it in the documentation but did not find it)?

    Do you see any problem in creating new custom variables to remedy the issue, as follows:

    Code:
    StopLossModeLong = StopLossMode = 0;
    Code:
    StopLossModeShort= StopLossMode = 0;
    What's the best way to make it work?


    EDIT:

    Here's the code with only the StopLossMode both for Long and Short orders snippets:

    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.


    EDIT2:

    Attached is the StopLossMode both for Long and Short orders snippets .zip archive successfully exported:
    Attached Files
    Last edited by Cormick; 05-26-2021, 12:48 PM. Reason: Added code .zip archive

    Comment


      #17
      Hi Cormick, thanks for your reply.

      The StopLossModeLong variable was never defined at the top of the class like StopLossMode is:
      // add private int StopLossModeLong;
      private int StopLossMode;

      See here for a refresher on C# classes and class members:
      W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.


      Best regards,
      -ChrisL

      Comment


        #18
        Hi Chris,

        Thanks a lot for the reply and useful observation.
        I had forgotten about the initialization of variables step.

        I got the script to compile and tested loading it on a chart but for some reason it remains disabled despite ticking the enabled box.

        Here's a video: What causes the enabling dysfunction?

        The code successfully exported in attachment.
        Attached Files

        Comment


          #19
          Hi Cormick, thanks for your reply.

          Please look in the Log tab of the Control Center. Is there an error about strategy initialization in the Log?

          Comment


            #20
            Hi Chris,

            Thanks a lot for the reply and useful tip.

            Actually there the following:
            Code:
            Strategy "MultiStepBreakeven": Error on calling "OnBarUpdate" method on bar 1: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.[URL="https://i.imgur.com/Wh6mjjT.png"][/URL]


            The chart I loaded the strategy on is an ES 1 min chart with 30 days to load.

            There are more than 4 bars on the chart.

            What's causing this issue?

            Comment


              #21
              Hi Cormick, thanks for your reply.

              This means you are accessing a bar index that has not yet processed yet. e.g. CurrentBar == 0 while you try to access Close[1] would cause this problem. Adding a CurrentBar check at the beginning of OnBarUpdate will fix the issue.

              Best regards.

              Comment


                #22
                Hi Chris,

                Thanks a lot for the reply and observation.

                There is already the Strategy builder generate CurrentBars[0] below.
                Code:
                protected override void OnBarUpdate()
                {
                if (BarsInProgress != 0)
                return;
                
                if (CurrentBars[0] < 1)
                return;


                I'm not sure what to do:

                Would adding
                Code:
                    if (CurrentBar < 1)
                        return;


                Solve the issue?

                Or would it conflict with the CurrentBars[0] < 1?


                EDIT:

                I just added as follows:
                Code:
                 protected override void OnBarUpdate()
                {
                if (BarsInProgress != 0)
                return;
                
                if (CurrentBars[0] < 1)
                return;
                
                if (CurrentBar < 1)
                return;

                And it return the same erros on the log:
                Code:
                Strategy "MultiStepBreakeven": Error on calling "OnBarUpdate" method on bar 1: You are accessing an index with a value that is invalid since it is out-of-range. I.E. accessing a series [barsAgo] with a value of 5 when there are only 4 bars on the chart.

                Do I need to delete the
                Code:
                if (CurrentBars[0] < 1)
                return;
                statement?
                Last edited by Cormick; 05-26-2021, 03:46 PM.

                Comment


                  #23
                  Hi Cormick, thanks for your reply.

                  The strategy code is unlocked, so it will not be editable with the builder after it has been unlocked and changed by hand.

                  The strategy is looking back 2 bars here:
                  (High[1] < High[2])

                  So the strategy needs to check for at least 2 bars before beginning to process OnBarUpdate.

                  Best regards,
                  -ChrisL

                  Comment


                    #24
                    Hi Chris!

                    You rock! It worked!



                    I'll do more testing next.

                    Be well!



                    EDIT:

                    The script:

                    And the code successfully exported in attachment.
                    Attached Files
                    Last edited by Cormick; 05-26-2021, 08:48 PM. Reason: Code comments fix

                    Comment


                      #25
                      Hi Cormick,
                      You might want to check your code or its description.
                      In Set 1, you say "greater", but code "smaller".
                      Didn't check the rest in much detail, but spotted the above immediately.
                      NT-Roland

                      Comment


                        #26
                        Hi Roland,

                        Thanks a lot for the helpful note.
                        I corrected the typos from the Short copy and paste snippet and updated the previous post codes.

                        Be well!

                        Comment


                          #27
                          After further tests the code still has the following 2 issues:

                          For some reason it still executes only Short orders.

                          Here's all the executed trades over the last 30 days time span:



                          From those, one didn't place/execute the initial stop and only executed the End of session Stop:

                          Here's a short demo video:

                          The script:



                          And the code successfully exported in attachment in previous post #24 above.


                          About the Long orders not executing issue:

                          Why doesn't the Long Orders get executed?

                          I distinguished the two StopLossMode both for long and short.

                          The code should execute Long orders as well.

                          Unless no Long order bars configuration occur, which I doubt is the cause.

                          What insights about fixing the issue do you suggest?




                          About the Initial stop not executing one of the Short orders:

                          It does not make sense that for all but one order the initial stop gets executed.

                          What cause and fix do you see to this 2nd issue?
                          Attached Files
                          Last edited by Cormick; 05-27-2021, 11:09 AM.

                          Comment


                            #28
                            Hi Cormick, thanks for your reply.

                            I will not be able to look through your custom code to fix these issues. To debug a problem like this, It is best to make a copy of the script and reduce the code until the issue is found, then build back up after. Also see the Print statement that can print out data from your strategy to the output window:
                            https://ninjatrader.com/support/help...script_cod.htm

                            Best regards,
                            -ChrisL

                            Comment


                              #29
                              Hi Chris,

                              Thanks for the reply.

                              The 2nd issue seems solved now after compiling.
                              No Initial Stop aren't executed.

                              For the 1st issue.

                              Is it possible to split the code and create 2 separate strategies and run them simultaneously on the same chart?
                              The 1st strategy for the Long side.
                              And the 2nd strategy for the Short side.

                              Or is there source for conflict?

                              Anything else I need to know about running multiple strategies on the same instrument at the same time?
                              Last edited by Cormick; 05-27-2021, 02:05 PM.

                              Comment


                                #30
                                Hi Cormick,
                                This forum has a quite powerful search functionality.
                                You will find several postings to the topic. Running multiple strategies against the same instrument is actually strongly advised against, unless you use different accounts.
                                Let's say I'm long on the ES and I'm in a 3-hour trade catching a trend. If I see an opportunity to short a pullback can I do that as long as I'm on another chart, even though that other chart is the same instrument (ES). I get that you can not go short and long at the same time on the same chart. However, I ask because I have

                                NT-Roland

                                Comment

                                Latest Posts

                                Collapse

                                Topics Statistics Last Post
                                Started by NullPointStrategies, Yesterday, 05:17 AM
                                0 responses
                                55 views
                                0 likes
                                Last Post NullPointStrategies  
                                Started by argusthome, 03-08-2026, 10:06 AM
                                0 responses
                                132 views
                                0 likes
                                Last Post argusthome  
                                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                                0 responses
                                73 views
                                0 likes
                                Last Post NabilKhattabi  
                                Started by Deep42, 03-06-2026, 12:28 AM
                                0 responses
                                45 views
                                0 likes
                                Last Post Deep42
                                by Deep42
                                 
                                Started by TheRealMorford, 03-05-2026, 06:15 PM
                                0 responses
                                49 views
                                0 likes
                                Last Post TheRealMorford  
                                Working...
                                X