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

For and while loops

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

    For and while loops

    Hello!
    I have again on issue with which I a struggling since few days without success.
    Here is the code:

    protected override void OnBarUpdate()
    {
    if(CurrentBar < Period) return;
    Int CountsBars = 300;
    Int Period = 15;
    Int shift = CurrentBar - CountSBars;

    while(shift >= 0)
    {
    Counter = shift;
    for(Counter = shift; Counter <= shift+9; Counter++)
    {

    }
    Shift++;
    }
    }

    Whell afet compiling,, I wanted to print the output. After attaching the indicator to the chart, the platform just stopps to work or to move whatever.

    What could be wrong in this code?

    Yesterday, I replaced "Counter" by "Period" annd the output pupped out a mistake that I accessing a bar 15 outside of the range.
    I have also seen that protected override void OnRender(ChartControl chartControl, ChartScale chartScale) doesnot require conditions such as "if(CurrentBar < Period) return;", in the forum I am also seen that on this function OnRender() could lag by one tick.
    Why is it impossible to use the for loop in "void OnBarUpdate()" when Period exceed a certain value? I have realised that when I have:
    for(Counter = 0; Counter <= Period-2; Counter++), I have a result. This time I want to use something+x and not something-x.
    How to fix this problem? Is void OnBarUpdate() the ppropraite place to perform these operations?
    Any help?

    Thanks!

    #2
    Hello Stanfillirenfro,

    , the platform just stopps to work or to move whatever.

    What could be wrong in this code?
    You have a while loop that is not being terminated. If you see the platform has locked up and you are using a while loop its a good guess that would be the cause. while loops are generally not used in NinjaScript as they can lock the thread.

    Yesterday, I replaced "Counter" by "Period" annd the output pupped out a mistake that I accessing a bar 15 outside of the range.
    An out of range error generally happens when you try to access data that is not currently available.

    I have also seen that protected override void OnRender(ChartControl chartControl, ChartScale chartScale) doesnot require conditions such as "if(CurrentBar < Period) return;", in the forum I am also seen that on this function OnRender() could lag by one tick.
    OnRender is used to render the currently visible data. If the chart currently has 3 bars then you could loop over the 3 visible bars and get data for each bar to render something about that bar. OnRender does not use BarsAgo, you are using the visible bars and their indexes. If you have 100 bars on the chart and scroll back in time so only the first 50 bars are visible, OnRender and the FromIndex and ToIndex variables would represent the first 50 bars which are currently visible.

    Why is it impossible to use the for loop in "void OnBarUpdate()" when Period exceed a certain value? I have realised that when I have:
    for(Counter = 0; Counter <= Period-2; Counter++), I have a result. This time I want to use something+x and not something-x.
    How to fix this problem? Is void OnBarUpdate() the ppropraite place to perform these operations?
    Any help?
    Using a for loop in OnBarUpdate would require that you wait for the amount of data you want to loop over to be available. As an example it would not make sense to try and loop over 50 bars when you have only 2 bars of data loaded so you need to wait until at least 50 bars have been processed before being able to loop over 50 bars.

    A for loop would need to wait for the data to be present, you can use conditions like
    Code:
    if(CurrentBar < 50) return;
    to prevent the code after that from being called until 50 bars are present.

    or
    Code:
    if(CurrentBar < Period) return;
    Please let me know if I may be of further assistance.

    JesseNinjaTrader Customer Service

    Comment


      #3
      Many thanks Jesse for your reply.
      You has mentioned that while loop is not generally used in NinjaTrader. Could I have the expected result by just using the "if" condition?
      How to terminate a while loop in this case? Is the lock up of the platform due to the number of the bars?

      I will revert to you again after improving the code.

      Many thanks!

      Comment


        #4
        Hello Stanfillirenfro,

        I am not really certain what you were trying to do in order to provide a better example. If you are going to use a while loop you will need to make sure it exits at some point. You can use the break; keyword to exit a while loop. The reason the lockup happens is that once you enter the while loop you never exit it, the code execution gets stuck there. Your script should never pause or otherwise make the platform wait for a result.

        Please let me know if I may be of further assistance.
        JesseNinjaTrader Customer Service

        Comment


          #5
          Many thanks Jesse for the reply.
          I will try with break keyword and revert to you.

          Thanks again

          Comment


            #6
            Originally posted by NinjaTrader_Jesse View Post
            while loops are generally not used in NinjaScript as they can lock the thread.
            That strikes me as completely baseless.

            That's like saying scalpels are generally not used in surgeries
            because they can cause excessive bleeding.

            Correct code using a while loop correctly should have absolutely
            zero impact on "locking the thread".

            A correctly coded while loop in NinjaScript is always going
            to exit, either naturally via the loop condition or explicitly via
            statements break or return.

            If you meant "incorrectly coded while loops are generally
            not used in NinjaScript as they can lock the thread" -- well,
            LOL ... ok, you got me there ... but that's just an infinite loop
            and is fundamentally a programming bug and needs to be
            corrected. And, yes, of course, an infinite loop would lock
            the thread, just like a scalpel used incorrectly would cause
            excessive bleeding.

            My point is:
            There is nothing inherently unsafe with 'while' loops. Used
            correctly, there is absolutely nothing wrong with them.
            I mean absolutely nothing. Zilch. Nyet. Nada.

            Otherwise, what evidence is there to support your claim?
            Last edited by bltdavid; 05-28-2021, 09:38 PM. Reason: More info, eg, exit is via loop condition or break or return

            Comment


              #7
              C# provides a variety of Iteration statements to facilitate repeated actions for a given set of conditions. You can read an overview about them here: https://docs.microsoft.com/en-us/dot...ion-statements They are for, foreach, while and do. (Each statement has detailed documentation at that URL too.)

              Iteration statements, by nature, repeat the same code until specific exit conditions are met. Exit conditions are part of each statement's syntax. (In the case of foreach, the exit condition is implicit and equals "last enumerable element reached".) One can use the break statement to "prematurely" exit an Iteration statement, i.e. before all iterations have taken place that would be expected with the defined exit conditions.

              Again, by nature, it is possible for Iteration statements to have zero, few, many or "infinite" iterations. The "infinite" variety is generally considered to be an error in programming, since the intent of an iteration is, typically, to move on from the iteration to other processing. There are cases, however, where an infinite iteration may be valid (and potentially appropriate) programming, but this is very rare and should mostly be avoided as a design approach as other better designs are almost always available.

              It is the inadvertent (or unintentional) infinite iterations (commonly called infinite loops) that must be avoided at all costs and are always programming errors, either unintentional in source editing, or by error of design. Both of these can be identified and fixed.

              The foreach and for statements tend to be relatively "safe" ways to avoid infinite loops (although it's probably possible to cause them even with these statements). On the other hand, while and do are prone to infinite loops if one is not very careful.

              To avoid infinite loops in while and do statements, one must ensure all intended exit conditions are explicit and correctly tested. One also needs to consider unintended circumstances that may invalidate normally valid exit conditions. In this latter case, for example, unexpected data may cause a perfectly reasonable and valid exit condition to fail and cause an infinite loop.

              Some good principles of approach for using Iteration statements include:
              • Ensure the conditions for entering the iteration are correct (good data, correct state, etc)
              • Ensure the exit conditions are explicit, achievable and comprehensive
              • Ensure the actions within the iteration do not cause the exit conditions to become unachievable (e.g. if an exit condition is simply an int > value, do not always reset the int to <= that value!)
              • For performance, ensure the actions within the iteration are as minimal as needed to achieve the desired outcome
              • For performance, use premature exits (break), if warranted, to reduce iterations
              Explicit Iteration statements can sometimes be avoided entirely by using other language capabilities. LINQ is often useful in this respect.

              Hope this is helpful.
              Multi-Dimensional Managed Trading
              jeronymite
              NinjaTrader Ecosystem Vendor - Mizpah Software

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by GLFX005, Today, 03:23 AM
              0 responses
              1 view
              0 likes
              Last Post GLFX005
              by GLFX005
               
              Started by XXtrader, Yesterday, 11:30 PM
              2 responses
              11 views
              0 likes
              Last Post XXtrader  
              Started by Waxavi, Today, 02:10 AM
              0 responses
              6 views
              0 likes
              Last Post Waxavi
              by Waxavi
               
              Started by TradeForge, Today, 02:09 AM
              0 responses
              14 views
              0 likes
              Last Post TradeForge  
              Started by Waxavi, Today, 02:00 AM
              0 responses
              3 views
              0 likes
              Last Post Waxavi
              by Waxavi
               
              Working...
              X