Wick C.E Stack+ (M1D)

mayb1dayy · study · 813 行 · 点赞 171 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © mayb1dayy
// Wick C.E Stack+ (M1D) — the last completed higher-timeframe candle read as a PD array, and the
// nearest higher-timeframe fair value gap graded in eighths.
//
// The stack: each wick of the candle gets its consequent encroachment (the wick's midpoint), and a
// third line sits halfway between the two, the C.E of the two C.Es. The three lines are carried onto
// the lower timeframes as one turning area.
//
// The ladder: the nearest higher-timeframe gap between candle one's wick and candle three's wick is
// split into eighths, 0.5 in green. A close back through the gap's far edge marks it inverted, and the
// rungs turn orange: a inversion FVG that price can climb or fall through one rung at a time. A later
// close back through its other edge retires it.
//
// The wick into a FVG: when a gap forms inside the wick of a candle a few candles to its left, with
// that candle's body outside the gap, the wick's C.E is drawn from the wick candle through the gap
// and on past price.
//
// The targeted candle: the candle whose wick is being worked (the wick left of the newest FVG, or the
// last closed candle when there is none) is drawn beside price with its timeframe above it. The wick
// carries ticks at 25 / 50 / 75 and a dot at the deepest point price has reached into it, with the %.
//
// Every value is taken from confirmed higher-timeframe candles, so nothing repaints.
 
//@version=6
indicator('Wick C.E Stack+ (M1D)', 'Wick CE+', overlay = true, max_lines_count = 100, max_labels_count = 100, max_boxes_count = 10)
 
// ── Inputs ──────────────────────────────────────────────────────────────────────
string G_SRC = 'Candle'
string htf      = input.timeframe('D', 'Timeframe', group = G_SRC, tooltip = 'The candle the stack is read from, and the timeframe the ladder gaps are found on. Daily is the read it was built for; weekly works the same way.')
 
