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

Why is exit actions delayed

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

    Why is exit actions delayed

    I'm testing a simple strategy that enters long at close of a green bar and exits either at the high or low.
    When I run it through the strategy analyzer, most trades exit several bars after the exit condition was met.
    I have changed the calculate field to On each tick and On price change with the same result. Please help







    Last edited by josid; 09-11-2017, 10:11 AM.

    #2
    Hello josid,

    Thanks for opening the thread.

    Without the full code, I am only left to speculate on the issue you are encountering. Strategies will follow the logic that they are programmed to, and issues with strategies will have to be debugged to fully understand the issue.

    One note to bear in mind is that the Strategy Analyzer processes historical data and will only use the OHLC values of the data series. If you want further granularity while backtesting, you could add a 1 tick data series or enable Tick Replay so you can use Calculate.OnEachTick with the Analyzer.

    With this in mind, I suggest to use Prints and TraceOrders to monitor the conditions that allow the order submissions to occur so you can properly debug the strategy and draw a picture of what is occurring.

    Here are some resources that you may wish to reference that breakdown the differences between historical data (backtesting) and realtime data (Simulated Data Feed, Market Replay, Live data), how Tick Replay can be used, how you can backtest with intrabar granularity, and how you can debug your strategy.

    Differences in Data (thread with demonstrations) - http://ninjatrader.com/support/forum...d.php?t=102504

    Discrepancies between historical and Realtime - https://ninjatrader.com/support/help...ime_vs_bac.htm

    Developing for Tick Replay - https://ninjatrader.com/support/help...ick_replay.htm

    Backtest with intrabar granularity - http://ninjatrader.com/support/forum...ead.php?t=6652

    Debugging - http://ninjatrader.com/support/forum...ead.php?t=3418

    TraceOrders - http://ninjatrader.com/support/forum...ead.php?t=3627

    Please let me know if I can be of further help.
    JimNinjaTrader Customer Service

    Comment


      #3
      #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 DecisionCandles : Strategy
      {
      private double StopLoss;
      private double TakeProfit;


      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"Enter the description for your new custom Strategy here.";
      Name = "DecisionCandles";
      Calculate = Calculate.OnEachTick;
      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;
      CloseToHigh = 1;
      OpenToClose = 1;
      StopLoss = 1;
      TakeProfit = 1;
      }
      else if (State == State.Configure)
      {
      }
      }

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

      // Set 1
      if ((Close[0] >= (Open[0] + (OpenToClose)) )
      && (High[0] >= (Close[0] + (CloseToHigh)) ))
      {
      EnterLong(Convert.ToInt32(DefaultQuantity), @"decCandle");
      StopLoss = Low[0];
      TakeProfit = High[0];
      Print(@"Entry Price :" + GetCurrentAsk(0).ToString() + @":Stop :" + Low[0].ToString() + @":Target :" + High[0].ToString() + ":" + Times[0][0].TimeOfDay.ToString());
      }
      // Set 2
      if ((Position.Quantity > 0)
      && (GetCurrentBid(0) >= TakeProfit)
      && (TakeProfit != 1))
      {
      ExitLong(Convert.ToInt32(Position.Quantity), @"decCandle", "");
      Print(@"Extiting at tartet: " + TakeProfit.ToString() + "" + Times[0][0].TimeOfDay.ToString() + "" + Times[0][0].ToString());
      }
      // Set 3
      if ((Position.Quantity > 0)
      && (GetCurrentBid(0) <= StopLoss)
      && (StopLoss != 1))
      {
      ExitLong(Convert.ToInt32(Position.Quantity), @"decCandle", "");
      Print(@"Extiting at stop: " + StopLoss.ToString() + "" + Times[0][0].TimeOfDay.ToString() + "" + Times[0][0].ToString());
      }

      }

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

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

      }
      }

      Comment


        #4
        Hi Jim, please find the code below. I will continue to explore the information you posted but pls help take a look. The issue is still present after enabling tick replay.

        Originally posted by NinjaTrader_Jim View Post
        Hello josid,

        Thanks for opening the thread.

        Without the full code, I am only left to speculate on the issue you are encountering. Strategies will follow the logic that they are programmed to, and issues with strategies will have to be debugged to fully understand the issue......
        Please let me know if I can be of further help.

        Comment


          #5
          Hello josid,

          Please test the strategy using Market Replay data in the Playback connection and add prints for the variables used in your if statements to verify the strategy's logic. This will tell you for each bar iteration, the values of the variables used to allow the strategy to take a certain action. If an action is not occurring as expected, the logic will tell the tale.

          For example:

          Code:
          Print("Close: " + Close[0] + " Open: " + Open[0] + " OpenToClose: " + OpenToClose + " High: " + High[0] + " CloseToHigh: " + CloseToHigh);
          // Set 1
          if ((Close[0] >= (Open[0] + (OpenToClose)) )
          && (High[0] >= (Close[0] + (CloseToHigh)) ))
          {
          	...
          This print will tell you on each bar the conditions that allow your entry. Please add statements like this for your other condition sets and view the prints in the Output window to debug the logic.

          Here is a resource for using Market Replay Data that can be useful for reproducing scenarios.

          Market Replay Data - https://ninjatrader.com/support/help...s/set_up12.htm

          If you have any questions on the results, please post a screenshot of the output window here, and I will provide further input.
          JimNinjaTrader Customer Service

          Comment


            #6
            Hey Jim,
            I already have prints in the strategy as shown in the code. I have prints and every entry and exit. The print shows that the variables have the right values but execution is wrong. I will try this out in the playback connection and see how that goes. Thanks

            Entry Price :21001:Stop :20959:Target :21024:21:40:00
            Entry Price :21033:Stop :21020:Target :21041:02:00:00
            Extiting at stop: 2102003:20:005/25/2017 3:20:00 AM
            Entry Price :20935:Stop :20917:Target :20942:15:40:00
            Entry Price :20945:Stop :20934:Target :20952:16:00:00
            Entry Price :21021:Stop :20998:Target :21028:10:00:00
            Entry Price :21001:Stop :20959:Target :21024:21:40:00
            Entry Price :21033:Stop :21020:Target :21041:02:00:00
            Extiting at stop: 2102003:20:005/25/2017 3:20:00 AM

            Comment


              #7
              Hello josid,

              Since the prints are inside the if statements, the prints will tell you values of some variables when a submission has already been allowed. Those prints won't tell you the values of the variables when submissions do not occur and will not provide useful information for understanding why a submission did not occur.

              Additionally, the information printed in the code you provided is not entirely relevant to the logic used to control the submission. For example, GetCurrentAsk(0).ToString() does not hold relevant information for the entry condition and is not the Average Entry Price.

              This is why I suggested to create prints like I have described in my previous post. Please use prints like I have outlined to properly debug the code. I may also suggest to comment out the prints inside the if statements to make the Output Window easier to follow.

              I look forward to being of further assistance.
              Last edited by NinjaTrader_Jim; 09-11-2017, 11:41 AM.
              JimNinjaTrader Customer Service

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by cre8able, Today, 03:20 PM
              0 responses
              5 views
              0 likes
              Last Post cre8able  
              Started by Fran888, 02-16-2024, 10:48 AM
              3 responses
              47 views
              0 likes
              Last Post Sam2515
              by Sam2515
               
              Started by martin70, 03-24-2023, 04:58 AM
              15 responses
              114 views
              0 likes
              Last Post NinjaTrader_Jesse  
              Started by The_Sec, Today, 02:29 PM
              1 response
              7 views
              0 likes
              Last Post NinjaTrader_Jesse  
              Started by jeronymite, 04-12-2024, 04:26 PM
              2 responses
              31 views
              0 likes
              Last Post NinjaTrader_BrandonH  
              Working...
              X