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

Question about where to reset my variables.

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

    Question about where to reset my variables.

    Hello,

    I have a basic strategy I'm trying to test. It will detect a gap in the S&P500 (5 min bars), from the previous close to the current open. If there is a gap up, I sell short the ES. If there's a gap down, I buy the ES. There is some more conditions based on day of the week and time of day. If it's a Monday or Friday, the trade should be entered at 7:02:00AM PST. If it's a Tuesday, Wednesday, or Thursday the trade should be entered at 6:59:57AM PST.

    I'm initializing the gapUP and gapDown variables at the start of the strategy. I'm a little unsure where to reset them back to FALSE. It's not an issue when I test on live data. However when I'm backtesting they need to be set back to FALSE at the end or at the beginning of the trading day. Hopefully that makes sense.

    Thanks!

    See the code below:

    Code:
    // Initialize gap detection flags 
    private bool gapUP = false;
    private bool gapDOWN = false;
    
    
    protected override void OnStateChange()
    {
        // This method is called when the state of the NinjaTrader strategy changes.
        if (State == State.SetDefaults)
        {
            // You can set other default properties here as needed (e.g., Calculate, IncludeCommission, etc.).
        }
        else if (State == State.Configure)
        {
            
            // Add a data series for the MES 03-24 contract with a bar size of 3 seconds. This is useful for high-frequency trading strategies or for strategies that require granular data.
            AddDataSeries("MES 03-24", BarsPeriodType.Second, 3);
            
            // Add a data series for the S&P 500 index with a bar size of 5 minutes. This could be used for comparison, hedging, or as part of the strategy's logic for entering or exiting positions based on broader market movements.
            AddDataSeries("^SP500", BarsPeriodType.Minute, 5);
        }
     
    }
    
    
    protected override void OnBarUpdate()
    {
    
        // Check for the S&P 500 series to perform gap analysis.
        if (BarsInProgress == 2) // This ensures we are working with the S&P 500 series.
        {
            // Ensures there is enough historical data to perform analysis.
            if (CurrentBars[0] < 1 || CurrentBars[2] < 1) return; // Not enough data to analyze.
    
            // Determines if the current bar is the first of a new trading day for gap detection.
            if (Times[2][0].Date != Times[2][1].Date)
            {
                // Capture the necessary price points for gap detection.
                double previousCloseHigh = Highs[2][1];
                double currentOpenLow = Lows[2][0];
                double previousCloseLow = Lows[2][1];
                double currentOpenHigh = Highs[2][0];
                
                
                // Identifies a gap up situation.
                if (currentOpenLow > previousCloseHigh)
                {
    
                    gapUP = true; // Sets the flag for a gap up condition.
                }
                
                
                // Identifies a gap down situation.
                else if (currentOpenHigh < previousCloseLow)
                {
          
                    gapDOWN = true; // Sets the flag for a gap down condition.
                }
                else
                {
                    Print("No significant gap detected at " + Times[2][0].ToString() + ".");
                }
            }
        }
    
        // Proceed with entry conditions for the MES 03-24 series.
        if (BarsInProgress == 1) // Ensures we're evaluating the MES 03-24 series.
        {
            // Capture the current time for this series.
            DateTime now = Times[1][0];
            // Define specific target times for trade entries.
            DateTime targetEntryTime = new DateTime(now.Year, now.Month, now.Day, 6, 59, 57);
            DateTime monFriTargetEntryTime = new DateTime(now.Year, now.Month, now.Day, 7, 02, 00);
    
            // Debugging information for time and day conditions.
            Print("Evaluating conditions - Now: " + now.ToString() + ", Target: " + targetEntryTime.ToString() + ", Mon/Fri: " + monFriTargetEntryTime.ToString() + ", Day: " + now.DayOfWeek.ToString());
    
            // Check for trade entry time on Tuesday, Wednesday, or Thursday - 6:59:57am.
            if (now.TimeOfDay >= targetEntryTime.TimeOfDay && now.DayOfWeek != DayOfWeek.Monday && now.DayOfWeek != DayOfWeek.Friday)
            {
                // Entry based on gap conditions. If GapUP -> Enter Short.
                if (gapUP)
                {
                    Print("Executing Short for gap up on " + now.DayOfWeek.ToString() + " at " + now.TimeOfDay.ToString() + ".");
                    EnterShort(0, 0, "Short entry");
                }
                // Entry based on gap conditions. If GapDown -> Enter Long.
                else if (gapDOWN)
                {
                    Print("Executing Long for gap down on " + now.DayOfWeek.ToString() + " at " + now.TimeOfDay.ToString() + ".");
                    EnterLong(0, 0, "Long entry");
                }
            }
    
            // Check for trade entry time on Monday or Friday - 7:02:00am.
            if (now.TimeOfDay >= monFriTargetEntryTime.TimeOfDay && (now.DayOfWeek == DayOfWeek.Monday || now.DayOfWeek == DayOfWeek.Friday))
            {
                // Entry based on gap conditions. If GapUP -> Enter Short.
                if (gapUP)
                {
                    Print("Executing Short for gap up on " + now.DayOfWeek.ToString() + " at " + now.TimeOfDay.ToString() + " (Mon/Fri condition).");
                    EnterShort(0, 0, "Short entry");
                }
                // Entry based on gap conditions. If GapDown -> Enter Long.
                else if (gapDOWN)
                {
                    Print("Executing Long for gap down on " + now.DayOfWeek.ToString() + " at " + now.TimeOfDay.ToString() + " (Mon/Fri condition).");
                    EnterLong(0, 0, "Long entry");
                }
            }
        }
    }​

    #2
    Hello devatechnologies,

    Thanks for your post.

    You could consider using a SessionIterator to get the start or end of a session, create a condition that checks if the time is equal to the start or end of the session, and set the bool to false when the condition occurs.

    See the help guide documentation below for more information.

    SessionIterator: https://ninjatrader.com/support/help...oniterator.htm
    ActualSessionBegin: https://ninjatrader.com/support/help...ssionbegin.htm
    ActualSessionEnd: https://ninjatrader.com/support/help...sessionend.htm
    Brandon H.NinjaTrader Customer Service

    Comment


      #3
      Aha. Thanks Brandon. I'll look into that. It seems like exactly what I need to use.

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by Karado58, 11-26-2012, 02:57 PM
      8 responses
      14,825 views
      0 likes
      Last Post Option Whisperer  
      Started by Option Whisperer, Today, 09:05 AM
      0 responses
      1 view
      0 likes
      Last Post Option Whisperer  
      Started by cre8able, Yesterday, 01:16 PM
      3 responses
      11 views
      0 likes
      Last Post cre8able  
      Started by Harry, 05-02-2018, 01:54 PM
      10 responses
      3,203 views
      0 likes
      Last Post tharton3  
      Started by ChartTourist, Today, 08:22 AM
      0 responses
      6 views
      0 likes
      Last Post ChartTourist  
      Working...
      X