Hugo
Hugo

Reputation: 27

Cannot use a mutable variable as an argument of the security function?

I have experiencing problem to include a mutable variable as an argument for security function. I tried wrapping the code with a mutable variable in a function, like this article suggested. But it doesn't seem to work for me on v4. The security function is required because my strategy runs on 4 different timeframes. The following code is a simplified version to show where the issue occurs. Any advices? https://www.tradingview.com/wiki/Pine_Version_3_Migration_Guide#Resolving_a_problem_with_a_mutable_variable_in_the_security_expression

//@version=4
strategy(title="My Strategy", overlay=true, process_orders_on_close=true)


// —————————— STATE

hasOpenTrade = strategy.opentrades != 0


// —————————— VARIABLES

var maxSinceLastBuySell = 0.
var minSinceLastBuySell = 0.


// —————————— FUNCTIONS

if hasOpenTrade
    maxSinceLastBuySell := max(maxSinceLastBuySell, high)
    minSinceLastBuySell := min(minSinceLastBuySell, low)


// —————————— MAIN

price_B = low < maxSinceLastBuySell * 0.9 ? 1 : 0
price_B_persistence = sum(price_B, 2) == 2 ? true : false

price_S() => 
    sum((high > minSinceLastBuySell * 1.1 ? 1 : 0), 2) == 2


// —————————— EXECUTIONS

longCondition = security(syminfo.tickerid, "60", price_B_persistence)
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition_sec = security(syminfo.tickerid, "60", price_S())
if (shortCondition_sec)
    strategy.entry("My Short Entry Id", strategy.short)

Upvotes: 0

Views: 5775

Answers (1)

Michel_T.
Michel_T.

Reputation: 2821

You have to put there different security and then choose one of the depending on your needs:

//@version=4
study("My Script")
s = bar_index % 2 == 0 ? security("F", "1", close) : security("BA", "1", close)
plot(s)

In your case it'll be something like:

...
// one security when the price_B_persistence is true and one - when it false
longCondition = price_B_persistence ? security(syminfo.tickerid, "60", true) : security(syminfo.tickerid, "60", false)
...
shortCondition_sec = price_S() ? security(syminfo.tickerid, "60", true) : security(syminfo.tickerid, "60", false)
price_S(h) => 
    sum((h > minSinceLastBuySell * 1.1 ? 1 : 0), 2) == 2

high60 = security(syminfo.tickerid, "60", high)
shortCondition_sec = price_S(high60)

Upvotes: 1

Related Questions