Indicator · Pine Script v6 · On the chart

HTF Candles

by haydenfowler

HTF Candles overlays higher timeframe candlestick structures directly onto the current price chart.

View on GitHub

GitHub stars3on the repository
Pine versionv6current
Lines of code429
Settings13inputs
LicenceNone statedfile: MPL-2.0
Last update6 weeks ago7 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

429 lines of Pine Script v6 from hft-candles.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

hft-candles.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/

//@version=6
indicator("HTF Candles", overlay=true, explicit_plot_zorder=true, max_lines_count=500, max_boxes_count=500, max_labels_count=500)

// USER SETTINGS

// Every input below carries display=display.none so it stays out of the chart's
// status line, which otherwise lists all thirteen of them after the indicator
// name. The timeframe is the only one worth reading there, so it is the only one
// left on display.
higher_timeframe_input = input.string("Auto", title="Higher Timeframe",
                                  options=["Auto", "1m", "5m", "15m", "30m", "1h", "4h", "D", "W", "M"],
                                  tooltip="Select 'Auto' to automatically use one timeframe higher than the chart, or choose a specific timeframe")

// Convert user-friendly labels to Pine Script timeframe format
get_timeframe_string(tf_input) =>
    switch tf_input
        "1m" => "1"
        "5m" => "5"
        "15m" => "15"
        "30m" => "30"
        "1h" => "60"
        "4h" => "240"
        => tf_input  // "Auto", "D", "W", "M" pass through unchanged

get_next_higher_timeframe() =>
    chart_tf = timeframe.in_seconds() / 60
    result = switch
        chart_tf < 1 => "1"
        chart_tf < 5 => "5"
        chart_tf < 15 => "15"
        chart_tf < 30 => "30"
        chart_tf < 60 => "60"
        chart_tf < 240 => "240"
        chart_tf < 1440 => "D"
        chart_tf < 10080 => "W"
        => "M"
    result

higher_timeframe = higher_timeframe_input == "Auto" ? get_next_higher_timeframe() : get_timeframe_string(higher_timeframe_input)

// Pine takes transparency, TradingView's picker shows opacity — these are the
// complements of 5% / 35% / 4% / 30% opacity respectively.
bullish_fill_color = input.color(color.new(color.green, 95), title="Bullish Fill Color", display=display.none)
bullish_line_color = input.color(color.new(color.green, 65), title="Bullish Line Color", display=display.none)
bearish_fill_color = input.color(color.new(color.red, 96), title="Bearish Fill Color", display=display.none)
bearish_line_color = input.color(color.new(color.rgb(255,120,120), 70), title="Bearish Line Color", display=display.none)
line_thickness = input.int(1, title="Line Thickness", minval=1, maxval=10, display=display.none)
line_style_input = input.string("Solid", title="Line Style", options=["Solid", "Dashed", "Dotted"], display=display.none)
line_style = line_style_input == "Solid" ? line.style_solid : line_style_input == "Dashed" ? line.style_dashed : line.style_dotted

// The midline is the candle's equilibrium — (high + low) / 2 of the full HTF
// range, wicks included. Same definition the prior-day midpoint scripts use.
// It takes the candle's own bullish/bearish line colour, so the only thing
// distinguishing it from the body border is its style.
show_midline = input.bool(true, title="Show Midline", display=display.none,
                          tooltip="Draws the midpoint of each HTF candle's high-low range as a horizontal line spanning the candle.")
midline_style_input = input.string("Dashed", title="Midline Style", options=["Solid", "Dashed", "Dotted"], display=display.none)
midline_style = midline_style_input == "Solid" ? line.style_solid : midline_style_input == "Dashed" ? line.style_dashed : line.style_dotted

show_countdown = input.bool(false, title="Show Countdown Timer", display=display.none)
countdown_color = input.color(color.white, title="Countdown Text Color", display=display.none)
countdown_position_input = input.string("Middle", title="Countdown Position", options=["Top", "Middle", "Bottom"], display=display.none)

