dorien
dorien

Reputation: 5407

Pine script exit with take profit closes positions different than set profit percentage and has multiple per bar

I have a strategy with an order entry based on limit price. This order is then closed with a strategy.exit() with profit argument. The profit percentage is set to 1%. However, checking the backtest, it is a random number from 0.01 to 2.6% or something. Secondly, it looks like multiple orders are open at the same time (Pyramiding is set to zero).

I have 'recalculate after order is filled' on. So is another order fired at the same time one is closed (possible?). I tried changing profit to limit, similar results.

How can I get insight into this. I think the more detailed intra-bar times are displayed as the bar start times. In the image below, you see 2 orders open on 5 May 8:00 and they also close then. One is 0.1% profit the other is 2.35%.

Backtest image

take_profit_percentage = input.float(1)

strategy.cancel_all()     
    
if (close > open) and buy and strategy.position_size == 0
    strategy.entry('Long', strategy.long, qty=ordersize, limit=buyPrice, comment=enterLongComment)
         
if (strategy.position_size > 0) 
    take_profit_limit =  strategy.position_avg_price * ((take_profit_percentage/100)+1)  //+ stretch * 2 
    take_profit =  strategy.position_avg_price * (take_profit_percentage/100)

    strategy.exit("Exit Long", from_entry="Long", profit = take_profit, stop = stop_loss, comment=exitLongComment) 

Upvotes: 0

Views: 1219

Answers (1)

dorien
dorien

Reputation: 5407

Turns out the strategy.entry() was being executed as a normal order as the limit price was higher than close. What I needed to use was a stop argument:

strategy.entry('Long', strategy.long, qty=ordersize, stop=buyPrice, comment=enterLongComment)

I further put

if barstate.isconfirmed

before the entry() so that is not executed twice per bar.

Upvotes: 0

Related Questions