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

Adding the last x list entries

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

    Adding the last x list entries

    Hi. I wanna add the last X entries of my list together with X being a changeable property.

    the way i do it atm is to just use an if statement for every X i would like, so

    if(x==1)
    savedListvalue[savedListvalue.Count-1].Value

    if(x==2)
    savedListvalue[savedListvalue.Count-1].Value + savedListvalue[savedListvalue.Count-2].Value

    if(x==3)
    savedListvalue[savedListvalue.Count-1].Value + savedListvalue[savedListvalue.Count-2].Value + savedListvalue[savedListvalue.Count-3].Value


    and so on and so forth. needless to say that this is rather awkward and static and makes the code really blown up pretty fast

    anyone an idea for an more elegant way?

    #2
    Hello,

    Thank you for the question.

    It looks like you are just trying to Add the X number of items in the list together is this correct?

    Are you trying to on each iteration add only the next value or start with the Count-1 value, then add Count-2 to that, then Count-3 to that etc?

    If so you could use a simple loop, depending on what direction of the list you want to iterate you may need to adjust the code:

    Code:
    double accumulatedTotal = 0;
    for(int i = savedListvalue.Count - 1; i >  0; i--) 
    {
        accumulatedTotal += savedListvalue[i].Value;
    }


    This would start at the last index of the list and work its way back through the lists count, you could modify this to only do X items if you wanted too.

    the += would accumulate the value to the variable so if you are simply trying to add X numbers together, this would be an easy way to condense the code.

    I look forward to being of further assistance.
    JesseNinjaTrader Customer Service

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by pechtri, 06-22-2023, 02:31 AM
    9 responses
    122 views
    0 likes
    Last Post NinjaTrader_ChelseaB  
    Started by frankthearm, 04-18-2024, 09:08 AM
    16 responses
    64 views
    0 likes
    Last Post NinjaTrader_Clayton  
    Started by habeebft, Today, 01:18 PM
    1 response
    5 views
    0 likes
    Last Post NinjaTrader_ChelseaB  
    Started by benmarkal, Today, 12:52 PM
    2 responses
    13 views
    0 likes
    Last Post benmarkal  
    Started by f.saeidi, Today, 01:38 PM
    1 response
    7 views
    0 likes
    Last Post NinjaTrader_BrandonH  
    Working...
    X