Denzel
Denzel

Reputation: 399

How to trigger only one entry?

I have code like this:

strategy.entry("slow", true, 1, when = crossover(ema(close,21),ema(close,42)) and strategy.position_size<=0)
strategy.entry("fast", true, 1, when = crossover(ema(close,7),ema(close,14)) and strategy.position_size<=0)

strategy.exit("slowExit", "slowExit", when = crossunder(ema(close,21),ema(close,42)))
strategy.exit("fastExit", "fastExit ", when = crossunder(ema(close,7),ema(close,14)))

I want to enter only one position. Either slow or fast. However, they trigger together. How to trigger only one entry?

Upvotes: 0

Views: 906

Answers (2)

Abolfazl Rastgou
Abolfazl Rastgou

Reputation: 832

Try it:

IsFlat() =>
    strategy.position_size == 0

if IsFlat() 
   strategy.entry("slow", true, 1, when = crossover(ema(close,21),ema(close,42)) and 
   strategy.position_size<=0)
   strategy.entry("fast", true, 1, when = crossover(ema(close,7),ema(close,14)) and 
   strategy.position_size<=0)

Upvotes: 1

Behnam Maboudi
Behnam Maboudi

Reputation: 684

var HasSlowPosition = false
var HasFastPosition = false

fastCondition = crossover(ema(close,7),ema(close,14)) and strategy.position_size<=0
slowCondition = crossover(ema(close,21),ema(close,42)) and strategy.position_size<=0
if(slowCondition and not HasFastPosition and not HasSlowPosition) 
    strategy.entry("slow", true, 1)
    HasSlowPosition := true
else if(fastCondition and not HasFastPosition and not HasSlowPosition)
    strategy.entry("fast", true, 1)
    HasFastPosition := true

exitSlowCondition = crossunder(ema(close,21),ema(close,42))
exitFastCondition = crossunder(ema(close,7),ema(close,14))
if (exitSlowCondition and HasSlowPosition)
    strategy.close("slow", comment = "slowExit" ) 
    HasSlowPosition := false
else if (exitFastCondition and HasFastPosition)
    strategy.close("fast", comment = "fastExit " )
    HasFastPosition := false

Please notice that var keyword will initialize your variable only once and it will not get reset on the next candle on its own.

Upvotes: 1

Related Questions