strategy.close_all stop loss calculation

843 views Asked by At

I'm working on a strategy which buys a set amount of contracts when a condition is met, then buys more when the price increases by a set amount, then buys more when it increases again and so on for 5 times. Then when the price decreases by a set percentage from the last opened position entry price it sells all the open positions. The problem is with closing all these trades - either the code is not working (and gives "no data") or the strategy closes the trades at bigger losses than set.

A part of my code currently looks like this:

// INPUTS

stoploss = input(2,"SL in %",group=gr3)
stoplossindecimals = stoploss / 100
stoplossprice = ((strategy.opentrades.entry_price(strategy.opentrades - 1)) * stoplossindecimals)

// CONDITIONS

if entry1long and strategy.opentrades == 0
    strategy.entry("L.1",strategy.long,qty=qty1)
    
if entry2long and strategy.opentrades == 1
    strategy.entry("L.2",strategy.long,qty=qty2)    

if entry3long and strategy.opentrades == 2
    strategy.entry("L.3",strategy.long,qty=qty3)        
    
if entry4long and strategy.opentrades == 3
    strategy.entry("L.4",strategy.long,qty=qty4)    

if entry5long and strategy.opentrades == 4
    strategy.entry("L.5",strategy.long,qty=qty5)

But this one gives "No data" in TV strategy tester, seems that something is looping.

If I make it like this:

if close <= strategy.opentrades.entry_price(strategy.opentrades - 1) - stoplossprice strategy.close_all()

It closes the trades, but with more losses than needed.

If I make it like this:

if close == strategy.opentrades.entry_price(strategy.opentrades - 1) - stoplossprice strategy.close_all()

It gives "no data" again.

Any suggestions?

1

There are 1 answers

1
Bjorgum On

You can use strategy.exit() to set a stop loss that respects the stop calculation. strategy.close will wait for a confirmed close and execute on the next tick, which is the open of the bar following and can result in a stop being exceeded. Can set a stop like this:

strategy.exit("Exit", stop = stoplossprice)

plot(stoplossprice, "Stop", color.red, style = plot.style_linebr)

Cheers and all the best