I'm trying to push cumDistance
into cumDistances
array for every iteration of the for loop but I am having trouble.
var inTrade = false
var entry = 0.
var exit = 0.
distance = 0.
entryCon = ta.crossover(ta.rsi(close, 10), 20) and not inTrade
exitCon = ta.crossunder(ta.rsi(close, 10), 80) and inTrade
cumDistances = array.new_float()
for i=1 to 5
if entryCon[1]
entry := close[1]
inTrade := true
if exitCon[1]
exit := close[1]
inTrade := false
distance := exit - entry*i
cumDistance = ta.cum(distance)
array.push(cumDistances, cumDistance)
The values inside the cumDistances
array that I get are all the same:
- -43.41588
- -43.41588
- -43.41588
- -43.41588
- -43.41588
.
if entryCon[1]
entry := close[1]
inTrade := true
if exitCon[1]
exit := close[1]
inTrade := false
distance := exit - entry*i //changed i to 1,2,3,4,5
cumDistance = ta.cum(distance)
If I run the code without for loops(like the code just above), these are the values of cumDistance
I get for their respective iteration.
- 0.02016
- -10.83885
- -21.69786
- -32.55687
- -43.41588
It seems that the array cumDistances
only saves the value of cumDistance
for the last iteration of the for loop to all index of the array.
How do I fix this?
EDIT: Response to elod008:
cumDistances = array.new_float()
for i=1 to 5
var distances = array.new_float()
if entryCon[1]
entry := close[1]
inTrade := true
if exitCon[1]
exit := close[1]
inTrade := false
distance := exit - entry*i
array.push(distances, distance)
cumDistance = array.sum(distances)
array.push(cumDistances, cumDistance)
//array.clear(distances) <---- placing this here, I will get NaN,NaN,NaN,NaN,Nan as result
plot(array.size(cumDistances), "no. of index", display=display.data_window)
table1 = table.new(position.top_right, 10, 10)
table.cell(table1, 0, 0, str.tostring(array.get(cumDistances, 0)) + ", "
+ str.tostring(array.get(cumDistances, 1)) + ", "
+ str.tostring(array.get(cumDistances, 2)) + ", "
+ str.tostring(array.get(cumDistances, 3)) + ", "
+ str.tostring(array.get(cumDistances, 4)))