SK-System Manual (unofficial tool for Crypto Wall Street fans)

stahmann_falk · study · 848 行 · 点赞 87 · TradingView 原页

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

Pine Script

//@version=6
// SK-System Manual
// Unofficial tool by a fan - not affiliated with, sponsored or endorsed by Stefan Kassing or Crypto Wall Street.
//
// Pick two candles (TradingView asks for two clicks when the indicator is added; "Candle 1" / "Candle 2"
// in its settings to pick again): 0 at the first one's low, A at the second one's high (long - short
// mirrored). The same sequence rules as the SK-System Suite (one engine, copied - see README.md):
// - played on the finest candles there are for each stretch of time (stitch: 1W / 1D / 4h ... down to 1m,
//   the last 1000 of each), never longer than the ones picked on - a big candle holding both a new low and
//   the bounce can't tell which came first, smaller ones can; 0 and A are found on the small candles inside
//   the picked ones that reached its low / high; the 0 names its candle's timeframe;
// - forming: every higher high moves A up, the SK box (0.5 - 0.667 of 0 -> A, dashed) grows with it until
//   the price comes near 0.5 (half the 0.5 -> 0.559 distance): confirmed, A fixed;
// - B: the lowest low after A until a high beyond A - that high activates it: the trend break line, the
//   extension box 1.618 - 2 from B ("C" in its middle) and the next correction box (B -> the highest high
//   since); a high beyond its fixed top starts the next one, and so on;
// - the extension's 1.618 reached: the GKL box (0 -> the high); from then on no correction box counts;
// - failed: after the activation the price clearly beyond B ("B invalidated"); complete: back in the GKL
//   box, then the 1.618 again - or a high beyond the fixed GKL box without the price having come into it
//   (that box is the next larger sequence's SK box, the high activates it); invalid: beyond 0 before the
//   activation. Then the next larger sequence takes over (the same 0 with A at the activating high / the
//   GKL box's top, else the nearest deeper 0); the finished one gray or hidden.
// - its opposing sequence (the opposing Fib - the app's counter-sequence, beProtection.js counterAnchors),
//   on unless switched off: long - a short one from the highest high since the sequence's 0 (short
//   mirrored), played from there candle by candle like the Suite's sequences - A runs with every lower low,
//   a bounce confirms it; a higher high moves its 0 there.
indicator("SK-System Manual", shorttitle = "SK-Manual", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100)
 
// ---------------------------------------------------------------- inputs
G_PICK = "Candles"
t0In = input.time(timestamp("01 Jan 2025 00:00 +0000"), "Candle 1 (0)", confirm = true, group = G_PICK)
tAIn = input.time(timestamp("02 Jan 2025 00:00 +0000"), "Candle 2 (A)", confirm = true, group = G_PICK)
pickedTfIn = input.timeframe("", "Picked on timeframe", group = G_PICK, tooltip = "The timeframe the two candles were picked on - the sequence is never played on bigger candles than these. Empty: the chart's timeframe. Set it when you picked on a bigger timeframe and look at a smaller one now.")
sideIn = input.string("Auto", "Direction", options = ["Auto", "Long", "Short"], group = G_PICK, tooltip = "Auto: long if the second candle's high lies further from the first one's low than the first one's high from the second one's low. One candle picked twice: which of its ends came first (from smaller candles), else its colour.")
 
