Search code examples
pine-scriptpine-script-v5back-testing

Pine script strategy tester calculates with future data


I test strategies for 3commas bots. 3commas bots works with completed candles. So if u want to open a trade when the rsi is under 20, the bot will buy AFTER the candle is CLOSED under 20 on the next candle. The next candle can have any rsi value. So u can see maybe an rsi 30 or 40 and trades on that day, because the PREVIOUS CLOSED day was under 20!

This sample script works with fixed 1 day timeframe.

My problem is this script makes trades immediately when a day (will) close under rsi 20. It sees the future!

//@version=5
strategy("Future test", overlay=true, initial_capital = 100, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1)

startTime = timestamp('2023-09-01 00:00:00')
endTime = timestamp('2023-09-11 00:00:00')

len_2 = input.int(2, "Length 2", options=[2])
tf_1d = 'D'

inTimePeriod = startTime <= time and time <= endTime
inTrade = strategy.position_size > 0
notInTrade = not(inTrade)

rsi_1d_2l = request.security(syminfo.ticker, tf_1d, ta.rsi(close, len_2), lookahead = barmerge.lookahead_off)

buyCondition = rsi_1d_2l < 20
sellCondition = true

if (inTimePeriod)
    if (notInTrade and buyCondition) 
        strategy.entry('buy', strategy.long)
    else if (inTrade and sellCondition)
        strategy.close('buy')

I want to open trades based on completed candle data (like the 3commas bot works).

The problem


Solution

  • Maybe calculate your rsi and look one bar back. The strategy tester evaluates your candle and then executes the trade.You want to buy the next day, when something happens

    buyCondition = rsi_1d_2l[1] < 20