Dev The Hall
Dev The Hall

Reputation: 7

Stop Loss is being irrational

I use pine script version 5. My stop loss is set to the recent swing.

On long position that would be the lowest low of the last five candles.

While on a Short it would be the highest high of the last five candles.

Unless the minimum stop percentage is further away than that is used.

For a reason I am not able to find after going over it numerous times and having friends look over it, on short positions the position automatically exits on the open of the next candle from the entry candle.

I show it in the image linked. Every time a short is entered it is exited on the next candle. the take profit and stop are shown

//Stop Loss

MinStopLong = strategy.position_avg_price * (1 - 0.00075)
MinStopShort = strategy.position_avg_price * (1 + 0.00075)
StopLossLong = ta.lowest(low,5)
StopLossShort = ta.highest(high,5)
if MinStopLong < StopLossLong
    StopLossLong := MinStopLong
if MinStopShort > StopLossShort
    StopLossShort := MinStopShort

//Take Profit

TakeProfitLong = strategy.position_avg_price + (2 * (strategy.position_avg_price -   StopLossLong))
TakeProfitShort = strategy.position_avg_price - (2 *(StopLossShort - strategy.position_avg_price))


//Strategy Exit
if strategy.position_avg_price>0
    strategy.exit(id='close', stop=StopLossLong, limit=TakeProfitLong) 
if strategy.position_avg_price<0
    strategy.exit(id='close', stop=StopLossShort, limit=TakeProfitShort)

Upvotes: 0

Views: 314

Answers (1)

Rohit Agarwal
Rohit Agarwal

Reputation: 1368

There appears to be several issues in the code. Firstly, Strategy Exit should check position size rather than strategy.position_avg_price. Why would the position avg price become negative. Secondly the takeprofitlong and takeprofitshort are getting calculated for all candles. They will give correct value if there is one position only.

Upvotes: 0

Related Questions