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 traderqz, Yesterday, 12:06 AM
    11 responses
    27 views
    0 likes
    Last Post NinjaTrader_Gaby  
    Started by PaulMohn, Today, 03:49 AM
    0 responses
    7 views
    0 likes
    Last Post PaulMohn  
    Started by inanazsocial, Today, 01:15 AM
    1 response
    10 views
    0 likes
    Last Post NinjaTrader_Jason  
    Started by rocketman7, Today, 02:12 AM
    0 responses
    10 views
    0 likes
    Last Post rocketman7  
    Started by dustydbayer, Today, 01:59 AM
    0 responses
    4 views
    0 likes
    Last Post dustydbayer  
    Working...
    X