本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script source code is subject to the Mozilla Public License 2.0.
// Copyright NovaLens
// Indicator: Market Regime [NovaLens]
// Product code: MR-01
// Version: 1.0
// Author: NovaLens
//@version=6
// Market Regime [NovaLens]: names the state of the market on every closed candle: Trend up, Chop or Trend down.
// Trend up starts when a close beats the highest close of the previous candles with a strong push measured in ATR; Trend down is the
// mirror on the lowest close. A trend ends after a set number of closes without a new highest close (Trend up) or lowest close (Trend down), and the same candle may start the
// opposite trend. Next to the state it keeps the chart's own record by period: how often a trend start was followed by a move of two
// ATR with the trend before two ATR against it within twenty candles, beside the same check from every candle.
// Profiles: Adaptive, Fast, Balanced, Smooth and Custom show a reading on every timeframe; the record table shows how
// each did on the chart itself. Where the four-coin study found a profile did not beat a random candle, the panel title hover says so.
// Picture: a slim state rail in its own pane with a dot where a trend starts, a soft wash on price while a trend runs, the state panel
// and the record table on the price chart.
// Repaint: states, the rail, the dots, the wash, the panel, the record and the alerts use closed candles only; the open candle shows the
// last confirmed state, and a confirmed candle is never redrawn.
// K-D engine contract (what the K-D blocks read; every value computed on every bar):
// engValid bool (this candle can be read), engReady bool (engValid and the engine's own history is filled), engWarmBars int,
// engCoverage float 0 to 1 (the share of the engine's window with usable data; under KIT_KD7_MIN_COVERAGE the reading is unavailable),
// engCandidate int (the condition the reading points to on this candle: 1 and 2 the two coloured conditions, 3 the neutral one, 0 none),
// engConfidence float 0 to 1 (how clearly the reading points to engCandidate; na while not ready),
// engStateValue float -1 to 1 (the pane line: towards +1 condition 1, towards -1 condition 2, near 0 neutral; na for a categorical engine).
// Order: T6, the engine's inputs and maths, KD7, T4, KD1, KD2, KD8, KD3.
indicator("Market Regime [NovaLens]", shorttitle="Market Regime [NovaLens]", overlay=false, precision=0, max_labels_count=500, max_bars_back=5000)
const string BRAND_NAME = "NovaLens"
const string BRAND_ENTITY = "NovaLens Quantitative Research"
// ==== STUDY RECORD (four-coin period measurement; it never blocks a reading) ====
// One line per profile and timeframe: true = on the four Coinbase coins pooled, Trend up starts were right at least 5 points more often
// than a random candle in each of the last 1, 3 and 5 years, and Trend down was never 5 or more points under it (windows with fewer than
// 30 starts skipped). false = it did not meet that bar there. Other timeframes were not measured. Every profile reads on every timeframe;
// where a line is false, or the timeframe was not measured, the panel title hover says so and points to the chart's own record table.
// Adaptive on 1D and 4h routes to Smooth's and Fast's settings, so it carries their result there.
// Balanced on 1D: +5.1 points at 3 years but +3.8 at 5 years, under the bar.
const bool STUDY_SMOOTH_1D = true
const bool STUDY_SMOOTH_4H = false
const bool STUDY_SMOOTH_1H = true
const bool STUDY_FAST_1D = true
const bool STUDY_FAST_4H = true
const bool STUDY_FAST_1H = false
const bool STUDY_ADAPTIVE_1D = true
const bool STUDY_ADAPTIVE_4H = true
const bool STUDY_ADAPTIVE_1H = true
const bool STUDY_BALANCED_1D = false
const bool STUDY_BALANCED_4H = false
const bool STUDY_BALANCED_1H = false
// ==== 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: 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 light panel base.
const color KIT_BULL_DARK = #33BD68
const color KIT_BULL_LIGHT = #2DA85D
const color KIT_BULL_DARK_TEXT = #33BD68
const color KIT_BULL_LIGHT_TEXT = #248449
const color KIT_BEAR_DARK = #EF5350
const color KIT_BEAR_LIGHT = #EF5350
const color KIT_BEAR_DARK_TEXT = #EF5350
const color KIT_BEAR_LIGHT_TEXT = #CD4341
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 = #787B86
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
kitPalette(string theme, color upIn, color downIn, color flatIn, color highIn, color lowIn) =>
bool light = kitIsLight(theme)
color upText = kitPick(upIn, KIT_BULL_DARK, KIT_BULL_LIGHT_TEXT, light)
color downText = kitPick(downIn, KIT_BEAR_DARK, KIT_BEAR_LIGHT_TEXT, light)
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)
// ==== KIT T6 END ====
// ==== ENGINE INPUTS: groups "1. Profile" and "2. Core (select Custom first)"; the kit groups follow as "3. Marks", "4. Display", "5. Colours" ====
// ==== PROFILE SWITCHBOARD (set from the profile lab) ====
// G_OPERATIONAL: how strongly the windows stretch with the timeframe (0 = not at all; 0.25 or 0.5).
// SMOOTH_HOLD: true = Smooth keeps the speed 1 windows and holds a stalled trend until a close is back through the level it broke out
// of, or the final stall limit; false = Smooth uses windows 1.5 times longer with the ordinary stall exit.
// ADAPTIVE_OFFGRID_FORMULA: true = on an interval the lab did not check Adaptive still applies the timeframe formula and says it is
// unchecked; false = it uses the default Core settings there and says so.
// LAB_ADAPTIVE / LAB_FAST / LAB_SMOOTH: the lab outcome on 15m, 1h and 4h crypto charts as three digits (1 met the stated behaviour
// rule, 2 checked and did not meet it, 0 not checked). Example: 110 = 15m met, 1h met, 4h not checked.
// To drop a profile: remove its name from the Profile options below and from the Profile hover text. As set from the lab: strength
// 0.25; Smooth with the hold exit; Adaptive met the stated rule on 1h and 4h (15m not conclusive: it uses the default Core settings
// there); Fast and Smooth met it on 4h and 1D (15m and 1h not conclusive). Where a profile is shown at all is set by the OFFERING
// MATRIX at the top; the Profile hover names the shipped offering in words, so change it with the matrix.
const float G_OPERATIONAL = 0.25
const bool SMOOTH_HOLD = true
const bool ADAPTIVE_OFFGRID_FORMULA = false
const int LAB_ADAPTIVE = 11
const int LAB_FAST = 1
const int LAB_SMOOTH = 1
// Profile hover: behavior, trade-offs and settings. Yearly counts are state changes on 1D,
// pooled over four Coinbase crypto markets for the five years ending 23 Oct 2026.
// Every option runs on every timeframe. The panel title hover explains the chosen profile and the study result.
engProfileIn = input.string("Smooth", "Profile", options=["Adaptive", "Fast", "Balanced", "Smooth", "Custom"], group="1. Profile", display=display.none, tooltip="Choose the speed. Faster turns sooner but flips more; smoother holds longer but turns later.\n\n• Adaptive: Smooth on 1D, Fast on 4h, longer crypto 1h windows, Core elsewhere.\n• Fast: quickest, most flips (28).\n• Balanced: fixed windows, sooner exits (16).\n• Smooth: longest holds, fewest flips (13).\n• Custom: your settings, unchecked.\n\n(n) = flips per year on 1D, 4 cryptos, 5 years.\n\nRuns on every timeframe; the table shows how it did on your chart. Past behaviour, not a forecast.")
engNIn = input.int(60, "Up breakout lookback", minval=20, maxval=200, group="2. Core (select Custom first)", active=engProfileIn == "Custom", display=display.none, tooltip="How many earlier closes the next close must beat to start Trend up.\n\nA longer window makes the closing-high test harder to clear. A strong push is also required.\n\nCounted in candles. Used only with Custom.")
engNDIn = input.int(30, "Down breakdown lookback", minval=10, maxval=200, group="2. Core (select Custom first)", active=engProfileIn == "Custom", display=display.none, tooltip="How many earlier closes the next close must fall below to start Trend down.\n\nA longer window makes the closing-low test harder to clear. A strong push is also required.\n\nCounted in candles. Used only with Custom.")
engLIn = input.int(10, "Push length", minval=3, maxval=30, group="2. Core (select Custom first)", active=engProfileIn == "Custom", display=display.none, tooltip="How many candles the push is measured over.\n\nThe push is how far the close has moved over that many candles. Higher = a longer stretch.\n\nCounted in candles. Only used when Profile = Custom.")
engAIn = input.float(2.5, "Push size (x ATR)", minval=0.5, maxval=5.0, step=0.1, group="2. Core (select Custom first)", active=engProfileIn == "Custom", display=display.none, tooltip="How strong the push must be to start a trend.\n\nHigher requires a larger move; lower accepts a smaller move. The closing-high or closing-low test must also pass.\n\nMeasured in ATR, the average true range over fourteen candles. Used only with Custom.")
engKIn = input.int(8, "Stall limit", minval=3, maxval=30, group="2. Core (select Custom first)", active=engProfileIn == "Custom", display=display.none, tooltip="Closes without a new highest close in Trend up, or lowest close in Trend down, before that trend ends.\n\nA new extreme close resets the count. The same close that ends a trend can start another.\n\nUsed only with Custom.")
// ENGINE: a closing-breakout and stall state machine (Donchian-style closing high and low with an ATR push filter).
// On each candle from the first ready one: a running trend records a strictly new best close or counts one more stalled close; a trend
// whose stall count reaches the limit falls back to Chop; from Chop (the same candle included) a close strictly above the highest of the
// previous N closes with a push strictly above A x ATR starts Trend up, else a close strictly below the lowest of the previous ND closes
// with a push strictly below -A x ATR starts Trend down. Every comparison is the sign of a difference, so tiny float gaps never tie.
const int ENG_ATR_LEN = 14
// The longest window a chart's history buffer can serve (max_bars_back is 5,000); a longer resolved window gives No reading.
const int ENG_MAX_WINDOW = 4999
// Settings in use. Custom reads the five Core inputs (defaults 60 / 30 / 10 / 2.5 / 8). Adaptive, Fast and Smooth resolve from the chart's timeframe:
// m = candles per day on a market that never closes, s = speed x m^g (g = 0 above one day), N = max(20, r(60 s)), ND = max(10, r(30 s)),
// L = max(3, r(10 s)), K = max(3, r(8 s)), A = 2.5 x sqrt(L / 10) to one decimal; the hold exit adds KH = max(K + 1, r(2.5 K)).
// r rounds halves up after rounding to 12 decimals. Speed: Adaptive 1, Fast 0.5, Smooth 1 with the hold exit or 1.5 without it. Adaptive routes:
// on 1D it takes Smooth's speed and exit, on 4h Fast's speed (engAdaptAsSmooth, engAdaptAsFast below).
engRhu(float x) =>
int(math.floor(math.round(x, 12) + 0.5))
engCustom = engProfileIn == "Custom"
engAdaptive = engProfileIn == "Adaptive"
engFast = engProfileIn == "Fast"
engSmooth = engProfileIn == "Smooth"
// Balanced uses fixed values 60 / 30 / 10 / 2.5 / 8 with the ordinary stall exit:
// the non-preset branch of engN, engND, engL, engA and engK below.
engBalanced = engProfileIn == "Balanced"
engPreset = engAdaptive or engFast or engSmooth
engTfSec = timeframe.in_seconds()
engIs1D = engTfSec == 86400
engAbove1D = engTfSec > 86400
// The lab grid: 1 = 15m, 2 = 1h, 3 = 4h, 0 = any other interval. The lab read crypto markets only, so elsewhere the digit is 0.
engGrid = engTfSec == 900 ? 1 : engTfSec == 3600 ? 2 : engTfSec == 14400 ? 3 : 0
engCrypto = syminfo.type == "crypto"
engLabCode = engAdaptive ? LAB_ADAPTIVE : engFast ? LAB_FAST : LAB_SMOOTH
engLabDigit = not engCrypto ? 0 : engGrid == 1 ? int(engLabCode / 100) % 10 : engGrid == 2 ? int(engLabCode / 10) % 10 : engGrid == 3 ? engLabCode % 10 : 0
// Measured timeframes: 1D = daily with multiplier 1, 4h = 240 minutes, 1h = 60 minutes.
// These select the study note and Adaptive route; they never block a reading.
ofIs1D = timeframe.isdaily and timeframe.multiplier == 1
ofIs4h = timeframe.isminutes and timeframe.multiplier == 240
ofIs1h = timeframe.isminutes and timeframe.multiplier == 60
ofMeasured = ofIs1D or ofIs4h or ofIs1h
ofSmooth = ofIs1D ? STUDY_SMOOTH_1D : ofIs4h ? STUDY_SMOOTH_4H : ofIs1h ? STUDY_SMOOTH_1H : false
ofFast = ofIs1D ? STUDY_FAST_1D : ofIs4h ? STUDY_FAST_4H : ofIs1h ? STUDY_FAST_1H : false
ofAdaptive = ofIs1D ? STUDY_ADAPTIVE_1D : ofIs4h ? STUDY_ADAPTIVE_4H : ofIs1h ? STUDY_ADAPTIVE_1H : false
ofBalanced = ofIs1D ? STUDY_BALANCED_1D : ofIs4h ? STUDY_BALANCED_4H : ofIs1h ? STUDY_BALANCED_1H : false
// The study result of the chosen profile on this timeframe (Custom: not studied).
ofStudyBeat = (engSmooth and ofSmooth) or (engFast and ofFast) or (engAdaptive and ofAdaptive) or (engBalanced and ofBalanced)
// Adaptive uses Smooth's settings and hold exit on 1D, Fast's settings on 4h, and its own longer windows on crypto 1h.
// Elsewhere it uses default Core settings. On 1D and 4h its reading and record are those of Smooth and Fast.
engAdaptAsSmooth = engAdaptive and ofIs1D
engAdaptAsFast = engAdaptive and ofIs4h
// Adaptive uses the default Core settings (60 / 30 / 10 / 2.5 / 8) above one day, on a lab interval (15m, 1h on a crypto chart)
// that did not meet the rule or was not conclusive, and (only with ADAPTIVE_OFFGRID_FORMULA off) wherever the lab has no result, which
// includes every 1h chart that is not crypto. On 1D and 4h it takes Smooth's and Fast's settings (the route above), on any market.
engAdaptFallback = engAdaptive and not engIs1D and not engAdaptAsFast and (engAbove1D or G_OPERATIONAL == 0 or (engCrypto and engGrid != 0 and engLabDigit != 1) or (not ADAPTIVE_OFFGRID_FORMULA and engLabDigit != 1))
engG = engAbove1D ? 0.0 : G_OPERATIONAL
engSpeed = engFast or engAdaptAsFast ? 0.5 : (engSmooth or engAdaptAsSmooth) and not SMOOTH_HOLD ? 1.5 : 1.0
engS = engAdaptFallback ? 1.0 : engSpeed * math.pow(86400.0 / engTfSec, engG)
engPN = math.max(20, engRhu(60 * engS))
engPND = math.max(10, engRhu(30 * engS))
engPL = math.max(3, engRhu(10 * engS))
engPK = math.max(3, engRhu(8 * engS))
engPA = math.floor(math.round(2.5 * math.sqrt(engPL / 10.0), 12) * 10 + 0.5) / 10.0
engN = engCustom ? engNIn : engPreset ? engPN : 60
engND = engCustom ? engNDIn : engPreset ? engPND : 30
engL = engCustom ? engLIn : engPreset ? engPL : 10
engA = engCustom ? engAIn : engPreset ? engPA : 2.5
engK = engCustom ? engKIn : engPreset ? engPK : 8
engHold = (engSmooth or engAdaptAsSmooth) and SMOOTH_HOLD
engKH = engHold ? math.max(engK + 1, engRhu(2.5 * engK)) : engK
engTooLong = math.max(engN, engND, engL) > ENG_MAX_WINDOW
engLenN = math.min(engN, ENG_MAX_WINDOW)
engLenND = math.min(engND, ENG_MAX_WINDOW)
engLenL = math.min(engL, ENG_MAX_WINDOW)
// Contract the K-D blocks read: engValid, engReady, engWarmBars, engCoverage, engCandidate, engConfidence, engStateValue.
engWarmBars = math.max(engN, engND, engL, ENG_ATR_LEN - 1)
engValid = chart.is_standard and not na(close) and not engTooLong
engAtr = ta.atr(ENG_ATR_LEN)
engHiN = ta.highest(close, engLenN)[1]
engLoND = ta.lowest(close, engLenND)[1]
engPush = close - close[engLenL]
var int engTrend = 0
var float engExt = na
var float engLvl = na
var int engSince = 0
if engValid and bar_index >= engWarmBars and not na(engAtr)
if engTrend == 1
if math.sign(close - engExt) > 0
engExt := close
engSince := 0
else
engSince += 1
else if engTrend == -1
if math.sign(close - engExt) < 0
engExt := close
engSince := 0
else
engSince += 1
// The ordinary exit: the stall count reaches the limit (engKH equals engK without the hold). The hold exit: once stalled engK
// closes, the trend ends on a close back through the level it broke out of (matching it does not count), and at engKH stalled
// closes whatever the price.
bool engBack = engTrend == 1 ? math.sign(close - engLvl) < 0 : engTrend == -1 ? math.sign(close - engLvl) > 0 : false
if engTrend != 0 and (engSince >= engKH or (engHold and engSince >= engK and engBack))
engTrend := 0
engExt := na
engLvl := na
engSince := 0
if engTrend == 0
if math.sign(close - engHiN) > 0 and math.sign(engPush - engA * engAtr) > 0
engTrend := 1
engExt := close
engLvl := engHiN
engSince := 0
else if math.sign(close - engLoND) < 0 and math.sign(-engPush - engA * engAtr) > 0
engTrend := -1
engExt := close
engLvl := engLoND
engSince := 0
// Ready one candle before the first state so the kit's gate (ready on this and the previous candle) first holds on the first state's
// candle; that one candle's candidate is the neutral condition and is never shown.
engReady = engValid and bar_index >= engWarmBars - 1
engCoverage = 1.0
engCandidate = not engReady ? 0 : bar_index < engWarmBars ? 3 : engTrend == 1 ? 1 : engTrend == -1 ? 2 : 3
engConfidence = engReady ? 1.0 : na
float engStateValue = na
// ==== KIT KD7 START ====
// KD7 settings for K-D (the T7 pattern: groups, the palette, the honest gate, one alert payload). The indicator's own inputs come
// first, in groups "1. Profile", "2. Core" and "3. Advanced"; this block adds Marks, Display and Colours in that order. Every input
// here changes only the picture. The alert conditions sit in KD8, after KD1 finds the confirmed changes.
// Condition colours (BRAND_GUIDE section 7): a condition is never shown as green against red. Condition 1 takes the accent (the Up role)
// only because the placeholder engine has no direction output; an engine that also gives a direction gives the accent to direction
// and moves condition 1 to another role. Condition 2 takes Orange (the extreme-high role's hex, which the guide also calls Amber; K-D
// keeps that hex for condition 2 only). The neutral condition takes Slate and never fills an area.
const string KIT_G_MARKS = "3. Marks"
const string KIT_G_DISPLAY = "4. Display"
const string KIT_G_COLOURS = "5. Colours"
// Slots: the names a trader reads in the settings, the panel header and the alerts.
const string KIT_INDICATOR = "Market Regime"
const string KIT_T3_STATE_1 = "Trend up"
const string KIT_T3_STATE_2 = "Trend down"
const string KIT_T3_STATE_3 = "Chop"
const string KIT_CHANGE_MARKS = "trend-start marks"
const string KIT_RAIL_NAME = "state rail"
const string KIT_ALERT_STATE_1 = "Trend Up Started"
const string KIT_ALERT_STATE_2 = "Trend Down Started"
const string KIT_ALERT_STATE_3 = "Chop Started"
const string KIT_ALERT_ANY = "State Changed"
// The share of the engine's window that must hold usable data; under it the reading is unavailable (No reading), not neutral.
const float KIT_KD7_MIN_COVERAGE = 0.8
const string KIT_DISPLAY_ONLY = "Display only; it does not change the calculation."
kitShowChangeMarks = input.bool(true, "Show " + KIT_CHANGE_MARKS, group=KIT_G_MARKS, display=display.none, tooltip="Shows a dot on the rail where a trend starts.\n\nThe dot takes the new trend's colour. Hover it for that trend's result. A return to Chop gets no dot.\n\nDrawn when the candle closes and never moved. Hiding dots does not change the alerts.")
kitTheme = input.string("Auto", "Theme", options=["Auto", "Dark", "Light"], group=KIT_G_DISPLAY, display=display.none, tooltip="Matches the colours to your chart background.\n\n• Auto: reads the chart background.\n• Dark, Light: force one set.\n\n" + KIT_DISPLAY_ONLY)
kitShowRail = input.bool(true, "Show " + KIT_RAIL_NAME, group=KIT_G_DISPLAY, display=display.none, tooltip="Shows the rail in the indicator pane.\n\nClosed candles take their state colour. Thin neutral rail means Chop; a gap means no reading was available.\n\nHiding the rail does not hide dots or change the panel or alerts.")
kitPanelPos = input.string("Btm Right", "Panel", options=["Top Right", "Btm Right", "Btm Left", "Off"], group=KIT_G_DISPLAY, display=display.none, tooltip="Places the Market Regime panel, or turns it off.\n\nThe panel reads the last closed candle.\n\n" + KIT_DISPLAY_ONLY)
kitPanelOn = input.string("Price", "Panel on", options=["Price", "Pane"], group=KIT_G_DISPLAY, display=display.none, active=kitPanelPos != "Off", tooltip="Chooses where the state panel sits.\n\n• Price: on the price chart.\n• Pane: with the state rail.\n\nDisplay only.")
kitUpIn = input.color(KIT_BULL_DARK, KIT_T3_STATE_1, group=KIT_G_COLOURS, inline="cond", display=display.none)
kitHighIn = input.color(KIT_BEAR_DARK, KIT_T3_STATE_2, group=KIT_G_COLOURS, inline="cond", display=display.none)
kitFlatIn = input.color(KIT_NEUTRAL_DARK, KIT_T3_STATE_3, group=KIT_G_COLOURS, inline="cond", display=display.none, tooltip="Colours for Trend up, Trend down and Chop.\n\nUsed on the rail, trend dots, price shading, coloured candles and tables. Chop does not shade price.\n\nDefault colours follow the light or dark palette. Custom colours are kept.")
// The Trend-down colour setting, kitHighIn, feeds the palette's down slot, so its text gets the readable down grade.
kitPal = kitPalette(kitTheme, kitUpIn, kitHighIn, kitFlatIn, KIT_EXT_HIGH_DARK, KIT_EXT_LOW_DARK)
// Line, rail and mark colour of a condition (1, 2, the neutral 3), and its text colour on the panel.
kitStateColor(KitPalette p, int cond) =>
cond == 1 ? p.up : cond == 2 ? p.down : p.flat
kitStateText(KitPalette p, int cond) =>
cond == 1 ? p.upText : cond == 2 ? p.downText : p.valueInk
kitStateName(int cond) =>
cond == 1 ? KIT_T3_STATE_1 : cond == 2 ? KIT_T3_STATE_2 : cond == 3 ? KIT_T3_STATE_3 : ""
// Honest warm-up and bar-close gating: nothing is drawn or alerted before the engine is ready and its data covers the window, and
// events only on a closed candle.
kitReady = engReady and engCoverage >= KIT_KD7_MIN_COVERAGE
kitGate = barstate.isconfirmed and kitReady and kitReady[1]
// Payload: indicator, event, symbol, timeframe, close and bar time, always confirmed on the bar close.
const string KIT_ALERT_HEAD = KIT_INDICATOR + " [NovaLens]: "
const string KIT_PAYLOAD = " on {{exchange}}:{{ticker}} ({{interval}}), close {{close}}, bar time {{time}}. Confirmed on bar close."
// ==== KIT KD7 END ====
// ==== Display inputs for the state on price and the record table ====
mrShadeIn = input.bool(true, "Shade price by state", group=KIT_G_DISPLAY, display=display.none, tooltip="Shades price while a trend runs.\n\nUses the Trend up or Trend down colour. Chop is unshaded. The open candle keeps the last closed reading.\n\nDisplay only.")
mrCandlesIn = input.bool(false, "Colour candles by state", group=KIT_G_DISPLAY, display=display.none, tooltip="Colours the candles of a running trend.\n\nUses the Trend up or Trend down colour. Chop keeps the chart's candle colours. Off by default so your candle colours keep their usual meaning.\n\n" + KIT_DISPLAY_ONLY)
mrRulesIn = input.bool(true, "Show what would change it", group=KIT_G_DISPLAY, display=display.none, active=kitPanelPos != "Off", tooltip="Shows what can change the current reading.\n\nIn Chop, a close must clear a level with a strong push. In a trend, the rows explain when it ends and what resets the count.\n\nClosed candles only. No line is drawn on price.")
// The price-level line is withdrawn for Step 1: no input and no drawing ships.
const bool mrLineIn = false
mrRecordMode = input.string("On", "Record", options=["On", "Off"], group=KIT_G_DISPLAY, display=display.none, tooltip="Shows or hides the record table.\n\nBy period, it counts how often past trend starts on this chart were right, beside the same check from a random candle.\n\nPast results, not a forecast. Display only.")
mrRecordIn = mrRecordMode == "On"
// Record table: five columns (period, each direction and its random-candle comparison) and seven rows
// (title, column heads, four periods, dates with the asterisk note).
// Method explanations are in the title, header and dates hovers.
const int MR_PD_COLS = 5
const int MR_PD_TROWS = 7
// The record defaults to the bottom-left corner, so a table never sits over the newest candles at the right edge (no room anchors).
mrRecordPosIn = input.string("Btm Left", "Record table position", options=["Btm Right", "Btm Left", "Top Left"], group=KIT_G_DISPLAY, active=mrRecordIn, display=display.none, tooltip="Places the record on the price chart.\n\nIf the state panel is on Price in the same corner, it keeps that corner and the record uses the other bottom corner.\n\nDisplay only.")
// ==== 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)
kitWhen() =>
timeframe.isintraday ? str.format_time(time_close, "d MMM yyyy HH:mm", syminfo.timezone) : str.format_time(time, "d MMM yyyy", syminfo.timezone)
kitClosedOn(string when) =>
"Confirmed on the " + when + " close. " + KIT_CAVEAT
kitPrice(float value) =>
"Close " + str.tostring(value, format.mintick)
// ==== KIT T4 END ====
// ==== KIT KD1 START ====
// KD1 condition arbiter (template K-D). It draws nothing: it turns the engine's candidate condition and confidence into confirmed
// conditions over time. A candidate becomes the confirmed condition only on a closed, ready candle (kitGate), after it held for
// KIT_KD1_HOLD closed candles in a row (KIT_KD1_HOLD_NEUTRAL for the neutral condition) and, for condition 1 or 2, with at least
// Normal confidence on that candle. A candidate that held long enough on Weak confidence stays provisional: the panel tooltip names it;
// it gets no mark and no alert. The confirmed condition only moves forward, on closed candles, so a confirmed candle is never redrawn.
// Unavailable data (engValid false, or engCoverage under KIT_KD7_MIN_COVERAGE) clears the confirmed condition to 0, which draws no rail
// at all, unlike the neutral condition, which keeps a thin rail; afterwards a condition is confirmed again from the start.
// State age counts the closed candles in the confirmed condition, the confirming candle included.
// Slots: the hold lengths, the neutral condition's number and the two confidence steps.
const int KIT_KD1_HOLD = 1
const int KIT_KD1_HOLD_NEUTRAL = 1
const int KIT_KD1_NEUTRAL = 3
const float KIT_KD1_NORMAL = 0.4
const float KIT_KD1_STRONG = 0.75
// Confidence step of this candle's candidate: 1 weak, 2 normal, 3 strong.
kdStep = not kitReady or na(engConfidence) ? 1 : engConfidence >= KIT_KD1_STRONG ? 3 : engConfidence >= KIT_KD1_NORMAL ? 2 : 1
// Confirmed condition (0 none), its age, the run of the latest candidate, the condition before the last change, and a weak hold.
var int kdState = 0
var int kdAge = 0
var int kdRunState = 0
var int kdRun = 0
var int kdFrom = 0
var int kdLastKnown = 0
var bool kdWeakHeld = false
kdChange = false
if barstate.isconfirmed
if kitReady
kdRun := engCandidate == kdRunState ? kdRun + 1 : 1
kdRunState := engCandidate
bool kdHeld = kdRunState != kdState and kdRun >= (kdRunState == KIT_KD1_NEUTRAL ? KIT_KD1_HOLD_NEUTRAL : KIT_KD1_HOLD)
bool kdSure = kdRunState == KIT_KD1_NEUTRAL or kdStep >= 2
kdWeakHeld := kdHeld and not kdSure
if kitGate and kdHeld and kdSure
kdFrom := kdLastKnown
kdState := kdRunState
kdAge := 1
kdChange := kdFrom != 0 and kdState != kdFrom
kdLastKnown := kdState
else
kdAge := kdState == 0 ? 0 : kdAge + 1
else
kdState := 0
kdAge := 0
kdRunState := 0
kdRun := 0
kdWeakHeld := false
// ==== KIT KD1 END ====
// ==== KIT KD2 START ====
// KD2 condition pane (template K-D). One reading line on a compact pane, a dotted middle line, a coloured area from the line to the
// middle, and a thin condition rail at the pane foot. The line takes the colour of the condition it points to only while it points
// there with at least Normal confidence; otherwise it is Slate. The area (the kit's fill grammar) runs from
// the line to the middle in that colour, densest at the line and clear at the middle, and is drawn only while the line is coloured, so
// the neutral condition and weak readings never fill an area. The rail shows the confirmed condition of every closed candle (KD1): a
// coloured segment for condition 1 or 2, a thin Slate line for the neutral condition, nothing while there is no reading. It never
// changes a candle it has drawn, and it sits at a fixed level under the line, so it never stretches the pane.
// Clean: the line (2 px) and a thin rail, no glow or area. Glow: a 3 px line, one soft glow, the area and a wider rail. Bold: a denser
// glow and area, and a lit edge just past the Strong level while the line is beyond it.
// A categorical engine (no line, engStateValue na) sets KIT_KD2_HAS_TRACE false: the rail is the hero, drawn wider, and the line, glow,
// area and edges are gone.
// Slots: titles, the scale, widths, fades, the area switch. Every colour comes from T6 through kitPal or kitStructure.
const string KIT_KD2_TITLE = "Reading"
const string KIT_KD2_RAIL_TITLE = "State rail"
const bool KIT_KD2_HAS_TRACE = false
const float KIT_KD2_HIGH = 1.0
const float KIT_KD2_MID = 0.0
const float KIT_KD2_RAIL_LEVEL = 0.5
const float KIT_KD2_EDGE_LEVEL = KIT_KD1_STRONG
const float KIT_KD2_EDGE = 0.08
const int KIT_KD2_WIDTH_CLEAN = 2
const int KIT_KD2_WIDTH = 3
const int KIT_KD2_RAIL_WIDTH_CLEAN = 3
const int KIT_KD2_RAIL_WIDTH = 6
const int KIT_KD2_RAIL_WIDTH_HERO = 10
const int KIT_KD2_GLOW_INNER_WIDTH = 8
const int KIT_KD2_GLOW_OUTER_WIDTH = 14
const int KIT_KD2_GLOW_INNER_FADE_DARK = 80
const int KIT_KD2_GLOW_INNER_FADE_LIGHT = 84
const int KIT_KD2_GLOW_INNER_FADE_BOLD_DARK = 74
const int KIT_KD2_GLOW_INNER_FADE_BOLD_LIGHT = 80
const int KIT_KD2_GLOW_OUTER_FADE_DARK = 88
const int KIT_KD2_GLOW_OUTER_FADE_LIGHT = 90
// The area's fade at the line, in Glow and in Bold, on a dark and a light chart; it fades to fully transparent at the middle line.
const int KIT_KD2_FILL_FADE_DARK = 80
const int KIT_KD2_FILL_FADE_LIGHT = 80
const int KIT_KD2_FILL_FADE_BOLD_DARK = 70
const int KIT_KD2_FILL_FADE_BOLD_LIGHT = 74
// The Bold edge's fade at the Strong level; it fades to fully transparent KIT_KD2_EDGE further out.
const int KIT_KD2_EDGE_FADE_DARK = 55
const int KIT_KD2_EDGE_FADE_LIGHT = 60
const int KIT_KD2_BASE_FADE = 10
const int KIT_KD2_MID_FADE = KIT_ZERO_FADE
// The coloured area; false gives no area.
const bool KIT_KD2_FILL_ON = true
// The rail reads KD1's confirmed condition on closed candles only; the live candle joins it when it closes.
// Both rail plots break at na (linebr), so a stretch with no confirmed condition (unavailable, or a fresh hold) draws no rail.
k2RailOn = kitShowRail and barstate.isconfirmed and kdState != 0
k2RailInk = kdState == 1 or kdState == 2 ? kitStateColor(kitPal, kdState) : color(na)
// Categorical scale: the rail sits in a fixed band between two clear levels with no whole number inside it, and the pane shows
// whole numbers only (precision 0). TradingView can still print one rounded scale tick (for example 1) beside the rail; it is not a state value.
const float MR_BAND_LOW = 0.2
const float MR_BAND_HIGH = 0.8
hline(MR_BAND_LOW, "Rail band low", color=color.new(KIT_NEUTRAL_DARK, 100), editable=false)
hline(MR_BAND_HIGH, "Rail band high", color=color.new(KIT_NEUTRAL_DARK, 100), editable=false)
plot(k2RailOn ? KIT_KD2_RAIL_LEVEL : na, "Rail base", color=color.new(kitPal.flat, KIT_KD2_BASE_FADE), linewidth=1, style=plot.style_linebr, display=display.pane, editable=false)
plot(k2RailOn ? KIT_KD2_RAIL_LEVEL : na, KIT_KD2_RAIL_TITLE, color=k2RailInk, linewidth=KIT_KD2_RAIL_WIDTH_HERO, style=plot.style_linebr, display=display.pane)
// Categorical engine (KIT_KD2_HAS_TRACE false): the reading line, its glows, its area and the lit edges never draw, so their plots
// are left out to keep the script under the 64-plot limit with the Data Window diagnostics; the rail is the hero.
// ==== KIT KD2 END ====
// ==== KIT KD8 START ====
// KD8 change marks and alerts for K-D (the T2 dot family: a core glyph and, in Glow and Bold, a fainter ring, both carrying the
// tooltip, T2 sizes and fades). One mark per confirmed change into condition 1 or 2 (KD1), on the closed candle that confirmed it,
// in the new condition's colour, never moved afterwards. A change into the neutral condition gets no mark: the rail's thin grey line
// shows it, and the mark budget (at most 8 in a 150-candle view) holds. One place only (KIT_KD8_ON_PRICE): on the condition rail by
// default, where the colour changes, or once above the candle on the price chart; never both. The rail mark sits at the rail's fixed
// level and the price mark is placed by TradingView above the candle, so neither stretches a scale.
// Alerts: one per confirmed condition and one for any change, all on closed, ready candles (kitGate).
const string KIT_T2_DOT_GLYPH = "●"
const int KIT_T2_CORE_SIZE = 13
const int KIT_T2_RING_SIZE = 16
const int KIT_T2_RING_FADE_GLOW = 72
const int KIT_T2_RING_FADE_BOLD = 65
const int KIT_T2_KEEP = 100
const bool KIT_KD8_ON_PRICE = false
const string KIT_TIP_MARK_1 = "A trend up starts here.\n\nThe close beat its recent closing high after a strong push up. It describes what price did, not where it goes next."
const string KIT_TIP_MARK_2 = "A trend down starts here.\n\nThe close fell below its recent closing low after a strong push down. It describes what price did; it is not a short signal."
const string KIT_TIP_TIMING_CHANGE = "This mark appears when that candle closes and is never moved."
kitState1 = kitGate and kdChange and kdState == 1
kitState2 = kitGate and kdChange and kdState == 2
kitState3 = kitGate and kdChange and kdState == KIT_KD1_NEUTRAL
kitAnyState = kitGate and kdChange
kitChangeMark = kitState1 or kitState2
t2RingFade = KIT_T2_RING_FADE_BOLD
// The rail keeps its last KIT_T2_KEEP marks: two labels (ring and core) per mark, one on price. t2Keep is K-A's T2 queue.
t2Capacity = (KIT_KD8_ON_PRICE ? 1 : 2) * KIT_T2_KEEP
t2Keep(array<label> marks, label mark) =>
if array.size(marks) >= t2Capacity
label.delete(array.shift(marks))
array.push(marks, mark)
var array<label> k8Marks = array.new<label>()
if kitGate and kitShowChangeMarks and kitChangeMark
color tone = kitStateColor(kitPal, kdState)
string tip = kitTip(kdState == 1 ? KIT_TIP_MARK_1 : KIT_TIP_MARK_2, KIT_TIP_TIMING_CHANGE, kitPrice(close), kitClosedOn(kitWhen()))
if KIT_KD8_ON_PRICE
t2Keep(k8Marks, label.new(bar_index, high, KIT_T2_DOT_GLYPH, yloc=yloc.abovebar, style=label.style_none, textcolor=tone, size=KIT_T2_CORE_SIZE, tooltip=tip, force_overlay=true))
else
t2Keep(k8Marks, label.new(bar_index, KIT_KD2_RAIL_LEVEL, KIT_T2_DOT_GLYPH, yloc=yloc.price, style=label.style_none, textcolor=color.new(tone, t2RingFade), size=KIT_T2_RING_SIZE, tooltip=tip))
t2Keep(k8Marks, label.new(bar_index, KIT_KD2_RAIL_LEVEL, KIT_T2_DOT_GLYPH, yloc=yloc.price, style=label.style_none, textcolor=tone, size=KIT_T2_CORE_SIZE, tooltip=tip))
alertcondition(kitState1, KIT_ALERT_STATE_1, KIT_ALERT_HEAD + "TREND UP STARTED" + KIT_PAYLOAD)
alertcondition(kitState2, KIT_ALERT_STATE_2, KIT_ALERT_HEAD + "TREND DOWN STARTED" + KIT_PAYLOAD)
alertcondition(kitState3, KIT_ALERT_STATE_3, KIT_ALERT_HEAD + "CHOP STARTED" + KIT_PAYLOAD)
alertcondition(kitAnyState, KIT_ALERT_ANY, KIT_ALERT_HEAD + "STATE CHANGED, new state code {{plot(\"State\")}} (1 Trend up, 0 Chop, -1 Trend down)" + KIT_PAYLOAD)
// ==== KIT KD8 END ====
// ==== Candle units and the confirmed stall count the panel rows read ====
mrDaily = timeframe.isdaily and timeframe.multiplier == 1
// The chart timeframe as a trader writes it (1D, 4h, 15m, 1W), for the record's horizon wording (whole hours read "4h").
mrTfName = timeframe.isminutes ? (timeframe.multiplier % 60 == 0 ? str.tostring(int(timeframe.multiplier / 60)) + "h" : timeframe.period + "m") : timeframe.isdwm ? str.tostring(timeframe.multiplier) + (timeframe.isdaily ? "D" : timeframe.isweekly ? "W" : "M") : timeframe.period
// The one study line of the panel title hover (crypto charts; Custom is not studied; other markets say "Unchecked on this market").
const string MR_CUSTOM_LABEL = "Your settings, not checked here"
mrStudyNote = engCustom or not engCrypto ? "" : not ofMeasured ? "Our four-coin study did not measure " + engProfileIn + " on " + mrTfName + ". The table shows this chart." : ofStudyBeat ? "" : "In our four-coin study " + engProfileIn + " did not clearly beat a random candle on " + mrTfName + ". The table shows this chart."
// The profile as the panel names it, the settings in use (header tooltip) and the one status sentence that applies, if any.
mrProfLine = engCustom ? MR_CUSTOM_LABEL : engAdaptAsSmooth ? "Adaptive · as Smooth" : engAdaptAsFast ? "Adaptive · as Fast" : engAdaptive ? (engAdaptFallback ? "Adaptive: default Core settings" : "Adaptive · " + mrTfName) : engProfileIn
// Panel title hover: the profile in plain words, settings in use, then the study note or Core-input explanation.
mrProfSentence = engCustom ? "Custom uses your own Core settings; they are not checked here." : engAdaptAsSmooth ? (engHold ? "Adaptive uses Smooth's settings on 1D: closing breakouts, and stalled trends get more time." : "Adaptive uses Smooth's settings on 1D: closing breakouts with longer windows.") : engAdaptAsFast ? "Adaptive uses Fast's settings on 4h: shorter windows, so labels turn sooner." : engAdaptive ? (engAdaptFallback ? "Adaptive uses the default Core settings here, with the ordinary stall exit." : "Adaptive uses longer fixed windows on crypto 1h charts, with the ordinary stall exit.") : engFast ? "Fast uses closing breakouts with shorter windows, so labels turn sooner." : engBalanced ? "Balanced uses the same fixed bar counts on every timeframe, with the ordinary stall exit." : engHold ? "Smooth uses closing breakouts and gives stalled trends more time." : "Smooth uses closing breakouts with longer windows."
mrSettings = mrProfSentence + "\n\nWindows " + str.tostring(engN) + " up / " + str.tostring(engND) + " down, push " + str.tostring(engL) + " candles over " + str.tostring(engA, "0.0") + " ATR, stall " + str.tostring(engK) + (engHold ? " (final " + str.tostring(engKH) + ")" : "") + ".\n\n" + (engCustom ? "These are your Core settings." : mrStudyNote != "" ? mrStudyNote : "Core inputs apply only to Custom.")
mrSettingsLine = "Settings in use: " + engProfileIn + (engAdaptAsSmooth ? " (Smooth's)" : engAdaptAsFast ? " (Fast's)" : "") + ", windows " + str.tostring(engN) + " / " + str.tostring(engND) + ", push " + str.tostring(engL) + " candles x " + str.tostring(engA, "0.0") + " ATR, stall " + str.tostring(engK) + (engHold ? " (final " + str.tostring(engKH) + ")" : "")
// The route line of Adaptive (the older lab lines are superseded by the study line of the title hover).
mrProfStatusBase = not engAdaptive ? "" : engAdaptAsSmooth ? "Adaptive: Smooth's settings on 1D" : engAdaptAsFast ? "Adaptive: Fast's settings on 4h" : engAdaptFallback ? "" : "Adaptive: longer fixed crypto 1h windows"
// On a chart that is not crypto no lab result applies: Adaptive, Fast, Balanced and Smooth say so, next to Adaptive's fallback or 1D sentence.
mrProfStatus = (engPreset or engBalanced) and not engCrypto ? (engAdaptive ? (engAdaptAsSmooth ? "Adaptive: Smooth's settings on 1D" : engAdaptAsFast ? "Adaptive: Fast's settings on 4h" : engAdaptFallback ? "" : "") + "\nUnchecked on this market" : "Unchecked on this market") : mrProfStatusBase
mrSettingsFull = mrSettings + (mrProfStatus == "" ? "" : "\n" + mrProfStatus)
kitJoinLine(string first, string second) =>
first == "" ? second : second == "" ? first : first + "\n" + second
mrUnits(int n) =>
mrDaily ? (n == 1 ? "day" : "days") : (n == 1 ? "bar" : "bars")
mrCount(int n) =>
str.tostring(n) + " " + mrUnits(n)
var int mrStall = 0
if barstate.isconfirmed
mrStall := engSince
// As of the last closed candle (never the open one): the closes the next candle must beat
// (highest of the last N closes, lowest of the last ND, this one included), the push in ATR and the running trend's best close.
// The panel shows them with "Show what would change it" (on by default); nothing is drawn on price. The five flip diagnostics plot them.
engHiNext = ta.highest(close, engLenN)
engLoNext = ta.lowest(close, engLenND)
var float mrUpLvl = na
var float mrDnLvl = na
var float mrPushAtr = na
var float mrBest = na
var float mrLvl = na
var int mrSnapTrend = 0
if barstate.isconfirmed
bool warm = bar_index >= engWarmBars and not na(engAtr)
mrUpLvl := warm ? engHiNext : na
mrDnLvl := warm ? engLoNext : na
mrPushAtr := warm and engAtr > 0 ? engPush / engAtr : na
mrBest := warm and engTrend != 0 ? engExt : na
mrLvl := warm and engTrend != 0 ? engLvl : na
mrSnapTrend := warm ? engTrend : 0
mrFlipAsOf(string when) =>
when == "" ? "State description only." : "Confirmed on the " + when + " close. State description only."
// One decimal with its sign; a value that rounds to zero prints 0.0.
mrSigned1(float v) =>
float r = math.round(v * 10) / 10
(r > 0 ? "+" : "") + str.tostring(r, "0.0")
// A whole number with thousands commas (86,595); prices under 1,000 keep the symbol's tick.
mrGroup(int n) =>
string digits = str.tostring(math.abs(n))
int len = str.length(digits)
string out = ""
for i = 0 to len - 1
if i > 0 and (len - i) % 3 == 0
out += ","
out += str.substring(digits, i, i + 1)
(n < 0 ? "-" : "") + out
mrPx(float v) =>
math.abs(v) >= 1000 ? mrGroup(int(math.round(v))) : str.tostring(v, format.mintick)
// A price at the symbol's tick precision with thousands commas (104,235.67): the rule rows never round a level.
mrPxTick(float v) =>
string raw = str.tostring(math.abs(v), format.mintick)
int dot = str.pos(raw, ".")
string whole = na(dot) ? raw : str.substring(raw, 0, dot)
string frac = na(dot) ? "" : str.substring(raw, dot)
(v < 0 ? "-" : "") + mrGroup(int(str.tonumber(whole))) + frac
const string MR_TIP_RULE_UP = "A close above this level starts Trend up only with a strong push up.\n\nBoth conditions must hold on the same close. The level updates after each close."
const string MR_TIP_RULE_DOWN = "A close below this level starts Trend down only with a strong push down.\n\nBoth conditions must hold on the same close. The level updates after each close."
const string MR_TIP_RULE_WARM = "More closed candles are needed before these rules can be shown.\n\nNo trend or change level is confirmed yet."
const string MR_TIP_RULE_WAITING = "The reading starts after a candle closes."
const string MR_TIP_RULE_FORMING = "No state is confirmed yet. The next eligible close can confirm one."
const string MR_TIP_RULE_NOREAD = "This chart cannot be read. Use standard candles with available prices."
// The panel title hover ends with the meaning of the labels and dots.
const string MR_TIP_PANEL_LEGEND = "Closed-candle labels, not trade signals. Dot = where a label started, not an entry."
const string MR_TIP_TOO_LONG = "This profile needs more history than a chart can hold on this interval.\n\nChoose a higher timeframe."
// ==== Runs, receipts and the finished-run lists the panel and the dots read ====
// A run is a stretch of closed candles with one state. It starts on the candle whose close confirmed the state and finishes on the
// candle that confirms the next one. Extreme close: the highest close of a Trend up run, the lowest of a Trend down run, against the
// run's start close. End result: the close of the finishing candle against the start close. The first run after warm-up has no
// confirmed start, so it gets no receipt and is never counted. Nothing here changes a state, a mark or an alert time.
const int MR_RECENT_W = 750
const string MR_DASH = "-"
const int MR_RECENT_MIN_RUNS = 5
const string MR_TIP_RUN_STALL = "Price can move back from a trend's highest or lowest close while the trend remains active. It ends when its exit rule is met. This is not a trade result."
const string MR_TIP_SINCE = "This run so far, measured from its first confirmed close."
const string MR_TIP_SINCE_CAVEAT = "A price change, not a trade return."
const string MR_TIP_PAST_CAVEAT = "These runs do not forecast this one."
// A signed percent with one decimal (+9.4%, -3.4%, 0.0%).
mrPct1(float v) =>
float r = math.round(v * 1000) / 10
(r > 0 ? "+" : "") + str.tostring(r, "0.0") + "%"
// Nonpositive prices: a percentage needs two closes strictly above zero. With a zero or negative close at either end the
// percentage is unavailable: na here, printed as a word, never as a number, and never counted as higher or lower. States, run
// lengths and candle counts do not depend on it. math.sign keeps a tiny positive close positive (Pine's > treats gaps near
// 1e-11 as equal).
const string MR_NO_PCT = "unavailable"
const string MR_NO_PCT_WHY = "A percentage needs both closes above zero."
mrPosPx(float v) =>
not na(v) and math.sign(v) > 0
mrPctOf(float last, float base) =>
mrPosPx(last) and mrPosPx(base) ? last / base - 1 : na
var int mrRunId = 0
var int mrRunSt = 0
var bool mrRunFirst = false
var float mrRunStartClose = na
var float mrRunBest = na
var int mrRunLen = 0
var float mrRunBestPct = na
var float mrRunNow = na
var string mrRunTipPrice = ""
var string mrRunTipWhen = ""
var label mrRunCore = na
var label mrRunRing = na
var array<float> mrLenUp = array.new<float>()
var array<float> mrBestUp = array.new<float>()
var array<float> mrEndUp = array.new<float>()
var array<float> mrLenDown = array.new<float>()
var array<float> mrBestDown = array.new<float>()
var array<float> mrEndDown = array.new<float>()
var array<float> mrLenChop = array.new<float>()
// The receipt when a percentage is unavailable (a close at or below zero at the run's start, best close or last close): the same
// sentence with the word in place of the number, then the reason.
mrReceiptNa(int st, int len, float best, float last, bool done) =>
string bestHead = st == 2 ? "Lowest close " : "Highest close "
string bestText = na(best) ? bestHead + MR_NO_PCT : best == 0 ? "No new " + (st == 2 ? "lowest" : "highest") + " close" : bestHead + mrPct1(best) + " from its start"
string endText = na(last) ? "End result " + MR_NO_PCT + "." : "Ended " + mrPct1(last) + " from its start."
string nowText = na(last) ? "Move from its start " + MR_NO_PCT + "." : "Now " + mrPct1(last) + " from its start."
(done ? (st == 2 ? "This trend down: " : "This trend up: ") + mrCount(len) + ". " + bestText + ". " + endText : "Running " + mrCount(len) + ". " + bestText + (na(best) ? "" : " so far") + ". " + nowText) + " " + MR_NO_PCT_WHY
// The receipt of a trend run: finished ("This trend up: 32 days. Highest close +9.4% from its start. Ended +2.4% from its start.")
// or still running.
mrReceipt(int st, int len, float best, float last, bool done) =>
string bestName = st == 2 ? "lowest" : "highest"
string bestText = best == 0 ? "No new " + bestName + " close" : (st == 2 ? "Lowest close " : "Highest close ") + mrPct1(best) + " from its start"
string full = done ? (st == 2 ? "This trend down: " : "This trend up: ") + mrCount(len) + ". " + bestText + ". Ended " + mrPct1(last) + " from its start." : "Running " + mrCount(len) + ". " + bestText + " so far. Now " + mrPct1(last) + " from its start."
na(best) or na(last) ? mrReceiptNa(st, len, best, last, done) : full
mrRunTip(string receipt) =>
kitTip(mrRunSt == 1 ? KIT_TIP_MARK_1 : KIT_TIP_MARK_2, "", mrRunTipPrice + "\n" + receipt, mrRunTipWhen)
// Per candle: the finished run's numbers on the candle that finished it (na elsewhere), and the state of a counted trend start.
float mrFinLen = na
float mrFinBest = na
float mrFinEnd = na
int mrFinSt = 0
int mrStartSt = 0
if barstate.isconfirmed and kdState != 0
if kdState != mrRunSt
if mrRunSt != 0 and not mrRunFirst
float endPct = mrPctOf(close, mrRunStartClose)
float bestPct = mrRunSt == KIT_KD1_NEUTRAL ? na : mrPctOf(mrRunBest, mrRunStartClose)
mrFinLen := mrRunLen
mrFinBest := bestPct
mrFinEnd := endPct
mrFinSt := mrRunSt
// The length of every finished run is kept; an unavailable best close or end result is left out of its list.
if mrRunSt == 1
array.push(mrLenUp, mrRunLen)
if not na(bestPct)
array.push(mrBestUp, bestPct)
if not na(endPct)
array.push(mrEndUp, endPct)
else if mrRunSt == 2
array.push(mrLenDown, mrRunLen)
if not na(bestPct)
array.push(mrBestDown, bestPct)
if not na(endPct)
array.push(mrEndDown, endPct)
else
array.push(mrLenChop, mrRunLen)
if mrRunSt != KIT_KD1_NEUTRAL
string doneTip = mrRunTip(mrReceipt(mrRunSt, mrRunLen, bestPct, endPct, true))
if not na(mrRunCore)
label.set_tooltip(mrRunCore, doneTip)
if not na(mrRunRing)
label.set_tooltip(mrRunRing, doneTip)
mrRunId += 1
mrRunFirst := mrRunId == 1
mrRunSt := kdState
mrRunStartClose := close
mrRunBest := close
mrRunLen := 1
mrRunTipPrice := kitPrice(close)
mrRunTipWhen := "Confirmed on the " + kitWhen() + " close."
mrStartSt := not mrRunFirst and kdState != KIT_KD1_NEUTRAL ? kdState : 0
bool marked = kitGate and kitShowChangeMarks and kitChangeMark
int marks = array.size(k8Marks)
mrRunCore := marked and marks > 0 ? array.get(k8Marks, marks - 1) : na
mrRunRing := marked and not KIT_KD8_ON_PRICE and marks > 1 ? array.get(k8Marks, marks - 2) : na
else
mrRunLen += 1
if mrRunSt == 1
mrRunBest := math.max(mrRunBest, close)
else if mrRunSt == 2
mrRunBest := math.min(mrRunBest, close)
mrRunBestPct := mrRunSt == KIT_KD1_NEUTRAL ? na : mrPctOf(mrRunBest, mrRunStartClose)
mrRunNow := mrPctOf(close, mrRunStartClose)
// The running trend's dot carries its receipt so far, refreshed on the last closed candle only.
if (barstate.islastconfirmedhistory or barstate.isrealtime) and mrRunSt != KIT_KD1_NEUTRAL and not mrRunFirst and not na(mrRunCore)
string runTip = mrRunTip(mrReceipt(mrRunSt, mrRunLen, mrRunBestPct, mrRunNow, false))
label.set_tooltip(mrRunCore, runTip)
if not na(mrRunRing)
label.set_tooltip(mrRunRing, runTip)
// The Since start row (panel): the move printed after the age, and the number block of its tooltip, as of the last closed candle.
mrSinceValue() =>
string shown = mrRunSt == 0 or mrRunFirst or na(mrRunNow) ? "" : " · " + mrPct1(mrRunNow)
mrRunSt != 0 and not mrRunFirst and na(mrRunNow) ? " · n/a" : shown
// Bars as the hovers name them: "daily bars" on a daily chart (the code counts bars, not calendar days), "bars" elsewhere.
mrBarWord(int n) =>
str.tostring(n) + (mrDaily ? (n == 1 ? " daily bar" : " daily bars") : (n == 1 ? " bar" : " bars"))
// The label hover of the Since start row: this run so far.
mrSinceNow() =>
string now = mrRunSt == 0 ? "" : mrRunFirst ? "This run began before the first counted candle, so it has no start to measure from." : na(mrRunNow) ? mrBarWord(mrRunLen) + "; close change " + MR_NO_PCT + "." : mrBarWord(mrRunLen) + "; close change " + mrPct1(mrRunNow) + "."
kitTip(MR_TIP_SINCE, "", now, MR_TIP_SINCE_CAVEAT)
// The value hover of the Since start row: earlier completed runs of this state in loaded history.
mrSincePast() =>
bool trend = mrRunSt == 1 or mrRunSt == 2
array<float> lens = mrRunSt == 1 ? mrLenUp : mrRunSt == 2 ? mrLenDown : mrLenChop
array<float> bests = mrRunSt == 2 ? mrBestDown : mrBestUp
array<float> ends = mrRunSt == 2 ? mrEndDown : mrEndUp
int done = array.size(lens)
string ext = mrRunSt == 2 ? "lowest" : "highest"
string head = "Earlier completed " + kitStateName(mrRunSt) + " runs in loaded history."
string past = str.tostring(done) + (done == 1 ? " run" : " runs")
if done < MR_RECENT_MIN_RUNS
past += "; too few to describe."
else
past += ". Median length: " + str.tostring(array.median(lens), "0.#") + (mrDaily ? " daily bars." : " bars.")
if trend
// Only runs with an available percentage are in bests and ends, so the medians and the count read those runs alone.
int nBests = array.size(bests)
int nEnds = array.size(ends)
int above = 0
if nEnds > 0
for i = 0 to nEnds - 1
above += math.sign(array.get(ends, i)) > 0 ? 1 : 0
string midBest = MR_NO_PCT
string midEnd = MR_NO_PCT
if nBests > 0
midBest := mrPct1(array.median(bests)) + " from start"
if nEnds > 0
midEnd := mrPct1(array.median(ends)) + " from start"
past += "\nMedian " + ext + " close: " + midBest + ".\nMedian final close: " + midEnd + ".\n" + str.tostring(above) + " of " + str.tostring(nEnds) + " ended above their start."
mrRunSt == 0 ? "" : kitTip(head, "", past, MR_TIP_PAST_CAVEAT)
// The note on unavailable percentages (a close at or below zero), kept out of the Since start hover so that hover stays short:
// why a percentage is missing and how many finished runs of this state have none. Empty on ordinary charts.
mrSinceNote() =>
bool trend = mrRunSt == 1 or mrRunSt == 2
array<float> lens = mrRunSt == 1 ? mrLenUp : mrRunSt == 2 ? mrLenDown : mrLenChop
array<float> bests = mrRunSt == 2 ? mrBestDown : mrBestUp
array<float> ends = mrRunSt == 2 ? mrEndDown : mrEndUp
int done = array.size(lens)
bool nowNa = mrRunSt != 0 and not mrRunFirst and na(mrRunNow)
bool gaps = trend and done >= MR_RECENT_MIN_RUNS and (array.size(bests) < done or array.size(ends) < done)
string counts = gaps ? " Finished runs without a " + (mrRunSt == 2 ? "lowest" : "highest") + " close percentage: " + str.tostring(done - array.size(bests)) + "; without an end result: " + str.tostring(done - array.size(ends)) + "." : ""
nowNa or gaps ? MR_NO_PCT_WHY + counts : ""
// ==== KIT KD3 START ====
// KD3 reading panel for K-D: the T3 face with condition rows, read from the last
// closed candle. A header row: the indicator's short name on the left in title ink, the confirmed condition on the right in its colour,
// one size larger, on a header tinted by that condition (KB3's zone-tinted header). Label rows: a muted label on the left, the value on
// the right. A 2 px frame and a 1 px inner border; detail lives in the tooltips.
// KIT_T3_ROWS counts every row, the header included: 3 by default (header, Confidence, State age). An indicator may use 2 to 4 and says why
// in KIT_T3_ROWS_REASON: 2 = header and Confidence; 4 = the default three and KIT_T3_LABEL_3 (the reading's value).
// Confidence reads how clearly the last closed candle supports the confirmed condition: its candidate's step when the candidate is the
// confirmed condition, Weak when it points elsewhere. A provisional change (a candidate not confirmed yet) is named in the header
// tooltip only. Status faces: Waiting, Warming up, No reading (the chart cannot be read, or too little usable data) and Forming (ready,
// no condition confirmed yet); the status word sits in the header state cell and every row value shows "-", so the panel keeps its shape.
// Panel on: the price chart by default, so the panel never covers the pane line; in the pane, a hidden anchor over the last
// KIT_KD3_ROOM_BARS candles makes room above the line's top (top placements) or under the rail (bottom placements).
// Slots: title, labels, words, text sizes, chrome widths, the header tints and the pane room. Every colour comes from T6 through kitPal.
const int KIT_T3_ROWS = 2
const string KIT_T3_ROWS_REASON = "State and its age and change; the two rule rows show by default (Show what would change it) and can be turned off; confidence is not measured."
const string KIT_T3_TITLE = "Market Regime"
const string KIT_T3_LABEL_1 = "State age"
const string KIT_T3_LABEL_2 = "Stall"
const string KIT_T3_LABEL_3 = "Reading"
const string KIT_T3_STRONG = "Strong"
const string KIT_T3_NORMAL = "Normal"
const string KIT_T3_WEAK = "Weak"
const string KIT_T3_BAR = " bar"
const string KIT_T3_BARS = " bars"
const string KIT_T3_WAITING = "Waiting"
const string KIT_T3_WARMING = "Warming up"
const string KIT_T3_NO_READING = "No reading"
const string KIT_T3_FORMING = "Forming"
const string KIT_T3_EMPTY = "-"
const string KIT_T3_TITLE_SIZE = size.normal
const string KIT_T3_STATE_SIZE = size.large
const string KIT_T3_ROW_SIZE = size.normal
const int KIT_T3_FRAME_PX = 2
const int KIT_T3_BORDER_PX = 1
const bool KIT_T3_TOP_CLEARANCE = true
const float KIT_KD3_ROOM = 0.8
const int KIT_KD3_ROOM_BARS = 150
// Header tint transparency (0 opaque, 100 invisible) over the panel base, and the contrast every condition-coloured text keeps on its cell.
const int KIT_KD3_STATE_TINT_FADE = 75
const int KIT_KD3_NEUTRAL_TINT_FADE = 80
const float KIT_KD3_TEXT_FLOOR = 4.5
const string KIT_TIP_STATE_1 = "Trend up under these rules.\n\nThe close broke the recent high with a strong push. The trend has not ended."
const string KIT_TIP_STATE_2 = "Trend down under these rules.\n\nThe close broke the recent low with a strong downward push. The trend has not ended."
const string KIT_TIP_STATE_3 = "No active trend under these rules.\n\nChop need not be quiet. Price can be ranging, pausing or moving sharply. The rail uses a thin neutral line."
const string KIT_TIP_CONFIDENCE = "This row shows how clearly the last closed candle supports the confirmed condition.\n\nStrong and Normal: the reading still points the same way. Weak: the reading has faded or points elsewhere."
const string KIT_TIP_AGE = "This row counts the closed candles since the state began.\n\nThe count starts again when a new state begins. It describes the past, not how long the state will last."
const string KIT_TIP_READING = "This row shows the reading's value on the closed candle.\n\nIt runs from the choppy end to the trending end, with the middle meaning neither."
const string KIT_TIP_WAITING = "The reading starts after a candle closes.\n\nThe panel uses closed candles only."
const string KIT_TIP_WARMING = "The reading needs more closed candles first.\n\nThe panel uses closed candles only."
const string KIT_TIP_NO_READING = "The indicator cannot read this chart.\n\nThe chart has a missing price or is not a standard candle chart."
const string KIT_TIP_NO_DATA = "The indicator has too little usable data here.\n\nToo many recent candles show no trading, so no condition is named until enough return."
const string KIT_TIP_FORMING = "No state is confirmed yet.\n\nThe first state is named on the next closed candle."
// Last closed candle snapshot: the panel never shows an unfinished candle.
var string t3Status = KIT_T3_WAITING
var bool t3NoData = false
var int t3State = 0
var int t3Age = 0
var int t3Step = 1
var int t3Pending = 0
var int t3PendingRun = 0
var bool t3PendingWeak = false
var float t3Reading = na
var string t3When = ""
if barstate.isconfirmed
t3NoData := engReady and not kitReady
t3Status := not engValid ? KIT_T3_NO_READING : not engReady or bar_index < engWarmBars ? KIT_T3_WARMING : not kitReady ? KIT_T3_NO_READING : kdState == 0 ? KIT_T3_FORMING : ""
t3State := kdState
t3Age := kdAge
t3Step := kdRunState == kdState ? kdStep : 1
t3Pending := kdRunState != kdState ? kdRunState : 0
t3PendingRun := kdRun
t3PendingWeak := kdWeakHeld
t3Reading := engStateValue
t3When := kitWhen()
t3Pos = kitPanelPos == "Top Left" ? position.top_left : kitPanelPos == "Btm Right" ? position.bottom_right : kitPanelPos == "Btm Left" ? position.bottom_left : position.top_right
t3ShowTable = kitPanelPos != "Off"
t3OnPrice = kitPanelOn == "Price"
// Room in the pane: a hidden anchor past the line's top or under the rail on the panel's side, drawn on the last KIT_KD3_ROOM_BARS
// candles only (show_last), so it never holds the scale over older history.
t3RoomTop = kitPanelPos == "Top Right" or kitPanelPos == "Top Left"
t3RoomValue = t3RoomTop ? KIT_KD2_HIGH + KIT_KD3_ROOM : KIT_KD2_RAIL_LEVEL - KIT_KD3_ROOM
// Room on the price chart: a hidden anchor on the panel's side, sized to the panel. It sits past the extreme of the last
// KIT_KD3_PANEL_BARS candles (the ones the panel can cover) by a share of their distance to the far side of the recent range, so those
// candles clear the panel at the default zoom and the scale stretches no further. The anchor exists only on the last candle:
// the price scale fits every plot value in the visible candles even with show_last, so older anchors could stretch the scale.
const float KIT_KD3_PRICE_ROOM_TOP = 0.26
const float KIT_KD3_PRICE_ROOM_BOTTOM = 0.15
// With "Show what would change it" on, the panel has four rows with two-line values. MR_ROOM_BOTTOM_RULES reserves
// more room below recent candles so they stay clear at the default zoom. With rule rows off, MR_ROOM_BOTTOM is used.
const float MR_ROOM_BOTTOM = 0.24
const float MR_ROOM_BOTTOM_RULES = 0.50
const int KIT_KD3_PANEL_BARS = 30
kd3PriceHigh = ta.highest(high, KIT_KD3_ROOM_BARS)
kd3PriceLow = ta.lowest(low, KIT_KD3_ROOM_BARS)
kd3PanelHigh = ta.highest(high, KIT_KD3_PANEL_BARS)
kd3PanelLow = ta.lowest(low, KIT_KD3_PANEL_BARS)
kd3PriceRoom = t3RoomTop ? kd3PanelHigh + KIT_KD3_PRICE_ROOM_TOP * (kd3PanelHigh - kd3PriceLow) : kd3PanelLow - (mrRulesIn ? MR_ROOM_BOTTOM_RULES : MR_ROOM_BOTTOM) * (kd3PriceHigh - kd3PanelLow)
plot(t3ShowTable and t3OnPrice and barstate.islast ? kd3PriceRoom : na, "Price panel room", color=color.new(KIT_NEUTRAL_DARK, 100), display=display.pane, editable=false, show_last=1, force_overlay=true)
plot(t3ShowTable and not t3OnPrice and kitReady ? t3RoomValue : na, "Panel room", color=color.new(kitPal.flat, 100), display=display.pane, editable=false, show_last=KIT_KD3_ROOM_BARS)
// Legend spacer: where the panel sits under a legend (Top Left, a Panel option an indicator may add in KD7) a transparent spacer row
// clears it and the frame is dropped there, so no empty framed box draws above the header. On the price chart the
// same transparent row also clears Top Right, where TradingView's pane buttons would otherwise cover the state word.
t3Spacer = KIT_T3_TOP_CLEARANCE and (kitPanelPos == "Top Left" or (kitPanelPos == "Top Right" and t3OnPrice))
t3Row0 = t3Spacer ? 1 : 0
t3CellBg = t3Spacer ? kitPal.base : color(na)
// force_overlay takes a constant, so the panel exists twice, once per chart area; only the chosen one is filled.
// Four rows by default (header, Since start, two rule rows); two with "Show what would change it" off. No legend row.
mrT3Rows = mrRulesIn ? 4 : KIT_T3_ROWS
var table t3PriceTable = table.new(t3Pos, 2, mrT3Rows + 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, force_overlay=true)
var table t3PaneTable = table.new(t3Pos, 2, mrT3Rows + 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)
t3Table = t3OnPrice ? t3PriceTable : t3PaneTable
// The colour a viewer sees where top is painted over an opaque colour (alpha compositing).
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))
// A condition-coloured text keeps its ink where it reads at KIT_KD3_TEXT_FLOOR on its cell as drawn on the chart, else black or white.
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_KD3_TEXT_FLOOR ? ink : kitInkOn(seen)
t3LabelInk = t3Readable(kitPal.labelInk, t3Over(kitPal.base, chart.bg_color))
t3Head(string state, color stateColor, color headBg, string titleTip, string tip) =>
table.cell(t3Table, 0, t3Row0, KIT_T3_TITLE, text_color=kitPal.titleInk, bgcolor=headBg, text_size=KIT_T3_TITLE_SIZE, text_halign=text.align_left, tooltip=titleTip)
table.cell(t3Table, 1, t3Row0, state, text_color=stateColor, bgcolor=headBg, text_size=KIT_T3_STATE_SIZE, 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=t3LabelInk, bgcolor=t3CellBg, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_left, tooltip=tip)
table.cell(t3Table, 1, t3Row0 + row, valueText, text_color=valueColor, bgcolor=t3CellBg, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_right, tooltip=tip)
// The same row with one hover per cell: the label explains the row, the value carries its numbers.
t3RowSplit(int row, string labelText, string valueText, color valueColor, string labelTip, string valueTip) =>
table.cell(t3Table, 0, t3Row0 + row, labelText, text_color=t3LabelInk, bgcolor=t3CellBg, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_left, tooltip=labelTip)
table.cell(t3Table, 1, t3Row0 + row, valueText, text_color=valueColor, bgcolor=t3CellBg, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_right, tooltip=valueTip)
if barstate.islast
bool face = t3Status != ""
color baseSeen = t3Over(kitPal.base, chart.bg_color)
color headTint = t3State == 1 or t3State == 2 ? color.new(kitStateColor(kitPal, t3State), KIT_KD3_STATE_TINT_FADE) : color.new(kitPal.flat, KIT_KD3_NEUTRAL_TINT_FADE)
color headSeen = t3Over(headTint, baseSeen)
color headBg = face ? t3CellBg : t3Spacer ? headSeen : headTint
string closedOn = t3When == "" ? KIT_CAVEAT : kitClosedOn(t3When)
string word = face ? t3Status : kitStateName(t3State)
string statusHead = engTooLong ? MR_TIP_TOO_LONG : t3Status == KIT_T3_WAITING ? KIT_TIP_WAITING : t3Status == KIT_T3_WARMING ? KIT_TIP_WARMING : t3Status == KIT_T3_FORMING ? KIT_TIP_FORMING : t3NoData ? KIT_TIP_NO_DATA : KIT_TIP_NO_READING
string statusNumbers = t3Status == KIT_T3_WARMING ? "Closed candles still needed: " + str.tostring(math.max(engWarmBars - (bar_index - (barstate.isconfirmed ? 0 : 1)), 1)) : ""
string pendingText = t3Pending == 0 ? "" : "Not confirmed yet: the reading has pointed to " + kitStateName(t3Pending) + " for " + str.tostring(t3PendingRun) + (t3PendingRun == 1 ? " closed candle" : " closed candles") + (t3PendingWeak ? ", too weakly to confirm it." : ".")
// A status face gives every cell the status tooltip, as the kit panel does; a reading gives each row its own.
string faceNumbers = statusNumbers == "" ? pendingText : statusNumbers
// The header row is split by subject so every hover stays short. State cell: what the state means, plus the profile's status
// sentence. Title cell: the settings in use (and, with non-positive prices, the note on unavailable percentages).
// Rule facts as of the last closed candle, in the rule rows' words, for the state hover.
bool inTrend = not face and (t3State == 1 or t3State == 2)
bool ruleTrend = inTrend and mrSnapTrend == (t3State == 1 ? 1 : -1) and not na(mrBest)
bool ruleLvl = ruleTrend and engHold and not na(mrLvl)
bool ruleChop = not face and t3State == KIT_KD1_NEUTRAL and mrSnapTrend == 0 and not na(mrUpLvl) and not na(mrDnLvl)
string resetLine = ruleTrend ? "Count resets if: close " + (t3State == 1 ? "> " : "< ") + mrPxTick(mrBest) : ""
string ruleFacts = ruleLvl ? "Trend ends if: " + str.tostring(engK) + "+ stalled closes AND close " + (t3State == 1 ? "< " : "> ") + mrPxTick(mrLvl) + "\nStalled closes: " + str.tostring(mrStall) + " of " + str.tostring(engKH) + "\n" + resetLine : ruleTrend and not engHold ? "Stalled closes: " + str.tostring(mrStall) + " of " + str.tostring(engK) + "\n" + resetLine : ruleChop ? "Trend up if: close > " + mrPxTick(mrUpLvl) + " AND strong push up\nTrend down if: close < " + mrPxTick(mrDnLvl) + " AND strong push down" : ""
string confirmedOn = t3When == "" ? "" : "Confirmed on the " + t3When + " close."
string stateTip = face ? kitTip(statusHead, "", faceNumbers, closedOn) : kitTip(t3State == 1 ? KIT_TIP_STATE_1 : t3State == 2 ? KIT_TIP_STATE_2 : KIT_TIP_STATE_3, "", kitJoinLine(mrProfStatus, ruleFacts), confirmedOn)
string titleTip = face ? kitTip(mrSettingsFull, "", "", closedOn) : kitTip(mrSettings, "", mrSinceNote(), MR_TIP_PANEL_LEGEND)
table.clear(t3Table, 0, 0, 1, mrT3Rows - 1 + t3Row0)
if t3ShowTable
if t3Spacer
table.cell(t3Table, 0, 0, " \n \n ", text_color=color.new(kitPal.valueInk, 100), bgcolor=na, text_size=size.small)
t3Head(word, face ? kitPal.valueInk : t3Readable(kitStateText(kitPal, t3State), headSeen), headBg, titleTip, stateTip)
// Row 1 Since start: the age and, beside it, the close against the close that began the state, then the profile. The label hover is
// this run so far; the value hover is the earlier completed runs of this state.
t3RowSplit(1, "Since start", face ? KIT_T3_EMPTY : mrCount(t3Age) + mrSinceValue() + "\n" + mrProfLine, kitPal.valueInk, face ? stateTip : mrSinceNow(), face ? stateTip : mrSincePast())
// Rows 2 and 3 explain what would change the reading as of the last closed candle. Chop shows the two start rules.
// Profiles using the hold exit show both early-exit conditions, then the remaining closes without a new extreme
// before the final limit. Profiles using the ordinary exit show the remaining closes without a new extreme
// before the stall limit, and the close that resets the count. The hovers describe the same rules.
string extName = t3State == 2 ? "lowest" : "highest"
if mrRulesIn
string asOf = t3When == "" ? "" : "As of " + t3When + "."
string asOfSp = asOf == "" ? "" : asOf + " "
string asOfBlock = asOf == "" ? "" : "\n\n" + asOf
bool up = t3State == 1
if inTrend
int left = math.max(engK - mrStall, 0)
if engHold
// Smooth with the hold exit: both conditions of the exit, then the final stall limit.
int leftH = math.max(engKH - mrStall, 0)
string clearTip = "Both conditions are needed to clear this label early." + (ruleLvl ? "\n\nAt least " + str.tostring(engK) + " closes without a new " + extName + " close, AND a close " + (up ? "below " : "above ") + mrPxTick(mrLvl) + ". Matching that price does not count.\nCurrent count: " + str.tostring(mrStall) + " of " + str.tostring(engK) + ". Final stall limit: " + str.tostring(engKH) + "." : "") + "\n\n" + asOfSp + "Not a reversal forecast."
string capTip = "Closes without a new extreme, against the final limit. Reaching it clears this label at any price." + (ruleLvl ? "\n\nStalled closes: " + str.tostring(mrStall) + " of " + str.tostring(engKH) + ".\nCount resets if: close " + (up ? "> " : "< ") + mrPxTick(mrBest) + ". Matching it does not reset the count." : "") + "\n\n" + asOfSp + "Not a reversal forecast."
t3Row(2, "Trend ends if", ruleLvl ? str.tostring(engK) + "+ stalled closes\nAND close " + (up ? "< " : "> ") + mrPxTick(mrLvl) : KIT_T3_EMPTY, kitPal.valueInk, clearTip)
t3Row(3, "Or ends after", ruleLvl ? str.tostring(leftH) + (leftH == 1 ? " close with no\nclose " : " closes with no\nclose ") + (up ? "> " : "< ") + mrPxTick(mrBest) : KIT_T3_EMPTY, kitPal.valueInk, capTip)
else
string countTip = "Closes since this trend's best close without a new one.\n\nReaching the limit clears this label; it does not predict a reversal." + (ruleTrend ? "\n\nStalled closes: " + str.tostring(mrStall) + " of " + str.tostring(engK) + "." : "") + asOfBlock
string resetTip = "A close " + (up ? "above the highest" : "below the lowest") + " close since this trend started resets the stall count.\n\nMatching it does not. This keeps the " + (up ? "Trend up" : "Trend down") + " label; it is not a target or an exit price." + (ruleTrend ? "\n\n" + (up ? "Highest close: " : "Lowest close: ") + mrPxTick(mrBest) + "." : "") + asOfBlock
t3Row(2, "Trend ends after", ruleTrend ? str.tostring(left) + (left == 1 ? " close with no\nnew " : " closes with no\nnew ") + (up ? "high" : "low") + " close" : KIT_T3_EMPTY, kitPal.valueInk, countTip)
t3Row(3, "Unless close", ruleTrend ? (up ? "Above " : "Below ") + mrPxTick(mrBest) + "\nresets the count" : KIT_T3_EMPTY, kitPal.valueInk, resetTip)
else
string ruleAsOf = mrFlipAsOf(t3When)
string faceTip = t3Status == KIT_T3_WARMING ? kitTip(MR_TIP_RULE_WARM, "", statusNumbers, "") : t3Status == KIT_T3_WAITING ? MR_TIP_RULE_WAITING : t3Status == KIT_T3_FORMING ? MR_TIP_RULE_FORMING : MR_TIP_RULE_NOREAD
string pushOver = " ATR over " + str.tostring(engL) + " candles"
t3Row(2, "Trend up if", ruleChop ? "Close > " + mrPxTick(mrUpLvl) + "\nAND strong push up" : KIT_T3_EMPTY, kitPal.valueInk, face ? faceTip : kitTip(MR_TIP_RULE_UP, "", ruleChop ? "Close above: " + str.tostring(mrUpLvl, format.mintick) + "\nPush above: " + str.tostring(engA, "0.0") + pushOver : "", ruleAsOf))
t3Row(3, "Trend down if", ruleChop ? "Close < " + mrPxTick(mrDnLvl) + "\nAND strong push down" : KIT_T3_EMPTY, kitPal.valueInk, face ? faceTip : kitTip(MR_TIP_RULE_DOWN, "", ruleChop ? "Close below: " + str.tostring(mrDnLvl, format.mintick) + "\nPush below: -" + str.tostring(engA, "0.0") + pushOver : "", ruleAsOf))
// ==== KIT KD3 END ====
// ==== The state on price ====
// A soft wash behind the candles of a running trend, Chop clear; candle colour is optional and off by default. Both read the confirmed
// state, so the open candle keeps the last closed state, and neither changes the states, the record or the alerts.
const int MR_WASH_FADE_DARK = 86
const int MR_WASH_FADE_LIGHT = 90
mrTrendOn = kdState == 1 or kdState == 2
mrWash = mrShadeIn and mrTrendOn ? color.new(kitStateColor(kitPal, kdState), kitPal.light ? MR_WASH_FADE_LIGHT : MR_WASH_FADE_DARK) : color(na)
bgcolor(mrWash, title="Price wash", editable=false, force_overlay=true)
barcolor(mrCandlesIn and mrTrendOn ? kitStateColor(kitPal, kdState) : color(na), title="Candle colour", editable=false)
mrLastConfNow = barstate.isconfirmed and (barstate.islastconfirmedhistory or barstate.isrealtime)
// ==== The after-candle counts (read by the dynamic alert and the Data Window; no table shows them) ====
// At each closed candle with a confirmed state the change over the last twenty candles, close / close twenty candles back - 1, is
// credited to the state confirmed twenty candles back, never to today's state; warm-up candles and the last twenty candles (still
// open outcomes) never count. Runs start at the first state and at every change; a completed run is one that has ended.
// Nonpositive prices: an outcome is credited only when both closes are strictly above zero (mrPosPx); with a zero or negative
// close at either end that candle adds nothing to the lifetime, Last 750 or once-per-trend counts.
const int MR_HORIZON = 20
const int MR_MIN_RUNS = 5
mrIdx(int s) =>
s == 1 ? 0 : s == 2 ? 2 : 1
mrCode(int s) =>
s == 1 ? 1 : s == 2 ? -1 : s == 3 ? 0 : na
// The confirmed state as one clean code (1 Trend up, 0 Chop, -1 Trend down), Data Window only; the State Changed message reads it.
plot(kdState != 0 ? mrCode(kdState) : na, "State", display=display.data_window, editable=false, precision=0)
var array<int> mrBars = array.from(0, 0, 0)
var array<int> mrRuns = array.from(0, 0, 0)
var array<int> mrMature = array.from(0, 0, 0)
var array<int> mrPositive = array.from(0, 0, 0)
var array<float> mrSum = array.from(0.0, 0.0, 0.0)
var array<float> mrOutUp = array.new<float>()
var array<float> mrOutChop = array.new<float>()
var array<float> mrOutDown = array.new<float>()
var array<float> mrOutAll = array.new<float>()
// One entry per counted candle in step with mrOutAll (higher or not, the state index and
// the run id of the candle the outcome is credited to), rolling counts over the last MR_RECENT_W entries, and the start-only
// outcomes: the outcome of the candle that started each Trend up or Trend down run, one per run.
var array<int> mrOutPos = array.new<int>()
var array<int> mrOutSt = array.new<int>()
var array<int> mrOutRid = array.new<int>()
var array<int> mrRecMature = array.from(0, 0, 0)
var array<int> mrRecPositive = array.from(0, 0, 0)
var array<int> mrRecRuns = array.from(0, 0, 0)
var array<float> mrSoUp = array.new<float>()
var array<float> mrSoDown = array.new<float>()
var int mrSoUpK = 0
var int mrSoDownK = 0
mrBaseRid = mrRunId[MR_HORIZON]
mrBaseStart = mrStartSt[MR_HORIZON]
var int mrLast = 0
// The record starts on the first candle with a confirmed state; mrLoadTime is the first loaded candle (footer tooltip).
var int mrFirstTime = na
var int mrLoadTime = time
var int mrLastTime = na
mrThen = nz(kdState[MR_HORIZON])
mrBase = close[MR_HORIZON]
float mrOutcome = na
int mrCredited = 0
if barstate.isconfirmed and kdState != 0
int i = mrIdx(kdState)
array.set(mrBars, i, array.get(mrBars, i) + 1)
if kdState != mrLast
array.set(mrRuns, i, array.get(mrRuns, i) + 1)
mrLast := kdState
mrLastTime := time
if na(mrFirstTime)
mrFirstTime := time
if mrThen != 0 and mrPosPx(mrBase) and mrPosPx(close)
mrOutcome := close / mrBase - 1
mrCredited := mrThen
int j = mrIdx(mrThen)
array.set(mrMature, j, array.get(mrMature, j) + 1)
// strictly above 0: math.sign keeps a tiny positive outcome positive; Pine's > treats gaps near 1e-11 as equal
array.set(mrPositive, j, array.get(mrPositive, j) + (math.sign(mrOutcome) > 0 ? 1 : 0))
array.set(mrSum, j, array.get(mrSum, j) + mrOutcome)
array.push(j == 0 ? mrOutUp : j == 2 ? mrOutDown : mrOutChop, mrOutcome)
array.push(mrOutAll, mrOutcome)
int pos01 = math.sign(mrOutcome) > 0 ? 1 : 0
array.push(mrOutPos, pos01)
array.push(mrOutSt, j)
array.push(mrOutRid, mrBaseRid)
int nOut = array.size(mrOutPos)
array.set(mrRecMature, j, array.get(mrRecMature, j) + 1)
array.set(mrRecPositive, j, array.get(mrRecPositive, j) + pos01)
if nOut == 1 or array.get(mrOutRid, math.max(nOut - 2, 0)) != mrBaseRid
array.set(mrRecRuns, j, array.get(mrRecRuns, j) + 1)
if nOut > MR_RECENT_W
int oldAt = nOut - 1 - MR_RECENT_W
int jOld = array.get(mrOutSt, oldAt)
array.set(mrRecMature, jOld, array.get(mrRecMature, jOld) - 1)
array.set(mrRecPositive, jOld, array.get(mrRecPositive, jOld) - array.get(mrOutPos, oldAt))
if array.get(mrOutRid, oldAt + 1) != array.get(mrOutRid, oldAt)
array.set(mrRecRuns, jOld, array.get(mrRecRuns, jOld) - 1)
if mrBaseStart == 1
array.push(mrSoUp, mrOutcome)
mrSoUpK += pos01
else if mrBaseStart == 2
array.push(mrSoDown, mrOutcome)
mrSoDownK += pos01
mrDone(int j) =>
array.get(mrRuns, j) - (mrIdx(mrLast) == j and mrLast != 0 ? 1 : 0)
mrSoUpN = array.size(mrSoUp)
mrSoDownN = array.size(mrSoDown)
mrPack(int j) =>
array.get(mrRecMature, j) * 1000000.0 + array.get(mrRecPositive, j) * 1000.0 + array.get(mrRecRuns, j)
// ==== The start race: how past trend starts went (fixed in code, never an input) ====
// A start is a closed candle in Trend up or Trend down whose previous candle has a different state. From its close, with the ATR(14)
// of that candle frozen as the unit, the next MR_RACE_H closes are read in order: the first close at least MR_RACE_M units with the
// trend = reached; at least MR_RACE_M units against it first = against first; neither = not reached. A start is counted only when it
// is MR_RACE_H candles old, even if its race ended sooner; younger starts are open. The baseline runs the same race from every closed
// candle with a state: up races for the Trend up row, down races for the Trend down row. The down race from a candle is the mirror of
// its up race, so one pass gives both. A candle without a positive unit is left out and counted apart. Every comparison is the sign
// of a difference. Nothing here changes a state, a mark, an alert or the after-candle record.
const int MR_RACE_H = 20
const float MR_RACE_M = 2.0
const int MR_RACE_MIN = 10
// Index 0 Trend up, 1 Trend down: mature starts, reached, against first, not reached, and the baseline's reached count.
var array<int> mrRcN = array.from(0, 0)
var array<int> mrRcWin = array.from(0, 0)
var array<int> mrRcLoss = array.from(0, 0)
var array<int> mrRcNone = array.from(0, 0)
var array<int> mrRcBaseWin = array.from(0, 0)
var int mrRcBaseN = 0
var int mrRcSkipStarts = 0
var int mrRcSkipBase = 0
var int mrRcOpenUp = 0
var int mrRcOpenDown = 0
// The record by period reads these lists. One entry per counted candle, oldest first: its close time and the running totals of the
// baseline's up and down races that reached their distance. One entry per counted start: its close time, direction (0 up, 1 down)
// and result (1 right, -1 wrong, 0 unclear).
var array<int> pdBaseT = array.new<int>()
var array<int> pdBaseUp = array.new<int>()
var array<int> pdBaseDn = array.new<int>()
var array<int> pdStT = array.new<int>()
var array<int> pdStD = array.new<int>()
var array<int> pdStR = array.new<int>()
mrRcUnitOk = not na(engAtr) and math.sign(engAtr) > 0
mrRcIsStart = barstate.isconfirmed and (kdState == 1 or kdState == 2) and nz(kdState[1]) != 0 and kdState[1] != kdState
mrRcOpenUpNow = math.sum(mrRcIsStart and mrRcUnitOk and kdState == 1 ? 1 : 0, MR_RACE_H)
mrRcOpenDownNow = math.sum(mrRcIsStart and mrRcUnitOk and kdState == 2 ? 1 : 0, MR_RACE_H)
mrRcThen = nz(kdState[MR_RACE_H])
mrRcThenPrev = nz(kdState[MR_RACE_H + 1])
mrRcUnit = engAtr[MR_RACE_H]
mrRcFrom = close[MR_RACE_H]
mrRcThenClose = time_close[MR_RACE_H]
if barstate.isconfirmed
if mrRcIsStart and not mrRcUnitOk
mrRcSkipStarts += 1
mrRcOpenUp := int(nz(mrRcOpenUpNow))
mrRcOpenDown := int(nz(mrRcOpenDownNow))
if mrRcThen != 0
if not na(mrRcUnit) and math.sign(mrRcUnit) > 0
// The up race from the candle MR_RACE_H back: +1 reached, -1 against first, 0 neither.
int res = 0
float barrier = MR_RACE_M * mrRcUnit
for j = 1 to MR_RACE_H
float diff = close[MR_RACE_H - j] - mrRcFrom
if math.sign(diff - barrier) >= 0
res := 1
break
if math.sign(diff + barrier) <= 0
res := -1
break
mrRcBaseN += 1
if res == 1
array.set(mrRcBaseWin, 0, array.get(mrRcBaseWin, 0) + 1)
else if res == -1
array.set(mrRcBaseWin, 1, array.get(mrRcBaseWin, 1) + 1)
array.push(pdBaseT, mrRcThenClose)
array.push(pdBaseUp, array.get(mrRcBaseWin, 0))
array.push(pdBaseDn, array.get(mrRcBaseWin, 1))
if (mrRcThen == 1 or mrRcThen == 2) and mrRcThenPrev != 0 and mrRcThenPrev != mrRcThen
int d = mrRcThen == 1 ? 0 : 1
int own = mrRcThen == 1 ? res : -res
array.set(mrRcN, d, array.get(mrRcN, d) + 1)
if own == 1
array.set(mrRcWin, d, array.get(mrRcWin, d) + 1)
else if own == -1
array.set(mrRcLoss, d, array.get(mrRcLoss, d) + 1)
else
array.set(mrRcNone, d, array.get(mrRcNone, d) + 1)
array.push(pdStT, mrRcThenClose)
array.push(pdStD, d)
array.push(pdStR, own)
else
mrRcSkipBase += 1
// Small samples: the percent is shown with an asterisk under MR_RACE_MIN calls; the date row
// explains the asterisk.
const string MR_PD_STAR = "*"
const string MR_PD_STAR_NOTE = " · * under 10 calls: not statistically meaningful"
const string MR_TIP_PD_TITLE = "Past trend starts, checked after 20 closes.\n\nRight: a close reaches 2 ATR with the trend before 2 ATR against. ATR(14) is fixed at the start. Against first, or neither within 20 closes, is not right.\n\nRandom: same test from every eligible candle. * = under 10 starts. Past results, not trade win rates or a forecast."
const string MR_TIP_PD_PERIOD = "Each period ends at the last closed candle.\n\nA start counts in a period when its start candle and its 20th close are both inside it. A period longer than the loaded history counts the loaded part and says how much is loaded; a longer one with no extra history reads Same as."
const string MR_TIP_PD_DIR = "Starts of this trend that were right, of all starts old enough to check.\n\nA start with no clear move within 20 candles counts as not right. Under 10 starts the percent carries *: not statistically meaningful."
const string MR_TIP_PD_RANDOM = "Random: the same test from every eligible candle, in the same period and direction.\n\nAll eligible candles are counted; no random sample is drawn. Historical comparison, not a chance for the next candle."
// A period longer than the loaded history: the shortest such row counts the loaded candles and names the span; each longer one
// holds the same candles and says so. The hovers name the span and that the trader's TradingView plan sets how much history loads.
const string MR_TIP_PD_PLAN = "Your TradingView plan sets how much history loads."
const string MR_TIP_PD_PART = "Only part of this period is loaded, so the counts cover the loaded candles only."
const string MR_TIP_PD_DATES = "Loaded: from the first candle with a reading to the last closed candle.\nScrolling back can load more history and change the counts."
const string MR_TIP_PD_STAR = "* Under 10 starts: not statistically meaningful. Chop is not scored."
// ==== The record by period (what the record table shows) ====
// Four rows: the last year, the last 3 years, the last 5 years and the loaded history. A year row starts at the last closed candle's
// close time minus that many calendar years (UTC; 29 February maps to 28 February) and ends at that close. A start counts in a row
// when its own candle closes after the row's start and its 20th close is at or before the row's end, so a start younger than 20
// candles waits and is outside the total. The random-candle comparison runs the same race from every counted candle of the same
// row. A year row is fully loaded when the first candle with a state opens at or before the row's start. The shortest year row that is
// not fully loaded is counted over the loaded candles, so it holds the same candles as the loaded history; every
// longer year row is not counted and reads Same as that row. Everything is recounted once per closed candle (never on an open candle's ticks) and kept in the lists below; a
// direction's place is row x 2 + direction (0 up, 1 down).
const int MR_PD_ROWS = 4
var array<bool> pdLoaded = array.new<bool>(MR_PD_ROWS, false)
var array<bool> pdCounted = array.new<bool>(MR_PD_ROWS, false)
var array<int> pdCut = array.new<int>(MR_PD_ROWS, na)
var array<int> pdBN = array.new<int>(MR_PD_ROWS, 0)
var array<int> pdBW = array.new<int>(MR_PD_ROWS * 2, 0)
var array<int> pdN = array.new<int>(MR_PD_ROWS * 2, 0)
var array<int> pdW = array.new<int>(MR_PD_ROWS * 2, 0)
var array<int> pdL = array.new<int>(MR_PD_ROWS * 2, 0)
var array<int> pdOpen = array.new<int>(MR_PD_ROWS * 2, 0)
mrPdName(int p) =>
p == 0 ? "Last year" : p == 1 ? "Last 3 years" : p == 2 ? "Last 5 years" : "Loaded history"
// The first place in a list of rising times that is after the given time (the list's size when none is).
mrPdFirstAfter(array<int> times, int cut) =>
int lo = 0
int hi = array.size(times)
while lo < hi
int mid = int((lo + hi) / 2)
if array.get(times, mid) > cut
hi := mid
else
lo := mid + 1
lo
// A whole percent, halves up, from whole numbers, so the face never depends on float rounding.
mrPctInt(int k, int n) =>
str.tostring(int(math.floor((200.0 * k + n) / (2.0 * n))))
// This candle as a waiting start: 1 up, 2 down, 0 none.
mrRcStartDir = mrRcIsStart and mrRcUnitOk ? (kdState == 1 ? 1 : 2) : 0
if mrLastConfNow
int tc = time_close
int tcMonth = month(tc, "UTC")
int tcDay = dayofmonth(tc, "UTC")
array.fill(pdBN, 0)
array.fill(pdBW, 0)
array.fill(pdN, 0)
array.fill(pdW, 0)
array.fill(pdL, 0)
array.fill(pdOpen, 0)
int nBase = array.size(pdBaseT)
for p = 0 to MR_PD_ROWS - 1
bool whole = p == MR_PD_ROWS - 1
int cut = whole or na(tc) ? na : timestamp("UTC", year(tc, "UTC") - (p == 0 ? 1 : p == 1 ? 3 : 5), tcMonth, tcMonth == 2 and tcDay == 29 ? 28 : tcDay, hour(tc, "UTC"), minute(tc, "UTC"), second(tc, "UTC"))
bool loaded = whole or (not na(cut) and not na(mrFirstTime) and mrFirstTime <= cut)
// Counted: fully loaded, or the shortest year row that is not (the previous, shorter row is fully loaded, or this is the last year).
bool counted = loaded or p == 0 or array.get(pdLoaded, math.max(p - 1, 0))
array.set(pdCut, p, cut)
array.set(pdLoaded, p, loaded)
array.set(pdCounted, p, counted)
if counted and nBase > 0
int from = whole ? 0 : mrPdFirstAfter(pdBaseT, cut)
array.set(pdBN, p, nBase - from)
array.set(pdBW, p * 2, array.get(pdBaseUp, nBase - 1) - (from > 0 ? array.get(pdBaseUp, from - 1) : 0))
array.set(pdBW, p * 2 + 1, array.get(pdBaseDn, nBase - 1) - (from > 0 ? array.get(pdBaseDn, from - 1) : 0))
int nSt = array.size(pdStT)
if nSt > 0
for i = 0 to nSt - 1
int stTime = array.get(pdStT, i)
int stDir = array.get(pdStD, i)
int stRes = array.get(pdStR, i)
for p = 0 to MR_PD_ROWS - 1
if array.get(pdCounted, p) and (p == MR_PD_ROWS - 1 or stTime > array.get(pdCut, p))
int at = p * 2 + stDir
array.set(pdN, at, array.get(pdN, at) + 1)
if stRes == 1
array.set(pdW, at, array.get(pdW, at) + 1)
else if stRes == -1
array.set(pdL, at, array.get(pdL, at) + 1)
for i = 0 to MR_RACE_H - 1
int waitDir = nz(mrRcStartDir[i])
if waitDir != 0
int waitTime = time_close[i]
for p = 0 to MR_PD_ROWS - 1
if array.get(pdCounted, p) and (p == MR_PD_ROWS - 1 or waitTime > array.get(pdCut, p))
int at = p * 2 + waitDir - 1
array.set(pdOpen, at, array.get(pdOpen, at) + 1)
// ==== One dynamic alert per confirmed change ====
// Fires on the same closed candles as State Changed, after this candle is counted in the record: the event, symbol, timeframe and
// close, the state it left and how long that lasted, and this chart's after-candle count for the new state (only with at least MR_MIN_RUNS
// completed runs). Set either this alert or the alert conditions, not both.
mrPrevAge = kdAge[1]
mrAlertText() =>
string rec = ""
string ev = kdState == 1 ? "TREND UP STARTED" : kdState == 2 ? "TREND DOWN STARTED" : "CHOP STARTED"
// After a finished trend the Before sentence carries its receipt (highest or lowest close and end result against its start close).
// A finished trend always gets the clause; a part without a percentage (a close at or below zero) reads "unavailable".
string finBest = (kdFrom == 2 ? "lowest" : "highest") + " close " + (na(mrFinBest) ? MR_NO_PCT : mrPct1(mrFinBest) + " from its start")
string finEnd = na(mrFinEnd) ? "end result " + MR_NO_PCT : "ended " + mrPct1(mrFinEnd) + " from its start"
string receipt = mrFinSt == 1 or mrFinSt == 2 ? " (" + finBest + ", " + finEnd + ")" : ""
string before = " Before: " + kitStateName(kdFrom) + (mrPrevAge > 0 ? " for " + mrCount(mrPrevAge) : "") + receipt + "."
KIT_ALERT_HEAD + ev + " on " + syminfo.prefix + ":" + syminfo.ticker + " (" + mrTfName + "), close " + str.tostring(close, format.mintick) + ", bar time " + str.format_time(time, "yyyy-MM-dd HH:mm", "UTC") + " UTC." + before + rec + " Confirmed on bar close."
if kitAnyState
alert(mrAlertText(), alert.freq_once_per_bar_close)
// Same-corner rule: on the price chart the reading panel keeps its corner and the record moves to the other bottom corner.
mrClash = t3ShowTable and t3OnPrice and mrRecordPosIn == kitPanelPos
mrCorner = mrClash ? (mrRecordPosIn == "Btm Right" ? "Btm Left" : "Btm Right") : mrRecordPosIn
// A relocated record says so in its date row, so choosing the panel's corner has a visible effect.
mrClashNote = mrClash ? "\nRecord moved to " + mrCorner + "; panel uses " + kitPanelPos : ""
mrRecPos = mrCorner == "Btm Left" ? position.bottom_left : mrCorner == "Top Left" ? position.top_left : position.bottom_right
var table mrTable = table.new(mrRecPos, MR_PD_COLS, MR_PD_TROWS, bgcolor=kitPal.base, frame_color=kitPal.frame, frame_width=KIT_T3_FRAME_PX, border_color=kitPal.border, border_width=KIT_T3_BORDER_PX, force_overlay=true)
// Record ink: the record table base is translucent and the price wash can sit under it, so every record ink must read at the
// floor over the base on the bare chart and, while the wash is on, over the base on the Trend up and Trend down wash; else black/white.
mrSeenBare = t3Over(kitPal.base, chart.bg_color)
mrSeenUp = t3Over(kitPal.base, t3Over(color.new(kitStateColor(kitPal, 1), kitPal.light ? MR_WASH_FADE_LIGHT : MR_WASH_FADE_DARK), chart.bg_color))
mrSeenDown = t3Over(kitPal.base, t3Over(color.new(kitStateColor(kitPal, 2), kitPal.light ? MR_WASH_FADE_LIGHT : MR_WASH_FADE_DARK), chart.bg_color))
mrReadable(color ink) =>
color bare = t3Readable(ink, mrSeenBare)
mrShadeIn ? t3Readable(t3Readable(bare, mrSeenUp), mrSeenDown) : bare
mrRecInk = mrReadable(kitPal.labelInk)
mrValInk = mrReadable(kitPal.valueInk)
mrTitleInk = mrReadable(kitPal.titleInk)
mrCell(int col, int row, string txt, color ink, string tip) =>
table.cell(mrTable, col, row, txt, text_color=ink, text_size=KIT_T3_ROW_SIZE, text_halign=col == 0 ? text.align_left : text.align_right, tooltip=tip)
// The state-name cell carries the panel header's faint state tint, so the table is the colour key; its ink is the
// state's text colour where it reads at the floor over the tint on the base (bare and, with the wash on, over both washes), else black/white.
mrTint(int s) =>
s == 1 or s == 2 ? color.new(kitStateColor(kitPal, s), KIT_KD3_STATE_TINT_FADE) : color.new(kitPal.flat, KIT_KD3_NEUTRAL_TINT_FADE)
mrNameInk(int s) =>
color tint = mrTint(s)
color bare = t3Readable(kitStateText(kitPal, s), t3Over(tint, mrSeenBare))
mrShadeIn ? t3Readable(t3Readable(bare, t3Over(tint, mrSeenUp)), t3Over(tint, mrSeenDown)) : bare
// A trend's column head carries the panel header's faint state tint, so the table is the colour key.
mrDirHead(int col, int s, string tip) =>
table.cell(mrTable, col, 1, kitStateName(s), text_color=mrNameInk(s), bgcolor=mrTint(s), text_size=KIT_T3_ROW_SIZE, text_halign=text.align_right, tooltip=tip)
// Medians: kept in persistent values, refreshed only on the last confirmed history bar and at each realtime close, and reused
// unchanged on every open-candle tick; the record only changes when a candle closes.
var float mrMedUp = na
var float mrMedChop = na
var float mrMedDown = na
var float mrMedAll = na
if mrLastConfNow
mrMedUp := array.size(mrOutUp) > 0 ? array.median(mrOutUp) : na
mrMedChop := array.size(mrOutChop) > 0 ? array.median(mrOutChop) : na
mrMedDown := array.size(mrOutDown) > 0 ? array.median(mrOutDown) : na
mrMedAll := array.size(mrOutAll) > 0 ? array.median(mrOutAll) : na
if barstate.islast
table.clear(mrTable, 0, 0, MR_PD_COLS - 1, MR_PD_TROWS - 1)
if mrRecordIn
int lastCol = MR_PD_COLS - 1
string firstDate = na(mrFirstTime) ? KIT_T3_EMPTY : str.format_time(mrFirstTime, "d MMM yyyy", syminfo.timezone)
string lastDate = na(mrLastTime) ? KIT_T3_EMPTY : str.format_time(mrLastTime, "d MMM yyyy", syminfo.timezone)
string titleTip = MR_TIP_PD_TITLE
table.cell(mrTable, 0, 0, "How right was the classification?\n" + syminfo.ticker + " · " + mrTfName + " · " + engProfileIn, text_color=mrTitleInk, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_left, tooltip=titleTip)
table.merge_cells(mrTable, 0, 0, lastCol, 0)
mrCell(0, 1, "Period", mrRecInk, MR_TIP_PD_PERIOD)
mrDirHead(1, 1, MR_TIP_PD_DIR)
mrCell(2, 1, "Random", mrRecInk, MR_TIP_PD_RANDOM)
mrDirHead(3, 2, MR_TIP_PD_DIR)
mrCell(4, 1, "Random", mrRecInk, MR_TIP_PD_RANDOM)
// The loaded span, first counted candle to last closed candle: whole months under 24 months, else years to one decimal, both
// rounded down so a partly loaded row never reads as whole.
float loadMo = na(mrFirstTime) or na(mrLastTime) ? na : (mrLastTime - mrFirstTime) / 2629746000.0
string loadSpan = na(loadMo) ? "" : loadMo < 1 ? "under 1 mo" : loadMo < 24 ? str.tostring(math.floor(loadMo)) + " mo" : str.tostring(math.floor(loadMo / 1.2) / 10.0, "0.0") + " y"
string loadedSpan = na(mrFirstTime) ? "No candle with a reading is loaded yet." : "Loaded: " + firstDate + " to " + lastDate + (loadSpan == "" ? "" : " (" + loadSpan + ")") + "."
string partName = ""
for p = 0 to MR_PD_ROWS - 1
bool loaded = array.get(pdLoaded, p)
bool partial = not loaded and array.get(pdCounted, p)
int cut = array.get(pdCut, p)
string fromDate = p == MR_PD_ROWS - 1 or partial ? firstDate : na(cut) ? KIT_T3_EMPTY : str.format_time(cut, "d MMM yyyy", syminfo.timezone)
string pdSpan = fromDate + " to " + lastDate + (partial and loadSpan != "" ? " (" + loadSpan + " loaded)" : "")
if partial
partName := mrPdName(p)
string sameTip = loadedSpan + " No more history is loaded, so this period holds the same candles as " + str.lower(partName) + ".\n\n" + MR_TIP_PD_PLAN
string partTip = MR_TIP_PD_PART + "\n\n" + loadedSpan + "\n\n" + MR_TIP_PD_PLAN
string partNote = partial ? "\n\n" + MR_TIP_PD_PLAN : ""
mrCell(0, p + 2, partial and loadSpan != "" ? mrPdName(p) + " (" + loadSpan + " loaded)" : mrPdName(p), mrValInk, loaded ? "Period: " + pdSpan : partial ? partTip : sameTip)
int m = array.get(pdBN, p)
for d = 0 to 1
int at = p * 2 + d
int n = array.get(pdN, at)
int w = array.get(pdW, at)
int lost = array.get(pdL, at)
int b = array.get(pdBW, at)
string wOfN = str.tostring(w) + " of " + str.tostring(n)
bool counted = loaded or partial
string face = not counted ? "" : n == 0 ? "No starts" : n < MR_RACE_MIN ? wOfN + " · " + mrPctInt(w, n) + "%" + MR_PD_STAR : wOfN + " · " + mrPctInt(w, n) + "%"
string rnd = not counted ? "" : m == 0 ? "Unavailable" : mrPctInt(b, m) + "%"
string diffLine = n == 0 ? "No starts to compare" : m == 0 ? "Random is unavailable" : mrSigned1(100.0 * (float(w) / n - float(b) / m)) + " points against Random" + (n < MR_RACE_MIN ? " (*: under 10 starts)" : "")
string resTip = str.tostring(w) + " right · " + str.tostring(lost) + " wrong · " + str.tostring(n - w - lost) + " unclear · " + str.tostring(array.get(pdOpen, at)) + " waiting\n" + diffLine + "\n" + pdSpan
string rndTip = mrGroup(b) + " of " + mrGroup(m) + " candles right\nSame check from every candle with a reading, for a move " + (d == 0 ? "up" : "down") + ".\n" + pdSpan
mrCell(1 + d * 2, p + 2, face, counted ? mrValInk : mrRecInk, counted ? resTip + partNote : "")
mrCell(2 + d * 2, p + 2, rnd, counted ? mrValInk : mrRecInk, counted ? rndTip + partNote : "")
if not loaded and not partial
// Same as: one dim cell across both trend columns and both Random columns (four repeated cells widened every column).
table.cell(mrTable, 1, p + 2, "Same as " + str.lower(partName), text_color=mrRecInk, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_center, tooltip=sameTip)
table.merge_cells(mrTable, 1, p + 2, lastCol, p + 2)
string datesTip = MR_TIP_PD_DATES + "\n\nLoaded from: " + str.format_time(mrLoadTime, "d MMM yyyy", syminfo.timezone) + "\nWaiting: " + str.tostring(mrRcOpenUp) + " up, " + str.tostring(mrRcOpenDown) + " down\nLeft out, no ATR yet: " + str.tostring(mrRcSkipStarts) + "\n\n" + MR_TIP_PD_STAR
table.cell(mrTable, 0, 6, (na(mrLastTime) ? KIT_T3_EMPTY : firstDate + " to " + lastDate + MR_PD_STAR_NOTE) + mrClashNote, text_color=mrRecInk, text_size=KIT_T3_ROW_SIZE, text_halign=text.align_left, tooltip=datesTip)
table.merge_cells(mrTable, 0, 6, lastCol, 6)
// ==== Data Window diagnostics (Data Window only, never drawn) ====
// Median diagnostics: na on every confirmed bar, history and committed realtime bars alike; only the open
// (unconfirmed) bar carries the persistent medians as of the last confirmed close. The table keeps using the same persistent values.
mrMedOpen = not barstate.isconfirmed
mrConf = barstate.isconfirmed
mrAcc = mrConf and bar_index >= engWarmBars
plot(mrConf ? open : na, "diag open", display=display.data_window, editable=false, precision=10)
plot(mrConf ? high : na, "diag high", display=display.data_window, editable=false, precision=10)
plot(mrConf ? low : na, "diag low", display=display.data_window, editable=false, precision=10)
plot(mrConf ? close : na, "diag close", display=display.data_window, editable=false, precision=10)
plot(mrConf ? mrCode(kdState) : na, "diag state", display=display.data_window, editable=false, precision=10)
plot(mrConf ? (kitState1 ? 1 : 0) : na, "diag alert up", display=display.data_window, editable=false, precision=10)
plot(mrConf ? (kitState2 ? 1 : 0) : na, "diag alert down", display=display.data_window, editable=false, precision=10)
plot(mrConf ? (kitState3 ? 1 : 0) : na, "diag alert chop", display=display.data_window, editable=false, precision=10)
plot(mrConf ? (kitAnyState ? 1 : 0) : na, "diag alert changed", display=display.data_window, editable=false, precision=10)
plot(mrConf ? mrOutcome : na, "diag outcome", display=display.data_window, editable=false, precision=10)
plot(mrConf and mrCredited != 0 ? mrCode(mrCredited) : na, "diag credited", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrBars, 0) : na, "diag up bars", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrRuns, 0) : na, "diag up runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrDone(0) : na, "diag up done runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrMature, 0) : na, "diag up mature", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrPositive, 0) : na, "diag up positive", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrSum, 0) : na, "diag up sum", display=display.data_window, editable=false, precision=10)
plot(mrMedOpen ? mrMedUp : na, "diag up median", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrBars, 1) : na, "diag chop bars", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrRuns, 1) : na, "diag chop runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrDone(1) : na, "diag chop done runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrMature, 1) : na, "diag chop mature", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrPositive, 1) : na, "diag chop positive", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrSum, 1) : na, "diag chop sum", display=display.data_window, editable=false, precision=10)
plot(mrMedOpen ? mrMedChop : na, "diag chop median", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrBars, 2) : na, "diag down bars", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrRuns, 2) : na, "diag down runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrDone(2) : na, "diag down done runs", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrMature, 2) : na, "diag down mature", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrPositive, 2) : na, "diag down positive", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? array.get(mrSum, 2) : na, "diag down sum", display=display.data_window, editable=false, precision=10)
plot(mrMedOpen ? mrMedDown : na, "diag down median", display=display.data_window, editable=false, precision=10)
plot(mrMedOpen ? mrMedAll : na, "diag all median", display=display.data_window, editable=false, precision=10)
// Flip-level diagnostics: on every confirmed bar after warm-up, the values the drawings use when that bar is the
// last closed one; best close and stall only while a trend runs (na in Chop). Also the values the optional rule rows show.
mrFlipDiag = mrConf and bar_index >= engWarmBars and not na(engAtr)
plot(mrFlipDiag ? engHiNext : na, "diag up level", display=display.data_window, editable=false, precision=10)
plot(mrFlipDiag ? engLoNext : na, "diag down level", display=display.data_window, editable=false, precision=10)
plot(mrFlipDiag and engTrend != 0 ? engExt : na, "diag best close", display=display.data_window, editable=false, precision=10)
plot(mrFlipDiag and engTrend != 0 ? engSince : na, "diag stall", display=display.data_window, editable=false, precision=10)
plot(mrFlipDiag and engAtr > 0 ? engPush / engAtr : na, "diag push atr", display=display.data_window, editable=false, precision=10)
// Nine more diagnostics (the plot budget allows no more): the run in progress, the run that finished on this candle, the once-per-trend
// counts (packed: starts x 1,000 + higher) and the recent window (packed: outcomes x 1,000,000 + higher x 1,000 + runs). The run id is
// the sum of the three "runs" columns.
plot(mrAcc and (mrRunSt == 1 or mrRunSt == 2) ? mrRunBestPct : na, "diag run best", display=display.data_window, editable=false, precision=10)
plot(mrAcc and mrRunSt != 0 ? mrRunNow : na, "diag run now", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrFinBest : na, "diag fin best", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrFinEnd : na, "diag fin end", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrSoUpN * 1000.0 + mrSoUpK : na, "diag so up pack", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrSoDownN * 1000.0 + mrSoDownK : na, "diag so down pack", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrPack(0) : na, "diag rec up pack", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrPack(1) : na, "diag rec chop pack", display=display.data_window, editable=false, precision=10)
plot(mrAcc ? mrPack(2) : na, "diag rec down pack", display=display.data_window, editable=false, precision=10)