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

break even not executing

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

    break even not executing

    I'm looking to isolate why my break even stop condition is not showing up on my back test results for the below code


    Code:
    #region Using declarations
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Xml.Serialization;
    using NinjaTrader.Cbi;
    using NinjaTrader.Gui;
    using NinjaTrader.Gui.Chart;
    using NinjaTrader.Gui.SuperDom;
    using NinjaTrader.Gui.Tools;
    using NinjaTrader.Data;
    using NinjaTrader.NinjaScript;
    using NinjaTrader.Core.FloatingPoint;
    using NinjaTrader.NinjaScript.Indicators;
    using NinjaTrader.NinjaScript.DrawingTools;
    #endregion
    
    //This namespace holds Strategies in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class ts1 : Strategy
        {
            private SMA SMA1;
            private SMA SMA2;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description = @"sma";
                    Name = "ts1";
                    Calculate = Calculate.OnBarClose;
                    EntriesPerDirection = 1;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = true;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.High;
                    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;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {
                    SMA1 = SMA(Close, 50);
                    SMA2 = SMA(Close, 200);
                    SMA2.Plots[0].Brush = Brushes.DarkRed;
                    SMA1.Plots[0].Brush = Brushes.Goldenrod;
                    AddChartIndicator(SMA1);
                    AddChartIndicator(SMA2);
                    SetProfitTarget(@"sma", CalculationMode.Currency, 2000);
                    SetStopLoss(@"sma", CalculationMode.Currency, 500, false);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                // Set 1
                if ((SMA1[0] > SMA2[0])
                     && (Close[0] > SMA1[0]))
                {
                    EnterLong(Convert.ToInt32(DefaultQuantity), @"sma");
                }
    
                // If we have an open position, check if it's profitable by $1000 or more
                if (Position.MarketPosition == MarketPosition.Long && Position.AveragePrice < Close[0])
                {
                    double profit = (Close[0] - Position.AveragePrice) * TickSize;
                    if (profit >= 500)
                    {
                        // Set stop loss to break even
                        double newStop = Position.AveragePrice;
                        SetStopLoss("sma", CalculationMode.Currency, newStop, false);
                    }
                }
            }
        }
    }
    ​

    #2
    Hello twomeangreens,

    This would be a situation where a Print is needed to find out what is happening with the conditions you made.

    Finding out if both conditions are true would be required to know why the stop is not being updated. you could print the variables being used in the two conditions:

    Code:
    Print(Position.MarketPosition + " " + Position.AveragePrice + " < " + Close[0]);
    Print(iprofit + " >= " + 500);
    JesseNinjaTrader Customer Service

    Comment


      #3
      Thank you Jesse,

      I'm not sure if I'm looking in the right place or not but after added the print code to my strategy I'm seeing the below message in the logs.

      Click image for larger version

Name:	image.png
Views:	85
Size:	17.7 KB
ID:	1248526

      Comment


        #4
        Hello twomeangreens,

        That does not relate to the prints. That is because you have stop target handing set to by strategy position but used a currency based stop order.

        SetStopLoss(@"sma", CalculationMode.Currency, 500, false);
        JesseNinjaTrader Customer Service

        Comment


          #5
          This is the last part of my code and the subsequent output after running a backtest.


          Click image for larger version

