Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Auto Breakeven

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

    Auto Breakeven

    Hi,

    I am trying to code an autobreaven stop using SetStopLoss() method but it doesnt work.
    Any idea whats wrong with this code?


    Code:
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description    = NinjaTrader.Custom.Resource.NinjaScriptStrategyDescriptionSampleMACrossOver;
                    Name        = "AAAAAAAATEST";
                    Calculate                       = Calculate.OnBarClose;
                    EntriesPerDirection               = 2;
                    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;
                    IsInstantiatedOnEachOptimizationIteration = false;
    
                }
                else if (State == State.DataLoaded)
                {            
    
                }
                else if (State == State.Configure)
                {        
                        SetProfitTarget("entry1", CalculationMode.Ticks, 10);
                        SetStopLoss("entry1", CalculationMode.Ticks, 10, false);
    
                }
            }
    
    
            protected override void OnBarUpdate()
            {
    
                if (CurrentBar < BarsRequiredToTrade)
                    return;
    
    
                    if (IsFirstTickOfBar && Position.MarketPosition == MarketPosition.Flat)
                    {
                        EnterLongLimit(1,Close[0],"entry1");
                    }    
                    if (Position.MarketPosition == MarketPosition.Long && High[0]>= Position.AveragePrice+5*TickSize)
                    {
                        SetStopLoss("entry1", CalculationMode.Price, Position.AveragePrice,false);
                        Draw.Dot(this, "tag1"+CurrentBar, true, 0, Low[0] - 1*TickSize, Brushes.Red);
                    }
    
            }​

    #2
    Hello cbadr,

    Thanks for your post.

    What exactly do you mean when you state "it doesn't work"? What exactly does not work in the script?

    Does the condition to move the stop loss become true?

    Add prints to the strategy one line above your condition to move the stop that prints out all the logic used for that condition to confirm if your logic is becoming true.

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.
    https://ninjatrader.com/support/foru...121#post791121

    See this reference sample demonstrating modifying the price of stop loss and profit target orders: https://ninjatrader.com/support/help...of_stop_lo.htm

    My colleague Chelsea has created educational examples of strategy builder breakeven and trailing stop in the strategy builder here that you could view:
    https://ninjatrader.com/support/forum/forum/suggestions-and-feedback/suggestions-and-feedback-
    aa/103992-request-breakeven-functions-in-strategy-builder#post806596
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment


      #3
      I've found the solution as shown in the code below, everything works fine:

      Code:
              private double triggerprice;
              private bool breakeven;
      
              protected override void OnStateChange()
              {
                  if (State == State.SetDefaults)
                  {
                      Description                       = @"Modifying the price of stop loss and profit target orders.";
                      Name                           = "Sample Price Modification";
                      Calculate                       = Calculate.OnBarClose;
                      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;
                      StopLossTicks                   = 5;
                      ProfitTargetTicks               = 20;
                      breakeven = false;
                  }
                  if (State == State.Configure)
                   {
                      SetStopLoss(CalculationMode.Ticks, StopLossTicks);
      //                SetProfitTarget(CalculationMode.Ticks, ProfitTargetTicks);
                   }
              }
      
              protected override void OnBarUpdate()
              {
                  if (CurrentBar < BarsRequiredToTrade)
                      return;
      
                  // Resets the stop loss to the original value when all positions are closed
                  if (Position.MarketPosition == MarketPosition.Flat)
                  {
                      SetStopLoss(CalculationMode.Ticks, StopLossTicks);
                      breakeven = false;
                  }
      
                  // 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.AveragePrice + 2*TickSize && breakeven == false)
                      {
                          SetStopLoss(CalculationMode.Price, Position.AveragePrice-5*TickSize);
                          triggerprice = Close[0];
                          breakeven = true;
                      }
                      else if (Close[0] >= triggerprice + 1*TickSize && breakeven == true)
                      {
                          SetStopLoss(CalculationMode.Price, triggerprice - 5*TickSize);
                          triggerprice = Close[0];
                      }
                  }
                  else if (Position.MarketPosition == MarketPosition.Short)
                  {
                      // Once the price is greater than entry price+50 ticks, set stop loss to breakeven
                      if (Close[0] <= Position.AveragePrice - 2*TickSize && breakeven == false)
                      {
                          SetStopLoss(CalculationMode.Price, Position.AveragePrice+5*TickSize);
                          triggerprice = Close[0];
                          breakeven = true;
                      }
                      else if (Close[0] <= triggerprice - 1*TickSize && breakeven == true)
                      {
                          SetStopLoss(CalculationMode.Price, triggerprice + 5*TickSize);
                          triggerprice = Close[0];
                      }
                  }
      
                  // Entry Condition: Increasing price along with RSI oversold condition
                  if (IsFirstTickOfBar && Position.MarketPosition == MarketPosition.Flat && Close[1] > Close[2])
                  {
                      EnterLongLimit(50,Close[1]);
                  }
                  if (IsFirstTickOfBar && Position.MarketPosition == MarketPosition.Flat && Close[1] < Close[2])
                  {
                      EnterShortLimit(50,Close[1]);
                  }
              }​

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by CarlTrading, 03-31-2026, 09:41 PM
      1 response
      47 views
      0 likes
      Last Post NinjaTrader_ChelseaB  
      Started by CarlTrading, 04-01-2026, 02:41 AM
      0 responses
      23 views
      0 likes
      Last Post CarlTrading  
      Started by CaptainJack, 03-31-2026, 11:44 PM
      0 responses
      33 views
      1 like
      Last Post CaptainJack  
      Started by CarlTrading, 03-30-2026, 11:51 AM
      0 responses
      51 views
      0 likes
      Last Post CarlTrading  
      Started by CarlTrading, 03-30-2026, 11:48 AM
      0 responses
      42 views
      0 likes
      Last Post CarlTrading  
      Working...
      X