//@version=6
indicator("tradingranchtime", shorttitle = "TRT", overlay = true, max_boxes_count = 300, max_lines_count = 300, max_labels_count = 20)

// tradingranchtime
// A multi-timeframe candle display inspired by the supplied screenshot.
// The active candle in each group updates until that timeframe closes.

// -----------------------------------------------------------------------------
// Timeframe groups
// -----------------------------------------------------------------------------
string groupTimeframe1 = input.timeframe("15", "Timeframe", group = "15-minute group", inline = "tf1")
string groupLabel1 = input.string("15m", "Label", group = "15-minute group", inline = "tf1")
int groupCount1 = input.int(15, "Candles", minval = 1, maxval = 20, group = "15-minute group")

string groupTimeframe2 = input.timeframe("60", "Timeframe", group = "1-hour group", inline = "tf2")
string groupLabel2 = input.string("1H", "Label", group = "1-hour group", inline = "tf2")
int groupCount2 = input.int(5, "Candles", minval = 1, maxval = 20, group = "1-hour group")

string groupTimeframe3 = input.timeframe("D", "Timeframe", group = "Daily group", inline = "tf3")
string groupLabel3 = input.string("D", "Label", group = "Daily group", inline = "tf3")
int groupCount3 = input.int(1, "Candles", minval = 1, maxval = 20, group = "Daily group")

// -----------------------------------------------------------------------------
// Appearance and layout
// -----------------------------------------------------------------------------
color bullishColor = input.color(color.rgb(0, 205, 168), "Bullish", group = "Appearance", inline = "colors")
color bearishColor = input.color(color.rgb(255, 23, 68), "Bearish", group = "Appearance", inline = "colors")
color labelColor = input.color(color.rgb(225, 228, 235), "Labels", group = "Appearance", inline = "colors")
int wickWidth = input.int(1, "Wick width", minval = 1, maxval = 4, group = "Appearance")

bool projectToRight = input.bool(true, "Project candles to right", group = "Layout")
int rightOffset = input.int(12, "Right-side gap", minval = 1, maxval = 50, group = "Layout")
int bodyWidth = input.int(2, "Body width", minval = 1, maxval = 3, group = "Layout")
int candleGap = input.int(1, "Gap between candles", minval = 0, maxval = 2, group = "Layout")
int groupGap = input.int(5, "Gap between groups", minval = 1, maxval = 20, group = "Layout")
float labelPadding = input.float(0.18, "Label height (ATR)", minval = 0.0, maxval = 2.0, step = 0.05, group = "Layout")

int historyLimit = 20
int candleStep = bodyWidth + candleGap

// Each group keeps its own OHLC history. Index 0 is the active candle.
var array<float> opens1 = array.new<float>()
var array<float> highs1 = array.new<float>()
var array<float> lows1 = array.new<float>()
var array<float> closes1 = array.new<float>()
var array<int> times1 = array.new<int>()

var array<float> opens2 = array.new<float>()
var array<float> highs2 = array.new<float>()
var array<float> lows2 = array.new<float>()
var array<float> closes2 = array.new<float>()
var array<int> times2 = array.new<int>()

var array<float> opens3 = array.new<float>()
var array<float> highs3 = array.new<float>()
var array<float> lows3 = array.new<float>()
var array<float> closes3 = array.new<float>()
var array<int> times3 = array.new<int>()

var array<box> candleBodies = array.new<box>()
var array<line> candleWicks = array.new<line>()
var array<label> groupLabels = array.new<label>()

f_updateGroup(array<float> groupOpens, array<float> groupHighs, array<float> groupLows, array<float> groupCloses, array<int> groupTimes, float candleOpen, float candleHigh, float candleLow, float candleClose, int candleTime) =>
    if not na(candleTime) and not na(candleOpen)
        bool isNewCandle = array.size(groupTimes) == 0 or array.get(groupTimes, 0) != candleTime
        if isNewCandle
            array.unshift(groupOpens, candleOpen)
            array.unshift(groupHighs, candleHigh)
            array.unshift(groupLows, candleLow)
            array.unshift(groupCloses, candleClose)
            array.unshift(groupTimes, candleTime)
            if array.size(groupTimes) > historyLimit
                array.pop(groupOpens)
                array.pop(groupHighs)
                array.pop(groupLows)
                array.pop(groupCloses)
                array.pop(groupTimes)
            0
        else
            array.set(groupOpens, 0, candleOpen)
            array.set(groupHighs, 0, candleHigh)
            array.set(groupLows, 0, candleLow)
            array.set(groupCloses, 0, candleClose)
            0

f_clearDrawings() =>
    if array.size(candleBodies) > 0
        for body in candleBodies
            box.delete(body)
    if array.size(candleWicks) > 0
        for wick in candleWicks
            line.delete(wick)
    if array.size(groupLabels) > 0
        for nameLabel in groupLabels
            label.delete(nameLabel)
    array.clear(candleBodies)
    array.clear(candleWicks)
    array.clear(groupLabels)

