SK-System (insp. by Stefan Kassing & CryptoWallstreet)

stahmann_falk · study · 568 行 · 点赞 13 · TradingView 原页

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

Pine Script

//@version=6
// SK-Sequence
//
// 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). Every candle after them is played through:
// - 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; 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).
indicator("SK-Sequence", shorttitle = "SK-Seq", 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. On a finer chart the 0 and A are then found on the small candle inside the big one that reached its low / high. Empty: the chart's timeframe.")
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 on a finer chart), 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")
finishedIn = input.string("Gray", "Finished sequences", options = ["Gray", "Hide"], group = G_LOOK, tooltip = "Failed, complete or invalid sequences: drawn gray beside the next larger one, or not at all.")
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
int MAX_DEPTH = 6 // larger sequences at most
color FAILED = #9e9e9e
var RET_MARKS = array.from(0.5, 0.559, 0.618, 0.667)
var EXT_MARKS = array.from(1.618, 1.809, 2.0)
// 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))
 
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
    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 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)
 
ext(int k, bool lng) => lng ? H.get(k) : L.get(k) // in the move's direction
tow(int k, bool lng) => lng ? L.get(k) : 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)
 
nearHalf(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(k, lng) <= level + dist : tow(k, lng) >= level - dist
 
touchesBand(int k, float base, float top) =>
    float p1 = lvl(base, top, BOX_LO)
    float p2 = lvl(base, top, BOX_HI)
    L.get(k) <= math.max(p1, p2) and 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, 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(k, lng), b.top.price, lng)
                b.top := Pt.new(k, ext(k, lng))
            else if nearHalf(k, b, lng)
                b.fixed := true
                b.fixedIndex := k
                b.low := Pt.new(k, tow(k, lng))
                if touchesBand(k, b.base, b.top.price)
                    b.lastTouch := k
        else
            if bey(ext(k, lng), b.top.price, lng)
                b.breakIndex := k
            else
                if bey(b.low.price, tow(k, lng), lng)
                    b.low := Pt.new(k, tow(k, lng))
                if touchesBand(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(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, H.size() - 1)
    Pt zero = Pt.new(i0, tow(i0, lng))
    Pt start = Pt.new(iA, ext(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(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(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(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 L.get(k) <= math.max(e0, e1) and H.get(k) >= math.min(e0, e1)
                    extTouched := true
            float target = box1.low.price + EXT_TARGET * move
            if not na(gkl)
                gkl.step(k, lng)
                // Complete: into the GKL box, then (a later candle) the extension's 1.618 again.
                if na(gklTouched)
                    if not na(gkl.lastTouch)
                        gklTouched := k
                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(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(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(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)
isOver(Geo g) => not na(g.failedIndex) or not na(g.completedIndex) or not na(g.invalidIndex)
 
// 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(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(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, H.size() - 1)
            int z = g.zero.index - 1
            while z >= 0 and na(deeper)
                if bey(g.zero.price, tow(z, lng), lng)
                    int e = z
                    if stop > z
                        for k = z + 1 to stop
                            if bey(ext(k, lng), ext(e, lng), lng)
                                e := k
                    Geo cand = geometry(z, e, until, lng, tol)
                    if spanOf(cand) > span
                        deeper := cand
                z -= 1
            result := na(deeper) ? grownOk : deeper
    result
 
// ---------------------------------------------------------------- picking
idxAtOrBefore(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
 
// The chart candles inside the candle picked at ts (spanMs: its length when the chart is finer, else 0).
subRange(int ts, int spanMs) =>
    int s = idxAtOrBefore(ts)
    int e = s
    if s >= 0 and spanMs > 0
        if T.get(s) < ts and s + 1 < T.size()
            s += 1
        e := s
        while e + 1 < T.size() and T.get(e + 1) < ts + spanMs
            e += 1
    [s, e]
 
// The picked candle as one: [open, high, low, close, first index reaching its high, first reaching its low].
aggregate(int s, int e) =>
    float hv = H.get(s)
    float lv = L.get(s)
    int hiIdx = s
    int loIdx = s
    if e > s
        for k = s + 1 to e
            if H.get(k) > hv
                hv := H.get(k)
                hiIdx := k
            if L.get(k) < lv
                lv := L.get(k)
                loIdx := k
    [O.get(s), hv, lv, 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(int s, int e, float hv, float lv) =>
    int res = 0
    for k = s to e
        bool lowHit = L.get(k) <= lv
        bool highHit = H.get(k) >= hv
        if lowHit and highHit
            break
        if lowHit
            res := 1
            break
        if highHit
            res := -1
            break
    res
 
// ---------------------------------------------------------------- drawing
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()
 
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_index, 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(float base, float top, int x1, int x2, color ink, bool dashed) =>
    float p1 = lvl(base, top, BOX_LO)
    float p2 = lvl(base, top, BOX_HI)
    box.new(x1, math.max(p1, p2), x2, 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_index)
    for r in RET_MARKS
        float p = lvl(base, top, r)
        line.new(x1, p, x2, p, xloc = xloc.bar_index, color = color.new(ink, 65), style = line.style_dotted)
        if showLevels
            txt(x1, p, str.tostring(r), label.style_label_right, ink, size.small)
    float p786 = lvl(base, top, LINE_786)
    line.new(x1, p786, x2, p786, xloc = xloc.bar_index, color = color.new(ink, 40), style = line.style_dashed)
    if showLevels
        txt(x1, p786, str.tostring(LINE_786), label.style_label_right, ink, size.small)
 
drawGeo(Geo g, color ink, bool hideFirst) =>
    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(bx.base, bx.top.price, bx.x1, bx.x2, ink, n == 0 and na(g.breakIndex) and na(g.invalidIndex))
    if not na(g.breakIndex)
        // The trend break: from A to the candle beyond it. Then the extension box 1.618 - 2.
        line.new(g.a.index, g.a.price, g.breakIndex, g.a.price, xloc = xloc.bar_index, color = ink, width = 2, style = line.style_dashed)
        float e0 = extOf(g, EXT_LO)
        float e1 = extOf(g, EXT_HI)
        box.new(g.cFrom, math.max(e0, e1), g.cTo, math.min(e0, e1), border_color = color.new(ink, 30), bgcolor = color.new(ink, 88), xloc = xloc.bar_index)
        for r in EXT_MARKS
            float p = extOf(g, r)
            line.new(g.cFrom, p, g.cTo, p, xloc = xloc.bar_index, color = color.new(ink, 65), style = line.style_dotted)
            if showLevels
                txt(g.cFrom, p, str.tostring(r), label.style_label_right, ink, size.small)
        txt(g.cMid, extOf(g, 1.809), "C", label.style_none, ink)
    if not na(g.gkl)
        drawBand(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(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_index(g.zero.index, g.zero.price), chart.point.from_index(g.a.index, g.a.price))
    if not na(g.b)
        pts.push(chart.point.from_index(g.b.index, g.b.price))
    if not na(g.breakIndex)
        pts.push(chart.point.from_index(g.cMid, extOf(g, 1.809)))
    polyline.new(pts, xloc = xloc.bar_index, line_color = color.new(ink, 15), line_width = 2)
    txt(g.zero.index, g.zero.price, "0", under, ink)
    txt(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(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)
        if deeper
            txt(bLow.index, bLow.price, "B?", under, ink)
        else if not hideFirst
            float mid = (lvl(first.base, first.top.price, BOX_LO) + edge) / 2
            txt(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(g.bTent.index, g.bTent.price, g.endIndex, g.bTent.price, xloc = xloc.bar_index, 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(g.failedIndex, g.b.price, "B invalidated", under, ink)
    else if not na(g.completedIndex) and not na(g.breakIndex)
        txt(g.completedIndex, extOf(g, EXT_TARGET), "Sequence complete", above, ink)
    else if not na(g.invalidIndex) and not na(g.b)
        txt(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"
 
// ---------------------------------------------------------------- run (on the newest candle only)
var table status = table.new(position.top_right, 1, 1)
var string prevKey = ""
 
if barstate.islast
    clearAll()
    int chartSec = timeframe.in_seconds()
    int pickedSec = pickedTfIn == "" ? chartSec : timeframe.in_seconds(pickedTfIn)
    int spanMs = pickedSec > chartSec ? pickedSec * 1000 : 0
    int tFirst = math.min(t0In, tAIn)
    int tSecond = math.max(t0In, tAIn)
    [s1, e1] = subRange(tFirst, spanMs)
    [s2, e2] = subRange(tSecond, spanMs)
    string problem = ""
    if s1 < 0
        problem := "Candle 1 lies before this chart's first candle - pick it again (or a bigger timeframe)."
    if problem == ""
        [o1, h1, l1, c1, hi1, lo1] = aggregate(s1, e1)
        [o2, h2, l2, c2, hi2, lo2] = aggregate(s2, e2)
        bool lng = true
        if sideIn != "Auto"
            lng := sideIn == "Long"
        else if s1 == s2
            int found = e1 > s1 ? sideFromSubs(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 = bar_index
        array<Geo> chain = array.new<Geo>()
        Geo g = geometry(i0, iA, last, lng, tolIn)
        chain.push(g)
        int depth = 0
        while depth < MAX_DEPTH
            Geo nx = largerOf(g, last, tolIn)
            if na(nx)
                break
            chain.push(nx)
            g := nx
            depth += 1
        Geo live = chain.last()
        array<Geo> shown = array.new<Geo>()
        if finishedIn == "Gray"
            shown := chain
        else if not isOver(live)
            shown.push(live)
        // 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))
        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) : ""), text_color = isOver(live) ? FAILED : ink, text_size = size.small, bgcolor = 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) and last > 0
            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 ? L.get(last - 1) > p + dist : H.get(last - 1) < 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))

← 返回列表