Ben's Toolkit: HTF EMAs + VWAP + Vector + Black Wing

benquest · study · 1272 行 · 点赞 104 · TradingView 原页

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

Pine Script

// Toolkit: higher-timeframe EMAs + VWAP with stdev bands + Vector + Black Wing, in one overlay.
// Each block has its own on/off switch. One dashboard (top right) carries the Black Wing timeframe
// states plus where price sits against VWAP and Vector.
//
// HTF EMAs (default 8 / 21 / 50 / 100 / 200 on the daily, regular-hours data):
//   Live  = the developing EMA without repainting: the last completed HTF bar's EMA blended with the
//           current price by the EMA formula, EMA_now = EMA_prev + a * (price - EMA_prev), a = 2/(n+1),
//           i.e. what the HTF chart will read if its bar closed here. Past bars keep their value.
//   Fixed = the last completed HTF bar's EMA, flat until the next HTF bar.
// VWAP: hl2 x volume from each new trading day, with volume-weighted stdev bands, as the "VWAP Stdev
//   Bands v2 Mod" script ported to v6: bands 1 (1.28) and 2 (2.01) plus one outer pair (2.51 / 3.09 /
//   4.01, your pick), lines only, to stay under TradingView's 64-plot limit. Needs volume (not on SPX).
// Vector: highest(lowest(low, 20), 20) (Fractal X), the fixed version in pine/vector.pine.
// Opening range: IB30 / IB60 high, low, mid from the cash open, and an auto OTE fib (0 / .236 / .5 / .618 /
//   .786 / 1) on the chosen IB: bullish (0 at the high) when the IB high came last, bearish when the low did.
//   The OTE is anchored at the 9:30 open, re-draws live while its IB forms, and locks when the IB completes.
// Prior day: PDH / PDL / PDC from completed regular-hours daily bars; ONH / ONL from the chart's own
//   extended-hours bars between the last close and the open (needs ETH on the chart).
// Right-edge tags: every line's tag goes through one placer that merges near-identical prices and spaces
//   the rest by a minimum gap, so tags do not print on top of each other.
// Dashboard extras: daily ATR(14), today's range vs the 20-day average range, volume so far vs a full day,
//   stretch from the HTF EMA 2 in daily ATRs, days to earnings, and price vs each HTF EMA.
// Theme: Auto / Dark / Light (high contrast). Light darkens every light colour to read on white, draws
//   lines and tags at full strength and turns the dashboard white. Dashboard: Full or Compact, any
//   corner, blank rows above it so indicator names do not cover it, four text sizes.
// Hull Suite: HMA / THMA / EHMA band (InSilico), optionally from a higher timeframe.
// Unraided liquidity: swing highs / lows on a chosen timeframe (default 60m, 6 / 6 bars) that price has not
//   traded through since, drawn to the right edge (after Texmoonbeam's script).
// Volume Stack is a separate pane script (pine/volume_stack.pine): pane and overlay cannot share a script.
// Black Wing: EMA 4/16/31/34/48 ribbon with ATR(19) wings (2.5 / 3 / 4) on EMA31, as pine's "Black Wing".
//
// ICT killzones: Asia / London / NY AM / NY lunch / NY PM boxes with their highs and lows extended until
//   price trades through them (after tradeforopp's "ICT Killzones & Pivots").
//@version=6
indicator("Toolkit: HTF EMAs + VWAP + Vector + Black Wing", "Toolkit", true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 60, max_polylines_count = 20)
 
// ---------------------------------------- Inputs --------------------------------------------------
// Quick on / off for every feature (each section below keeps its own switch too; both must be on).
var g_Q0 = "Quick Toggles"
qEma     = input.bool(true, "HTF EMAs", inline = "Q1", group = g_Q0, display = display.none)
qEma2    = input.bool(true, "EMA Set 2", inline = "Q1", group = g_Q0, display = display.none)
qVwap    = input.bool(true, "VWAP", inline = "Q1", group = g_Q0, display = display.none)
qVec     = input.bool(true, "Vector", inline = "Q1", group = g_Q0, display = display.none)
qWing    = input.bool(true, "Black Wing", inline = "Q2", group = g_Q0, display = display.none)
qHull    = input.bool(false, "Hull", inline = "Q2", tooltip = "Turns Hull on and off. (The Show Hull switch in the Hull Suite section is on by default, so this button alone controls it.)", group = g_Q0, display = display.none)
qLiq     = input.bool(true, "Liquidity", inline = "Q2", group = g_Q0, display = display.none)
qIb      = input.bool(true, "IB / OTE", inline = "Q3", group = g_Q0, display = display.none)
qPd      = input.bool(true, "Prior Day", inline = "Q3", group = g_Q0, display = display.none)
qOn      = input.bool(true, "Overnight H/L", inline = "Q3", group = g_Q0, display = display.none)
qKz      = input.bool(true, "Killzones", inline = "Q4", group = g_Q0, display = display.none)
qTags    = input.bool(true, "Right-Edge Tags", inline = "Q4", group = g_Q0, display = display.none)
qDash    = input.bool(true, "Dashboard", inline = "Q4", group = g_Q0, display = display.none)
qRs      = input.bool(true, "RS Rating", inline = "Q5", group = g_Q0, display = display.none)
 