hide_incomplete = input.bool(false, title="Hide candles extending beyond view", display=display.none,
                             tooltip="Hides HTF candles whose close has not yet passed the right edge of the visible chart. Useful for manual backtesting by scrolling — prevents seeing future candle close prices.")

// VARIABLES

htf_seconds = timeframe.in_seconds(higher_timeframe)
chart_seconds = timeframe.in_seconds()

// An intraday HTF period is contiguous trading time, so the chart projects one
// empty slot per chart interval across the part of it that has not happened
// yet. Daily and above straddle overnight and weekend closures the chart never
// draws, so wall-clock time cannot be converted to slots there.
htf_is_intraday = htf_seconds < 86400

new_htf_candle_started = timeframe.change(higher_timeframe)

// True open/close timestamps of the HTF bar containing this chart bar. These are
// session-aware: when a session ends part-way through an HTF period (e.g. a 4H
// period on an 11-hour session) time_close returns the real, shortened close
// rather than open + htf_seconds. Deriving the candle's width from these instead
// of from a chart-bar count avoids assuming every HTF period holds the same
// number of chart bars — an assumption 4H breaks on most session-based symbols.
htf_open_time = time(higher_timeframe)
htf_close_time = time_close(higher_timeframe)

var float current_htf_open_price = na
var float current_htf_high_price = na
var float current_htf_low_price = na
var float current_htf_close_price = na

// The wick belongs at the visual centre of the body, which is the middle chart
// *bar* of the HTF period — not the middle of its time range. The x axis is
// linear in bars, so any gap inside the period pulls the two apart.
//
// Two kinds of gap do this. A weekly period swallows a whole weekend: its
// calendar midpoint falls near Thursday's open, roughly 60% of the way across
// the five sessions actually drawn. And on any timeframe, a symbol that goes
// untraded for an interval gets no bar for it at all — a thin instrument can
// drop a quarter of its minutes inside a single hour. Bar space is therefore
// the only honest space for the wick, on every HTF, not just W.
var int htf_start_bar = na
var int htf_duration_ms = na
var int prev_htf_bar_count = na
var int prev_htf_duration_ms = na

// Chart bars the current HTF period is expected to hold. Used only to centre the
// live candle's wick on a daily-or-higher HTF, where the remaining span crosses
// closures the chart does not draw and so cannot be projected from the clock.
// Completed candles are re-centred exactly once their bar count is known.
// Scaling the previous period's count by the ratio of durations
// keeps the estimate honest when consecutive periods differ in length, which is
// the session-truncated 4H stub case a raw bar count got wrong.
estimate_period_bars(int prev_count, int prev_ms, int cur_ms) =>
    int raw = na(prev_count) or na(prev_ms) or prev_ms <= 0 or na(cur_ms)
         ? int(cur_ms / (chart_seconds * 1000))
         : int(math.round(prev_count * (cur_ms / float(prev_ms))))
    math.max(raw, 1)

