Please teach me how to use the for loop in the Pine language (scripts for TradingView charts). I made a test indicator (code below), which displays the MACD. In green chart, I simply display MACD at the top level of the script. I get the same MACD value in red chart, but taken inside the 'for' loop. See how it works:
- the loop increments the value of n from 0 to 20
- when n is 0, the script takes the MACD value and writes it to the cell val
- then there are another 20 empty steps.
- at the end, the script displays val on the screen, completing the red chart
Logically, the green and red graphics should ideally match, since they display the same values. But they are different !!! Help understand the error. Thank you.
//@version=4
study("My Script")
[_,_,currMacd] = macd(close[0], 12, 26, 9)
plot(currMacd, style=plot.style_histogram, color=color.green)
//
float val = 0.0
for int n = 0 to 20
[_,_,tempMacd] = macd(close[n], 12, 26, 9)
if n == 0
val := tempMacd
plot(val, style=plot.style_histogram, color=color.red)