Search code examples
pine-scriptpine-script-v5

Drawing box using timestamp


As title says im trying to plot a box using 2 timestamps (start and stop). Considering the High and Low inside this range.

Here an image: Example of the result

Well i tried to do something but im stuck with the dates. For now i use an int box to go back to the date, but its a bit complicated when change timeframe.

Here's the code:

//@version=5
indicator('Test Box', overlay=true)

lenght = input.int(200,    title='Lenght')
show   = input.bool(true,  title='Show Box')

lowPrice  = ta.lowest(low,   lenght)
highPrice = ta.highest(high, lenght)

if barstate.ishistory
  
   if show
      _Bot   = line.new(bar_index[lenght], lowPrice,  bar_index,         lowPrice)
      _Top   = line.new(bar_index[lenght], highPrice, bar_index,         highPrice)
      _Left  = line.new(bar_index[lenght], highPrice, bar_index[lenght], lowPrice)
      _Right = line.new(bar_index,         highPrice, bar_index,         lowPrice)

      line.delete(_Bot[1])
      line.delete(_Top[1])
      line.delete(_Left[1])
      line.delete(_Right[1])

Any suggestion to get the result displayed in image but using timestamps form start and end date?


Solution

  • box.new() has an argument called xloc. You can set it to xloc.bar_time and then use your timestamps for the left and right.

    Below example shows you how to do that:

    start = timestamp(2023, 01, 01, 00, 00)
    end = timestamp(2023, 01, 15, 00, 00)
    
    draw_box = (time[1] < end) and (time >= end)    // Only draw the box when the end date is reached
    
    if (draw_box)
        box.new(start, high, end, low, xloc=xloc.bar_time)
    

    You then just need to find the top and bottom range.