// Middle bar of the live candle, in the bar space the body is actually drawn in.
//
// The body's two edges resolve differently and cannot be averaged in clock time.
// Its left edge is a real bar at start_bar. Its right edge is a timestamp in the
// future, which the chart projects at one slot per chart interval. The elapsed
// half is therefore however many bars actually *printed* — a symbol with no
// trades in a given minute gets no bar for it, so that half is narrower than the
// clock says — while the projected half is always full density.
//
// Measuring the elapsed half rather than predicting it also makes this
// self-correcting: every new bar re-reads the real count, so the wick converges
// on the true centre instead of inheriting the previous period's error.
//
// Half of the span, not of span - 1: the body runs from the open time, at
// start_bar, to the close time, which is the first slot of the *next* period.
// So it straddles span + 1 positions and its centre is start_bar + span / 2.
//
// An odd span has no bar at that centre — a 5m period on a 1m chart holds bars
// at offsets 0..4 and wants offset 2.5 — so the half has to be truncated, not
// rounded. Rounding breaks every such tie upward and lands the wick a full bar
// right of the period's middle bar, which is the whole of why a 5m candle's wick
// printed on its 4th bar. int() truncates toward zero and both spans here are
// non-negative, so it floors.
//
// Clamped because bar_index drawings cannot reach past 500 bars into the future.
live_centre_bar(int start_bar) =>
    int remaining = htf_is_intraday
         ? int(math.round((htf_close_time - time) / (chart_seconds * 1000.0)))
         : math.max(estimate_period_bars(prev_htf_bar_count, prev_htf_duration_ms, htf_duration_ms) - (bar_index - start_bar), 0)
    int right_bar = bar_index + math.max(remaining, 0)
    math.min(start_bar + int((right_bar - start_bar) / 2.0), bar_index + 499)

var box visible_candle_body = na
var line upper_shadow_line = na
var line lower_shadow_line = na
var line midline = na

var color current_fill_color = na
var color current_line_color = na
var label countdown_label = na

// Arrays for tracking all HTF candle objects (used for dynamic hide/show based on viewport)
var box[] all_htf_boxes = array.new<box>()
var line[] all_htf_upper_wicks = array.new<line>()
var line[] all_htf_lower_wicks = array.new<line>()
var line[] all_htf_midlines = array.new<line>()  // na entries when the midline is disabled
var int[] all_htf_close_times = array.new<int>()  // ms; session-aware close, exact from creation
var bool[] all_htf_is_bullish = array.new<bool>()

// CANDLE RENDERING

// Only render if chart timeframe is less than the higher timeframe
htf_is_higher = chart_seconds < htf_seconds

if htf_is_higher and new_htf_candle_started and not na(htf_open_time) and not na(htf_close_time)
    // The previous candle's box needs no finalizing: it was drawn to its true
    // close time from the start. Its wick does — until now it sat at an
    // estimated centre, and the exact bar count has only just become known.
    if not na(htf_start_bar)
        closed_bar_count = bar_index - htf_start_bar
        closed_idx = array.size(all_htf_boxes) - 1
        if closed_idx >= 0 and closed_bar_count > 0
            // Truncated, not rounded, for the same reason as live_centre_bar:
            // an odd bar count has no centre bar and rounding always biases the
            // wick a bar to the right.
            exact_centre = htf_start_bar + int(closed_bar_count / 2.0)
            closed_upper = array.get(all_htf_upper_wicks, closed_idx)
            closed_lower = array.get(all_htf_lower_wicks, closed_idx)
            if not na(closed_upper)
                line.set_x1(closed_upper, exact_centre)
                line.set_x2(closed_upper, exact_centre)
            if not na(closed_lower)
                line.set_x1(closed_lower, exact_centre)
                line.set_x2(closed_lower, exact_centre)
        prev_htf_bar_count := closed_bar_count
        prev_htf_duration_ms := htf_duration_ms

    htf_start_bar := bar_index
    htf_duration_ms := htf_close_time - htf_open_time
    wick_bar = live_centre_bar(htf_start_bar)

    current_htf_open_price := open
    current_htf_high_price := high
    current_htf_low_price := low
    current_htf_close_price := close

    is_bullish = current_htf_close_price >= current_htf_open_price
    current_fill_color := is_bullish ? bullish_fill_color : bearish_fill_color
    current_line_color := is_bullish ? bullish_line_color : bearish_line_color

    // Span the box across the HTF period's real time range. xloc.bar_time is
    // required here: the right edge sits in the future, and bar_index-based
    // drawings are capped ~500 bars ahead.
    new_box = box.new(
         left=htf_open_time,
         right=htf_close_time,
         xloc=xloc.bar_time,
         top=math.max(current_htf_open_price, current_htf_close_price),
         bottom=math.min(current_htf_open_price, current_htf_close_price),
         bgcolor=current_fill_color,
         border_color=current_line_color,
         border_width=line_thickness,
         border_style=line_style
     )
    visible_candle_body := new_box

    // Wick centered on the middle chart bar of the HTF period
    upper_shadow_line := line.new(
         x1=wick_bar,
         y1=math.max(current_htf_open_price, current_htf_close_price),
         x2=wick_bar,
         y2=current_htf_high_price,
         xloc=xloc.bar_index,
         color=current_line_color,
         width=line_thickness,
         style=line_style
     )

    lower_shadow_line := line.new(
         x1=wick_bar,
         y1=math.min(current_htf_open_price, current_htf_close_price),
         x2=wick_bar,
         y2=current_htf_low_price,
         xloc=xloc.bar_index,
         color=current_line_color,
         width=line_thickness,
         style=line_style
     )

    // Midline spans the candle's real time range, like the box — its x edges are
    // fixed for the whole period, so only its price level moves as the range
    // develops. That is why it is updated in place rather than redrawn like the
    // wicks, whose centre bar shifts.
    line new_midline = na
    if show_midline
        mid_price = (current_htf_high_price + current_htf_low_price) / 2
        new_midline := line.new(
             x1=htf_open_time,
             y1=mid_price,
             x2=htf_close_time,
             y2=mid_price,
             xloc=xloc.bar_time,
             color=current_line_color,
             width=line_thickness,
             style=midline_style
         )
    midline := new_midline

    // Track new candle in arrays. The close time is exact, so it never needs revising.
    array.push(all_htf_boxes, new_box)
    array.push(all_htf_upper_wicks, upper_shadow_line)
    array.push(all_htf_lower_wicks, lower_shadow_line)
    array.push(all_htf_midlines, new_midline)
    array.push(all_htf_close_times, htf_close_time)
    array.push(all_htf_is_bullish, is_bullish)

