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

stahmann_falk · study · 799 行 · 点赞 15 · TradingView 原页

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

Pine Script

//@version=6
// SK-System Suite
// Unofficial tool by a fan - not affiliated with, sponsored or endorsed by Stefan Kassing or CryptoWallstreet.
//
// Four parts on one chart: the SK sequences, the all-time high, liquidation levels and moving averages.
//
// SK sequences - no candles to pick - found by itself on every chart, nested like a Matryoshka:
// - Long: the largest long SK sequence from the all-time low that is not complete / failed yet (dark green);
// - Short: the same, short from the all-time high (red);
// - Long 2: from the lowest low after the all-time high (light green) - not drawn when that low is the
//   all-time low itself ("= Long");
// - Short 2: from the highest high after that low (orange).
// Each is played from its 0 on the chart's candles when they reach back to it, else on weekly candles
// (the whole history).
//
// All-time high: a line from its candle to the newest one - where the Short sequence starts.
//
// Liquidation levels: up to 8 zones typed in (two prices and a colour per row). Every price the market
// touched inside a zone (over the last N candles) is taken out of it, so it shrinks as it is eaten; fully
// eaten, it goes 10 candles later.
//
// Moving averages (EMA 50 / 200, SMA 50 / 200): the trend the sequences run with or against, and levels
// that can lie inside an SK box.
//
// A sequence from 0 and A (long - short mirrored), played candle by candle:
// - 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; complete: back in the GKL box, then the
//   1.618 again; invalid: beyond 0 before the activation. Failed or complete: 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)
//   until one is still open.
indicator("SK-System Suite", shorttitle = "SK-Suite", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500, max_polylines_count = 100)
 
