pine-script

How to enter a trade on next days open, but exit at the same days close


I want to perform a backtest in TradingView where I enter a trade on next days open after the entry trigger occurs, but exit at the same days close of the exit trigger. Here's an example strategy just using rsi as indicator:

//@version=5
strategy(title = "Indicator Backtest", overlay = true, process_orders_on_close = true)

fromYear = year > 2011
toYear = year < 2023

VI = rsi(10)
BUY = VI < 30
SELL = VI > 70

if (BUY and fromYear and toYear)
    strategy.entry("Long", strategy.long)
if ((SELL or ta.barssince(BUY) >= 21))
    strategy.close("Long")

I am aware of two ways in TradingView to set the entry/exit procedure (using daily charts):

  1. strategy(title = "Indicator Backtest", overlay = true, process_orders_on_close = true) --> This will open the trade on the close on the day the buy signal is triggered and exits on the close of the day the sell signal is triggered.

  2. strategy(title = "Indicator Backtest", overlay = true, process_orders_on_close = false) --> This will open the trade on the open of the next day after the buy signal is triggered and exits on the open of the next day after the sell signal is triggered.

I also tried to use strategy 1) but using 'if (BUY[1] and fromYear and toYear)' instead of 'if (BUY and fromYear and toYear)'. This indeed opens the trade on the next day, however, not on the open but on the close...

Any idea?


Solution

  • The immediately parameter can help you:

    //@version=5
    strategy(title = "Indicator Backtest", overlay = true)
    
    fromYear = year > 2011
    toYear = year < 2023
    
    VI = ta.rsi(close, 10)
    BUY = VI < 30
    SELL = VI > 70
    
    if (BUY and fromYear and toYear)
        strategy.entry("Long", strategy.long)
    if ((SELL or ta.barssince(BUY) >= 21))
        strategy.close("Long", immediately = true)