pine-scriptpine-script-v4

Lines from a date picker


What I'm trying to get in Pinescript Tradingview are horizontal lines generated from a date picker. Selecting a date(s) should make a new line or lines using that days high and low. The calculation is simple but there are two that I'd like to select from. So I'd get new high and low lines for the next day but the days I'd like to start from change that's the reason for the date picker.

Something like the below example but using the high and low of the day.

//@version=4
study("", "", true)
i_date = input(timestamp("2021-05-14"), type = input.time)
var float hi = na
var float lo = na

if time == i_date
    hi := open * 1.02
    lo := open * 0.99
    
plot(hi)
plot(lo)

Solution

  • You can use a timestamp as you did for the date, and then check if you are on the selected day by using year(), month() and dayofmonth() functions.

    Store the daily high and lows in a temp variable and when the selected day is over, simply use those temp variables.

    //@version=5
    indicator("My script", overlay=true)
    
    in_date = input.time(timestamp("01 Jan 2024"), "Date")
    
    var float selected_day_high = na
    var float selected_day_low = na
    
    var temp_daily_high = high
    var temp_daily_low = low
    
    is_new_day = timeframe.change("D")
    was_selected_day = (year[1] == year(in_date)) and (month[1] == month(in_date)) and (dayofmonth[1] == dayofmonth(in_date))
    
    if (is_new_day)
        if (was_selected_day)
            selected_day_high := temp_daily_high
            selected_day_low := temp_daily_low
            line.new(bar_index, selected_day_high, bar_index + 1, selected_day_high, extend=extend.right, color=color.green)
            line.new(bar_index, selected_day_low, bar_index + 1, selected_day_low, extend=extend.right, color=color.red)
    
        temp_daily_high := high
        temp_daily_low := low
    else
        if (high > temp_daily_high)
            temp_daily_high := high
    
        if (low < temp_daily_low)
            temp_daily_low := low
    

    In the below example, I have selected 03-Jan-24 as my timestamp. As soon as the new day starts, it plots the high and low of the selected day.

    enter image description here