Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Possible timespan coding issue

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

    Possible timespan coding issue

    Hello,

    Currently I'm working on developing code that uses 2 timespans.
    1) 8:30a - 9:30a
    2) 9:30a - 1:00p

    Within the first timespan, I'm tracking highest high and lowest low. These numbers are accurately being updated and printed throughout both timespans.
    Within the second timespan, I'm trying to take a trade based on a close above or below either the highest high or lowest low. The trade should stay active until filled.
    The issue I'm having is that with strategy analyzer and playback, no trades are being taken so it must be in my code.

    Hoping to get some eyes on my code to see what might be causing the issue, please.

    Establishing Timespans within OnBarUpdate:

    Code:
    TimeSpan sessionStartTime = new TimeSpan(8, 30, 30);
    TimeSpan sessionEndTime = new TimeSpan(9, 30, 0);
    TimeSpan tradeStartTime = new TimeSpan(9, 31, 0);
    TimeSpan tradeEndTime = new TimeSpan(13, 0, 0);​
    Establishing HighestHigh/LowestLow:

    Code:
    // Wait for the first bar after 8:30 AM
    if (Time[0].TimeOfDay < tradeStartTime)
    return;
    
    // Wait for the second bar to close
    if (CurrentBar < 2)
    return;
    
    // Update the pivotHighestHigh whenever a new highest high is found within the session time
    if (High[0] > pivotHighestHigh)
    {
    pivotHighestHigh = High[0];
    Print("New highest high: " + pivotHighestHigh + " at " + Time[0]);
    }
    
    // Update the pivotHighestHigh whenever a new lowest low is found within the session time
    if (Low[0] < pivotLowestLow)
    {
    pivotLowestLow = Low[0];
    Print("New lowest low: " + pivotLowestLow + " at " + Time[0]);
    }​
    Establishing Long Entry Condition:
    Code:
    // Check if the current time is within the trade time range
    if (Time[0].TimeOfDay >= tradeStartTime && Time[0].TimeOfDay <= tradeEndTime)
    {
    // Check if the current close is greater than pivotHighestHigh
    if (Close[0] > pivotHighestHigh)
    {
    // Calculate the Long Limit order price 20 points below pivotHighestHigh
    double limitPrice = pivotHighestHigh - 20 * TickSize;
    
    // Place the Long Limit order
    EnterLongLimit(0, true, 1, limitPrice, "LongTrade");
    }
    }
    }​
    I'm using SetProfitTarget and SetStopLoss accordingly and I think I'm using the EnterLongLimit string correctly, with "true" being isLiveUntilCancelled. But again, no trades are being taken. Any help would be greatly appreciated.

    Thanks,
    J

    #2
    Hello J,

    Thank you for your post.

    So I may accurately assist you, please answer all of the following questions:
    • What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 8.?.?.?)
    • Do you get any errors on the Log tab of the Control Center when you enable the strategy in playback or attempt a backtest in the Strategy Analyzer? If so, what do the errors report?
    • Are you connected to your data feed provider when running this test in the Strategy Analyzer? If so, who is your data provider?
    • What instrument(s) (and expiry if applicable) have you selected?
    • What Data Series Type have you selected? Example: Tick, Minute, Day
    • What From and To date is selected?
    I look forward to your reply.

    Comment


      #3
      Originally posted by NinjaTrader_Emily View Post
      Hello J,

      Thank you for your post.

      So I may accurately assist you, please answer all of the following questions:
      • What version of NinjaTrader are you using? Please provide the entire version number. This can be found under Help -> About (Example: 8.?.?.?)
        8.1.1.7 64-bit
      • Do you get any errors on the Log tab of the Control Center when you enable the strategy in playback or attempt a backtest in the Strategy Analyzer? If so, what do the errors report?
        I do not receive any errors on the output. When I enable the script on a SIM account, this is the full printout from output:
        Enabling NinjaScript strategy 'IBHighLowSimple/256058866' : On starting a real-time strategy - StartBehavior=WaitUntilFlat EntryHandling=All entries EntriesPerDirection=1 StopTargetHandling=Per entry execution ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=True / triggering 30 seconds before close SetOrderQuantityBy=Strategy ConnectionLossHandling=Keep running DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On bar close IsUnmanaged=False MaxRestarts=4 in 5 minutes
      • Are you connected to your data feed provider when running this test in the Strategy Analyzer? If so, who is your data provider?
        Yes, I am running this using the same data provider I run all other strategies through (those work). My provider is Rithmic, but I have also tried this on Kinetick (End of Day).
      • What instrument(s) (and expiry if applicable) have you selected?
        NQ Sep23. Same as other backtests that work.
      • What Data Series Type have you selected? Example: Tick, Minute, Day
        30 seconds (Price based on Last), same on other backtests that work.
      • What From and To date is selected?
        I've tried multiple settings. 01/2023 - 08/07/23, just 08/07/23-08/07/23, just August, etc. This really is just a coding issue, I believe. I have experience running backtests and analyzer.
      I look forward to your reply.
      Hi Emily,

      Thanks for the response. I've added the answers to your questions above.

      Comment


        #4
        Hello wisdomspoon,

        Enable TraceOrders in State.Configure, and print the limit price, and the current ask just one line above where this is used in the order submission method call.

        Print(string.Format("{0} | limitPrice: {1} < GetCurrentAsk(): {2}", Time[0], limitPrice, GetCurrentAsk()));

        Temporarily comment out all other prints, so can focus on the output of just this one print and the output from TraceOrders.

        Then please attach the output from the output window.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi ChelseaB,

          Nice to hear from you on this. Thanks for your input. I've added that line and commented out all other prints.Unfortunately the only output I'm getting is this:
          PHP Code:
          8/7/2023 1:16:39 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='Long Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:16:39 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:16:39 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='Short Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:16:39 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False&#8203; 
          
          That's with TraceOrders = true; in State.SetDefaults. I've also tried it in State.Configure as you've suggested using: TraceOrder = true; as well as within SetDefaults.

          Again this is the only thing I'm getting:
          PHP Code:
          8/7/2023 1:26:27 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='Long Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:26:27 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Long Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:26:27 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Target FromEntrySignal='Short Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False
          8/7/2023 1:26:27 PM Strategy 'IBHighNinjaForum/-1': Entered internal SetStopTarget() method: Type=Stop FromEntrySignal='Short Entry' Mode=Ticks Value=50 IsSimulatedStop=False IsMarketIfTouched=False&#8203; 
          
          This backtest is from 07/03/23 - 08/07/23.

          I also had tried adding a flag for condition met and tried printing the flag but this was not printing either. I've also tried nesting the double variable outside of the entry conditions but within OnBarUpdate to no avail. Here is the updated code I used, but note that I commented the other prints out as you suggested:

          PHP Code:
          double limitPriceLow = pivotLowestLow + 20 * TickSize;
          double limitPrice = pivotHighestHigh - 20 * TickSize;
          
          // Check if the current time is within the trade time range
          if (Time[0].TimeOfDay >= tradeStartTime && Time[0].TimeOfDay <= tradeEndTime)
          {
          // Check if the initial condition is met (Close[0] > pivotHighestHigh)
          if (!isEntryConditionMet && Close[0] > pivotHighestHigh)
          {
          isEntryConditionMet = true;
          // Print("Initial condition met. Waiting for additional conditions.");
          }
          
          // If the initial condition is met, check the additional conditions
          if (isEntryConditionMet && Close[0] >= pivotHighestHigh)
          {
          // // Check additional conditions:
          // if (Close[0] <= limitPrice)
          // {
          
          Print(string.Format("{0} | limitPrice: {1} < GetCurrentAsk(): {2}", Time[0], limitPrice, GetCurrentAsk()));
          
          // Place the Long Limit order
          EnterLongLimit(0, true, 1, limitPrice, "Long Entry");
          // Print("Long Limit order placed at: " + limitPrice + " at " + Time[0]);
          
          // Reset the flag to wait for the next initial condition
          isEntryConditionMet = false;
          }
          }&#8203; 
          
          Also including my State.Configure just in case I perhaps am using TraceOrders incorrectly.
          PHP Code:
                      else if (State == State.Configure)
                      {
                      SetProfitTarget("Long Entry", CalculationMode.Ticks, longProfitTarget);
                      SetStopLoss("Long Entry", CalculationMode.Ticks, longStopLoss, false);
                      SetProfitTarget("Short Entry", CalculationMode.Ticks, shortProfitTarget);
                      SetStopLoss("Short Entry", CalculationMode.Ticks, shortStopLoss, false);
                      TraceOrders                = true;
                      AddDataSeries(BarsPeriodType.Tick, 1);        
                      } 
          
          Any other suggestions would be helpful. Thank you kindly,
          J
          Last edited by wisdomspoon; 08-08-2023, 09:06 AM.

          Comment


            #6
            Also, I wanted to add this... do you suppose the reason I'm not able to "track" pivotHighestHigh, or pivotLowestLow, has something to do with the timespan? That's how I initially posited the question, is that because I'm tracking it in a timespan, then acting on it in a different timespan, perhaps that's why I'm not getting anything to print or unable to store the value of pivotHighestHigh pivotLowestLow because those occurred in a different timespan. See code from post 1 https://forum.ninjatrader.com/forum/...ue#post1263417 That's the only thing I can think of.. is that because I'm started a new timespan, it can't find the price of the pivots previously stored.

            Comment


              #7
              I have been able to update the code to take trades now. The issue was on the second timespan. By removing this, I was able to get it to work:
              PHP Code:
              // Wait for the first bar after 9:30 AM
              if (Time[0].TimeOfDay < new TimeSpan(9, 31, 0) || Time[0].TimeOfDay > new TimeSpan(13, 30, 0))
              return;&#8203; 
              
              However, the problem I'm having is that the trades are being taken during this time period with this timespan:
              PHP Code:
              // Wait for the first bar after 8:30 AM
              if (Time[0].TimeOfDay < new TimeSpan(8, 31, 0) || Time[0].TimeOfDay > new TimeSpan(9, 30, 0))
              return;&#8203; 
              
              I need to be able to segregate it into another timespan so that the pivotHighestHigh and pivotLowestLow are checked in only the 8:31 to 9:30, but trades are taken after that timespan is complete. How can that be done without adding the first timespan code that is posted above (9:31 - 13:30)?

              Also, Chelsea, thanks for the print read-out.... that's now functioning correctly, sample below:
              PHP Code:
              Short Limit order placed at: 15823 at 7/27/2023 8:33:00 AM
              7/27/2023 8:34:30 AM | limitPriceLow: 15823 < GetCurrentAsk(): 15863
              7/27/2023 8:34:31 AM Strategy 'IBHighNinjav3/256058918': Entered internal SubmitOrderManaged() method at 7/27/2023 8:34:31 AM: BarsInProgress=0 Action=SellShort OrderType=Limit Quantity=1 LimitPrice=15823.00 StopPrice=0 SignalName='Short Entry' FromEntrySignal=''
              Short Limit order placed at: 15823 at 7/27/2023 8:34:30 AM
              7/27/2023 8:41:30 AM | limitPriceLow: 15823 < GetCurrentAsk(): 15886.5
              7/27/2023 8:41:31 AM Strategy 'IBHighNinjav3/256058918': Entered internal SubmitOrderManaged() method at 7/27/2023 8:41:31 AM: BarsInProgress=0 Action=SellShort OrderType=Limit Quantity=1 LimitPrice=15823.00 StopPrice=0 SignalName='Short Entry' FromEntrySignal=''
              Short Limit order placed at: 15823 at 7/27/2023 8:41:30 AM
              7/27/2023 8:49:30 AM | limitPriceLow: 15823 < GetCurrentAsk(): 15888.75
              7/27/2023 8:49:31 AM Strategy 'IBHighNinjav3/256058918': Entered internal SubmitOrderManaged() method at 7/27/2023 8:49:31 AM: BarsInProgress=0 Action=SellShort OrderType=Limit Quantity=1 LimitPrice=15823.00 StopPrice=0 SignalName='Short Entry' FromEntrySignal=''
              Short Limit order placed at: 15823 at 7/27/2023 8:49:30 AM&#8203; 
              

              Comment


                #8
                Hello wisdomspoon,

                Thank you for the update.

                You mentioned you need to check pivotHighestHigh and pivotLowestLow only between 8:31 and 9:30, yet you also want to allow trades after that timespan. Please clarify; are there any restricted times when you do not want any trades placed? If so, what are the times you want to place trades and the times you do not? You would likely need to put your entry logic into its own time filters.

                I look forward to your clarification.

                Comment


                  #9
                  Originally posted by NinjaTrader_Emily View Post
                  Hello wisdomspoon,

                  Thank you for the update.

                  You mentioned you need to check pivotHighestHigh and pivotLowestLow only between 8:31 and 9:30, yet you also want to allow trades after that timespan. Please clarify; are there any restricted times when you do not want any trades placed? If so, what are the times you want to place trades and the times you do not? You would likely need to put your entry logic into its own time filters.

                  I look forward to your clarification.
                  Hi Emily,

                  Please note the initial post. https://forum.ninjatrader.com/forum/...ue#post1263417

                  These are the timespans:
                  Code:
                  TimeSpan sessionStartTime = new TimeSpan(8, 30, 30);
                  TimeSpan sessionEndTime = new TimeSpan(9, 30, 0);
                  TimeSpan tradeStartTime = new TimeSpan(9, 31, 0);
                  TimeSpan tradeEndTime = new TimeSpan(13, 0, 0);​
                  Thanks,
                  J​

                  Comment


                    #10
                    I got it to work, you can close this ticket.
                    Thanks,
                    J

                    Comment

                    Latest Posts

                    Collapse

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