else if htf_is_higher and not na(current_htf_open_price)
    current_htf_high_price := math.max(current_htf_high_price, high)
    current_htf_low_price := math.min(current_htf_low_price, low)
    current_htf_close_price := close

    is_bullish = current_htf_close_price >= current_htf_open_price
    current_fill_color := is_bullish ? bullish_fill_color : bearish_fill_color
    current_line_color := is_bullish ? bullish_line_color : bearish_line_color

    // The box's left/right edges are fixed for the whole HTF period; only the
    // body extent and colour move as price develops.
    if not na(visible_candle_body)
        box.set_top(visible_candle_body, math.max(current_htf_open_price, current_htf_close_price))
        box.set_bottom(visible_candle_body, math.min(current_htf_open_price, current_htf_close_price))
        box.set_bgcolor(visible_candle_body, current_fill_color)
        box.set_border_color(visible_candle_body, current_line_color)

    if not na(upper_shadow_line)
        line.delete(upper_shadow_line)
    if not na(lower_shadow_line)
        line.delete(lower_shadow_line)

    top_price = math.max(current_htf_open_price, current_htf_close_price)
    bottom_price = math.min(current_htf_open_price, current_htf_close_price)

    wick_bar = live_centre_bar(htf_start_bar)

    // Always create wicks (they'll be zero-length if high/low equals body edge)
    upper_shadow_line := line.new(
         x1=wick_bar,
         y1=top_price,
         x2=wick_bar,
         y2=current_htf_high_price,
         xloc=xloc.bar_index,
         color=current_line_color,
         width=line_thickness,
         style=line_style
     )

    lower_shadow_line := line.new(
         x1=wick_bar,
         y1=bottom_price,
         x2=wick_bar,
         y2=current_htf_low_price,
         xloc=xloc.bar_index,
         color=current_line_color,
         width=line_thickness,
         style=line_style
     )

    if not na(midline)
        mid_price = (current_htf_high_price + current_htf_low_price) / 2
        line.set_y1(midline, mid_price)
        line.set_y2(midline, mid_price)
        line.set_color(midline, current_line_color)

    // Keep current candle's array entry up to date (wicks are deleted/recreated each bar)
    last_idx = array.size(all_htf_boxes) - 1
    if last_idx >= 0
        array.set(all_htf_upper_wicks, last_idx, upper_shadow_line)
        array.set(all_htf_lower_wicks, last_idx, lower_shadow_line)
        array.set(all_htf_is_bullish, last_idx, is_bullish)

