Flow CISD+ (M1D)

mayb1dayy · study · 1021 行 · 点赞 165 · TradingView 原页

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

Pine Script

//@version=6
// © mayb1dayy
// Flow CISD+ (M1D)
// A delta pane under the chart and a absorption reversal read on it. Each bar's volume is split into
// buying and selling from lower timeframe candles (a candle closing up counts as buying, closing down as
// selling, flat as half each). The pane shows volume, delta and delta as a share of volume in one cell
// per bar under the candles, or as a table, or delta as columns. On the chart: C2 trading through C1's
// high or low on the higher timeframe candles, swing highs and lows taken, absorption (heavy delta into
// a sweep that price does not follow) and the CISD order block that confirms on 1m or 2m closes inside
// C2 or C3, after the sweep extreme. A CISD whose candle's delta flipped its way after absorption at the
// sweep is the full absorption reversal and draws its zone tinted.
indicator("Flow CISD+ (M1D)", "Flow CISD+", overlay = false,
     max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, calc_bars_count = 5000)
 
// == CONSTANTS ==
bool  DARK   = color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color) < 384
color INK    = DARK ? #FFFFFF : #000000
color MUTE   = DARK ? #B2B5BE : #4A4A4A
color NOFILL = color.new(#FFFFFF, 100)
color PILL   = color.new(#787B86, 75)
 
// A drawing anchored on a stored origin can sit thousands of chart bars back. The `time` buffer is
// sized here and anything older clamps to the buffer's edge.
const int MAX_REACH = 4900
max_bars_back(time, 5000)
 
// == INPUTS ==
const string G_FLOW  = "Flow"
const string G_ABS   = "Absorption"
const string G_MODEL = "C1 / C2 model"
const string G_SWP   = "Sweeps"
const string G_SET   = "Settings"
 
string ltfIn   = input.string("Auto", "Delta from", options = ["Auto", "1S", "5S", "15S", "30S", "1"], group = G_FLOW,
     tooltip = "The lower timeframe the delta is built from. Auto picks the finest that still covers the chart's history: 1S up to 2m, 5S on 5m, 15S on 15m, 30S on 1H, 1 minute above. Each candle's volume counts as buying when it closes up, selling when it closes down, and half each when it closes flat. Seconds need a plan with seconds data. When nothing loads the pane stays empty and the Data row says so; it never shows a zero.")
int    avgLen  = input.int(20, "Average over (bars)", minval = 5, maxval = 200, group = G_FLOW,
     tooltip = "The column shading and the absorption test measure each bar's delta against the average size of delta over this many bars.")
bool   stripOn = input.bool(true, "Strip", group = G_FLOW, inline = "st")
int    stripN  = input.int(8, "", minval = 3, maxval = 20, group = G_FLOW, inline = "st",
     tooltip = "Bars in the strip table, newest on the right: time, volume, delta and delta as a % of volume.")
string stripPos = input.string("Top Right", "Strip position", options = ["Top Right", "Top Center", "Top Left", "Bottom Right", "Bottom Center"], group = G_FLOW)
 
bool   absOn    = input.bool(true, "Absorption marks", group = G_ABS,
     tooltip = "ABS? marks a bar whose delta is at least the set multiple of the average, against the way it closed: heavy selling with a close in the upper half of the bar, or heavy buying with a close in the lower half. It becomes ABS when the next bar does not trade past its low (high). A mark that fails is removed.")
string absScope = input.string("At sweeps", "Where", options = ["At sweeps", "Everywhere"], group = G_ABS,
     tooltip = "At sweeps: only within the set number of bars after C1's high or low, or a swing high or low, is taken.")
float  absMult  = input.float(2.0, "Delta at least (x average)", minval = 1.0, maxval = 10.0, step = 0.25, group = G_ABS)
int    absWin   = input.int(3, "Bars after a sweep", minval = 0, maxval = 20, group = G_ABS)
 
string htfIn   = input.timeframe("", "C1 / C2 candles", group = G_MODEL,
     tooltip = "Empty picks from the chart: under 5m 15m, 5m to 14m 1H, 15m to 59m 4H, 1H and above D.")
string confIn  = input.string("1", "CISD on closes of", options = ["Chart", "1", "2", "3", "5"], group = G_MODEL,
     tooltip = "The candles the CISD is read on. A timeframe at or below the chart's uses the chart candles.")
string gateIn  = input.string("C1 sweep", "CISD needs", options = ["C1 sweep", "C1 or swing sweep"], group = G_MODEL,
     tooltip = "C1 sweep: C2 traded through C1's high or low, and the CISD closes after C2's extreme while C2 or C3 is forming and no candle has traded back through C2's extreme. C1 or swing sweep: a swing high or low taken also arms it, for the set number of bars.")
int    minRun  = input.int(2, "Minimum candles in the run", minval = 1, maxval = 10, group = G_MODEL,
     tooltip = "The opposing run of same-colour candles the CISD closes back through. Its level is the most extreme open in the run.")
string perIn   = input.string("First after the extreme", "CISDs per sweep", options = ["First after the extreme", "Every"], group = G_MODEL,
     tooltip = "First after the extreme: one CISD per side for each sweep, the first close back through a run after the sweep's extreme. A deeper wick that still closes back inside is the same sweep reaching further: its extreme moves there and it can give one CISD after it. Every: each close back through a run while the gate is open.")
int    runAge  = input.int(60, "Run must confirm within (candles)", minval = 5, maxval = 300, group = G_MODEL)
bool   zoneOn  = input.bool(true, "Order block zone", group = G_MODEL,
     tooltip = "From the CISD level to the run's last close: the block the run delivered from.")
bool   eqOn    = input.bool(true, "0.5 line", group = G_MODEL)
int    extBars = input.int(10, "Bars drawn past the CISD", minval = 1, maxval = 100, group = G_MODEL)
 
bool   c1SwpOn = input.bool(true, "C1 sweep lines", group = G_SWP)
bool   swingOn = input.bool(true, "Swing sweeps", group = G_SWP)
int    pivLen  = input.int(3, "Swing pivot length", minval = 1, maxval = 20, group = G_SWP)
int    liqLook = input.int(10, "Swing must be the extreme of (bars)", minval = 0, maxval = 200, group = G_SWP,
     tooltip = "A pivot only counts as liquidity when it is the highest high (lowest low) of this many bars ending at it. 0 accepts every pivot.")
int    swingWin = input.int(20, "Swing sweep arms a CISD for (bars)", minval = 1, maxval = 200, group = G_SWP)
 
string lookIn  = input.string("Clean", "Look", options = ["Clean", "Full"], group = G_SET,
     tooltip = "Clean: the setups shown below, the last four sweeps and six absorption marks. Full: ten of each.")
bool   showLbl = input.bool(true, "Labels", group = G_SET)
bool   pxOn    = input.bool(false, "Prices on names", group = G_SET)
int    TXT     = input.int(10, "Text size", minval = 6, maxval = 14, group = G_SET)
int    setsIn  = input.int(2, "Setups shown", minval = 1, maxval = 10, group = G_SET)
bool   panelOn = input.bool(true, "Panel", group = G_SET, inline = "pn")
string panelPos = input.string("Top Right", "", options = ["Top Right", "Top Center", "Bottom Right"], group = G_SET, inline = "pn")
color  BULL    = input.color(#9585b9, "Bullish", group = G_SET, inline = "dir")
color  BEAR_IN = input.color(#4A4A4A, "Bearish", group = G_SET, inline = "dir",
     tooltip = "The default dark grey turns light grey on a dark chart.")
 
string stripMode = input.string("Under candles", "Strip style", options = ["Under candles", "Table"], group = G_FLOW,
     tooltip = "Under candles: one shaded cell per bar for volume, delta and delta %, lined up under each candle; the numbers show when the chart is zoomed in far enough to fit them. Table: the last bars in a corner table. Under candles needs the delta columns off.")
int    stripBars = input.int(60, "Bars under candles", minval = 10, maxval = 150, group = G_FLOW)
bool   colsOn    = input.bool(false, "Delta columns", group = G_FLOW,
     tooltip = "Draws each bar's delta as a column in the pane. With the columns on, the strip shows as a table.")
bool   cellNums  = input.bool(false, "Numbers in cells", group = G_FLOW,
     tooltip = "Writes volume, delta and delta % in each cell under the candles. They need the chart zoomed in until a bar is wide enough to hold them; zoomed out, the shading alone carries the read.")
 
bool   bubOn   = input.bool(true, "Delta bubbles", group = G_FLOW, inline = "bub",
     tooltip = "A circle on each bar whose delta is at least the set multiple of the average, sized by how far past it: violet for buying, grey for selling. Hover for the numbers.")
float  bubMin  = input.float(2.0, "", minval = 0.5, maxval = 5.0, step = 0.25, group = G_FLOW, inline = "bub")
bool   tintOn  = input.bool(true, "Tint candles by delta", group = G_FLOW,
     tooltip = "Colours a candle by its delta once the delta is past the average: violet for buying, grey for selling, deeper the heavier. A candle that closes up on heavy selling (or down on heavy buying) is absorption showing.")
bool   markOn  = input.bool(true, "Absorption reversal mark", group = G_MODEL,
     tooltip = "Names the sweep extreme when all three steps are in: the sweep, absorption at it, and a CISD whose candle's delta flipped its way.")
 
bool   sdOn    = input.bool(true, "Standard deviation zones", group = G_MODEL,
     tooltip = "From the newest CISD: the run it closed through, projected the CISD's way. Zones at 1.27 to 1.68 and 2.27 to 2.68 of that run, and a line at 3.")
 
color BEAR = DARK and BEAR_IN == #4A4A4A ? #B2B5BE : BEAR_IN
bool  FULL = lookIn == "Full"
bool  STRIP_UC = stripOn and stripMode == "Under candles" and not colsOn
bool  STRIP_TB = stripOn and not STRIP_UC
color ZONE     = color.new(#787B86, 88)
int   KEEP_SETS  = FULL ? 10 : setsIn
int   KEEP_SWP   = FULL ? 10 : 4
int   KEEP_ABS   = FULL ? 10 : 6
 
//@function Resolves a position name.
//@param s (string) The input value.
//@returns (string) A position.* constant.
f_pos(string s) =>
    switch s
        "Top Center"    => position.top_center
        "Top Left"      => position.top_left
        "Bottom Right"  => position.bottom_right
        "Bottom Center" => position.bottom_center
        =>                 position.top_right
 
// == TIMEFRAMES ==
int    CHART_SEC = timeframe.in_seconds()
// Auto keeps about 60 to 120 lower timeframe candles a bar, so the request's history stays long.
string LTF_IN    = ltfIn != "Auto" ? ltfIn : CHART_SEC <= 120 ? "1S" : CHART_SEC <= 300 ? "5S" : CHART_SEC <= 900 ? "15S" : CHART_SEC <= 3600 ? "30S" : "1"
bool   LTF_OK    = timeframe.in_seconds(LTF_IN) < CHART_SEC
string LTF       = LTF_OK ? LTF_IN : timeframe.period
string HTF       = htfIn != "" and timeframe.in_seconds(htfIn) > CHART_SEC ? htfIn : CHART_SEC < 300 ? "15" : CHART_SEC < 900 ? "60" : CHART_SEC < 3600 ? "240" : "D"
bool   CONF_CH   = confIn == "Chart" or timeframe.in_seconds(confIn) <= CHART_SEC
string CONF      = CONF_CH ? timeframe.period : confIn
 
//@function A timeframe as a short tag: 15m, 1H, 4H, 90m, D, 3D, 2W, 12M, 1S.
//@param tf (string) The timeframe.
//@returns (string) The tag.
f_tfTag(string tf) =>
    int s = timeframe.in_seconds(tf)
    // Seconds, days, weeks and months keep their own spelling (3D, 2W, 12M); minutes read as hours only
    // when they divide evenly, so 90 stays 90m.
    bool own = str.endswith(tf, "S") or str.endswith(tf, "D") or str.endswith(tf, "W") or str.endswith(tf, "M")
    own ? tf : s % 3600 == 0 ? str.tostring(s / 3600) + "H" : str.tostring(s / 60) + "m"
 
//@function A volume figure in the strip's short form: 830, 5.1K, 1.2M.
//@param v (float) The volume.
//@returns (string) The text.
f_k(float v) =>
    float a = math.abs(v)
    string sg = v < 0 ? "-" : ""
    na(v) ? "" : a >= 1000000 ? sg + str.tostring(a / 1000000, "#.#") + "M" : a >= 10000 ? sg + str.tostring(math.round(a / 1000)) + "K" : a >= 1000 ? sg + str.tostring(a / 1000, "#.#") + "K" : sg + str.tostring(math.round(a))
 
//@function Clamps a bar-time anchor to the oldest bar the drawing engine can still place.
//@param t (int) The stored origin time.
//@returns (int) t, or the time of the oldest reachable bar.
f_xClamp(int t) =>
    math.max(t, time[math.min(bar_index, MAX_REACH)])
 
// == DELTA ==
[lO, lC, lV] = request.security_lower_tf(syminfo.tickerid, LTF, [open, close, volume], ignore_invalid_timeframe = true)
 
float buyV = 0.0
float sellV = 0.0
int   nIn = LTF_OK ? array.size(lC) : 0
if nIn > 0
    for i = 0 to nIn - 1
        float v = nz(lV.get(i))
        float c = lC.get(i)
        float o = lO.get(i)
        if c > o
            buyV += v
        else if c < o
            sellV += v
        else
            buyV  += v * 0.5
            sellV += v * 0.5
 
float dV    = nIn > 0 ? buyV - sellV : na
float tV    = nIn > 0 ? buyV + sellV : na
float dPct  = nIn > 0 and tV > 0 ? 100.0 * dV / tV : na
float absD  = math.abs(dV)
float avgAbs = ta.sma(absD, avgLen)
float avgV   = ta.sma(tV, avgLen)
float dStr   = na(dV) or na(avgAbs) or avgAbs <= 0 ? na : math.min(absD / (avgAbs * absMult), 1.0)
 
//@function A delta colour shaded by strength: 80 transparency when quiet, 30 at the absorption size.
//@param d (float) The delta.
//@param s (float) Its strength, 0 to 1.
//@returns (color) The shade.
f_dCol(float d, float s) =>
    na(d) ? NOFILL : color.new(d >= 0 ? BULL : BEAR, 80 - 50 * nz(s))
 
plot(colsOn ? dV : na, "Delta", f_dCol(dV, dStr), style = plot.style_columns)
// The strip's three rows sit between 0 and 3 in the pane; these two invisible plots hold that scale.
plot(STRIP_UC ? 0.0 : na, "", NOFILL, editable = false, display = display.pane)
plot(STRIP_UC ? 3.0 : na, "", NOFILL, editable = false, display = display.pane)
float atr14 = ta.atr(14)
 
// Candle tint: strength 0 at the average delta, 1 at the absorption size.
float tintS = na(dV) or na(avgAbs) or avgAbs <= 0 ? na : (absD / avgAbs - 1.0) / math.max(absMult - 1.0, 0.25)
barcolor(tintOn and not na(tintS) and tintS > 0 ? color.new(dV >= 0 ? BULL : BEAR, 60 - 55 * math.min(tintS, 1.0)) : na, title = "Delta tint")
 
// == HTF CANDLES ==
//@type One higher timeframe candle, followed on the chart.
type Cnd
    float o
    float h
    float l
    float c
    int   t
    int   hiT
    int   loT
    int   hiB
    int   loB
 
var array<Cnd> cs = array.new<Cnd>(0)
int htfT = time(HTF)
if not na(htfT)
    if cs.size() == 0 or cs.last().t != htfT
        cs.push(Cnd.new(o = open, h = high, l = low, c = close, t = htfT, hiT = time, loT = time, hiB = bar_index, loB = bar_index))
        while cs.size() > 5
            cs.shift()
    else
        Cnd cd = cs.last()
        if high > cd.h
            cd.h   := high
            cd.hiT := time
            cd.hiB := bar_index
        if low < cd.l
            cd.l   := low
            cd.loT := time
            cd.loB := bar_index
        cd.c := close
 
//@function Whether a candle is a doji: body under a tenth of its range.
//@param cd (Cnd) The candle.
//@returns (bool) True for a doji.
f_thin(Cnd cd) =>
    math.abs(cd.c - cd.o) < (cd.h - cd.l) * 0.1
 
//@function The live C1 / C2 pair on one side. Side 1: C2 traded through C1's low. Side -1: C1's high.
//          C2 is the forming candle, or the one before it while C3 forms, as long as no later candle
//          traded through C2's extreme and the closed C2 closed back inside C1's body or beyond the
//          swept side. A doji C1 gives way to the candle before it.
//@param side (int) 1 bullish, -1 bearish.
//@returns ([int, int, int]) Index of C1, index of C2 (-1 when none) and the phase, 2 or 3.
f_seq(int side) =>
    int r1 = -1
    int r2 = -1
    int ph = 0
    int n = cs.size()
    if n >= 2
        for back = 0 to 1
            int i2 = n - 1 - back
            if r2 < 0 and i2 >= 1
                int i1 = i2 - 1
                if f_thin(cs.get(i1))
                    i1 := i2 >= 2 and not f_thin(cs.get(i2 - 2)) ? i2 - 2 : -1
                if i1 >= 0
                    Cnd c1 = cs.get(i1)
                    Cnd c2 = cs.get(i2)
                    bool swept = side == 1 ? c2.l < c1.l : c2.h > c1.h
                    bool holds = true
                    if back == 1
                        Cnd c3 = cs.get(n - 1)
                        bool closedIn = c2.c < math.max(c1.o, c1.c) and c2.c > math.min(c1.o, c1.c)
                        bool beyond   = side == 1 ? c2.c < c1.l : c2.c > c1.h
                        holds := (closedIn or beyond) and (side == 1 ? c3.l >= c2.l : c3.h <= c2.h)
                    if swept and holds
                        r1 := i1
                        r2 := i2
                        ph := back + 2
    [r1, r2, ph]
 
[bI1, bI2, bPh] = f_seq(1)
[sI1, sI2, sPh] = f_seq(-1)
 
// == SWINGS ==
float pvtHighRaw = ta.pivothigh(high, pivLen, pivLen)
float pvtLowRaw  = ta.pivotlow(low, pivLen, pivLen)
float legHigh    = ta.highest(high, math.max(liqLook, 1))
float legLow     = ta.lowest(low, math.max(liqLook, 1))
float pvtHigh    = na(pvtHighRaw) ? na : (liqLook == 0 or pvtHighRaw >= legHigh[pivLen]) ? pvtHighRaw : na
float pvtLow     = na(pvtLowRaw)  ? na : (liqLook == 0 or pvtLowRaw  <= legLow[pivLen])  ? pvtLowRaw  : na
 
// == DRAWING ==
//@type A drawn CISD order block.
type Set
    bool  bull
    float level
    float far
    int   originB
    bool  spent
    line  ln
    line  eq
    box   zone
    label lb
    label eqLb
    box   sd1
    box   sd2
    line  sd3
    label sdL1
    label sdL2
    label sdL3
    label sdL4
    label sdL5
 
//@type A drawn sweep: the taken level from the bar that made it to the bar that took it, named
//      past the wick of the candle that took it.
type Swp
    line  ln
    label lb
 
var array<Set>   sets   = array.new<Set>(0)
var array<Swp>   swps   = array.new<Swp>(0)
var array<label> absLbs = array.new<label>(0)
var array<label> bubs   = array.new<label>(0)
var array<label> marks  = array.new<label>(0)
const int KEEP_BUB = 300
 
//@function Names a sweep extreme as a full absorption reversal, on the outside of the extreme.
//@param bull (bool) True for a bullish reversal, named below the low.
//@param x (int) Bar index of the extreme.
//@param px (float) The extreme.
//@param tm (int) Bar time of the extreme.
//@param nameT (int) Bar time of that side's newest sweep name.
//@returns (void)
f_mark(bool bull, int x, float px, int tm, int nameT) =>
    if markOn
        // One spacer line per name already on that bar (the sweep name, a absorption mark), so none stack.
        int lines = (tm == nameT ? 1 : 0)
        for lb in absLbs
            if label.get_x(lb) == tm
                lines += 1
        string pad = ""
        for i = 1 to 2
            if i <= lines
                pad += "\n"
        string txt = bull ? pad + "▲ ABSORPTION REVERSAL" : "▼ ABSORPTION REVERSAL" + pad
        marks.push(label.new(math.max(x, bar_index - MAX_REACH), px, txt, xloc = xloc.bar_index,
             style = bull ? label.style_label_up : label.style_label_down, color = NOFILL, textcolor = bull ? BULL : BEAR, size = TXT + 1,
             text_font_family = font.family_monospace, tooltip = "Sweep, absorption at the sweep, CISD with delta flipped its way", force_overlay = true))
        while marks.size() > KEEP_SETS
            label.delete(marks.shift())
 
//@function A transparent monospace label on the chart.
//@param x (int) Bar time, or bar index with byIdx.
//@param y (float) Price.
//@param txt (string) The name.
//@param sty (string) A label.style_* constant.
//@param tip (string) The hover text.
//@param byIdx (bool) True when x is a bar index.
//@returns (label) The label, or na with labels off.
f_lbl(int x, float y, string txt, string sty, string tip, bool byIdx) =>
    showLbl ? label.new(x, y, txt, xloc = byIdx ? xloc.bar_index : xloc.bar_time, style = sty, color = NOFILL, textcolor = INK, size = TXT,
         textalign = sty == label.style_label_left ? text.align_left : text.align_center, tooltip = tip,
         text_font_family = font.family_monospace, force_overlay = true) : label(na)
 
//@function A name with its price when Prices on names is on.
//@param nm (string) The name.
//@param px (float) The price.
//@returns (string) The text.
f_nm(string nm, float px) =>
    pxOn ? nm + " " + str.tostring(px, format.mintick) : nm
 
//@function Deletes a set's standard deviation zones.
//@param s (Set) The set.
//@returns (void)
f_killSd(Set s) =>
    box.delete(s.sd1)
    box.delete(s.sd2)
    line.delete(s.sd3)
    label.delete(s.sdL1)
    label.delete(s.sdL2)
    label.delete(s.sdL3)
    label.delete(s.sdL4)
    label.delete(s.sdL5)
 
//@function Deletes a set's drawings.
//@param s (Set) The set.
//@returns (void)
f_killSet(Set s) =>
    line.delete(s.ln)
    line.delete(s.eq)
    box.delete(s.zone)
    label.delete(s.lb)
    label.delete(s.eqLb)
    f_killSd(s)
 
//@function Draws a taken level, dotted, from the swing that made it to the bar that took it, and
//          names it past that bar's wick: below the low for sellside, above the high for buyside.
//@param fromT (int) Bar time the level was made on.
//@param toT (int) Bar time it was taken on.
//@param px (float) The level.
//@param nm (string) The name.
//@param isLow (bool) True for sellside.
//@param ext (float) The taking candle's low (sellside) or high (buyside).
//@returns (void)
f_swp(int fromT, int toT, float px, string nm, bool isLow, float ext) =>
    line ln = line.new(f_xClamp(fromT), px, toT, px, xloc = xloc.bar_time, color = MUTE, width = 1,
         style = line.style_dotted, force_overlay = true)
    label lb = f_lbl(toT, ext, f_nm(nm, px), isLow ? label.style_label_up : label.style_label_down,
         nm + " " + str.tostring(px, format.mintick) + " taken " + str.format_time(toT, "EEE HH:mm", "America/New_York"), false)
    swps.push(Swp.new(ln = ln, lb = lb))
    while swps.size() > KEEP_SWP
        Swp old = swps.shift()
        line.delete(old.ln)
        label.delete(old.lb)
 
//@function Draws a confirmed CISD order block and banks it.
//@param bull (bool) True for a bullish CISD.
//@param level (float) The CISD level: the run's most extreme open.
//@param far (float) The run's last close: the block's far edge.
//@param originB (int) Bar index of the candle that carries the level.
//@param tip (string) The hover text.
//@param full (bool) True when all three steps are in: sweep, absorption, delta flip on the CISD candle.
//@returns (void)
f_set(bool bull, float level, float far, int originB, string tip, bool full) =>
    color dc = bull ? BULL : BEAR
    // Ahead of price by bar count: a future time in a market closure is squashed onto the last bar.
    int x1 = math.max(originB, bar_index - MAX_REACH)
    int x2 = bar_index + extBars
    float mid = math.avg(level, far)
    Set s = Set.new(bull = bull, level = level, far = far, originB = originB, spent = false)
    if zoneOn
        s.zone := box.new(x1, math.max(level, far), x2, math.min(level, far), xloc = xloc.bar_index,
             border_color = NOFILL, border_width = 0, bgcolor = full ? color.new(dc, 80) : ZONE, force_overlay = true)
    // A block too thin to hold two names keeps only the CISD name.
    if eqOn and math.abs(level - far) / 2 >= nz(atr14)
        s.eq := line.new(x1, mid, x2, mid, xloc = xloc.bar_index, color = MUTE, width = 1, style = line.style_dotted, force_overlay = true)
        s.eqLb := f_lbl(x2, mid, f_nm("0.5", mid), label.style_label_left, "0.5 " + str.tostring(mid, format.mintick), true)
    s.ln := line.new(x1, level, x2, level, xloc = xloc.bar_index, color = dc, width = 1, style = line.style_solid, force_overlay = true)
    s.lb := f_lbl(x2, level, f_nm("CISD", level), label.style_label_left, tip, true)
    float unit = math.abs(level - far)
    if sdOn and unit > 0
        for old in sets
            f_killSd(old)
        float dir = bull ? 1.0 : -1.0
        float a1 = level + dir * unit * 1.27
        float b1 = level + dir * unit * 1.68
        float a2 = level + dir * unit * 2.27
        float b2 = level + dir * unit * 2.68
        float l3 = level + dir * unit * 3.0
        int sx1 = bar_index
        s.sd1 := box.new(sx1, math.max(a1, b1), x2, math.min(a1, b1), xloc = xloc.bar_index, border_color = NOFILL, border_width = 0,
             bgcolor = color.new(#787B86, 94), force_overlay = true)
        s.sd2 := box.new(sx1, math.max(a2, b2), x2, math.min(a2, b2), xloc = xloc.bar_index, border_color = NOFILL, border_width = 0,
             bgcolor = color.new(#787B86, 94), force_overlay = true)
        s.sd3 := line.new(sx1, l3, x2, l3, xloc = xloc.bar_index, color = MUTE, width = 1, style = line.style_dotted, force_overlay = true)
        s.sdL1 := f_lbl(x2, a1, f_nm("1.27", a1), label.style_label_left, "STDV 1.27 " + str.tostring(a1, format.mintick), true)
        s.sdL2 := f_lbl(x2, b1, f_nm("1.68", b1), label.style_label_left, "STDV 1.68 " + str.tostring(b1, format.mintick), true)
        s.sdL3 := f_lbl(x2, a2, f_nm("2.27", a2), label.style_label_left, "STDV 2.27 " + str.tostring(a2, format.mintick), true)
        s.sdL4 := f_lbl(x2, b2, f_nm("2.68", b2), label.style_label_left, "STDV 2.68 " + str.tostring(b2, format.mintick), true)
        s.sdL5 := f_lbl(x2, l3, f_nm("3", l3), label.style_label_left, "STDV 3 " + str.tostring(l3, format.mintick), true)
    sets.push(s)
    while sets.size() > KEEP_SETS
        f_killSet(sets.shift())
 
// == STATE ==
// Swing sweeps: the last raid on each side, its wick and whether a close through the level ended it.
var float swingHigh = na
var int   swingHighT = 0
var float swingLow = na
var int   swingLowT = 0
// The bar a close went through each swing; a swing closed through and not reclaimed by the next bar is retired.
var int   swingLowBrk = -1
var int   swingHighBrk = -1
var int   sslSwB = -1
var int   sslSwT = na
var float sslSwLvl = na
var float sslSwWick = na
var int   bslSwB = -1
var int   bslSwT = na
var float bslSwLvl = na
var float bslSwWick = na
// The drawn line and name of each side's live swing raid, moved when the raid reaches further.
var Swp   sslSwCur = na
var Swp   bslSwCur = na
// The last bar any sellside / buyside was taken on, for the absorption scope.
var int   sslB = -1
var int   bslB = -1
// The C2 a sweep line was drawn for, per side, so each draws once and its end follows C2's extreme.
var int   bSwpKey = na
var int   sSwpKey = na
var Swp   bSwpCur = na
// The bar each side's newest sweep name sits on.
var int   sslNameT = na
// The bar C2 first traded through C1's low / high, per side.
var int   bTakeT = na
var int   sTakeT = na
var int   bslNameT = na
var Swp   sSwpCur = na
// The CISD candles: the one forming, and whether it has been read.
var float cfO = na
var float cfC = na
var int   cfT = na
var int   cfB = na
var float cfD = na
var bool  cfDone = true
//@type The runs of same-colour CISD candles: each side's most extreme open, its last close, where it began.
type Runs
    bool  prevDn  = false
    bool  prevUp  = false
    int   dnN     = 0
    float dnTop   = na
    float dnFar   = na
    int   dnB     = na
    int   dnStart = na
    int   upN     = 0
    float upBot   = na
    float upFar   = na
    int   upB     = na
    int   upStart = na
    int   idx     = 0
var Runs rs = Runs.new()
// Absorption: the pending mark per side and whether one was confirmed since that side's last sweep.
var bool  pendB   = false
var label pAbsB   = na
var float pAbsBLo = na
var bool  pendS   = false
var label pAbsS   = na
var float pAbsSHi = na
var bool  absSeenB = false
var bool  absSeenS = false
// The sweep extreme bar each side's last CISD fired on, so one fires per sweep.
var int   bUsed = -1
var int   sUsed = -1
// The newest set per side, for the panel.
var Set   lastSet = na
var float lastCfD = na
var bool  lastAbs = false
var bool  lastFlip = false
 
bool bullCisd = false
bool bearCisd = false
bool fullBull = false
bool fullBear = false
bool absBull  = false
bool absBear  = false
 
// The CISD candle rolls on its own clock; on the chart timeframe every chart bar is one.
int  cfOpen = time(CONF)
bool cfRoll = CONF_CH or na(cfT) or cfOpen != cfT
 
//@function Reads one sealed CISD candle: grows the runs and fires a CISD on a close back through one.
//@param o (float) Open.
//@param c (float) Close.
//@param b (int) Bar index of its first chart bar.
//@returns ([int, float, float, int]) Direction fired (0 none), level, far edge, origin bar index.
f_readCf(float o, float c, int b) =>
    int   fired = 0
    float lvl = na
    float far = na
    int   oT = na
    rs.idx += 1
    if c > o and not na(rs.dnTop) and rs.dnN >= minRun and c > rs.dnTop and rs.idx - rs.dnStart <= runAge
        fired := 1
        lvl   := rs.dnTop
        far   := rs.dnFar
        oT    := rs.dnB
        rs.dnTop := na
        rs.dnN   := 0
    if c < o and not na(rs.upBot) and rs.upN >= minRun and c < rs.upBot and rs.idx - rs.upStart <= runAge
        fired := -1
        lvl   := rs.upBot
        far   := rs.upFar
        oT    := rs.upB
        rs.upBot := na
        rs.upN   := 0
    if c < o
        if not rs.prevDn or na(rs.dnTop)
            rs.dnN     := 1
            rs.dnTop   := o
            rs.dnFar   := c
            rs.dnB     := b
            rs.dnStart := rs.idx
        else
            rs.dnN += 1
            if o > rs.dnTop
                rs.dnTop := o
                rs.dnB   := b
            rs.dnFar := math.min(rs.dnFar, c)
    if c > o
        if not rs.prevUp or na(rs.upBot)
            rs.upN     := 1
            rs.upBot   := o
            rs.upFar   := c
            rs.upB     := b
            rs.upStart := rs.idx
        else
            rs.upN += 1
            if o < rs.upBot
                rs.upBot := o
                rs.upB   := b
            rs.upFar := math.max(rs.upFar, c)
    rs.prevDn := c < o
    rs.prevUp := c > o
    [fired, lvl, far, oT]
 
//@function The absorption mark's hover text, built only when a mark is drawn.
//@returns (string) The text.
f_absTip() =>
    "Delta " + f_k(dV) + " (" + str.tostring(dPct, "#.#") + "%) against the average of " + f_k(avgAbs)
 
// == READ ==
int   fDir = 0
float fLvl = na
float fFar = na
int   fOT  = na
float fD   = na
 
// A candle that rolled before it was read (a missing chart bar at its close) is read on the roll.
if cfRoll and not cfDone and not CONF_CH
    [a1, a2, a3, a4] = f_readCf(cfO, cfC, cfB)
    fDir := a1
    fLvl := a2
    fFar := a3
    fOT  := a4
    fD   := cfD
    cfDone := true
if cfRoll
    cfO := open
    cfC := close
    cfT := CONF_CH ? time : cfOpen
    cfB := bar_index
    cfD := dV
    cfDone := false
else
    cfC := close
    cfD := na(cfD) ? dV : na(dV) ? cfD : cfD + dV
 
if barstate.isconfirmed
 
    // -- Swing raids, tested against the swing as it stood before this bar's pivot. --
    // A close through a swing leaves one bar to reclaim it; after that the liquidity is taken, not swept.
    if not na(swingLow) and swingLowBrk >= 0 and bar_index - swingLowBrk > 1
        swingLow := na
    if not na(swingHigh) and swingHighBrk >= 0 and bar_index - swingHighBrk > 1
        swingHigh := na
    // A deeper wick that still closes back inside is the same raid reaching further: its extreme moves there.
    if sslSwB >= 0 and sslSwB < bar_index and low < sslSwWick and close > sslSwLvl
        sslSwB    := bar_index
        sslSwT    := time
        sslSwWick := low
        sslB      := bar_index
        if swingOn and not na(sslSwCur)
            line.set_x2(sslSwCur.ln, time)
            label.set_xy(sslSwCur.lb, time, low)
            sslNameT := time
    if bslSwB >= 0 and bslSwB < bar_index and high > bslSwWick and close < bslSwLvl
        bslSwB    := bar_index
        bslSwT    := time
        bslSwWick := high
        bslB      := bar_index
        if swingOn and not na(bslSwCur)
            line.set_x2(bslSwCur.ln, time)
            label.set_xy(bslSwCur.lb, time, high)
            bslNameT := time
    if not na(swingLow) and low < swingLow and close > swingLow
        sslSwB    := bar_index
        sslSwT    := time
        sslSwLvl  := swingLow
        sslSwWick := low
        sslB      := bar_index
        absSeenB  := false
        sslSwCur  := na
        if swingOn
            f_swp(swingLowT, time, swingLow, "SSL", true, low)
            sslSwCur := swps.last()
            sslNameT := time
        swingLow := na
    if not na(swingHigh) and high > swingHigh and close < swingHigh
        bslSwB    := bar_index
        bslSwT    := time
        bslSwLvl  := swingHigh
        bslSwWick := high
        bslB      := bar_index
        absSeenS  := false
        bslSwCur  := na
        if swingOn
            f_swp(swingHighT, time, swingHigh, "BSL", false, high)
            bslSwCur := swps.last()
            bslNameT := time
        swingHigh := na
    if not na(swingLow) and close < swingLow and swingLowBrk < 0
        swingLowBrk := bar_index
    if not na(swingHigh) and close > swingHigh and swingHighBrk < 0
        swingHighBrk := bar_index
    if not na(pvtLow)
        swingLow    := pvtLow
        swingLowT   := time[pivLen]
        swingLowBrk := -1
    if not na(pvtHigh)
        swingHigh    := pvtHigh
        swingHighT   := time[pivLen]
        swingHighBrk := -1
    // A close through a raided swing ends the raid.
    if sslSwB >= 0 and close < sslSwLvl
        sslSwB := -1
    if bslSwB >= 0 and close > bslSwLvl
        bslSwB := -1
 
    // -- C1 sweeps. One line per C2, its right end following C2's extreme. --
    if bI2 >= 0
        Cnd c1 = cs.get(bI1)
        Cnd c2 = cs.get(bI2)
        if na(bSwpKey) or bSwpKey != c2.t
            bTakeT := na
        if low < c1.l and time >= c2.t
            sslB := bar_index
            bTakeT := na(bTakeT) ? time : bTakeT
        if na(bSwpKey) or bSwpKey != c2.t
            bSwpKey  := c2.t
            absSeenB := false
            if c1SwpOn
                // The newer sweep traded through the older C1 level: only the newest keeps a line and name.
                if not na(bSwpCur)
                    line.delete(bSwpCur.ln)
                    label.delete(bSwpCur.lb)
                f_swp(c1.loT, c2.loT, c1.l, "C1 SSL", true, c2.l)
                bSwpCur := swps.last()
        else if c1SwpOn and not na(bSwpCur)
            line.set_x2(bSwpCur.ln, c2.loT)
            label.set_xy(bSwpCur.lb, c2.loT, c2.l)
        if c1SwpOn and not na(bSwpCur)
            label.set_tooltip(bSwpCur.lb, "C1 SSL " + str.tostring(c1.l, format.mintick) + " taken " + str.format_time(nz(bTakeT, c2.loT), "EEE HH:mm", "America/New_York") +
                 "\nC2 low " + str.tostring(c2.l, format.mintick) + " at " + str.format_time(c2.loT, "EEE HH:mm", "America/New_York"))
        sslNameT := c1SwpOn ? c2.loT : sslNameT
    if sI2 >= 0
        Cnd c1 = cs.get(sI1)
        Cnd c2 = cs.get(sI2)
        if na(sSwpKey) or sSwpKey != c2.t
            sTakeT := na
        if high > c1.h and time >= c2.t
            bslB := bar_index
            sTakeT := na(sTakeT) ? time : sTakeT
        if na(sSwpKey) or sSwpKey != c2.t
            sSwpKey  := c2.t
            absSeenS := false
            if c1SwpOn
                if not na(sSwpCur)
                    line.delete(sSwpCur.ln)
                    label.delete(sSwpCur.lb)
                f_swp(c1.hiT, c2.hiT, c1.h, "C1 BSL", false, c2.h)
                sSwpCur := swps.last()
        else if c1SwpOn and not na(sSwpCur)
            line.set_x2(sSwpCur.ln, c2.hiT)
            label.set_xy(sSwpCur.lb, c2.hiT, c2.h)
        if c1SwpOn and not na(sSwpCur)
            label.set_tooltip(sSwpCur.lb, "C1 BSL " + str.tostring(c1.h, format.mintick) + " taken " + str.format_time(nz(sTakeT, c2.hiT), "EEE HH:mm", "America/New_York") +
                 "\nC2 high " + str.tostring(c2.h, format.mintick) + " at " + str.format_time(c2.hiT, "EEE HH:mm", "America/New_York"))
        bslNameT := c1SwpOn ? c2.hiT : bslNameT
 
    // -- Absorption. A pending mark is decided by the bar after it. --
    if pendB
        if low >= pAbsBLo
            if not na(pAbsB)
                label.set_text(pAbsB, (label.get_x(pAbsB) == sslNameT ? "\n" : "") + "▲ ABS")
                absLbs.push(pAbsB)
            absSeenB := true
            absBull  := true
        else
            label.delete(pAbsB)
        pendB := false
    if pendS
        if high <= pAbsSHi
            if not na(pAbsS)
                label.set_text(pAbsS, "▼ ABS" + (label.get_x(pAbsS) == bslNameT ? "\n" : ""))
                absLbs.push(pAbsS)
            absSeenS := true
            absBear  := true
        else
            label.delete(pAbsS)
        pendS := false
    bool strong = absOn and not na(dV) and not na(avgAbs) and avgAbs > 0 and absD >= absMult * avgAbs
    bool nearSsl = absScope == "Everywhere" or (sslB >= 0 and bar_index - sslB <= absWin)
    bool nearBsl = absScope == "Everywhere" or (bslB >= 0 and bar_index - bslB <= absWin)
    if strong and dV < 0 and close >= hl2 and nearSsl
        pendB   := true
        pAbsBLo := low
        pAbsB   := f_lbl(time, low, (time == sslNameT ? "\n" : "") + "▲ ABS?", label.style_label_up, "Selling absorbed: " + f_absTip(), false)
    if strong and dV > 0 and close <= hl2 and nearBsl
        pendS   := true
        pAbsSHi := high
        pAbsS   := f_lbl(time, high, "▼ ABS?" + (time == bslNameT ? "\n" : ""), label.style_label_down, "Buying absorbed: " + f_absTip(), false)
    while absLbs.size() > KEEP_ABS
        label.delete(absLbs.shift())
 
    // -- Delta bubbles: at the close, sized by delta against its average. --
    float bubR = na(dV) or na(avgAbs) or avgAbs <= 0 ? na : absD / avgAbs
    if bubOn and not na(bubR) and bubR >= bubMin
        string bsz = bubR >= bubMin * 2.5 ? size.large : bubR >= bubMin * 2 ? size.normal : bubR >= bubMin * 1.5 ? size.small : size.tiny
        bubs.push(label.new(time, close, "", xloc = xloc.bar_time, style = label.style_circle, color = color.new(dV >= 0 ? BULL : BEAR, 45),
             size = bsz, tooltip = (dV >= 0 ? "Buying " : "Selling ") + f_k(dV) + " (" + str.tostring(dPct, "#") + "%), " + str.tostring(bubR, "#.#") + "x the average",
             force_overlay = true))
        while bubs.size() > KEEP_BUB
            label.delete(bubs.shift())
 
    // -- The CISD candle closes on this bar: read it. --
    if not cfDone and (CONF_CH or time_close == time_close(CONF))
        [a1, a2, a3, a4] = f_readCf(cfO, cfC, cfB)
        // A candle read late on this bar's roll keeps its CISD unless this one fires too.
        if a1 != 0 or fDir == 0
            fDir := a1
            fLvl := a2
            fFar := a3
            fOT  := a4
            fD   := cfD
        cfDone := true
 
    // -- Gate: after C2's extreme while C2 or C3 forms, or a live swing raid. --
    bool every = perIn == "Every"
    // Each sweep is keyed by the bar of its extreme, so one CISD fires per sweep and a deeper extreme is a new key.
    int  bKey = bI2 >= 0 and bar_index > cs.get(bI2).loB ? cs.get(bI2).loB : gateIn != "C1 sweep" and sslSwB >= 0 and bar_index - sslSwB <= swingWin ? sslSwB : -1
    int  sKey = sI2 >= 0 and bar_index > cs.get(sI2).hiB ? cs.get(sI2).hiB : gateIn != "C1 sweep" and bslSwB >= 0 and bar_index - bslSwB <= swingWin ? bslSwB : -1
    bool bGate = bKey >= 0 and (every or bKey != bUsed)
    bool sGate = sKey >= 0 and (every or sKey != sUsed)
    if fDir == 1 and bGate
        bullCisd := true
        bUsed    := bKey
        bool flip = not na(fD) and fD > 0
        fullBull := absSeenB and flip
        string src = bI2 >= 0 ? "C" + str.tostring(bPh) + " after a C1 sweep (" + f_tfTag(HTF) + ")" : "after a swing sweep"
        string tip = "▲ CISD " + str.tostring(fLvl, format.mintick) + ", " + f_tfTag(CONF) + " close, " + src +
             "\nAbsorption at the sweep " + (absSeenB ? "✓" : "×") + "\nDelta on the CISD candle " + (na(fD) ? "no data" : f_k(fD)) + (flip ? " ✓" : " ×") +
             (fullBull ? "\nAbsorption reversal: all three steps" : "")
        f_set(true, fLvl, fFar, fOT, tip, fullBull)
        if fullBull
            f_mark(true, bI2 >= 0 ? cs.get(bI2).loB : sslSwB, bI2 >= 0 ? cs.get(bI2).l : sslSwWick, bI2 >= 0 ? cs.get(bI2).loT : sslSwT, sslNameT)
        lastSet  := sets.last()
        lastCfD  := fD
        lastAbs  := absSeenB
        lastFlip := flip
    if fDir == -1 and sGate
        bearCisd := true
        sUsed    := sKey
        bool flip = not na(fD) and fD < 0
        fullBear := absSeenS and flip
        string src = sI2 >= 0 ? "C" + str.tostring(sPh) + " after a C1 sweep (" + f_tfTag(HTF) + ")" : "after a swing sweep"
        string tip = "▼ CISD " + str.tostring(fLvl, format.mintick) + ", " + f_tfTag(CONF) + " close, " + src +
             "\nAbsorption at the sweep " + (absSeenS ? "✓" : "×") + "\nDelta on the CISD candle " + (na(fD) ? "no data" : f_k(fD)) + (flip ? " ✓" : " ×") +
             (fullBear ? "\nAbsorption reversal: all three steps" : "")
        f_set(false, fLvl, fFar, fOT, tip, fullBear)
        if fullBear
            f_mark(false, sI2 >= 0 ? cs.get(sI2).hiB : bslSwB, sI2 >= 0 ? cs.get(sI2).h : bslSwWick, sI2 >= 0 ? cs.get(sI2).hiT : bslSwT, bslNameT)
        lastSet  := sets.last()
        lastCfD  := fD
        lastAbs  := absSeenS
        lastFlip := flip
 
    // -- A close back through a CISD level ends the set: the zone goes, the line turns dotted. --
    if sets.size() > 0
        for i = sets.size() - 1 to 0
            Set s = sets.get(i)
            if not s.spent and (s.bull ? close < s.level : close > s.level)
                s.spent := true
                box.delete(s.zone)
                line.delete(s.eq)
                label.delete(s.eqLb)
                line.set_style(s.ln, line.style_dotted)
                line.set_color(s.ln, MUTE)
 
// == STRIP ==
// The last closed bars are kept as they close; the forming bar is read live.
var array<int>   hT = array.new<int>(0)
var array<float> hV = array.new<float>(0)
var array<float> hD = array.new<float>(0)
var array<float> hP = array.new<float>(0)
var array<float> hS = array.new<float>(0)
var array<float> hA = array.new<float>(0)
if barstate.isconfirmed
    hT.push(time)
    hV.push(tV)
    hD.push(dV)
    hP.push(dPct)
    hS.push(dStr)
    hA.push(avgV)
    while hT.size() > 20
        hT.shift()
        hV.shift()
        hD.shift()
        hP.shift()
        hS.shift()
        hA.shift()
 
var table strip = table.new(f_pos(stripPos), 21, 4, border_width = 0, frame_width = 0)
if barstate.islast and STRIP_TB
    table.clear(strip, 0, 0, 20, 3)
    int nClosed = hT.size()
    bool liveBar = not barstate.isconfirmed
    int nCols = math.min(stripN, nClosed + (liveBar ? 1 : 0))
    table.cell(strip, 0, 0, f_tfTag(timeframe.period), text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(strip, 0, 1, "V", text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(strip, 0, 2, "ΔV", text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(strip, 0, 3, "Δ%", text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace)
    if nCols > 0
        for j = 0 to nCols - 1
            // Column j counts back from the newest: the live bar first when there is one.
            int back = nCols - 1 - j
            bool isLive = liveBar and back == 0
            int k = nClosed - 1 - (liveBar ? back - 1 : back)
            int   tt = isLive ? time : hT.get(k)
            float vv = isLive ? tV : hV.get(k)
            float dd = isLive ? dV : hD.get(k)
            float pp = isLive ? dPct : hP.get(k)
            float ss = isLive ? dStr : hS.get(k)
            float aa = isLive ? avgV : hA.get(k)
            float vShade = na(vv) or na(aa) or aa <= 0 ? 0.0 : math.min(vv / (aa * 2), 1.0)
            color vBg = na(vv) ? NOFILL : color.new(#787B86, 90 - 30 * vShade)
            string tipTxt = str.format_time(tt, "HH:mm", "America/New_York") + (isLive ? " forming" : "") +
                 "\nVolume " + (na(vv) ? "no data" : str.tostring(vv, "#")) + "\nDelta " + (na(dd) ? "no data" : str.tostring(dd, "#"))
            table.cell(strip, j + 1, 0, str.format_time(tt, "HH:mm", "America/New_York") + (isLive ? "?" : ""), text_color = INK, text_size = TXT, text_font_family = font.family_monospace, tooltip = tipTxt)
            table.cell(strip, j + 1, 1, f_k(vv), text_color = INK, text_size = TXT, bgcolor = vBg, text_font_family = font.family_monospace, tooltip = tipTxt)
            table.cell(strip, j + 1, 2, f_k(dd), text_color = INK, text_size = TXT, bgcolor = f_dCol(dd, ss), text_font_family = font.family_monospace, tooltip = tipTxt)
            table.cell(strip, j + 1, 3, na(pp) ? "" : str.tostring(math.round(pp)), text_color = INK, text_size = TXT, bgcolor = f_dCol(dd, ss), text_font_family = font.family_monospace, tooltip = tipTxt)
 
// -- Under the candles: one cell per bar and row, centred on its bar. --
//@function The text colour for a cell: white on a strong shade, black on the light grey selling shade of a dark chart, ink otherwise.
//@param s (float) The shade's strength, 0 to 1.
//@param d (float) The cell's delta; 0 for the volume row.
//@returns (color) The text colour.
f_cellInk(float s, float d) =>
    nz(s) > 0.6 ? (DARK and nz(d) < 0 and BEAR_IN == #4A4A4A ? #000000 : #FFFFFF) : INK
 
//@function Writes one strip cell's text, shade and hover text.
//@param bx (box) The cell.
//@param txt (string) The text.
//@param bg (color) The shade.
//@param s (float) The shade's strength, 0 to 1.
//@param d (float) The cell's delta; 0 for the volume row.
//@returns (void)
f_cell(box bx, string txt, color bg, float s, float d) =>
    box.set_text(bx, cellNums ? txt : "")
    box.set_bgcolor(bx, bg)
    box.set_text_color(bx, f_cellInk(s, d))
 
var array<box>   cellV = array.new<box>(0)
var array<box>   cellD = array.new<box>(0)
var array<box>   cellP = array.new<box>(0)
var array<label> rowLbs = array.new<label>(0)
int HALF_MS = CHART_SEC * 500
if STRIP_UC and bar_index > last_bar_index - stripBars
    // A cell made on a live bar's first tick is rolled back on the next, so each run checks the newest cell is this bar's.
    if cellV.size() == 0 or box.get_left(cellV.last()) != time - HALF_MS
        int l = time - HALF_MS
        int r = time + HALF_MS
        cellV.push(box.new(l, 2.95, r, 2.05, xloc = xloc.bar_time, border_width = 0, border_color = NOFILL, bgcolor = NOFILL,
             text_size = size.tiny, text_font_family = font.family_monospace))
        cellD.push(box.new(l, 1.95, r, 1.05, xloc = xloc.bar_time, border_width = 0, border_color = NOFILL, bgcolor = NOFILL,
             text_size = size.tiny, text_font_family = font.family_monospace))
        cellP.push(box.new(l, 0.95, r, 0.05, xloc = xloc.bar_time, border_width = 0, border_color = NOFILL, bgcolor = NOFILL,
             text_size = size.tiny, text_font_family = font.family_monospace))
        while cellV.size() > stripBars
            box.delete(cellV.shift())
            box.delete(cellD.shift())
            box.delete(cellP.shift())
    float vShadeNow = na(tV) or na(avgV) or avgV <= 0 ? 0.0 : math.min(tV / (avgV * 2), 1.0)
    f_cell(cellV.last(), f_k(tV), na(tV) ? NOFILL : color.new(#787B86, 90 - 40 * vShadeNow), vShadeNow * 0.5, 0.0)
    f_cell(cellD.last(), f_k(dV), f_dCol(dV, dStr), dStr, dV)
    f_cell(cellP.last(), na(dPct) ? "" : str.tostring(math.round(dPct)), f_dCol(dV, dStr), dStr, dV)
if barstate.islast and STRIP_UC
    if rowLbs.size() == 0
        rowLbs.push(label.new(bar_index, 2.5, "V", style = label.style_label_left, color = NOFILL, textcolor = INK, size = TXT, text_font_family = font.family_monospace))
        rowLbs.push(label.new(bar_index, 1.5, "ΔV", style = label.style_label_left, color = NOFILL, textcolor = INK, size = TXT, text_font_family = font.family_monospace))
        rowLbs.push(label.new(bar_index, 0.5, "Δ%", style = label.style_label_left, color = NOFILL, textcolor = INK, size = TXT, text_font_family = font.family_monospace))
    for lb in rowLbs
        label.set_x(lb, bar_index + 1)
 
// == PANEL ==
// How far back the delta reaches: the first bar the lower timeframe returned candles for.
var int firstDataT = na
if nIn > 0 and na(firstDataT)
    firstDataT := time
 
var table panel = table.new(f_pos(panelPos), 3, 6, border_width = 0, frame_width = 0, force_overlay = true)
 
//@function Writes one panel row.
//@param r (int) Row.
//@param a (string) Label.
//@param b (string) Value.
//@param c (string) Verdict, in the pill.
//@param tip (string) Hover text.
//@returns (void)
f_row(int r, string a, string b, string c, string tip) =>
    table.cell(panel, 0, r, a, text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    table.cell(panel, 1, r, b, text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    table.cell(panel, 2, r, c, text_color = INK, text_size = TXT, text_halign = text.align_center, bgcolor = c == "" ? NOFILL : PILL, text_font_family = font.family_monospace, tooltip = tip)
 
if barstate.islast and panelOn
    table.clear(panel, 0, 0, 2, 5)
    table.cell(panel, 0, 0, "Flow CISD", text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(panel, 1, 0, f_tfTag(HTF) + " · " + f_tfTag(CONF), text_color = INK, text_size = TXT, text_halign = text.align_left, text_font_family = font.family_monospace,
         tooltip = "C1 / C2 candles " + f_tfTag(HTF) + ", CISD read on " + f_tfTag(CONF) + " closes")
    int r = 1
    // The model: the live C2 or C3 on each side, bullish first.
    string mTxt = bI2 >= 0 and sI2 >= 0 ? "▲ C" + str.tostring(bPh) + "  ▼ C" + str.tostring(sPh) : bI2 >= 0 ? "▲ C" + str.tostring(bPh) + " · C1 low taken" : sI2 >= 0 ? "▼ C" + str.tostring(sPh) + " · C1 high taken" : "No C1 sweep"
    string mTip = bI2 >= 0 ? "C1 low " + str.tostring(cs.get(bI1).l, format.mintick) + ", C2 low " + str.tostring(cs.get(bI2).l, format.mintick) : sI2 >= 0 ? "C1 high " + str.tostring(cs.get(sI1).h, format.mintick) + ", C2 high " + str.tostring(cs.get(sI2).h, format.mintick) : ""
    f_row(r, "Model", mTxt, bI2 >= 0 or sI2 >= 0 ? "C" + str.tostring(bI2 >= 0 ? bPh : sPh) : "", mTip)
    r += 1
    if not na(lastSet)
        f_row(r, "CISD", (lastSet.bull ? "▲ " : "▼ ") + str.tostring(lastSet.level, format.mintick), lastSet.spent ? "×" : "✓",
             "Delta on the CISD candle " + (na(lastCfD) ? "no data" : f_k(lastCfD)) + "\n✓ holding, × closed back through")
        r += 1
        f_row(r, "Flow", "Δ " + (na(lastCfD) ? "no data" : f_k(lastCfD)) + (lastFlip ? " ✓" : " ×"), lastAbs ? "ABS ✓" : "ABS ×",
             "Delta on the CISD candle, ✓ when it flipped the CISD's way\nAbsorption confirmed between the sweep and the CISD: " + (lastAbs ? "yes" : "no"))
        r += 1
        int steps = 1 + (lastAbs ? 1 : 0) + (lastFlip ? 1 : 0)
        f_row(r, "Setup", steps == 3 ? "Absorption reversal" : str.tostring(steps) + " of 3", steps == 3 ? "✓" : "×",
             "Sweep, absorption at the sweep, CISD with the delta flipped its way")
        r += 1
    // The data row says whether the lower timeframe is loading, how many candles a bar and since when.
    string dTxt = not LTF_OK ? f_tfTag(LTF_IN) + " is not below the chart" : nIn > 0 ? f_tfTag(LTF) + " · " + str.tostring(nIn) + " a bar" : f_tfTag(LTF) + " not loading"
    string dTip = na(firstDataT) ? "No lower timeframe candles on any bar" : "Delta from " + str.format_time(firstDataT, "dd MMM HH:mm", "America/New_York") + " New York; bars before that have none"
    f_row(r, "Data", dTxt, nIn > 0 ? "✓" : "×", dTip)
 
// == ALERTS ==
alertcondition(bullCisd, "Bullish CISD", "Bullish CISD after a sweep on {{ticker}}")
alertcondition(bearCisd, "Bearish CISD", "Bearish CISD after a sweep on {{ticker}}")
alertcondition(absBull, "Selling absorbed", "Selling absorbed at a sweep on {{ticker}}")
alertcondition(absBear, "Buying absorbed", "Buying absorbed at a sweep on {{ticker}}")
alertcondition(fullBull, "Absorption reversal, bullish", "Bullish absorption reversal on {{ticker}}: sweep, absorption, CISD with delta flipped up")
alertcondition(fullBear, "Absorption reversal, bearish", "Bearish absorption reversal on {{ticker}}: sweep, absorption, CISD with delta flipped down")

← 返回列表