Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Help with breakeven

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

    Help with breakeven

    Hello everybody and sorry for my english, iīm from Spain, and it isnīt very good.

    I'm attempting to do an immediate stop and reverse on a system with code that sets the stop to breakeven. I copied the code from the SamplePriceModification.cs file on another help item and am using that. But what occurs now is that after a winning long trade I close the position, go short immediately and get immediately stopped out (instantly) on the backtesting of the strategy.

    I saw the forum "Set stop to breakeven after profit" and your help but it doesnt work neither.
    Can you help me please

    This is the code.

    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // Resets the stop loss to the original value when all positions are closed
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    SetStopLoss(CalculationMode.Ticks, StopLoss);
    }
    // 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+50 ticks, set stop loss to breakeven
    if (Close[0] > Position.AvgPrice + 50 * TickSize)
    {
    SetStopLoss(CalculationMode.Price, Position.AvgPrice);
    }
    }
    // Condition set 1
    if (CrossAbove(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1))
    {
    EnterLong(DefaultQuantity, "Largo");
    }

    // Condition set 2
    if (CrossBelow(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1)
    && ADX(14)[0] > ValorADX)
    {
    EnterShort(DefaultQuantity, "Corto");

    #2
    Welcome to our forums!

    Is there more code to your strategy? It appears to be cut off.

    How exactly to you close the position? Are you just letting the stop loss execute at the break even price?

    First of all you would want to use Print() statements to verify values are what you expect - Debugging your NinjaScript code.

    For strategies add TraceOrders = true to your Initialize() method and you can then view valuable output related to strategy submitted orders through Tools > Output window - TraceOrders

    It may also help to add drawing objects to your chart for signal and condition confirmation - Drawing Objects.
    MatthewNinjaTrader Product Management

    Comment


      #3
      Iīm really impressed for your quick response... on saturday!!
      Thank you.

      Originally posted by NinjaTrader_Matthew View Post
      Welcome to our forums!

      Is there more code to your strategy? It appears to be cut off.
      Yes. Now you can view complete.

      How exactly to you close the position? Are you just letting the stop loss execute at the break even price?
      Usually, stoploss works, and breakeven also for long trades. But after a long winning trade, if there is a short trade, it close inmediatly.

      First of all you would want to use Print() statements to verify values are what you expect - Debugging your NinjaScript code.
      I dont know how to make "debugging", iīll look at this link as soon as possible.

      For strategies add TraceOrders = true to your Initialize() method and you can then view valuable output related to strategy submitted orders through Tools > Output window - TraceOrders

      It may also help to add drawing objects to your chart for signal and condition confirmation - Drawing Objects.
      The complete 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

      // This namespace holds all strategies and is required. Do not change it.
      namespace NinjaTrader.Strategy
      {
      /// <summary>
      /// Seguidor de tendencias del bund con filtros
      /// </summary>
      [Description("Seguidor de tendencias del bund con filtros")]
      public class CopiadelTrendBund : Strategy
      {
      #region Variables
      // Wizard generated variables
      private int cortaEntradaLargo = 7; // Default setting for CortaEntradaLargo
      private int stopLoss = 60; // Default setting for StopLoss
      private int periodoDonchian = 9; // Default setting for PeriodoDonchian
      private int largaEntradaLargo = 120; // Default setting for LargaEntradaLargo
      private int valorADX = 20; // Default setting for ValorADX
      // 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()
      {
      Add(WMA(CortaEntradaLargo));
      Add(WMA(LargaEntradaLargo));
      Add(ADX(14));
      Add(DonchianChannel(PeriodoDonchian));

      CalculateOnBarClose = true;
      }
      /// <summary>
      /// Called on each bar update event (incoming tick)
      /// </summary>
      protected override void OnBarUpdate()
      {
      // Resets the stop loss to the original value when all positions are closed
      if (Position.MarketPosition == MarketPosition.Flat)
      {
      SetStopLoss(CalculationMode.Ticks, StopLoss);
      }
      // 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+50 ticks, set stop loss to breakeven
      if (Close[0] > Position.AvgPrice + 50 * TickSize)
      {
      SetStopLoss(CalculationMode.Price, Position.AvgPrice);
      }
      }
      // Condition set 1
      if (CrossAbove(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1))
      {
      EnterLong(DefaultQuantity, "Largo");
      }

      // Condition set 2
      if (CrossBelow(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1)
      && ADX(14)[0] > ValorADX)
      {
      EnterShort(DefaultQuantity, "Corto");
      }

      // Condition set 3
      if (Position.MarketPosition == MarketPosition.Short
      && Close[0] > DonchianChannel(PeriodoDonchian).Upper[1]
      && Position.GetProfitLoss(Close[0], PerformanceUnit.Currency) > 0)
      {
      ExitShort("Salida donchian", "Corto");
      }


      }

      #region Properties
      [Description("")]
      [GridCategory("Parameters")]
      public int CortaEntradaLargo
      {
      get { return cortaEntradaLargo; }
      set { cortaEntradaLargo = Math.Max(1, value); }
      }

      [Description("")]
      [GridCategory("Parameters")]
      public int StopLoss
      {
      get { return stopLoss; }
      set { stopLoss = Math.Max(1, value); }
      }

      [Description("")]
      [GridCategory("Parameters")]
      public int PeriodoDonchian
      {
      get { return periodoDonchian; }
      set { periodoDonchian = Math.Max(1, value); }
      }

      [Description("")]
      [GridCategory("Parameters")]
      public int LargaEntradaLargo
      {
      get { return largaEntradaLargo; }
      set { largaEntradaLargo = Math.Max(1, value); }
      }

      [Description("")]
      [GridCategory("Parameters")]
      public int ValorADX
      {
      get { return valorADX; }
      set { valorADX = Math.Max(1, value); }
      }
      #endregion
      }
      }

      At the image you can see an example of a short trade after a long winning trade.
      Attached Files

      Comment


        #4
        Hello Mercader,

        Thank you for your patience.

        I have reviewed and tested your code and I do not see the same behavior in backtesting on my end.

        Can you provide a screenshot of the settings tab after running the backtest that produces those results so I may test the same settings on my end?

        I look forward to assisting your further.

        Comment


          #5
          Here you can see
          Attached Files

          Comment


            #6
            Hello Mercader,

            Thank you for your patience.

            This is occurring when the EnterShort() is called and the Stop Loss for the EnterLong() is still at breakeven and when we go short the Stop Loss is then filled as the Stop Loss will not be set back to 60 ticks away until the next bar.

            To resolve this matter you can use the signalNames for your entries in your Stop Losses:
            Code:
            if (Position.MarketPosition == MarketPosition.Flat)
            {
            SetStopLoss("Corto", CalculationMode.Ticks, 60, false);
            SetStopLoss("Largo", CalculationMode.Ticks, 60, false);
            }
            
            if (Position.MarketPosition == MarketPosition.Long)
            {
            if (Close[0] > Position.AvgPrice + 50 * TickSize)
            {
            SetStopLoss("Largo", CalculationMode.Price, Position.AvgPrice, false);
            }
            
            if (Position.MarketPosition == MarketPosition.Short)
            {
            if (Close[0] < Position.AvgPrice - 50 * TickSize)
            {
            SetStopLoss("Corto", CalculationMode.Price, Position.AvgPrice, false);
            }
            Please let me know if this resolves the matter.
            Last edited by NinjaTrader_PatrickH; 08-01-2013, 06:22 AM.

            Comment


              #7
              Hello Patrick,

              Iīm really greatful for your work.
              I thougt that this solved the problem and it does mostly but i found 6 trades that their MAE is bigger than StopLoss.
              I donīt know why.

              Usually there are more trades that their MAE is bigger than StopLoss because of gaps and cause of this MAE=Profit, but how you can see at the attached file, some of these trades are wrong.


              This is the code.

              // Resets the stop loss to the original value when all positions are closed
              if (Position.MarketPosition == MarketPosition.Flat)
              {
              SetStopLoss("Corto", CalculationMode.Ticks, 60, false);
              SetStopLoss("Largo", CalculationMode.Ticks, 60, false);
              }
              if (Position.MarketPosition == MarketPosition.Long)
              {
              if (High[0] > Position.AvgPrice + 50 * TickSize)
              {
              SetStopLoss("Largo", CalculationMode.Price, Position.AvgPrice + (12 * TickSize), false);
              }}

              if (Position.MarketPosition == MarketPosition.Short)
              {
              if (Low[0] < Position.AvgPrice - 50 * TickSize)
              {
              SetStopLoss("Corto", CalculationMode.Price, Position.AvgPrice - (12 * TickSize), false);
              }}
              Attached Files

              Comment


                #8
                Hello Mercader,

                Thank you for your response.

                Can you expand the Entry Price and Exit Price columns of your Strategy Analyzer results on the Trades tab and provide a screenshot of this as well?

                You can also right click in the results on the Trades tab > select Grid > Export to Excel > save the file in Excel and attach the file to your response if you have Excel.

                I look forward to assisting you further.

                Comment


                  #9
                  Hello Patrick,

                  thanks again.

                  Of course, here you are.

                  Sorry, but the "manage attachments" donīt let me send you an excel file.
                  Itīs a pdf file, ok?
                  Attached Files

                  Comment


                    #10
                    Hello Mercader,

                    Thank you for your response.

                    The MAE here would be the average up to the trade you are comparing, so your MAE went from $1,150 on the previous negative PnL on the last trade (#97) to $1,070 on trade #98 which was a profitable trade. So the MAE average dropped due to the profitable trade.

                    For information on statistics definitions in NinjaTrader please visit the following link: http://www.ninjatrader.com/support/h...efinitions.htm

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

                    Comment


                      #11
                      Hello Patrick,

                      I used the statistics to explain the error.

                      The MAE in trade 98 is 1070$ cause of entry price was 108,47$ and the worst price gets to reach is 107,4$ (108,47-107,4=1,07)
                      It would never have happened because stoploss was 60 ticks how you can see in the graphic at the previous message.

                      When I do the backtest withot the breakeven, the stoploss work correctly always.

                      Comment


                        #12
                        Hello Mercader,

                        Thank you for your response.

                        Can you provide a toy version of your script that causes this to occur when using breakeven for your Stop Loss?

                        I look forward to your response.

                        Comment


                          #13
                          Hello

                          Well, I have found the problem, but I donīt know how to fix it.

                          1.- It goes long by a cross moving average,
                          2.- It reach the price for stop breakeven.
                          3.- The strategie goes short by a cross moving average.
                          4.- It goes long again by a cross moving average. (It never has been flat)
                          5.- It doesnīt take stoploss because itīs blocked for stop breakeven (long), because condition for reset stoploss is to be flat.

                          Here itīs the 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

                          // This namespace holds all strategies and is required. Do not change it.
                          namespace NinjaTrader.Strategy
                          {
                          /// <summary>
                          /// Seguidor de tendencias del bund con filtros
                          /// </summary>
                          [Description("Seguidor de tendencias del bund con filtros")]
                          public class CopiadelTrendBund : Strategy
                          {
                          #region Variables
                          // Wizard generated variables
                          private int cortaEntradaLargo = 7; // Default setting for CortaEntradaLargo
                          private int stopLoss = 60; // Default setting for StopLoss
                          private int periodoDonchian = 9; // Default setting for PeriodoDonchian
                          private int largaEntradaLargo = 120; // Default setting for LargaEntradaLargo
                          private int valorADX = 20; // Default setting for ValorADX
                          // 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()
                          {
                          Add(WMA(CortaEntradaLargo));
                          Add(WMA(LargaEntradaLargo));
                          Add(ADX(14));
                          Add(DonchianChannel(PeriodoDonchian));

                          CalculateOnBarClose = true;
                          }
                          /// <summary>
                          /// Called on each bar update event (incoming tick)
                          /// </summary>
                          protected override void OnBarUpdate()
                          {
                          // Resets the stop loss to the original value when all positions are closed
                          if (Position.MarketPosition == MarketPosition.Flat)
                          {
                          SetStopLoss("Corto", CalculationMode.Ticks, 60, false);
                          SetStopLoss("Largo", CalculationMode.Ticks, 60, false);
                          }
                          if (Position.MarketPosition == MarketPosition.Long)
                          {
                          if (High[0] > Position.AvgPrice + 110 * TickSize)
                          {
                          SetStopLoss("Largo", CalculationMode.Price, Position.AvgPrice + (12 * TickSize), false);
                          }}

                          if (Position.MarketPosition == MarketPosition.Short)
                          {
                          if (Low[0] < Position.AvgPrice - 110 * TickSize)
                          {
                          SetStopLoss("Corto", CalculationMode.Price, Position.AvgPrice - (12 * TickSize), false);
                          }}

                          // Condition set 1
                          if (CrossAbove(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1)
                          && ADX(14)[0] > ValorADX)
                          {
                          EnterLong(DefaultQuantity, "Largo");
                          }

                          // Condition set 2
                          if (CrossBelow(WMA(CortaEntradaLargo), WMA(LargaEntradaLargo), 1)
                          && ADX(14)[0] > 20)
                          {
                          EnterShort(DefaultQuantity, "Corto");
                          }

                          // Condition set 3
                          if (Position.MarketPosition == MarketPosition.Short
                          && Close[0] > DonchianChannel(PeriodoDonchian).Upper[1]
                          && Position.GetProfitLoss(Close[0], PerformanceUnit.Currency) > 0)
                          {
                          ExitShort("Salida donchian", "Corto");
                          }


                          }

                          #region Properties
                          [Description("")]
                          [GridCategory("Parameters")]
                          public int CortaEntradaLargo
                          {
                          get { return cortaEntradaLargo; }
                          set { cortaEntradaLargo = Math.Max(1, value); }
                          }

                          [Description("")]
                          [GridCategory("Parameters")]
                          public int StopLoss
                          {
                          get { return stopLoss; }
                          set { stopLoss = Math.Max(1, value); }
                          }

                          [Description("")]
                          [GridCategory("Parameters")]
                          public int PeriodoDonchian
                          {
                          get { return periodoDonchian; }
                          set { periodoDonchian = Math.Max(1, value); }
                          }

                          [Description("")]
                          [GridCategory("Parameters")]
                          public int LargaEntradaLargo
                          {
                          get { return largaEntradaLargo; }
                          set { largaEntradaLargo = Math.Max(1, value); }
                          }

                          [Description("")]
                          [GridCategory("Parameters")]
                          public int ValorADX
                          {
                          get { return valorADX; }
                          set { valorADX = Math.Max(1, value); }
                          }
                          #endregion
                          }
                          }

                          Comment


                            #14
                            Hello Mercader,

                            Thank you for your response.

                            Do you wish for reverse conditions to occur? Where you are long and then an EnterShort() is submitted to reverse your position?
                            Or would you prefer to see the Stop Loss close the position?

                            I look forward to your response.

                            Comment


                              #15
                              Originally posted by NinjaTrader_PatrickH View Post
                              Hello Mercader,

                              Thank you for your response.

                              Do you wish for reverse conditions to occur?
                              Yes I do.
                              Where you are long and then an EnterShort() is submitted to reverse your position?
                              Yes but ther is an ADX filter and sometimes it doesnīt occur.

                              Or would you prefer to see the Stop Loss close the position?

                              I look forward to your response.
                              The problem is after to reverse my position for two times, and a change for breakevan, if Iīm long the stoploss doesnīt works because itīs blocked by the previous breakeven.
                              I want the two options are actives, stoploss and close position by cross moving average.

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                              0 responses
                              623 views
                              0 likes
                              Last Post Geovanny Suaza  
                              Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                              0 responses
                              359 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by Mindset, 02-09-2026, 11:44 AM
                              0 responses
                              105 views
                              0 likes
                              Last Post Mindset
                              by Mindset
                               
                              Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                              0 responses
                              562 views
                              1 like
                              Last Post Geovanny Suaza  
                              Started by RFrosty, 01-28-2026, 06:49 PM
                              0 responses
                              567 views
                              1 like
                              Last Post RFrosty
                              by RFrosty
                               
                              Working...
                              X