HalfTrend Breakout [NovaLens]

NovaLens · study · 785 行 · 点赞 36 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script source code is subject to the Mozilla Public License 2.0.
// Copyright NovaLens
//@version=6
// HalfTrend Breakout [NovaLens]: HalfTrend (Everget's method) as the trend band, with Bill Williams fractal breakouts in the
// trend's direction, each graded by its bar's recorded volume against its prior volume average; inspired by BigBeluga's
// HalfTrend Fractal Breakout Engine. Credits: BigBeluga (concept), Everget (HalfTrend method), Bill Williams (fractals).
// NovaLens adds profiles, the flip arrow, the graded breakout diamond, the panel, tooltips, confirmed events and alerts.
// Picture: the band on price with a crisp line, one short soft edge and a fill that fades toward price; a small arrow where the
// band turns, a smaller, lighter diamond on the first heavy-volume swing break of each trend, and a three-row reading panel.
// Repaint: the band and its colour update on the live candle and finalize on close; arrows, diamonds, level lines, the panel
// and alerts use closed candles only. The first 150 candles of each price segment are a warm-up.
indicator("HalfTrend Breakout [NovaLens]", shorttitle="HalfTrend Breakout [NovaLens]", overlay=true, precision=2, max_labels_count=500, max_lines_count=500, max_bars_back=300)
 
const string BUILD_TOKEN = "4ac4e935e9f7"
 
// ==== KIT T6 START ====
// T6 theme presets. Every colour the kit draws is defined here, once per theme; no hex appears outside this block.
// Roles: bull, bear, neutral (direction), extreme high and extreme low (rare levels), the reading panel's base, inks, frame and inner border.
// The panel values are the TV-35 v12 panel's (LESSON 13.11): base, title, label and value inks, frame and inner border, dark and light.
// Light values are darkened so lines reach 3:1 and text 4.5:1 on white; the design-kit tests recompute every ratio from these hex values.
// The light bull and bear text grades are the first darker step on the same hue and saturation (HSL lightness only) that reads 4.5:1 on the v12 light panel base.
// HalfTrend Breakout direction values (owner direction 2): up teal, down magenta red, with same-hue light and text roles;
// the dark caption ink is the first lighter step of the house caption that reads 4.5:1 on both dark backgrounds (Decisions row 27).
const color KIT_BULL_DARK = #04B491
const color KIT_BULL_LIGHT = #04A887
const color KIT_BULL_DARK_TEXT = #05D9AF
const color KIT_BULL_LIGHT_TEXT = #03866C
const color KIT_BEAR_DARK = #FF0055
const color KIT_BEAR_LIGHT = #FF0055
const color KIT_BEAR_DARK_TEXT = #FF80AA
const color KIT_BEAR_LIGHT_TEXT = #EB004E
const color KIT_NEUTRAL_DARK = #787B86
const color KIT_NEUTRAL_LIGHT = #787B86
const color KIT_NEUTRAL_DARK_TEXT = #787B86
const color KIT_NEUTRAL_LIGHT_TEXT = #737681
const color KIT_EXT_HIGH_DARK = #FF9800
const color KIT_EXT_HIGH_LIGHT = #D68000
const color KIT_EXT_LOW_DARK = #42A5F5
const color KIT_EXT_LOW_LIGHT = #3D99E4
const color KIT_TABLE_BASE_DARK = #363A45
const color KIT_TABLE_BASE_LIGHT = #FAFAFC
const color KIT_TITLE_INK_DARK = #FFFFFF
const color KIT_TITLE_INK_LIGHT = #0F1423
const color KIT_LABEL_INK_DARK = #9B9DA5
const color KIT_LABEL_INK_LIGHT = #5A5F73
const color KIT_VALUE_INK_DARK = #FFFFFF
const color KIT_VALUE_INK_LIGHT = #191E2D
const color KIT_TABLE_FRAME_DARK = #787B86
const color KIT_TABLE_FRAME_LIGHT = #AAAFBE
const color KIT_TABLE_BORDER_DARK = #787B86
const color KIT_TABLE_BORDER_LIGHT = #C8CDD7
const color KIT_INK_BLACK = #000000
const color KIT_INK_WHITE = #FFFFFF
// Transparency (0 opaque, 100 invisible) of the theme-level fills that carry text or a weak line, and of the panel chrome.
const int KIT_TABLE_BASE_FADE_DARK = 15
const int KIT_TABLE_BASE_FADE_LIGHT = 10
const int KIT_TABLE_FRAME_FADE_DARK = 30
const int KIT_TABLE_FRAME_FADE_LIGHT = 30
const int KIT_TABLE_BORDER_FADE_DARK = 50
const int KIT_TABLE_BORDER_FADE_LIGHT = 40
const int KIT_WEAK_FADE_DARK = 25
const int KIT_WEAK_FADE_LIGHT = 15
// Structure ink (zero line, levels) is the chart's own text colour at a fixed fade, so it follows any theme.
const int KIT_ZERO_FADE = 80
const int KIT_LEVEL_FADE = 60
 
type KitPalette
    bool light
    color up
    color down
    color flat
    color high
    color low
    color upText
    color downText
    color flatText
    color upWeak
    color downWeak
    color base
    color labelInk
    color valueInk
    color titleInk
    color frame
    color border
 