// HIDE/SHOW LOGIC
//
// chart.right_visible_bar_time updates as the user scrolls and triggers a recalc on barstate.islast.
// On each recalc we iterate all tracked candles and hide any whose close time is beyond the right
// edge of the visible chart. When hide_incomplete is off, all candles are restored to their colors.

if htf_is_higher and barstate.islast
    transparent = color.new(color.white, 100)
    n = array.size(all_htf_boxes)
    if n > 0
        for i = 0 to n - 1
            b = array.get(all_htf_boxes, i)
            close_time = array.get(all_htf_close_times, i)
            is_bull = array.get(all_htf_is_bullish, i)
            u = array.get(all_htf_upper_wicks, i)
            l = array.get(all_htf_lower_wicks, i)
            m = array.get(all_htf_midlines, i)

            should_hide = hide_incomplete and (not na(chart.right_visible_bar_time)) and (close_time > chart.right_visible_bar_time)

            fill_c   = should_hide ? transparent : (is_bull ? bullish_fill_color : bearish_fill_color)
            border_c = should_hide ? transparent : (is_bull ? bullish_line_color  : bearish_line_color)
            wick_c   = should_hide ? transparent : (is_bull ? bullish_line_color  : bearish_line_color)

            if not na(b)
                box.set_bgcolor(b, fill_c)
                box.set_border_color(b, border_c)
            if not na(u)
                line.set_color(u, wick_c)
            if not na(l)
                line.set_color(l, wick_c)
            if not na(m)
                line.set_color(m, wick_c)

// COUNTDOWN TIMER

format_countdown(seconds) =>
    int s = int(seconds)
    int d = int(s / 86400)
    int h = int((s % 86400) / 3600)
    int m = int((s % 3600) / 60)
    string result = ""
    if d > 0
        result += str.tostring(d) + "d"
    if d > 0 or h > 0
        result += str.tostring(h) + "h"
    result += str.tostring(m) + "m"
    result

if htf_is_higher and show_countdown and barstate.islast and not na(current_htf_open_price)
    // Calculate time remaining until HTF candle closes
    int remaining_ms = htf_close_time - timenow
    int remaining_s = int(math.max(0, remaining_ms / 1000))

    countdown_text = format_countdown(remaining_s)

    // Position label centered within the visible portion of the candle (time domain)
    // Using xloc.bar_time avoids bar-index estimation errors from non-trading gaps
    vis_left_time = math.max(htf_open_time, chart.left_visible_bar_time)
    vis_right_time = math.min(htf_close_time, chart.right_visible_bar_time)
    label_x = int(math.round((vis_left_time + vis_right_time) / 2.0))

    top_price = math.max(current_htf_open_price, current_htf_close_price)
    bottom_price = math.min(current_htf_open_price, current_htf_close_price)
    label_y = switch countdown_position_input
        "Top" => top_price
        "Bottom" => bottom_price
        => (top_price + bottom_price) / 2

    label_valign = switch countdown_position_input
        "Top" => label.style_label_down
        "Bottom" => label.style_label_up
        => label.style_label_center

    if not na(countdown_label)
        label.delete(countdown_label)

    countdown_label := label.new(
         x=label_x,
         xloc=xloc.bar_time,
         y=label_y,
         text=countdown_text,
         color=color.new(color.black, 100),
         textcolor=countdown_color,
         style=label_valign,
         size=size.normal
     )

