curiousgeorge
curiousgeorge

Reputation: 17

Calculate how many bars between chart timeframe and higher timeframe bar

So I'm creating higher timeframe candles on the chart and currently I have an input variable that I adjust to increase/decrease the width of the higher timeframe candle body box. How can I calculate the number of bars between the chart timeframe and the designated higher timeframe bar automatically? This way the higher timeframe bar on the chart would take up the exact amount of space to show what time it represents clearly.

barsBack = input.int(50, title="Candle Body Width In Bars")

box.new(bar_index - barsBack, array.last(htf1ClosePrice), bar_index - 1, array.last(htf1OpenPrice), xloc=xloc.bar_index,
          border_color=greenCandlehtf1 ? greenLineColor : redLineColor, bgcolor=greenCandlehtf1 ? greenBoxColor : redBoxColor))

Upvotes: 0

Views: 552

Answers (1)

AmphibianTrading
AmphibianTrading

Reputation: 1415

Create an input for the higher time frame, then use use the ta.change function and and if statement. It will set the width to match the higher time frame. See example below

//@version=5
indicator("My script", overlay = true)
htf = input.timeframe('D', 'Higher Time Frame')
var startIndex = 0
var box body = na
var box upperWick = na
var box lowerWick = na

newTime = ta.change(time(htf))
[ohtf, hhtf, lhtf, chtf] = request.security(syminfo.tickerid, htf, [open, high, low, close])
bullish = chtf > ohtf

if newTime
    startIndex := bar_index

if newTime or barstate.islast
    (body[1]).delete(), (upperWick[1]).delete(), (lowerWick[1]).delete()
    boxColor = bullish ? color.green : color.red
    body := box.new(startIndex, bullish ? chtf : ohtf, bar_index, bullish ? ohtf : chtf, color.new(boxColor,50), bgcolor = color.new(boxColor,50))
    upperWick := box.new(startIndex, hhtf, bar_index, bullish ? chtf : ohtf, color.new(boxColor,90), bgcolor = color.new(boxColor,90))
    lowerWick := box.new(startIndex, bullish ? ohtf : chtf, bar_index, lhtf, color.new(boxColor,90), bgcolor = color.new(boxColor,90))

Upvotes: 0

Related Questions