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

Adjusting Stop Loss and/or Profit target with strategy builder?

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

    Adjusting Stop Loss and/or Profit target with strategy builder?

    I am basically brand new to NT and have no experience with coding at all. I used the strategy builder to create a strategy considering my lack of experience/knowledge and the strategy works as expected as far as entries and profit target exits so no problem there. The only issue that I ran in to is that I'd like it to be "semi" automated in the sense that I'd like to adjust profit target as well as stop loss as I see fit based on market conditions. My plan is to monitor the strategy closely I really just want to use it to execute entries for me. I noticed that when I try to drag the stop order or the profit target limit order it just snaps back to the place defined by the strategy. Is there a way to set it up so that I can adjust these orders?

    #2
    Hello spencerp92,

    Yes you can do that but you would need to manually code the strategy so you can manually code the targets. The only way to have targets that get submitted by a strategy and then can be manually changed would be to use live until cancelled orders meaning they stay active after submitted and don't need any additional logic to keep them active.

    The easiest way to do that would be to start with the following sample script: https://ninjatrader.com/support/help...and_onexec.htm

    This shows a few concepts, mainly how to submit targets based on an entry order fill. It also has logic for a breakeven which can be removed if you don't want that.

    You can still use what you made in the builder by clicking View Code and then adding your entry conditions into the sample in place of its existing entry condition. The targets are submitted as live until cancelled so they could be changed after submitted by using the chart trader or any other tool which shows the targets.

    The following code is what controls the entry and is where you would change it to match what you made in the builder, please ensure to keep the signal name MyEntry because that is how the targets know when the entry execution happens.

    Code:
    if (entryOrder == null && Position.MarketPosition == MarketPosition.Flat && CurrentBar > BarsRequiredToTrade)
    {
    /* Enter Long. We will assign the resulting Order object to entryOrder1 in OnOrderUpdate() */
    EnterLong(1, "MyEntry");
    }


    The following is the code for the breakeven, this whole section of code can be removed to remove the breakeven

    Code:
    /* If we have a long position and the current price is 4 ticks in profit, raise the stop-loss order to breakeven.
    We use (7 * (TickSize / 2)) to denote 4 ticks because of potential precision issues with doubles. Under certain
    conditions (4 * TickSize) could end up being 3.9999 instead of 4 if the TickSize was 1. Using our method of determining
    4 ticks helps cope with the precision issue if it does arise. */
    if (Position.MarketPosition == MarketPosition.Long && Close[0] >= Position.AveragePrice + (7 * (TickSize / 2)))
    {
    // Checks to see if our Stop Order has been submitted already
    if (stopOrder != null && stopOrder.StopPrice < Position.AveragePrice)
    {
    // Modifies stop-loss to breakeven
    stopOrder = ExitLongStopMarket(0, true, stopOrder.Quantity, Position.AveragePrice, "MyStop", "MyEntry");
    }
    }
    JesseNinjaTrader Customer Service

    Comment


      #3
      thank you for the help but I must admit I am still so lost as I have never looked at a line of code in my life. the code for my strategy is as shown below. What exactly would I need to remove from here and what exactly would I need to paste from the provided code? I did remove the breakeven section already as I don't want that in the strategy.

      //This namespace holds Strategies in this folder and is required. Do not change it.
      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class EMAstratLongShort : Strategy
      {
      private EMA EMA1;
      private EMA EMA2;
      private EMA EMA3;

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"long and short combined";
      Name = "EMAstratLongShort";
      Calculate = Calculate.OnEachTick;
      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 = 1;
      // Disable this property for performance gains in Strategy Analyzer optimizations
      // See the Help Guide for additional information
      IsInstantiatedOnEachOptimizationIteration = true;
      ProfitTarget = 80;
      StopLoss = 80;
      }
      else if (State == State.Configure)
      {
      }
      else if (State == State.DataLoaded)
      {
      EMA1 = EMA(Close, 8);
      EMA2 = EMA(Close, 50);
      EMA3 = EMA(Close, 200);
      EMA1.Plots[0].Brush = Brushes.Blue;
      EMA2.Plots[0].Brush = Brushes.Indigo;
      EMA3.Plots[0].Brush = Brushes.Aqua;
      AddChartIndicator(EMA1);
      AddChartIndicator(EMA2);
      AddChartIndicator(EMA3);
      SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
      SetStopLoss("", CalculationMode.Ticks, StopLoss, false);
      }
      }

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

      if (CurrentBars[0] < 1)
      return;

      // Set 1
      if ((GetCurrentAsk(0) > EMA1[0])
      && (GetCurrentAsk(0) > EMA2[0])
      && (GetCurrentAsk(0) > EMA3[0])
      && (Times[0][0].TimeOfDay >= new TimeSpan(10, 45, 0))
      && (Times[0][0].TimeOfDay <= new TimeSpan(15, 0, 0)))
      {
      EnterLong(1, "");
      }

      // Set 2
      if ((GetCurrentAsk(0) < EMA1[0])
      && (GetCurrentAsk(0) < EMA2[0])
      && (GetCurrentAsk(0) < EMA3[0])
      && (Times[0][0].TimeOfDay >= new TimeSpan(10, 45, 0))
      && (Times[0][0].TimeOfDay <= new TimeSpan(15, 0, 0)))
      {
      EnterShort(1, "");
      }

      }

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

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

      }
      }​

      Comment


        #4
        Hello spencerp92,

        The sample that I linked shows 1 side of the trade, the long side. The code that you could use from the strategy builder script would be your public properties and also the conditions from set 1. If you wanted to make a long and short strategy you will need to add logic for the short side that is similar to how the long side is built. It would be best to focus on just the long side first so you can see what logic is needed to make your idea work, then you can replicate that for the short side.

        The code you copy over needs to go in the same locations in the script. I have highlighted your code below to show what parts are able to be copied.

        //This namespace holds Strategies in this folder and is required. Do not change it.
        namespace NinjaTrader.NinjaScript.Strategies
        {
        public class EMAstratLongShort : Strategy
        {
        private EMA EMA1;
        private EMA EMA2;
        private EMA EMA3;


        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = @"long and short combined";
        Name = "EMAstratLongShort";
        Calculate = Calculate.OnEachTick;
        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 = 1;
        // Disable this property for performance gains in Strategy Analyzer optimizations
        // See the Help Guide for additional information
        IsInstantiatedOnEachOptimizationIteration = true;
        ProfitTarget = 80;
        StopLoss = 80;

        }
        else if (State == State.Configure)
        {
        }
        else if (State == State.DataLoaded)
        {
        EMA1 = EMA(Close, 8);
        EMA2 = EMA(Close, 50);
        EMA3 = EMA(Close, 200);
        EMA1.Plots[0].Brush = Brushes.Blue;
        EMA2.Plots[0].Brush = Brushes.Indigo;
        EMA3.Plots[0].Brush = Brushes.Aqua;
        AddChartIndicator(EMA1);
        AddChartIndicator(EMA2);
        AddChartIndicator(EMA3);

        SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
        SetStopLoss("", CalculationMode.Ticks, StopLoss, false);
        }
        }

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

        if (CurrentBars[0] < 1)
        return;

        // Set 1
        if ((GetCurrentAsk(0) > EMA1[0])
        && (GetCurrentAsk(0) > EMA2[0])
        && (GetCurrentAsk(0) > EMA3[0])
        && (Times[0][0].TimeOfDay >= new TimeSpan(10, 45, 0))
        && (Times[0][0].TimeOfDay <= new TimeSpan(15, 0, 0)))
        {
        EnterLong(1, "");
        }


        // Set 2
        if ((GetCurrentAsk(0) < EMA1[0])
        && (GetCurrentAsk(0) < EMA2[0])
        && (GetCurrentAsk(0) < EMA3[0])
        && (Times[0][0].TimeOfDay >= new TimeSpan(10, 45, 0))
        && (Times[0][0].TimeOfDay <= new TimeSpan(15, 0, 0)))
        {
        EnterShort(1, "");
        }

        }

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

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


        }
        }​​
        JesseNinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by NinjaTrader_ChelseaB, 03-14-2017, 10:17 AM
        227 responses
        34,318 views
        7 likes
        Last Post rare312
        by rare312
         
        Started by f.saeidi, Today, 12:11 AM
        0 responses
        5 views
        0 likes
        Last Post f.saeidi  
        Started by Graci117, Yesterday, 11:40 PM
        0 responses
        6 views
        0 likes
        Last Post Graci117  
        Started by BIOK.NT, Yesterday, 01:56 PM
        2 responses
        11 views
        0 likes
        Last Post BIOK.NT
        by BIOK.NT
         
        Started by i2ogu3, Yesterday, 11:31 PM
        0 responses
        6 views
        0 likes
        Last Post i2ogu3
        by i2ogu3
         
        Working...
        X