• If this is your first visit, you will have to register before you can post. To view messages, please scroll below and select the forum that you would like to visits. Questions? Be sure to check out the Forum FAQ.

Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Exit together with a Stop

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

    Exit together with a Stop

    Hello,

    I can't seem to get a strategy to work if it has both a SetStopLoss and ExitLong. If I run Optimization on a strategy with say 200 different parameter sets over 12 years, they nearly all at some point stop taking entry signals, some after a year, some after several years. By adding a SetProfitTarget this greatly improves how many of the parameter sets actually work and take all signals. Even if I set the profit target so it never gets hit, i.e. 90%.

    If you run the strategy below (and attached) with the parameters all set to "1" (Line1a, Line2a & Line2b), on instrument ES from 2005 to 2010, you'll see the strategy abruptly stops entering after 27 July 2007.

    How do I fix this? Thanks

    #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.MyStrategies
    {
    public class StopExitStrategy : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "StopExitStrategy";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = false;
    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;

    Line1b = 1;
    Line2a = 1;
    Line2b = 1;

    }
    else if (State == State.Configure)
    {

    }
    }

    protected override void OnBarUpdate()
    {
    if (CurrentBars[0] < BarsRequiredToTrade)
    return;

    if (Close[0] < Open[Line1b] &&
    Close[Line2a] < Open[Line2b + Line2a] &&

    //(Position.MarketPosition == MarketPosition.Flat) &&
    //(BarsSinceEntryExecution() == -1 || BarsSinceEntryExecution(0, "", 0) >= 0) &&
    (BarsSinceExitExecution() == -1 || BarsSinceExitExecution() >= 0))
    {
    Draw.ArrowUp(this, CurrentBar.ToString(), true, 0, Low[0] - TickSize * 100, Brushes.Blue);
    SetProfitTarget(CalculationMode.Percent, 0.90);
    SetStopLoss("",CalculationMode.Percent, 0.04, false);
    EnterLong(1);
    }

    if (Close[0] > Open[0] &&
    Position.MarketPosition == MarketPosition.Long)
    {
    ExitLong(1);
    }

    }

    #region Properties
    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Line1b", Order = 1, GroupName = "NinjaScriptStrategyParameters")]
    public int Line1b
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Line2a", Order = 1, GroupName = "NinjaScriptStrategyParameters")]
    public int Line2a
    { get; set; }

    [NinjaScriptProperty]
    [Range(1, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name = "Line2b", Order = 1, GroupName = "NinjaScriptStrategyParameters")]
    public int Line2b
    { get; set; }
    #endregion
    }
    }
    Attached Files

    #2
    Thank you for your question. If we review the help guide documentation for SetStopLoss, we see

    Originally posted by http://ninjatrader.com/support/helpGuides/nt8/en-us/setstoploss.htm
    A stop loss order is automatically canceled if the managing position is closed by another strategy generated exit order
    While you will need to review the Log tab of the control center to find the exact reason your strategy disables, it is very likely that an overfill is occurring due to the stop loss order being cancelled while another entry or exit order is taking place.

    To avoid this situation I highly recommend, if you are going to exit your position using ExitLong, using ExitLongStopMarket or ExitLongStopLimit as your stop loss order. This is documented here,

    http://ninjatrader.com/support/helpG...stopmarket.htm

    If IsLiveUntilCancelled is true, and you keep a reference to your returned order object, you can use ChangeOrder to manage this order.

    http://ninjatrader.com/support/helpG...hangeorder.htm

    Please let us know if there are any other ways we can help.
    Jessica P.NinjaTrader Customer Service

    Comment


      #3
      Hi Jessica,

      Thanks. I still can't work this out.

      I want to be able to exit a position when a condition is met, e.g. Close[0] > Open[0], and also have a fixed percent stop. I'm not worried about coding the strategy for live trading just yet (if that makes a difference).

      Please see the code below. What am I doing wrong here? Depending on the time frame/instrument I test this on, I sometimes get the following error. "A Sell stop order placed at '4/05/2010 4:00:00 PM' has been ignored since the stop price is greater than or equal to the close price of the current bar. This is an invalid order and subsequent orders may also be ignored. Please fix your strategy.".

      It seems like ExitLongStopMarket() isn't able to execute on the same bar as the entry. I'm basically using the same code structure from the example in the Support page. I've just added ExitLong() at the bottom.


      private double stopPrice = 0;

      protected override void OnBarUpdate()
      {
      if (CurrentBars[0] < BarsRequiredToTrade)
      return;

      if (Close[0] < Close[1] &&
      Position.MarketPosition == MarketPosition.Flat)
      {
      EnterLong(1);
      stopPrice = Close[0] * 0.99;
      }

      ExitLongStopMarket(stopPrice);

      if (Close[0] > Open[0] &&
      Position.MarketPosition == MarketPosition.Long)
      {
      ExitLong(1);
      }

      }

      Comment


        #4
        After reviewing your code more carefully, I noticed when you did use a SetStopLoss and SetProfitTarget, you didn't have any code setting an initial value during State.Configure. Please see the help guide sample for more information.

        http://ninjatrader.com/support/helpG...ofittarget.htm

        Because the code to create and manage exit orders this way is going to be more complicated, let's first try adding these calls to your State.Configure section and continue to use SetProfitTarget and SetStopLoss, and see if your strategy performs well. If it doesn't, let us know and we will prepare an educational code example where we manage an exit order "by hand"
        Jessica P.NinjaTrader Customer Service

        Comment


          #5
          Normally I put my Stops and Profits in State.Configure. I've tried that, and also tried having Stops and Profits in both places at the same time. None are working. The strategy works when you "turn off" the Stop and Profit and just leave the Exit Long, and it also works when you "turn off" Exit Long and leave the Stop and Profit. Weird thing about the strategy I attached in my first post, where I said to set the parameters to "1" for Line1a, Line2a & Line2b. These parameters seem to work for the strategy now, not sure why. But many other combinations still don't work, for e.g. Line1b = 5, Line2a = 6, Line2b = 3. The strategy still just abruptly stops taking trades. Please let me know where to go from here. Thanks, I appreciate your help.

          Comment


            #6
            We are very happy to be able to help.
            Attached is a code sample that creates and manages a very basic stop loss and profit target order which ride 3 ticks on either side of a 14 period SMA. This code requires understanding OnExecutionUpdate. Code samples we provide are for educational purposes, and are not intended for live trading, and are not guaranteed to accomplish any user goal or to be maintained.


            Please let us know if there are any other ways we can help.
            Attached Files
            Jessica P.NinjaTrader Customer Service

            Comment


              #7
              I've been reading through the code and help guide. It's a little confusing, but before I can try understand it I need to get this strategy to work. When I run the strategy you sent me on the ES from 2005 Daily time frame, it only completes 2 trades, and 1 trade remains open until today. I've been playing around with it, but it doesn't seem to want to work. Isn't the entry signal for this strategy to just go long when there is no position open?

              Comment


                #8
                While this strategy was intended for educational purposes, if you would like to see it in action, you'll need to change

                Code:
                if (CurrentBar < BarsRequiredToTrade)
                to

                Code:
                if (CurrentBar < BarsRequiredToTrade && State >= State.Realtime)
                You will then need to set up this strategy's start behavior to Immediately submit + sync . You won't be able to backtest it this way, so try it in a chart. I recommend trying it on 5 second bars.

                The issue is that this strategy as written falls into a "catch 22" situation with respect to start behavior. Writing to avoid this would make the strategy's logic and the purpose of every line of code less clear to you as a user.
                Last edited by NinjaTrader_JessicaP; 04-13-2017, 03:23 PM.
                Jessica P.NinjaTrader Customer Service

                Comment


                  #9
                  It seems so convoluted for such a simple and common exit strategy. Luckily, I figured out a way to do it easy. I simply replaced ExitLong() with SetStopLoss("", CalculationMode.Price, 100000, false);, because the "Stop" price is $100,000, it triggers to sell at the next open when the Exit conditions are met, just like ExitLong does. Also, I put the other SetStopLoss (%) and SetProfitTarget with EnterLong(). I noticed if you have this Stop/Profit in state.configure it doesn't work, it needs to be with the entry.

                  Comment

                  Latest Posts

                  Collapse

                  Topics Statistics Last Post
                  Started by darkgreen, Today, 03:35 PM
                  0 responses
                  7 views
                  0 likes
                  Last Post darkgreen  
                  Started by GTBrooks, Today, 02:44 PM
                  2 responses
                  14 views
                  0 likes
                  Last Post GTBrooks  
                  Started by GLFX005, Today, 12:22 PM
                  4 responses
                  41 views
                  0 likes
                  Last Post NinjaTrader_Kate  
                  Started by AspenHiker, Today, 08:37 AM
                  1 response
                  13 views
                  0 likes
                  Last Post NinjaTrader_Kate  
                  Started by MartinT, Yesterday, 01:12 PM
                  3 responses
                  17 views
                  0 likes
                  Last Post MartinT
                  by MartinT
                   
                  Working...
                  X