// ---------------------------------------------------------------- inputs
G_SEQ = "Sequences"
onL = input.bool(true, "Long from the all-time low", inline = "l", group = G_SEQ)
colL = input.color(#1b7a3a, "", inline = "l", group = G_SEQ)
onS = input.bool(true, "Short from the all-time high", inline = "s", group = G_SEQ)
colS = input.color(#ef5350, "", inline = "s", group = G_SEQ)
onL2 = input.bool(true, "Long 2 from the low after the ATH", inline = "l2", group = G_SEQ)
colL2 = input.color(#66bb6a, "", inline = "l2", group = G_SEQ)
onS2 = input.bool(true, "Short 2 from the high after that low", inline = "s2", group = G_SEQ)
colS2 = input.color(#ff9800, "", inline = "s2", group = G_SEQ)
 
G_LOOK = "Look"
showAth = input.bool(true, "All-time high line", inline = "ath", group = G_LOOK)
colAth = input.color(#26a69a, "", inline = "ath", group = G_LOOK)
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, a new sequence)", group = G_ALERT)
 
G_LIQ = "Liquidation levels (a row: on, the two prices, colour)"
liqLookback = input.int(300, "Touches counted over the last (candles)", minval = 10, maxval = 5000, group = G_LIQ, tooltip = "Every price the market touched inside a zone within these candles is taken out of it. A zone the market went through completely shows once those candles have passed again.")
liqOn1 = input.bool(false, "", inline = "liq1", group = G_LIQ)
liqA1 = input.price(0.0, "", inline = "liq1", group = G_LIQ)
liqB1 = input.price(0.0, "", inline = "liq1", group = G_LIQ)
liqC1 = input.color(#ffeb3b, "", inline = "liq1", group = G_LIQ)
liqOn2 = input.bool(false, "", inline = "liq2", group = G_LIQ)
liqA2 = input.price(0.0, "", inline = "liq2", group = G_LIQ)
liqB2 = input.price(0.0, "", inline = "liq2", group = G_LIQ)
liqC2 = input.color(#ffeb3b, "", inline = "liq2", group = G_LIQ)
liqOn3 = input.bool(false, "", inline = "liq3", group = G_LIQ)
liqA3 = input.price(0.0, "", inline = "liq3", group = G_LIQ)
liqB3 = input.price(0.0, "", inline = "liq3", group = G_LIQ)
liqC3 = input.color(#ffeb3b, "", inline = "liq3", group = G_LIQ)
liqOn4 = input.bool(false, "", inline = "liq4", group = G_LIQ)
liqA4 = input.price(0.0, "", inline = "liq4", group = G_LIQ)
liqB4 = input.price(0.0, "", inline = "liq4", group = G_LIQ)
liqC4 = input.color(#ffeb3b, "", inline = "liq4", group = G_LIQ)
liqOn5 = input.bool(false, "", inline = "liq5", group = G_LIQ)
liqA5 = input.price(0.0, "", inline = "liq5", group = G_LIQ)
liqB5 = input.price(0.0, "", inline = "liq5", group = G_LIQ)
liqC5 = input.color(#ffeb3b, "", inline = "liq5", group = G_LIQ)
liqOn6 = input.bool(false, "", inline = "liq6", group = G_LIQ)
liqA6 = input.price(0.0, "", inline = "liq6", group = G_LIQ)
liqB6 = input.price(0.0, "", inline = "liq6", group = G_LIQ)
liqC6 = input.color(#ffeb3b, "", inline = "liq6", group = G_LIQ)
liqOn7 = input.bool(false, "", inline = "liq7", group = G_LIQ)
liqA7 = input.price(0.0, "", inline = "liq7", group = G_LIQ)
liqB7 = input.price(0.0, "", inline = "liq7", group = G_LIQ)
liqC7 = input.color(#ffeb3b, "", inline = "liq7", group = G_LIQ)
liqOn8 = input.bool(false, "", inline = "liq8", group = G_LIQ)
liqA8 = input.price(0.0, "", inline = "liq8", group = G_LIQ)
liqB8 = input.price(0.0, "", inline = "liq8", group = G_LIQ)
liqC8 = input.color(#ffeb3b, "", inline = "liq8", group = G_LIQ)
 
G_MA = "Moving averages"
ma1On = input.bool(true, "", inline = "ma1", group = G_MA)
ma1Type = input.string("EMA", "", options = ["EMA", "SMA"], inline = "ma1", group = G_MA)
ma1Len = input.int(50, "", minval = 1, maxval = 1000, inline = "ma1", group = G_MA)
ma1Col = input.color(#42a5f5, "", inline = "ma1", group = G_MA)
ma1W = input.int(1, "", minval = 1, maxval = 4, inline = "ma1", group = G_MA)
ma2On = input.bool(true, "", inline = "ma2", group = G_MA)
ma2Type = input.string("EMA", "", options = ["EMA", "SMA"], inline = "ma2", group = G_MA)
ma2Len = input.int(200, "", minval = 1, maxval = 1000, inline = "ma2", group = G_MA)
ma2Col = input.color(#ab47bc, "", inline = "ma2", group = G_MA)
ma2W = input.int(2, "", minval = 1, maxval = 4, inline = "ma2", group = G_MA)
ma3On = input.bool(true, "", inline = "ma3", group = G_MA)
ma3Type = input.string("SMA", "", options = ["EMA", "SMA"], inline = "ma3", group = G_MA)
ma3Len = input.int(50, "", minval = 1, maxval = 1000, inline = "ma3", group = G_MA)
ma3Col = input.color(#ffa726, "", inline = "ma3", group = G_MA)
ma3W = input.int(1, "", minval = 1, maxval = 4, inline = "ma3", group = G_MA)
ma4On = input.bool(true, "", inline = "ma4", group = G_MA)
ma4Type = input.string("SMA", "", options = ["EMA", "SMA"], inline = "ma4", group = G_MA)
ma4Len = input.int(200, "", minval = 1, maxval = 1000, inline = "ma4", group = G_MA)
ma4Col = input.color(#ef5350, "", inline = "ma4", group = G_MA)
ma4W = input.int(2, "", minval = 1, maxval = 4, inline = "ma4", group = G_MA)
 
// ---------------------------------------------------------------- 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 WEEK_MS = 7 * 86400 * 1000
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)
 
// A candle series: the chart's own, or the weekly one (the whole history; its newest candle built from
// the chart's own of this week). spanMs: one candle's length.
type Cs
    array<float> o
    array<float> h
    array<float> l
    array<float> c
    array<int> t
    int spanMs
    bool weekly = false
 
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]
 
// The weekly candles of the whole history, evaluated on the weekly timeframe.
weeklyCandles() =>
    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)
    [wo, wh, wl, wc, wt]
 
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)
 
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.
                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(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
 
// The extreme's candle from `from` on: long the lowest low, short the highest high (the first of equal ones; -1: none).
extremeFrom(Cs cs, int from, bool lng) =>
    int best = -1
    int n = cs.h.size()
    if from < n
        for k = from to n - 1
            if best < 0
                best := k
            else if bey(tow(cs, best, lng), tow(cs, k, lng), lng)
                best := k
    best
 
// The largest sequence from the extreme (from `from` on) that is not complete or failed: started from the
// extreme and its next candle, then each finished one's next larger one. Invalid or none left: na.
openFrom(Cs cs, int from, bool lng) =>
    Geo res = na
    int i0 = extremeFrom(cs, from, lng)
    int last = cs.h.size() - 1
    if i0 >= 0 and i0 < last
        Geo g = geometry(cs, i0, i0 + 1, last, lng, tolIn)
        int n = 0
        while n < MAX_STEPS
            if na(g.failedIndex) and na(g.completedIndex)
                if na(g.invalidIndex)
                    res := g
                break
            Geo nx = largerOf(cs, g, last, tolIn)
            if na(nx)
                break
            g := nx
            n += 1
    res
 
// One kind: its 0 from fromTime on (na: the whole history), played on the chart's candles when they reach
// back to `startTime` (na: the extreme's weekly candle), else on the weekly ones - and once its 0 is found
// there, again on the chart's if they reach back to that 0's week.
findKind(Cs ch, Cs wk, bool lng, int fromTime, int startTime) =>
    Geo res = na
    int st = startTime
    if na(st)
        int iw = extremeFrom(wk, 0, lng)
        st := iw >= 0 ? wk.t.get(iw) : na
    if not na(st) and ch.t.size() > 1
        bool chartReaches = ch.t.get(0) <= st
        Cs cs = chartReaches ? ch : wk
        Geo g = openFrom(cs, na(fromTime) ? 0 : idxAtOrAfter(cs, fromTime), lng)
        if not na(g) and not chartReaches
            if ch.t.get(0) <= cs.t.get(g.zero.index)
                g := openFrom(ch, na(fromTime) ? 0 : idxAtOrAfter(ch, fromTime), lng)
        res := g
    res
 
zeroTimeOf(Geo g) => g.cs.t.get(g.zero.index)
zeroEndOf(Geo g) => g.cs.t.get(g.zero.index) + g.cs.spanMs
 
// ---------------------------------------------------------------- drawing (in time: the chart's or the weekly candles)
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()
 
// A candle's time; past the newest one: further on in chart candles. The weekly series' newest candle is now.
xt(Cs cs, int k) =>
    int n = cs.t.size()
    int res = 0
    if k >= n - 1 and (cs.weekly or k >= n)
        res := time + (k - n + 1) * CHART_MS
    else
        res := 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)
 
drawGeo(Geo g, color ink) =>
    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
        drawBand(cs, 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(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)
    txt(xt(cs, g.zero.index), g.zero.price, "0", 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)
        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)
        if deeper
            txt(xt(cs, bLow.index), bLow.price, "B?", under, ink)
        else
            float mid = (lvl(first.base, first.top.price, BOX_LO) + edge) / 2
            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)
 
stateOf(Geo g) =>
    not na(g.gkl) ? "1.618 reached (GKL box)" : not na(g.breakIndex) ? "activated" : not na(g.confirmedIndex) ? "confirmed" : "forming"
 
// ---------------------------------------------------------------- alerts
var array<string> prevKeys = array.from("", "", "", "")
 
// One kind's alerts: its events (a new sequence, confirmed, activated, 1.618 reached) and the price coming
// near a ticked level of the box it is in now.
alertsFor(Geo g, int slot, string name) =>
    string key = na(g) ? "none" : str.tostring(g.zero.price) + "|" + str.tostring(spanOf(g)) + "|" + stateOf(g)
    string prev = prevKeys.get(slot)
    if alEvents and prev != "" and key != prev and not na(g)
        alert(syminfo.ticker + " " + timeframe.period + ": SK " + name + " - " + stateOf(g), alert.freq_once_per_bar)
    prevKeys.set(slot, key)
    if not na(g)
        Bx cur = na
        if not na(g.gkl)
            cur := g.gkl
        else
            Bx lb = g.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 = g.lng ? low <= p + dist : high >= p - dist
                bool wasAway = g.lng ? prevLow > p + dist : prevHigh < p - dist
                if nowNear and wasAway
                    alert(syminfo.ticker + " " + timeframe.period + ": SK " + name + " - price near " + str.tostring(r) + " (" + str.tostring(p, format.mintick) + ")", alert.freq_once_per_bar)
 
// ---------------------------------------------------------------- liquidation levels
int LIQ_REACH = 10 // a zone reaches this far past the newest candle
int LIQ_LINGER = 10 // fully eaten: gone this many candles later
int LIQ_MAX_PIECES = 40 // eaten pieces drawn per zone at most
 
// A zone between two prices: played from `liqLookback` candles back - every candle takes the prices it
// touched out of the parts still untouched (drawn up to that candle), the rest reaches past the newest
// candle with "Liq" at its right end. Faint fill, no border, like the app's.
drawLiq(float pa, float pb, color ink) =>
    if pa > 0 and pb > 0 and pa != pb
        float top = math.max(pa, pb)
        float bot = math.min(pa, pb)
        int last = bar_index
        int start = math.max(0, last - liqLookback + 1)
        array<float> uLo = array.from(bot) // the untouched parts
        array<float> uHi = array.from(top)
        array<float> eLo = array.new<float>() // the eaten pieces and the candle that ate them
        array<float> eHi = array.new<float>()
        array<int> eAt = array.new<int>()
        int eatenAt = na
        for k = start to last
            float ch = H.get(k)
            float cl = L.get(k)
            array<float> nLo = array.new<float>()
            array<float> nHi = array.new<float>()
            for [i, lo] in uLo
                float hi = uHi.get(i)
                if cl > hi or ch < lo
                    nLo.push(lo)
                    nHi.push(hi)
                else
                    if eAt.size() < LIQ_MAX_PIECES
                        eLo.push(math.max(lo, cl))
                        eHi.push(math.min(hi, ch))
                        eAt.push(k)
                    if lo < cl
                        nLo.push(lo)
                        nHi.push(cl)
                    if hi > ch
                        nLo.push(ch)
                        nHi.push(hi)
            uLo := nLo
            uHi := nHi
            if uLo.size() == 0
                eatenAt := k
                break
        if na(eatenAt) or last - eatenAt <= LIQ_LINGER
            color fill = color.new(ink, 87)
            for [i, lo] in eLo
                box.new(start, eHi.get(i), math.max(eAt.get(i), start + 1), lo, xloc = xloc.bar_index, border_color = NONE, bgcolor = fill)
            float bigLo = na
            float bigHi = na
            for [i, lo] in uLo
                float hi = uHi.get(i)
                box.new(start, hi, last + LIQ_REACH, lo, xloc = xloc.bar_index, border_color = NONE, bgcolor = fill)
                if na(bigLo) or hi - lo > bigHi - bigLo
                    bigLo := lo
                    bigHi := hi
            if not na(bigLo)
                label.new(last + LIQ_REACH, (bigLo + bigHi) / 2, "Liq", xloc = xloc.bar_index, style = label.style_label_left, color = NONE, textcolor = ink, size = size.small)
 
// ---------------------------------------------------------------- run (on the newest candle only)
var table status = table.new(position.top_right, 1, 4)
 
statusRow(int row, bool on, Geo g, string name, color ink, string none) =>
    if showStatus
        if not on
            table.cell(status, 0, row, "")
        else
            table.cell(status, 0, row, name + " · " + (na(g) ? none : stateOf(g)), text_color = na(g) ? color.gray : ink, text_size = size.small, bgcolor = color.new(color.black, 80), text_halign = text.align_left)
 
if barstate.islast
    clearAll()
    // The liquidation zones first: behind everything else.
    if liqOn1
        drawLiq(liqA1, liqB1, liqC1)
    if liqOn2
        drawLiq(liqA2, liqB2, liqC2)
    if liqOn3
        drawLiq(liqA3, liqB3, liqC3)
    if liqOn4
        drawLiq(liqA4, liqB4, liqC4)
    if liqOn5
        drawLiq(liqA5, liqB5, liqC5)
    if liqOn6
        drawLiq(liqA6, liqB6, liqC6)
    if liqOn7
        drawLiq(liqA7, liqB7, liqC7)
    if liqOn8
        drawLiq(liqA8, liqB8, liqC8)
    Cs ch = Cs.new(O, H, L, C, T, CHART_MS, false)
    Cs wk = ch
    if timeframe.in_seconds() < 7 * 86400
        [wo, wh, wl, wc, wt] = request.security(syminfo.tickerid, "1W", weeklyCandles(), lookahead = barmerge.lookahead_off)
        if 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()
            // This week from the chart's own candles (the weekly one may not be up to date yet).
            int weekStart = time("1W")
            while t2.size() > 0 and t2.last() >= weekStart
                o2.pop()
                h2.pop()
                l2.pop()
                c2.pop()
                t2.pop()
            int s = idxAtOrAfter(ch, weekStart)
            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(weekStart)
            wk := Cs.new(o2, h2, l2, c2, t2, WEEK_MS, true)
    // Long 2 lies after Short's 0, Short 2 after Long 2's: those found for them even when not shown.
    Geo gL = onL ? findKind(ch, wk, true, na, na) : na
    Geo gS = onS or onL2 or onS2 ? findKind(ch, wk, false, na, na) : na
    Geo gL2 = na
    if (onL2 or onS2) and not na(gS)
        gL2 := findKind(ch, wk, true, zeroEndOf(gS), zeroTimeOf(gS))
    // The low after the ATH is the all-time low: the dark green one - not drawn twice.
    bool sameL2 = false
    if not na(gL2)
        int iLow = extremeFrom(wk, 0, true)
        if iLow >= 0
            float atl = math.min(wk.l.get(iLow), L.get(extremeFrom(ch, 0, true)))
            sameL2 := math.abs(gL2.zero.price - atl) <= math.abs(atl) * 1e-9
    Geo gS2 = na
    if onS2 and not na(gL2)
        gS2 := findKind(ch, wk, false, zeroEndOf(gL2), zeroTimeOf(gL2))
    // The larger ones first: the nested ones lie over them.
    if onL and not na(gL)
        drawGeo(gL, colL)
    if onS and not na(gS)
        drawGeo(gS, colS)
    if onL2 and not na(gL2) and not sameL2
        drawGeo(gL2, colL2)
    if onS2 and not na(gS2)
        drawGeo(gS2, colS2)
    // The all-time high: from its candle (the chart's when it reaches back that far, else its week) to the newest.
    if showAth
        int iw = extremeFrom(wk, 0, false)
        if iw >= 0
            float athPrice = wk.h.get(iw)
            int athTime = wk.t.get(iw)
            int ic = extremeFrom(ch, 0, false)
            if T.get(0) <= athTime or H.get(ic) >= athPrice
                athPrice := math.max(athPrice, H.get(ic))
                athTime := T.get(ic)
            line.new(athTime, athPrice, time, athPrice, xloc = xloc.bar_time, color = colAth, width = 1)
            label.new(time, athPrice, "ATH " + str.tostring(athPrice, format.mintick), xloc = xloc.bar_time, style = label.style_label_left, color = NONE, textcolor = colAth, size = size.small)
    // Shown ones only (Short is found for Long 2 / Short 2 even when off).
    Geo shS = na
    if onS
        shS := gS
    Geo shL2 = na
    if onL2 and not sameL2
        shL2 := gL2
    statusRow(0, onL, gL, "Long (ATL)", colL, "none open")
    statusRow(1, onS, shS, "Short (ATH)", colS, "none open")
    statusRow(2, onL2, shL2, "Long 2", colL2, sameL2 ? "= Long" : "none open")
    statusRow(3, onS2, gS2, "Short 2", colS2, "none open")
    alertsFor(gL, 0, "Long (ATL)")
    alertsFor(shS, 1, "Short (ATH)")
    alertsFor(shL2, 2, "Long 2")
    alertsFor(gS2, 3, "Short 2")
 
// ---------------------------------------------------------------- moving averages
// Both computed on every candle (Pine's ta functions need that), the picked type shown.
maOf(string typ, int len) =>
    float e = ta.ema(close, len)
    float m = ta.sma(close, len)
    typ == "EMA" ? e : m
plot(ma1On ? maOf(ma1Type, ma1Len) : na, "MA 1", ma1Col, ma1W)
plot(ma2On ? maOf(ma2Type, ma2Len) : na, "MA 2", ma2Col, ma2W)
plot(ma3On ? maOf(ma3Type, ma3Len) : na, "MA 3", ma3Col, ma3W)
plot(ma4On ? maOf(ma4Type, ma4Len) : na, "MA 4", ma4Col, ma4W)

← 返回列表