pine-scriptpine-script-v5

How to get high and low of the previous 'n' days from an intraday timeframe?


I'm new to Pine Script.

I want to get the high/low/date (DD/MM/YYYY) from the previous 'n' "D" days (say last 3 from user input) when on a lower intraday timeframe. This is so I can print the last three days highs and lows on the intraday chart.

I know the following code doesn't work and I understand why - I cannot pass a mutable variable into request.security. However, I can't think of a way to be on the current day's intraday chart and start from the previous day back 'n' days, using a loop in order to handle the variable number of lookback days as per user input. I don't know how to pass the calculated series subscript value into request.security? Any advice on how to achieve this would be greatly appreciated.

type CandleRange
    float high
    float low
    int time

CandleRange[] candles = array.new<CandleRange>()

timeframe = input.timeframe("D","Timeframe")
lookbackDays = input.int(3,"Number of Days")

getDailyHighLow(timeframe,index=1)=>
    float dailyHigh = request.security(syminfo.tickerid,timeframe,high[index])
    float dailyLow = request.security(syminfo.tickerid,timeframe,low[index])
    int  dailyTime = request.security(syminfo.tickerid,timeframe,time[index])
    [dailyHigh, dailyLow,dailyTime]

if barstate.islastconfirmedhistory
    for i = 1 to lookbackDays by 1
    // using i gives...
    // Cannot use loop variables or mutable variables from a loop's local scope as `expression` arguments in `request.*()` calls.
    [ dailyHigh, dailyLow, dailyTime] = getDailyHighLow(timeframe,i) 
    CandleRange cr = CandleRange.new(dailyHigh, dailyLow, dailyTime)
    candles.push(cr)

Solution

  • No need for a for loop. Since it is an intraday timeframe, keep track of the daily high/low yourself as new bars form. Then push the daily high/low to an array whenever it is a new day. You can retrieve the last n values from this array to use it later.

    //@version=5
    indicator("My script", overlay=true)
    
    timeframe = input.timeframe("D","Timeframe")
    lookbackDays = input.int(3,"Number of Days")
    
    is_new_day = timeframe.change("D")
    
    var daily_high_arr = array.new_float()
    var daily_low_arr = array.new_float()
    var daily_high = high
    var daily_low = low
    
    if (is_new_day)
        // Push last day high/low to the array
        array.push(daily_high_arr, daily_high)
        array.push(daily_low_arr, daily_low)
    
        // Reset variables for the new day
        daily_high := high
        daily_low := low
    else
        if (high > daily_high)
            daily_high := high
    
        if (low < daily_low)
            daily_low := low