pine-scriptalgorithmic-trading

using valuewhen in pine script


I can understand how valuewhen works in pine script by its docs at https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}valuewhen

The example given there is simple:

// Get value of `close` on second most recent cross
plot(ta.valuewhen(ta.cross(slow, fast), close, 1))

But I'm not able to understand how the following code works in a production open source script that finds highs in a divergence where Dinput1 is the series D for stochastic calculated earlier in the script.

depth = input(2, 'Fractal Depth')
_src = Dinput1
_high = high
_low = low
top_fractal = ta.highest(_src, depth * 2 + 1) == _src[depth]
prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth]
prev_high = ta.valuewhen(top_fractal, _high[depth], 0)[depth]

Specifically, the line:

prev_top_fractal = ta.valuewhen(top_fractal, _src[depth], 0)[depth]

As I understand it, if the depth = default 2 then 5 candles are examined each time starting from index 0 (rightnost) and if the middle value is highest then top_fractal condition will give a true result. But what will be returned by valuewhen? From docs, it should return that highest value found. But then why is it indexing it again by [depth]? That suggest that what is returned is a series. Is it a value or series?

Update after some research: It seems valuewhen returns the highest value in the most recent (0th) occurence of last 5 candles only if the highest is also the middle value in those 5 candles. But what I'm not able to understand is the [depth] suffix to get the prev_top_fractal (previous high). That suggests that valuewhen returns the series beginning with 5 candles so that [depth] suffix is needed to get the highest value.


Solution

  • Figured it out. Coming from a regular programming background, I had a confusion on how the historic referencing works and the way the pine script runs on each bar.

    valuewhen returns the first occurrence of the 5-bar D fractal with the TOP value in the middle. The actual top value prev_top_fractal is obtained by historic referencing [2] on the returned result.

    In the next line, prev_high in price is found by a similar logic.