Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Assistance in exiting trades at a specific time

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

    Assistance in exiting trades at a specific time

    Evening.

    In the below code my strategy enters trades within the given window of time while my exit code is not. I'd like my trades to exit at 2pm yet when I Optimize/Backtest a strategy the code will exit at 9am / 9:05am / 10am / 12:01pm / 5pm / 5:31pm....pretty much everything BUT 2pm. Can someone please point out what i'm doing incorrect?



    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class Test : Strategy
    {

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Name = "Test ";
    Calculate = Calculate.OnBarClose;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = false;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.Infinite;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 2;
    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 = true;

    Start_Time = DateTime.Parse("07:00", System.Globalization.CultureInfo.InvariantCulture) ;
    End_Time = DateTime.Parse("12:00", System.Globalization.CultureInfo.InvariantCulture) ;
    Exit_Trades = DateTime.Parse("14:00", System.Globalization.CultureInfo.InvariantCulture) ;

    TradeLong = false;
    TradeShort = false;

    }

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

    }

    protected override void OnBarUpdate()
    {

    if (
    (Time[0].TimeOfDay >= Start_Time.TimeOfDay)
    && (Time[0].TimeOfDay <= End_Time.TimeOfDay)
    )

    {

    // Look for Long Entries
    if ( TradeLong )
    {
    EnterLong(Contract_Qty,@"L");
    }


    // Look for Short Entries
    if ( TradeShort )
    {
    EnterShort(Contract_Qty,@"S");
    }
    }


    //Exit Trades at specific time
    if (
    Time[0].TimeOfDay >= Exit_Trades.TimeOfDay
    )
    {
    if (
    Position.MarketPosition == MarketPosition.Long
    )
    {
    ExitLong(1, "eLong", "L");
    }

    if (
    Position.MarketPosition == MarketPosition.Short
    )
    {
    ExitShort(1, "eShort", "S");
    }
    }



    }​

    #2
    Hello DirtyGoats,

    Thanks for your post.

    I have tested your sample code on an ES 12-22 1-Minute instrument and see the strategy exiting trades at 2:01PM (containing bar data from 2:00PM-2:01PM) as expected.

    See the attached screenshots demonstrating this for both long and short trades. I am also attaching the strategy used to test this.

    If the strategy is not behaving as you expect it to, you would need to add debugging prints to the script to understand exactly how it is processing logic and placing trades.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

    Below is a link to a forum post that demonstrates how to use prints to understand behavior.

    https://ninjatrader.com/support/foru...121#post791121

    Let us know if we may assist further.​
    Attached Files
    <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


      #3
      Thank you for your time, Brandon.

      Taking your provided TestStrategy and running it on a 10min chart I get the following:​



      Click image for larger version

Name:	Screenshot.jpg
Views:	96
Size:	567.7 KB
ID:	1220586

      Comment


        #4
        ...hmmm...wondering if it's because of the Trading Hours I'm using. Both the 1/18/2021 and 2/15/2021 were holidays. I'm thinking that's probably why I'm getting goofy results.

        Comment


          #5
          Hello DirtyGoats,

          Thanks for your note.

          "Both the 1/18/2021 and 2/15/2021 were holidays. I'm thinking that's probably why I'm getting goofy results."

          This could be the case if those days were holidays.

          If you run a backtest on the TestStrategy script attached in post # 2 using the exact same settings seen in the screenshot in post # 2, do you get the same results?

          Note that the instrument is ES 12-22, the start date is 10/10/2022, the end date is 10/22/2022, the data series type is 1-Minute, and the Trading hours are set to use instrument default trading hours.

          I look forward to assisting further.
          <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


            #6
            Yes Brandon I do receive those same results. So I'm guessing it has to do with the Trading Hours I was initially using.

            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
            127 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