f_drawGroup(array<float> groupOpens, array<float> groupHighs, array<float> groupLows, array<float> groupCloses, int requestedCount, int startX, string name, float verticalPadding) =>
    int available = math.min(requestedCount, array.size(groupOpens))
    int nextX = startX
    float groupHigh = na

    if available > 0
        for historyIndex = available - 1 to 0
            int displayIndex = available - 1 - historyIndex
            int candleX = startX + displayIndex * candleStep
            int wickX = candleX + int(math.floor(bodyWidth * 0.5))
            float candleOpen = array.get(groupOpens, historyIndex)
            float candleHigh = array.get(groupHighs, historyIndex)
            float candleLow = array.get(groupLows, historyIndex)
            float candleClose = array.get(groupCloses, historyIndex)
            color candleColor = candleClose >= candleOpen ? bullishColor : bearishColor

            float bodyTop = math.max(candleOpen, candleClose)
            float bodyBottom = math.min(candleOpen, candleClose)
            float minimumBody = syminfo.mintick * 2.0
            if bodyTop - bodyBottom < minimumBody
                float bodyMiddle = (bodyTop + bodyBottom) * 0.5
                bodyTop := bodyMiddle + minimumBody * 0.5
                bodyBottom := bodyMiddle - minimumBody * 0.5

            line newWick = line.new(x1 = wickX, y1 = candleLow, x2 = wickX, y2 = candleHigh, xloc = xloc.bar_index, color = candleColor, width = wickWidth, force_overlay = true)
            box newBody = box.new(left = candleX, top = bodyTop, right = candleX + bodyWidth, bottom = bodyBottom, xloc = xloc.bar_index, border_color = candleColor, border_width = 1, bgcolor = candleColor, force_overlay = true)
            array.push(candleWicks, newWick)
            array.push(candleBodies, newBody)
            groupHigh := na(groupHigh) ? candleHigh : math.max(groupHigh, candleHigh)

        int firstCenter = startX + int(math.floor(bodyWidth * 0.5))
        int lastCenter = startX + (available - 1) * candleStep + int(math.floor(bodyWidth * 0.5))
        int labelX = int(math.round((firstCenter + lastCenter) * 0.5))
        label newLabel = label.new(x = labelX, y = groupHigh + verticalPadding, text = name, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(color.black, 100), style = label.style_none, textcolor = labelColor, size = size.small, force_overlay = true)
        array.push(groupLabels, newLabel)
        nextX := startX + available * candleStep - candleGap + groupGap

    nextX

// lookahead_on lets the dashboard reproduce each historical HTF candle's final
// shape. It is visualization-only; the active candle still changes until close.
[open1, high1, low1, close1, time1] = request.security(syminfo.tickerid, groupTimeframe1, [open, high, low, close, time], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[open2, high2, low2, close2, time2] = request.security(syminfo.tickerid, groupTimeframe2, [open, high, low, close, time], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
[open3, high3, low3, close3, time3] = request.security(syminfo.tickerid, groupTimeframe3, [open, high, low, close, time], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)

f_updateGroup(opens1, highs1, lows1, closes1, times1, open1, high1, low1, close1, time1)
f_updateGroup(opens2, highs2, lows2, closes2, times2, open2, high2, low2, close2, time2)
f_updateGroup(opens3, highs3, lows3, closes3, times3, open3, high3, low3, close3, time3)

float atrValue = nz(ta.atr(14), math.max(high - low, syminfo.mintick * 10.0))

if barstate.islast
    f_clearDrawings()
    int displaySpan = (groupCount1 + groupCount2 + groupCount3) * candleStep - candleGap * 3 + groupGap * 2
    int nextGroupX = projectToRight ? bar_index + rightOffset : bar_index - displaySpan
    nextGroupX := f_drawGroup(opens1, highs1, lows1, closes1, groupCount1, nextGroupX, groupLabel1, atrValue * labelPadding)
    nextGroupX := f_drawGroup(opens2, highs2, lows2, closes2, groupCount2, nextGroupX, groupLabel2, atrValue * labelPadding)
    nextGroupX := f_drawGroup(opens3, highs3, lows3, closes3, groupCount3, nextGroupX, groupLabel3, atrValue * labelPadding)

// A lower chart timeframe is required to reconstruct every candle in all groups.
float chartSeconds = timeframe.in_seconds()
float smallestGroupSeconds = math.min(timeframe.in_seconds(groupTimeframe1), math.min(timeframe.in_seconds(groupTimeframe2), timeframe.in_seconds(groupTimeframe3)))
var table timeframeNotice = table.new(position.bottom_right, 1, 1, border_width = 0, force_overlay = true)
if barstate.islast
    if chartSeconds > smallestGroupSeconds
        table.cell(timeframeNotice, 0, 0, "Use a chart timeframe at or below " + groupLabel1 + " for complete candle history", text_color = color.white, bgcolor = color.new(color.red, 20), text_size = size.small)
    else
        table.cell(timeframeNotice, 0, 0, "", text_color = color.new(color.white, 100), bgcolor = color.new(color.black, 100), text_size = size.small)
