Search code examples
pine-scriptpine-script-v5tradingalgorithmic-trading

Stop Loss and Exit Condition


I'm working on a Tradingview Pinescript strategy. I initiate a short position when the RSI falls below 60. I'd like to incorporate a 50-point stop loss into this strategy. The exit condition is when the RSI drops below 40 and then crosses above 50, at which point my open position should be closed instantly.

Code:

//@version=5
strategy(title="RSI", process_orders_on_close=true, use_bar_magnifier=true, overlay=true)

// RSI
rsi = ta.rsi(close, input.int(14, title="RSI Period"))

// Entry
if ta.crossunder(rsi, 60)
    strategy.entry("Enter Short", strategy.short)

// Exit
if ta.crossover(rsi, 50)
    strategy.close("Enter Short", comment="Exit Short")

I attempted to implement a stop with "stop=50" and "loss=50," but it didn't function correctly.

My current exit strategy seems flawed since it closes the position even if the RSI drops to 49 and then crosses above 50. I require it to stay below 40 at a minimum before closing above 50 for the position to be closed.


Solution

  • strategy.close() is used for conditional closes. So, if you want to close your position based on an RSI value, use that.

    strategy.exit() is used for exits based on some price. If you want to have SL and TP, use this. You can use the profit and loss arguments. They expect the target to be specified in ticks. So, you might need to convert points to ticks.