Name:	image.png
Views:	90
Size:	110.7 KB
ID:	1248531

          Comment


            #6
            Hello twomeangreens,

            The prints I can see dont have the print for the profit which means that condition hasnt been true. You could add a print ouside that condition to see what the profit actually is

            Code:
            Print(iprofit + " >= " + 500);
            if (profit >= 500)
            {
            JesseNinjaTrader Customer Service

            Comment


              #7
              Thanks for all your help thus far Jesse,

              After adding the above code I'm now seeing small numbers being printed. I suspect this might be the issue but I'm not sure whats causing it

              Click image for larger version

Name:	image.png
Views:	87
Size:	5.4 KB
ID:	1248541

              Comment


                #8
                Hello twomeangreens,

                The way you have your variable set up its multiplying by TickSize, You may want to try the following wich would be a different in price which makes an amount if price.

                Code:
                double profit = (Close[0] - Position.AveragePrice);
                JesseNinjaTrader Customer Service

                Comment


                  #9
                  I added the code as suggested but I'm still not seeing break even executing in the backtest results. Curious if the strategy has an issue with backtests running off of tickets instead of minute bars? Otherwise I'm at a loss for what the issue might be

                  Click image for larger version

Name:	image.png
Views:	90
Size:	173.1 KB
ID:	1248579

                  Comment


                    #10
                    Hello twomeangreens,

                    From the image your output still shows that the value is less than 500 so the condition for breakeven should not be true. You would need to make a condition that becomes true for the code to be called and update the stop loss
                    JesseNinjaTrader Customer Service

                    Comment


                      #11
                      I've altered the code to reflect a 20 point target before the break even should be activated. I'm not seeing the stops being moved from $500 up to break even in the trades although I see the condition set evaluating as true in the output

                      Click image for larger version

Name:	image.png
Views:	75
Size:	123.6 KB
ID:	1249728


                      #region Using declarations
                      using System;
                      using System.Collections.Generic;
                      using System.ComponentModel;
                      using System.ComponentModel.DataAnnotations;
                      using System.Linq;
                      using System.Text;
                      using System.Threading.Tasks;
                      using System.Windows;
                      using System.Windows.Input;
                      using System.Windows.Media;
                      using System.Xml.Serialization;
                      using NinjaTrader.Cbi;
                      using NinjaTrader.Gui;
                      using NinjaTrader.Gui.Chart;
                      using NinjaTrader.Gui.SuperDom;
                      using NinjaTrader.Gui.Tools;
                      using NinjaTrader.Data;
                      using NinjaTrader.NinjaScript;
                      using NinjaTrader.Core.FloatingPoint;
                      using NinjaTrader.NinjaScript.Indicators;
                      using NinjaTrader.NinjaScript.DrawingTools;
                      #endregion

                      //This namespace holds Strategies in this folder and is required. Do not change it.
                      namespace NinjaTrader.NinjaScript.Strategies
                      {
                      public class ts1 : Strategy
                      {
                      private SMA SMA1;
                      private SMA SMA2;

                      protected override void OnStateChange()
                      {
                      if (State == State.SetDefaults)
                      {
                      Description = @"sma";
                      Name = "ts1";
                      Calculate = Calculate.OnBarClose;
                      EntriesPerDirection = 1;
                      EntryHandling = EntryHandling.AllEntries;
                      IsExitOnSessionCloseStrategy = true;
                      ExitOnSessionCloseSeconds = 30;
                      IsFillLimitOnTouch = false;
                      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                      OrderFillResolution = OrderFillResolution.High;
                      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;
                      }
                      else if (State == State.Configure)
                      {
                      }
                      else if (State == State.DataLoaded)
                      {
                      SMA1 = SMA(Close, 50);
                      SMA2 = SMA(Close, 200);
                      SMA2.Plots[0].Brush = Brushes.DarkRed;
                      SMA1.Plots[0].Brush = Brushes.Goldenrod;
                      AddChartIndicator(SMA1);
                      AddChartIndicator(SMA2);
                      SetProfitTarget(@"sma", CalculationMode.Currency, 2000);
                      SetStopLoss(@"sma", CalculationMode.Currency, 500, false);
                      }
                      }

                      protected override void OnBarUpdate()
                      {
                      if (BarsInProgress != 0)
                      return;

                      if (CurrentBars[0] < 1)
                      return;

                      // Set 1
                      if ((SMA1[0] > SMA2[0])
                      && (Close[0] > SMA1[0]))
                      {
                      EnterLong(Convert.ToInt32(DefaultQuantity), @"sma");
                      }

                      // If we have an open position, check if it's profitable by $1000 or more
                      if (Position.MarketPosition == MarketPosition.Long && Position.AveragePrice < Close[0])
                      {
                      Print(Position.MarketPosition + " " + Position.AveragePrice + " < " + Close[0]);
                      double profit = (Close[0] - Position.AveragePrice);
                      Print(profit + " >= " + 20);
                      if (profit >= 20)
                      {
                      Print(profit + " >= " + 20);
                      // Set stop loss to break even
                      double newStop = Position.AveragePrice;
                      SetStopLoss("@sma", CalculationMode.Currency, newStop, false);
                      }
                      }
                      }
                      }
                      }

                      Comment


                        #12
                        Hello twomeangreens,

                        The SetStopLoss you have used is set to CalculationMode.Currency but the price you are using is not a currency, that is a price. Position.AveragePrice is the average price between the entries that make the position. If you had 1 quantity that would just be the entry price. To use that with SetStopLoss you would need to use CalculationMode.Price


                        Code:
                        double newStop = Position.AveragePrice;
                        SetStopLoss("@sma", CalculationMode.Price, newStop, false);​


                        JesseNinjaTrader Customer Service

                        Comment

                        Latest Posts

                        Collapse

                        Topics Statistics Last Post
                        Started by rhyminkevin, Today, 04:58 PM
                        0 responses
                        7 views
                        0 likes
                        Last Post rhyminkevin  
                        Started by lightsun47, Today, 03:51 PM
                        0 responses
                        5 views
                        0 likes
                        Last Post lightsun47  
                        Started by 00nevest, Today, 02:27 PM
                        1 response
                        12 views
                        0 likes
                        Last Post 00nevest  
                        Started by futtrader, 04-21-2024, 01:50 AM
                        4 responses
                        48 views
                        0 likes
                        Last Post futtrader  
                        Started by Option Whisperer, Today, 09:55 AM
                        1 response
                        15 views
                        0 likes
                        Last Post bltdavid  
                        Working...
                        X