Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Break even after price advancement

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

    Break even after price advancement

    Hi guys, I am trying to set you the price to break even after price advanced few ticks in my favor. I did download and imported the sample from http://www.ninjatrader.com/support/f...ead.php?t=3222

    First of all the stop loss order is not moved to break even after 10 ticks advancement(I changed it from 50 as in sample).

    if (Close[0] >= Position.AvgPrice + 10 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
    }

    Secondary the sample page mentioning:
    Other methods and properties of interest include:
    Is nothing in the code that refer to SetTrailstop


    I'm working with 5 range bars on CL Feb 15 contract.

    Please advise, the file attached.
    Attached Files

    #2
    Hello meowflying,

    Thanks for your post.

    The issue is that if you run your strategy with CalculateOnbarClose=true you will have situations where the stop will not get moved because the strategy code does not execute until the end of the bar and the conditions of avgprice are not evaluated until then. If you run with CalculateOnbarClose(COBC) = false then the statements are evaluated on each tick. To help illustrate I created a video showing the difference using COBC = true and COBC = false using the same data. http://screencast.com/t/ovwnGOcgiCX In the video, no sound, the first test is with COBC=true, here you will see price will be at the level that would move the stop however because bar has not closed at that point the stop is not moved because code is not executed. When the bar does close, it is below the value that would cause the stop to move. In the 2nd test with COBC=false, the stop moves at the moment that the evaluation price condition is met.

    I suspect that had you used a larger profit target or a small bar size that your strategy would work even with COBC = true.

    You are correct, the code does not use SetTrailstop, it was only a reference to another method that may be of interest.

    Please let me know if I can be of further assistance.

    Comment


      #3
      Thank you for your answer, it does work with COBC) = false. Now I did implement that code in my strategy, however it does work only for longs, could you take a look( I did try to input if (Close[0] > Position.AvgPrice - 10 * TickSize): didnt help as well:

      // Resets the stop loss to the original value when all positions are closed
      if (Position.MarketPosition == MarketPosition.Flat)
      {
      SetStopLoss(CalculationMode.Ticks, 10);
      }

      // If a long position is open, allow for stop loss modification to breakeven
      else if (Position.MarketPosition == MarketPosition.Long)
      {
      // Once the price is greater than entry price+10 ticks, set stop loss to breakeven
      if (Close[0] > Position.AvgPrice + 10 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AvgPrice,);
      }
      }



      // If a short position is open, allow for stop loss modification to breakeven
      else if (Position.MarketPosition == MarketPosition.Short)
      {
      // Once the price is greater than entry price+10 ticks, set stop loss to breakeven
      if (Close[0] > Position.AvgPrice + 10 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AvgPrice);
      }
      }


      Originally posted by NinjaTrader_Paul View Post
      Hello meowflying,

      Thanks for your post.

      The issue is that if you run your strategy with CalculateOnbarClose=true you will have situations where the stop will not get moved because the strategy code does not execute until the end of the bar and the conditions of avgprice are not evaluated until then. If you run with CalculateOnbarClose(COBC) = false then the statements are evaluated on each tick. To help illustrate I created a video showing the difference using COBC = true and COBC = false using the same data. http://screencast.com/t/ovwnGOcgiCX In the video, no sound, the first test is with COBC=true, here you will see price will be at the level that would move the stop however because bar has not closed at that point the stop is not moved because code is not executed. When the bar does close, it is below the value that would cause the stop to move. In the 2nd test with COBC=false, the stop moves at the moment that the evaluation price condition is met.

      I suspect that had you used a larger profit target or a small bar size that your strategy would work even with COBC = true.

      You are correct, the code does not use SetTrailstop, it was only a reference to another method that may be of interest.

      Please let me know if I can be of further assistance.

      Comment


        #4
        Hello meowflying,

        Thanks for your reply.

        On the short side you want to test if the current price is less than your entry price - 10 ticks.

        if (Close[0] < Position.AvgPrice - 10 * TickSize)

        Please let me know if I can be of further assistance.

        Comment


          #5
          Following that issue, the breakeven feature working in most cases, but not 100% even with the COBC = false and big targets/stops. What is the problem and how to fix it?

          Also I have another question will few conditions like that work together(creating kinda trailing stop that depends on amount of ticks that price goes in our favor):

          else if (Position.MarketPosition == MarketPosition.Long)
          {

          if (Close[0] > Position.AvgPrice + 10 * TickSize)
          {
          SetStopLoss(CalculationMode.Price, Position.AvgPrice,);


          if (Close[0] > Position.AvgPrice + 20 * TickSize)
          {
          SetStopLoss(CalculationMode.Price, Position.AvgPrice+ 5 * TickSize);
          }
          }




          Originally posted by NinjaTrader_Paul View Post
          Hello meowflying,

          Thanks for your reply.

          On the short side you want to test if the current price is less than your entry price - 10 ticks.

          if (Close[0] < Position.AvgPrice - 10 * TickSize)

          Please let me know if I can be of further assistance.

          Comment


            #6
            Hello meowflying,

            Thanks for your post.

            You will want to follow a debugging process for your code to understand what is happening and when. Use Print statements (these show up on the Output window ( Tools>output window) at each area where a critical step is being evaluated and use the print statement to output those results so that you can review them step by step. For example, Print ("Close price: "+Close[0]+" entry price: "+Position.AvgPrice); When I debug my code I will use a print statement at each step until I am sure that step is functioning as expected and yes it can be tedious but that is the one way for you to know why something is or is not working.

            The condition statements will work together however note that each time the code is executed that the stop could be moved to breakeven then + 5 ticks repeatedly. If you only want the code to be executed one time once the conditions has been reached (IE: Close>+10 or Close>+20), then you can use bools in each condition. For example:

            else if (Position.MarketPosition == MarketPosition.Long)
            {

            if (Close[0] > Position.AvgPrice + 10 * TickSize && !be1stop)
            {
            SetStopLoss(CalculationMode.Price, Position.AvgPrice,);
            be1stop = true; // set so only execute once.
            }


            if (Close[0] > Position.AvgPrice + 20 * TickSize && be1stop && !be2stop)
            {
            SetStopLoss(CalculationMode.Price, Position.AvgPrice+ 5 * TickSize);
            be2stop = true; // set so only execute once.
            }

            }

            Note that you would need to declare be1stop and be2stop as bools and set them to false each time you are flat.

            Please let me know if I can be of further assistance.

            Comment


              #7
              My knowledge of bools and coding is limited unfortunately, should it be something like that:

              #region Variables
              private bool be1stop = false; // Default setting for Be1stop

              private bool be2stop = false; // Default setting for Be2stop


              #endregion


              #region Properties

              [Description("")]
              [GridCategory("Parameters")]
              public bool Be1stop
              {
              get { return be1stop; }
              set { be1stop = value; }
              }

              [Description("")]
              [GridCategory("Parameters")]
              public bool Be2stop
              {
              get { return be2stop; }
              set { be2stop = value; }
              }

              #endregion




              Originally posted by NinjaTrader_Paul View Post
              Hello meowflying,

              Thanks for your post.

              You will want to follow a debugging process for your code to understand what is happening and when. Use Print statements (these show up on the Output window ( Tools>output window) at each area where a critical step is being evaluated and use the print statement to output those results so that you can review them step by step. For example, Print ("Close price: "+Close[0]+" entry price: "+Position.AvgPrice); When I debug my code I will use a print statement at each step until I am sure that step is functioning as expected and yes it can be tedious but that is the one way for you to know why something is or is not working.

              The condition statements will work together however note that each time the code is executed that the stop could be moved to breakeven then + 5 ticks repeatedly. If you only want the code to be executed one time once the conditions has been reached (IE: Close>+10 or Close>+20), then you can use bools in each condition. For example:

              else if (Position.MarketPosition == MarketPosition.Long)
              {

              if (Close[0] > Position.AvgPrice + 10 * TickSize && !be1stop)
              {
              SetStopLoss(CalculationMode.Price, Position.AvgPrice,);
              be1stop = true; // set so only execute once.
              }


              if (Close[0] > Position.AvgPrice + 20 * TickSize && be1stop && !be2stop)
              {
              SetStopLoss(CalculationMode.Price, Position.AvgPrice+ 5 * TickSize);
              be2stop = true; // set so only execute once.
              }

              }

              Note that you would need to declare be1stop and be2stop as bools and set them to false each time you are flat.

              Please let me know if I can be of further assistance.

              Comment


                #8
                hello meowflying,

                Thanks for your reply and question.

                This is all you need to declare the variables:

                #region Variables
                private bool be1stop = false; // Default setting for Be1stop
                private bool be2stop = false; // Default setting for Be2stop
                #endregion

                The other properties section in your example would only be needed if you were setting these variables externally. So the properties are not needed.

                Comment


                  #9
                  Thank you for your reply. I didnt want to open new thread, I've got another question about halting the strategy after defined profit or loss is reached. The following code should make it happen, my question is how to restart the strategy in the beginning of the next day trading session?


                  // After our strategy has a PnL greater than $1000 or less than -$400 we will stop our strategy
                  if (Performance.AllTrades.TradesPerformance.Currency. CumProfit > 1000
                  || Performance.AllTrades.TradesPerformance.Currency.C umProfit < -400)
                  {
                  /* A custom method designed to close all open positions and cancel all working orders will be called.
                  This will ensure we do not have an unmanaged position left after we halt our strategy. */
                  StopStrategy();

                  // Halt further processing of our strategy
                  return;
                  }


                  Originally posted by NinjaTrader_Paul View Post
                  hello meowflying,

                  Thanks for your reply and question.

                  This is all you need to declare the variables:

                  #region Variables
                  private bool be1stop = false; // Default setting for Be1stop
                  private bool be2stop = false; // Default setting for Be2stop
                  #endregion

                  The other properties section in your example would only be needed if you were setting these variables externally. So the properties are not needed.

                  Comment


                    #10
                    Hello,

                    If your strategy runs 24 hours a day then you can control restarting by testing for the first bar of the session, for example

                    if (Bars.FirstBarOfSession)
                    {
                    runStrategy = true; // A simple bool to allow strategy to run (need to declare in region variables)
                    }

                    if (runStrategy)
                    {

                    // execute strategy stuff here

                    (adding in your example)
                    if (Performance.AllTrades.TradesPerformance.Currency. CumProfit > 1000
                    || Performance.AllTrades.TradesPerformance.Currency.C umProfit < -400)
                    {
                    StopStrategy();
                    runStrategy = false; // stop running until new session
                    // Halt further processing of our strategy
                    return;
                    }

                    }

                    Also, please review these reference samples: http://www.ninjatrader.com/support/f...ead.php?t=4804

                    Comment


                      #11
                      Thank you Paul, it seems like a good and simple solution. However that will calculate total profit of the strategy including previous days. How to make it calculate only current day? Also will it halt even if the strategy in the position, or it waits till we are flat?

                      Originally posted by NinjaTrader_Paul View Post
                      Hello,

                      If your strategy runs 24 hours a day then you can control restarting by testing for the first bar of the session, for example

                      if (Bars.FirstBarOfSession)
                      {
                      runStrategy = true; // A simple bool to allow strategy to run (need to declare in region variables)
                      }

                      if (runStrategy)
                      {

                      // execute strategy stuff here

                      (adding in your example)
                      if (Performance.AllTrades.TradesPerformance.Currency. CumProfit > 1000
                      || Performance.AllTrades.TradesPerformance.Currency.C umProfit < -400)
                      {
                      StopStrategy();
                      runStrategy = false; // stop running until new session
                      // Halt further processing of our strategy
                      return;
                      }

                      }

                      Also, please review these reference samples: http://www.ninjatrader.com/support/f...ead.php?t=4804

                      Comment


                        #12
                        Hello,

                        You could use another variable to hold the days profit/loss which can then be reset each day on the first bar of the session and another which can hold the accumulated profit/loss which can be subtracted from the Alltrades. For example: dailyPNL = Performance.AllTrades.TradesPerformance.Currency. CumProfit - dailyAccPNL; You would also then want to use the dailyPNL variable for your daily check of profit/loss.

                        I added the runStrategy = false; after StopStrategy call, so whatever your StopStrategy() does, when it returns, runStrategy will be set false and will no longer be allow to place orders until the next session.

                        In order for you to see how your strategy runs, I recommend that you add Print statements in key areas to help you understand.

                        Comment


                          #13
                          All is working fine Paul, thank you. I added some BarsSinceExit conditions to my entries, however the script executing only short trades now. It does limit both short and long, but it limits all longs. Any idea?

                          P.S. Just now it seems like its blocking long and shorts in random. Very strange, such an easy and clear condition.

                          // Condition set 1
                          if (Position.MarketPosition == MarketPosition.Flat
                          && CrossAbove(EMA(5), EMA(50), 1)&& (BarsSinceExit("long") > 10 || BarsSinceExit() == -1) && (BarsSinceExit("long1") > 10 || BarsSinceExit() == -1))
                          {
                          EnterLong(DefaultQuantity, "long");
                          EnterLong(DefaultQuantity, "long1");

                          }
                          if (Position.MarketPosition == MarketPosition.Flat
                          && CrossAbove(EMA(5), EMA(50), 1)&& (BarsSinceExit("long") < 10 || BarsSinceExit() == -1) && (BarsSinceExit("long1") < 10 || BarsSinceExit() == -1))
                          {
                          Print("Long is limited");
                          DrawArrowUp("My up arrow" + CurrentBar, false, 0, Low[0] + 1 * TickSize, Color.Lime);
                          }
                          // Condition set 2
                          if (Position.MarketPosition == MarketPosition.Flat
                          && CrossBelow(EMA(5), EMA(50), 1)&& (BarsSinceExit("short") > 10 || BarsSinceExit() == -1) && (BarsSinceExit("short1") > 10 || BarsSinceExit() == -1))
                          {

                          EnterShort(DefaultQuantity, "short");
                          EnterShort(DefaultQuantity, "short1");
                          }
                          if (Position.MarketPosition == MarketPosition.Flat
                          && CrossBelow(EMA(5), EMA(50), 1)&& (BarsSinceExit("short") < 10 || BarsSinceExit() == -1) && (BarsSinceExit("short1") < 10 || BarsSinceExit() == -1))
                          {
                          Print("Short is limited");
                          DrawArrowDown("My down arrow" + CurrentBar, false, 0, High[0] - 1 * TickSize, Color.Red);
                          }






                          Originally posted by NinjaTrader_Paul View Post
                          Hello,

                          You could use another variable to hold the days profit/loss which can then be reset each day on the first bar of the session and another which can hold the accumulated profit/loss which can be subtracted from the Alltrades. For example: dailyPNL = Performance.AllTrades.TradesPerformance.Currency. CumProfit - dailyAccPNL; You would also then want to use the dailyPNL variable for your daily check of profit/loss.

                          I added the runStrategy = false; after StopStrategy call, so whatever your StopStrategy() does, when it returns, runStrategy will be set false and will no longer be allow to place orders until the next session.

                          In order for you to see how your strategy runs, I recommend that you add Print statements in key areas to help you understand.
                          Last edited by meowflying; 03-05-2015, 09:54 AM.

                          Comment


                            #14
                            Hello,

                            Thanks for your reply, glad to hear of your progress.

                            In this statement:
                            (BarsSinceExit("long") > 10 || BarsSinceExit() == -1) && (BarsSinceExit("long1") > 10 || BarsSinceExit() == -1)

                            Please add the signal names of long and long1 in the -1 check, so:
                            (BarsSinceExit("long") > 10 || BarsSinceExit("long") == -1) && (BarsSinceExit("long1") > 10 || BarsSinceExit("long1") == -1)

                            Same change for the short side as well.

                            Please let me know if I can be of further assistance.

                            Comment


                              #15
                              Thank you, seems to work well. The only problem is with the beginning of the day, it seems to look back on the last session exits(exit on close etc) and its preventing it from entering the trades. I guess need to reset it with Bars.FirstBarOfSession, or some other command ? How to do it in the right way?

                              Originally posted by NinjaTrader_Paul View Post
                              Hello,

                              Thanks for your reply, glad to hear of your progress.

                              In this statement:
                              (BarsSinceExit("long") > 10 || BarsSinceExit() == -1) && (BarsSinceExit("long1") > 10 || BarsSinceExit() == -1)

                              Please add the signal names of long and long1 in the -1 check, so:
                              (BarsSinceExit("long") > 10 || BarsSinceExit("long") == -1) && (BarsSinceExit("long1") > 10 || BarsSinceExit("long1") == -1)

                              Same change for the short side as well.

                              Please let me know if I can be of further assistance.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              648 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              369 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              108 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              572 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              573 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X