Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Order execution take too long after matching the condition as per the Chart

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

    Order execution take too long after matching the condition as per the Chart

    I am using simple strategy to EnterLong and EnterShort if EMA1 crossover EMA2. In Chart I can see, Orders get executed after 2 Bar of the CrossOver event happen.

    I want to Enter the order as soon as cross over happen.

    Please advice what I am doing wrong.


    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 EquityEdgeCrossoverUnlocked : Strategy
        {
            private int FirstEMA;
            private int SecondEMA;
    
            private EMA EMA1;
            private EMA EMA2;
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "EquityEdgeCrossoverUnlocked";
                    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;
                    EMALength1                    = 5;
                    EMALength2                    = 13;
                    LongTrailStop                    = 320;
                    ShortTrailStop                    = 320;
                    StrategyStartTime                        = DateTime.Parse("04:30", System.Globalization.CultureInfo.InvariantCulture);
                    StrategyEndTime                        = DateTime.Parse("13:45", System.Globalization.CultureInfo.InvariantCulture);
                    FirstEMA                    = 1;
                    SecondEMA                    = 1;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    EMA1                = EMA(Close, Convert.ToInt32(EMALength1));
                    EMA2                = EMA(Close, Convert.ToInt32(EMALength2));
                    EMA1.Plots[0].Brush = Brushes.Green;
                    EMA2.Plots[0].Brush = Brushes.Red;
                    AddChartIndicator(EMA1);
                    AddChartIndicator(EMA2);
                }
            }
    
            protected override void OnBarUpdate()
            {
    //            if (BarsInProgress != 0)
    //                return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if ((CrossBelow(EMA1, EMA2, 1))
                     && (Times[0][0].TimeOfDay < StrategyEndTime.TimeOfDay)
                     && (Times[0][0].TimeOfDay > StrategyStartTime.TimeOfDay))
                {
                    Print(Time[0]  + ": Going Short at Current Ask " + GetCurrentAsk(0));
                    EnterShort(Convert.ToInt32(DefaultQuantity), @"Short");
                }
    
                 // Set 2
                if ((CrossAbove(EMA1, EMA2, 1))
                     && (Times[0][0].TimeOfDay < StrategyEndTime.TimeOfDay)
                     && (Times[0][0].TimeOfDay > StrategyStartTime.TimeOfDay))
                {
                    Print(Time[0] + ": Going Long at Current Ask " + GetCurrentAsk(0));
                    EnterLong(Convert.ToInt32(DefaultQuantity), @"Long");
                }
    
            }
    
            #region Properties
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="EMALength1", Order=1, GroupName="Parameters")]
            public int EMALength1
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="EMALength2", Order=2, GroupName="Parameters")]
            public int EMALength2
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="LongTrailStop", Order=3, GroupName="Parameters")]
            public int LongTrailStop
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="ShortTrailStop", Order=4, GroupName="Parameters")]
            public int ShortTrailStop
            { get; set; }
    
            [NinjaScriptProperty]
            [PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
            [Display(Name="StrategyStartTime", Order=5, GroupName="Parameters")]
            public DateTime StrategyStartTime
            { get; set; }
    
            [NinjaScriptProperty]
            [PropertyEditor("NinjaTrader.Gui.Tools.TimeEditorKey")]
            [Display(Name="StrategyEndTime", Order=6, GroupName="Parameters")]
            public DateTime StrategyEndTime
            { get; set; }
            #endregion
    
        }
    }
    ​
    Attached Files

    #2
    Hello futtrader,

    Thanks for your post.

    Are the orders in the screenshot historical (virtual) orders generated after enabling the strategy? Or are these real-time orders placed while the strategy was running?

    When testing the code you shared on my end I am seeing that the order is being placed the moment the crossover condition occurs.

    See this demonstration video: https://brandonh-ninjatrader.tinytak...M18yMjUzOTA3MA

    Note that when in historical data all prices and actions come from and occur when the bar closes as this is all the information that is known. Because of this, OnBarUpdate will only update 'On bar close' as it does not have the intra-bar information necessary for 'On price change' or 'On each tick' and the script will not have the intra-bar information to accurately fill an order at the exact price and time.

    If you want to see your historical orders placed OnPriceChange or OnEachTick then you would need to add intrabar granularity to your script and enable Tick Replay.

    Tick Replay would be used to have the logic process OnEachTick or OnPriceChange with historical data, but this does not allow for intra-bar order fills. You would need to add a single tick data series and submit orders to that single tick data series for a strategy that uses Tick Replay.

    SampleIntrabarBacktest 'Backtesting NinjaScript Strategies with an intrabar granularity' - https://ninjatrader.com/support/helpGuides/nt8/backtesting_ninjascript_strate.htm

    TickReplay — https://ninjatrader.com/support/help...ick_replay.htm

    Developing for Tick Replay -
    https://ninjatrader.com/support/helpGuides/nt8/developing_for__tick_replay.htm?zoom_highlightsub= developing+for+tick+replay

    Additional information may be found in this NinjaTrader Forum post —
    https://ninjatrader.com/support/forum/forum/ninjatrader-8/strategy-development/100192-comparing-real-time-historical-and-replay-performance?t=102504​​
    <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, Yesterday, 05:17 AM
    0 responses
    55 views
    0 likes
    Last Post NullPointStrategies  
    Started by argusthome, 03-08-2026, 10:06 AM
    0 responses
    132 views
    0 likes
    Last Post argusthome  
    Started by NabilKhattabi, 03-06-2026, 11:18 AM
    0 responses
    73 views
    0 likes
    Last Post NabilKhattabi  
    Started by Deep42, 03-06-2026, 12:28 AM
    0 responses
    45 views
    0 likes
    Last Post Deep42
    by Deep42
     
    Started by TheRealMorford, 03-05-2026, 06:15 PM
    0 responses
    49 views
    0 likes
    Last Post TheRealMorford  
    Working...
    X