G_LOOK = "Look"
colourIn = input.string("1st", "Colour", options = ["1st", "2nd", "3rd", "4th", "Custom"], group = G_LOOK, inline = "col", tooltip = "By direction - short: red, orange, yellow; long: dark green, turquoise, light blue, dark blue. Your first sequence on a chart 1st, the next 2nd, and so on. Custom: the colour beside it.")
customColIn = input.color(#66bb6a, "", group = G_LOOK, inline = "col")
counterOn = input.bool(true, "Opposing sequence (opposing Fib)", group = G_LOOK, inline = "cnt", tooltip = "Built with it: for a long sequence a short one from the highest high since its 0 (a short one the other way round), played from there candle by candle - its A runs with every lower low until a bounce confirms it. A higher high starts the next one there.")
counterColIn = input.color(#ffeb3b, "", group = G_LOOK, inline = "cnt")
finishedIn = input.string("Hide", "Finished sequences", options = ["Hide", "Gray"], group = G_LOOK, tooltip = "Failed, complete or invalid sequences: not drawn (only the one running now), or drawn gray beside the next larger one.")
showLevels = input.bool(true, "Level numbers", group = G_LOOK)
showStatus = input.bool(true, "Status box", group = G_LOOK)
tolIn = input.float(2.0, "Zero tolerance (% of 0 -> A)", minval = 0, maxval = 50, step = 0.5, group = G_LOOK, tooltip = "How far past 0 the price must go to count as beyond it - a wick just through 0 (a sweep) doesn't.") / 100
 
G_ALERT = "Alerts (create an alert with \"Any alert() function call\")"
al500 = input.bool(true, "0.5", inline = "lv", group = G_ALERT)
al559 = input.bool(false, "0.559", inline = "lv", group = G_ALERT)
al618 = input.bool(false, "0.618", inline = "lv", group = G_ALERT)
al667 = input.bool(false, "0.667", inline = "lv", group = G_ALERT)
al786 = input.bool(false, "0.786", inline = "lv", group = G_ALERT)
alEvents = input.bool(true, "Sequence events (confirmed, activated, 1.618 reached, failed, complete, invalid)", group = G_ALERT)
 
// ---------------------------------------------------------------- rules
float BOX_LO = 0.5
float BOX_HI = 0.667
float LINE_786 = 0.786
float EXT_LO = 1.618
float EXT_HI = 2.0
float EXT_TARGET = 1.618
float EXT_DONE = 3.0 // touched the extension box, then here: it ends
float NEAR_SHARE = 0.5 * (0.559 - 0.5) // "near 0.5": half the 0.5 -> 0.559 distance, of the move
int MAX_BOXES = 20
int BOX_PAST = 3 // the open box reaches this far past the newest candle (chart candles)
int MAX_STEPS = 60 // larger sequences followed at most until an open one
int CHART_MS = timeframe.in_seconds() * 1000
var RET_MARKS = array.from(0.5, 0.559, 0.618, 0.667)
var EXT_MARKS = array.from(1.618, 1.809, 2.0)
int MAX_DEPTH = 6 // larger sequences at most
color FAILED = #9e9e9e
// A new sequence's colours by its side; past the last one: the last.
var SHORT_COLOURS = array.from(#ef5350, #ff9800, #ffeb3b)
var LONG_COLOURS = array.from(#1b7a3a, #1de9b6, #81d4fa, #0d47a1)
colourOf(bool lng) =>
    array<color> list = lng ? LONG_COLOURS : SHORT_COLOURS
    int n = colourIn == "1st" ? 0 : colourIn == "2nd" ? 1 : colourIn == "3rd" ? 2 : 3
    colourIn == "Custom" ? customColIn : list.get(math.min(n, list.size() - 1))
 
// A candle series: the chart's own or one rung of the timeframe ladder. spanMs: one candle's length.
// coarse: longer candles than the chart's - its newest candle built from the chart's own, it is now.
type Cs
    array<float> o
    array<float> h
    array<float> l
    array<float> c
    array<int> t
    int spanMs
    bool coarse = false
    string name = ""
    array<int> sp = na // a stitched series (stitch): each candle's length
 
type Pt
    int index
    float price
 
// A box: the retracement of base -> top. Its top follows every higher high until the price comes near
// its 0.5 (fixed); then its correction (low), the candles touching it (0.5 - 0.667), and a high beyond the
// top breaks it. x1 / x2: the candles it is drawn over.
type Bx
    float base
    Pt top
    bool fixed = false
    int fixedIndex = na
    Pt low = na
    int breakIndex = na
    int lastTouch = na
    int x1 = na
    int x2 = na
 
type Geo
    Cs cs
    bool lng = true
    Pt zero
    Pt second
    Pt a
    Pt b
    Pt bTent
    int confirmedIndex
    int breakIndex
    array<Bx> boxes
    Bx gkl
    int targetIndex
    int endIndex
    int invalidIndex
    int failedIndex
    int completedIndex
    int cFrom
    int cTo
    int cMid
 
// ---------------------------------------------------------------- the chart's candles (index = bar_index)
var array<float> O = array.new<float>()
var array<float> H = array.new<float>()
var array<float> L = array.new<float>()
var array<float> C = array.new<float>()
var array<int> T = array.new<int>()
O.push(open)
H.push(high)
L.push(low)
C.push(close)
T.push(time)
float prevHigh = high[1]
float prevLow = low[1]
 
// Candles kept per ladder timeframe (about what the app loads, 990) - stitched together (stitch).
int PLAY_KEEP = 1000
int WEEK_KEEP = 5000 // weekly: the whole history (picked on 1W)
 
// A timeframe's newest `keep` candles, evaluated on that timeframe. Handed out on its newest candle only:
// a request keeps what it returns for every candle, so arrays returned on each one fill the memory (RE10139).
tierCandles(int keep) =>
    var array<float> wo = array.new<float>()
    var array<float> wh = array.new<float>()
    var array<float> wl = array.new<float>()
    var array<float> wc = array.new<float>()
    var array<int> wt = array.new<int>()
    wo.push(open)
    wh.push(high)
    wl.push(low)
    wc.push(close)
    wt.push(time)
    if wt.size() > keep
        wo.shift()
        wh.shift()
        wl.shift()
        wc.shift()
        wt.shift()
    bool give = barstate.islast
    [give ? wo : na, give ? wh : na, give ? wl : na, give ? wc : na, give ? wt : na]
 
ext(Cs cs, int k, bool lng) => lng ? cs.h.get(k) : cs.l.get(k) // in the move's direction
tow(Cs cs, int k, bool lng) => lng ? cs.l.get(k) : cs.h.get(k) // against it
bey(float x, float y, bool lng) => lng ? x > y : x < y
lvl(float base, float top, float r) => top - r * (top - base)
 
// A candle's length; its timeframe's name.
spanAt(Cs cs, int k) => na(cs.sp) ? cs.spanMs : cs.sp.get(k)
tfName(int ms) =>
    int sec = int(ms / 1000)
    sec < 3600 ? str.tostring(int(sec / 60)) + "m" : sec < 86400 ? str.tostring(int(sec / 3600)) + "h" : sec < 604800 ? str.tostring(int(sec / 86400)) + "D" : sec == 604800 ? "1W" : timeframe.period
 
nearHalf(Cs cs, int k, Bx b, bool lng) =>
    float level = lvl(b.base, b.top.price, 0.5)
    float dist = NEAR_SHARE * math.abs(b.top.price - b.base)
    lng ? tow(cs, k, lng) <= level + dist : tow(cs, k, lng) >= level - dist
 
touchesBand(Cs cs, int k, float base, float top) =>
    float p1 = lvl(base, top, BOX_LO)
    float p2 = lvl(base, top, BOX_HI)
    cs.l.get(k) <= math.max(p1, p2) and cs.h.get(k) >= math.min(p1, p2)
 
newBox(float base, Pt top) =>
    Bx.new(base, Pt.new(top.index, top.price))
 
method step(Bx b, Cs cs, int k, bool lng) =>
    if na(b.breakIndex)
        if not b.fixed
            // (A candle making the new high doesn't count as coming near too - which came first in it is unknown.)
            if bey(ext(cs, k, lng), b.top.price, lng)
                b.top := Pt.new(k, ext(cs, k, lng))
            else if nearHalf(cs, k, b, lng)
                b.fixed := true
                b.fixedIndex := k
                b.low := Pt.new(k, tow(cs, k, lng))
                if touchesBand(cs, k, b.base, b.top.price)
                    b.lastTouch := k
        else
            if bey(ext(cs, k, lng), b.top.price, lng)
                b.breakIndex := k
            else
                if bey(b.low.price, tow(cs, k, lng), lng)
                    b.low := Pt.new(k, tow(cs, k, lng))
                if touchesBand(cs, k, b.base, b.top.price)
                    b.lastTouch := k
    b
 
// The sequence from the candles at i and j (either order, the same one twice too), played up to `until`.
geometry(Cs cs, int i, int j, int until, bool lng, float tol) =>
    int i0 = math.min(i, j)
    int iA = math.max(i, j)
    int last = math.min(until, cs.h.size() - 1)
    Pt zero = Pt.new(i0, tow(cs, i0, lng))
    Pt start = Pt.new(iA, ext(cs, iA, lng))
    Bx box1 = newBox(zero.price, start)
    array<Bx> boxes = array.from(box1)
    float sgn = lng ? 1.0 : -1.0
    Bx gkl = na
    Pt hiSince = na // the highest high since the activation
    int targetIndex = na
    int invalidIndex = na
    int failedIndex = na
    int gklTouched = na
    int completedIndex = na
    bool extTouched = false
    int extEnd = na
    bool extOvershot = false // ended by reaching 3 - not an end for the GKL box
    int beyondZero = na // after the activation: the first candle beyond 0 - the GKL box ends there
    if iA < last
        for k = iA + 1 to last
            Bx cur = boxes.last()
            cur.step(cs, k, lng)
            // Really beyond 0: past it by more than `tol` of 0 -> A (A as it is then).
            bool pastZero = bey(zero.price - sgn * tol * math.abs(box1.top.price - zero.price), tow(cs, k, lng), lng)
            if na(box1.breakIndex)
                // The price beyond 0 after the confirmation: over.
                if box1.fixed and pastZero
                    invalidIndex := k
                    break
                continue
            float xk = ext(cs, k, lng)
            if na(hiSince)
                hiSince := Pt.new(k, xk)
            else if bey(xk, hiSince.price, lng)
                hiSince := Pt.new(k, xk)
            if na(beyondZero) and pastZero
                beyondZero := k
            float move = box1.top.price - zero.price
            // The extension box runs to the newest candle - unless the price touched it and reached 3 after, or went beyond 0.
            if na(extEnd)
                float e0 = box1.low.price + EXT_LO * move
                float e1 = box1.low.price + EXT_HI * move
                if extTouched and not bey(box1.low.price + EXT_DONE * move, xk, lng)
                    extEnd := k
                    extOvershot := true
                else if pastZero
                    extEnd := k
                else if cs.l.get(k) <= math.max(e0, e1) and cs.h.get(k) >= math.min(e0, e1)
                    extTouched := true
            float target = box1.low.price + EXT_TARGET * move
            if not na(gkl)
                gkl.step(cs, k, lng)
                // Complete: into the GKL box, then (a later candle) the extension's 1.618 again. Or a high beyond
                // its fixed top without having come into it: the GKL box is the next larger sequence's SK box (the
                // same 0, A at its top) and that high activates it - it takes over.
                if na(gklTouched)
                    if not na(gkl.lastTouch)
                        gklTouched := k
                    else if gkl.breakIndex == k
                        completedIndex := k
                        break
                else if not bey(target, xk, lng)
                    completedIndex := k
                    break
            else
                // A box broken: the next one from here on - B -> the new high.
                if not na(cur.breakIndex) and cur.breakIndex == k and boxes.size() < MAX_BOXES
                    boxes.push(newBox(box1.low.price, Pt.new(k, xk)))
                if not bey(target, xk, lng)
                    // 1.618 reached: the GKL box. The correction box still running drops, no new one starts.
                    targetIndex := k
                    gkl := newBox(zero.price, hiSince)
                    Bx lastBox = boxes.last()
                    if boxes.size() > 1 and na(lastBox.breakIndex)
                        boxes.pop()
            // Failed only after the activation, and only clearly beyond B.
            if k > box1.breakIndex and not na(box1.low)
                if bey(box1.low.price, tow(cs, k, lng), lng)
                    failedIndex := k
                    break
    Pt a = box1.top
    Pt b = box1.low
    int brk = box1.breakIndex
    // Not confirmed yet (no B): where B would be now - the lowest low since A as it is now.
    Pt bTent = na
    if na(b) and na(invalidIndex) and a.index < last
        for k = a.index + 1 to last
            float tk = tow(cs, k, lng)
            if na(bTent)
                bTent := Pt.new(k, tk)
            else if bey(bTent.price, tk, lng)
                bTent := Pt.new(k, tk)
    int cFrom = na
    int cTo = na
    int cMid = na
    if not na(brk)
        cFrom := brk
        cTo := math.max(brk + 1, na(extEnd) ? last : extEnd)
        cMid := math.round((brk + cTo) / 2.0)
    // Drawn from the candle after its top to the last one touching it before its break (not touched yet: the newest).
    for [n, bx] in boxes
        int lim = not na(bx.breakIndex) ? bx.breakIndex : n == 0 and not na(invalidIndex) ? invalidIndex : last + BOX_PAST
        bx.x1 := bx.top.index + 1
        bx.x2 := math.max(bx.x1 + 1, na(bx.lastTouch) ? lim : math.min(bx.lastTouch, lim))
    if not na(gkl)
        gkl.x1 := gkl.top.index + 1
        gkl.x2 := math.max(gkl.top.index + 2, extOvershot ? (na(beyondZero) ? last : beyondZero) : cTo)
    Geo.new(cs = cs, lng = lng, zero = zero, second = start, a = a, b = b, bTent = bTent, confirmedIndex = box1.fixedIndex, breakIndex = brk, boxes = boxes, gkl = gkl, targetIndex = targetIndex, endIndex = last, invalidIndex = invalidIndex, failedIndex = failedIndex, completedIndex = completedIndex, cFrom = cFrom, cTo = cTo, cMid = cMid)
 
spanOf(Geo g) => math.abs(g.a.price - g.zero.price)
extOf(Geo g, float r) => g.b.price + r * (g.a.price - g.zero.price)
 
// The next larger sequence, only after this one failed or completed: the same 0 with A at the activating
// high (failed) or the GKL box's top (complete); if that one failed too, the nearest deeper 0 with the
// furthest extreme from there on. Always a strictly bigger 0 -> A.
largerOf(Cs cs, Geo g, int until, float tol) =>
    Geo result = na
    int overIndex = not na(g.failedIndex) ? g.failedIndex : g.completedIndex
    if not na(overIndex)
        bool lng = g.lng
        float span = spanOf(g)
        int grownA = na
        if not na(g.failedIndex)
            grownA := g.breakIndex
        else if not na(g.gkl)
            grownA := g.gkl.top.index
        Geo grownOk = na
        if not na(grownA) and grownA != g.zero.index
            Geo grown = geometry(cs, g.zero.index, grownA, until, lng, tol)
            if spanOf(grown) > span
                grownOk := grown
        bool grownHolds = false
        if not na(grownOk)
            grownHolds := na(grownOk.failedIndex)
        if grownHolds
            result := grownOk
        else
            Geo deeper = na
            int stop = math.min(overIndex, cs.h.size() - 1)
            int z = g.zero.index - 1
            while z >= 0 and na(deeper)
                if bey(g.zero.price, tow(cs, z, lng), lng)
                    int e = z
                    if stop > z
                        for k = z + 1 to stop
                            if bey(ext(cs, k, lng), ext(cs, e, lng), lng)
                                e := k
                    Geo cand = geometry(cs, z, e, until, lng, tol)
                    if spanOf(cand) > span
                        deeper := cand
                z -= 1
            result := na(deeper) ? grownOk : deeper
    result
 
// ---------------------------------------------------------------- finding them
// The first candle at or after t (the series' size: none).
idxAtOrAfter(Cs cs, int t) =>
    int lo = 0
    int hi = cs.t.size() - 1
    int found = cs.t.size()
    while lo <= hi
        int mid = math.floor((lo + hi) / 2.0)
        if cs.t.get(mid) >= t
            found := mid
            hi := mid - 1
        else
            lo := mid + 1
    found
 
// ---------------------------------------------------------------- drawing (in time: whichever candles it was played on)
clearAll() =>
    for b in box.all
        b.delete()
    for l in line.all
        l.delete()
    for l in label.all
        l.delete()
    for p in polyline.all
        p.delete()
 
// The opening time of the chart candle holding time t (before the chart's first candle: t itself).
chartOpenAt(int t) =>
    int lo = 0
    int hi = T.size() - 1
    int found = -1
    while lo <= hi
        int mid = math.floor((lo + hi) / 2.0)
        if T.get(mid) <= t
            found := mid
            lo := mid + 1
        else
            hi := mid - 1
    found >= 0 ? T.get(found) : t
 
// A candle's time; past the newest one: further on in chart candles. A coarse series' newest candle is now.
// Finer candles than the chart's sit on the chart candle holding them - else TradingView puts a point inside
// a big candle on the next one (an A in the ATH's week looked like the following week's).
xt(Cs cs, int k) =>
    int n = cs.t.size()
    int res = 0
    if k >= n - 1 and (cs.coarse or k >= n)
        res := time + (k - n + 1) * CHART_MS
    else
        res := spanAt(cs, k) < CHART_MS ? chartOpenAt(cs.t.get(k)) : cs.t.get(k)
    res
 
NONE = color.new(color.black, 100)
txt(int x, float y, string s, string st, color c, string sz = size.normal) =>
    label.new(x, y, s, xloc = xloc.bar_time, style = st, color = NONE, textcolor = c, size = sz)
 
// A box 0.5 - 0.667 of a retracement (strong edge, faint fill), its levels left outside, 0.786 as a line.
drawBand(Cs cs, float base, float top, int x1, int x2, color ink, bool dashed) =>
    int t1 = xt(cs, x1)
    int t2 = math.max(xt(cs, x2), t1 + CHART_MS)
    float p1 = lvl(base, top, BOX_LO)
    float p2 = lvl(base, top, BOX_HI)
    box.new(t1, math.max(p1, p2), t2, math.min(p1, p2), border_color = ink, border_width = 2, border_style = dashed ? line.style_dashed : line.style_solid, bgcolor = color.new(ink, 95), xloc = xloc.bar_time)
    for r in RET_MARKS
        float p = lvl(base, top, r)
        line.new(t1, p, t2, p, xloc = xloc.bar_time, color = color.new(ink, 65), style = line.style_dotted)
        if showLevels
            txt(t1, p, str.tostring(r), label.style_label_right, ink, size.small)
    float p786 = lvl(base, top, LINE_786)
    line.new(t1, p786, t2, p786, xloc = xloc.bar_time, color = color.new(ink, 40), style = line.style_dashed)
    if showLevels
        txt(t1, p786, str.tostring(LINE_786), label.style_label_right, ink, size.small)
 
isOver(Geo g) => not na(g.failedIndex) or not na(g.completedIndex) or not na(g.invalidIndex)
 
drawGeo(Geo g, color ink, bool hideFirst, bool firstAsGkl) =>
    Cs cs = g.cs
    bool lng = g.lng
    string under = lng ? label.style_label_up : label.style_label_down
    string above = lng ? label.style_label_down : label.style_label_up
    for [n, bx] in g.boxes
        if not (n == 0 and hideFirst)
            drawBand(cs, bx.base, bx.top.price, bx.x1, bx.x2, ink, n == 0 and na(g.breakIndex) and na(g.invalidIndex) and not firstAsGkl)
    if not na(g.breakIndex)
        // The trend break: from A to the candle beyond it. Then the extension box 1.618 - 2.
        line.new(xt(cs, g.a.index), g.a.price, xt(cs, g.breakIndex), g.a.price, xloc = xloc.bar_time, color = ink, width = 2, style = line.style_dashed)
        float e0 = extOf(g, EXT_LO)
        float e1 = extOf(g, EXT_HI)
        int c1 = xt(cs, g.cFrom)
        int c2 = math.max(xt(cs, g.cTo), c1 + CHART_MS)
        box.new(c1, math.max(e0, e1), c2, math.min(e0, e1), border_color = color.new(ink, 30), bgcolor = color.new(ink, 88), xloc = xloc.bar_time)
        for r in EXT_MARKS
            float p = extOf(g, r)
            line.new(c1, p, c2, p, xloc = xloc.bar_time, color = color.new(ink, 65), style = line.style_dotted)
            if showLevels
                txt(c1, p, str.tostring(r), label.style_label_right, ink, size.small)
        txt(xt(cs, g.cMid), extOf(g, 1.809), "C", label.style_none, ink)
    if not na(g.gkl)
        drawBand(cs, g.gkl.base, g.gkl.top.price, g.gkl.x1, g.gkl.x2, ink, false)
        float mid = (lvl(g.gkl.base, g.gkl.top.price, BOX_LO) + lvl(g.gkl.base, g.gkl.top.price, BOX_HI)) / 2
        txt(xt(cs, math.round((g.gkl.x1 + g.gkl.x2) / 2.0)), mid, "GKL", label.style_none, ink)
    // 0 -> A -> B -> C
    array<chart.point> pts = array.from(chart.point.from_time(xt(cs, g.zero.index), g.zero.price), chart.point.from_time(xt(cs, g.a.index), g.a.price))
    if not na(g.b)
        pts.push(chart.point.from_time(xt(cs, g.b.index), g.b.price))
    if not na(g.breakIndex)
        pts.push(chart.point.from_time(xt(cs, g.cMid), extOf(g, 1.809)))
    polyline.new(pts, xloc = xloc.bar_time, line_color = color.new(ink, 15), line_width = 2)
    // The 0 names the timeframe it was played on (the status box does too).
    txt(xt(cs, g.zero.index), g.zero.price, "0 (" + tfName(spanAt(cs, g.zero.index)) + ")", under, ink)
    txt(xt(cs, g.a.index), g.a.price, "A", above, ink)
    // B's name: "B" only once activated; before, "B?" in the SK box - or under the low once that's beyond its 0.667.
    if not na(g.b) and (not na(g.breakIndex) or not na(g.invalidIndex))
        txt(xt(cs, g.b.index), g.b.price, "B", under, ink)
    else
        Pt bLow = na(g.b) ? g.bTent : g.b
        Bx first = g.boxes.first()
        float edge = lvl(first.base, first.top.price, BOX_HI)
        bool deeper = false
        if not na(bLow)
            deeper := bey(edge, bLow.price, lng)
        float mid = (lvl(first.base, first.top.price, BOX_LO) + edge) / 2
        if deeper
            txt(xt(cs, bLow.index), bLow.price, "B?", under, ink)
        if firstAsGkl
            txt(xt(cs, math.round((first.x1 + first.x2) / 2.0)), mid, "GKL", label.style_none, ink)
        else if not deeper and not hideFirst
            txt(xt(cs, math.round((first.x1 + first.x2) / 2.0)), mid, "B?", label.style_none, color.new(ink, 30))
    // Not confirmed yet: B as it would be now - faint, dotted to the newest candle.
    if na(g.b) and not na(g.bTent)
        line.new(xt(cs, g.bTent.index), g.bTent.price, xt(cs, g.endIndex), g.bTent.price, xloc = xloc.bar_time, color = color.new(ink, 60), style = line.style_dotted)
    // Failed: the words under B where it broke; complete: over the 1.618 where the price came back.
    if not na(g.failedIndex) and not na(g.b)
        txt(xt(cs, g.failedIndex), g.b.price, "B invalidated", under, ink)
    else if not na(g.completedIndex) and not na(g.breakIndex)
        txt(xt(cs, g.completedIndex), extOf(g, EXT_TARGET), "Sequence complete", above, ink)
    else if not na(g.invalidIndex) and not na(g.b)
        txt(xt(cs, g.invalidIndex), g.b.price, lng ? "Invalid - B below 0" : "Invalid - B above 0", under, ink)
 
// A sequence's first box, not activated yet, that is another drawn one's GKL box (a smaller sequence's
// GKL box is the larger one's SK box): not drawn twice.
coveredFirst(array<Geo> shown, int n) =>
    Geo g = shown.get(n)
    bool res = false
    if na(g.breakIndex) and na(g.invalidIndex)
        Bx bx = g.boxes.first()
        float lo = lvl(bx.base, bx.top.price, BOX_LO)
        float hi = lvl(bx.base, bx.top.price, BOX_HI)
        for m = 0 to shown.size() - 1
            Geo k = shown.get(m)
            if m != n and not na(k.gkl) and k.lng == g.lng
                float tolG = 0.01 * math.abs(k.gkl.top.price - k.gkl.base)
                bool same = math.abs(lvl(k.gkl.base, k.gkl.top.price, BOX_LO) - lo) <= tolG and math.abs(lvl(k.gkl.base, k.gkl.top.price, BOX_HI) - hi) <= tolG
                if same and bx.x1 <= k.gkl.x2 and bx.x2 >= k.gkl.x1
                    res := true
    res
 
stateOf(Geo g) =>
    not na(g.invalidIndex) ? "invalid" : not na(g.failedIndex) ? "failed" : not na(g.completedIndex) ? "complete" : not na(g.gkl) ? "1.618 reached (GKL box)" : not na(g.breakIndex) ? "activated" : not na(g.confirmedIndex) ? "confirmed" : "forming"
 
// ---------------------------------------------------------------- picking
// The last candle starting at or before t (-1: none).
idxAtOrBefore(Cs cs, int t) =>
    int lo = 0
    int hi = cs.t.size() - 1
    int found = -1
    while lo <= hi
        int mid = math.floor((lo + hi) / 2.0)
        if cs.t.get(mid) <= t
            found := mid
            lo := mid + 1
        else
            hi := mid - 1
    found
 
// The candles of `cs` inside the candle picked at ts, pickedMs long: [first, last] (-1: before its first one).
subRange(Cs cs, int ts, int pickedMs) =>
    int s = idxAtOrBefore(cs, ts)
    int e = s
    if s >= 0 and spanAt(cs, s) < pickedMs
        if cs.t.get(s) < ts and cs.t.get(s) + spanAt(cs, s) <= ts and s + 1 < cs.t.size()
            s += 1
        e := s
        while e + 1 < cs.t.size() and cs.t.get(e + 1) < ts + pickedMs
            e += 1
    [s, e]
 
// The picked candle as one: [open, high, low, close, first candle reaching its high, first reaching its low].
aggregate(Cs cs, int s, int e) =>
    float hv = cs.h.get(s)
    float lv = cs.l.get(s)
    int hiIdx = s
    int loIdx = s
    if e > s
        for k = s + 1 to e
            if cs.h.get(k) > hv
                hv := cs.h.get(k)
                hiIdx := k
            if cs.l.get(k) < lv
                lv := cs.l.get(k)
                loIdx := k
    [cs.o.get(s), hv, lv, cs.c.get(e), hiIdx, loIdx]
 
// One candle picked twice: which of its ends its smaller candles reached first (1 long, -1 short, 0 unknown).
sideFromSubs(Cs cs, int s, int e, float hv, float lv) =>
    int res = 0
    for k = s to e
        bool lowHit = cs.l.get(k) <= lv
        bool highHit = cs.h.get(k) >= hv
        if lowHit and highHit
            break
        if lowHit
            res := 1
            break
        if highHit
            res := -1
            break
    res
 
// One rung of the timeframe ladder (na: no candles). The chart's own timeframe: the chart's candles stand
// for it. Coarser than the chart: its newest candle built from the chart's own (the requested one may not
// be up to date yet).
tierOf(Cs ch, simple string tf, string name, int keep) =>
    Cs res = na
    int sec = timeframe.in_seconds(tf)
    int chartSec = timeframe.in_seconds()
    if sec == chartSec
        res := Cs.new(ch.o, ch.h, ch.l, ch.c, ch.t, ch.spanMs, false, name)
    else if sec < chartSec
        // Finer: lookahead_off reads a chart candle's last small candle (the newest one, handing the arrays
        // out); lookahead_on would read its first one - na.
        [fo, fh, fl, fc, ft] = request.security(syminfo.tickerid, tf, tierCandles(keep), lookahead = barmerge.lookahead_off)
        if not na(ft) and ft.size() > 0
            res := Cs.new(fo, fh, fl, fc, ft, sec * 1000, false, name)
    else
        // Coarser: lookahead_on - on the chart's newest candle the coarse timeframe's newest candle (the one
        // handing the arrays out) must be the one read; with lookahead_off it would be the one before, na.
        // Nothing of the future is read: only the newest candle uses them, and its current period is rebuilt below.
        [wo, wh, wl, wc, wt] = request.security(syminfo.tickerid, tf, tierCandles(keep), lookahead = barmerge.lookahead_on)
        if not na(wt) and wt.size() > 0
            array<float> o2 = wo.copy()
            array<float> h2 = wh.copy()
            array<float> l2 = wl.copy()
            array<float> c2 = wc.copy()
            array<int> t2 = wt.copy()
            int periodStart = time(tf)
            while t2.size() > 0 and t2.last() >= periodStart
                o2.pop()
                h2.pop()
                l2.pop()
                c2.pop()
                t2.pop()
            int s = idxAtOrAfter(ch, periodStart)
            if s < T.size()
                float hv = H.get(s)
                float lv = L.get(s)
                for k = s to T.size() - 1
                    hv := math.max(hv, H.get(k))
                    lv := math.min(lv, L.get(k))
                o2.push(O.get(s))
                h2.push(hv)
                l2.push(lv)
                c2.push(C.last())
                t2.push(periodStart)
            if t2.size() > 0
                res := Cs.new(o2, h2, l2, c2, t2, sec * 1000, true, name)
    res
 
// The ladder fine -> coarse.
addTier(array<Cs> tiers, Cs cs) =>
    if not na(cs)
        int at = tiers.size()
        for [i, x] in tiers
            if x.spanMs > cs.spanMs
                at := i
                break
        tiers.insert(at, cs)
 
// One series of the finest candles there are for each stretch of time (owner 2026-11-20): the longest rung
// not longer than maxMs, then from the first of its candle boundaries the next finer rung has candles for on
// that one's, and so on down to 1m - old stretches on big candles, the recent ones on small ones. A big
// candle holding both a new low and the bounce can't tell which came first; where smaller ones exist, they
// can - so a bounce confirms a smaller sequence wherever the data allows (one timeframe for all of it, the
// app's playTimeframe, left the bounce on 4h when 1h didn't reach back to the 0).
stitch(array<Cs> tiers, int maxMs) =>
    Cs res = na
    for i = tiers.size() - 1 to 0
        Cs x = tiers.get(i)
        if x.spanMs <= maxMs and x.t.size() > 1
            if na(res)
                array<int> sp = array.new<int>(x.t.size(), x.spanMs)
                res := Cs.new(x.o.copy(), x.h.copy(), x.l.copy(), x.c.copy(), x.t.copy(), x.spanMs, x.coarse, x.name, sp)
            else
                // The first candle boundary of the series so far at or after the finer one's first candle.
                int b = idxAtOrAfter(res, x.t.get(0))
                if b < res.t.size()
                    int from = idxAtOrAfter(x, res.t.get(b))
                    if from < x.t.size()
                        while res.t.size() > b
                            res.o.pop()
                            res.h.pop()
                            res.l.pop()
                            res.c.pop()
                            res.t.pop()
                            res.sp.pop()
                        for k = from to x.t.size() - 1
                            res.o.push(x.o.get(k))
                            res.h.push(x.h.get(k))
                            res.l.push(x.l.get(k))
                            res.c.push(x.c.get(k))
                            res.t.push(x.t.get(k))
                            res.sp.push(x.spanMs)
                        res.spanMs := x.spanMs
                        res.coarse := x.coarse
                        res.name := tfName(res.sp.first()) + "-" + x.name
    res
 
// A sequence from candles i and j with every larger one after it (each finished one's next larger one).
chainOf(Cs cs, int i, int j, int last, bool lng) =>
    array<Geo> chain = array.new<Geo>()
    Geo g = geometry(cs, i, j, last, lng, tolIn)
    chain.push(g)
    int depth = 0
    while depth < MAX_DEPTH
        Geo nx = largerOf(cs, g, last, tolIn)
        if na(nx)
            break
        chain.push(nx)
        g := nx
        depth += 1
    chain
 
// A chain drawn: all of it (finished ones gray) or only the live one ("Finished sequences": Hide). Hidden,
// a live one grown from the smaller one's GKL box (the same 0, A at its top) shows its first box as that
// GKL box until it is activated - like the SK-System Suite.
drawChain(array<Geo> chain, color ink) =>
    Geo live = chain.last()
    array<Geo> shown = array.new<Geo>()
    if finishedIn == "Gray"
        shown := chain
    else if not isOver(live)
        shown.push(live)
    bool liveFromGkl = false
    if finishedIn == "Hide" and chain.size() > 1 and na(live.breakIndex)
        Geo p = chain.get(chain.size() - 2)
        if not na(p.gkl)
            liveFromGkl := p.zero.index == live.zero.index and p.gkl.top.index == live.second.index
    // The larger ones first: the smaller (gray) ones lie over them.
    if shown.size() > 0
        for n = shown.size() - 1 to 0
            Geo sg = shown.get(n)
            drawGeo(sg, isOver(sg) ? FAILED : ink, coveredFirst(shown, n), n == shown.size() - 1 and liveFromGkl)
 
// The sequence's opposing sequence (the app's counterAnchors): long - from the highest high since its 0 (the
// last of a new high each time) to the lowest low after it, short mirrored. [0, A] (-1: no candle after it).
counterOf(Cs cs, Geo g, int last) =>
    bool lng = g.lng
    int idx = g.zero.index
    if idx < last
        for k = idx + 1 to last
            if bey(ext(cs, k, lng), ext(cs, idx, lng), lng)
                idx := k
    int end = -1
    if idx < last
        end := idx + 1
        for k = idx + 1 to last
            if bey(tow(cs, end, lng), tow(cs, k, lng), lng)
                end := k
    [idx, end]
 
// ---------------------------------------------------------------- run (on the newest candle only)
var table status = table.new(position.top_right, 1, 2)
var string prevKey = ""
 
if barstate.islast
    clearAll()
    Cs ch = Cs.new(O, H, L, C, T, CHART_MS, false, timeframe.period)
    array<Cs> tiers = array.new<Cs>()
    addTier(tiers, tierOf(ch, "1", "1m", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "5", "5m", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "15", "15m", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "30", "30m", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "60", "1h", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "240", "4h", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "1D", "1D", PLAY_KEEP))
    addTier(tiers, tierOf(ch, "1W", "1W", WEEK_KEEP))
    // A chart timeframe off the ladder (2h, 3D, 1M ...): its own candles as one more rung.
    bool onLadder = false
    for x in tiers
        if x.spanMs == CHART_MS
            onLadder := true
    if not onLadder
        addTier(tiers, ch)
    int chartSec = timeframe.in_seconds()
    int pickedMs = (pickedTfIn == "" ? chartSec : timeframe.in_seconds(pickedTfIn)) * 1000
    int tFirst = math.min(t0In, tAIn)
    int tSecond = math.max(t0In, tAIn)
    Cs cs = stitch(tiers, pickedMs)
    string problem = ""
    if na(cs) or cs.t.get(0) > tFirst
        problem := "Candle 1 lies before the candles loaded here - pick it again (or set a bigger \"Picked on timeframe\")."
    if problem == ""
        [s1, e1] = subRange(cs, tFirst, pickedMs)
        [s2, e2] = subRange(cs, tSecond, pickedMs)
        [o1, h1, l1, c1, hi1, lo1] = aggregate(cs, s1, e1)
        [o2, h2, l2, c2, hi2, lo2] = aggregate(cs, s2, e2)
        bool lng = true
        if sideIn != "Auto"
            lng := sideIn == "Long"
        else if s1 == s2 or tFirst == tSecond
            int found = e1 > s1 ? sideFromSubs(cs, s1, e1, h1, l1) : 0
            lng := found != 0 ? found == 1 : not (c1 < o1)
        else
            float up = h2 - l1
            float down = h1 - l2
            lng := up != down ? up > down : c2 > c1
        color ink = colourOf(lng)
        int i0 = lng ? lo1 : hi1
        int iA = lng ? hi2 : lo2
        int last = cs.h.size() - 1
        array<Geo> chain = chainOf(cs, i0, iA, last, lng)
        Geo live = chain.last()
        // The opposing sequence first: the sequence lies over it. Of the live one (the largest still running).
        string counterState = ""
        if counterOn
            // On the same stitched candles, played from its 0 and the next candle - A runs with every lower low,
            // so a bounce on the way down confirms a smaller opposing sequence (the app's Gegenfib starts with A
            // at the lowest low already and skips such a bounce). A finished one hands over to its larger one.
            [c0, cA] = counterOf(cs, live, last)
            if cA >= 0
                array<Geo> cChain = chainOf(cs, c0, c0 + 1, last, not live.lng)
                drawChain(cChain, counterColIn)
                counterState := stateOf(cChain.last()) + " (" + tfName(spanAt(cs, c0)) + ")"
        drawChain(chain, ink)
        string side = lng ? "long" : "short"
        string state = stateOf(live)
        if showStatus
            table.cell(status, 0, 0, "SK-Sequence " + side + " · " + state + (chain.size() > 1 ? " · larger #" + str.tostring(chain.size() - 1) : "") + " (" + tfName(spanAt(cs, live.zero.index)) + ")", text_color = isOver(live) ? FAILED : ink, text_size = size.small, bgcolor = color.new(color.black, 80))
            table.cell(status, 0, 1, counterState == "" ? "" : "Opposing sequence (" + (lng ? "short" : "long") + ") · " + counterState, text_color = counterColIn, text_size = size.small, bgcolor = counterState == "" ? NONE : color.new(color.black, 80))
        // Alerts: the sequence's events, and the price coming near a level of the box it is in now.
        string key = str.tostring(chain.size()) + "|" + state
        if alEvents and prevKey != "" and key != prevKey
            alert(syminfo.ticker + " " + timeframe.period + ": SK-Sequence " + side + " " + state + (chain.size() > 1 ? " (larger sequence)" : ""), alert.freq_once_per_bar)
        prevKey := key
        if not isOver(live)
            Bx cur = na
            if not na(live.gkl)
                cur := live.gkl
            else
                Bx lb = live.boxes.last()
                if na(lb.breakIndex)
                    cur := lb
            if not na(cur)
                array<float> levels = array.new<float>()
                if al500
                    levels.push(0.5)
                if al559
                    levels.push(0.559)
                if al618
                    levels.push(0.618)
                if al667
                    levels.push(0.667)
                if al786
                    levels.push(0.786)
                // "Near": half the 0.5 -> 0.559 distance before the level, on the side the price comes from.
                float dist = NEAR_SHARE * math.abs(cur.top.price - cur.base)
                for r in levels
                    float p = lvl(cur.base, cur.top.price, r)
                    bool nowNear = lng ? low <= p + dist : high >= p - dist
                    bool wasAway = lng ? prevLow > p + dist : prevHigh < p - dist
                    if nowNear and wasAway
                        alert(syminfo.ticker + " " + timeframe.period + ": SK-Sequence " + side + " - price near " + str.tostring(r) + " (" + str.tostring(p, format.mintick) + ")", alert.freq_once_per_bar)
    else
        if showStatus
            table.cell(status, 0, 0, problem, text_color = color.orange, text_size = size.small, bgcolor = color.new(color.black, 80))

← 返回列表