In this video you will learn how to use lists and loops in Quagensia® N Edition and at the same time learn how to build the Quagensia Strategy named “Best Month to Trade (Uses Parallel Lists)” entirely without code just by clicking choices on a screen. It’s one of many no-code trading strategies that come with Quagensia N Edition.
This is a more advanced video. Before you watch this video you should have already watched the “Create NinjaTrader® Strategies Using Point-&-Click with Quagensia N Edition – Full Tutorial” video. You should have also already watched the “Determine the Best Month to Trade with Quagensia N Edition” video.
Note that although this advanced tutorial on lists and loops was made for Quagensia N Edition it can be followed almost word-for-word in Quagensia T Edition as well.
Video Transcript: How to Create the “Best Month to Trade” Strategy with Lists & Loops in Quagensia N Edition
Hi, I’m Brook from Quagensia,
And in this video you will learn how to use lists and loops in Quagensia N Edition and at the same time learn how to build this Quagensia Strategy named “Best Month to Trade (Uses Parallel Lists)” entirely without code just by clicking choices on a screen. It’s one of many no-code trading strategies you can get free by downloading Quagensia N Edition from the Quagensia website at quagensia.com.
This is a more advanced video. Before you watch this video you should have already watched the 1-hour Introduction to Quagensia N Edition video on our home page at quagensia.com. You should have also already watched the video named “Determine the Best Month to Trade with Quagensia N Edition” which is available on the Strategy Home Page of the Quagensia Strategy which you can reach by opening Quagensia N Edition, then opening the “Best Month to Trade (Uses Parallel Lists)” strategy by clicking on it here, clicking “View Strategy”, and opening the Strategy Home Page in your default browser by clicking on the link here.
Let’s get started.
We just opened the “Best Month to Trade (Uses Parallel Lists)” Quagensia Strategy by clicking here and choosing “View Strategy”. This is a template strategy that is built into Quagensia N Edition so it cannot be edited directly. In this video we will be adding logic to this strategy, so we first need to create a copy of it that can be edited. You can do this by selecting “Create New Strategy From a Copy of This Strategy” here.
After creating a copy of the strategy so you can edit it, you need to save it to the “My Algos” folder on your computer before continuing. Change its name here then click the “Save” button. Notice that the “Save As” window already defaults to the “My Algos” folder, so all you need to do is click “Save”. Now it shows up in the “My Algos” folder from within Quagensia and can be edited.
To generate a report like this, the numbers must be stored somewhere during the backtest. These numbers are stored in the three lists you can see in the Internal Variables section when you expand it by clicking here.
Lists are collections of values of a certain data type, such as a collection of numbers or dates. They can hold millions of items if needed, but for this report, each of the three lists only needs to hold one numeric value for each of the 12 months of the year. Also, while the lists in this Quagensia Strategy hold decimal numbers and whole numbers, Quagensia N Edition supports lists of values of many other data types, including Booleans, text, dates and times, advanced numeric types, items selected from a list of choices, and colors.
You can create a list the same way you create any other internal variable. Scroll down to the end of the Internal Variables section, enter a name for your list, choose “List” for the data type of the variable, and select a data type for the individual list items from this drop-down list. Press the “Add Variable” button and you have now created a list with no items in it yet.
Before we move on, note that there are other Quagensia N Edition data types that hold collections of values. The collections of values that allow you to add, edit, and delete items like lists do include single-dimensional arrays, multi-dimensional arrays, and editable time series. The collections of values whose items are available to the calculations in your Quagensia Strategies but whose items cannot be modified are indicator time series and secondary price bars.
Let’s scroll up and look more carefully at the three lists used by this Quagensia Strategy.
The first list holds 12 items, where each item is the cumulative sum of the percentage price changes from the open to the close for each of the price bars in the backtest. These 12 values will be used to calculate the arithmetic mean for each of the 12 months.
The second list also holds 12 items, where each item is the cumulative product of 1 plus the percentage price changes from the open to the close for each of the price bars in the backtest. These 12 values will be used to calculate the geometric mean for each of the 12 months.
The third and final list also holds 12 items, where each item is the count of the bars that were included in the report’s results. These 12 values are used in the calculations for both the arithmetic and geometric means.
These three lists work together as “parallel lists” to hold the equivalent of an in-memory data table of report data. “Parallel lists” are lists that work together as columns of data, where the items at the same numeric index of all the lists represent a row of data. In this report, each of the three lists have 12 items that the report uses, one for each of the months of the year. The items at the same numeric index in all three lists represent the same month. For example, the items at the numeric index 5 in all three lists together represent a row of data for the 5th month of the year, May.
At this point in the strategy’s logic, our three lists have no items in them. At the very beginning of the backtest, before the calculations are done on the first price bar of the chart, we need to resize the lists to have one item for each month of the year. The lists are resized in the second contracted “Conditional Trading Logic (If Block)” in the “When Bar Updates” section. You can expand this contracted block of logic by clicking on it and selecting “Show This Item’s Details”.
The three lists are resized using the “Resize List” function. The reason why the “New List Size” input parameters are all set to 13 instead of 12 is explained in the yellow “comment” here. Namely, setting the list sizes to 13 instead of 12 for the 12 months of the year simplifies the logic a little, because the first item in a list has an index of 0, which doesn’t correspond with a month, whereas the second through the thirteenth items in a list have indices between 1 and 12, which correspond with the 12 months of the year. We could have, instead, created lists with 12 items instead of 13, but then we would need to subtract 1 from all the month numbers to get the correct 0-based list index and then add 1 to the 0-based list indices to get the correct month numbers.
To add the “Resize List” function to the logic of a strategy, click anywhere that allows you to add an action, such as clicking the “Add Trading Logic” link here, or clicking another action and choosing “Add Item Before Me” or “Add Item After Me”, then navigate to the context menu subfolder shown in the Context-Sensitive Help panel when you roll your mouse pointer over one of the “Resize List” function calls, or if the Context-Sensitive Help panel is not visible, then navigate to the context menu subfolder that is displayed in the tooltip when you roll your mouse pointer over the gear icon to the right of one of the “Resize List” function calls. The tooltip said to navigate to “More Actions >> Lists, Arrays, and Time Series >> Lists >> Change List Size” and there it is.
Select it to make it appear at your desired location and set the “List” parameter to the List you created in the Internal Variables section.
Then in the “New List Size” input parameter, enter a list size. It can be a simple number like 12, an input parameter, an internal variable, the result of another Quagensia Function that returns a whole number, or very complex expression made up of many expressions nested together, with each expression’s input parameters being filled with other expressions whose input parameters are made up of even more nested expressions, and where each expression can be a complex arithmetic combination of many terms, like the most complicated mathematical formulas that you’ve ever seen in any advanced math textbook.
Then choose a value to initialize new values to and you are done.
Many other Quagensia Action Functions and many Quagensia Expression Functions work with lists.
To learn more about the Quagensia Action Functions that work with lists and can go wherever actions are allowed, click anywhere an action is allowed, navigate to the context menu’s subfolder “More Actions >> Lists, Arrays, and Time Series >> Lists”, and roll your mouse pointer over the other subfolders to check out all your options as I am doing here.
To learn more about the Quagensia Expression Functions that work with lists and can go wherever an expression of a given data type is allowed, click any location in the “When Bar Updates” section where the data type is allowed, navigate to the context menu’s subfolder “More Expressions >> Lists, Arrays, and Time Series >> Lists”, and roll your mouse pointer over the other subfolders to check out all your options as I am doing here.
Since we’re done with this block of logic, let’s collapse it by clicking on its gear icon and selecting “Hide This Item’s Details”.
Scrolling down further, we get to the set of conditions we customized in the video that this one is based on, titled “Determine the Best Month to Trade with Quagensia N Edition”. This set of conditions determines if a given price bar’s percentage change from open to close is included in the report.
Let’s see what calculations occur and how they are saved in the three lists for price bars meeting the filter criteria that we customized in the previous video by expanding this block of logic.
Here we set a whole number variable called “Month of Year (Temporary Variable)” with the numeric month of the year of the time of the current price bar using the Quagensia Function named “Months Part”. Let’s re-create this same action beneath it to show you how. First, click this action and navigate to the context menu’s subfolder “Add Item After Me >> Set a Variable” to see all the internal variables we can set here, then select “Month of Year (Temporary Variable)”.
Now let’s set this variable to the same calculation as in the action above. To see where the Quagensia Function named “Months Part” is located, let’s use search instead of relying on the tooltip of the “Months Part” function call above. Click “(Not Set)”, roll your mouse pointer over the “Set Item” context menu subfolder, enter “month” in the search text box, and press the Enter key to see the Quagensia Functions and internal variables that have the word “Month” in them and that are allowed at this location. Click the “Months Part” search result and select “Add this function to your algo at the location you specified.” and there it is. Now, let’s finish by setting this function’s “Date and Time” input parameter to the time of the current bar by clicking the gear icon here and navigating to the context menu subfolder “Replace Item >> Price Data” and select “Time”.
The internal variable we just set now contains a number from 1 to 12 representing the numeric month of the year for the current bar. This number is also the numeric index of the item in each of our three parallel lists that holds the cumulative totals for that month of the year which now needs to be changed to account for the percentage price change of the current bar.
The next action sets the item in the list named “Counts of Bars By Month of Year” that is located at the index to which we just set the “Month of Year (Temporary Variable)”. So, if the current bar’s end time is in March, the item in this list at index 3 will be set. Looking on the right side of the action that sets this variable, we see that the item at this index is set to the value it currently is set to plus 1, which makes sense because this list holds the counts of the bars that will be included in this report.
To show you how to create an action like this one that sets an item at a location in a list by its numeric index, let’s re-create this same action beneath it to show you how. First, click this action and navigate to the context menu’s subfolder “Add Item After Me >> Set a Variable” to see all the internal variables we can set here, then select “Counts of Bars By Month of Year (An Item in the List)”. To re-create the action above, we now need to replace this textbox with the internal variable named “Month of Year (Temporary Variable)” by either copying the usage of this internal variable from the action above and pasting it at this location or by clicking the gear icon to the right of the textbox, navigating to the context menu’s subfolder “Replace Item >> Input Parameters and Internal Variables >> Internal Variables” and choosing the internal variable named “Month of Year (Temporary Variable)”.
Since the right side of this action is just the left side plus 1, let’s copy and paste the left side onto the right side. Now, let’s add 1 to the right side by clicking the expression we just pasted and choosing “This Number + [A New Number]”, then enter “1” in the textbox that appears.
To make our right side match the right side of the action above it, all we have left to do is to make the arithmetic expression display vertically instead of horizontally by clicking on the gear icon that represents the entire arithmetic expression not here but here and selecting “Align These Items Vertically instead of Horizontally”. While aligning the arithmetic expression vertically didn’t save a lot of horizontal space in this instance, it can save a lot of horizontal space when used with more complex arithmetic expressions like this one.
Now that we have re-created two actions that set variables and used an arithmetic expression, you now have the knowledge to re-create the three remaining actions in this section, because all they do is set variables to the results of arithmetic expressions.
Since we’re done with this block of logic, let’s collapse it by clicking on its gear icon and selecting “Hide This Item’s Details”.
At this point, the only thing left is to do some work on the last bar of the backtest that finishes calculating the arithmetic and geometric means for each month of the year and print out the report to the NinjaScript® Output Window. You can see how to do this by expanding the final contracted logic block in the strategy by clicking it and selecting “Show This Item’s Details”.
This condition ensures that the logic below only executes once at the end of the backtest.
Let’s scroll past the actions that set the text variables that end up being the title and subtitle rows and column headers of the report since they are simple “text concatenations”, meaning that pieces of text such as text in textboxes and text variables are appended onto the end or prepended onto the beginning of each other to build a larger piece of text. You already know how to roll your mouse pointer over Quagensia Function calls to find their location in the context menu and you also already know how to use search to find the functions that way as well so you can explore this section on your own.
Instead, we will focus on this block of logic that says “While the following condition is true… Continue to do the following…” because it is an example of a loop that does a set of actions some number of times until the set of conditions here is no longer true.
When the execution of this strategy’s logic gets here, an internal variable called “Counter (Temporary Variable)” is set to 1.
Next, when the execution of this strategy’s logic reaches this loop for the first time, it checks that the internal variable “Counter (Temporary Variable)” is less than 13. The first time this condition is checked, this variable’s value is 1 because it was just set to 1 in the action above.
Since this condition is true the first time the loop is reached, the actions inside of the loop are executed.
First, the final values of the arithmetic and geometric means are calculated here. As you can see, all three of our parallel lists are used together to do these calculations. Since the counter variable has a value of 1 the first time the loop is entered and since we are using that counter variable to determine the numeric indices of the locations in the three lists, the first time this loop is entered the calculations will be for month 1 of the year, January.
Once the means for January are calculated, they are printed to the NinjaScript® Output window by this “Print To Output Window” action. Here you have the month number, the arithmetic mean, the geometric mean, and the number of bars that went into the calculation for the month of January, delimited by semicolons.
The final thing that happens inside this loop is that the value of the counter variable is increased by 1. If this is the first time that this loop was entered, the counter variable would therefore have its value increased from 1 to 2, where 2 represents the month of February. Now that the end of the loop was reached the first time and the counter variable is set to 2, this execution of this strategy’s logic goes back up to the top of the loop and the condition is checked again. Since 2 is less than 13, the condition evaluates to true and the loop is entered a second time. All the actions inside the loop occur a second time, but this time with the counter variable set to 2, so all the calculations will be for February. At the end of the loop, the counter variable is set to 3, and this keeps going on until the last execution of the loop, where the counter variable is 12, the loop is entered and its actions are executed for the month of December, and the counter variable is set to 13. The execution of this strategy’s logic moves back up to the loop condition again, but this time the condition evaluates to false, because 13 is not less than 13. Since the loop condition was false, the execution of the strategy’s logic does not enter the loop again, and instead moves to the first action after the loop. In our example, there are no more actions after the loop, so no more work is done in the “When Bar Updates” event for this bar update event. By this point, the report’s results are printed to the NinjaScript® Output window and the backtest is done.
Before we end this video, there are a few more things you should know about loops.
Quagensia N Edition has three kinds of loops, while loops like this one, do while loops, and for loops.
You can add these to your strategy’s logic by clicking anywhere an action can go, including inside of other loops as I am demonstrating here, then navigating to the context menu’s subfolder “More Actions >> Loops”, and selecting a loop. Let’s choose the “While Loop” option not just because it is what was used in this strategy, but also because “While Loops” are the easiest to use and understand and can be made to work like the other two types of loops when needed.
Let’s build a simple while loop right here.
Let’s re-create some aspects of the while loop relied on by this report. Let’s first create a counter variable that is only used by this loop by scrolling up to the internal variables section, naming the variable “My Counter Variable”, changing the data type to “Whole Number”, and pressing the “Add Variable” button. Now, scroll back down to where we were, and let’s set that counter variable to an initial value of 100.
Let’s add a loop condition that requires that the counter variable be less than 110.
If we ran a backtest of this strategy now, NinjaTrader® 8 would freeze up because the execution of our strategy’s logic would enter this loop, go back up to the loop condition which will always be true no matter how many times the loop executes, and reenter the loop over and over again. This is because without adding any other logic, the variable named “My Counter Variable” will always be 100 at the point this condition is reached, and 100 will always be less than 110.
Let’s make sure we don’t end up in an “infinite loop” situation in a backtest by adding 1 to the counter variable inside the loop. Now, the loop will execute 10 times, until the value of the counter variable reaches 110, at which point the loop condition will be false and the execution of the strategy’s logic will jump to the action directly below the loop, which is here.
Let’s make this loop print the value of the counter variable to the NinjaScript® Output window by clicking on the action we just created and navigating to the context menu subfolder “Add Item Before Me >> Output (Alerts and Logging) >> Print To Log / Output Window” and selecting “Print To Output Window”.
In the “Message” textbox, we will enter the text “My Counter Variable’s Value Is:”. Then we will append a string to the end of this text by clicking on the gear icon to the right of the textbox and selecting “This Piece of Text + [A New Piece of Text]”. Replace this empty textbox with the value of the variable named “My Counter Variable” by clicking on the gear icon to its right, navigating to the context menu subfolder “Replace Item >> Input Parameters and Internal Variables >> Internal Variables” and selecting “My Counter Variable”. Since we created this loop inside of the report’s main loop that executes once for each month of the year, if we were to backtest this strategy in NinjaTrader® 8 we would see 10 lines that display text that says “My Counter Variable’s Value Is:” followed by a number between 100 and 109 followed by the report results for January’s report results followed by 10 more lines showing the counter variable’s value from 100 to 109 again, followed by February’s report results, and this would continue through December.
In addition to three kinds of loops, Quagensia N Edition also has two powerful loop-related actions that are only allowed inside of loops and that are therefore only visible in a context menu if you click on a location that is inside of a loop where an action is allowed.
The first one is called “Exit Out of This Loop”. You can add it to your strategy’s logic by clicking on the “Print To Output Window” action, navigating to the context menu subfolder “Add Item After Me >> More Actions >> Loops” and choosing “Exit Out of This Loop”.
This action causes execution of the strategy’s logic to exit out of this loop, without executing the rest of the logic in this loop that is beneath this action. If this line of code is currently located inside of multiple nested loops, execution of the code will exit out of the innermost loop only.
Currently, this “Exit Out of This Loop” action will cause our loop to only ever execute once. Let’s put it inside of a Conditional Trading Logic (If Block) so that it will only break out of our loop when the counter variable hits 105. Now, the “Print To Output Window” action will print the value of the counter variable up until it is 105, at which point this condition will be true, causing the “Exit Out of This Loop” action to execute, which causes the execution of our strategy to jump outside the loop, to the action directly beneath it, which is here.
The second powerful loop-related action in Quagensia N Edition is called “Continue Back to the Loop Condition of This Loop”. You can add it to your strategy’s logic by clicking on the “Print To Output Window” action, navigating to the context menu subfolder “Add Item Before Me >> More Actions >> Loops” and choosing “Continue Back to the Loop Condition of This Loop”.
This action causes execution of the strategy’s logic to continue back to the “loop condition” of this loop, without executing the rest of the logic in this loop that is beneath this action.
If this action is currently located inside of multiple nested loops, execution of the strategy’s logic will continue back to the “loop condition” that belongs to the innermost loop only.
If the “loop condition” of the innermost loop that contains this action evaluates to true, the innermost loop will be executed again.
Currently, this “Continue Back to the Loop Condition of This Loop” action will create an infinite loop scenario since execution will enter the loop, the “Continue Back to the Loop Condition of This Loop” action will cause execution to jump back up to the loop condition without adding 1 to the value of the counter variable causing the loop condition to always be true. If we backtested our strategy with this bug in it, NinjaTrader® 8 would freeze. Let’s put it inside of a Conditional Trading Logic (If Block) so that it will only send execution back up to the loop condition when the counter variable hits 103. We still have an infinite loop bug because once the counter variable is equal to 103 the “Continue Back to the Loop Condition of This Loop” action will send execution back up to the loop condition without adding 1 to the value of the counter variable. Let’s add a statement before the “Continue Back to the Loop Condition of This Loop” action that adds 1 to the counter variable to fix this infinite loop bug. Now, the “Print To Output Window” action will print the value of the counter variable up until it is 102, but the counter variable’s value will not be printed when it is 103 due to our “Continue Back to the Loop Condition of This Loop” action that is executed when the counter variable is 103, causing execution to jump to the loop condition before it reaches the “Print To Output Window”. Since we add 1 to the counter variable before we execute the “Continue Back to the Loop Condition of This Loop” action, its value become 104, the loop is entered again and the counter variable’s value of 104 is printed, execution continues to the very bottom of the loop at which point the counter variable becomes 105, the loop condition is true again and the counter variable’s value of 105 is printed, and finally, this condition will be true, causing the “Exit Out of This Loop” action to execute, which causes the execution of our strategy to jump outside the loop, to the action directly beneath it, which is here. So, our current logic prints the values 100, 101, and 102, then skips 103, then prints 104 and 105, then exits out of the loop and prints no other numbers.
One more thing before we wrap up: I’ve mentioned NinjaTrader® a few times in this video. It should be noted that Quagensia N Edition is a product of Quagensia, Inc., a company which has no affiliation with NinjaTrader, LLC.
Also, NinjaTrader® and NinjaScript® are registered trademarks of NinjaTrader, LLC.
That’s the end of our video. Thanks for watching. If you liked it, please let us know by giving this video a like and subscribing to our channel. And if you loved it, please consider sharing this video.
Download the free trial of Quagensia N Edition from quagensia.com to get all our free no-code trading strategies so that you can use them as-is and customize them without code.
And on behalf of our users, thank you to the content creators who take this strategy and run with it and publish their Quagensia Strategies in their own videos. Content creators, if you let us know when you’ve published high-quality Quagensia-enhanced content, we will consider promoting it for free on our website.
Have a great day.