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

New market order fill at exact time of previous order stoploss/take profit

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

    New market order fill at exact time of previous order stoploss/take profit

    Hi,
    I have been working on this strategy more and have run into some more roadblocks. The idea of this strategy is that whenever a order is filled and travels back through the stoploss, the long/short position will be closed due to the stop loss, but another limit order will fill its place going the other direction (long or short). Here is the code I have been trying. I have tried changing all the defaults to see if I can get anything to work. Attached also is a screenshot of the chart when I run the script. At the stop loss at 4079.00 I would expect to also see a 'Short' at the exact same price. At the stoploss at 4081.00 I would also expect to see a 'long' at the exact same price. Hopefully this is making sense. I just dont understand why the stoploss/takeprofit cant execute at the exact time the new 'long' or 'short' order executes.
    Thank you so much!


    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class TEST10 : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "TEST10";
    Calculate = Calculate.OnEachTick;
    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;
    KPLa = 1;
    KPLb = 1;
    KPLc = 1;
    Buf = 1;
    }
    else if (State == State.Configure)
    {
    }
    }

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

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if (CrossAbove(Close, KPLb, 1))
    {
    EnterLongStopMarket(0, true, 1, KPLb + Buf, "Long");
    SetStopLoss("Long", CalculationMode.Price, KPLb - Buf, true);
    SetProfitTarget("Long", CalculationMode.Price, KPLc - Buf, true);
    }
    else if (CrossBelow(Close, KPLb, 1))
    {
    EnterShortStopMarket(0, true, 1, KPLb - Buf, "Short");
    SetStopLoss("Short", CalculationMode.Price, KPLb + Buf, true);
    SetProfitTarget("Short", CalculationMode.Price, KPLa + Buf, true);
    }
    }

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

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

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

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

    }
    }

    #2
    Hello todc55,

    Thanks for your post.

    Are you testing your strategy on live data, or Playback with Market replay data, or on historical data in the Strategy analyzer, or historical data on a chart?

    When you run your strategy, please check the "Log" tab of the control center, do you see any errors related to your strategy?

    As a suggestion for better practice, place your set stop loss and set profit target above the entry order. The reason to do that is the set method retains the last value used and is immediately deployed upon an entry fill, so by setting them first you ensure there will be no potential order errors. This change will not change what you are seeing but will be a good practice going forward.
    Paul H.NinjaTrader Customer Service

    Comment


      #3
      Here is some of the Log from when I was running the strategy!

      Comment


        #4
        I was using LiveData off of the Continuum feed CQG demo.

        Comment


          #5
          Hello todc55,

          Thanks for your post.

          It looks like your strategy is based on your entering values KPLa,b, and c when you apply the strategy. These values are likely invalid for the historical portion of the chart and this is likely what is generating most of the errors (because the values are not correct for the historical entries).

          To eliminate errors because of the historical data, you can add above //set 1, these lines:

          if (State != State.Realtime)
          return;
          Paul H.NinjaTrader Customer Service

          Comment


            #6
            Hi Paul,
            So I'm now using historical data because my demo has expired. Here are a couple screenshots of what i am experiencing. Based on the code I should have entered long at 4066. For some reason it didnt. This isn't the only place this is an error im sure. I dont understand why it wouldn't enter right there, but does in other places on the chart at that same price level.
            Thanks for your help! Here is my code!


            #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 FINALMAYbe : Strategy
            {
            protected override void OnStateChange()
            {
            if (State == State.SetDefaults)
            {
            Description = @"Enter the description for your new custom Strategy here.";
            Name = "FINALMAYbe";
            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 = 1;
            // Disable this property for performance gains in Strategy Analyzer optimizations
            // See the Help Guide for additional information
            IsInstantiatedOnEachOptimizationIteration = false;
            KPLa = 1;
            KPLb = 1;
            KPLc = 1;
            KPLd = 1;
            KPLe = 1;
            KPLf = 1;
            KPLg = 1;
            KPLh = 1;
            KPLi = 1;
            KPLj = 1;
            KPLk = 1;
            KPLl = 1;
            KPLm = 1;
            KPLn = 1;
            KPLo = 1;
            KPLp = 1;
            KPLq = 1;
            KPLr = 1;
            KPLs = 1;
            KPLt = 1;
            KPLu = 1;
            KPLv = 1;
            KPLw = 1;
            KPLx = 1;
            KPLy = 1;
            KPLz = 1;
            Buf = 1;
            }
            else if (State == State.Configure)
            {
            }
            }
            protected override void OnBarUpdate()
            {
            if (BarsInProgress != 0)
            return;

            if (CurrentBars[0] < 1)
            return;

            // KPLb


            //Entry Long
            if (CrossAbove(Close, KPLb, 1))
            {
            EnterLongStopMarket(0, true, 1, KPLb + Buf, "Long");

            }
            //Stop Loss
            if (CrossBelow(Close, KPLb - Buf, 1))

            {

            ExitLong("Long");

            }
            //Take Profit
            if (CrossAbove(Close, KPLc - Buf, 1))
            {
            ExitLong("Long");

            }

            //Entry Short
            if (CrossBelow(Close, KPLb, 1))
            {
            EnterShortStopMarket(0, true, 1, KPLb - Buf, "Short");

            }
            //StopLoss
            if (CrossAbove(Close, KPLb + Buf, 1))
            {
            ExitShort("Short");

            }
            //Take Profit
            if (CrossBelow(Close, KPLa + Buf, 1))
            {
            ExitShort("Short");

            }



            //KPLc
            if (CrossAbove(Close, KPLc, 1))
            {
            EnterLongStopMarket(0, true, 1, KPLc + Buf, "Long");

            }
            if (CrossBelow(Close, KPLc - Buf, 1))

            {

            ExitLong("Long");

            }

            if (CrossAbove(Close, KPLd - Buf, 1))
            {
            ExitLong("Long");

            }


            if (CrossBelow(Close, KPLc, 1))
            {
            EnterShortStopMarket(0, true, 1, KPLc - Buf, "Short");

            }

            if (CrossAbove(Close, KPLc + Buf, 1))
            {
            ExitShort("Short");

            }

            if (CrossBelow(Close, KPLb + Buf, 1))
            {
            ExitShort("Short");

            }




            //KPLd

            if (CrossAbove(Close, KPLd, 1))
            {
            EnterLongStopMarket(0, true, 1, KPLd + Buf, "Long");

            }
            if (CrossBelow(Close, KPLd - Buf, 1))

            {

            ExitLong("Long");

            }

            if (CrossAbove(Close, KPLe - Buf, 1))
            {
            ExitLong("Long");

            }


            if (CrossBelow(Close, KPLd, 1))
            {
            EnterShortStopMarket(0, true, 1, KPLd - Buf, "Short");

            }

            if (CrossAbove(Close, KPLd + Buf, 1))
            {
            ExitShort("Short");

            }

            if (CrossBelow(Close, KPLc + Buf, 1))
            {
            ExitShort("Short");

            }



            }

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

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

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

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLd", Order=4, GroupName="Parameters")]
            public double KPLd
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLe", Order=5, GroupName="Parameters")]
            public double KPLe
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLf", Order=6, GroupName="Parameters")]
            public double KPLf
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLg", Order=7, GroupName="Parameters")]
            public double KPLg
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLh", Order=8, GroupName="Parameters")]
            public double KPLh
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLi", Order=9, GroupName="Parameters")]
            public double KPLi
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLj", Order=10, GroupName="Parameters")]
            public double KPLj
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLk", Order=11, GroupName="Parameters")]
            public double KPLk
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLl", Order=12, GroupName="Parameters")]
            public double KPLl
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLm", Order=13, GroupName="Parameters")]
            public double KPLm
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLn", Order=14, GroupName="Parameters")]
            public double KPLn
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLo", Order=15, GroupName="Parameters")]
            public double KPLo
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLp", Order=16, GroupName="Parameters")]
            public double KPLp
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLq", Order=17, GroupName="Parameters")]
            public double KPLq
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLr", Order=18, GroupName="Parameters")]
            public double KPLr
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLs", Order=19, GroupName="Parameters")]
            public double KPLs
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLt", Order=20, GroupName="Parameters")]
            public double KPLt
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLu", Order=21, GroupName="Parameters")]
            public double KPLu
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLv", Order=22, GroupName="Parameters")]
            public double KPLv
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLw", Order=23, GroupName="Parameters")]
            public double KPLw
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLx", Order=24, GroupName="Parameters")]
            public double KPLx
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLy", Order=25, GroupName="Parameters")]
            public double KPLy
            { get; set; }

            [NinjaScriptProperty]
            [Range(1, double.MaxValue)]
            [Display(Name="KPLz", Order=26, GroupName="Parameters")]
            public double KPLz
            { get; set; }

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

            }
            }

            Comment


              #7
              Hello todc55,

              Thanks for your reply.

              What I would suggest is to start debugging your code to see why it is not performing as expected.

              There are a couple of approaches you can take and you may want to use both. Debugging code is part of the creation process.

              Add a drawing object on the chart for each and every entry and exit code block. You can use all different drawing objects and set them at various ticks above or below the price. This can be useful to see what conditions are true and when on the chart they are true. This is often helpful because may see something that you did not realize was true. I put links to various draw objects you can use plus you can color them as you wish making it easier to distinguish.
              Reference:






              Here is a simple example:
              if (CrossAbove(Close, KPLb, 1))
              {
              EnterLongStopMarket(0, true, 1, KPLb + Buf, "Long");
              Draw.Dot(this, "KPLb"+CurrentBar, 0, KPLb+buf, Brushes.Green); // draw a dot at the long stop price level
              }

              The other approach is to use the 'Print" statement where you send the print output to the New>Ninjascript output window. The print statement can be used to show the actual values of the conditions and/or text to indicator the code progression. Here is a simple example
              if (CrossAbove(Close, KPLb, 1))
              {
              EnterLongStopMarket(0, true, 1, KPLb + Buf, "Long");
              Print(Time[0]+" KPLB block, entered long at "+(KPLb+Buf).ToString());
              }


              Here is a link to our other debugging tips: https://ninjatrader.com/support/help...script_cod.htm
              Paul H.NinjaTrader Customer Service

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by fitspressoburnfat, Today, 04:25 AM
              0 responses
              2 views
              0 likes
              Last Post fitspressoburnfat  
              Started by Skifree, Today, 03:41 AM
              1 response
              4 views
              0 likes
              Last Post Skifree
              by Skifree
               
              Started by usazencort, Today, 01:16 AM
              0 responses
              1 view
              0 likes
              Last Post usazencort  
              Started by kaywai, 09-01-2023, 08:44 PM
              5 responses
              603 views
              0 likes
              Last Post NinjaTrader_Jason  
              Started by xiinteractive, 04-09-2024, 08:08 AM
              6 responses
              23 views
              0 likes
              Last Post xiinteractive  
              Working...
              X