Dev Oberay
Dev Oberay

Reputation: 11

strategy.exit() not closing position even when stop loss is reached

I am trying to create a strategy in Pine script for TradingView that exits a long position when the low of the candle where the trade is reached as a stop loss. For short position, when the high of the candle where the trade was executed as a stop loss I am using the strategy.exit() function with the "stop" argument to set the stop loss value and the strategy.entry() function to enter the position. However, the position is not being closed even when the stop loss level is reached.

I am using the strategy.exit() function with the "stop" argument to set the stop loss value and the strategy.entry() function to enter the position. However, the position is not being closed even when the stop loss level is reached.

`oversold = 10
overbought = 90

co = ta.crossover(rsiPlus, oversold)
cu = ta.crossunder(rsiPlus, overbought)
if (not na(rsiPlus))
    if (co) and (ta.ema(close,20) <close)
        strategy.entry("RSI", strategy.long, comment="RSI")
        strategy.exit("RSI", "sl", stop=low[1]-atr)
    if (cu) and (ta.ema(close,20) >close)
        strategy.entry("RSI", strategy`

Upvotes: 1

Views: 3878

Answers (2)

Adam Wallner
Adam Wallner

Reputation: 2411

The problem is the following line:

strategy.exit("RSI", "sl", stop=low[1]-atr)

According to the documentation of strategy.exit:

If an order with the same ID is already pending, it is possible to modify the order

So you modify the stop value on every bars when if(s) are true. I usually do something like this to prevent modification after entering position:

if barstate.isconfirmed and strategy.position_size == 0
    // Your entry and exit here

Also you should replace the 1st 2 parameters. Because the 1st parameter is just the ID of the exit order, which is used if you later want to cancel it, and to be able to identify in list of orders.

Upvotes: 2

vitruvius
vitruvius

Reputation: 21294

Couple of things here.

  1. You probably don't want to place your exit order with those conditions. Instead, check if you are in a long position and then place your exit order. Use var variables to store data at the time of entry.

  2. The first parameter of the strategy.exit() is id which is the order identifier. The second parameter is from_entry which is the identifier of a specific entry order to exit from. In your example, you are trying to exit from an order called sl which does not exist.

Code:

var float low_at_entry = na
var float atr_at_entry = na

co = ta.crossover(rsiPlus, oversold)
cu = ta.crossunder(rsiPlus, overbought)
if (not na(rsiPlus))
    if (co) and (ta.ema(close,20) <close)
        strategy.entry("RSI", strategy.long, comment="RSI")
        low_at_entry := low
        atr_at_entry := atr

if (strategy.position_size > 0)  // If in a long position
    strategy.exit("sl", "RSI", stop=low_at_entry [1]-atr_at_entry)

Upvotes: 1

Related Questions