Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

How to add a stop loss and profit target to a basic script?

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

    How to add a stop loss and profit target to a basic script?

    Hello all,

    I'm playing around with a basic crossover script and when I try to add a stop loss and profit target that can be adjustable in the Strategy settings in NT8 I get errors.

    Anyone willing to insert them for me here? Thanks in advance if you can! Cheers.

    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 LoCroswsoverunlocked : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"From Trade for Opprotunity youtube video Make a Trading Bot in 10 Minutes - NinjaTrader (Beginner)";
    Name = "LoCroswsoverunlocked";
    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;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    FastMA = 10;
    SlowMA = 20;
    }
    else if (State == State.Configure)
    {
    }
    }

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

    // Check if RTH
    bool market_open = ToTime(Time[0]) >= 093000 && ToTime(Time[0]) <= 160000;

    // Moving Average
    bool cross_above = CrossAbove(SMA(FastMA), SMA(SlowMA), 1);
    bool cross_below = CrossBelow(SMA(FastMA), SMA(SlowMA), 1);

    // Enter Positions
    if (market_open)
    {
    if (cross_above)
    {
    EnterLong();
    }
    else if (cross_below)
    {
    EnterShort();
    }
    }

    // Exit Positions
    if (!market_open)
    {
    ExitLong();
    }



    }

    region Properties
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="FastMA", Order=1, GroupName="Parameters")]
    public int FastMA
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(Name="SlowMA", Order=2, GroupName="Parameters")]
    public int SlowMA
    { get; set; }
    #endregion



    }

    }​

    #2
    Hello traderzoso,

    Thank you for your inquiry.

    Can you please share exactly what errors you are getting? Provide a screenshot if possible or share the full error message.

    It's important to identify which specific line of code is causing the error. Comment that line out and all lines below it to confirm the error stops. Uncomment that line to ensure the error returns to properly identify the line is causing the error.


    Please see the Help Guide page on creating user defined input parameters:


    You can create two parameters to have the user input their stop loss and profit target values, then use these in your SetStopLoss() and SetProfitTarget() method values.

    SetStopLoss() - https://ninjatrader.com/support/help...etstoploss.htm
    SetProfitTarget - https://ninjatrader.com/support/help...ofittarget.htm

    Please let us know if we can assist further.

    Comment


      #3
      Thanks for the speedy reply. Ok here is the code with the stop loss and price target added. Then when I try to compile it after adding the stop and price target code here are the error screen shots attached.

      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class LoCroswsover003 : Strategy
      {
      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"From Trade for Opportunity YouTube video Make a Trading Bot in 10 Minutes - NinjaTrader (Beginner)";
      Name = "LoCroswsover003";
      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;
      IsInstantiatedOnEachOptimizationIteration = true;
      FastMA = 9;
      SlowMA = 20;
      StopLoss = 10; // Default value for stop loss, can be adjusted in settings
      ProfitTarget = 10; // Default value for profit target, can be adjusted in settings
      }
      else if (State == State.Configure)
      {
      // Add your additional configuration here
      }
      }

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

      // Check if RTH
      bool market_open = ToTime(Time[0]) >= 093000 && ToTime(Time[0]) <= 160000;

      // Moving Average
      bool cross_above = CrossAbove(SMA(FastMA), SMA(SlowMA), 1);
      bool cross_below = CrossBelow(SMA(FastMA), SMA(SlowMA), 1);

      // Enter Positions
      if (market_open)
      {
      if (cross_above)
      {
      EnterLong();
      SetStopLoss(CalculationMode.Ticks, StopLoss);
      SetProfitTarget(CalculationMode.Ticks, ProfitTarget);
      }
      else if (cross_below)
      {
      EnterShort();
      SetStopLoss(CalculationMode.Ticks, StopLoss);
      SetProfitTarget(CalculationMode.Ticks, ProfitTarget);
      }
      }

      // Exit Positions
      if (!market_open)
      {
      ExitLong();
      }
      }

      region Properties
      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="FastMA", Order=1, GroupName="Parameters")]
      public int FastMA
      { get; set; }

      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="SlowMA", Order=2, GroupName="Parameters")]
      public int SlowMA
      { get; set; }

      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="StopLoss", Order=3, GroupName="Parameters")]
      public int StopLoss
      { get; set; }

      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="ProfitTarget", Order=4, GroupName="Parameters")]
      public int ProfitTarget
      { get; set; }
      #endregion
      }
      }
      ​


      Attached Files

      Comment


        #4
        Here are the remaining errors attached also.
        Attached Files

        Comment


          #5
          Hello,

          Add this using statement back to the script, in the 'using declarations' region:

          using System.ComponentModel.DataAnnotations;

          The CS0101 error indicates there is an error with one of your other strategies, that this script and another script are sharing the same name as defined inside the strategy. Do you have another copy of this exact script in the Editor?

          Comment


            #6
            Hi,

            Yes I do have a few more the same that I modified the names when doing "Save As" so as to not compromise the original script.

            Comment


              #7
              Hello,

              The CS0101 error would indicate that the class name LoCroswsover003 has been used in another file. Likely the LoCroswsoverunlocked003.cs file (the file referenced in the error), the class name does not match the filename.

              To resolve the error, change the class name in this file to LoCroswsoverunlocked003.

              In the future, make sure to use the NinjaScript Editor to create a copy of a file by right-clicking within the code > Save As > provide a new unique name. The Editor will create a new class name with this name in a new file with the same name. For indicators, the Editor will also use this new name for the auto generated code for creating overload methods used to call the indicator. This way you can avoid these types of errors in the future.

              Please let us know if we can assist further.

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by NullPointStrategies, Today, 05:17 AM
              0 responses
              44 views
              0 likes
              Last Post NullPointStrategies  
              Started by argusthome, 03-08-2026, 10:06 AM
              0 responses
              124 views
              0 likes
              Last Post argusthome  
              Started by NabilKhattabi, 03-06-2026, 11:18 AM
              0 responses
              65 views
              0 likes
              Last Post NabilKhattabi  
              Started by Deep42, 03-06-2026, 12:28 AM
              0 responses
              42 views
              0 likes
              Last Post Deep42
              by Deep42
               
              Started by TheRealMorford, 03-05-2026, 06:15 PM
              0 responses
              46 views
              0 likes
              Last Post TheRealMorford  
              Working...
              X