Mentis course
Lesson 8. Loops, arrays and functions
40 min, intermediate level
A for loop repeats. An array is a list. A function names a piece of logic.
//@zscript 1
indicator("Last 5 closes average")
var prices = array.new<float>()
array.push(prices, close)
if array.size(prices) > 5
array.shift(prices)
plot(array.avg(prices))
mid(h, l) => (h + l) / 2
Loops run on every bar, so keep them short. A built-in such as ta.highest is almost always faster than the same loop. Zscript stops runaway loops with a clear error.
Exercises
- Write a function. Write range(h, l) that returns high minus low as a percent of close, and plot it.
- Count in a loop. Use for to count how many of the last 10 closes were above their open.
Quick quiz
Why keep loops short?
Cost multiplies by thousands of bars.
What does array.push do?
push appends.
Education only. Not financial advice. Examples are teaching samples, not trading results.