string G_STK = 'Wick C.E stack'
bool   showStk  = input.bool(true, 'Show the stack', group = G_STK, tooltip = 'Upper wick C.E = midpoint of the body top and the high. Lower wick C.E = midpoint of the low and the body bottom. Stack C.E = midpoint of those two.')
color  stkCol   = input.color(#7246CE, 'Wick C.E / Stack C.E', inline = 's', group = G_STK)
color  midCol   = input.color(#2962FF, '', inline = 's', group = G_STK)
 
string G_LAD = 'Ladder (gap in eighths)'
bool   showLad  = input.bool(true, 'Show the ladder', group = G_LAD, tooltip = 'The higher-timeframe fair value gap nearest to price, split into eighths from candle three\'s wick to candle one\'s wick.')
color  rungCol  = input.color(#4A4A4A, 'Rungs / 0.5', inline = 'l', group = G_LAD)
color  ceCol    = input.color(#4CAF50, '', inline = 'l', group = G_LAD)
int    gapKeep  = input.int(10, 'Gaps remembered', minval = 1, maxval = 30, group = G_LAD, tooltip = 'How many of the latest gaps are kept to choose the nearest from.')
 
string G_LOOK = 'Look'
bool   showLbl  = input.bool(true, 'Labels', group = G_LOOK)
bool   pxOnLbl  = input.bool(false, 'Prices on names', group = G_LOOK)
int    TXT      = input.int(10, 'Text size', minval = 6, maxval = 14, group = G_LOOK)
int    runway   = input.int(10, 'Runway (bars past price)', minval = 2, maxval = 60, group = G_LOOK)
 
string G_TBL = 'Tables'
bool   showTbl  = input.bool(true, 'Read table', group = G_TBL)
string tblPos   = input.string('Top Right', 'Position', options = ['Top Right', 'Middle Right', 'Bottom Right', 'Top Left', 'Bottom Left'], group = G_TBL)
 
string G_FW = 'Wick into a FVG'
bool   showFw   = input.bool(false, 'Show wick C.E through the FVG', group = G_FW, tooltip = 'When a FVG forms, the candles to the left of its first candle are checked for a wick the gap fits into, with that candle\'s body outside the gap. The nearest one\'s C.E is drawn from the wick candle through the gap and on past price. Covers a gap that fits inside the wick and a wick that fits inside the gap.')
int    fwBack   = input.int(8, 'Wick up to this many candles left of the FVG', minval = 1, maxval = 20, group = G_FW)
int    fwKeep   = input.int(2, 'Kept on the chart', minval = 1, maxval = 5, group = G_FW)
color  fwCol    = input.color(#7246CE, 'Colour', group = G_FW)
 
string G_TG = 'Targeted candle'
bool   showTg   = input.bool(true, 'Show the targeted candle', group = G_TG, tooltip = 'Draws the candle whose wick is being worked beside price: the wick candle left of the newest FVG when one is kept, otherwise the last closed candle. Its timeframe sits above it.')
int    tgOff    = input.int(10, 'Candle offset (bars past price)', minval = 2, maxval = 40, group = G_TG)
bool   showDot  = input.bool(true, 'Depth dot and %', group = G_TG, tooltip = 'A dot on price at the candle that made the deepest point into the wick, just outside its own wick, and the % past the end of the drawn wick. 0% is the tip of the wick, 100% is the body. The dot only moves further into the wick from the side price came in. No % shows until price has traded into the wick.')
bool   showTk   = input.bool(true, 'Wick ticks 25 / 50 / 75', group = G_TG, tooltip = 'Short dotted ticks across the drawn wick. 50 is the wick C.E.')
color  tgBull   = input.color(#7246CE, 'Candle up / down', inline = 'tg', group = G_TG)
color  tgBear   = input.color(#4A4A4A, '', inline = 'tg', group = G_TG)
bool   ladAll   = input.bool(false, 'Name every ladder rung', group = G_LAD, tooltip = 'Off: only the gap\'s 0, C.E and 1 are named, so the name column stays readable. On: all nine rungs are named.')
bool   mobOn    = input.bool(false, 'Mobile Mode', group = G_TBL, inline = 'mob')
string mobMode  = input.string('Mode 1', '', options = ['Mode 1', 'Mode 2'], group = G_TBL, inline = 'mob', tooltip = 'For phones: the read table moves to the bottom right and shows each row\'s name and verdict only, and every table and name gets one size: Mode 1 tiny, Mode 2 small. The Position and Text size settings are ignored while this is on; a table that is off stays off. Turn it off to go back to your settings.')
bool   PHONE    = mobOn
int    SZ       = PHONE ? (mobMode == 'Mode 1' ? 8 : 10) : TXT
 
// ── Tokens ──────────────────────────────────────────────────────────────────────
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 PILL   = color.new(#787B86, 75)
color NOFILL = color.new(#FFFFFF, 100)
const color INV = #FF9800
 
// ── Higher-timeframe candles (confirmed only) ─────────────────────────────────
// [1] is the last closed candle; for a gap it is candle three, [3] is candle one.
[cT, cO, cH, cL, cC, aT, aH, aL] = request.security(syminfo.tickerid, htf, [time[1], open[1], high[1], low[1], close[1], time[3], high[3], low[3]], lookahead = barmerge.lookahead_on)
 
// ── Gaps ────────────────────────────────────────────────────────────────────────
type Gap
    float top
    float bot
    int   t1
    bool  bear
    bool  inverted = false
    int   idx = 0
 
// A wick that reached into a earlier FVG, and its C.E.
type Hit
    float y
    int   t1
    int   tw
    float gTop
    float gBot
    bool  upper
    float tip
    float edge
    int   back
    float o = na
    float h = na
    float l = na
    float c = na
    bool  fromTip = true
    float depth = 0.0
    int   deepT = na
    float deepY = na
 
var array<Gap> gaps = array.new<Gap>()
var array<Hit> hits = array.new<Hit>()
var int hIdx = 0
// The last closed higher-timeframe candles, oldest first.
var array<int>   hT = array.new<int>()
var array<float> hO = array.new<float>()
var array<float> hH = array.new<float>()
var array<float> hL = array.new<float>()
var array<float> hC = array.new<float>()
 
//@function Price as text at the symbol's tick.
//@param p (float) The price.
//@returns (string)
px(float p) =>
    str.tostring(math.round_to_mintick(p), format.mintick)
 
bool newHtf = ta.change(cT) != 0 and not na(cT)
 
if newHtf
    hIdx += 1
    // Inversion is a close of the closed candle through the gap's far edge. A inverted gap leaves the
    // ladder when a later close goes back through its other edge: the inversion has failed.
    if gaps.size() > 0
        for i = gaps.size() - 1 to 0
            Gap g = gaps.get(i)
            if not g.inverted
                if g.bear and cC > g.top
                    g.inverted := true
                else if not g.bear and cC < g.bot
                    g.inverted := true
            else if (g.bear and cC < g.bot) or (not g.bear and cC > g.top)
                gaps.remove(i)
    hT.push(cT)
    hO.push(cO)
    hH.push(cH)
    hL.push(cL)
    hC.push(cC)
    while hT.size() > 30
        hT.shift()
        hO.shift()
        hH.shift()
        hL.shift()
        hC.shift()
    Gap ng = na
    if not na(aL) and aL > cH
        ng := Gap.new(top = aL, bot = cH, t1 = aT, bear = true, idx = hIdx)
    else if not na(aH) and aH < cL
        ng := Gap.new(top = cL, bot = aH, t1 = aT, bear = false, idx = hIdx)
    if not na(ng)
        gaps.push(ng)
        // Look left of the gap's first candle for the nearest wick the gap fits into, body outside it.
        int n  = hT.size()
        int c1 = n - 3
        if c1 >= 1
            bool found = false
            for j = c1 - 1 to math.max(0, c1 - fwBack)
                if not found
                    float wH = hH.get(j)
                    float wL = hL.get(j)
                    float wTop = math.max(hO.get(j), hC.get(j))
                    float wBot = math.min(hO.get(j), hC.get(j))
                    if wH > ng.bot and wTop <= ng.bot and wH > wTop
                        float yU = math.round_to_mintick((wH + wTop) / 2)
                        hits.push(Hit.new(y = yU, t1 = hT.get(j), tw = hT.get(j), gTop = ng.top, gBot = ng.bot, upper = true, tip = wH, edge = wTop, back = c1 - j, o = hO.get(j), h = wH, l = wL, c = hC.get(j), fromTip = cC > yU))
                        found := true
                    else if wL < ng.top and wBot >= ng.top and wL < wBot
                        float yL = math.round_to_mintick((wL + wBot) / 2)
                        hits.push(Hit.new(y = yL, t1 = hT.get(j), tw = hT.get(j), gTop = ng.top, gBot = ng.bot, upper = false, tip = wL, edge = wBot, back = c1 - j, o = hO.get(j), h = wH, l = wL, c = hC.get(j), fromTip = cC < yL))
                        found := true
    while hits.size() > fwKeep
        hits.shift()
    while gaps.size() > gapKeep
        gaps.shift()
 
// ── Stack values ────────────────────────────────────────────────────────────────
float bodyTop = math.max(cO, cC)
float bodyBot = math.min(cO, cC)
float upCE    = math.round_to_mintick((cH + bodyTop) / 2)
float loCE    = math.round_to_mintick((cL + bodyBot) / 2)
float stackCE = math.round_to_mintick((upCE + loCE) / 2)
 
// ── Depth into a wick ───────────────────────────────────────────────────────────
//@function How far this bar reached into a wick, kept at the deepest reading so far.
//@param prev (float) The deepest share so far, 0 to 1.
//@param fromP (float) The end of the wick price came in from.
//@param toP (float) The far end of the wick.
//@returns (float) The share of the wick traded through, 0 to 1.
f_depth(float prev, float fromP, float toP) =>
    float len = math.abs(toP - fromP)
    float p = len > 0 ? (toP > fromP ? high - fromP : fromP - low) / len : 0.0
    math.max(prev, math.min(1.0, math.max(0.0, p)))
 
//@function The deepest point as a share of the wick counted from its tip, as text.
//@param d (float) The share traded through from the end price came in from, 0 to 1.
//@param cameFromTip (bool) True when price came in past the tip.
//@returns (string) The % from the tip, empty until price has traded into the wick.
f_pctS(float d, bool cameFromTip) =>
    na(d) or d <= 0 ? '' : str.tostring((cameFromTip ? d : 1 - d) * 100, '0') + '%'
 
// Each kept wick, from the bar after its FVG closed.
if hits.size() > 0
    for ht in hits
        float hFrom = ht.fromTip ? ht.tip : ht.edge
        float hTo   = ht.fromTip ? ht.edge : ht.tip
        float hNew  = f_depth(ht.depth, hFrom, hTo)
        if hNew > ht.depth
            ht.depth := hNew
            ht.deepT := time
            ht.deepY := hTo > hFrom ? high : low
 
// The last closed candle's two wicks, from that candle's close. The bar that made each deepest
// point is kept with its own high or low.
var float dUp   = 0.0
var float dLo   = 0.0
var bool  upTip = false
var bool  loTip = false
var int   dUpT  = na
var float dUpY  = na
var int   dLoT  = na
var float dLoY  = na
if newHtf
    dUp   := 0.0
    dLo   := 0.0
    upTip := open > upCE
    loTip := open < loCE
    dUpT  := na
    dUpY  := na
    dLoT  := na
    dLoY  := na
if not na(cH)
    float nUp = f_depth(dUp, upTip ? cH : bodyTop, upTip ? bodyTop : cH)
    if nUp > dUp
        dUp  := nUp
        dUpT := time
        dUpY := upTip ? low : high
    float nLo = f_depth(dLo, loTip ? cL : bodyBot, loTip ? bodyBot : cL)
    if nLo > dLo
        dLo  := nLo
        dLoT := time
        dLoY := loTip ? high : low
 
// Time left in the live higher-timeframe candle.
int    remSec = math.max(0, int((time_close(htf) - timenow) / 1000))
string timer  = str.format('{0,number,00}:{1,number,00}:{2,number,00}', int(remSec / 3600), int(remSec % 3600 / 60), remSec % 60)
 
// ── Drawing ─────────────────────────────────────────────────────────────────────
const int RUNGS = 9
var array<line>  stkLines = array.new<line>()
var array<label> stkLbls  = array.new<label>()
var array<line>  ladLines = array.new<line>()
var array<label> ladLbls  = array.new<label>()
var array<line>  fwLines  = array.new<line>()
var array<label> fwLbls   = array.new<label>()
// Each line's run past price, placed by bar count.
var array<line>  stkRuns  = array.new<line>()
var array<line>  ladRuns  = array.new<line>()
var array<line>  fwRuns   = array.new<line>()
// The targeted candle beside price.
var box          tgBody   = na
var line         tgWickUp = na
var line         tgWickLo = na
var label        tgTag    = na
var label        tgDot    = na
var label        tgPct    = na
var array<line>  tgTicks  = array.new<line>()
// The left edge of the stack's zone on a daily read.
var line         stkDiv   = na
 
if barstate.isfirst
    for i = 0 to 2
        stkLines.push(line.new(na, na, na, na, xloc = xloc.bar_time, width = 1))
        stkRuns.push(line.new(na, na, na, na, width = 1))
        stkLbls.push(label.new(na, na, '', style = label.style_label_left, color = NOFILL, size = SZ, text_font_family = font.family_monospace))
    for i = 0 to RUNGS - 1
        ladLines.push(line.new(na, na, na, na, xloc = xloc.bar_time, width = 1))
        ladRuns.push(line.new(na, na, na, na, width = 1))
        ladLbls.push(label.new(na, na, '', style = label.style_label_left, color = NOFILL, size = SZ, text_font_family = font.family_monospace))
    for i = 0 to 4
        fwLines.push(line.new(na, na, na, na, xloc = xloc.bar_time, width = 1))
        fwRuns.push(line.new(na, na, na, na, width = 1))
        fwLbls.push(label.new(na, na, '', style = label.style_label_left, color = NOFILL, size = SZ, text_font_family = font.family_monospace))
    tgBody   := box.new(na, na, na, na, border_width = 1, border_style = line.style_solid)
    tgWickUp := line.new(na, na, na, na, width = 1)
    tgWickLo := line.new(na, na, na, na, width = 1)
    tgTag    := label.new(na, na, '', style = label.style_label_down, color = NOFILL, size = SZ, text_font_family = font.family_monospace)
    tgDot    := label.new(na, na, '', xloc = xloc.bar_time, style = label.style_label_down, color = NOFILL, size = SZ, text_font_family = font.family_monospace)
    tgPct    := label.new(na, na, '', style = label.style_label_up, color = NOFILL, size = SZ, text_font_family = font.family_monospace)
    stkDiv   := line.new(na, na, na, na, xloc = xloc.bar_time, width = 1, style = line.style_dotted)
    for i = 0 to 2
        tgTicks.push(line.new(na, na, na, na, width = 1, style = line.style_dotted))
 
// The drawn candle is three bars wide; the stack's names start at one bar past it. The ladder
// stops short of the candle.
const int TG_W = 2
const int LAD_RUN = 1
int xCandle = bar_index + tgOff
int nameBar = bar_index + (showTg ? math.max(runway, tgOff + TG_W + 6) : runway)
 
//@function Places one line and its name: the line runs to the live bar, its run carries it on to where the name sits.
//@param ln (line) The line, from its origin to the live bar.
//@param rn (line) Its run past price.
//@param lb (label) Its name.
//@param x1 (int) Start time.
//@param xe (int) The bar the run ends on, where the name starts.
//@param y (float) The price.
//@param col (color) Line colour.
//@param sty (string) Line style.
//@param nm (string) The name, empty for none.
//@param tip (string) The tooltip.
f_place(line ln, line rn, label lb, int x1, int xe, float y, color col, string sty, string nm, string tip) =>
    line.set_xy1(ln, x1, y)
    line.set_xy2(ln, time, y)
    line.set_color(ln, col)
    line.set_style(ln, sty)
    line.set_xy1(rn, bar_index, y)
    line.set_xy2(rn, xe, y)
    line.set_color(rn, col)
    line.set_style(rn, sty)
    label.set_xy(lb, xe, y)
    label.set_text(lb, showLbl and nm != '' ? (pxOnLbl ? nm + ' ' + px(y) : nm) : '')
    label.set_textcolor(lb, INK)
    label.set_tooltip(lb, tip)
    true
 
//@function Hides one line, its run and its name.
//@param ln (line) The line.
//@param rn (line) Its run past price.
//@param lb (label) Its name.
f_hide(line ln, line rn, label lb) =>
    line.set_xy1(ln, na, na)
    line.set_xy2(ln, na, na)
    line.set_xy1(rn, na, na)
    line.set_xy2(rn, na, na)
    label.set_xy(lb, na, na)
    label.set_text(lb, '')
    true
 
//@function Distance from a price to a wick: zero when the price is inside it.
//@param p (float) The price.
//@param a (float) One end of the wick.
//@param b (float) The other end.
//@returns (float)
f_dist(float p, float a, float b) =>
    float hi = math.max(a, b)
    float lo = math.min(a, b)
    p > hi ? p - hi : p < lo ? lo - p : 0.0
 
//@function The nearest gap to a price: zero distance when the price is inside it.
//@param p (float) The price.
//@returns (int) Index into gaps, or -1 when none.
f_nearest(float p) =>
    int   best = -1
    float bestD = na
    if gaps.size() > 0
        for i = 0 to gaps.size() - 1
            Gap g = gaps.get(i)
            float d = p > g.top ? p - g.top : p < g.bot ? g.bot - p : 0.0
            if na(bestD) or d <= bestD
                best  := i
                bestD := d
    best
 
int   gi      = f_nearest(close)
Gap   gNow    = gi >= 0 ? gaps.get(gi) : na
int    htfSec = timeframe.in_seconds(htf)
string tfTag  = htfSec >= 86400 ? (htf == '1D' ? 'D' : htf == '1W' ? 'W' : htf == '1M' ? 'M' : htf) : htfSec % 3600 == 0 ? str.tostring(htfSec / 3600) + 'H' : str.tostring(htfSec / 60) + 'm'
string wickNm = tfTag + ' Wick C.E'
 
// The targeted wick: the wick price is inside, otherwise the nearest one. The last closed candle's
// wicks are read first, then the wick left of the newest FVG.
float tgTip   = na
float tgEdge  = na
float tgDepth = na
bool  tgFrom  = true
bool  tgUpper = true
float tgO     = na
float tgH     = na
float tgL     = na
float tgC     = na
int   tgT     = na
bool  tgIsFw  = false
int   tgDeepT = na
float tgDeepY = na
// The % shown past each wick's end of the drawn candle, empty for none.
string tgUpS  = ''
string tgLoS  = ''
 
if barstate.islast
    float bestD = na
    if showStk and not na(cH)
        if cH > bodyTop
            bestD   := f_dist(close, cH, bodyTop)
            tgTip   := cH
            tgEdge  := bodyTop
            tgDepth := dUp
            tgFrom  := upTip
            tgUpper := true
            tgDeepT := dUpT
            tgDeepY := dUpY
            tgUpS   := f_pctS(dUp, upTip)
        if cL < bodyBot
            tgLoS := f_pctS(dLo, loTip)
            if na(bestD) or f_dist(close, cL, bodyBot) < bestD
                bestD   := f_dist(close, cL, bodyBot)
                tgTip   := cL
                tgEdge  := bodyBot
                tgDepth := dLo
                tgFrom  := loTip
                tgUpper := false
                tgDeepT := dLoT
                tgDeepY := dLoY
        if not na(bestD)
            tgO := cO
            tgH := cH
            tgL := cL
            tgC := cC
            tgT := cT
    if showFw and hits.size() > 0
        Hit hw = hits.get(hits.size() - 1)
        if na(bestD) or f_dist(close, hw.tip, hw.edge) < bestD
            tgTip   := hw.tip
            tgEdge  := hw.edge
            tgDepth := hw.depth
            tgFrom  := hw.fromTip
            tgUpper := hw.upper
            tgDeepT := hw.deepT
            tgDeepY := hw.deepY
            tgUpS   := hw.upper ? f_pctS(hw.depth, hw.fromTip) : ''
            tgLoS   := hw.upper ? '' : f_pctS(hw.depth, hw.fromTip)
            tgO     := hw.o
            tgH     := hw.h
            tgL     := hw.l
            tgC     := hw.c
            tgT     := hw.tw
            tgIsFw  := true
 
float  tgFromP = tgFrom ? tgTip : tgEdge
float  tgToP   = tgFrom ? tgEdge : tgTip
float  tgDeep  = math.round_to_mintick(tgFromP + (tgToP - tgFromP) * tgDepth)
string tgPctS  = f_pctS(tgDepth, tgFrom)
 
if barstate.islast
    // Wick C.E names already in the column, so one price carries one name.
    array<float> named = array.new<float>()
 
    // The stack.
    if showStk and not na(cH)
        string base = tfTag + ' candle ' + str.format_time(cT, 'EEE dd MMM', 'America/New_York') + ': H ' + px(cH) + ', L ' + px(cL) + ', body ' + px(bodyBot) + ' - ' + px(bodyTop)
        f_place(stkLines.get(0), stkRuns.get(0), stkLbls.get(0), cT, nameBar, upCE, stkCol, line.style_dotted, wickNm, 'Upper wick C.E ' + px(upCE) + ' = (' + px(cH) + ' + ' + px(bodyTop) + ') / 2\n' + base)
        f_place(stkLines.get(1), stkRuns.get(1), stkLbls.get(1), cT, nameBar, stackCE, midCol, line.style_dashed, tfTag + ' Stack C.E', 'C.E of the two C.Es ' + px(stackCE) + ' = (' + px(upCE) + ' + ' + px(loCE) + ') / 2\n' + base)
        f_place(stkLines.get(2), stkRuns.get(2), stkLbls.get(2), cT, nameBar, loCE, stkCol, line.style_dotted, loCE == upCE ? '' : wickNm, 'Lower wick C.E ' + px(loCE) + ' = (' + px(cL) + ' + ' + px(bodyBot) + ') / 2\n' + base)
        named.push(upCE)
        named.push(loCE)
    else
        for i = 0 to 2
            f_hide(stkLines.get(i), stkRuns.get(i), stkLbls.get(i))
 
    // On a daily read, a divider at the candle's own 18:00 open, where the two wick C.E lines start,
    // cut to those two lines: it closes the zone's left side.
    if showStk and not na(cH) and htfSec == 86400
        line.set_xy1(stkDiv, cT, loCE)
        line.set_xy2(stkDiv, cT, upCE)
        line.set_color(stkDiv, stkCol)
    else
        line.set_xy1(stkDiv, na, na)
        line.set_xy2(stkDiv, na, na)
 
    // The ladder.
    if showLad and not na(gNow)
        float span = gNow.top - gNow.bot
        string side = gNow.bear ? '▼' : '▲'
        for k = 0 to RUNGS - 1
            float f = k / 8.0
            // Graded from candle three's wick (0) to candle one's wick (1).
            float y = math.round_to_mintick(gNow.bear ? gNow.bot + span * f : gNow.top - span * f)
            bool  ce = k == 4
            color col = ce ? ceCol : gNow.inverted ? INV : rungCol
            string nm = ce ? 'FVG C.E' : ladAll ? str.tostring(f, '0.000') : k == 0 ? 'FVG 0' : k == RUNGS - 1 ? 'FVG 1' : ''
            string tip = side + ' ' + tfTag + ' FVG ' + px(gNow.bot) + ' - ' + px(gNow.top) + ' (' + px(span) + ' pts, ' + px(span / 8) + ' a step)\nLevel ' + str.tostring(f, '0.000') + ' = ' + px(y) + (gNow.inverted ? '\nInverted: closed back through the far edge' : '')
            f_place(ladLines.get(k), ladRuns.get(k), ladLbls.get(k), gNow.t1, bar_index + LAD_RUN, y, col, line.style_solid, nm, tip)
    else
        for k = 0 to RUNGS - 1
            f_hide(ladLines.get(k), ladRuns.get(k), ladLbls.get(k))
 
    // Wick C.Es drawn through the FVG they reached into. A price already named keeps its one name.
    for i = 0 to 4
        int n = hits.size()
        if showFw and i < n
            Hit hw = hits.get(n - 1 - i)
            string wk = hw.upper ? 'upper' : 'lower'
            string tip = tfTag + ' ' + wk + ' wick of ' + str.format_time(hw.tw, 'EEE dd MMM HH:mm', 'America/New_York') + ': the FVG ' + px(hw.gBot) + ' - ' + px(hw.gTop) + ' formed ' + str.tostring(hw.back) + (hw.back == 1 ? ' candle' : ' candles') + ' to its right, inside the wick\'s range\nWick C.E ' + px(hw.y) + ' = (' + px(hw.tip) + ' + ' + px(hw.edge) + ') / 2'
            f_place(fwLines.get(i), fwRuns.get(i), fwLbls.get(i), hw.t1, nameBar, hw.y, fwCol, line.style_solid, named.includes(hw.y) ? '' : wickNm, tip)
            named.push(hw.y)
        else
            f_hide(fwLines.get(i), fwRuns.get(i), fwLbls.get(i))
 
    // The targeted candle beside price: body, two wicks, timeframe above, ticks and the depth dot.
    if showTg and not na(tgTip)
        float bT = math.max(tgO, tgC)
        float bB = math.min(tgO, tgC)
        string wk = tgUpper ? 'upper' : 'lower'
        box.set_lefttop(tgBody, xCandle, bT)
        box.set_rightbottom(tgBody, xCandle + TG_W, bB)
        box.set_bgcolor(tgBody, tgC >= tgO ? tgBull : tgBear)
        box.set_border_color(tgBody, INK)
        line.set_xy1(tgWickUp, xCandle + 1, bT)
        line.set_xy2(tgWickUp, xCandle + 1, tgH)
        line.set_color(tgWickUp, INK)
        line.set_xy1(tgWickLo, xCandle + 1, bB)
        line.set_xy2(tgWickLo, xCandle + 1, tgL)
        line.set_color(tgWickLo, INK)
        // Above the high: the timeframe with the time left in the live candle, then the upper wick's %.
        // Below the low: the lower wick's %.
        string dTip = 'Deepest ' + px(tgDeep) + ' into the ' + wk + ' wick, counted from the tip ' + px(tgTip) + ' to the body ' + px(tgEdge) + '\n' + px(math.abs(tgDeep - tgTip)) + ' / ' + px(math.abs(tgEdge - tgTip)) + ' = ' + tgPctS
        bool pctOn = showDot and showLbl
        label.set_xy(tgTag, xCandle + 1, tgH)
        label.set_text(tgTag, tfTag + ' ' + timer + (pctOn and tgUpS != '' ? '\n' + tgUpS : ''))
        label.set_textcolor(tgTag, INK)
        label.set_xy(tgPct, xCandle + 1, tgL)
        label.set_text(tgPct, pctOn ? tgLoS : '')
        label.set_textcolor(tgPct, INK)
        label.set_tooltip(tgPct, tgUpper ? 'How deep price has traded into the lower wick' : dTip)
        label.set_tooltip(tgTag, (tgUpper ? dTip + '\n' : '') + tfTag + ' candle ' + str.format_time(tgT, 'EEE dd MMM HH:mm', 'America/New_York') + ': O ' + px(tgO) + ', H ' + px(tgH) + ', L ' + px(tgL) + ', C ' + px(tgC) + '\nTargeted: its ' + wk + ' wick ' + px(tgEdge) + ' - ' + px(tgTip) + (tgIsFw ? ', the wick left of the newest FVG' : ', the last closed candle'))
        for k = 0 to 2
            line tk = tgTicks.get(k)
            if showTk
                float yk = math.round_to_mintick(tgTip + (tgEdge - tgTip) * (k + 1) / 4.0)
                line.set_xy1(tk, xCandle, yk)
                line.set_xy2(tk, xCandle + TG_W, yk)
                line.set_color(tk, k == 1 ? stkCol : MUTE)
            else
                line.set_xy1(tk, na, na)
                line.set_xy2(tk, na, na)
        // The dot sits on price, at the candle that made the deepest point, just outside its own wick.
        if showDot and not na(tgDeepT)
            bool upReach = tgToP > tgFromP
            label.set_xy(tgDot, tgDeepT, tgDeepY)
            label.set_style(tgDot, upReach ? label.style_label_down : label.style_label_up)
            label.set_text(tgDot, showLbl ? (upReach ? tgPctS + '\n●' : '●\n' + tgPctS) : '●')
            label.set_textcolor(tgDot, INK)
            label.set_tooltip(tgDot, dTip)
        else
            label.set_xy(tgDot, na, na)
            label.set_text(tgDot, '')
    else
        box.set_lefttop(tgBody, na, na)
        box.set_rightbottom(tgBody, na, na)
        line.set_xy1(tgWickUp, na, na)
        line.set_xy2(tgWickUp, na, na)
        line.set_xy1(tgWickLo, na, na)
        line.set_xy2(tgWickLo, na, na)
        label.set_xy(tgTag, na, na)
        label.set_text(tgTag, '')
        label.set_xy(tgDot, na, na)
        label.set_text(tgDot, '')
        label.set_xy(tgPct, na, na)
        label.set_text(tgPct, '')
        for k = 0 to 2
            line.set_xy1(tgTicks.get(k), na, na)
            line.set_xy2(tgTicks.get(k), na, na)
 
// ── Read table ──────────────────────────────────────────────────────────────────
//@function Table position from its name.
//@param s (string) The position name.
//@returns (string)
f_pos(string s) =>
    switch s
        'Middle Right' => position.middle_right
        'Bottom Right' => position.bottom_right
        'Top Left'     => position.top_left
        'Bottom Left'  => position.bottom_left
        =>                position.top_right
 
var table tb = showTbl ? table.new(PHONE ? position.bottom_right : f_pos(tblPos), 3, 6, border_width = 0, frame_width = 0) : na
 
//@function One read-panel row: label, value, verdict.
//@param r (int) Row.
//@param name (string) Label.
//@param val (string) Value.
//@param pill (string) Verdict, empty for none.
//@param tip (string) Tooltip.
f_row(int r, string name, string val, string pill, string tip) =>
    table.cell(tb, 0, r, name, text_color = INK, text_size = SZ, text_halign = text.align_left, text_font_family = font.family_monospace)
    table.cell(tb, 1, r, PHONE ? '' : val, text_color = INK, text_size = SZ, text_halign = text.align_left, text_font_family = font.family_monospace, tooltip = tip)
    table.cell(tb, 2, r, pill, text_color = INK, bgcolor = pill == '' ? na : PILL, text_size = SZ, text_halign = text.align_center, text_font_family = font.family_monospace, tooltip = tip)
    true
 
if barstate.islast and showTbl and not na(cH)
    table.clear(tb, 0, 0, 2, 5)
    int r = 0
    f_row(r, 'Wick C.E Stack+', '', '', '')
    table.cell(tb, 2, r, tfTag, text_color = INK, text_size = SZ, text_halign = text.align_center, text_font_family = font.family_monospace)
    r += 1
    string where = close > upCE ? 'Above' : close < loCE ? 'Below' : 'Inside'
    f_row(r, 'Stack', px(upCE) + ' / ' + px(stackCE) + ' / ' + px(loCE), where, 'Upper wick C.E / C.E of the two C.Es / lower wick C.E, from the ' + str.format_time(cT, 'EEE dd MMM', 'America/New_York') + ' candle')
    r += 1
    if not na(gNow)
        float span = gNow.top - gNow.bot
        float pos = gNow.bear ? (close - gNow.bot) / span : (gNow.top - close) / span
        string at = pos < 0 ? 'Under' : pos > 1 ? 'Over' : str.tostring(math.floor(pos * 8)) + '/8'
        f_row(r, 'Ladder', (gNow.bear ? '▼ ' : '▲ ') + px(gNow.bot) + ' - ' + px(gNow.top), at, 'Nearest ' + tfTag + ' FVG, ' + px(span) + ' pts, ' + px(span / 8) + ' a step. Position counted from candle three\'s wick (0/8) to candle one\'s wick (8/8).')
        r += 1
        f_row(r, 'Inverted', gNow.inverted ? '✓' : '×', '', 'A close back through the far edge of the gap')
        r += 1
    if showFw and hits.size() > 0
        Hit h = hits.get(hits.size() - 1)
        f_row(r, 'FVG wick', (h.upper ? '▲ ' : '▼ ') + px(h.y), close > h.y ? 'Above' : 'Below', 'Latest wick C.E drawn through the FVG ' + px(h.gBot) + ' - ' + px(h.gTop))
        r += 1
    if showTg and not na(tgTip)
        f_row(r, 'Target', (tgUpper ? '▲ ' : '▼ ') + tfTag + ' wick ' + str.format_time(tgT, 'EEE dd MMM', 'America/New_York'), tgPctS, 'The ' + (tgUpper ? 'upper' : 'lower') + ' wick ' + px(tgEdge) + ' - ' + px(tgTip) + '. Deepest ' + px(tgDeep) + ', counted from the tip: ' + px(math.abs(tgDeep - tgTip)) + ' / ' + px(math.abs(tgEdge - tgTip)) + ' = ' + tgPctS)
 
// ── Alerts ──────────────────────────────────────────────────────────────────────
bool hitStack = barstate.isconfirmed and not na(stackCE) and high >= stackCE and low <= stackCE
bool hitLadCE = barstate.isconfirmed and not na(gNow) and high >= (gNow.top + gNow.bot) / 2 and low <= (gNow.top + gNow.bot) / 2
alertcondition(hitStack, 'Stack C.E traded', 'Wick C.E Stack+: {{ticker}} traded the C.E of the two C.Es')
alertcondition(hitLadCE, 'Ladder 0.5 traded', 'Wick C.E Stack+: {{ticker}} traded the ladder 0.5')
float lastFw = hits.size() > 0 ? hits.get(hits.size() - 1).y : na
bool hitFw = barstate.isconfirmed and showFw and not na(lastFw) and high >= lastFw and low <= lastFw
alertcondition(hitFw, 'FVG wick C.E traded', 'Wick C.E Stack+: {{ticker}} traded the wick C.E drawn through a FVG')
 
// == NAME LANE ==
// Every name past the live bar is checked once on the last bar. A name stays at the right end of its own line unless
// it would print over another name on the same row; then it steps right to just past that name, and its line runs on
// to meet it. Names on one price share one name, joined with " / ". A name with no line of its own, and every MSS or
// CISD name, never moves. Widths are the name's own characters at its text size, read against the bar spacing below.
const string G_NL = "Names"
bool  nlOn    = input.bool(true, "Keep names apart", group = G_NL, tooltip = "On: a name that would print over another steps right along its own line to just past it, and names on one price share one name. Off: every name sits where it was drawn.")
float nlBarPx = input.float(6.0, "Bar spacing on screen (pixels)", minval = 1.0, maxval = 50.0, step = 0.5, group = G_NL, tooltip = "How wide one bar is on your chart. A name's width in bars is its characters times the character width at its text size, divided by this. 6 is the chart's default spacing; zoomed in, raise it.")
 
// Names placed by bar index join the lane too when this is true
const bool NL_IDX = true
 
float nlAtrD = request.security(syminfo.tickerid, "D", ta.atr(14)[1], lookahead = barmerge.lookahead_on)
 
// What the last pass changed, so the next pass starts from each name as its owner left it
var array<label>  nlLb  = array.new<label>()
var array<int>    nlX0  = array.new<int>()
var array<int>    nlX1  = array.new<int>()
var array<string> nlT0  = array.new<string>()
var array<string> nlT1  = array.new<string>()
var array<line>   nlLn  = array.new<line>()
var array<int>    nlLx0 = array.new<int>()
var array<int>    nlLx1 = array.new<int>()
 
//@function One monospace character's width in pixels at a label text size
//@param sz (string) A size.* constant
//@returns (float) Pixels
f_nlCharPx(string sz) =>
    float px = sz == size.tiny ? 8.0 : sz == size.small ? 10.0 : sz == size.normal ? 12.0 : sz == size.large ? 15.0 : sz == size.huge ? 20.0 : 10.0
    px * 0.6
 
//@function One monospace character's width in pixels at a label text size
//@param pt (int) Text size in points
//@returns (float) Pixels
f_nlCharPx(int pt) =>
    pt * 4.0 / 3.0 * 0.6
 
//@function True for a name that holds its place: MSS and CISD names sit at their own line's end
//@param t (string) The name
//@returns (bool) Fixed
f_nlFixed(string t) =>
    str.contains(t, "MSS") or str.contains(t, "CISD")
 
//@function The flat line that ends at a name, or na when the name has no line of its own
//@param x (int) The name's x
//@param y (float) The name's price
//@returns (line) The line
f_nlLine(int x, float y) =>
    line hit = na
    for ln in line.all
        if na(hit) and line.get_x2(ln) == x and math.abs(line.get_y2(ln) - y) < syminfo.mintick / 2 and math.abs(line.get_y1(ln) - y) < syminfo.mintick / 2
            hit := ln
    hit
 
if barstate.islast
    // undo the last pass wherever the owner has left the name as the pass set it
    if nlLb.size() > 0
        for k = 0 to nlLb.size() - 1
            label lb = nlLb.get(k)
            if label.get_text(lb) == nlT1.get(k)
                label.set_text(lb, nlT0.get(k))
            if label.get_x(lb) == nlX1.get(k)
                label.set_x(lb, nlX0.get(k))
    if nlLn.size() > 0
        for k = 0 to nlLn.size() - 1
            line ln = nlLn.get(k)
            if line.get_x2(ln) == nlLx1.get(k)
                line.set_x2(ln, nlLx0.get(k))
    nlLb.clear()
    nlX0.clear()
    nlX1.clear()
    nlT0.clear()
    nlT1.clear()
    nlLn.clear()
    nlLx0.clear()
    nlLx1.clear()
    // one name's height in price: a fixed share of the daily ATR that grows with the chart's timeframe
    // (5m: 0.022 x daily ATR), never read from the bars on screen
    float rowH  = na(nlAtrD) ? syminfo.mintick * 20 : nlAtrD * 0.01 * math.sqrt(math.min(timeframe.in_seconds() / 60.0, 15))
    int   barMs = timeframe.in_seconds() * 1000
    float chBar = f_nlCharPx(SZ) / nlBarPx
    array<label> nmL = array.new<label>()
    array<float> nmY = array.new<float>()
    array<float> nmS = array.new<float>()
    array<bool>  nmB = array.new<bool>()
    for lb in label.all
        int    x = label.get_x(lb)
        string t = label.get_text(lb)
        if nlOn and t != "" and na(str.tonumber(t))
            // a name placed by bar time, or by bar index, past the live bar; its spot counted in bars past the live bar
            bool byT = x > time
            bool byB = NL_IDX and not byT and x > bar_index and x <= bar_index + 500
            if byT or byB
                nmL.push(lb)
                nmY.push(label.get_y(lb))
                nmS.push(byT ? (x - time) / float(barMs) : x - bar_index)
                nmB.push(byB)
    int cnt = nmL.size()
    if cnt > 0
        // names in price order, top first; names on one price share the first one's name, "PDH / Asia H"
        array<int>  byP  = nmY.sort_indices(order.descending)
        array<int>  host = array.new<int>(cnt, -1)
        if cnt > 1
            for j = 1 to cnt - 1
                int ix = byP.get(j)
                string it = label.get_text(nmL.get(ix))
                // only names at the end of their own line join; a tag with no line keeps its own spot
                if not f_nlFixed(it) and not na(f_nlLine(label.get_x(nmL.get(ix)), nmY.get(ix)))
                    int h = j - 1
                    while h >= 0 and host.get(ix) < 0 and math.abs(nmY.get(byP.get(h)) - nmY.get(ix)) < syminfo.mintick / 2
                        int hx = byP.get(h)
                        label hl = nmL.get(hx)
                        string ht = label.get_text(hl)
                        if host.get(hx) < 0 and not f_nlFixed(ht) and not na(f_nlLine(label.get_x(hl), nmY.get(hx)))
                            // a name already in the joined name is not repeated
                            string jt = str.contains(" / " + ht + " / ", " / " + it + " / ") ? ht : ht + " / " + it
                            nlLb.push(hl)
                            nlX0.push(label.get_x(hl))
                            nlX1.push(label.get_x(hl))
                            nlT0.push(ht)
                            nlT1.push(jt)
                            label.set_text(hl, jt)
                            nlLb.push(nmL.get(ix))
                            nlX0.push(label.get_x(nmL.get(ix)))
                            nlX1.push(label.get_x(nmL.get(ix)))
                            nlT0.push(it)
                            nlT1.push("")
                            label.set_text(nmL.get(ix), "")
                            host.set(ix, hx)
                        h -= 1
        // names that never move are placed first: MSS and CISD names, and names with no line of their own;
        // then every other name keeps its spot, or steps to just past the name it would print over
        array<float> pY = array.new<float>()
        array<float> pS = array.new<float>()
        array<float> pE = array.new<float>()
        for ps = 0 to 1
            for o = 0 to cnt - 1
                int i = byP.get(o)
                if host.get(i) < 0
                    label  lb = nmL.get(i)
                    string t  = label.get_text(lb)
                    int    x0 = label.get_x(lb)
                    float  y  = nmY.get(i)
                    line   ln = f_nlLine(x0, y)
                    bool   fx = f_nlFixed(t) or na(ln)
                    if ps == 0 ? fx : not fx
                        float s0 = nmS.get(i)
                        // a name's width in bars: its longest line's characters at its text size
                        int   len = 0
                        for part in str.split(t, "\n")
                            len := math.max(len, str.length(part))
                        float w  = len * chBar
                        float ns = s0
                        bool  hit = not fx
                        int   n  = 0
                        while hit and n < 8
                            hit := false
                            if pY.size() > 0
                                for k = 0 to pY.size() - 1
                                    if ns < pE.get(k) and ns + w > pS.get(k) and math.abs(pY.get(k) - y) < rowH
                                        hit := true
                                        ns  := pE.get(k)
                            n += 1
                        pY.push(y)
                        pS.push(ns)
                        pE.push(ns + w)
                        if ns != s0
                            int nx = nmB.get(i) ? x0 + int(math.ceil(ns - s0)) : x0 + int(math.ceil((ns - s0) * barMs))
                            label.set_x(lb, nx)
                            nlLb.push(lb)
                            nlX0.push(x0)
                            nlX1.push(nx)
                            nlT0.push(t)
                            nlT1.push(t)
                            // its own line, and the line of any name joined into it, runs on to meet it
                            for l2 in line.all
                                if line.get_x2(l2) == x0 and math.abs(line.get_y2(l2) - y) < syminfo.mintick / 2 and math.abs(line.get_y1(l2) - y) < syminfo.mintick / 2
                                    line.set_x2(l2, nx)
                                    nlLn.push(l2)
                                    nlLx0.push(x0)
                                    nlLx1.push(nx)

← 返回列表