Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

I need a little help with "Cancel order if pending order is not filled in X bars"

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

    I need a little help with "Cancel order if pending order is not filled in X bars"

    Hi Folks,

    I need your help coding a simple strategy.

    I have zero knowledge about coding, but I was happy to learn that Ninjatrader had a "Strategy Builder" that you can program an strategy with no coding skills.

    So I finally made the following simple strategy

    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 Prueba2 : Strategy
        {
            private BuySellVolume BuySellVolume1;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "Prueba2";
                    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                                    = true;
                    RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelCloseIgnoreRejects;
                    StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade                            = 3;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration    = true;
                    StopLoss                    = 150;
                    TakeProfit                    = 50;
                    Value                    = 20000;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    BuySellVolume1                = BuySellVolume(Close);
                    BuySellVolume1.Plots[0].Brush = Brushes.DarkCyan;
                    BuySellVolume1.Plots[1].Brush = Brushes.Crimson;
                    AddChartIndicator(BuySellVolume1);
                    SetStopLoss("", CalculationMode.Ticks, StopLoss, false);
                    SetProfitTarget("", CalculationMode.Ticks, TakeProfit);
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if ((BuySellVolume1.Buys[0] == Value)
                     && (Open[1] < Open[0]))
                {
                    EnterLongStopMarket(Convert.ToInt32(DefaultQuantity), (High[1] + (6 * TickSize)) , "");
                }
    
                 // Set 2
                if ((BuySellVolume1.Buys[0] == Value)
                     && (Open[1] > Open[0]))
                {
                    EnterShortStopMarket(Convert.ToInt32(DefaultQuantity), (Low[1] + (-6 * TickSize)) , "");
                }
    
            }
    
            #region Properties
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="StopLoss", Order=1, GroupName="Parameters")]
            public int StopLoss
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="TakeProfit", Order=2, GroupName="Parameters")]
            public int TakeProfit
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="Value", Order=3, GroupName="Parameters")]
            public int Value
            { get; set; }
            #endregion
    
        }
    }
    ​
    So far so good, the pending orders are placed exactly where and when I want them to be, but something was not working as desired, as my orders were always canceled each time a new bar is printed.

    I made my reasearch and found that the main problem is that all pending orders (limit and stop) are cancelled by default when a new bar starts, and there is no option in strategy builder to change that behavior without manual coding.

    So, my idea is to cancel the pending orders if they are not filled in X bars.

    Again, I made my reasearch and found the following post from 2009



    It seems someone had the same problem as me, and came out with the solution, but the problem is that I do not have any coding skills, so I really do not understand the procedure of it.

    He said that the following code worked for him;

    Code:
    private IOrder myEntryOrder = null;
    private int barNumberOfOrder = 0;
    
    protected override void OnBarUpdate()
    {
    // Submit an entry order at the low of a bar
    if (myEntryOrder == null)
    {
    myEntryOrder = EnterLongLimit(0, true, 1, Low[0], "Long Entry");
    barNumberOfOrder = CurrentBar;
    }
    
    // If more than 5 bars has elapsed, cancel the entry order
    if (myEntryOrder != null && CurrentBar > barNumberOfOrder + 5)
    CancelOrder(myEntryOrder);
    }​
    I tried to unlock my strategy and implement this to it, but I get errors. It can´t be that easy as I just copied and pasted!

    So I really ask for help if somehow can fix my code in order to make it work.

    On the other hand, I started to be interested with coding, I learnt that Ninjascript is C# based. I need to start from zero, do you have any hints for that?

    Manyt thanks in advance, if you can help me I will be eternally gratefull.

    Regards,


    #2
    Hello Maliboo,

    Thanks for your post.

    I have moved this inquiry to the NinjaTrader 8 Strategy Development section of the Forums since the first section of strategy code your shared is for NinjaTrader 8, not NinjaTrader 7.
    "main problem is that all pending orders (limit and stop) are cancelled by default when a new bar starts"

    That is correct. The Strategy Builder uses the Managed Approach for creating custom Strategies. From the Managed Approach help guide page linked below: "By default, orders submitted via Entry() and Exit() methods automatically cancel at the end of a bar if not re-submitted."

    Managed Approach: https://ninjatrader.com/support/help...d_approach.htm

    To keep an order alive, you would need to unlock the strategy and code the Entry/Exit order methods to use the isLiveUntilCancelled overload. An example of the syntax for this overload could be seen below.

    EnterLongLimit(int barsInProgressIndex, bool isLiveUntilCancelled, int quantity, double limitPrice, string signalName)

    See this reference sample demonstrating keeping orders alive using isLiveUntilCancelled: https://ninjatrader.com/support/help...ders_alive.htm

    A similar approach to the script you shared could be used to cancel an order with the CancelOrder() method. However, it is important to understand how the script works so that you could implement it properly into your strategy.

    The script tracks the entry order as an Order object and saved the CurrentBar to a variable when the entry order is submitted. Then, the script checks that the Order object is not null and the CurrentBar processing is greater than the saved 'barNumberOfOrder' bar number + 5 (bars).

    Note that in NinjaTrader 8, we would use private Order myEntryOrder instead of private IOrder myEntryOrder.

    See the help guide documentation below for more information.

    Order objects: https://ninjatrader.com/support/help.../nt8/order.htm
    CancelOrder(): https://ninjatrader.com/support/help...nt8/cancel.htm
    CurrentBar: https://ninjatrader.com/support/help...sub=currentbar

    And, here is a reference sample demonstrating the use of CancelOrder() in a script: https://ninjatrader.com/support/help...thod_to_ca.htm

    The best way to begin learning NinjaScript is to use the Strategy Builder. With the Strategy Builder, you can set up conditions and variables and then see the generated code in the NinjaScript Editor by clicking the View Code button.

    Here is a link to our publicly available training videos, 'Strategy Builder 301' and 'NinjaScript Editor 401', for you to view at your own convenience.

    Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE&t=13s

    NinjaScript Editor 401 - https://youtu.be/H7aDpWoWUQs?list=PL...We0Nf&index=14

    I am also linking you to the Educational Resources section of the Help Guide to help you get started with NinjaScript:
    https://ninjatrader.com/support/help..._resources.htm

    If you are new to C#, to get a basic foundation for the concepts and syntax used in NinjaScript I would recommend this section of articles in our help guide first:
    https://ninjatrader.com/support/help...g_concepts.htm

    And the MSDN (Microsft Developers Network) C# Language Reference.
    https://ninjatrader.com/support/help...erence_wip.htm

    Please let us know if we may further assist.​
    <span class="name">Brandon H.</span><span class="title">NinjaTrader Customer Service</span><iframe name="sig" id="sigFrame" src="/support/forum/core/clientscript/Signature/signature.php" frameborder="0" border="0" cellspacing="0" style="border-style: none;width: 100%; height: 120px;"></iframe>

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by NullPointStrategies, Today, 05:17 AM
    0 responses
    50 views
    0 likes
    Last Post NullPointStrategies  
    Started by argusthome, 03-08-2026, 10:06 AM
    0 responses
    126 views
    0 likes
    Last Post argusthome  
    Started by NabilKhattabi, 03-06-2026, 11:18 AM
    0 responses
    69 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