var g_E  = "HTF EMAs"
emaOnIn   = input.bool(true, "Show HTF EMAs", group = g_E, display = display.none)
emaOn = qEma and emaOnIn
emaTf    = input.timeframe("D", "Timeframe", tooltip = "The higher timeframe the EMAs come from (60, 240, D, W...).", group = g_E, display = display.none)
emaMode  = input.string("Live", "Mode", options = ["Live", "Fixed (last completed bar)"], group = g_E, display = display.none)
emaLbl   = input.bool(true, "Labels At The Right Edge", group = g_E, display = display.none)
eOn1     = input.bool(true, "", inline = "E1", group = g_E, display = display.none)
eLen1    = input.int(8, "EMA", 1, inline = "E1", group = g_E, display = display.none)
eCol1    = input.color(#2979ff, "", inline = "E1", group = g_E, display = display.none)
eOn2     = input.bool(true, "", inline = "E2", group = g_E, display = display.none)
eLen2    = input.int(21, "EMA", 1, inline = "E2", group = g_E, display = display.none)
eCol2    = input.color(#ff4081, "", inline = "E2", group = g_E, display = display.none)
eOn3     = input.bool(true, "", inline = "E3", group = g_E, display = display.none)
eLen3    = input.int(50, "EMA", 1, inline = "E3", group = g_E, display = display.none)
eCol3    = input.color(#7c4dff, "", inline = "E3", group = g_E, display = display.none)
eOn4     = input.bool(true, "", inline = "E4", group = g_E, display = display.none)
eLen4    = input.int(100, "EMA", 1, inline = "E4", group = g_E, display = display.none)
eCol4    = input.color(#c6ff00, "", inline = "E4", group = g_E, display = display.none)
eOn5     = input.bool(true, "", inline = "E5", group = g_E, display = display.none)
eLen5    = input.int(200, "EMA", 1, inline = "E5", group = g_E, display = display.none)
eCol5    = input.color(#800020, "", inline = "E5", group = g_E, display = display.none)
 
var g_E2 = "HTF EMAs - Set 2"
ema2OnIn = input.bool(true, "Show Set 2", inline = "E2S", group = g_E2, display = display.none)
ema2On   = qEma2 and ema2OnIn
ema2Pick = input.string("Auto", "Timeframe", options = ["Auto", "Manual"], inline = "E2T", tooltip = "Auto: charts below the 'Lower Charts Use' timeframe get that timeframe's EMAs (e.g. 10m EMAs on a 3m chart); a 10m chart or higher gets EMAs from its own timeframe (15m on 15m, 1h on 1h...). Manual: always the timeframe picked below.", group = g_E2, display = display.none)
ema2Floor = input.timeframe("10", "Lower Charts Use", inline = "E2T", group = g_E2, display = display.none)
ema2Tf   = input.timeframe("10", "Manual Timeframe", inline = "E2S", tooltip = "Used when Timeframe = Manual: EMAs from this timeframe, shown on charts at or below it. Drawn as lines over the last bars only, so it does not use any of TradingView's 64 plot slots.", group = g_E2, display = display.none)
ema2Mode = input.string("Live", "Mode", options = ["Live", "Fixed (last completed bar)"], inline = "E2M", group = g_E2, display = display.none)
ema2Sty  = input.string("Solid", "Style", options = ["Solid", "Dashed", "Dotted"], inline = "E2M", group = g_E2, display = display.none)
ema2Bars = input.int(500, "Bars Of History", 50, 2000, step = 50, inline = "E2B", group = g_E2, display = display.none)
ema2W    = input.int(2, "Width", 1, 4, inline = "E2B", group = g_E2, display = display.none)
fOn1     = input.bool(false, "", inline = "F1", group = g_E2, display = display.none)
fLen1    = input.int(8, "EMA", 1, inline = "F1", group = g_E2, display = display.none)
fCol1    = input.color(#ffab40, "", inline = "F1", group = g_E2, display = display.none)
fOn2     = input.bool(false, "", inline = "F2", group = g_E2, display = display.none)
fLen2    = input.int(21, "EMA", 1, inline = "F2", group = g_E2, display = display.none)
fCol2    = input.color(#ffe57f, "", inline = "F2", group = g_E2, display = display.none)
fOn3     = input.bool(true, "", inline = "F3", group = g_E2, display = display.none)
fLen3    = input.int(50, "EMA", 1, inline = "F3", group = g_E2, display = display.none)
fCol3    = input.color(#ff6e40, "", inline = "F3", group = g_E2, display = display.none)
fOn4     = input.bool(true, "", inline = "F4", group = g_E2, display = display.none)
fLen4    = input.int(100, "EMA", 1, inline = "F4", group = g_E2, display = display.none)
fCol4    = input.color(#1de9b6, "", inline = "F4", group = g_E2, display = display.none)
fOn5     = input.bool(true, "", inline = "F5", group = g_E2, display = display.none)
fLen5    = input.int(200, "EMA", 1, inline = "F5", group = g_E2, display = display.none)
fCol5    = input.color(#ea80fc, "", inline = "F5", group = g_E2, display = display.none)
 
var g_V  = "VWAP"
vwOnIn    = input.bool(true, "Show VWAP", group = g_V, display = display.none)
vwOn = qVwap and vwOnIn
vwCol    = input.color(#00e5ff, "VWAP", inline = "VC", group = g_V, display = display.none)
vwUpCol  = input.color(#ff5252, "Upper", inline = "VC", group = g_V, display = display.none)
vwDnCol  = input.color(#69f0ae, "Lower", inline = "VC", group = g_V, display = display.none)
dev1     = input.float(1.28, "Band 1", 0.0, step = 0.01, inline = "D1", group = g_V, display = display.none)
dev2     = input.float(2.01, "Band 2", 0.0, step = 0.01, inline = "D1", group = g_V, display = display.none)
dev3     = input.float(2.51, "Band 3", 0.0, step = 0.01, inline = "D2", group = g_V, display = display.none)
dev4     = input.float(3.09, "Band 4", 0.0, step = 0.01, inline = "D2", group = g_V, display = display.none)
dev5     = input.float(4.01, "Band 5", 0.0, step = 0.01, inline = "D3", group = g_V, display = display.none)
showB2   = input.bool(true, "Band 2", inline = "SB", group = g_V, display = display.none)
showB3   = input.bool(true, "Outer Band", inline = "SB", group = g_V, display = display.none)
outerB   = input.string("Band 3", "", options = ["Band 3", "Band 4", "Band 5"], inline = "SB", group = g_V, display = display.none)
showPrev = input.bool(false, "Previous Day's Closing VWAP", group = g_V, display = display.none)
vwBandTags = input.bool(true, "Label The Bands (sd)", tooltip = "Right-edge tags on each shown band, e.g. VWAP +2.01sd, with the same overlap spacing as the other tags.", group = g_V, display = display.none)
 
var g_X  = "Vector"
vecOnIn   = input.bool(true, "Show Vector", group = g_X, display = display.none)
vecOn = qVec and vecOnIn
vecLen   = input.int(20, "Length", 1, group = g_X, display = display.none)
vecCol   = input.color(#ff10f0, "Line", inline = "XC", group = g_X, display = display.none)
vecBars  = input.bool(false, "Color Bars", inline = "XC", tooltip = "White above / black below, as the original. Off by default so it does not fight the other colours.", group = g_X, display = display.none)
vecUpCol = input.color(color.white, "Above", inline = "XB", group = g_X, display = display.none)
vecDnCol = input.color(#030303, "Below", inline = "XB", group = g_X, display = display.none)
vecX     = input.bool(true, "Mark Confirmed Crosses", inline = "VX", group = g_X, display = display.none)
vecXSty  = input.string("Arrows", "", options = ["Arrows", "Triangles", "Diamonds", "Circles", "Text ▲▼"], inline = "VX", tooltip = "Shape of the cross markers, so they read differently from the other marks on the chart.", group = g_X, display = display.none)
vecXUp   = input.color(#69f0ae, "Up", inline = "VXC", group = g_X, display = display.none)
vecXDn   = input.color(#ff5252, "Down", inline = "VXC", group = g_X, display = display.none)
 
var g_H  = "Hull Suite"
hullOnIn  = input.bool(true, "Show Hull", group = g_H, display = display.none)
hullOn = qHull and hullOnIn
hullMode = input.string("Hma", "Variation", options = ["Hma", "Thma", "Ehma"], inline = "HM", group = g_H, display = display.none)
hullLen  = input.int(55, "Length", 2, inline = "HM", tooltip = "180-200 for floating S/R, 55 for swing entries (InSilico's notes).", group = g_H, display = display.none)
hullMult = input.float(1.0, "Length Multiplier", 0.1, step = 0.1, group = g_H, display = display.none)
hullHtfOn = input.bool(false, "From Timeframe", inline = "HT", group = g_H, display = display.none)
hullHtf  = input.timeframe("240", "", inline = "HT", group = g_H, display = display.none)
hullTrend = input.bool(true, "Colour By Trend", inline = "HC", group = g_H, display = display.none)
hullBars = input.bool(false, "Colour Candles", inline = "HC", tooltip = "Vector's bar colouring wins if both are on.", group = g_H, display = display.none)
hullBand = input.bool(true, "Show As A Band", inline = "HB", group = g_H, display = display.none)
hullW    = input.int(1, "Width", 1, 4, inline = "HB", group = g_H, display = display.none)
hullFillT = input.int(40, "Band Transparency", 0, 100, step = 5, group = g_H, display = display.none)
 
var g_Q  = "Unraided Liquidity"
liqOnIn   = input.bool(true, "Show Unraided Highs / Lows", tooltip = "Swing highs / lows on the chosen timeframe that price has not traded through since (after Texmoonbeam's 'Unraided Liquidity and S/R Pivots').", group = g_Q, display = display.none)
liqOn = qLiq and liqOnIn
liqTf    = input.timeframe("60", "Timeframe", inline = "LQ", group = g_Q, display = display.none)
liqLook  = input.int(300, "Look Back (bars)", 10, 500, inline = "LQ", group = g_Q, display = display.none)
liqLeft  = input.int(6, "Left Bars", 1, inline = "LQB", group = g_Q, display = display.none)
liqRight = input.int(6, "Right Bars", 1, inline = "LQB", group = g_Q, display = display.none)
liqUntest = input.bool(true, "Untested Only", group = g_Q, display = display.none)
liqHiCol = input.color(#39ff14, "Highs", inline = "LQC", group = g_Q, display = display.none)
liqLoCol = input.color(#ff3131, "Lows", inline = "LQC", group = g_Q, display = display.none)
liqWidth = input.int(1, "Width", 1, 4, inline = "LQC", group = g_Q, display = display.none)
liqTags  = input.bool(true, "Tags At The Right Edge", group = g_Q, display = display.none)
 
var g_W  = "Black Wing"
bwOnIn    = input.bool(true, "Show Black Wing", group = g_W, display = display.none)
bwOn = qWing and bwOnIn
bwLen1   = input.int(4, "EMA 1", 1, inline = "BW1", group = g_W, display = display.none)
bwLen2   = input.int(16, "EMA 2", 1, inline = "BW1", group = g_W, display = display.none)
bwLen3   = input.int(31, "EMA 3 (centre)", 1, inline = "BW2", group = g_W, display = display.none)
bwLen4   = input.int(34, "EMA 4", 1, inline = "BW2", group = g_W, display = display.none)
bwLen5   = input.int(48, "EMA 5", 1, inline = "BW3", group = g_W, display = display.none)
atrLen   = input.int(19, "ATR", 1, inline = "BW3", group = g_W, display = display.none)
kIn      = input.float(2.5, "Wing mults", step = 0.05, inline = "BWK", group = g_W, display = display.none)
kOut     = input.float(4.0, "", step = 0.05, inline = "BWK", group = g_W, display = display.none)
tf1      = input.timeframe("15", "Dashboard TFs", inline = "TF", group = g_W, display = display.none)
tf2      = input.timeframe("60", "", inline = "TF", group = g_W, display = display.none)
tf3      = input.timeframe("D", "", inline = "TF", group = g_W, display = display.none)
tf4      = input.timeframe("W", "", inline = "TF", group = g_W, display = display.none)
cUp      = input.color(#22c55e, "Bull", inline = "BWC", group = g_W, display = display.none)
cDn      = input.color(#ef4444, "Bear", inline = "BWC", group = g_W, display = display.none)
cCld     = input.color(#bdbdbd, "Wings", inline = "BWC", group = g_W, display = display.none)
fillT    = input.int(90, "Wedge / band / cloud transparency", 0, 95, inline = "BWT", group = g_W, display = display.none)
darkT    = input.int(90, "", 0, 95, inline = "BWT", group = g_W, display = display.none)
deepT    = input.int(90, "", 0, 95, inline = "BWT", group = g_W, display = display.none)
bwWedge  = input.bool(true, "Wedge", inline = "BWF", group = g_W, display = display.none)
bwBand   = input.bool(true, "Dark Band", inline = "BWF", group = g_W, display = display.none)
bwCloud  = input.bool(true, "Deep Cloud", inline = "BWF", group = g_W, display = display.none)
bwWings  = input.bool(false, "Wings", inline = "BWF", tooltip = "Turn the ribbon fills and the grey ATR wings off one by one; the ribbon lines stay.", group = g_W, display = display.none)
 
var g_I  = "Opening Range (IB) & OTE"
ibOnIn    = input.bool(true, "Show IB30", inline = "IB", group = g_I, display = display.none)
ibOn = qIb and ibOnIn
ib60OnIn  = input.bool(false, "IB60", inline = "IB", group = g_I, display = display.none)
ib60On = qIb and ib60OnIn
ibCol30  = input.color(#ffd700, "", inline = "IB", group = g_I, display = display.none)
ibCol60  = input.color(#ffbf00, "", inline = "IB", group = g_I, display = display.none)
cashSess = input.session("0930-1600", "Cash Session (ET)", tooltip = "The IB, today's range and today's volume start at this open, so futures still line up with the cash session.", group = g_I, display = display.none)
oteOnIn   = input.bool(true, "OTE Fib On", inline = "OT", group = g_I, display = display.none)
oteOn = qIb and oteOnIn
oteSrc   = input.string("IB30", "", options = ["IB30", "IB60"], inline = "OT", tooltip = "Anchored at the 9:30 open and built from that IB's high and low. Bullish (low -> high, retracing down from the high) when the IB high came after the IB low; bearish (high -> low) when the low came last.", group = g_I, display = display.none)
oteLive  = input.bool(true, "Draw While The IB Is Forming", tooltip = "On: the fib appears at the open and re-draws as the IB high / low and direction change, then locks when the IB completes. Off: it appears only once the IB is complete.", group = g_I, display = display.none)
oteTimeOn = input.bool(true, "Only Show OTE During", inline = "OTT", tooltip = "The OTE lines, zone and tags show only while the current bar is inside this window (ET), e.g. the cash session; outside it they are hidden. Untick to show them at all hours.", group = g_I, display = display.none)
oteSess  = input.session("0930-1600", "", inline = "OTT", group = g_I, display = display.none)
ibKeep   = input.int(3, "Past Sessions Kept", 0, 20, tooltip = "Like the killzones: each session's IB and OTE are drawn from 09:30 once the IB completes, grow through that cash session, then stay where they are. This many past sessions are kept besides today. 0 = today only.", group = g_I, display = display.none)
oteCol   = input.color(color.white, "OTE Colour", group = g_I, display = display.none)
oteBull  = input.color(#00e676, "OTE Zone Bull", inline = "OZ", group = g_I, display = display.none)
oteBear  = input.color(#ff1744, "Bear", inline = "OZ", tooltip = "Shading of the 0.618 - 0.786 zone: bull colour when the OTE is bullish (IB high made after the low), bear colour when bearish.", group = g_I, display = display.none)
oteLvls  = input.string("0, 0.236, 0.5, 0.618, 0.786, 1", "OTE Levels", group = g_I, display = display.none)
oteZone  = input.bool(true, "Shade 0.618 - 0.786", group = g_I, display = display.none)
 
var g_P  = "Prior Day"
pdOnIn    = input.bool(true, "Prior Day High / Low / Close", group = g_P, display = display.none)
pdOn = qPd and pdOnIn
pdHLCol  = input.color(#b0bec5, "High / Low", inline = "PD", group = g_P, display = display.none)
pdCCol   = input.color(#78909c, "Close", inline = "PD", group = g_P, display = display.none)
onOnIn    = input.bool(true, "Overnight High / Low", inline = "ON", tooltip = "High and low of the bars between the last cash close and today's open. Needs extended-hours bars on the chart (stocks: turn on ETH in the chart settings; futures always have them).", group = g_P, display = display.none)
onOn = qOn and onOnIn
onCol    = input.color(#80cbc4, "", inline = "ON", group = g_P, display = display.none)
 
var g_L  = "Right-Edge Labels"
lblOnIn   = input.bool(true, "Name Tags At The Right Edge", tooltip = "One tag per line: HTF EMAs, VWAP, IB, OTE, prior day. Tags closer than the merge distance share one tag; the rest are pushed apart by the spacing.", group = g_L, display = display.none)
lblOn = qTags and lblOnIn
lblOff   = input.int(3, "Bars Right Of The Last Candle", 0, 50, group = g_L, display = display.none)
lblMerge = input.float(0.0, "Merge Tags Within (x ATR)", 0.0, step = 0.05, tooltip = "0 = never merge, so every tag keeps its own line's colour (spacing still stops overlap). Above 0, tags that close share one tag in the lowest one's colour.", group = g_L, display = display.none)
lblGap   = input.float(0.30, "Min Spacing (x chart ATR)", 0.0, step = 0.05, inline = "LG", group = g_L, display = display.none)
lblGapD  = input.float(0.03, "or (x daily ATR)", 0.0, step = 0.005, inline = "LG", tooltip = "Tags sit at least the larger of the two apart. On 1-3m charts the chart ATR is tiny, so the daily-ATR floor (0.03 x a ~11 point QQQ day = ~0.33) keeps tags from printing on top of each other. Raise either if they still touch when zoomed out.", group = g_L, display = display.none)
lblSize  = input.string("Small", "Size", options = ["Tiny", "Small", "Normal"], group = g_L, display = display.none)
 
var g_R  = "RS Rating"
rsOnIn   = input.bool(true, "Show RS Rating", inline = "RS0", tooltip = "IBD-style Relative Strength Rating, 1 to 99: this symbol's past year (last 3 months count double) vs about 6,100 US stocks. Rating data: Fred6724's free daily feed (github.com/Fred6725/relative-strength), Mozilla Public License 2.0; method after TheMarketBishop's Biryani Ribbons. Index funds that track the market sit near the middle.", group = g_R, display = display.none)
rsOn     = qRs and rsOnIn
rsBadgeOn = input.bool(false, "Badge Above The Last Candle", inline = "RS0", group = g_R, display = display.none)
rsDotsOn = input.bool(true, "Orange Dots When The RS Line Makes A New High", inline = "RS1", tooltip = "RS line = this symbol / the S&P 500. A dot above the candle when it makes a new high over the look-back (Fred6724's blue dots). Skipped on the S&P 500 itself and funds that move with it.", group = g_R, display = display.none)
rsDotLen = input.int(250, "Look-Back", 20, 1000, inline = "RS1", group = g_R, display = display.none)
rsDotMode = input.string("Every RS new high", "Which", options = ["Every RS new high", "Only when RS leads price"], tooltip = "Only when RS leads price: only while price itself has not made a new high over the look-back - strength showing before price.", group = g_R, display = display.none)
rsCol    = input.color(#ff8a00, "Dot Colour", group = g_R, display = display.none)
rsStripOn = input.bool(true, "Colour Strip Along The Bottom", inline = "RST", tooltip = "Biryani's RS strip: a square under every candle, green = RS 80+, grey = 40-79, red = under 40. On intraday charts each candle uses the previous day's finished rating, so it never changes after the fact; older parts are estimates (only recent cutoffs exist).", group = g_R, display = display.none)
rsStripT = input.int(15, "Transparency", 0, 100, inline = "RST", group = g_R, display = display.none)
 
var g_K  = "ICT Killzones"
kzOnIn    = input.bool(true, "Show", inline = "KZ", group = g_K, display = display.none)
kzOn = qKz and kzOnIn
kzKeep   = input.int(3, "Sessions Kept", 1, 10, inline = "KZ", group = g_K, display = display.none)
kzFillT  = input.int(97, "Box Fill Transparency", 0, 100, inline = "KZF", group = g_K, display = display.none)
kzMoreT  = input.int(10, "Extra Transparency (lines, labels, borders)", 0, 100, tooltip = "Added on top of the line / text opacity for everything a killzone draws: its border, high / low lines, H / L labels and right-edge tags.", group = g_K, display = display.none)
kzPivots = input.bool(true, "Highs / Lows Until Taken", inline = "KZF", tooltip = "Each killzone's high and low extend to the right until price trades through them, like tradeforopp's script; then they stop where they were taken.", group = g_K, display = display.none)
kzAlerts = input.bool(false, "Alert When A Killzone High / Low Is Taken", group = g_K, display = display.none)
kzExt    = input.string("Until Taken", "Extend Highs / Lows", options = ["Always (latest session)", "Until Taken"], tooltip = "Always: the latest session's high and low run to the right edge even after price trades through them. Until Taken: they stop where they were taken (tradeforopp's default).", group = g_K, display = display.none)
kzTags   = input.bool(true, "Tags At The Right Edge", tooltip = "Copies the latest session's high / low into the right-edge tags (killzone colour, with the other tags' overlap spacing). The killzone lines themselves stay where they are.", group = g_K, display = display.none)
kzOn1    = input.bool(true, "", inline = "K1", group = g_K, display = display.none)
kzN1     = input.string("ASIA", "", inline = "K1", group = g_K, display = display.none)
kzC1     = input.color(#40c4ff, "", inline = "K1", group = g_K, display = display.none)
kzS1     = input.session("2000-0000", "", inline = "K1", group = g_K, display = display.none)
kzOn2    = input.bool(true, "", inline = "K2", group = g_K, display = display.none)
kzN2     = input.string("LNDN", "", inline = "K2", group = g_K, display = display.none)
kzC2     = input.color(#b388ff, "", inline = "K2", group = g_K, display = display.none)
kzS2     = input.session("0200-0500", "", inline = "K2", group = g_K, display = display.none)
kzOn3    = input.bool(true, "", inline = "K3", group = g_K, display = display.none)
kzN3     = input.string("NYAM", "", inline = "K3", group = g_K, display = display.none)
kzC3     = input.color(#ffab40, "", inline = "K3", group = g_K, display = display.none)
kzS3     = input.session("0930-1100", "", inline = "K3", group = g_K, display = display.none)
kzOn4    = input.bool(false, "", inline = "K4", group = g_K, display = display.none)
kzN4     = input.string("NYL", "", inline = "K4", group = g_K, display = display.none)
kzC4     = input.color(#ffe57f, "", inline = "K4", group = g_K, display = display.none)
kzS4     = input.session("1200-1300", "", inline = "K4", group = g_K, display = display.none)
kzOn5    = input.bool(true, "", inline = "K5", group = g_K, display = display.none)
kzN5     = input.string("NYPM", "", inline = "K5", group = g_K, display = display.none)
kzC5     = input.color(#ff80ab, "", inline = "K5", group = g_K, display = display.none)
kzS5     = input.session("1330-1600", "", inline = "K5", group = g_K, display = display.none)
 
theme    = input.string("Auto (match chart)", "Theme", options = ["Auto (match chart)", "Dark", "Light (high contrast)"], tooltip = "Light (high contrast): every light colour (white OTE, yellow VWAP, cyan IB / ONH...) is darkened until it reads on white, lines and tags draw at full strength, and the dashboard turns white with dark text. Auto picks it whenever the chart background is light.", group = "Look", display = display.none)
opac     = input.int(50, "Line Opacity %", 0, 100, tooltip = "Dark theme: scales every line and marker on the chart (100 = as coloured, 50 = half see-through). The light theme always draws them at full strength. Fills keep their own transparency settings; the dashboard is not affected.", group = "Look", display = display.none)
tagOpac  = input.int(100, "Text Opacity %", 0, 100, tooltip = "The right-edge tags and the cross markers' text, separately from the lines, so the text stays crisp while the lines stay soft.", group = "Look", display = display.none)
 
bgLum   = 0.299 * color.r(chart.bg_color) + 0.587 * color.g(chart.bg_color) + 0.114 * color.b(chart.bg_color)
isLight = theme == "Light (high contrast)" or (theme == "Auto (match chart)" and bgLum >= 128)
 
// Light theme: darken a colour until its luminance is at most 0.45, keeping its hue and transparency.
ink(color c) =>
    float lum = (0.299 * color.r(c) + 0.587 * color.g(c) + 0.114 * color.b(c)) / 255
    float f = isLight and lum > 0.45 ? 0.45 / lum : 1.0
    color.rgb(color.r(c) * f, color.g(c) * f, color.b(c) * f, color.t(c))
 
// Lines, tags, markers: dark theme at opac% of their own opacity; light theme darkened, full strength.
fade(color c) =>
    color k = ink(c)
    isLight ? k : color.new(k, 100 - (100 - color.t(k)) * opac / 100)
 
// Text: same darkening on white, its own opacity in both themes.
textFade(color c) =>
    color k = ink(c)
    color.new(k, 100 - (100 - color.t(k)) * tagOpac / 100)
 
showDashIn = input.bool(true, "Dashboard", inline = "DB", group = "Dashboard", display = display.none)
showDash = qDash and showDashIn
dashMode = input.string("Compact", "", options = ["Full", "Compact"], inline = "DB", tooltip = "Compact: short wording, the four Black Wing timeframes on one row, day stats folded into two rows.", group = "Dashboard", display = display.none)
dashPos  = input.string("Top Left", "Position", options = ["Top Right", "Top Left", "Middle Right", "Bottom Right", "Bottom Left"], inline = "DP", group = "Dashboard", display = display.none)
dashGap  = input.int(3, "Empty Rows Above", 0, 10, inline = "DP", tooltip = "Top positions only: leaves blank rows so TradingView's indicator names (top left) do not cover the table. 3 suits Top Left.", group = "Dashboard", display = display.none)
dashSize = input.string("Small", "Text Size", options = ["Tiny", "Small", "Normal", "Large"], group = "Dashboard", display = display.none)
dashExtra = input.bool(true, "Day Stats (ATR, range, volume, stretch, earnings)", group = "Dashboard", display = display.none)
dashEmas = input.bool(true, "HTF EMA List", group = "Dashboard", display = display.none)
rvDays   = input.int(10, "Rel. Volume: Past Sessions", 1, 30, tooltip = "Compared with the same time of day on this many past sessions, using this chart's own bars (needs that much intraday history loaded).", group = "Dashboard", display = display.none)
// ---------------------------------------- Inputs --------------------------------------------------
 
 
// ---------------------------------------- HTF EMAs --------------------------------------------------
tk = ticker.modify(syminfo.tickerid, session.regular)
 
// Completed higher-timeframe EMAs ([1] + lookahead_on: the last finished bar, never repaints).
htfEmas() =>
    [ta.ema(close, eLen1)[1], ta.ema(close, eLen2)[1], ta.ema(close, eLen3)[1], ta.ema(close, eLen4)[1], ta.ema(close, eLen5)[1]]
 
[hp1, hp2, hp3, hp4, hp5] = request.security(tk, emaTf, htfEmas(), lookahead = barmerge.lookahead_on)
 
liveEma(float prev, int n) =>
    emaMode == "Live" ? prev + 2.0 / (n + 1) * (close - prev) : prev
 
he1 = liveEma(hp1, eLen1)
he2 = liveEma(hp2, eLen2)
he3 = liveEma(hp3, eLen3)
he4 = liveEma(hp4, eLen4)
he5 = liveEma(hp5, eLen5)
 
// Shown on charts at or below the set's timeframe (on its own timeframe it is the chart's own EMA).
emaShow = emaOn and timeframe.in_seconds("") <= timeframe.in_seconds(emaTf)
plot(emaShow and eOn1 ? he1 : na, "HTF EMA 1", fade(eCol1), 1, display = display.all - display.status_line - display.price_scale)
plot(emaShow and eOn2 ? he2 : na, "HTF EMA 2", fade(eCol2), 1, display = display.all - display.status_line - display.price_scale)
plot(emaShow and eOn3 ? he3 : na, "HTF EMA 3", fade(eCol3), 2, display = display.all - display.status_line - display.price_scale)
plot(emaShow and eOn4 ? he4 : na, "HTF EMA 4", fade(eCol4), 2, display = display.all - display.status_line - display.price_scale)
plot(emaShow and eOn5 ? he5 : na, "HTF EMA 5", fade(eCol5), 2, display = display.all - display.status_line - display.price_scale)
 
// Set 2: same method (completed bars + live blend), from the chart's own session data. Kept as the last
// ema2Bars points per EMA and drawn as polylines on the last bar, so it costs no plot slots.
htfEmas2() =>
    [ta.ema(close, fLen1)[1], ta.ema(close, fLen2)[1], ta.ema(close, fLen3)[1], ta.ema(close, fLen4)[1], ta.ema(close, fLen5)[1]]
 
// Auto: the floor timeframe on lower charts, otherwise the chart's own timeframe.
ema2TfEff = ema2Pick == "Manual" ? ema2Tf : timeframe.in_seconds() < timeframe.in_seconds(ema2Floor) ? ema2Floor : timeframe.period
[gp1, gp2, gp3, gp4, gp5] = request.security(syminfo.tickerid, ema2TfEff, htfEmas2(), lookahead = barmerge.lookahead_on)
liveEma2(float prev, int n) =>
    ema2Mode == "Live" ? prev + 2.0 / (n + 1) * (close - prev) : prev
ge1 = liveEma2(gp1, fLen1)
ge2 = liveEma2(gp2, fLen2)
ge3 = liveEma2(gp3, fLen3)
ge4 = liveEma2(gp4, fLen4)
ge5 = liveEma2(gp5, fLen5)
// Set 2 steps aside when it would land on the same timeframe as the main set (no duplicate lines).
ema2Show = ema2On and timeframe.in_seconds("") <= timeframe.in_seconds(ema2TfEff) and not (emaShow and timeframe.in_seconds(ema2TfEff) == timeframe.in_seconds(emaTf))
 
var chart.point[] gPts1 = array.new<chart.point>()
var chart.point[] gPts2 = array.new<chart.point>()
var chart.point[] gPts3 = array.new<chart.point>()
var chart.point[] gPts4 = array.new<chart.point>()
var chart.point[] gPts5 = array.new<chart.point>()
keepPt(chart.point[] pts, float v) =>
    if not na(v)
        pts.push(chart.point.from_time(time, v))
        if pts.size() > ema2Bars
            pts.shift()
if ema2Show
    keepPt(gPts1, ge1)
    keepPt(gPts2, ge2)
    keepPt(gPts3, ge3)
    keepPt(gPts4, ge4)
    keepPt(gPts5, ge5)
 
var polyline[] gLines = array.new<polyline>()
ema2Style = ema2Sty == "Solid" ? line.style_solid : ema2Sty == "Dotted" ? line.style_dotted : line.style_dashed
drawPoly(bool on, chart.point[] pts, color c) =>
    if on and pts.size() > 1
        gLines.push(polyline.new(pts, false, false, xloc.bar_time, ink(c), line_style = ema2Style, line_width = ema2W))
if barstate.islast
    for pl in gLines
        pl.delete()
    gLines.clear()
    if ema2Show
        drawPoly(fOn1, gPts1, fCol1)
        drawPoly(fOn2, gPts2, fCol2)
        drawPoly(fOn3, gPts3, fCol3)
        drawPoly(fOn4, gPts4, fCol4)
        drawPoly(fOn5, gPts5, fCol5)
 
// Right-edge name tags for these lines are drawn with all the others in "Right-Edge Labels" below.
// ---------------------------------------- HTF EMAs --------------------------------------------------
 
 
// ---------------------------------------- VWAP --------------------------------------------------
newDay = timeframe.change("D")
var float vSum  = na
var float vVol  = na
var float vSq   = na
var float prevV = na
float pv = hl2 * volume
if newDay or na(vSum)
    prevV := nz(vSum / vVol, prevV)
    vSum := pv
    vVol := volume
    vSq := volume * hl2 * hl2
else
    vSum += pv
    vVol += volume
    vSq += volume * hl2 * hl2
float vwap = vVol > 0 ? vSum / vVol : na
float vDev = vVol > 0 ? math.sqrt(math.max(vSq / vVol - vwap * vwap, 0)) : na
 
band(bool on, float m) =>
    vwOn and on ? vwap + m * vDev : na
 
// Lines only (TradingView allows 64 plots per script; the band fills alone cost 10). The "outer band"
// input picks which of bands 3 / 4 / 5 is drawn as the outermost pair.
float devOut = outerB == "Band 4" ? dev4 : outerB == "Band 5" ? dev5 : dev3
plot(vwOn ? vwap : na, "VWAP", fade(vwCol), 2, display = display.all - display.status_line - display.price_scale)
plot(band(true, dev1), "VWAP +1", fade(color.new(color.gray, 30)), 1, display = display.all - display.status_line - display.price_scale)
plot(band(true, -dev1), "VWAP -1", fade(color.new(color.gray, 30)), 1, display = display.all - display.status_line - display.price_scale)
plot(band(showB2, dev2), "VWAP +2", fade(vwUpCol), display = display.all - display.status_line - display.price_scale)
plot(band(showB2, -dev2), "VWAP -2", fade(vwDnCol), display = display.all - display.status_line - display.price_scale)
plot(band(showB3, devOut), "VWAP outer +", fade(vwUpCol), 2, display = display.all - display.status_line - display.price_scale)
plot(band(showB3, -devOut), "VWAP outer -", fade(vwDnCol), 2, display = display.all - display.status_line - display.price_scale)
// ---------------------------------------- VWAP --------------------------------------------------
 
 
// ---------------------------------------- Vector --------------------------------------------------
vec      = ta.highest(ta.lowest(low, vecLen), vecLen)
vecAbove = close >= vec
plot(vecOn ? vec : na, "Vector", fade(vecCol), 2, display = display.all - display.status_line - display.price_scale)
confUp = barstate.isconfirmed and vecAbove and vecAbove[1] and not vecAbove[2]
confDn = barstate.isconfirmed and not vecAbove and not vecAbove[1] and vecAbove[2]
// Labels, not plotshapes: labels do not count toward the 64-plot limit.
if vecOn and vecX and (confUp or confDn)
    color xc = fade(confUp ? vecXUp : vecXDn)
    string xTip = "Vector confirmed cross " + (confUp ? "UP: closed above" : "DOWN: closed below") + " the Vector line (" + str.tostring(vec, format.mintick) + ") for a second bar in a row, the guide's 'does not return for one candle' rule."
    if vecXSty == "Text ▲▼"
        label.new(bar_index, confUp ? low : high, confUp ? "▲" : "▼", style = confUp ? label.style_label_up : label.style_label_down, color = #ffffff00, textcolor = textFade(confUp ? vecXUp : vecXDn), size = size.tiny, tooltip = xTip, text_formatting = text.format_bold)
    else
        string sty = vecXSty == "Arrows" ? (confUp ? label.style_arrowup : label.style_arrowdown) : vecXSty == "Triangles" ? (confUp ? label.style_triangleup : label.style_triangledown) : vecXSty == "Diamonds" ? label.style_diamond : label.style_circle
        label.new(bar_index, confUp ? low : high, "", yloc = confUp ? yloc.belowbar : yloc.abovebar, style = sty, color = xc, size = size.tiny, tooltip = xTip)
alertcondition(confUp, "Vector confirmed cross up", "{{ticker}} held above Vector @ {{close}}")
alertcondition(confDn, "Vector confirmed cross down", "{{ticker}} held below Vector @ {{close}}")
// ---------------------------------------- Vector --------------------------------------------------
 
 
// ---------------------------------------- Hull Suite --------------------------------------------------
// HMA / THMA / EHMA as InSilico's Hull Suite; the band is the Hull vs itself 2 bars ago.
hullOf(float s, int len) =>
    float hma  = ta.wma(2 * ta.wma(s, math.max(int(len / 2), 1)) - ta.wma(s, len), math.max(int(math.round(math.sqrt(len))), 1))
    float ehma = ta.ema(2 * ta.ema(s, math.max(int(len / 2), 1)) - ta.ema(s, len), math.max(int(math.round(math.sqrt(len))), 1))
    int tl = math.max(int(len / 2), 3)
    float thma = ta.wma(ta.wma(s, math.max(int(tl / 3), 1)) * 3 - ta.wma(s, math.max(int(tl / 2), 1)) - ta.wma(s, tl), tl)
    hullMode == "Ehma" ? ehma : hullMode == "Thma" ? thma : hma
 
int hullN = math.max(int(hullLen * hullMult), 2)
hullLocal = hullOf(close, hullN)
hull = hullHtfOn ? request.security(syminfo.tickerid, hullHtf, hullOf(close, hullN)) : hullLocal
hullUp = hull > hull[2]
hullCol = hullTrend ? (hullUp ? #00ff00 : #ff0000) : #ff9800
hullP1 = plot(hullOn ? hull : na, "Hull", fade(color.new(hullCol, 50)), hullW, display = display.all - display.status_line - display.price_scale)
hullP2 = plot(hullOn and hullBand ? hull[2] : na, "Hull 2 bars ago", fade(color.new(hullCol, 50)), hullW, display = display.all - display.status_line - display.price_scale)
fill(hullP1, hullP2, color.new(hullCol, hullFillT), "Hull band")
barcolor(vecOn and vecBars and not na(vec) ? (vecAbove ? vecUpCol : vecDnCol) : hullOn and hullBars and hullTrend ? hullCol : na)
alertcondition(ta.crossover(hull, hull[2]), "Hull trending up", "{{ticker}} Hull trending up @ {{close}}")
alertcondition(ta.crossunder(hull, hull[2]), "Hull trending down", "{{ticker}} Hull trending down @ {{close}}")
// ---------------------------------------- Hull Suite --------------------------------------------------
 
 
// ---------------------------------------- Unraided Liquidity --------------------------------------------------
// The last liqLook + liqLeft bars of liqTf (index 0 = newest). A swing high has liqLeft lower highs before it
// and liqRight lower highs after it; "unraided" = no later bar traded above it. Lows mirror that.
liqData() =>
    float[] hs = array.new_float()
    float[] ls = array.new_float()
    int[]   ts = array.new_int()
    for n = 0 to liqLook + liqLeft
        hs.push(high[n])
        ls.push(low[n])
        ts.push(time[n])
    [hs, ls, ts]
 
[lqH, lqL, lqT] = request.security(syminfo.tickerid, liqTf, liqData(), ignore_invalid_symbol = true)
var float[] liqP  = array.new_float()
var int[]   liqT  = array.new_int()
var bool[]  liqHi = array.new_bool()
 
liqScan(float[] v, bool hi) =>
    int n = v.size()
    if n > liqLeft + liqRight
        for a = liqRight to n - liqLeft - 1
            float x = v.get(a)
            bool piv = true
            for j = a - liqRight to a + liqLeft
                if j != a and (hi ? v.get(j) > x : v.get(j) < x)
                    piv := false
                    break
            bool clean = true
            if piv and liqUntest and a > liqRight
                for b = 0 to a - liqRight - 1
                    if hi ? v.get(b) > x : v.get(b) < x
                        clean := false
                        break
            if piv and clean
                liqP.push(x)
                liqT.push(lqT.get(a))
                liqHi.push(hi)
 
if barstate.islast
    liqP.clear()
    liqT.clear()
    liqHi.clear()
    if liqOn and not na(lqH)
        liqScan(lqH, true)
        liqScan(lqL, false)
// ---------------------------------------- Unraided Liquidity --------------------------------------------------
 
 
// ---------------------------------------- Black Wing --------------------------------------------------
b1e = ta.ema(close, bwLen1)
b2e = ta.ema(close, bwLen2)
b3e = ta.ema(close, bwLen3)
b4e = ta.ema(close, bwLen4)
b5e = ta.ema(close, bwLen5)
wAtr = ta.atr(atrLen)
 
wing(float m) =>
    bwOn and bwWings ? b3e + m * wAtr : na
 
// Each wing is one plain fill between its inner and outer ring (a gradient fill costs extra plot
// slots, and TradingView allows 64 per script).
wu3 = plot(wing(kOut), "Wing upper outer", na, editable = false, display = display.all - display.status_line - display.price_scale)
wu1 = plot(wing(kIn), "Wing upper inner", na, editable = false, display = display.all - display.status_line - display.price_scale)
wd1 = plot(wing(-kIn), "Wing lower inner", na, editable = false, display = display.all - display.status_line - display.price_scale)
wd3 = plot(wing(-kOut), "Wing lower outer", na, editable = false, display = display.all - display.status_line - display.price_scale)
fill(wu3, wu1, color.new(cCld, 80), "Upper wing")
fill(wd1, wd3, color.new(cCld, 80), "Lower wing")
 
bull = b1e > b2e
hueA = bull ? cUp : cDn
hueC = b3e > b4e ? cUp : cDn
hueD = b4e > b5e ? cUp : cDn
r1 = plot(bwOn ? b1e : na, "BW EMA 1", fade(color.new(hueA, 25)), 1, display = display.all - display.status_line - display.price_scale)
r2 = plot(bwOn ? b2e : na, "BW EMA 2", fade(color.new(hueA, 25)), 1, display = display.all - display.status_line - display.price_scale)
r3 = plot(bwOn ? b3e : na, "BW EMA 3 (hidden)", na, editable = false, display = display.all - display.status_line - display.price_scale)
r4 = plot(bwOn ? b4e : na, "BW EMA 4", fade(hueC), 2, display = display.all - display.status_line - display.price_scale)
r5 = plot(bwOn ? b5e : na, "BW EMA 5 (hidden)", na, editable = false, display = display.all - display.status_line - display.price_scale)
fill(r1, r2, bwWedge ? color.new(hueA, fillT) : na, "Wedge")
fill(r3, r4, bwBand ? color.new(hueC, darkT) : na, "Dark band")
fill(r4, r5, bwCloud ? color.new(hueD, deepT) : na, "Deep cloud")
 
state = close > b3e + kIn * wAtr ? "UPPER EXTENSION" : close > b3e ? "ABOVE EQUILIBRIUM" : close < b3e - kIn * wAtr ? "LOWER EXTENSION" : "BELOW EQUILIBRIUM"
 
tfBull(simple string tf) =>
    request.security(syminfo.tickerid, tf, ta.ema(close, bwLen1) > ta.ema(close, bwLen2), lookahead = barmerge.lookahead_off)
 
s1 = tfBull(tf1)
s2 = tfBull(tf2)
s3 = tfBull(tf3)
s4 = tfBull(tf4)
score = (s1 ? 1 : 0) + (s2 ? 1 : 0) + (s3 ? 1 : 0) + (s4 ? 1 : 0)
 
alertcondition(bull and not bull[1], "Ribbon flips bull", "Black Wing: chart ribbon turned bullish")
alertcondition(not bull and bull[1], "Ribbon flips bear", "Black Wing: chart ribbon turned bearish")
alertcondition(score == 4 and score[1] < 4, "All green", "Black Wing: every timeframe bull")
alertcondition(score == 0 and score[1] > 0, "All red", "Black Wing: every timeframe bear")
// ---------------------------------------- Black Wing --------------------------------------------------
 
 
// ---------------------------------------- Opening Range & OTE --------------------------------------------------
// IB30 / IB60 = high and low of the first 30 / 60 minutes after the cash open, each fixed from the first
// bar that opens after its window. Today's range and volume are tracked over the same cash session.
type IB
    float hi   = na
    float lo   = na
    int   hiT  = na
    int   loT  = na
    bool  done = false
    int   endB = na
 
inCash   = not na(time(timeframe.period, cashSess, "America/New_York"))
// A new cash session: entering the session, or a new day while already in it (a regular-hours-only
// chart has no bars outside the session, so the first bar of each day is the open).
cashOpen = inCash and (not inCash[1] or timeframe.change("D"))
var IB    ib30    = IB.new()
var IB    ib60    = IB.new()
var int   openT   = na
var int   openB   = na
var float dayHi   = na
var float dayLo   = na
var float dayVol  = 0.0
 
// +1 bullish (high made after the low), -1 bearish; a tie on coarse charts goes by the close vs the midpoint.
ibDir(IB b) =>
    b.hiT > b.loT ? 1 : b.hiT < b.loT ? -1 : close >= (b.hi + b.lo) / 2 ? 1 : -1
 
// OTE level r: bullish = hi - r * range (0 at the high, 1 at the low); bearish = lo + r * range.
oteLevel(IB b, int d, float r) =>
    d == 1 ? b.hi - r * (b.hi - b.lo) : b.lo + r * (b.hi - b.lo)
 
var float[] oteR = array.new_float()
var string[] oteN = array.new_string()
if barstate.isfirst
    for part in str.split(oteLvls, ",")
        float v = str.tonumber(str.trim(part))
        if not na(v)
            oteR.push(v)
            oteN.push(str.trim(part))
 
if cashOpen
    ib30 := IB.new()
    ib60 := IB.new()
    openT := time
    openB := bar_index
    dayHi := high
    dayLo := low
    dayVol := 0.0
// Overnight = every bar outside the cash session since the last close; fixed at the open as ONH / ONL.
var float onHi    = na
var float onLo    = na
var float onHiFix = na
var float onLoFix = na
if not inCash and timeframe.isintraday
    onHi := na(onHi) ? high : math.max(onHi, high)
    onLo := na(onLo) ? low : math.min(onLo, low)
if cashOpen
    onHiFix := onHi
    onLoFix := onLo
    onHi := na
    onLo := na
if inCash and not na(openT)
    dayHi := math.max(dayHi, high)
    dayLo := math.min(dayLo, low)
    dayVol += nz(volume)
 
// Relative volume from the chart's OWN bars: today's volume so far vs the same minutes-since-open on the
// last rvDays sessions. (TradingView's daily volume is consolidated, but intraday volume on non-pro data is
// one exchange's share, so mixing the two reads far too low.) History: flat arrays, one segment per day.
var int[]   rvOff   = array.new_int()
var float[] rvCum   = array.new_float()
var int[]   rvStart = array.new_int()
var int[]   tdOff   = array.new_int()
var float[] tdCum   = array.new_float()
if cashOpen and tdOff.size() > 0
    rvStart.push(rvOff.size())
    rvOff.concat(tdOff)
    rvCum.concat(tdCum)
    tdOff.clear()
    tdCum.clear()
    while rvStart.size() > rvDays
        int cut = rvStart.size() > 1 ? rvStart.get(1) : rvOff.size()
        for i = 1 to cut
            rvOff.shift()
            rvCum.shift()
        rvStart.shift()
        for [i, v] in rvStart
            rvStart.set(i, v - cut)
if inCash and not na(openT) and timeframe.isintraday
    tdOff.push(int((time - openT) / 60000))
    tdCum.push(dayVol)
 
// [average cumulative volume at this minute of the session, average full-day volume, days used]
rvAverages() =>
    int nowOff = int((time - openT) / 60000)
    float sAt = 0.0
    float sFull = 0.0
    int n = rvStart.size()
    if n > 0
        for d = 0 to n - 1
            int a = rvStart.get(d)
            int b = d < n - 1 ? rvStart.get(d + 1) - 1 : rvOff.size() - 1
            float at = 0.0
            for i = a to b
                if rvOff.get(i) <= nowOff
                    at := rvCum.get(i)
            sAt += at
            sFull += rvCum.get(b)
    [n > 0 ? sAt / n : na, n > 0 ? sFull / n : na, n]
 
ibTrack(IB b, int mins) =>
    if not b.done and not na(openT)
        if time - openT < mins * 60000
            if na(b.hi) or high > b.hi
                b.hi := high
                b.hiT := time
            if na(b.lo) or low < b.lo
                b.lo := low
                b.loT := time
        else if not na(b.hi)
            b.done := true
            b.endB := bar_index
 
if inCash and timeframe.isintraday
    ibTrack(ib30, 30)
    ibTrack(ib60, 60)
 
IB oteIb = oteSrc == "IB30" ? ib30 : ib60
inOteTime = not na(time(timeframe.period, oteSess, "America/New_York"))
oteShow  = oteOn and timeframe.isintraday and not na(oteIb.hi) and (oteIb.done or oteLive) and (not oteTimeOn or inOteTime)
oteDir   = oteShow ? ibDir(oteIb) : 0
 
// IB / OTE drawings, killzone style: each is created once its IB completes, grows bar by bar through
// its own cash session, and then stays where it is. The current session plus ibKeep past ones are kept.
var line[] sesLn = array.new_line()
var box[]  sesBx = array.new_box()
var int[]  sesNl = array.new_int()      // lines per session, oldest first
var int[]  sesNb = array.new_int()      // boxes per session
var bool   drew30  = false
var bool   drew60  = false
var bool   drewOte = false
 
sesLine(float y, color c, string st, int w) =>
    if not na(y)
        sesLn.push(line.new(openT, y, time, y, xloc = xloc.bar_time, color = fade(c), style = st, width = w))
        sesNl.set(sesNl.size() - 1, sesNl.last() + 1)
 
if timeframe.isintraday and cashOpen
    sesNl.push(0)
    sesNb.push(0)
    drew30 := false
    drew60 := false
    drewOte := false
    while sesNl.size() > ibKeep + 1
        int a = sesNl.shift()
        int b = sesNb.shift()
        if a > 0
            for i = 1 to a
                sesLn.shift().delete()
        if b > 0
            for i = 1 to b
                sesBx.shift().delete()
 
if timeframe.isintraday and sesNl.size() > 0 and not na(openT)
    if ibOn and ib30.done and not drew30
        sesLine(ib30.hi, ibCol30, line.style_solid, 1)
        sesLine(ib30.lo, ibCol30, line.style_solid, 1)
        sesLine((ib30.hi + ib30.lo) / 2, color.new(ibCol30, 50), line.style_dashed, 1)
        drew30 := true
    if ib60On and ib60.done and not drew60
        sesLine(ib60.hi, ibCol60, line.style_solid, 2)
        sesLine(ib60.lo, ibCol60, line.style_solid, 2)
        sesLine((ib60.hi + ib60.lo) / 2, color.new(ibCol60, 50), line.style_dashed, 1)
        drew60 := true
    if oteOn and oteIb.done and not drewOte
        int d = ibDir(oteIb)
        for r in oteR
            sesLine(oteLevel(oteIb, d, r), color.new(oteCol, r == 0.618 or r == 0.786 ? 0 : 45), line.style_dashed, 1)
        if oteZone
            float z1 = oteLevel(oteIb, d, 0.618)
            float z2 = oteLevel(oteIb, d, 0.786)
            sesBx.push(box.new(openT, math.max(z1, z2), time, math.min(z1, z2), xloc = xloc.bar_time, border_color = color.new(d == 1 ? oteBull : oteBear, 100), bgcolor = color.new(d == 1 ? oteBull : oteBear, 85)))
            sesNb.set(sesNb.size() - 1, sesNb.last() + 1)
        drewOte := true
    // grow the current session's drawings while its cash session is open
    if inCash
        int nl = sesNl.last()
        int nb = sesNb.last()
        if nl > 0
            for i = sesLn.size() - nl to sesLn.size() - 1
                sesLn.get(i).set_x2(time)
        if nb > 0
            for i = sesBx.size() - nb to sesBx.size() - 1
                sesBx.get(i).set_right(time)
// ---------------------------------------- Opening Range & OTE --------------------------------------------------
 
 
// ---------------------------------------- Prior Day & Day Stats --------------------------------------------------
// Completed daily bars only ([1] + lookahead_on): yesterday's H/L/C, ATR(14), average range and volume (20 days).
[pdH, pdL, pdC, dAtr, dAdr, dAvgV] = request.security(tk, "D", [high[1], low[1], close[1], ta.atr(14)[1], ta.sma(high - low, 20)[1], ta.sma(volume, 20)[1]], lookahead = barmerge.lookahead_on)
pdShow  = pdOn and timeframe.isintraday
onShow  = onOn and timeframe.isintraday and not na(onHiFix)
earnT   = earnings.future_time
earnDays = na(earnT) ? na : math.ceil((earnT - timenow) / 86400000.0)
// ---------------------------------------- Prior Day & Day Stats --------------------------------------------------
 
 
// ---------------------------------------- RS Rating --------------------------------------------------
// Rating curve and daily cutoffs from Fred6724's RS Rating (Mozilla Public License 2.0), as used in
// TheMarketBishop's Biryani Ribbons. Score = weighted 1-year performance (last quarter x 0.4, the three
// before x 0.2 each) of this symbol / the same for the S&P 500 x 100; the feed's 7 cutoffs (ratings 99,
// 90, 70, 50, 30, 10, 1 across ~6,100 US stocks) place it on 1 - 99.
rsPerf() =>
    float c0 = ta.valuewhen(barstate.isfirst, close, 0)
    0.4 * close / nz(close[63], c0) + 0.2 * close / nz(close[126], c0) + 0.2 * close / nz(close[189], c0) + 0.2 * close / nz(close[252], c0)
rsStockPerf = request.security(syminfo.tickerid, "D", rsPerf(), ignore_invalid_symbol = true)
rsSpxPerf   = request.security("SP:SPX", "D", rsPerf(), ignore_invalid_symbol = true)
rsScore     = rsSpxPerf > 0 ? rsStockPerf / rsSpxPerf * 100 : na
 
// Backup cutoffs (Oct 8, 2026), used only if the feed cannot be read at all.
const float RSB_99 = 212.35
const float RSB_90 = 121.49
const float RSB_70 = 96.99
const float RSB_50 = 88.88
const float RSB_30 = 76.26
const float RSB_10 = 48.92
const float RSB_01 = 17.15
rsCuts() =>
    float sv = request.seed("seed_fred6725_rs_rating", "RSRATING", close, true)
    float st = request.seed("seed_fred6725_rs_rating", "RSRATING", time, true)
    array<float> vals = array.new<float>()
    float lastT = na
    for i = 0 to 44
        float v = sv[i]
        if na(lastT) and not na(st[i])
            lastT := st[i]
        if not na(v) and v != 0 and vals.size() < 7 and not vals.includes(v)
            vals.push(v)
    bool ok = vals.size() == 7
    if ok
        vals.sort(order.descending)
    while vals.size() < 7
        vals.push(na)
    [ok ? 1.0 : 0.0, lastT, vals.get(0), vals.get(1), vals.get(2), vals.get(3), vals.get(4), vals.get(5), vals.get(6)]
[rsOk, rsFeedT, rsL99, rsL90, rsL70, rsL50, rsL30, rsL10, rsL01] = request.security("SP:SPX", "D", rsCuts())
rsHaveFeed = rsOk == 1.0
rsStale = not rsHaveFeed or na(rsFeedT) or (timenow - rsFeedT) / 86400000.0 > 7
rsC99 = rsHaveFeed ? rsL99 : RSB_99
rsC90 = rsHaveFeed ? rsL90 : RSB_90
rsC70 = rsHaveFeed ? rsL70 : RSB_70
rsC50 = rsHaveFeed ? rsL50 : RSB_50
rsC30 = rsHaveFeed ? rsL30 : RSB_30
rsC10 = rsHaveFeed ? rsL10 : RSB_10
rsC01 = rsHaveFeed ? rsL01 : RSB_01
rsBand(float x, float taller, float smaller, float rUp, float rDn, float w) =>
    float sm = x + (x - smaller) * w
    if sm > taller - 1
        sm := taller - 1
    float k1 = smaller / rDn
    float k2 = (taller - 1) / rUp
    float k3 = (k1 - k2) / (taller - 1 - smaller)
    math.max(rDn, math.min(rUp, sm / (k1 - k3 * (x - smaller))))
rsRate(float x) =>
    float rr = na(x) ? na : x >= rsC99 ? 99.0 : x >= rsC90 ? rsBand(x, rsC99, rsC90, 98, 90, 0.33) : x >= rsC70 ? rsBand(x, rsC90, rsC70, 89, 70, 2.1) : x >= rsC50 ? rsBand(x, rsC70, rsC50, 69, 50, 0) : x >= rsC30 ? rsBand(x, rsC50, rsC30, 49, 30, 0) : x >= rsC10 ? rsBand(x, rsC30, rsC10, 29, 10, 0) : x > rsC01 ? rsBand(x, rsC10, rsC01, 9, 2, 0) : 1.0
    na(rr) ? na : float(math.max(1, math.min(99, math.round(rr))))
rsRating = rsRate(rsScore)
// The strip's rating: on intraday charts the previous day's finished score, so past squares never change.
rsStockC = timeframe.isintraday ? request.security(syminfo.tickerid, "D", rsPerf()[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true) : rsStockPerf
rsSpxC   = timeframe.isintraday ? request.security("SP:SPX", "D", rsPerf()[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true) : rsSpxPerf
rsRatingC = rsRate(rsSpxC > 0 ? rsStockC / rsSpxC * 100 : na)
rsColFor(float r) =>
    na(r) ? color.gray : r >= 80 ? cUp : r < 40 ? cDn : color.gray
plotshape(rsOn and rsStripOn and not na(rsRatingC), "RS strip", shape.square, location.bottom, color.new(ink(rsColFor(rsRatingC)), rsStripT), size = size.tiny, display = display.pane)
 
// RS line new highs (labels, so they cost no plot slots).
rsSpxNow = request.security("SP:SPX", timeframe.period, close, ignore_invalid_symbol = true)
rsLine   = rsSpxNow > 0 ? close / rsSpxNow : na
rsLook   = timeframe.isweekly and rsDotLen == 250 ? 52 : rsDotLen
rsHi     = ta.highest(rsLine, rsLook)
rsLo     = ta.lowest(rsLine, rsLook)
rsCorr   = ta.correlation(ta.roc(close, 1), ta.roc(rsSpxNow, 1), 50)
pxHi     = ta.highest(high, rsLook)
rsMoves  = not na(rsLo) and rsLo > 0 and (rsHi - rsLo) / rsLo > 0.005 and nz(rsCorr) < 0.98
rsLead   = rsOn and rsDotsOn and not na(rsLine) and rsLine >= rsHi and rsMoves and (rsDotMode == "Every RS new high" or high < pxHi) and barstate.isconfirmed
var label[] rsDots = array.new_label()
if rsLead
    rsDots.push(label.new(bar_index, high, "●", yloc = yloc.abovebar, style = label.style_none, textcolor = textFade(rsCol), size = size.small, tooltip = "RS line new high: " + syminfo.ticker + " vs the S&P 500 is at its highest in " + str.tostring(rsLook) + " bars" + (high < pxHi ? ", while price is not - strength leading price." : ".")))
    if rsDots.size() > 60
        rsDots.shift().delete()
 
var label rsBadge = na
if barstate.islast
    if not na(rsBadge)
        rsBadge.delete()
    if rsOn and rsBadgeOn and not na(rsRating)
        color bc = rsColFor(rsRating)
        rsBadge := label.new(bar_index, high, "RS " + str.tostring(rsRating, "#") + (rsStale ? "*" : ""), yloc = yloc.abovebar, style = label.style_label_down, color = color.new(ink(bc), 10), textcolor = color.white, size = size.small, text_formatting = text.format_bold, tooltip = "RS Rating " + str.tostring(rsRating, "#") + " of 99: " + syminfo.ticker + "'s past year beat about " + str.tostring(rsRating, "#") + "% of ~6,100 US stocks." + (rsStale ? " (* estimated: the daily rating data is late or unreadable.)" : ""))
// ---------------------------------------- RS Rating --------------------------------------------------
 
 
// ---------------------------------------- ICT Killzones --------------------------------------------------
// After tradeforopp's "ICT Killzones & Pivots": a box per session, and its high / low extended until taken.
// Light fills in this script's own neon hues; kept for kzKeep sessions; charts of 30 minutes or less.
type KZone
    string  name
    color   col
    box[]   bx
    line[]  hl
    line[]  ll
    label[] hb
    label[] lb
    bool[]  hLive
    bool[]  lLive
 
newKz(string n, color c) =>
    KZone.new(n, c, array.new_box(), array.new_line(), array.new_line(), array.new_label(), array.new_label(), array.new_bool(), array.new_bool())
 
var KZone kz1 = newKz(kzN1, kzC1)
var KZone kz2 = newKz(kzN2, kzC2)
var KZone kz3 = newKz(kzN3, kzC3)
var KZone kz4 = newKz(kzN4, kzC4)
var KZone kz5 = newKz(kzN5, kzC5)
 
kzTfOk = timeframe.isintraday and timeframe.in_seconds() <= 1800
// Killzone colours with kzMoreT extra transparency.
kzc(color c) =>
    color.new(c, math.min(100, color.t(c) + kzMoreT))
kzTip(KZone z, string side, float y, int t0) =>
    z.name + " " + side + ": " + str.tostring(y, format.mintick) + "  (" + str.format_time(t0, "MMM d HH:mm", "America/New_York") + " ET session)"
 
kzStep(KZone z, bool on, bool inZ, bool wasIn) =>
    if on and kzOn and kzTfOk
        if inZ and not wasIn
            z.bx.unshift(box.new(time, high, time, low, xloc = xloc.bar_time, border_color = fade(kzc(color.new(z.col, 70))), bgcolor = color.new(ink(z.col), kzFillT), text = z.name, text_color = textFade(kzc(z.col)), text_size = size.tiny, text_halign = text.align_left, text_valign = text.align_top))
            z.hl.unshift(line.new(time, high, time, high, xloc = xloc.bar_time, color = fade(kzc(z.col))))
            z.ll.unshift(line.new(time, low, time, low, xloc = xloc.bar_time, color = fade(kzc(z.col))))
            z.hb.unshift(label.new(time, high, z.name + " H", xloc = xloc.bar_time, style = label.style_label_left, color = #ffffff00, textcolor = textFade(kzc(z.col)), size = size.tiny, text_formatting = text.format_bold, tooltip = kzTip(z, "high", high, time)))
            z.lb.unshift(label.new(time, low, z.name + " L", xloc = xloc.bar_time, style = label.style_label_left, color = #ffffff00, textcolor = textFade(kzc(z.col)), size = size.tiny, text_formatting = text.format_bold, tooltip = kzTip(z, "low", low, time)))
            z.hLive.unshift(true)
            z.lLive.unshift(true)
            while z.bx.size() > kzKeep
                z.bx.pop().delete()
                z.hl.pop().delete()
                z.ll.pop().delete()
                z.hb.pop().delete()
                z.lb.pop().delete()
                z.hLive.pop()
                z.lLive.pop()
        if z.bx.size() > 0
            box b = z.bx.get(0)
            if inZ
                float top = math.max(b.get_top(), high)
                float bot = math.min(b.get_bottom(), low)
                b.set_right(time)
                b.set_top(top)
                b.set_bottom(bot)
                z.hl.get(0).set_y1(top)
                z.hl.get(0).set_y2(top)
                z.hl.get(0).set_x2(time)
                z.ll.get(0).set_y1(bot)
                z.ll.get(0).set_y2(bot)
                z.ll.get(0).set_x2(time)
                z.hb.get(0).set_xy(time, top)
                z.lb.get(0).set_xy(time, bot)
                z.hb.get(0).set_tooltip(kzTip(z, "high", top, b.get_left()))
                z.lb.get(0).set_tooltip(kzTip(z, "low", bot, b.get_left()))
            else if kzPivots
                bool always = kzExt == "Always (latest session)"
                float yh = z.hl.get(0).get_y1()
                float yl = z.ll.get(0).get_y1()
                if z.hLive.get(0) or always
                    z.hl.get(0).set_x2(time)
                    z.hb.get(0).set_x(time)
                if z.lLive.get(0) or always
                    z.ll.get(0).set_x2(time)
                    z.lb.get(0).set_x(time)
                if z.hLive.get(0) and high > yh
                    z.hLive.set(0, false)
                    z.hb.get(0).set_tooltip(kzTip(z, "high", yh, b.get_left()) + "\nTaken " + str.format_time(time, "MMM d HH:mm", "America/New_York") + " ET")
                    if kzAlerts
                        alert(syminfo.ticker + ": " + z.name + " high " + str.tostring(yh, format.mintick) + " taken", alert.freq_once_per_bar)
                if z.lLive.get(0) and low < yl
                    z.lLive.set(0, false)
                    z.lb.get(0).set_tooltip(kzTip(z, "low", yl, b.get_left()) + "\nTaken " + str.format_time(time, "MMM d HH:mm", "America/New_York") + " ET")
                    if kzAlerts
                        alert(syminfo.ticker + ": " + z.name + " low " + str.tostring(yl, format.mintick) + " taken", alert.freq_once_per_bar)
 
tk1 = not na(time(timeframe.period, kzS1, "America/New_York"))
tk2 = not na(time(timeframe.period, kzS2, "America/New_York"))
tk3 = not na(time(timeframe.period, kzS3, "America/New_York"))
tk4 = not na(time(timeframe.period, kzS4, "America/New_York"))
tk5 = not na(time(timeframe.period, kzS5, "America/New_York"))
kzStep(kz1, kzOn1, tk1, tk1[1])
kzStep(kz2, kzOn2, tk2, tk2[1])
kzStep(kz3, kzOn3, tk3, tk3[1])
kzStep(kz4, kzOn4, tk4, tk4[1])
kzStep(kz5, kzOn5, tk5, tk5[1])
// ---------------------------------------- ICT Killzones --------------------------------------------------
 
 
// ---------------------------------------- Lines & Right-Edge Labels --------------------------------------------------
// Today's IB / OTE / prior-day lines are redrawn on the last bar from the cash open (no history kept).
chartAtr = ta.atr(14)
var line[]  dayLines = array.new_line()
var box     oteBox   = na
var label[] edgeLbls = array.new_label()
 
// x1 is a bar TIME: bar-index drawings reaching back past the history buffer (~300 bars) fail at runtime.
dline(int x1, float y, color c, string st, int w) =>
    if not na(y) and not na(x1)
        dayLines.push(line.new(x1, y, time + lblOff * timeframe.in_seconds() * 1000, y, xloc = xloc.bar_time, color = fade(c), style = st, width = w))
 
addTag(float[] ys, string[] ts, color[] cs, bool on, float y, string name, color c, bool withPrice = true) =>
    if on and not na(y)
        ys.push(y)
        ts.push(withPrice ? name + " " + str.tostring(y, format.mintick) : name)
        cs.push(c)
 
// Hover text for a right-edge tag, from its name.
tagTip(string s) =>
    str.contains(s, " EMA ") ? s + ": a higher-timeframe EMA drawn on this chart (Live mode blends the current price into the last completed higher-timeframe bar's EMA; past bars never repaint)." :
     str.startswith(s, "pVWAP") ? s + ": yesterday's closing VWAP." :
     str.startswith(s, "VWAP +") or str.startswith(s, "VWAP -") ? s + ": a VWAP band, this many volume-weighted standard deviations of today's prices from VWAP." :
     str.startswith(s, "VWAP") ? s + ": today's volume-weighted average price, reset each day." :
     str.startswith(s, "IB") ? s + ": initial balance, the high / low / mid of the first " + (str.startswith(s, "IB30") ? "30" : "60") + " minutes after the 9:30 cash open." :
     str.startswith(s, "OTE") ? s + ": OTE fib on " + oteSrc + ". Bullish = 0 at the IB high and 1 at the IB low (pullback levels down), bearish mirrored; the 0.618 - 0.786 band is shaded." :
     str.contains(s, " H ") and not str.startswith(s, "IB") and not str.contains(s, "liq") ? s + ": the latest killzone session's high." :
     str.contains(s, " L ") and not str.startswith(s, "IB") and not str.contains(s, "liq") ? s + ": the latest killzone session's low." :
     str.startswith(s, "PDH") ? s + ": prior day's regular-hours high." :
     str.startswith(s, "PDL") ? s + ": prior day's regular-hours low." :
     str.startswith(s, "PDC") ? s + ": prior day's regular-hours close." :
     str.startswith(s, "ONH") ? s + ": overnight high, the extended-hours bars between yesterday's close and today's open." :
     str.startswith(s, "ONL") ? s + ": overnight low, the extended-hours bars between yesterday's close and today's open." :
     str.contains(s, " liq ") ? s + ": unraided liquidity, a swing " + (str.contains(s, " liq H") ? "high" : "low") + " on the " + liqTf + " chart (" + str.tostring(liqLeft) + " bars each side) that price has not traded through since." :
     s
 
// The latest killzone session's high / low copied into the right-edge tags (the lines are not extended).
kzTag(KZone z, bool on, float[] ys, string[] ts, color[] cs) =>
    if on and kzOn and kzTfOk and z.bx.size() > 0
        // its own small H / L labels would sit right next to the copies: blank them while tags are on
        z.hb.get(0).set_text(kzTags ? "" : z.name + " H")
        z.lb.get(0).set_text(kzTags ? "" : z.name + " L")
    if on and kzOn and kzTfOk and kzTags and z.bx.size() > 0
        addTag(ys, ts, cs, true, z.hl.get(0).get_y1(), z.name + " H", kzc(z.col))
        addTag(ys, ts, cs, true, z.ll.get(0).get_y1(), z.name + " L", kzc(z.col))
 
tagSize = lblSize == "Tiny" ? size.tiny : lblSize == "Normal" ? size.normal : size.small
 
if barstate.islast
    for ln in dayLines
        ln.delete()
    dayLines.clear()
    if not na(oteBox)
        oteBox.delete()
    for lb in edgeLbls
        lb.delete()
    edgeLbls.clear()
    if timeframe.isintraday and not na(openB)
        if oteShow and not oteIb.done
            // The OTE while its IB is still forming (re-drawn each update); once the IB completes it
            // becomes a permanent drawing above. 0.618 / 0.786 drawn brighter than the rest.
            for r in oteR
                dline(openT, oteLevel(oteIb, oteDir, r), color.new(oteCol, r == 0.618 or r == 0.786 ? 0 : 45), line.style_dashed, 1)
            if oteZone
                oteBox := box.new(openT, math.max(oteLevel(oteIb, oteDir, 0.618), oteLevel(oteIb, oteDir, 0.786)), time + lblOff * timeframe.in_seconds() * 1000, math.min(oteLevel(oteIb, oteDir, 0.618), oteLevel(oteIb, oteDir, 0.786)), xloc = xloc.bar_time, border_color = color.new(oteDir == 1 ? oteBull : oteBear, 100), bgcolor = color.new(oteDir == 1 ? oteBull : oteBear, 85))
        if pdShow
            dline(openT, pdH, pdHLCol, line.style_dashed, 1)
            dline(openT, pdL, pdHLCol, line.style_dashed, 1)
            dline(openT, pdC, pdCCol, line.style_dotted, 1)
        if onShow
            dline(openT, onHiFix, onCol, line.style_dashed, 1)
            dline(openT, onLoFix, onCol, line.style_dashed, 1)
        if vwOn and showPrev
            dline(openT, prevV, vwCol, line.style_dotted, 1)
    // Unraided liquidity: one line from each swing to the right edge (bar_time, since the swing may be
    // on a higher timeframe than the chart).
    if liqOn
        int xR = time + lblOff * timeframe.in_seconds() * 1000
        for [i, y] in liqP
            bool hi = liqHi.get(i)
            dayLines.push(line.new(liqT.get(i), y, xR, y, xloc = xloc.bar_time, color = fade(hi ? liqHiCol : liqLoCol), width = liqWidth))
 
    if lblOn
        float[]  ys = array.new_float()
        string[] ts = array.new_string()
        color[]  cs = array.new_color()
        bool emaTags = emaShow and emaLbl
        addTag(ys, ts, cs, emaTags and eOn1, he1, emaTf + " EMA " + str.tostring(eLen1), eCol1)
        addTag(ys, ts, cs, emaTags and eOn2, he2, emaTf + " EMA " + str.tostring(eLen2), eCol2)
        addTag(ys, ts, cs, emaTags and eOn3, he3, emaTf + " EMA " + str.tostring(eLen3), eCol3)
        addTag(ys, ts, cs, emaTags and eOn4, he4, emaTf + " EMA " + str.tostring(eLen4), eCol4)
        addTag(ys, ts, cs, emaTags and eOn5, he5, emaTf + " EMA " + str.tostring(eLen5), eCol5)
        bool ema2Tags = ema2Show and emaLbl
        addTag(ys, ts, cs, ema2Tags and fOn1, ge1, ema2TfEff + " EMA " + str.tostring(fLen1), fCol1)
        addTag(ys, ts, cs, ema2Tags and fOn2, ge2, ema2TfEff + " EMA " + str.tostring(fLen2), fCol2)
        addTag(ys, ts, cs, ema2Tags and fOn3, ge3, ema2TfEff + " EMA " + str.tostring(fLen3), fCol3)
        addTag(ys, ts, cs, ema2Tags and fOn4, ge4, ema2TfEff + " EMA " + str.tostring(fLen4), fCol4)
        addTag(ys, ts, cs, ema2Tags and fOn5, ge5, ema2TfEff + " EMA " + str.tostring(fLen5), fCol5)
        addTag(ys, ts, cs, vwOn, vwap, "VWAP", vwCol)
        if vwOn and vwBandTags and not na(vDev)
            addTag(ys, ts, cs, true, vwap + dev1 * vDev, "VWAP +" + str.tostring(dev1) + "sd", color.gray)
            addTag(ys, ts, cs, true, vwap - dev1 * vDev, "VWAP -" + str.tostring(dev1) + "sd", color.gray)
            addTag(ys, ts, cs, showB2, vwap + dev2 * vDev, "VWAP +" + str.tostring(dev2) + "sd", vwUpCol)
            addTag(ys, ts, cs, showB2, vwap - dev2 * vDev, "VWAP -" + str.tostring(dev2) + "sd", vwDnCol)
            addTag(ys, ts, cs, showB3, vwap + devOut * vDev, "VWAP +" + str.tostring(devOut) + "sd", vwUpCol)
            addTag(ys, ts, cs, showB3, vwap - devOut * vDev, "VWAP -" + str.tostring(devOut) + "sd", vwDnCol)
        bool intra = timeframe.isintraday
        addTag(ys, ts, cs, intra and ibOn and ib30.done, ib30.hi, "IB30 H", ibCol30)
        addTag(ys, ts, cs, intra and ibOn and ib30.done, ib30.lo, "IB30 L", ibCol30)
        addTag(ys, ts, cs, intra and ib60On and ib60.done, ib60.hi, "IB60 H", ibCol60)
        addTag(ys, ts, cs, intra and ib60On and ib60.done, ib60.lo, "IB60 L", ibCol60)
        addTag(ys, ts, cs, intra and ib60On and ib60.done, (ib60.hi + ib60.lo) / 2, "IB60 mid", color.new(ibCol60, 30))
        if oteShow
            string od = oteIb.done ? "" : " (forming)"
            for [i, r] in oteR
                // 0 and 1 sit on the IB high / low already tagged above: skip them when that IB's tags show.
                bool onIb = (r == 0 or r == 1) and oteIb.done and (oteSrc == "IB30" ? ibOn : ib60On)
                addTag(ys, ts, cs, not onIb, oteLevel(oteIb, oteDir, r), "OTE " + oteN.get(i) + od, oteCol, false)
        addTag(ys, ts, cs, pdShow, pdH, "PDH", pdHLCol)
        addTag(ys, ts, cs, pdShow, pdL, "PDL", pdHLCol)
        addTag(ys, ts, cs, pdShow, pdC, "PDC", pdCCol)
        addTag(ys, ts, cs, onShow, onHiFix, "ONH", onCol)
        addTag(ys, ts, cs, onShow, onLoFix, "ONL", onCol)
        kzTag(kz1, kzOn1, ys, ts, cs)
        kzTag(kz2, kzOn2, ys, ts, cs)
        kzTag(kz3, kzOn3, ys, ts, cs)
        kzTag(kz4, kzOn4, ys, ts, cs)
        kzTag(kz5, kzOn5, ys, ts, cs)
        addTag(ys, ts, cs, vwOn and showPrev and timeframe.isintraday, prevV, "pVWAP", vwCol)
        if liqOn and liqTags
            for [i, y] in liqP
                bool hi = liqHi.get(i)
                addTag(ys, ts, cs, true, y, liqTf + (hi ? " liq H" : " liq L"), hi ? liqHiCol : liqLoCol)
        // Walk up by price: tags within lblMerge share one tag; each tag sits at least lblGap above the last.
        if ys.size() > 0
            float mergeTol = lblMerge * chartAtr
            float gap = math.max(lblGap * chartAtr, nz(lblGapD * dAtr))
            int[] idx = ys.sort_indices(order.ascending)
            float prevY = na
            int k = 0
            while k < idx.size()
                float y0 = ys.get(idx.get(k))
                string txt = ts.get(idx.get(k))
                string tip = tagTip(ts.get(idx.get(k)))
                color c = cs.get(idx.get(k))
                int j = k + 1
                while j < idx.size() and ys.get(idx.get(j)) - y0 <= mergeTol
                    txt += " · " + ts.get(idx.get(j))
                    tip += "\n\n" + tagTip(ts.get(idx.get(j)))
                    j += 1
                float y = na(prevY) ? y0 : math.max(y0, prevY + gap)
                edgeLbls.push(label.new(bar_index + lblOff, y, txt, style = label.style_label_left, color = #ffffff00, textcolor = textFade(c), size = tagSize, tooltip = tip, text_formatting = text.format_bold))
                prevY := y
                k := j
// ---------------------------------------- Lines & Right-Edge Labels --------------------------------------------------
 
 
// ---------------------------------------- Dashboard --------------------------------------------------
tfName(string tf) =>
    switch tf
        "15"  => "15 Min"
        "60"  => "60 Min"
        "240" => "4 Hour"
        "D"   => "Daily"
        "W"   => "Weekly"
        "M"   => "Monthly"
        => tf
 
tfShort(string tf) =>
    switch tf
        "15"  => "15m"
        "60"  => "1h"
        "240" => "4h"
        "D"   => "D"
        "W"   => "W"
        "M"   => "M"
        => tf
 
cBgHd  = isLight ? #e5e7eb : #0b0e13
cBg    = isLight ? #ffffff : #11151c
cLab   = isLight ? #111827 : #b9c2d0
cHead  = isLight ? #111827 : color.white
cEdge  = isLight ? #9ca3af : #2c3646
cAmb   = isLight ? #b45309 : #e8b34a
dSize  = dashSize == "Tiny" ? size.tiny : dashSize == "Normal" ? size.normal : dashSize == "Large" ? size.large : size.small
compact = dashMode == "Compact"
 
dcell(table t, int col, int r, string txt, color c, string align, color bg, string tip = "") =>
    table.cell(t, col, r, txt, text_color = c, text_size = dSize, bgcolor = bg, text_halign = align, text_formatting = text.format_bold, tooltip = tip)
 
// One label / value row; the value colour is darkened on white so it stays readable.
cellRow(table t, int r, string lbl, string val, color c, string tip = "") =>
    dcell(t, 0, r, lbl, cLab, text.align_left, cBg, tip)
    dcell(t, 1, r, val, ink(c), text.align_right, cBg, tip)
    r + 1
 
emaRow(table t, int r, bool on, float v, float prev, int n, color c) =>
    int out = r
    if on and not na(v)
        float d = (close - v) / v * 100
        string arrow = v > prev ? " ▲" : v < prev ? " ▼" : " •"
        string val = compact ? str.tostring(d, "+0.00;-0.00") + "%" + arrow : str.tostring(math.abs(d), "0.00") + "% " + (d >= 0 ? "above" : "below") + arrow
        string tip = emaTf + " EMA " + str.tostring(n) + " = " + str.tostring(v, format.mintick) + ". Price is " + str.tostring(math.abs(d), "0.00") + "% " + (d >= 0 ? "above" : "below") + " it.\nArrow: ▲ the EMA is above the last completed " + emaTf + " bar's EMA (rising), ▼ below it (falling), • unchanged.\n" + (emaMode == "Live" ? "Live mode: today's price is blended into the EMA, so it moves during the day; past bars never change." : "Fixed mode: the last completed " + emaTf + " bar's EMA, flat until the next one.")
        dcell(t, 0, r, (compact ? emaTf : emaTf + " EMA ") + str.tostring(n), ink(c), text.align_left, cBg, tip)
        dcell(t, 1, r, val, ink(c), text.align_right, cBg, tip)
        out += 1
    out
 
// Dashboard hover text.
tipTf(string tf) =>
    "Black Wing ribbon on the " + tfName(tf) + " chart: BULL while EMA " + str.tostring(bwLen1) + " is above EMA " + str.tostring(bwLen2) + " (the wedge is green), BEAR below. Reads that timeframe's current bar, so it can change before the bar closes."
string TIP_SUM   = "ALL GREEN = all four timeframes BULL, ALL RED = all four BEAR, MIXED otherwise. Alerts exist for both."
string TIP_PRIM  = "This chart's Black Wing wedge: EMA " + str.tostring(bwLen1) + " vs EMA " + str.tostring(bwLen2) + ". Flips are alertable."
string TIP_STATE = "Close vs the hidden centre (EMA " + str.tostring(bwLen3) + "). EXTENSION = beyond the inner wing, " + str.tostring(kIn) + " x ATR(" + str.tostring(atrLen) + ") from the centre: price is stretched from equilibrium."
string TIP_VWAP  = "Today's volume-weighted average price (hl2 x volume, reset each day) and how many volume-weighted standard deviations price is from it. Bands at " + str.tostring(dev1) + " and " + str.tostring(dev2) + " sd plus the outer band."
string TIP_VEC   = "Vector (Fractal X) = highest of the " + str.tostring(vecLen) + "-bar lowest lows: follows price up closely and steps down slowly. Above the line = bullish bias, below = bearish (the Fractal X guide)."
string TIP_IB    = "IB30 / IB60 = high and low of the first 30 / 60 minutes after the 9:30 cash open. OTE fib on " + oteSrc + ": bullish (0 at the high, 1 at the low) when the IB high came after the low, bearish when the low came last. Shaded zone = 0.618 - 0.786. Above / inside / below = where price is vs that IB now."
string TIP_ATR   = "Average true range of the last 14 completed regular-hours days, in price and as % of price. A normal day's move: handy for stops and targets."
string TIP_RNG   = "Today's high minus low since the cash open, vs the average daily high-low of the last 20 days. Amber once today has already moved a full normal day: chasing further is riskier."
string TIP_RV    = "Today's volume so far vs the average volume at this same minute of the session over the last " + str.tostring(rvDays) + " sessions, all from this chart's own bars (so a one-exchange data feed compares like with like). Second number: today so far as a share of a full normal day. Amber at 1.5x."
string TIP_ST    = "Distance from the " + emaTf + " EMA " + str.tostring(eLen2) + " in daily ATRs. Amber at 2x or more: price is stretched from that average."
string TIP_EARN  = "Days until the next earnings report (TradingView's calendar). Amber at 7 days or less: moves around earnings can be large and gappy."
string TIP_TFS   = "Black Wing ribbon (EMA " + str.tostring(bwLen1) + " vs " + str.tostring(bwLen2) + ") on " + tfName(tf1) + ", " + tfName(tf2) + ", " + tfName(tf3) + ", " + tfName(tf4) + ": ▲ bull, ▼ bear. Green = all bull, red = all bear, amber = mixed."
string TIP_TREND = "This chart's Black Wing wedge (EMA " + str.tostring(bwLen1) + " vs " + str.tostring(bwLen2) + ") and whether price is above or below the centre line EMA " + str.tostring(bwLen3) + " (EQ)."
string TIP_VV    = TIP_VWAP + "\n\n" + TIP_VEC
string TIP_AR    = TIP_ATR + "\n\n" + TIP_RNG
string TIP_RS    = TIP_RV + "\n\n" + TIP_ST
 
dashWhere = dashPos == "Top Left" ? position.top_left : dashPos == "Middle Right" ? position.middle_right : dashPos == "Bottom Right" ? position.bottom_right : dashPos == "Bottom Left" ? position.bottom_left : position.top_right
gapRows = dashPos == "Top Left" or dashPos == "Top Right" ? dashGap : 0
 
if barstate.islast
    var table t = table.new(dashWhere, 2, 40, border_width = 1)
    t.clear(0, 0, 1, 39)
    if showDash
        t.set_border_color(cEdge)
        t.set_frame_color(cEdge)
        t.set_frame_width(gapRows > 0 ? 0 : 1)
        int r = 0
        if gapRows > 0
            for g = 0 to gapRows - 1
                table.cell(t, 0, g, " ", text_size = dSize)
            r := gapRows
        dcell(t, 0, r, "TOOLKIT", cHead, text.align_left, cBgHd, "Hover any row for what it measures. Lines on the chart have hover text on their right-edge tags; Vector cross markers explain themselves too.")
        dcell(t, 1, r, compact ? "" : "BLACK WING", cHead, text.align_right, cBgHd)
        r += 1
        string sumTxt = score == 4 ? "✦ ALL GREEN" : score == 0 ? "✦ ALL RED" : "◆ MIXED"
        color sumCol = score == 4 ? cUp : score == 0 ? cDn : cAmb
        if compact
            string tfs = tfShort(tf1) + (s1 ? "▲ " : "▼ ") + tfShort(tf2) + (s2 ? "▲ " : "▼ ") + tfShort(tf3) + (s3 ? "▲ " : "▼ ") + tfShort(tf4) + (s4 ? "▲" : "▼")
            r := cellRow(t, r, "Wing TFs", tfs, sumCol, TIP_TFS)
            r := cellRow(t, r, "Trend", (bull ? "▲ BULL" : "▼ BEAR") + (close > b3e ? " · above EQ" : " · below EQ"), bull ? cUp : cDn, TIP_TREND)
        else
            r := cellRow(t, r, tfName(tf1), s1 ? "▲ BULL" : "▼ BEAR", s1 ? cUp : cDn, tipTf(tf1))
            r := cellRow(t, r, tfName(tf2), s2 ? "▲ BULL" : "▼ BEAR", s2 ? cUp : cDn, tipTf(tf2))
            r := cellRow(t, r, tfName(tf3), s3 ? "▲ BULL" : "▼ BEAR", s3 ? cUp : cDn, tipTf(tf3))
            r := cellRow(t, r, tfName(tf4), s4 ? "▲ BULL" : "▼ BEAR", s4 ? cUp : cDn, tipTf(tf4))
            r := cellRow(t, r, sumTxt, "", sumCol, TIP_SUM)
            dcell(t, 0, r - 1, sumTxt, ink(sumCol), text.align_left, cBg, TIP_SUM)
            r := cellRow(t, r, "Primary Trend", bull ? "▲ BULLISH" : "▼ BEARISH", bull ? cUp : cDn, TIP_PRIM)
            r := cellRow(t, r, "Price State", state, close > b3e ? cUp : cDn, TIP_STATE)
        float z = vDev > 0 ? (close - vwap) / vDev : na
        if compact
            r := cellRow(t, r, "VWAP · Vector", (na(vwap) ? "-" : str.tostring(z, "+0.0;-0.0") + "sd") + " · " + (na(vec) ? "-" : vecAbove ? "above" : "below"), close >= vwap ? cUp : cDn, TIP_VV)
        else
            r := cellRow(t, r, "VWAP", na(vwap) ? "no volume" : (close >= vwap ? "above " : "below ") + str.tostring(z, "+#.##;-#.##") + " sd", close >= vwap ? cUp : cDn, TIP_VWAP)
            r := cellRow(t, r, "Vector", na(vec) ? "-" : (vecAbove ? "above " : "below ") + str.tostring(vec, format.mintick), vecAbove ? cUp : cDn, TIP_VEC)
        if timeframe.isintraday and (ibOn or ib60On or oteOn)
            IB b = oteSrc == "IB30" ? ib30 : ib60
            string where = close > b.hi ? "above IB" : close < b.lo ? "below IB" : "inside IB"
            string ibTxt = na(b.hi) ? "waiting for the open" : not b.done ? (compact ? "forming" : oteSrc + " forming " + str.tostring(b.lo, format.mintick) + " – " + str.tostring(b.hi, format.mintick)) : compact ? (oteDir == 1 ? "▲ bull · " : "▼ bear · ") + where : oteSrc + (oteDir == 1 ? " ▲ bull OTE" : " ▼ bear OTE") + " · " + where
            r := cellRow(t, r, compact ? oteSrc : "Opening range", ibTxt, oteDir == 1 ? cUp : oteDir == -1 ? cDn : cLab, TIP_IB)
        if rsOn and not na(rsRating)
            float rsPct = rsScore - 100
            string rsTip = "RS Rating 1 - 99 (IBD style): this symbol's past year, last 3 months counted double, vs about 6,100 US stocks. Past year vs the S&P 500 on the same weighting. Data: Fred6724's daily feed." + (rsStale ? " Marked * while that feed is late or unreadable." : "")
            if compact
                r := cellRow(t, r, "RS", str.tostring(rsRating, "#") + (rsStale ? "*" : "") + " · " + str.tostring(rsPct, "+0;-0") + "% vs SPX", rsColFor(rsRating), rsTip)
            else
                r := cellRow(t, r, "RS Rating", str.tostring(rsRating, "#") + (rsStale ? "*" : ""), rsColFor(rsRating), rsTip)
                r := cellRow(t, r, "Past year vs market", (math.abs(rsPct) < 0.5 ? "matching" : rsPct >= 0 ? "beating by " : "lagging by ") + (math.abs(rsPct) < 0.5 ? "" : str.tostring(math.abs(rsPct), "#") + "%"), rsPct >= 0 ? cUp : cDn, rsTip)
        if dashExtra
            [avgAt, avgFull, nDays] = rvAverages()
            bool haveAtr = not na(dAtr) and close > 0
            bool haveRng = timeframe.isintraday and not na(dayHi) and dAdr > 0
            float used = haveRng ? (dayHi - dayLo) / dAdr : na
            bool haveRv = timeframe.isintraday and dayVol > 0 and avgAt > 0
            float rv = haveRv ? dayVol / avgAt : na
            bool haveSt = emaShow and eOn2 and not na(he2) and dAtr > 0
            float st = haveSt ? (close - he2) / dAtr : na
            if compact
                if haveAtr or haveRng
                    r := cellRow(t, r, "ATR · range", (haveAtr ? str.tostring(dAtr, format.mintick) : "-") + " · " + (haveRng ? str.tostring(used * 100, "#") + "%" : "-"), used >= 1 ? cAmb : cLab, TIP_AR)
                if haveRv or haveSt
                    r := cellRow(t, r, "RVOL · stretch", (haveRv ? str.tostring(rv, "0.00") + "x" : "-") + " · " + (haveSt ? str.tostring(st, "+0.0;-0.0") + " ATR" : "-"), rv >= 1.5 or math.abs(nz(st)) >= 2 ? cAmb : cLab, TIP_RS)
            else
                if haveAtr
                    r := cellRow(t, r, "ATR (14 days)", str.tostring(dAtr, format.mintick) + "  (" + str.tostring(dAtr / close * 100, "0.0") + "%)", cLab, TIP_ATR)
                if haveRng
                    r := cellRow(t, r, "Today's range", str.tostring(dayHi - dayLo, format.mintick) + " = " + str.tostring(used * 100, "#") + "% of normal" + (used >= 1 ? " !" : ""), used >= 1 ? cAmb : cLab, TIP_RNG)
                if haveRv
                    r := cellRow(t, r, "Rel. volume", str.tostring(rv, "0.00") + "x normal for this time · " + str.tostring(dayVol / avgFull * 100, "#") + "% of a full day (" + str.tostring(nDays) + "d)", rv >= 1.5 ? cAmb : cLab, TIP_RV)
                if haveSt
                    r := cellRow(t, r, "Stretch from " + emaTf + " EMA " + str.tostring(eLen2), str.tostring(math.abs(st), "0.0") + "x ATR " + (st >= 0 ? "above" : "below") + (math.abs(st) >= 2 ? " !" : ""), math.abs(st) >= 2 ? cAmb : cLab, TIP_ST)
            if not na(earnDays) and earnDays >= 0 and (not compact or earnDays <= 7)
                r := cellRow(t, r, "Earnings", earnDays == 0 ? "today" : "in " + str.tostring(earnDays) + " days" + (compact ? "" : " (" + str.format_time(int(earnT), "MMM d", "UTC") + ")") + (earnDays <= 7 ? " !" : ""), earnDays <= 7 ? cAmb : cLab, TIP_EARN)
        if dashEmas and emaShow
            r := emaRow(t, r, eOn1, he1, hp1, eLen1, eCol1)
            r := emaRow(t, r, eOn2, he2, hp2, eLen2, eCol2)
            r := emaRow(t, r, eOn3, he3, hp3, eLen3, eCol3)
            r := emaRow(t, r, eOn4, he4, hp4, eLen4, eCol4)
            r := emaRow(t, r, eOn5, he5, hp5, eLen5, eCol5)
// ---------------------------------------- Dashboard --------------------------------------------------

← 返回列表