Overview

HTF Candles automatically selects the next higher timeframe or allows manual timeframe selection. The indicator draws candlestick bodies using boxes, wicks using vertical lines, and an optional midpoint line representing the equilibrium range of each higher timeframe bar. Customization settings include colors, line styles, fill transparency, and a candle countdown timer. Due to platform element limits, older wicks and midlines drop off before candlestick bodies.

Details

Published by

haydenfowler on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Higher TimeframestringAutohigher_timeframe_input
Bullish Fill Colorcolorcolor.new(color.green, 95)bullish_fill_color
Bullish Line Colorcolorcolor.new(color.green, 65)bullish_line_color
Bearish Fill Colorcolorcolor.new(color.red, 96)bearish_fill_color
Bearish Line Colorcolorcolor.new(color.rgb(255,120,120), 70)bearish_line_color
Line Thicknessint1line_thickness
Line StylestringSolidline_style_input
Show Midlinebooltrueshow_midline
Midline StylestringDashedmidline_style_input
Show Countdown Timerboolfalseshow_countdown
Countdown Text Colorcolorcolor.whitecountdown_color
Countdown PositionstringMiddlecountdown_position_input
Show all 13 settings
SettingTypeDefaultVariable
Hide candles extending beyond viewboolfalsehide_incomplete
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

[RS]MTF Candle Sticks

by ricardosantos79
261 stars

This indicator overlays up to five higher-timeframe candlestick groups on the price chart. For each enabled timeframe it requests open, high, low, and close and can show up to five candles, offset by a spacing setting. The main inputs set the candle count, the

Indicator v4 Candlestick patternsSupport & resistance Repaints
Updated 5 years ago · None stated GitHub repository of [RS]MTF Candle Sticks

Candlestick Patterns

by harryguiacorn
220 stars

This indicator plots optional candlestick pattern signals on the price chart. It detects engulfing bars, inside bars, HOLP and LOHP, kicker patterns, body-mass extremes, higher highs and lower lows, ATR warnings, and four-bar fractals. Optional pivot marks use

Indicator v5 Candlestick patternsVolatility & bands
Updated 1 year ago · None stated GitHub repository of Candlestick Patterns

Strat Assistant

by rickyzcarroll
90 stars

The Strat Assistant indicator identifies candlestick patterns from the STRAT methodology on the price chart. It detects inside bars, 2-candle directional bars, 3-candle outside bars, and sequences like 212 and 222 for continuations and reversals. Shapes such a

Indicator v4 Candlestick patternsSupport & resistance
Updated 5 years ago · None stated GitHub repository of Strat Assistant
56 stars

This overlay indicator highlights candles with a body smaller than 50% of their total range by coloring them white on the price chart. Simultaneously, it calculates and plots horizontal lines for open prices across multiple higher timeframes, such as daily, we

Indicator v6 Support & resistanceCandlestick patterns Repaints
Updated 3 months ago · None stated GitHub repository of Daily Weekly Monthly Yearly Opens

This Pine Script indicator identifies liquidity sweeps and confirms signals using a close-back candle pattern directly on the price chart. It tracks recent swing highs and lows over a customizable lookback period. A bullish signal forms when a prior bar sweeps

Indicator v6 SMC / ICT / price actionSupport & resistance
Updated 3 months ago · MPL-2.0 GitHub repository of Liquidity Sweep + Close-Back Confirmation

8020 System Indicator

by TamaraKGreen
47 stars

This overlay indicator draws 80/20 price levels and optional 40-point zone bands on the price chart. It marks repairs, cross sections, and forks with optional letter labels, and can highlight confluence when those marks sit near a level. Separate options shade

Indicator v6 Support & resistanceCandlestick patterns
Updated 2 months ago · None stated GitHub repository of 8020 System Indicator

More Candlestick patterns scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers