Bjorn Mistiaen
Bjorn Mistiaen

Reputation: 6875

Conditional security() call

I'm trying to get the daily High/Low/Close with a security() call (with lookahead_on).
Those daily hlc values remain unchanged for every intraday bar within the same day.
Therefore, I'm trying to call the security function only once per day (when the date changes).
However, I keep getting the error Cannot read property 'isTuple' of undefined.
I don't understand why, and cannot seem to get it fixed.
Any ideas?

This is my example code

//@version=4
study("My Script")

f_sec() => security(syminfo.ticker, "D", [high,low,close], lookahead = barmerge.lookahead_on)

bar_date_ts = timestamp(year(time),month(time),dayofmonth(time),0,0,0)
is_new_date = change(bar_date_ts)

var float h = na
var float l = na
var float c = na

if (is_new_date)
    [x,y,z] = f_sec()
    h := x
    l := y
    c := z
    
plot(h)
plot(l)
plot(c)

Upvotes: 1

Views: 1151

Answers (1)

e2e4
e2e4

Reputation: 3828

Security function should be called in the global scope.

If you'll remove the tuple you'll receive the correct compiler error: Cannot call 'security' or 'financial' inside 'if' or 'for'

if (is_new_date)
    x := security(syminfo.ticker, "D", high, lookahead = barmerge.lookahead_on)
    y := security(syminfo.ticker, "D", low, lookahead = barmerge.lookahead_on)
    z := security(syminfo.ticker, "D", close, lookahead = barmerge.lookahead_on)
    h := x
    l := y
    c := z

So move your f_sec function outside the if statement, however the function would be called on each bar instead of once per day.

The solution is to use the conditional operator ? :, it doesn't work with tuples, so you'll have to make 3 security calls. Also Im not sure about saving the computation power that way, compiler could evaluate both.

var float x = na
var float y = na
var float z = na

x := is_new_date ? security(syminfo.ticker, "D", high,  lookahead = barmerge.lookahead_on) : nz(x[1])
y := is_new_date ? security(syminfo.ticker, "D", low,   lookahead = barmerge.lookahead_on) : nz(y[1])
z := is_new_date ? security(syminfo.ticker, "D", close, lookahead = barmerge.lookahead_on) : nz(z[1])

plot(x)
plot(y)
plot(z)

Note that using lookahead without history reference operator will lead script to repaint during current security resolution argument period.

Upvotes: 1

Related Questions