// Auto reads the chart background: an average channel above 128 is a light chart.
kitIsLight(string theme) =>
    float bgAverage = (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3.0
    theme == "Light" or (theme == "Auto" and bgAverage > 128.0)
 
// A colour the user left at its dark default switches to the light value on a light chart; a colour the user changed is kept.
kitPick(color userColor, color darkDefault, color lightValue, bool light) =>
    light and userColor == darkDefault ? lightValue : userColor
 
// HalfTrend Breakout: a direction left at its default uses the dark text role for words on a dark chart (panel words read 4.5:1).
kitPalette(string theme, color upIn, color downIn, color flatIn, color highIn, color lowIn) =>
    bool light = kitIsLight(theme)
    color upText = upIn == KIT_BULL_DARK ? (light ? KIT_BULL_LIGHT_TEXT : KIT_BULL_DARK_TEXT) : upIn
    color downText = downIn == KIT_BEAR_DARK ? (light ? KIT_BEAR_LIGHT_TEXT : KIT_BEAR_DARK_TEXT) : downIn
    color flatText = kitPick(flatIn, KIT_NEUTRAL_DARK, KIT_NEUTRAL_LIGHT_TEXT, light)
    int weakFade = light ? KIT_WEAK_FADE_LIGHT : KIT_WEAK_FADE_DARK
    color upWeakBase = light and upIn == KIT_BULL_DARK ? KIT_BULL_LIGHT_TEXT : upIn
    color downWeakBase = light and downIn == KIT_BEAR_DARK ? KIT_BEAR_LIGHT_TEXT : downIn
    KitPalette.new(light, kitPick(upIn, KIT_BULL_DARK, KIT_BULL_LIGHT, light), kitPick(downIn, KIT_BEAR_DARK, KIT_BEAR_LIGHT, light), kitPick(flatIn, KIT_NEUTRAL_DARK, KIT_NEUTRAL_LIGHT, light), kitPick(highIn, KIT_EXT_HIGH_DARK, KIT_EXT_HIGH_LIGHT, light), kitPick(lowIn, KIT_EXT_LOW_DARK, KIT_EXT_LOW_LIGHT, light), upText, downText, flatText, color.new(upWeakBase, weakFade), color.new(downWeakBase, weakFade), light ? color.new(KIT_TABLE_BASE_LIGHT, KIT_TABLE_BASE_FADE_LIGHT) : color.new(KIT_TABLE_BASE_DARK, KIT_TABLE_BASE_FADE_DARK), light ? KIT_LABEL_INK_LIGHT : KIT_LABEL_INK_DARK, light ? KIT_VALUE_INK_LIGHT : KIT_VALUE_INK_DARK, light ? KIT_TITLE_INK_LIGHT : KIT_TITLE_INK_DARK, light ? color.new(KIT_TABLE_FRAME_LIGHT, KIT_TABLE_FRAME_FADE_LIGHT) : color.new(KIT_TABLE_FRAME_DARK, KIT_TABLE_FRAME_FADE_DARK), light ? color.new(KIT_TABLE_BORDER_LIGHT, KIT_TABLE_BORDER_FADE_LIGHT) : color.new(KIT_TABLE_BORDER_DARK, KIT_TABLE_BORDER_FADE_DARK))
 
// Line and mark colour for a direction (+1, -1, 0) and a strength step (1 weak, 2 normal, 3 strong).
kitDirColor(KitPalette p, int dir, int step) =>
    dir > 0 ? (step <= 1 ? p.upWeak : p.up) : dir < 0 ? (step <= 1 ? p.downWeak : p.down) : p.flat
 
// Text colour for a direction word on the table or a pill.
kitDirText(KitPalette p, int dir) =>
    dir > 0 ? p.upText : dir < 0 ? p.downText : p.valueInk
 
// Black or white, whichever reads better on a filled cell or pill (WCAG relative luminance).
kitChannel(float channel) =>
    float v = channel / 255.0
    v <= 0.04045 ? v / 12.92 : math.pow((v + 0.055) / 1.055, 2.4)
kitInkOn(color fillColor) =>
    float lum = 0.2126 * kitChannel(color.r(fillColor)) + 0.7152 * kitChannel(color.g(fillColor)) + 0.0722 * kitChannel(color.b(fillColor))
    (lum + 0.05) / 0.05 >= 1.05 / (lum + 0.05) ? KIT_INK_BLACK : KIT_INK_WHITE
 
kitStructure(int fade) =>
    color.new(chart.fg_color, fade)
// HalfTrend Breakout additions (per-indicator constants; the kit lines above keep their structure).
// Band fill: the direction colour at this transparency at the band, fully clear at the candles' middle (owner direction 2).
const int HB_FILL_FADE_BAND = 90
const int HB_FILL_FADE_CLEAR = 100
// Short soft edge of the band in Look Clean: one plot two pixels wider than the line (four at Normal) at this transparency.
const int HB_EDGE_FADE = 90
const int HB_EDGE_EXTRA = 2
const int HB_STUB_FADE = 15
// Breakout diamond ink by theme (graphic role, at least 3:1 on the chart background and on the band fill): dark charts use the
// direction colour at these fades, light charts the darker text grade of the same hue; a missing grade uses the neutral colour.
const int HB_DIAMOND_FADE_UP_DARK = 30
const int HB_DIAMOND_FADE_DOWN_DARK = 15
const int HB_DIAMOND_FADE_LIGHT = 10
const int HB_DIAMOND_FADE_FLAT = 10
// ==== KIT T6 END ====
 
// ==== ENGINE INPUTS: groups "1. Profile", "2. Core" ====
// Input tooltips: one short line on what the setting does, then one line per option with its effect.
const string HB_TIP_PROFILE = "Sets how quickly the band turns with price.\n\n• Reactive (Amplitude 6, Channel Deviation 1.5): turns sooner, more flips.\n• Balanced (10, 2.0): the default.\n• Smooth (16, 2.5): turns later, fewer flips.\n• Custom: uses Amplitude and Channel Deviation below."
const string HB_TIP_AMP = "Sets how many candles the band looks back for its swing.\n\nHigher = slower turns and a calmer band. Counted in candles. Used when Profile = Custom."
const string HB_TIP_DEV = "Sets how far the band sits from price.\n\nHigher = the band sits further out and turns less often. Used when Profile = Custom."
const string HB_TIP_FLIPS = "Shows a small arrow where the band turns.\n\n• On: an arrow under the candle when the band turns up, above it when it turns down.\n• Off: no arrows. Alerts stay on."
const string HB_TIP_BREAK = "Picks which breakouts get a diamond on the chart.\n\n• 1st Heavy: the first heavy-volume break of each trend.\n• All Heavy: every heavy-volume break.\n• All: every break, sized by volume.\n• 1st break: the first break of each trend, any volume.\n• Off: no diamonds.\n\nHeavy = volume above 1.5x its prior 20-candle average. Alerts keep every breakout."
const string HB_TIP_LEVEL = "Shows the broken swing level as a dashed line.\n\n• On: a line from the swing candle to its diamond, ending at the breakout.\n• Off: diamonds only."
const string HB_TIP_BAND = "Shows the trend band on the price chart.\n\n• On: the band line, its soft edge and its fill.\n• Off: no band. Marks, panel and alerts stay."
const string HB_TIP_LOOK = "Sets how the band line is drawn.\n\n• Clean: a thin line with a short soft edge.\n• Bold: the thin line with a wide glow."
const string HB_TIP_FILL = "Shows a tinted fill from the band toward the candles.\n\n• On: darkest at the band, fading out before the candles' middle.\n• Off: the band line only."
const string HB_TIP_THEME = "Matches the colours to your chart background.\n\n• Auto: reads the chart background.\n• Dark: the set for dark charts.\n• Light: the set for light charts."
const string HB_TIP_PANEL = "Shows the reading panel: trend side, its age and the last shown mark.\n\n• On: the panel reads the last closed candle.\n• Off: no panel."
const string HB_TIP_POS = "Places the reading panel on the chart.\n\n• Top Right, Top Left: the top corners; Top Left adds space under the legend.\n• Btm Right (default), Btm Left: the bottom corners.\n• Mid Right: the middle of the right edge."
const string HB_TIP_PSIZE = "Sets the text size of the reading panel.\n\n• Small: one size smaller.\n• Normal: the default.\n• Large: one size larger."
const string HB_TIP_UP = "Colour of the band, arrows and diamonds while the band is up.\n\nIt shows direction, not a trade call. On a light chart the default switches to a darker teal."
const string HB_TIP_DOWN = "Colour of the band, arrows and diamonds while the band is down.\n\nIt shows direction, not a trade call. On a light chart, words use a darker red."
const string HB_TIP_FLAT = "Colour of a diamond on a candle with no volume.\n\nIt shows only when Breakout marks draws more than heavy-volume breaks."
hbProfileIn = input.string("Balanced", "Profile", options=["Reactive", "Balanced", "Smooth", "Custom"], group="1. Profile", display=display.none, tooltip=HB_TIP_PROFILE)
hbAmpIn = input.int(10, "Amplitude", minval=2, maxval=50, step=1, group="2. Core", active=hbProfileIn == "Custom", display=display.none, tooltip=HB_TIP_AMP)
hbDevIn = input.float(2.0, "Channel Deviation", minval=0.5, maxval=5.0, step=0.1, group="2. Core", active=hbProfileIn == "Custom", display=display.none, tooltip=HB_TIP_DEV)
 
// ENGINE: source-neutral contract (HalfTrend switch, Wilder ATR channel, five-bar fractals, prior-window volume ratio)
const int HB_READY_BARS = 150
const int HB_RV_BARS = 20
const int HB_SLOW_ATR = 100
const int HB_MARK_ATR = 14
hbCustom = hbProfileIn == "Custom"
hbAmp = hbCustom ? hbAmpIn : hbProfileIn == "Reactive" ? 6 : hbProfileIn == "Smooth" ? 16 : 10
hbDev = hbCustom ? hbDevIn : hbProfileIn == "Reactive" ? 1.5 : hbProfileIn == "Smooth" ? 2.5 : 2.0
 
// Strict order with no comparison tolerance: true only when a is above b; false when either is missing.
hbAbove(float a, float b) =>
    math.sign(a - b) > 0
hbMax(float a, float b) =>
    na(a) ? b : na(b) ? a : math.max(a, b)
hbMin(float a, float b) =>
    na(a) ? b : na(b) ? a : math.min(a, b)
 
// Price segment: a candle with any missing open, high, low or close (or a non-standard chart) ends it; the next complete candle is index 0.
hbValidBar = chart.is_standard and not na(open) and not na(high) and not na(low) and not na(close)
var int hbLocal = -1
hbLocal := hbValidBar ? hbLocal + 1 : -1
hbHasPrior = hbLocal >= 1
 
// Wilder average range, restarted at the start of every price segment.
hbRange = hbLocal == 0 ? high - low : math.max(high - low, math.abs(high - close[1]), math.abs(low - close[1]))
hbWilder(float src, int len, int localIndex) =>
    var float acc = 0.0
    var float value = na
    if localIndex < 0
        acc := 0.0
        value := na
    else if localIndex == 0
        acc := src
        value := len == 1 ? src : na
    else if localIndex < len
        acc += src
        value := localIndex == len - 1 ? acc / len : na
    else
        value := (1.0 / len) * src + (1 - 1.0 / len) * value
    value
atrSlow = hbWilder(hbRange, HB_SLOW_ATR, hbLocal)
atrMark = hbWilder(hbRange, HB_MARK_ATR, hbLocal)
 
hbFull = hbLocal >= hbAmp - 1
hbTopAll = ta.highest(high, hbAmp)
hbBottomAll = ta.lowest(low, hbAmp)
hbMeanHighAll = ta.sma(high, hbAmp)
hbMeanLowAll = ta.sma(low, hbAmp)
winTop = hbFull ? hbTopAll : na
winBottom = hbFull ? hbBottomAll : na
meanHigh = hbFull ? hbMeanHighAll : na
meanLow = hbFull ? hbMeanLowAll : na
hbPrevHigh = hbHasPrior ? high[1] : high
hbPrevLow = hbHasPrior ? low[1] : low
 
// Everget's switch as rules: a rising leg ends when the high average falls under the highest recent low and price closes under the prior low.
var int swingDir = 1
var bool seekFalling = false
var float floorPeak = na
var float ceilTrough = na
var float baseline = na
bool hbSwitch = false
if hbLocal < 0
    swingDir := 1
    seekFalling := false
    floorPeak := na
    ceilTrough := na
    baseline := na
else
    if hbLocal == 0
        swingDir := 1
        seekFalling := false
        floorPeak := low
        ceilTrough := high
    int dirBefore = swingDir
    if seekFalling
        floorPeak := hbMax(floorPeak, winBottom)
        if hbAbove(floorPeak, meanHigh) and hbAbove(hbPrevLow, close)
            swingDir := -1
            seekFalling := false
            ceilTrough := winTop
    else
        ceilTrough := hbMin(ceilTrough, winTop)
        if hbAbove(meanLow, ceilTrough) and hbAbove(close, hbPrevHigh)
            swingDir := 1
            seekFalling := true
            floorPeak := winBottom
    hbSwitch := hbLocal > 0 and swingDir != dirBefore
    if hbLocal == 0
        baseline := low
    else if not hbSwitch
        baseline := swingDir == 1 ? hbMax(floorPeak, baseline) : hbMin(ceilTrough, baseline)
 
upperBand = hbLocal >= 0 ? baseline + hbDev * atrSlow / 2 : na
lowerBand = hbLocal >= 0 ? baseline - hbDev * atrSlow / 2 : na
 
// Regime: a close through the far side of the band assigns it; a flip is only a change of the assigned side.
var int regime = -1
if hbLocal <= 0
    regime := -1
int regimeBefore = regime
hbBandsKnown = hbHasPrior and not na(upperBand) and not na(lowerBand) and not na(upperBand[1]) and not na(lowerBand[1])
hbCrossUp = hbBandsKnown and hbAbove(close, upperBand) and not hbAbove(close[1], upperBand[1])
hbCrossDown = hbBandsKnown and hbAbove(lowerBand, close) and not hbAbove(lowerBand[1], close[1])
if hbCrossUp
    regime := 1
else if hbCrossDown
    regime := -1
flip = hbHasPrior and regime != regimeBefore
var int hbFlipBar = na
if hbLocal <= 0
    hbFlipBar := na
if flip
    hbFlipBar := bar_index
 
// Five-bar fractals (two candles each side, strict), detected two candles after the swing candle.
swingTopSeen = hbLocal >= 4 and hbAbove(high[2], high[4]) and hbAbove(high[2], high[3]) and hbAbove(high[2], high[1]) and hbAbove(high[2], high)
swingBottomSeen = hbLocal >= 4 and hbAbove(low[4], low[2]) and hbAbove(low[3], low[2]) and hbAbove(low[1], low[2]) and hbAbove(low, low[2])
 
// One pending level per side: register, clear both on an actual flip, then test and consume.
var float pendingHigh = na
var float pendingLow = na
var int pendingHighBar = na
var int pendingLowBar = na
var int pendingHighTime = na
var int pendingLowTime = na
var int pendingHighSeen = na
var int pendingLowSeen = na
if hbLocal <= 0
    pendingHigh := na
    pendingLow := na
if swingTopSeen and regime == 1
    pendingHigh := high[2]
    pendingHighBar := bar_index - 2
    pendingHighTime := time[2]
    pendingHighSeen := time
if swingBottomSeen and regime == -1
    pendingLow := low[2]
    pendingLowBar := bar_index - 2
    pendingLowTime := time[2]
    pendingLowSeen := time
if flip
    pendingHigh := na
    pendingLow := na
breakoutUp = hbLocal >= 0 and regime == 1 and not na(pendingHigh) and hbAbove(close, pendingHigh)
breakoutDown = hbLocal >= 0 and not breakoutUp and regime == -1 and not na(pendingLow) and hbAbove(pendingLow, close)
float eventLevel = na
int eventSwingBar = na
int eventSwingTime = na
int eventSeenTime = na
if breakoutUp
    eventLevel := pendingHigh
    eventSwingBar := pendingHighBar
    eventSwingTime := pendingHighTime
    eventSeenTime := pendingHighSeen
    pendingHigh := na
if breakoutDown
    eventLevel := pendingLow
    eventSwingBar := pendingLowBar
    eventSwingTime := pendingLowTime
    eventSeenTime := pendingLowSeen
    pendingLow := na
 
// RV20: this candle's volume over the plain average of its 20 prior candles (never repaired from price, never segment-restarted).
// The prior window is kept as a rolling sum of its finite volumes with counts of missing and non-zero values: each bar adds the
// candle that enters the window and removes the one that leaves it. A window with no non-zero volume averages exactly zero.
hbPriorVolume() =>
    float total = 0.0
    bool complete = bar_index >= HB_RV_BARS
    if complete
        for i = 1 to HB_RV_BARS
            float v = volume[i]
            if na(v)
                complete := false
                break
            total += v
    complete ? total / HB_RV_BARS : na
var float hbVolSum = 0.0
var int hbVolMissing = 0
var int hbVolNonZero = 0
if bar_index >= 1
    float vIn = volume[1]
    if na(vIn)
        hbVolMissing += 1
    else
        hbVolSum += vIn
        hbVolNonZero += vIn != 0 ? 1 : 0
if bar_index > HB_RV_BARS
    float vOut = volume[HB_RV_BARS + 1]
    if na(vOut)
        hbVolMissing -= 1
    else
        hbVolSum -= vOut
        hbVolNonZero -= vOut != 0 ? 1 : 0
hbRollMean = bar_index >= HB_RV_BARS and hbVolMissing == 0 ? (hbVolNonZero == 0 ? 0.0 : hbVolSum / HB_RV_BARS) : na
hbRollRv = not na(volume) and not na(hbRollMean) and hbRollMean > 0 ? volume / hbRollMean : na
// A breakout candle, or a rolling reading within a billionth of a grade cut, takes the exact twenty-candle sum, so event values
// and every grade equal the direct sum.
hbExactRv = breakoutUp or breakoutDown or (not na(hbRollRv) and (math.abs(hbRollRv - 1.0) < 1e-9 or math.abs(hbRollRv - 1.5) < 1e-9))
hbPriorMean = hbExactRv ? hbPriorVolume() : hbRollMean
relVol = not na(volume) and not na(hbPriorMean) and hbPriorMean > 0 ? volume / hbPriorMean : na
// 0 = available, 1 = current volume missing, 2 = prior window incomplete or missing, 3 = prior average not positive.
hbVolCause = not na(relVol) ? 0 : na(volume) ? 1 : na(hbPriorMean) ? 2 : 3
// Grade step: 1 Light (at most 1.0x), 2 Middle (above 1.0x up to 1.5x), 3 Heavy (above 1.5x), 0 Unavailable.
hbStep(float rv) =>
    na(rv) ? 0 : math.sign(rv - 1.0) <= 0 ? 1 : math.sign(rv - 1.5) <= 0 ? 2 : 3
 
// Readiness: local index 150 onwards; before it nothing is drawn, read or alerted.
hbReady = hbValidBar and hbLocal >= HB_READY_BARS
drawnBand = hbReady and not flip ? (regime == 1 ? lowerBand : upperBand) : na
hbEventUp = hbReady and breakoutUp
hbEventDown = hbReady and breakoutDown
hbEvent = hbEventUp or hbEventDown
hbEventDir = hbEventUp ? 1 : hbEventDown ? -1 : 0
hbEventStep = hbEvent ? hbStep(relVol) : na
hbMarkRange = na(atrMark) ? high - low : atrMark
hbEventDist = hbEvent and not na(atrMark) and atrMark > 0 ? math.abs(close - eventLevel) / atrMark : na
 
// Data Window parity series (no visible graphics, no alert semantics).
plot(hbLocal >= 0 ? baseline : na, "HB Raw Line", display=display.data_window, editable=false)
plot(upperBand, "HB Raw Upper Band", display=display.data_window, editable=false)
plot(lowerBand, "HB Raw Lower Band", display=display.data_window, editable=false)
plot(hbLocal >= 0 ? regime : na, "HB Raw Regime", display=display.data_window, editable=false)
plot(pendingHigh, "HB Pending High", display=display.data_window, editable=false)
plot(pendingLow, "HB Pending Low", display=display.data_window, editable=false)
plot(relVol, "HB Raw RV20", display=display.data_window, editable=false)
plot(hbReady ? 1 : 0, "HB Ready", display=display.data_window, editable=false)
plot(drawnBand, "HB Drawn Band", display=display.data_window, editable=false)
plot(hbEvent ? hbEventDir : na, "HB Event Dir", display=display.data_window, editable=false)
plot(hbEvent ? eventLevel : na, "HB Event Level", display=display.data_window, editable=false)
plot(hbEvent ? relVol : na, "HB Event RV20", display=display.data_window, editable=false)
plot(hbEvent ? hbEventStep : na, "HB Event Grade Step", display=display.data_window, editable=false)
plot(hbEventDist, "HB Event Dist ATR", display=display.data_window, editable=false)
 
// ==== KIT T7 START ====
// T7 settings and alerts. Every input here changes only the picture; events and alerts are unchanged.
const string KIT_G_MARKS = "4. Marks"
const string KIT_G_DISPLAY = "5. Display"
const string KIT_G_COLOURS = "6. Colours"
 
hbShowFlips = input.bool(true, "Show flip marks", group=KIT_G_MARKS, display=display.none, tooltip=HB_TIP_FLIPS)
hbBreakMode = input.string("1st Heavy", "Breakout marks", options=["1st Heavy", "All Heavy", "All", "1st break", "Off"], group=KIT_G_MARKS, display=display.none, tooltip=HB_TIP_BREAK)
hbShowLevel = input.bool(true, "Show broken level", group=KIT_G_MARKS, active=hbBreakMode != "Off", display=display.none, tooltip=HB_TIP_LEVEL)
hbShowBand = input.bool(true, "Show band", group=KIT_G_DISPLAY, display=display.none, tooltip=HB_TIP_BAND)
kitLook = input.string("Clean", "Look", options=["Clean", "Bold"], group=KIT_G_DISPLAY, active=hbShowBand, display=display.none, tooltip=HB_TIP_LOOK)
hbShowFill = input.bool(true, "Show band fill", group=KIT_G_DISPLAY, active=hbShowBand, display=display.none, tooltip=HB_TIP_FILL)
kitTheme = input.string("Auto", "Theme", options=["Auto", "Dark", "Light"], group=KIT_G_DISPLAY, display=display.none, tooltip=HB_TIP_THEME)
hbShowPanel = input.bool(true, "Show Info Panel", group=KIT_G_DISPLAY, display=display.none, tooltip=HB_TIP_PANEL)
hbPanelPos = input.string("Btm Right", "Panel Position", options=["Top Right", "Top Left", "Btm Right", "Btm Left", "Mid Right"], group=KIT_G_DISPLAY, active=hbShowPanel, display=display.none, tooltip=HB_TIP_POS)
hbPanelSize = input.string("Normal", "Panel size", options=["Small", "Normal", "Large"], group=KIT_G_DISPLAY, active=hbShowPanel, display=display.none, tooltip=HB_TIP_PSIZE)
kitUpIn = input.color(KIT_BULL_DARK, "Up colour", group=KIT_G_COLOURS, display=display.none, tooltip=HB_TIP_UP)
kitDownIn = input.color(KIT_BEAR_DARK, "Down colour", group=KIT_G_COLOURS, display=display.none, tooltip=HB_TIP_DOWN)
kitFlatIn = input.color(KIT_NEUTRAL_DARK, "Neutral colour", group=KIT_G_COLOURS, display=display.none, tooltip=HB_TIP_FLAT)
 
// Built once and kept: changing an input or the theme recalculates the script; a chart background that turns light or dark
// without a recalculation is caught on the last bar, which rebuilds the palette.
var KitPalette kitPal = kitPalette(kitTheme, kitUpIn, kitDownIn, kitFlatIn, KIT_EXT_HIGH_DARK, KIT_EXT_LOW_DARK)
if barstate.islast and kitPal.light != kitIsLight(kitTheme)
    kitPal := kitPalette(kitTheme, kitUpIn, kitDownIn, kitFlatIn, KIT_EXT_HIGH_DARK, KIT_EXT_LOW_DARK)
kitBold = kitLook == "Bold"
 
// Bar-close gating: events, marks and alerts only on a closed candle at or after readiness.
hbGate = barstate.isconfirmed
hbAlertUp = hbGate and hbEventUp
hbAlertDown = hbGate and hbEventDown
hbAlertRegimeUp = hbGate and hbReady and flip and regime == 1
hbAlertRegimeDown = hbGate and hbReady and flip and regime == -1
 
alertcondition(hbAlertUp, "Breakout Up (Once Per Bar Close)", "HalfTrend Breakout [NovaLens]: Breakout Up on {{exchange}}:{{ticker}} {{interval}}. Close {{close}} is above the swing high {{plot(\"HB Event Level\")}} while the band is up. Volume {{plot(\"HB Event RV20\")}}x the average of its prior 20 bars, grade step {{plot(\"HB Event Grade Step\")}} (1 Light, 2 Middle, 3 Heavy, 0 Unavailable). Bar time {{time}}. Confirmed on bar close.")
alertcondition(hbAlertDown, "Breakout Down (Once Per Bar Close)", "HalfTrend Breakout [NovaLens]: Breakout Down on {{exchange}}:{{ticker}} {{interval}}. Close {{close}} is below the swing low {{plot(\"HB Event Level\")}} while the band is down. Volume {{plot(\"HB Event RV20\")}}x the average of its prior 20 bars, grade step {{plot(\"HB Event Grade Step\")}} (1 Light, 2 Middle, 3 Heavy, 0 Unavailable). Bar time {{time}}. Confirmed on bar close.")
alertcondition(hbAlertRegimeUp, "Regime Up (Once Per Bar Close)", "HalfTrend Breakout [NovaLens]: Regime Up on {{exchange}}:{{ticker}} {{interval}}. Close {{close}} is above the upper band and the band turned up. Grade: not applicable. Bar time {{time}}. Confirmed on bar close.")
alertcondition(hbAlertRegimeDown, "Regime Down (Once Per Bar Close)", "HalfTrend Breakout [NovaLens]: Regime Down on {{exchange}}:{{ticker}} {{interval}}. Close {{close}} is below the lower band and the band turned down. Grade: not applicable. Bar time {{time}}. Confirmed on bar close.")
 
// Dynamic route: one JSON message per confirmed event; every field is a string.
hbEsc(string s) =>
    str.replace_all(str.replace_all(s, "\\", "\\\\"), "\"", "\\\"")
hbTimeframe() =>
    timeframe.isdwm and str.length(timeframe.period) == 1 ? "1" + timeframe.period : timeframe.period
hbBarTime(int t) =>
    timeframe.isintraday ? str.format_time(t, "yyyy-MM-dd HH:mm", syminfo.timezone) : str.format_time(t, "yyyy-MM-dd", syminfo.timezone)
hbGradeWord(int step) =>
    step == 1 ? "Light" : step == 2 ? "Middle" : step == 3 ? "Heavy" : "Unavailable"
// One shared two-decimal RV formatter: "na" when unavailable (JSON), the raw text otherwise; the event's text is made once.
hbRvRaw(float rv) =>
    na(rv) ? "na" : str.tostring(rv, "0.00")
hbEventRvRaw = hbEvent ? hbRvRaw(relVol) : na
hbPayload(string eventName, float level, string rvText, string grade) =>
    "{\"brand\":\"NovaLens\",\"indicator\":\"HalfTrend Breakout\",\"event\":\"" + eventName + "\",\"ticker\":\"" + hbEsc(syminfo.prefix + ":" + syminfo.ticker) + "\",\"timeframe\":\"" + hbEsc(hbTimeframe()) + "\",\"price\":\"" + str.tostring(close, format.mintick) + "\",\"level\":\"" + str.tostring(level, format.mintick) + "\",\"rv\":\"" + rvText + "\",\"rv_bars\":\"20\",\"grade\":\"" + grade + "\",\"bar_time\":\"" + hbBarTime(time) + "\",\"confirmed\":\"bar close\"}"
if hbAlertUp
    alert(hbPayload("breakout_up", eventLevel, hbEventRvRaw, hbGradeWord(hbStep(relVol))), alert.freq_once_per_bar_close)
if hbAlertDown
    alert(hbPayload("breakout_down", eventLevel, hbEventRvRaw, hbGradeWord(hbStep(relVol))), alert.freq_once_per_bar_close)
if hbAlertRegimeUp
    alert(hbPayload("regime_up", upperBand, "na", "not applicable"), alert.freq_once_per_bar_close)
if hbAlertRegimeDown
    alert(hbPayload("regime_down", lowerBand, "na", "not applicable"), alert.freq_once_per_bar_close)
// ==== KIT T7 END ====
 
// ==== KIT T4 START ====
// T4 tooltips. House layout: a plain first block, a blank line, short blocks, the caveat last.
// The first two blocks use plain trader words: no digits, no units, no engine words (the kit lint checks every KIT_TIP_ constant).
// Numbers a trader uses go in one short block near the end, with plain names. Every head is a named KIT_TIP_ constant.
const string KIT_CAVEAT = "A reading, not an entry."
 
kitJoin(string first, string galSecond) =>
    first == "" ? galSecond : galSecond == "" ? first : first + "\n\n" + galSecond
 
// head = the two plain blocks; timing = when the mark or reading appears; numbers = the short number block; caveat last.
kitTip(string head, string timing, string numbers, string caveat) =>
    kitJoin(kitJoin(kitJoin(head, timing), numbers), caveat)
 
kitPrice(float value) =>
    str.tostring(value, format.mintick)
 
// HalfTrend Breakout tooltip text and builders (additions; the kit helpers above are unchanged).
const string KIT_TIP_FLIP_UP = "Trend flip up.\n\nPrice closed above the upper band and the band turned up."
const string KIT_TIP_FLIP_DOWN = "Trend flip down.\n\nPrice closed below the lower band and the band turned down."
const string KIT_TIP_BREAK_UP = "Breakout up.\n\nPrice closed above a confirmed swing high with the band up."
const string KIT_TIP_BREAK_DOWN = "Breakout down.\n\nPrice closed below a confirmed swing low with the band down."
const string HB_FLIP_CAVEAT = "The band lags like a Supertrend. " + KIT_CAVEAT
const string HB_BREAK_CAVEAT = "The grade describes this bar's volume, not what price does next. " + KIT_CAVEAT
const string HB_FIRST_HEAVY = "First Heavy break of this trend."
const string HB_SESSION_OPEN = "Session open bar: it includes the overnight gap; the grade is not session adjusted."
const string HB_GRADE_RULE = "Light 1.0x or less, Middle above 1.0x up to 1.5x, Heavy above 1.5x."
const string HB_ROUNDING = "Multiples are rounded for display; grades use the exact reading."
const string HB_SIGNAL_CAVEAT = "Recorded volume, not confidence. " + KIT_CAVEAT
 
hbCauseText(int cause) =>
    cause == 1 ? "current volume missing" : cause == 2 ? "prior 20-bar window incomplete or missing" : "prior 20-bar average not positive"
 
// Human form of the shared formatter's text; a multiple that displays exactly at a cut says it is rounded.
hbRvText(string raw) =>
    raw + "x" + (raw == "1.00" or raw == "1.50" ? " (rounded)" : "")
 
hbFlipTip(int dir, int priorBars, float bandLevel) =>
    string prior = na(priorBars) ? (dir > 0 ? "The down trend before it began before the loaded history." : "The up trend before it began before the loaded history.") : (dir > 0 ? "The down trend before it lasted " : "The up trend before it lasted ") + str.tostring(priorBars) + (priorBars == 1 ? " bar." : " bars.")
    string timing = "Confirmed " + hbBarTime(time) + " close. " + prior
    string numbers = "Close " + kitPrice(close) + "; " + (dir > 0 ? "upper band " : "lower band ") + kitPrice(bandLevel) + "."
    kitTip(dir > 0 ? KIT_TIP_FLIP_UP : KIT_TIP_FLIP_DOWN, timing, numbers, HB_FLIP_CAVEAT)
 
hbBreakTip(int dir, float level, float rv, string rvRaw, int cause, int swingTime, int seenTime, bool firstHeavy) =>
    string timing = "Swing " + hbBarTime(swingTime) + "; confirmed " + hbBarTime(seenTime) + "; broke " + hbBarTime(time) + " close." + (firstHeavy ? " " + HB_FIRST_HEAVY : "")
    string volText = na(rv) ? "Volume Unavailable: " + hbCauseText(cause) + "." : "Volume " + hbGradeWord(hbStep(rv)) + " · " + hbRvText(rvRaw) + " its prior 20-bar average."
    string session = timeframe.isintraday and syminfo.type == "stock" and session.isfirstbar_regular ? " " + HB_SESSION_OPEN : ""
    string numbers = volText + " Close " + kitPrice(close) + "; level " + kitPrice(level) + "." + session
    kitTip(dir > 0 ? KIT_TIP_BREAK_UP : KIT_TIP_BREAK_DOWN, timing, numbers, HB_BREAK_CAVEAT)
// ==== KIT T4 END ====
 
// ==== KIT T1 START ====
// T1 hero line on the price chart, with the owner-directed look for this indicator.
// Clean (default): a crisp two-pixel line plus one soft edge plot two pixels wider (one quiet pixel each side).
// Bold: the line plus the kit's two wide glow layers. The fill fades from the band toward the candles' middle.
// The band takes the direction colour only; it breaks for one candle on an actual flip and is absent before readiness.
const string KIT_T1_TITLE = "Band"
const int KIT_T1_GLOW_OUTER_WIDTH_BOLD = 20
const int KIT_T1_GLOW_INNER_WIDTH_BOLD = 12
const int KIT_T1_GLOW_OUTER_FADE_DARK = 86
const int KIT_T1_GLOW_INNER_FADE_DARK = 70
const int KIT_T1_GLOW_OUTER_FADE_LIGHT = 89
const int KIT_T1_GLOW_INNER_FADE_LIGHT = 76
const int HB_T1_WIDTH = 2
t1Color = regime == 1 ? kitPal.up : kitPal.down
t1BoldDisplay = kitBold ? display.pane : display.none
t1EdgeDisplay = kitBold ? display.none : display.pane
hbVisibleBand = hbShowBand ? drawnBand : na
plot(hbVisibleBand, "Glow outer", color=color.new(t1Color, kitPal.light ? KIT_T1_GLOW_OUTER_FADE_LIGHT : KIT_T1_GLOW_OUTER_FADE_DARK), linewidth=KIT_T1_GLOW_OUTER_WIDTH_BOLD, style=plot.style_linebr, display=t1BoldDisplay, editable=false)
plot(hbVisibleBand, "Glow inner", color=color.new(t1Color, kitPal.light ? KIT_T1_GLOW_INNER_FADE_LIGHT : KIT_T1_GLOW_INNER_FADE_DARK), linewidth=KIT_T1_GLOW_INNER_WIDTH_BOLD, style=plot.style_linebr, display=t1BoldDisplay, editable=false)
plot(hbVisibleBand, "Soft edge", color=color.new(t1Color, HB_EDGE_FADE), linewidth=HB_T1_WIDTH + HB_EDGE_EXTRA, style=plot.style_linebr, display=t1EdgeDisplay, editable=false)
t1Plot = plot(hbVisibleBand, KIT_T1_TITLE, color=t1Color, linewidth=HB_T1_WIDTH, style=plot.style_linebr, display=display.pane + display.price_scale)
t1Mid = plot(hbShowBand and hbShowFill and not na(drawnBand) ? hl2 : na, "Fill anchor", display=display.none, editable=false)
t1FillTop = math.max(drawnBand, hl2)
t1FillBottom = math.min(drawnBand, hl2)
t1Near = color.new(t1Color, HB_FILL_FADE_BAND)
t1Far = color.new(t1Color, HB_FILL_FADE_CLEAR)
fill(t1Plot, t1Mid, t1FillTop, t1FillBottom, regime == 1 ? t1Far : t1Near, regime == 1 ? t1Near : t1Far, title="Band fill", fillgaps=false)
// ==== KIT T1 END ====
 
// ==== KIT T2 START ====
// T2 marks, two tiers (Decisions row 20; subtle per owner direction 3, msg 1560381728672186399, BRAND_GUIDE "markers subtle"):
// a small arrow glyph in the direction colour where the band actually turns (no plate, box or frame), and a smaller, lighter
// diamond glyph on a
// drawn breakout. One label object per mark, carrying its own tooltip; drawn on the confirmed close and never moved.
// Placement (Decisions row 22): an arrow is anchored on the new band, or one ATR(14) beyond its candle when the band is closer than that.
// The glyph is centred on its own label (so the hover opens on the glyph itself) a small ATR fraction beyond the anchor, and never
// closer than one ATR(14) to the candle before the flip; on the band its tip meets the band. Fixed once at the event close.
// A diamond sits one ATR(14) beyond the farther extreme of its bar and the bar before it.
// Which breakouts get a diamond (Decisions row 19): the first Heavy break of each trend leg by default; events and alerts keep every breakout.
const string KIT_T2_UP_GLYPH = "▲"
const string KIT_T2_DOWN_GLYPH = "▼"
const string KIT_T2_DIAMOND_GLYPH = "◆"
const float HB_T2_GAP_ATR = 1.0
const float HB_T2_ATTACH_ATR = 0.15
const int KIT_T2_KEEP = 100
 
type HbBundle
    label mark
    line stub
 
// Glyph sizes in typographic points, size.tiny / size.small class; the flip arrow is always larger than any diamond.
const int HB_FLIP_SIZE = 9
const int HB_DIAMOND_SIZE = 5
hbGraded = hbBreakMode == "All" or hbBreakMode == "1st break"
// Diamond size: one size for Heavy-only modes; by grade (Light, Middle, Heavy) when more than Heavy marks are drawn.
hbDiamondSize(int step) =>
    hbGraded ? HB_DIAMOND_SIZE + (step == 3 ? 1 : step == 1 ? -1 : 0) : HB_DIAMOND_SIZE
 
// Diamond ink: a graphic role that keeps 3:1 on the chart background and on the band fill (see the T6 HB_DIAMOND_ fades).
hbDiamondInk(int dir, int step) =>
    step == 0 ? color.new(kitPal.flat, HB_DIAMOND_FADE_FLAT) : kitPal.light ? color.new(dir > 0 ? kitPal.upText : kitPal.downText, HB_DIAMOND_FADE_LIGHT) : dir > 0 ? color.new(kitPal.up, HB_DIAMOND_FADE_UP_DARK) : color.new(kitPal.down, HB_DIAMOND_FADE_DOWN_DARK)
 
t2Keep(array<HbBundle> marks, HbBundle mark) =>
    array.push(marks, mark)
    if array.size(marks) > KIT_T2_KEEP
        HbBundle old = array.shift(marks)
        label.delete(old.mark)
        line.delete(old.stub)
 
var array<HbBundle> t2FlipUp = array.new<HbBundle>()
var array<HbBundle> t2FlipDown = array.new<HbBundle>()
var array<HbBundle> t2BreakUp = array.new<HbBundle>()
var array<HbBundle> t2BreakDown = array.new<HbBundle>()
float t2Unit = hbMarkRange > 0 ? hbMarkRange : syminfo.mintick
 
// Trend-leg memory for the default mark rule: reset at a price-segment start and on every actual flip.
var bool hbLegHeavy = false
var bool hbLegAny = false
var int hbPrevFlipBar = na
if hbLocal <= 0
    hbLegHeavy := false
    hbLegAny := false
    hbPrevFlipBar := na
hbFlipShown = false
hbBreakShown = false
hbBreakFirstHeavy = false
if hbGate and hbReady and flip
    hbLegHeavy := false
    hbLegAny := false
    hbFlipShown := hbShowFlips
    if hbFlipShown
        bool up = regime == 1
        float band = up ? lowerBand : upperBand
        float gap = HB_T2_GAP_ATR * t2Unit
        float anchor = up ? math.min(band, low - gap) : math.max(band, high + gap)
        float base = up ? math.min(anchor, low[1] - gap) : math.max(anchor, high[1] + gap)
        float y = up ? base - HB_T2_ATTACH_ATR * t2Unit : base + HB_T2_ATTACH_ATR * t2Unit
        int priorBars = na(hbPrevFlipBar) ? na : bar_index - hbPrevFlipBar
        color tone = up ? kitPal.up : kitPal.down
        string tip = hbFlipTip(up ? 1 : -1, priorBars, up ? upperBand : lowerBand)
        label arrow = label.new(bar_index, y, up ? KIT_T2_UP_GLYPH : KIT_T2_DOWN_GLYPH, yloc=yloc.price, style=label.style_label_center, color=color.new(tone, 100), textcolor=tone, size=HB_FLIP_SIZE, tooltip=tip)
        t2Keep(up ? t2FlipUp : t2FlipDown, HbBundle.new(arrow, na))
if hbGate and flip
    hbPrevFlipBar := bar_index
if hbGate and hbEvent
    bool up = hbEventUp
    int step = hbStep(relVol)
    bool heavy = step == 3
    hbBreakFirstHeavy := heavy and not hbLegHeavy
    hbBreakShown := hbBreakMode == "All" or (hbBreakMode == "All Heavy" and heavy) or (hbBreakMode == "1st Heavy" and hbBreakFirstHeavy) or (hbBreakMode == "1st break" and not hbLegAny)
    hbLegHeavy := hbLegHeavy or heavy
    hbLegAny := true
    if hbBreakShown
        float y = up ? math.min(low, low[1]) - HB_T2_GAP_ATR * t2Unit : math.max(high, high[1]) + HB_T2_GAP_ATR * t2Unit
        color tone = step == 0 ? kitPal.flat : up ? kitPal.up : kitPal.down
        string tip = hbBreakTip(hbEventDir, eventLevel, relVol, hbEventRvRaw, hbVolCause, eventSwingTime, eventSeenTime, hbBreakMode == "1st Heavy" and hbBreakFirstHeavy)
        label diamond = label.new(bar_index, y, KIT_T2_DIAMOND_GLYPH, yloc=yloc.price, style=up ? label.style_label_up : label.style_label_down, color=color.new(tone, 100), textcolor=hbDiamondInk(hbEventDir, step), size=hbDiamondSize(step), tooltip=tip)
        line stub = hbShowLevel ? line.new(eventSwingBar, eventLevel, bar_index, eventLevel, xloc=xloc.bar_index, color=color.new(tone, HB_STUB_FADE), style=line.style_dashed, width=1) : na
        t2Keep(up ? t2BreakUp : t2BreakDown, HbBundle.new(diamond, stub))
// ==== KIT T2 END ====
 
// ==== KIT T3 START ====
// T3 reading panel: the Returns Stochastic KB3 face (T3 chrome, tinted header with the big state word, label rows in the
// caption ink, values through the 4.5:1 readable-ink floor), adapted to this overlay: one product table, no pane-selection
// table and no room plot. Numbers and states are stored on each closed candle; text is formatted and written on the last bar only.
// The build identity cell is a separate table and stays observable with the panel off.
const int KIT_T3_ROWS = 3
const string KIT_T3_ROWS_REASON = ""
const string KIT_T3_TITLE = "HalfTrend"
const string KIT_T3_UP = "Uptrend"
const string KIT_T3_DOWN = "Downtrend"
const string KIT_T3_LABEL_1 = "Trend age"
const string KIT_T3_LABEL_2 = "Last signal"
const string KIT_T3_LABEL_LEFT = "Closes left"
const string KIT_T3_WARMING = "Warming up"
const string KIT_T3_NO_READING = "No reading"
const string KIT_T3_NO_SIGNAL = "No visible signal"
const string KIT_T3_NO_FLIP = "no flip yet"
const string KIT_T3_EMPTY = "-"
const int KIT_T3_FRAME_PX = 2
const int KIT_T3_BORDER_PX = 1
const bool KIT_T3_TOP_CLEARANCE = true
const int KIT_KB3_ZONE_TINT_FADE = 75
const int KIT_KB3_INSIDE_TINT_FADE = 80
const float KIT_KB3_TEXT_FLOOR = 4.5
const string KIT_TIP_AGE = "Bars since the band last turned, from the available history.\n\nThe big word names the side of the band on the last closed candle."
const string KIT_TIP_NO_FLIP = "The band has not turned in the available history.\n\nThe big word names the side it started on; the age starts at the first turn."
const string KIT_TIP_SIGNAL = "The last shown mark of the current trend: the arrow where the band turned, or a later drawn breakout in the same direction.\n\nIt follows the mark settings and never names an older trend."
const string KIT_TIP_NO_SIGNAL = "No mark of this trend is shown under the current display settings.\n\nThe trend side and age above stay valid."
const string KIT_TIP_WARMING = "The reading needs more closed candles first.\n\nThe first candles of a price segment are a warm-up: the band, marks, panel and alerts start after them. A chart that loads a different amount of history can show a different band."
const string KIT_TIP_NO_PRICE = "The indicator cannot read this candle.\n\nA candle with a missing open, high, low or close restarts the price calculation and its warm-up; no event prints on it."
const string KIT_TIP_NO_CHART = "The indicator cannot read this chart.\n\nThis chart type is not a standard candle chart, so the band, marks and alerts are off."
 
// Last closed candle snapshot (numbers and states only). Before the first close it shows Warming up, never a trend.
var int t3Status = chart.is_standard ? 1 : 3
var int t3Remaining = HB_READY_BARS + 1
var int t3Regime = -1
var int t3Age = na
var int t3ClosedBar = na
var int t3ClosedTime = na
var float t3ClosedRv = na
var int t3ClosedCause = 0
var int t3FlipTime = na
// Last signal of the current trend leg: 0 none, 1 flip arrow, 2 breakout diamond.
var int t3SigKind = 0
var int t3SigDir = 0
var int t3SigBar = na
var int t3SigTime = na
var int t3SigStep = 0
var float t3SigRv = na
var string t3SigRvRaw = na
var int t3SigCause = 0
var float t3SigLevel = na
var float t3SigClose = na
if barstate.isconfirmed
    t3Status := not chart.is_standard ? 3 : not hbValidBar ? 2 : not hbReady ? 1 : 0
    t3Remaining := hbValidBar ? math.max(HB_READY_BARS - hbLocal, 0) : HB_READY_BARS + 1
    t3Regime := regime
    t3Age := na(hbFlipBar) ? na : bar_index - hbFlipBar
    t3FlipTime := flip ? time : hbLocal <= 0 ? na : t3FlipTime
    t3ClosedBar := bar_index
    t3ClosedTime := time
    t3ClosedRv := relVol
    t3ClosedCause := hbVolCause
    if hbLocal <= 0 or flip
        t3SigKind := 0
    if hbFlipShown
        t3SigKind := 1
        t3SigDir := regime
        t3SigBar := bar_index
        t3SigTime := time
    if hbBreakShown
        t3SigKind := 2
        t3SigDir := hbEventDir
        t3SigBar := bar_index
        t3SigTime := time
        t3SigStep := hbStep(relVol)
        t3SigRv := relVol
        t3SigRvRaw := hbEventRvRaw
        t3SigCause := hbVolCause
        t3SigLevel := eventLevel
        t3SigClose := close
 
t3Pos = hbPanelPos == "Top Left" ? position.top_left : hbPanelPos == "Btm Right" ? position.bottom_right : hbPanelPos == "Btm Left" ? position.bottom_left : hbPanelPos == "Mid Right" ? position.middle_right : position.top_right
// Top Left sits under the pane legend: three transparent spacer rows clear the symbol line and the study title line, and the
// frame is dropped there so no empty framed box draws above the header. No spacer anywhere else.
t3Spacer = KIT_T3_TOP_CLEARANCE and hbPanelPos == "Top Left"
t3Row0 = t3Spacer ? 3 : 0
t3CellBg = t3Spacer ? kitPal.base : color(na)
t3TitleSize = hbPanelSize == "Small" ? size.small : hbPanelSize == "Large" ? size.large : size.normal
t3StateSize = hbPanelSize == "Small" ? size.normal : hbPanelSize == "Large" ? size.huge : size.large
t3RowSize = t3TitleSize
var table t3Table = table.new(t3Pos, 2, KIT_T3_ROWS + t3Row0, bgcolor=t3Spacer ? color(na) : kitPal.base, frame_color=t3Spacer ? color(na) : kitPal.frame, frame_width=t3Spacer ? 0 : KIT_T3_FRAME_PX, border_color=t3Spacer ? color(na) : kitPal.border, border_width=KIT_T3_BORDER_PX)
var table t3Build = table.new(position.bottom_center, 1, 1)
 
t3Head(string state, color stateColor, color headBg, string tip) =>
    table.cell(t3Table, 0, t3Row0, KIT_T3_TITLE, text_color=kitPal.titleInk, bgcolor=headBg, text_size=t3TitleSize, text_halign=text.align_left, tooltip=tip)
    table.cell(t3Table, 1, t3Row0, state, text_color=stateColor, bgcolor=headBg, text_size=t3StateSize, text_halign=text.align_right, tooltip=tip)
t3Row(int row, string labelText, string valueText, color valueColor, string tip) =>
    table.cell(t3Table, 0, t3Row0 + row, labelText, text_color=kitPal.labelInk, bgcolor=t3CellBg, text_size=t3RowSize, text_halign=text.align_left, tooltip=tip)
    table.cell(t3Table, 1, t3Row0 + row, valueText, text_color=valueColor, bgcolor=t3CellBg, text_size=t3RowSize, text_halign=text.align_right, tooltip=tip)
t3Over(color top, color under) =>
    color.from_gradient(1 - color.t(top) / 100, 0, 1, under, color.new(top, 0))
t3Lum(color c) =>
    0.2126 * kitChannel(color.r(c)) + 0.7152 * kitChannel(color.g(c)) + 0.0722 * kitChannel(color.b(c))
t3Readable(color ink, color seen) =>
    float hi = math.max(t3Lum(ink), t3Lum(seen))
    float lo = math.min(t3Lum(ink), t3Lum(seen))
    (hi + 0.05) / (lo + 0.05) >= KIT_KB3_TEXT_FLOOR ? ink : kitInkOn(seen)
t3Bars(int n) =>
    str.tostring(n) + (n == 1 ? " bar" : " bars")
 
if barstate.islast
    table.set_bgcolor(t3Table, t3Spacer ? color(na) : kitPal.base)
    table.set_frame_color(t3Table, t3Spacer ? color(na) : kitPal.frame)
    table.set_border_color(t3Table, t3Spacer ? color(na) : kitPal.border)
    table.clear(t3Table, 0, 0, 1, KIT_T3_ROWS - 1 + t3Row0)
    table.cell(t3Build, 0, 0, BUILD_TOKEN, text_color=color.new(chart.fg_color, 100), text_size=size.tiny)
    if hbShowPanel
        if t3Spacer
            for r = 0 to t3Row0 - 1
                table.cell(t3Table, 0, r, " \n \n ", text_color=color.new(kitPal.valueInk, 100), bgcolor=na, text_size=size.small)
        bool face = t3Status != 0
        color baseSeen = t3Over(kitPal.base, chart.bg_color)
        int zone = face ? 0 : t3Regime
        color headTint = zone > 0 ? color.new(kitPal.up, KIT_KB3_ZONE_TINT_FADE) : zone < 0 ? color.new(kitPal.down, KIT_KB3_ZONE_TINT_FADE) : color.new(kitPal.flat, KIT_KB3_INSIDE_TINT_FADE)
        color headSeen = t3Over(headTint, baseSeen)
        color headBg = face ? t3CellBg : t3Spacer ? headSeen : headTint
        string closedOn = na(t3ClosedTime) ? KIT_CAVEAT : "Confirmed on the " + hbBarTime(t3ClosedTime) + " close. " + KIT_CAVEAT
        string closedVolume = na(t3ClosedTime) ? "" : "Last closed bar (" + hbBarTime(t3ClosedTime) + "): " + (na(t3ClosedRv) ? "volume grade unavailable (" + hbCauseText(t3ClosedCause) + ")." : "volume " + hbRvText(hbRvRaw(t3ClosedRv)) + " the average of its prior 20 bars.")
        if face
            string headWord = t3Status == 1 ? KIT_T3_WARMING : KIT_T3_NO_READING
            string tip = kitTip(t3Status == 1 ? KIT_TIP_WARMING : t3Status == 3 ? KIT_TIP_NO_CHART : KIT_TIP_NO_PRICE, "", t3Status == 1 ? "Closes still needed: " + str.tostring(t3Remaining) + "." : "", closedOn)
            t3Head(headWord, kitPal.valueInk, headBg, tip)
            t3Row(1, t3Status == 1 ? KIT_T3_LABEL_LEFT : KIT_T3_LABEL_1, t3Status == 1 ? str.tostring(t3Remaining) : KIT_T3_EMPTY, kitPal.valueInk, tip)
            t3Row(2, KIT_T3_LABEL_2, KIT_T3_EMPTY, kitPal.valueInk, tip)
        else
            string stateWord = t3Regime == 1 ? KIT_T3_UP : KIT_T3_DOWN
            string ageNumbers = na(t3Age) ? "No turn in the available history." : "Trend age " + t3Bars(t3Age) + (na(t3FlipTime) ? "." : ", since the " + hbBarTime(t3FlipTime) + " close.")
            string headTip = kitTip(na(t3Age) ? KIT_TIP_NO_FLIP : KIT_TIP_AGE, "", kitJoin(ageNumbers, closedVolume), closedOn)
            t3Head(stateWord, t3Readable(kitDirText(kitPal, t3Regime), headSeen), headBg, headTip)
            t3Row(1, KIT_T3_LABEL_1, na(t3Age) ? KIT_T3_NO_FLIP : t3Bars(t3Age), kitPal.valueInk, headTip)
            if t3SigKind == 0
                t3Row(2, KIT_T3_LABEL_2, KIT_T3_NO_SIGNAL, kitPal.valueInk, kitTip(KIT_TIP_NO_SIGNAL, "", "", closedOn))
            else
                int ago = t3ClosedBar - t3SigBar
                string side = t3SigDir > 0 ? "up" : "down"
                string grade = t3SigStep == 0 ? "Volume unavailable" : hbGradeWord(t3SigStep)
                string sigText = t3SigKind == 1 ? "Flip " + side + ", " + t3Bars(ago) + " ago" : grade + " breakout " + side + ", " + t3Bars(ago) + " ago"
                string sigEvent = t3SigKind == 1 ? "Flip " + side + "." : (t3SigStep == 0 ? "Breakout " + side + ", volume unavailable." : hbGradeWord(t3SigStep) + " breakout " + side + ".")
                string when = "The last shown mark of this trend; the panel reads the last closed candle."
                string dated = "Shown on the " + hbBarTime(t3SigTime) + " close, " + t3Bars(ago) + " ago. "
                string volText = t3SigKind == 1 ? "Flip, not graded." : na(t3SigRv) ? "Recorded volume: Unavailable, " + hbCauseText(t3SigCause) + "." : "Recorded volume " + hbRvText(t3SigRvRaw) + " the average of its prior 20 bars. " + HB_GRADE_RULE + " " + HB_ROUNDING
                string levels = t3SigKind == 1 ? "" : " Close " + kitPrice(t3SigClose) + ". Level " + kitPrice(t3SigLevel) + "."
                t3Row(2, KIT_T3_LABEL_2, sigText, t3Readable(kitDirText(kitPal, t3SigDir), baseSeen), kitTip(sigEvent, when, dated + volText + levels, HB_SIGNAL_CAVEAT))
// ==== KIT T3 END ====

← 返回列表