Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Timespan

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

    Timespan

    Hi there. I am brand new to ninjatrader 8 but with your help had developed some indicators for ninja 7 that I am trying to transfer over. First problem I am having is the timespan code which you guys helped me with in ninja7 and compiles fine there.

    For myTS and myTS1 etc in on barupdate it has "identifier expected" as the code error. I am not seeing anything on the timespan in ninja 8. Also on line 70 (after int minutes 4) it says it says type or namespace definition or end of file expected. Any ideas the correct method? Thanks.



    public class TimerIndicator : Indicator
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Indicator here.";
    Name = "TimerIndicator";
    Calculate = Calculate.OnBarClose;
    IsOverlay = false;
    DisplayInDataBox = true;
    DrawOnPricePanel = true;
    DrawHorizontalGridLines = true;
    DrawVerticalGridLines = true;
    PaintPriceMarkers = true;
    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
    private TimeSpan myTS;
    private TimeSpan myTS1;
    private TimeSpan myTS2;
    private TimeSpan myTS3;
    private TimeSpan myTS4;

    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
    //See Help Guide for additional information.
    IsSuspendedWhileInactive = true;
    }
    else if (State == State.Configure)
    {
    }
    }

    protected override void OnBarUpdate()
    {
    myTS = Time[0] - Time[1];
    myTS1 = Time[1] - Time[2];
    myTS2 = Time[2] - Time[3];
    myTS3 = Time[3] - Time[4];
    myTS4 = Time[4] - Time[3];

    int minutes = ((int)myTS.TotalMinutes) + (myTS.Seconds > 30 ? 1 : 0);
    int minutes1 = ((int)myTS1.TotalMinutes) + (myTS1.Seconds > 30 ? 1 : 0);
    int minutes2 = ((int)myTS2.TotalMinutes) + (myTS2.Seconds > 30 ? 1 : 0);
    int minutes3 = ((int)myTS3.TotalMinutes) + (myTS3.Seconds > 30 ? 1 : 0);
    int minutes4 = ((int)myTS4.TotalMinutes) + (myTS4.Seconds > 30 ? 1 : 0);
    }
    }
    }
    Last edited by djkiwi; 11-06-2020, 11:49 AM.

    #2
    Hello djkiwi,

    Thank you for your post.

    In your code snippet, I see you are initializing TimeSpan variables in State.SetDefault. These variables should be initialized before OnStateChange(). For example;

    private TimeSpan myTS;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    ......
    }
    }

    Then, you would assign the myTS variable a value as well as set up and assign your 'int minutes' variable in OnBarUpdate().

    Please see the example script attached which demonstrates how this would be accomplished. Please note that our example adds a CurrentBar check to ensure that there are enough bars on the chart for the indicator to process.

    Make sure you have enough bars - https://ninjatrader.com/support/help...oom_highlights ub=enough+bars

    Below I am including a link to a list of the Code Breaking Changes from NinjaTrader 7 to NinjaTrader 8.
    http://ninjatrader.com/support/helpG...ng_changes.htm

    The help guide will be the best way to see how things have changed from NinjaTrader 7 to NinjaTrader 8.

    When first starting to port scripts, I myself would open the NT7 help guide and the NT8 help guide to the same sections so that I could compare.

    The majority of code supported by NinjaTrader is included in the help guides.

    Below is a link to a forum post with helpful information about learning with NinjaScript.
    https://ninjatrader.com/support/foru...040#post786040

    Please 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
      Thanks Brandon. That worked and the links helped quite a bit. Also having an issue with conditions. This worked in NT7 plus my code seems to be the same as the examples used on this NT8 here so not sure what is going on. I am getting the error "invalid expression term" "else" for both of those items. It also is asking for a ; but they all seem in order. Thanks.

      if(showtime&&(minutes<=0.3));
      {
      BarBrush = Brushes.Cyan;
      CandleOutlineBrush = Brushes.Cyan;
      }

      else if (showtime&&minutes>0.3 && minutes<=1);
      {
      BarBrush = Brushes.Lime;
      CandleOutlineBrush = Color.Lime;
      }

      else
      {
      BarBrush = Brushes.Yellow;
      CandleOutlineBrush = Color.Yellow;
      }

      Comment


        #4
        Hello djkiwi,

        Thank you for that information.

        There should not be spaced between the if, else if, else conditions in your code. Also, the semi-colons should be removed at the end of the if condition and else if condition. The code would like something like this.

        if(showtime&&(minutes<=0.3))
        {
        BarBrush = Brushes.Cyan;
        CandleOutlineBrush = Brushes.Cyan;
        }
        else if (showtime&&minutes>0.3 && minutes<=1)
        {
        BarBrush = Brushes.Lime;
        CandleOutlineBrush = Color.Lime;
        }
        else
        {
        BarBrush = Brushes.Yellow;
        CandleOutlineBrush = Color.Yellow;
        }

        After removing the spaces between your conditions and removing the semi-colons mentioned above, do you still see an error message?

        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


          #5
          Thanks Brandon.

          As I continue to delve into this timespan part there still appears to be a couple of issues and would appreciate some guidance. I have some sample code in a bare bones strategy. What I am trying to do is enter based on the timespan (average) of previous bars and and exit based on a future bar timespan. For example I have in Time 1 in line 62 - the entry time of 10 seconds (based on previous bar (s) and time 2 100 seconds for a future bar. So in this case if the previous bar formed in 10 seconds then enter and then exit on a future bar if the timespan of the future bar is reaches say 100 seconds. This is based on first tick of bar rather than bar close.

          So an example is to enter on the 10 second timespan of the previous bar. I have the code in row 103 as int seconds 1=int myTS1.Totalseconds; I am assuming that this references the previous bar as per row 91 myTS1=Time[1]=Time[2]. This does enter the trade but based on less than 10 seconds of the current bar i.e immediately as when the new bar forms it is zero seconds not based on the previous bar as required.

          For the exit I have the code in row 161 which does exit the trade once a following bar has had a duration 100 seconds (as an example). This references total seconds in row 102. I think I am missing something here on how to reference the historical bars.

          Also on this strategy I am getting these errors (below) which stops it working and errors out sometimes. It was initially built from strategy builder so not sure why it would cause problems. I have put in firsttickofbar which ensures only one entry per bar which reduced the issue still happens on the odd occasion. Any ideas that jump out?
          11/13/2020 23:14:24 Order Playback101, Order '8ba1442817664aa3861aad8ea63f80d3' can't be submitted: The OCO ID ‘4d8d3f24021644f2a723b63d02b97b5c’ cannot be reused. Please use a new OCO ID. affected Order: Sell 1 Limit @ 11779
          11/13/2020 23:14:24 Order Playback101, Sell stop or sell stop limit orders can't be placed above the market. affected Order: Sell 1 StopMarket @ 11765.25
          11/13/2020 23:14:24 Default Strategy 'NQRenkoSetup1/215418033' submitted an order that generated the following error 'Order rejected'. Strategy has sent cancel requests, attempted to close the position and terminated itself.
          Thanks in advance


          Attached Files
          Last edited by djkiwi; 11-16-2020, 02:26 AM.

          Comment


            #6
            Hello djkiwi,

            Thank you for your note.

            The OCO ID error message is being caused by your profit target since the stop loss was rejected for not being submitted to a proper level. To resolve this, you should make sure that you are resetting the stop loss to a proper level when flat before the entry order is submitted.

            Please see the SamplePriceModification example in the help guide linked below which demonstrates resetting the stop loss when flat.

            SamplePriceModification - https://ninjatrader.com/support/help...of_stop_lo.htm

            Please see the attached TimeSpanExample script which demonstrates how to measure the time it took a bar to form, and how long it took a previous bar to form. The script also demonstrates resetting the stop loss when in a flat position.

            Also, please see the BarTimes script from our NinjaTrader Ecosystem User App Share page.

            BarTimes - https://ninjatraderecosystem.com/use.../nt8-bartimes/

            Let us know if we may assist further.

            The NinjaTrader Ecosystem website is for educational and informational purposes only and should not be considered a solicitation to buy or sell a futures contract or make any other type of investment decision. The add-ons listed on this website are not to be considered a recommendation and it is the reader's responsibility to evaluate any product, service, or company. NinjaTrader Ecosystem LLC is not responsible for the accuracy or content of any product, service or company linked to on this website.
            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


              #7
              Thanks for doing that Brandon. That solved the orders cancelling themselves. I am still grappling with the timespan issue though. I ran the script and then compared to the output window. I have attached a chart to show things. So in this case the yellow bar is 237 seconds. Once that bar closes the next bar (the cyan) bar should check the last bar. If it is 5 seconds or less (as an example) the entry should trigger. The problem here is the entry is triggering every time. In this case because it is 237 seconds it should not trigger.

              The output window for "seconds" always shows zero every time I think because it is taking temp [0] which is close [0] then myTS minuses close [0] so is always equal zero so will always trigger unless I am missing something.

              Also seconds1 should be the current bar or subsequent bars. So if the current (cyan bar) or any subsequent bar reaches 10 seconds or less (based on each tick) then the entry exits. The seconds1 one seems to have a negative number in the output window and never triggers an exit. My seconds1 would trigger ok. Seconds1 I think should just be seconds elapsed for the current bar as a positive number?

              Also the output window seems to be cluttered up with "Size:12" nonstop. Not seeing a print statement for that or understand why it is doing it.

              I looked at the Bartimes indicator. This seems to do things a little differently as it has these case CustomBSEnumNamespace parts and then switches it. Any other ideas would be appreciated.

              Thanks
              DJ
              Attached Files
              Last edited by djkiwi; 11-16-2020, 08:34 PM.

              Comment


                #8
                Hello djkiwi,

                Thank you for that information.

                If the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true or the order is being ignored for other reasons.

                To understand why the script is behaving as it is, you would need to add prints to your script to determine why you are getting an entry when you are not expecting to. Also, prints need to be used to find out why you are not getting an exit when you are expecting to.

                In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar.

                Also, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

                Below is a link to a forum post that demonstrates using prints to understand behavior.
                https://ninjatrader.com/support/foru...121#post791121

                Please let me know if I 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


                  #9
                  Originally posted by NinjaTrader_BrandonH View Post
                  Hello djkiwi,

                  Thank you for that information.

                  If the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true or the order is being ignored for other reasons.

                  To understand why the script is behaving as it is, you would need to add prints to your script to determine why you are getting an entry when you are not expecting to. Also, prints need to be used to find out why you are not getting an exit when you are expecting to.

                  In the strategy add prints (outside of any conditions) that print the values of every variable used in every condition that places an order along with the time of that bar.

                  Also, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

                  Below is a link to a forum post that demonstrates using prints to understand behavior.
                  https://ninjatrader.com/support/foru...121#post791121

                  Please let me know if I may further assist.
                  Hi Brandon,

                  I have a strategy that I run with time charts and tick charts with different instruments. Apparently I found out out that when I use Timespan with tick charts it doesn't trigger my conditions properly.

                  E.g. the following condition shows true when used with ToTime() on 4000 tick chart
                  if (CrossAbove(Close, ATRTrailingStop4, 1) && (ToTime(Time[0]) >= 063000 && ToTime(Time[0]) < 125700))
                  {
                  <some code>
                  }

                  but if I run the exact same day in playback with TimeSpan on 4000 tick chart the condition never becomes true on 4000 tick chart

                  if (CrossAbove(Close, ATRTrailingStop4, 1)
                  && Times[0][0].TimeOfDay > new TimeSpan(6, 30, 0)
                  && Times[0][0].TimeOfDay < new TimeSpan(12, 57, 0))
                  {
                  <some code>
                  }

                  I am trying to understand what the reason is and what is the difference between the two. TimeSpan with time charts works without any issues and only with tick charts I am running into problems.

                  What am I missing here?

                  Comment


                    #10
                    Originally posted by vpatanka View Post

                    Hi Brandon,

                    I have a strategy that I run with time charts and tick charts with different instruments. Apparently I found out out that when I use Timespan with tick charts it doesn't trigger my conditions properly.

                    E.g. the following condition shows true when used with ToTime() on 4000 tick chart
                    if (CrossAbove(Close, ATRTrailingStop4, 1) && (ToTime(Time[0]) >= 063000 && ToTime(Time[0]) < 125700))
                    {
                    <some code>
                    }

                    but if I run the exact same day in playback with TimeSpan on 4000 tick chart the condition never becomes true on 4000 tick chart

                    if (CrossAbove(Close, ATRTrailingStop4, 1)
                    && Times[0][0].TimeOfDay > new TimeSpan(6, 30, 0)
                    && Times[0][0].TimeOfDay < new TimeSpan(12, 57, 0))
                    {
                    <some code>
                    }

                    I am trying to understand what the reason is and what is the difference between the two. TimeSpan with time charts works without any issues and only with tick charts I am running into problems.

                    What am I missing here?
                    Actually never mind. It looks to be working. It was a bit confusing to see the signals with 4000 tick chart as the trigger for the trade was not on the same day as the entry. I think I am all good. Thank you

                    Comment

                    Latest Posts

                    Collapse

                    Topics Statistics Last Post
                    Started by Geovanny Suaza, 02-11-2026, 06:32 PM
                    0 responses
                    649 views
                    0 likes
                    Last Post Geovanny Suaza  
                    Started by Geovanny Suaza, 02-11-2026, 05:51 PM
                    0 responses
                    370 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by Mindset, 02-09-2026, 11:44 AM
                    0 responses
                    109 views
                    0 likes
                    Last Post Mindset
                    by Mindset
                     
                    Started by Geovanny Suaza, 02-02-2026, 12:30 PM
                    0 responses
                    573 views
                    1 like
                    Last Post Geovanny Suaza  
                    Started by RFrosty, 01-28-2026, 06:49 PM
                    0 responses
                    576 views
                    1 like
                    Last Post RFrosty
                    by RFrosty
                     
                    Working...
                    X