Pine Script 5, once sold, is only bought back after a number of bars

33 Views Asked by At

I am creating a trading strategy as follows:

if buy_condition1
     strategy.entry('.', strategy.long)

if sell_condition1a
     strategy.close('.')

if sell_condition1b
     strategy.close('.')

I want after selling with condition sell_condition1b, to wait at least 10 bars before being able to execute the next buy order. Please guide me how to do it, thank you very much.

I tried the following, but it still doesn't work. There is still a buy order right after sell_condition2 instead of having to wait 10 bars.

var bool inBuy1 = false
var bool inBuy1x = false
var bool can_buy = true
var int bars_since_sell = na

if not na(bars_since_sell)
    bars_since_sell := bars_since_sell + 1

if bars_since_sell >= 10
    can_buy := true

if buy_condition1 and can_buy
    if buy_condition1a and not B
        strategy.entry('.', strategy.long)
        inBuy1 := true
        can_buy := false
    if buy_condition1b and conditionX and B
        strategy.entry('.', strategy.long)
        inBuy1 := true
        can_buy := false

if sell_condition1a and not inBuy1x
    strategy.close('.')
    inBuy1 := false
    can_buy := true

if buy_condition2 and can_buy
    strategy.entry('.', strategy.long)
    inBuy1x := true
    can_buy := false

if sell_condition2 and inBuy1x 
    strategy.close('.')
    inBuy1x := false
    can_buy := false
    bars_since_sell := 0
1

There are 1 best solutions below

0
NqHai On

I found the answer, the way to do it is as follows:

var bool inBuy1 = false
var bool inBuy1x = false
var int bars_since_sell = na

if not na(bars_since_sell)
    bars_since_sell := bars_since_sell + 1

if buy_condition1 and na(bars_since_sell) or bars_since_sell >= 10
    if buy_condition1a and not B
        strategy.entry('.', strategy.long)
        inBuy1 := true
    if buy_condition1b and conditionX and B
        strategy.entry('.', strategy.long)
        inBuy1 := true

if sell_condition1a and not inBuy1x
    strategy.close('.')
    inBuy1 := false

if buy_condition2 
    strategy.entry('.', strategy.long)
    inBuy1x := true

if sell_condition2 and inBuy1x 
    strategy.close('.')
    inBuy1x := false
    bars_since_sell := 0