Hosoda Waves with Price Targets [Saikix]

Saikix · study · 750 行 · 点赞 37 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// Hosoda Waves with Price Targets [Saikix]
// © Saikix
 
//@version=6
indicator("Hosoda Waves with Price Targets [Saikix]", shorttitle="Saikix-Nehaba", overlay=true, max_lines_count=500, max_labels_count=500, max_bars_back=2200, behind_chart=false)
 
G1 = "Basic settings"
swingLen = input.int(12, "Swing length", minval=2, maxval=50, group=G1, display=display.none,
     tooltip="A swing high is a high with no higher high this many bars before and after it (a swing low the same way), so a swing is confirmed this many bars after it. Swings closer than 0.8 × ATR(14) to the previous swing are ignored. 12 is the same as Ichimoku Cloud [Saikix].")
tfIn = input.timeframe("", "Timeframe", group=G1, display=display.none,
     tooltip="Empty = chart timeframe. A higher timeframe uses its closed bars only, so its swings and targets do not change while its bar is forming. A timeframe below the chart's uses the chart's.")
lookback = input.int(1000, "Lookback (bars)", minval=100, maxval=2000, group=G1, display=display.none,
     tooltip="How far back swings and waves are drawn, in bars of the timeframe above.")
distUnit = input.string("Auto", "Distance unit", options=["Auto", "Pips", "Absolute", "Percent"], group=G1, display=display.none,
     tooltip="How wave sizes are shown. Auto: pips on forex and metals, percent on other markets. Absolute: price difference. Percent: of the price where the wave started.")
 
G2 = "Waves"
showWave = input.bool(true, "Show wave lines", inline="wv", group=G2, display=display.none)
upCol = input.color(#089981, "", inline="wv", group=G2, display=display.none)
dnCol = input.color(#F23645, "", inline="wv", group=G2, display=display.none)
waveW = input.int(2, "", minval=1, maxval=4, inline="wv", group=G2, display=display.none, active=showWave,
     tooltip="Lines from swing to swing. Colors (rise, drop) and width. The colors are also used for the wave sizes.")
showLbl = input.bool(true, "Show wave sizes", group=G2, display=display.none,
     tooltip="The size of the latest waves at their ends, e.g. 87.0 pips: the last two confirmed waves (A to B and B to C when an N wave is in place) and the forming wave. Earlier waves are lines only, except the waves of earlier N waves kept by Past N waves to show. Hover a size for the details.")
showRatio = input.bool(true, "Show ratio to the prior wave in the same direction", group=G2, display=display.none, active=showLbl,
     tooltip="How many times the size of the previous wave in the same direction: a rise against the previous rise, a drop against the previous drop (not the wave just before it). e.g. 1.32× = 1.32 times the previous rise. 1.00× = the same size. On the forming wave from C of an N wave, the previous rise is A to B, so 1.00× is the N target.")
showBars = input.bool(false, "Show bar counts", group=G2, display=display.none, active=showLbl,
     tooltip="How many bars each wave took, counted Ichimoku style: the start bar is bar 1.")
showForm = input.bool(true, "Show forming wave", group=G2, display=display.none,
     tooltip="A dashed line from the last confirmed swing to the highest high or lowest low since, with its size marked (forming). It moves until the next swing is confirmed. The last swing itself can still move to a higher high (lower low) until a swing in the other direction is confirmed. Earlier waves stay as drawn.")
 
G3 = "Price targets"
showTgt = input.bool(true, "Show price targets", inline="tg", group=G3, display=display.none)
tgtCol = input.color(#2962FF, "", inline="tg", group=G3, display=display.none, active=showTgt)
tgtW = input.int(2, "", minval=1, maxval=4, inline="tg", group=G3, display=display.none, active=showTgt,
     tooltip="Drawn when an N wave forms: a rise A to B, a pullback B to C that stays above A, and C confirmed as a swing low (the reverse for a fall). Not drawn for converging (P) or widening (Y) swings.\nV = B + (B − C)\nN = C + (B − A)\nE = B + (B − A)\nNT = C + (C − A)\nMain target (solid line): N when the pullback B to C is less than half of A to B, V otherwise.\nThe targets stay while the third wave is in progress, until the next swing is confirmed.\nColor, and width of the main target.")
tgtSet = input.string("All", "Targets", options=["All", "Main"], group=G3, display=display.none, active=showTgt,
     tooltip="All: V, N, E and NT. Main: only the main target.")
showABC = input.bool(true, "Show A, B and C", group=G3, display=display.none, active=showTgt,
     tooltip="Letters on the three swings the targets come from, and thicker wave lines from A to B and B to C.")
pastN = input.int(0, "Past N waves to show", minval=0, maxval=10, group=G3, display=display.none, active=showTgt,
     tooltip="Keeps earlier N waves whose third wave has ended (the next swing was confirmed), each drawn until its third wave ended, with the sizes of its three waves. A line stops where price reached it. 0 = only the N wave in progress.")
 
G4 = "Text"
txtSize = input.int(13, "Text size", minval=8, maxval=30, group=G4, display=display.none)
 
G5 = "Alerts"
alOn = input.bool(true, "Alerts", group=G5, display=display.none,
     tooltip="One alert for everything checked here: create the alert with \"Any alert() function call\". Swing confirmed, N wave formed and C broken are checked on closed bars and sent right after the bar closes. Target reached, Target approaching and Forming wave reached the ratio are sent the moment price gets there. Never sent on past bars. Independent of what is shown on the chart.\nFor a separate alert (or webhook) per event, pick the event in the alert's Condition list instead, e.g. \"Main target reached\".")
alDir = input.string("Both", "Directions to alert", options=["Both", "Up", "Down"], group=G5, display=display.none, active=alOn,
     tooltip="Up: rising N waves and their targets, swing highs (HH, LH), rising waves. Down: the reverse. Both: all of them.")
alSwing = input.bool(false, "Swing confirmed", group=G5, display=display.none, active=alOn,
     tooltip="A new swing high or swing low was confirmed (Swing length bars after it), compared with the previous swing of the same kind: HH (higher high), LH (lower high), HL (higher low), LL (lower low).")
alSwTyp = input.string("All", "Swings to alert", options=["All", "HH and HL", "LH and LL", "HH", "LH", "HL", "LL"], group=G5, display=display.none, active=alOn and alSwing,
     tooltip="All: every confirmed swing. HH and HL: swings higher than the previous ones. LH and LL: swings lower than the previous ones. Or one kind. A swing with no earlier swing of the same kind to compare is sent with All only.")
alFormed = input.bool(true, "N wave formed", group=G5, display=display.none, active=alOn,
     tooltip="A, B and C are in place and the targets are drawn.")
alReach = input.bool(true, "Target reached", group=G5, display=display.none, active=alOn,
     tooltip="Price touched a target of the latest N wave for the first time. Targets already reached before the bar the N wave formed on are not sent.")
alNear = input.bool(false, "Target approaching", group=G5, display=display.none, active=alOn,
     tooltip="Price came within the approach distance of a target of the latest N wave for the first time, before reaching it. Not sent when price gets there and reaches the target on the same bar (Target reached is sent instead), or when it was already that close before the bar the N wave formed on.")
nearPct = input.float(10.0, "Approach distance (% of A to B)", minval=1.0, maxval=50.0, step=1.0, group=G5, display=display.none, active=alOn and alNear,
     tooltip="How close counts as approaching, as a percentage of the wave A to B. 10 = within one tenth of A to B from the target.")
alTgt = input.string("Main", "Targets to alert", options=["Main", "All", "V", "N", "E", "NT"], group=G5, display=display.none, active=alOn and (alReach or alNear),
     tooltip="For Target reached and Target approaching. Main: the main target only (N or V). All: V, N, E and NT. Or one target.")
alBrk = input.bool(true, "C broken", group=G5, display=display.none, active=alOn,
     tooltip="A bar closed below C (above C for a falling N wave). The target lines are removed and a gray line at C is marked C broken.")
alForm = input.bool(false, "Forming wave reached the ratio", group=G5, display=display.none, active=alOn,
     tooltip="The forming wave grew to the ratio below of the previous wave in the same direction. A forming wave starts when the swing it starts from is confirmed (Swing length bars later); if it is already past the ratio then, it is not sent. On the forming wave from C of an N wave, the previous wave is A to B, so 1.00 is the N target.")
formRatio = input.float(1.0, "Ratio (× the prior wave)", minval=0.1, maxval=5.0, step=0.05, group=G5, display=display.none, active=alOn and alForm,
     tooltip="e.g. 1.00 = as large as the previous wave in the same direction. 0.50 = half of it.")
alFmt = input.string("Text", "Message format", options=["Text", "JSON"], group=G5, display=display.none, active=alOn,
     tooltip="JSON is for webhooks: indicator, ticker, chart_tf, tf, price and a list of events.")
 
float SWING_MIN_ATR = 0.8
float TARGET_RETRACE_SPLIT = 0.5
int   MAX_PIV = 150
int   PS = 4
int   FS = 8
int   KS = 19
float LBL_FRAC = 0.04
 
COL_GRAY = #787B86
COL_NONE = color.new(color.white, 100)
 
isPipMarket() =>
    string s = str.upper(syminfo.ticker)
    syminfo.type == "forex" or str.contains(s, "XAU") or str.contains(s, "GOLD") or str.contains(s, "XAG") or str.contains(s, "SILVER")
pipUnit() =>
    string s = str.upper(syminfo.ticker)
    str.contains(s, "JPY") ? 0.01 : str.contains(s, "XAU") or str.contains(s, "GOLD") ? 0.1 : str.contains(s, "XAG") or str.contains(s, "SILVER") ? 0.01 : str.contains(s, "BTC") or str.contains(s, "ETH") ? 1.0 : syminfo.type == "forex" ? 0.0001 : syminfo.mintick
bool   pipMkt    = isPipMarket()
string unitShown = distUnit == "Auto" ? (pipMkt ? "Pips" : "Percent") : distUnit
fmtSize(float d, float base) =>
    unitShown == "Pips" ? str.tostring(math.round(d / pipUnit(), 1), "#0.0") + " pips" : unitShown == "Percent" ? str.tostring(base != 0 ? d / base * 100.0 : 0.0, "#0.00") + "%" : str.tostring(d, format.mintick)
fmtP(float p) => str.tostring(p, format.mintick)
tfLabel(string tf) =>
    int sec = timeframe.in_seconds(tf)
    sec < 3600 ? str.tostring(math.round(sec / 60.0), "#") + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600.0), "#") + "h" : sec < 604800 ? "D" : sec < 2419200 ? "W" : "M"
 
string tfChosen = tfIn == "" ? timeframe.period : tfIn
string tfUse = timeframe.in_seconds(tfChosen) < timeframe.in_seconds(timeframe.period) ? timeframe.period : tfChosen
bool   htf = tfUse != timeframe.period
string tfPre = htf ? tfLabel(tfUse) + " " : ""
 
isPY(array<float> zp, array<bool> zh, int j) =>
    bool res = false
    if zp.size() >= j + 5
        array<float> hs = array.new<float>()
        array<float> ls = array.new<float>()
        for i = j to j + 4
            if zh.get(i)
                if hs.size() < 3
                    hs.push(zp.get(i))
            else
                if ls.size() < 3
                    ls.push(zp.get(i))
        if hs.size() >= 2 and ls.size() >= 2
            bool highsDown = hs.get(0) < hs.get(1)
            bool highsUp = hs.get(0) > hs.get(1)
            bool lowsUp = ls.get(0) > ls.get(1)
            bool lowsDown = ls.get(0) < ls.get(1)
            if hs.size() >= 3
                highsDown := highsDown and hs.get(1) < hs.get(2)
                highsUp := highsUp and hs.get(1) > hs.get(2)
            if ls.size() >= 3
                lowsUp := lowsUp and ls.get(1) > ls.get(2)
                lowsDown := lowsDown and ls.get(1) < ls.get(2)
            res := (highsDown and lowsUp) or (highsUp and lowsDown)
    res
 
pushLeg(array<float> F, float x0, float y0, float x1, float y1, float prior, int bars, bool up, bool labeled) =>
    F.push(x0)
    F.push(y0)
    F.push(x1)
    F.push(y1)
    F.push(prior)
    F.push(bars)
    F.push(up ? 1.0 : 0.0)
    F.push(labeled ? 1.0 : 0.0)
 
engine(int sw, int lb, int nPast, float nearF) =>
    float atrMT = ta.sma(ta.tr(true), 14)
    float hhW = ta.highest(high, 2 * sw + 1)
    float llW = ta.lowest(low, 2 * sw + 1)
 
    bool cH = not na(hhW) and high[sw] >= hhW
    bool cL = not na(llW) and low[sw] <= llW
    array<float> P = na
    array<float> F = na
    array<float> K = na
    if bar_index >= last_bar_index - 1
        P := array.new<float>()
        F := array.new<float>()
        K := array.new<float>()
 
        array<float> zp = array.new<float>()
        array<int> zo = array.new<int>()
        array<bool> zh = array.new<bool>()
        int scanMax = math.min(lb + sw, bar_index - sw)
        if scanMax > sw + 1
            for i = sw + 1 to scanMax
                bool isH = cH[i - sw]
                bool isL = cL[i - sw]
                if isH != isL
                    float price = isH ? high[i] : low[i]
                    int n = zp.size()
                    bool skip = false
                    if n > 0 and zh.get(n - 1) == isH
                        bool more = isH ? price > zp.get(n - 1) : price < zp.get(n - 1)
                        if more
                            zp.set(n - 1, price)
                            zo.set(n - 1, i)
                        skip := true
                    if not skip and n > 0
                        float a = atrMT[i]
                        if a > 0 and math.abs(price - zp.get(n - 1)) < a * SWING_MIN_ATR
                            skip := true
                    if not skip
                        if n >= MAX_PIV
                            break
                        zp.push(price)
                        zo.push(i)
                        zh.push(isH)
        int np = zp.size()
        if np > 0
            for k = np - 1 to 0
                int o = zo.get(k)
                P.push(zp.get(k))
                P.push(time[o])
                P.push(zh.get(k) ? 1.0 : 0.0)
                P.push(bar_index - o)
 
        if np >= 2
            int o0 = zo.get(0)
            float p0 = zp.get(0)
            bool h0 = zh.get(0)
            float mx = na
            int omx = na
            float mn = na
            int omn = na
            for o = o0 - 1 to 0
                if na(mx) or high[o] > mx
                    mx := high[o]
                    omx := o
                if na(mn) or low[o] < mn
                    mn := low[o]
                    omn := o
            bool exceeded = h0 ? mx > p0 : mn < p0
            if not exceeded
 
                float e = h0 ? mn : mx
                int oe = h0 ? omn : omx
                float prior = np >= 3 ? math.abs(zp.get(1) - zp.get(2)) : na
                pushLeg(F, time[o0], p0, time[oe], e, prior, o0 - oe + 1, not h0, true)
            else
 
                int o1 = zo.get(1)
                float p1 = zp.get(1)
                float e1 = h0 ? mx : mn
                int oe1 = h0 ? omx : omn
                float prior1 = np >= 4 ? math.abs(zp.get(2) - zp.get(3)) : na
                if oe1 > 0
 
                    float e2 = na
                    int oe2 = na
                    for o = oe1 - 1 to 0
                        float v = h0 ? low[o] : high[o]
                        if na(e2) or (h0 ? v < e2 : v > e2)
                            e2 := v
                            oe2 := o
                    float prior2 = np >= 3 ? math.abs(zp.get(1) - zp.get(2)) : na
                    pushLeg(F, time[o1], p1, time[oe1], e1, prior1, o1 - oe1 + 1, h0, false)
                    pushLeg(F, time[oe1], e1, time[oe2], e2, prior2, oe1 - oe2 + 1, not h0, true)
                else
                    pushLeg(F, time[o1], p1, time[oe1], e1, prior1, o1 - oe1 + 1, h0, true)
 
        if np >= 3
            int nOld = 0
            for j = 0 to np - 3
 
                if j > 0 and nOld >= nPast
                    break
                bool cLow = not zh.get(j)
                float C = zp.get(j)
                float B = zp.get(j + 1)
                float A = zp.get(j + 2)
                bool up = cLow and C > A
                bool dn = not cLow and C < A
                float legAB = math.abs(B - A)
                if (up or dn) and legAB > 0 and not isPY(zp, zh, j)
                    int oA = zo.get(j + 2)
                    int oB = zo.get(j + 1)
                    int oC = zo.get(j)
                    float tV = B + (B - C)
                    float tN = C + (B - A)
                    float tE = B + (B - A)
                    float tNT = C + (C - A)
                    bool mainN = math.abs(B - C) / legAB < TARGET_RETRACE_SPLIT
                    int status = j == 0 ? 0 : 1
                    int oEnd = j == 0 ? 0 : zo.get(j - 1)
 
                    int lastClosed = j == 0 ? 1 : oEnd
                    if oC - 1 >= lastClosed
                        for o = oC - 1 to lastClosed
                            if (up and close[o] < C) or (dn and close[o] > C)
                                status := 2
                                oEnd := o
                                break
 
                    float rV = na
                    float rN = na
                    float rE = na
                    float rNT = na
 
                    float dN = legAB * nearF
                    float nV = na
                    float nN = na
                    float nE = na
                    float nNT = na
                    for o = oC - 1 to oEnd
                        float hi = high[o]
                        float lo = low[o]
                        if na(nV) and (up ? hi >= tV - dN : lo <= tV + dN)
                            nV := time[o]
                        if na(nN) and (up ? hi >= tN - dN : lo <= tN + dN)
                            nN := time[o]
                        if na(nE) and (up ? hi >= tE - dN : lo <= tE + dN)
                            nE := time[o]
                        if na(nNT) and (up ? hi >= tNT - dN : lo <= tNT + dN)
                            nNT := time[o]
                        if na(rV) and (up ? hi >= tV : lo <= tV)
                            rV := time[o]
                        if na(rN) and (up ? hi >= tN : lo <= tN)
                            rN := time[o]
                        if na(rE) and (up ? hi >= tE : lo <= tE)
                            rE := time[o]
                        if na(rNT) and (up ? hi >= tNT : lo <= tNT)
                            rNT := time[o]
                    K.push(A)
                    K.push(B)
                    K.push(C)
                    K.push(time[oA])
                    K.push(time[oB])
                    K.push(time[oC])
                    K.push(up ? 1.0 : 0.0)
                    K.push(mainN ? 1.0 : 0.0)
                    K.push(status)
                    K.push(status == 0 ? na : time[oEnd])
                    K.push(rV)
                    K.push(rN)
                    K.push(rE)
                    K.push(rNT)
                    K.push(j > 0 and status == 1 ? zp.get(j - 1) : na)
                    K.push(nV)
                    K.push(nN)
                    K.push(nE)
                    K.push(nNT)
                    if j > 0
                        nOld += 1
    [P, F, K]
 
[P, F, K] = request.security(syminfo.tickerid, tfUse, engine(swingLen, lookback, showTgt ? pastN : 0, nearPct / 100.0), lookahead=barmerge.lookahead_off)
 
[tCurBar, tPrevBar] = request.security(syminfo.tickerid, tfUse, [time, time[1]], lookahead=barmerge.lookahead_off)
 
waveText(string letter, float size, float base, float prior, int bars, bool up, bool forming) =>
    string s1 = (letter != "" ? letter + " · " : "") + fmtSize(size, base) + (showBars ? " · " + str.tostring(bars) + " bars" : "") + (forming ? " (forming)" : "")
 
    string s2 = showRatio and not na(prior) and prior > 0 ? str.tostring(size / prior, "#0.00") + "×" : ""
    s2 == "" ? s1 : s1 + "\n" + s2
waveTip(float p0, float p1, float size, float prior, int bars, bool up) =>
    string w = up ? "rise" : "drop"
    string head = (up ? "Rise" : "Drop") + " from " + fmtP(p0) + " to " + fmtP(p1) + ": " + fmtSize(size, p0) + ", " + str.tostring(bars) + " bars (the start bar counted as 1)."
    head + (not na(prior) and prior > 0 ? "\n" + str.tostring(size / prior, "#0.00") + "× the previous " + w + " (" + fmtSize(prior, p0) + ")." : "")
tgtCode(int k) => k == 0 ? "V" : k == 1 ? "N" : k == 2 ? "E" : "NT"
tgtFormula(int k) => k == 0 ? "V = B + (B − C)" : k == 1 ? "N = C + (B − A)" : k == 2 ? "E = B + (B − A)" : "NT = C + (C − A)"
tgtName(int k, bool isMain) => isMain ? "Main target (" + tgtCode(k) + ")" : tgtCode(k) + " target"
 
float rng200 = ta.highest(high, 200) - ta.lowest(low, 200)
 
var array<line> lns = array.new<line>()
var array<label> lbs = array.new<label>()
float psV = na
float psN = na
float psE = na
float psNT = na
 
if barstate.islast
    for l in lns
        l.delete()
    lns.clear()
    for b in lbs
        b.delete()
    lbs.clear()
    int nP = na(P) ? 0 : P.size() / PS
    int nK = na(K) ? 0 : K.size() / KS
    bool hasPat = showTgt and nK > 0
    float lA = hasPat ? K.get(3) : na
    float lB = hasPat ? K.get(4) : na
    float lC = hasPat ? K.get(5) : na
 
    if nP >= 2
        for k = 1 to nP - 1
            float p0 = P.get((k - 1) * PS)
            float t0 = P.get((k - 1) * PS + 1)
            float b0 = P.get((k - 1) * PS + 3)
            float p1 = P.get(k * PS)
            float t1 = P.get(k * PS + 1)
            bool h1 = P.get(k * PS + 2) == 1.0
            float b1 = P.get(k * PS + 3)
            bool up = p1 > p0
            color wc = up ? upCol : dnCol
            bool abLeg = showABC and hasPat and ((t0 == lA and t1 == lB) or (t0 == lB and t1 == lC))
            if showWave
                lns.push(line.new(int(t0), p0, int(t1), p1, xloc=xloc.bar_time, color=wc, width=abLeg ? waveW + 1 : waveW))
            string letter = showABC and hasPat ? (t1 == lA ? "A" : t1 == lB ? "B" : t1 == lC ? "C" : "") : ""
            bool inPat = false
            if nK > 0 and k < nP - 2
                for q = 0 to nK - 1
                    float qB = K.get(q * KS + 4)
                    float qC = K.get(q * KS + 5)
                    if t1 == qB or t1 == qC or t0 == qC
                        inPat := true
                        break
            bool sized = showLbl and (k >= nP - 2 or inPat)
            if sized or letter != ""
                float size = math.abs(p1 - p0)
                float prior = k >= 3 ? math.abs(P.get((k - 2) * PS) - P.get((k - 3) * PS)) : na
                int bars = int(b1 - b0) + 1
                string txt = sized ? waveText(letter, size, p0, prior, bars, up, false) : letter
                lbs.push(label.new(int(t1), p1, txt, xloc=xloc.bar_time, style=h1 ? label.style_label_down : label.style_label_up, color=COL_NONE, textcolor=wc, size=txtSize, tooltip=waveTip(p0, p1, size, prior, bars, up)))
 
    int nF = na(F) ? 0 : F.size() / FS
    if showForm and nF > 0
        for f = 0 to nF - 1
            float x0 = F.get(f * FS)
            float y0 = F.get(f * FS + 1)
            float x1 = F.get(f * FS + 2)
            float y1 = F.get(f * FS + 3)
            float prior = F.get(f * FS + 4)
            int bars = int(F.get(f * FS + 5))
            bool up = F.get(f * FS + 6) == 1.0
            bool lab = F.get(f * FS + 7) == 1.0
            color wc = up ? upCol : dnCol
            if showWave and x1 > x0
                lns.push(line.new(int(x0), y0, int(x1), y1, xloc=xloc.bar_time, color=wc, style=line.style_dashed, width=waveW))
            if showLbl and lab and x1 > x0
                float size = math.abs(y1 - y0)
 
                string nTip = nK > 0 and K.get(8) == 0.0 and x0 == K.get(5) ? "\nAt 1.00× it reaches the N target " + fmtP(K.get(2) + (K.get(1) - K.get(0))) + "." : ""
                lbs.push(label.new(int(x1), y1, waveText("", size, y0, prior, bars, up, true), xloc=xloc.bar_time, style=up ? label.style_label_down : label.style_label_up, color=COL_NONE, textcolor=wc, size=txtSize,
                     tooltip="Forming: " + waveTip(y0, y1, size, prior, bars, up) + nTip + "\nIt moves until the next swing is confirmed."))
 
    if hasPat
        float thr = rng200 * LBL_FRAC
        float barMs = timeframe.in_seconds(tfUse) * 1000.0
        for q = 0 to nK - 1
            int base = q * KS
            float A = K.get(base)
            float B = K.get(base + 1)
            float C = K.get(base + 2)
            float tB = K.get(base + 4)
            float tC = K.get(base + 5)
            bool up = K.get(base + 6) == 1.0
            bool mainN = K.get(base + 7) == 1.0
            int status = int(K.get(base + 8))
            float tEnd = K.get(base + 9)
            float pD = K.get(base + 14)
            bool past = q > 0
            color baseCol = status == 2 ? COL_GRAY : tgtCol
            color col = past ? color.new(baseCol, 45) : baseCol
            array<float> vals = array.from(B + (B - C), C + (B - A), B + (B - A), C + (C - A))
 
            array<int> lx = array.new<int>()
            array<float> ly = array.new<float>()
            array<string> lt = array.new<string>()
            array<bool> lm = array.new<bool>()
            array<bool> li = array.new<bool>()
            for k = 0 to 3
                bool isMain = (k == 1 and mainN) or (k == 0 and not mainN)
 
                if (tgtSet == "Main" and not isMain) or status == 2
                    continue
                float v = vals.get(k)
                float r = K.get(base + 10 + k)
                float tStart = k == 0 or k == 2 ? tB : tC
                bool reached = not na(r)
                bool live = status == 0 and not reached
                int x2 = live ? time : int(reached ? r : tEnd)
                lns.push(line.new(int(tStart), v, x2, v, xloc=xloc.bar_time, extend=live ? extend.right : extend.none, color=col, style=isMain ? line.style_solid : line.style_dashed, width=isMain ? tgtW : 1))
 
                bool inBC = up ? v < B : v > B
                int labX = live ? time : reached ? (inBC ? int(r + barMs) : int(r - barMs)) : (not na(pD) and math.abs(v - pD) < 2 * thr ? int(tStart) : int(tEnd - barMs))
                lx.push(labX)
                li.push(reached and inBC)
                ly.push(v)
                lt.push(tfPre + tgtName(k, isMain) + (reached ? " · Reached" : ""))
                lm.push(isMain)
                if q == 0 and live
                    if k == 0
                        psV := v
                    else if k == 1
                        psN := v
                    else if k == 2
                        psE := v
                    else
                        psNT := v
 
            int nL = lx.size()
            array<bool> used = array.new<bool>(nL, false)
            if nL > 0
                for i = 0 to nL - 1
                    if used.get(i)
                        continue
                    string txt = lt.get(i)
                    float y = ly.get(i)
                    bool m = lm.get(i)
                    float hiY = y
                    float loY = y
                    if i < nL - 1
                        for jj = i + 1 to nL - 1
                            if not used.get(jj) and lx.get(jj) == lx.get(i) and math.abs(ly.get(jj) - y) < thr
                                used.set(jj, true)
                                txt := ly.get(jj) > y ? lt.get(jj) + " / " + txt : txt + " / " + lt.get(jj)
                                m := m or lm.get(jj)
                                hiY := math.max(hiY, ly.get(jj))
                                loY := math.min(loY, ly.get(jj))
                    string tip = ""
                    for k = 0 to 3
                        tip := tip + (k == 0 ? "" : "\n") + tgtFormula(k) + " = " + fmtP(vals.get(k))
                    tip := (up ? "Upside targets of the rising N wave A " : "Downside targets of the falling N wave A ") + fmtP(A) + " · B " + fmtP(B) + " · C " + fmtP(C) + "\n" + tip + "\nMain target: " + (mainN ? "N (the pullback B to C is less than half of A to B)" : "V (the pullback B to C is half of A to B or more)") + (status == 2 ? "\nC broken: a bar closed beyond C, so these targets no longer apply." : status == 1 ? "\nThe third wave has ended (the next swing is confirmed)." : "")
                    bool inner = li.get(i)
                    string sty = inner ? (up ? label.style_label_upper_left : label.style_label_lower_left) : (up ? label.style_label_lower_right : label.style_label_upper_right)
                    lbs.push(label.new(lx.get(i), inner ? y : (up ? hiY : loY), txt, xloc=xloc.bar_time, style=sty, color=m ? col : COL_NONE, textcolor=m ? color.white : col, size=txtSize, tooltip=tip))
 
            if status == 2
                lns.push(line.new(int(tC), C, int(tEnd), C, xloc=xloc.bar_time, color=col, style=line.style_dashed, width=1))
 
                lbs.push(label.new(int(tEnd), C, "C broken", xloc=xloc.bar_time, style=up ? label.style_label_upper_left : label.style_label_lower_left, color=col, textcolor=color.white, size=txtSize,
                     tooltip="A bar closed " + (up ? "below" : "above") + " C " + fmtP(C) + ", so the targets of this N wave (A " + fmtP(A) + " · B " + fmtP(B) + " · C " + fmtP(C) + ") no longer apply. If a new swing " + (up ? "low" : "high") + " is confirmed and it stays " + (up ? "above" : "below") + " A, it becomes the new C."))
 
plot(psV, "V target", color=tgtCol, display=display.price_scale, editable=false, show_last=1)
plot(psN, "N target", color=tgtCol, display=display.price_scale, editable=false, show_last=1)
plot(psE, "E target", color=tgtCol, display=display.price_scale, editable=false, show_last=1)
plot(psNT, "NT target", color=tgtCol, display=display.price_scale, editable=false, show_last=1)
 
var bool  sInit = false
var float sPivT = na
var float sPivP = na
var bool  sPivH = false
var string sSwTyp = ""
var float sPatC = na
var bool  sR0 = false
var bool  sR1 = false
var bool  sR2 = false
var bool  sR3 = false
var bool  sN0 = false
var bool  sN1 = false
var bool  sN2 = false
var bool  sN3 = false
var int   sStat = 0
var float sFormT = na
var bool  sFormHit = false
 
bool evSwH = false
bool evSwL = false
bool evUpN = false
bool evDnN = false
bool evBrk = false
bool evForm = false
array<bool> evR = array.new<bool>(4, false)
array<bool> evNr = array.new<bool>(4, false)
bool curUp = false
bool curMainN = false
float cA = na
float cB = na
float cC = na
array<float> cVals = array.new<float>(4, na)
float swP = na
float swPrev = na
string swTyp = ""
float fRatio = na
float fPrior = na
bool fUp = false
 
if barstate.islast
    int nP = na(P) ? 0 : P.size() / PS
    int nK = na(K) ? 0 : K.size() / KS
    int nF = na(F) ? 0 : F.size() / FS
 
    if nP > 0
        float lp = P.get((nP - 1) * PS)
        float lt = P.get((nP - 1) * PS + 1)
        bool lh = P.get((nP - 1) * PS + 2) == 1.0
 
        string typ = ""
        float prv = na
        if nP >= 3
            prv := P.get((nP - 3) * PS)
            typ := lh ? (lp > prv ? "HH" : "LH") : (lp < prv ? "LL" : "HL")
 
        if sInit and (lt != sPivT or lp != sPivP) and (lh != sPivH or typ != sSwTyp)
            evSwH := lh
            evSwL := not lh
            swP := lp
            swPrev := prv
            swTyp := typ
        sPivT := lt
        sPivP := lp
        sPivH := lh
        sSwTyp := typ
 
    bool hasCur = nK > 0 and K.get(8) != 1.0
    if hasCur
        float tC = K.get(5)
        int st = int(K.get(8))
        curUp := K.get(6) == 1.0
        curMainN := K.get(7) == 1.0
        cA := K.get(0)
        cB := K.get(1)
        cC := K.get(2)
        cVals.set(0, cB + (cB - cC))
        cVals.set(1, cC + (cB - cA))
        cVals.set(2, cB + (cB - cA))
        cVals.set(3, cC + (cC - cA))
        bool r0 = not na(K.get(10))
        bool r1 = not na(K.get(11))
        bool r2 = not na(K.get(12))
        bool r3 = not na(K.get(13))
        bool n0 = not na(K.get(15))
        bool n1 = not na(K.get(16))
        bool n2 = not na(K.get(17))
        bool n3 = not na(K.get(18))
        if sInit
            if tC != sPatC
                if st == 0
                    evUpN := curUp
                    evDnN := not curUp
 
                evR.set(0, r0 and K.get(10) >= tCurBar)
                evR.set(1, r1 and K.get(11) >= tCurBar)
                evR.set(2, r2 and K.get(12) >= tCurBar)
                evR.set(3, r3 and K.get(13) >= tCurBar)
                evNr.set(0, n0 and K.get(15) >= tCurBar and not evR.get(0))
                evNr.set(1, n1 and K.get(16) >= tCurBar and not evR.get(1))
                evNr.set(2, n2 and K.get(17) >= tCurBar and not evR.get(2))
                evNr.set(3, n3 and K.get(18) >= tCurBar and not evR.get(3))
            else
                evR.set(0, r0 and not sR0)
                evR.set(1, r1 and not sR1)
                evR.set(2, r2 and not sR2)
                evR.set(3, r3 and not sR3)
 
                evNr.set(0, n0 and not sN0 and not evR.get(0))
                evNr.set(1, n1 and not sN1 and not evR.get(1))
                evNr.set(2, n2 and not sN2 and not evR.get(2))
                evNr.set(3, n3 and not sN3 and not evR.get(3))
                if st == 2 and sStat != 2
                    evBrk := true
        sPatC := tC
        sR0 := r0
        sR1 := r1
        sR2 := r2
        sR3 := r3
        sN0 := n0
        sN1 := n1
        sN2 := n2
        sN3 := n3
        sStat := st
    else
        sPatC := -1.0
        sR0 := false
        sR1 := false
        sR2 := false
        sR3 := false
        sN0 := false
        sN1 := false
        sN2 := false
        sN3 := false
        sStat := 0
 
    if nF > 0
        int f = nF - 1
        float x0 = F.get(f * FS)
        float size = math.abs(F.get(f * FS + 3) - F.get(f * FS + 1))
        fPrior := F.get(f * FS + 4)
        fUp := F.get(f * FS + 6) == 1.0
        fRatio := not na(fPrior) and fPrior > 0 ? size / fPrior : na
        bool hit = not na(fRatio) and fRatio >= formRatio
 
        if sInit and hit and ((x0 == sFormT and not sFormHit) or (x0 != sFormT and x0 >= tPrevBar))
            evForm := true
        sFormT := x0
        sFormHit := hit
    sInit := true
 
bool evMain = curMainN ? evR.get(1) : evR.get(0)
bool evMainNear = curMainN ? evNr.get(1) : evNr.get(0)
bool evHH = evSwH and swTyp == "HH"
bool evLH = evSwH and swTyp == "LH"
bool evHL = evSwL and swTyp == "HL"
bool evLL = evSwL and swTyp == "LL"
 
dirOk(bool up) => alDir == "Both" or (alDir == "Up" and up) or (alDir == "Down" and not up)
tgtOk(int k, bool isMain) => alTgt == "All" or (alTgt == "Main" and isMain) or alTgt == tgtCode(k)
swOk(string t) => alSwTyp == "All" or alSwTyp == t or (alSwTyp == "HH and HL" and (t == "HH" or t == "HL")) or (alSwTyp == "LH and LL" and (t == "LH" or t == "LL"))
swName(string t) => t == "HH" ? "Higher high (HH)" : t == "LH" ? "Lower high (LH)" : t == "HL" ? "Higher low (HL)" : "Lower low (LL)"
jsStr(string v) => "\"" + v + "\""
addTxt(string acc, string v) => acc == "" ? v : acc + " · " + v
addJs(string acc, string v) => acc == "" ? v : acc + "," + v
msgOf(string txt, string js) =>
    alFmt == "JSON" ?
         "{\"indicator\":\"Saikix-Nehaba\",\"ticker\":" + jsStr(syminfo.ticker) + ",\"chart_tf\":" + jsStr(timeframe.period) + ",\"tf\":" + jsStr(tfUse) + ",\"price\":" + str.tostring(close) + ",\"events\":[" + js + "]}" :
         "[Saikix-Nehaba] " + syminfo.ticker + " " + tfLabel(timeframe.period) + " " + (htf ? "(" + tfLabel(tfUse) + " swings) " : "") + txt + ". Price " + fmtP(close)
abcJs() => ",\"a\":" + str.tostring(cA) + ",\"b\":" + str.tostring(cB) + ",\"c\":" + str.tostring(cC)
 
string aTxt = ""
string aJs = ""
if alOn
    if alSwing and (evSwH or evSwL) and dirOk(evSwH) and swOk(swTyp)
        string what = swTyp == "" ? (evSwH ? "Swing high" : "Swing low") : swName(swTyp)
        aTxt := addTxt(aTxt, what + " confirmed at " + fmtP(swP) + (na(swPrev) ? "" : " (previous " + (evSwH ? "high " : "low ") + fmtP(swPrev) + ")"))
        aJs := addJs(aJs, "{\"event\":\"swing_confirmed\",\"direction\":" + jsStr(evSwH ? "up" : "down") + ",\"swing\":" + jsStr(evSwH ? "high" : "low") + ",\"type\":" + jsStr(swTyp == "" ? (evSwH ? "H" : "L") : swTyp) + ",\"price_level\":" + str.tostring(swP) + (na(swPrev) ? "" : ",\"previous_level\":" + str.tostring(swPrev)) + "}")
    if alFormed and (evUpN or evDnN) and dirOk(curUp)
        int km = curMainN ? 1 : 0
        aTxt := addTxt(aTxt, (curUp ? "Up" : "Down") + " N wave formed: A " + fmtP(cA) + " · B " + fmtP(cB) + " · C " + fmtP(cC) + ". " + tgtName(km, true) + " " + fmtP(cVals.get(km)))
        aJs := addJs(aJs, "{\"event\":\"n_wave_formed\",\"direction\":" + jsStr(curUp ? "up" : "down") + abcJs() + ",\"main\":" + jsStr(tgtCode(km)) + ",\"v\":" + str.tostring(cVals.get(0)) + ",\"n\":" + str.tostring(cVals.get(1)) + ",\"e\":" + str.tostring(cVals.get(2)) + ",\"nt\":" + str.tostring(cVals.get(3)) + "}")
    if alBrk and evBrk and dirOk(curUp)
        aTxt := addTxt(aTxt, "C " + fmtP(cC) + " broken: a bar closed " + (curUp ? "below" : "above") + " C")
        aJs := addJs(aJs, "{\"event\":\"c_broken\",\"direction\":" + jsStr(curUp ? "up" : "down") + abcJs() + "}")
if aTxt != ""
    alert(msgOf(aTxt, aJs), alert.freq_once_per_bar)
 
reachMsg(int k) =>
    bool isMain = (k == 1 and curMainN) or (k == 0 and not curMainN)
    string t = (curUp ? "Upside " : "Downside ") + tgtName(k, isMain) + " " + fmtP(cVals.get(k)) + " reached"
    string j = "{\"event\":\"target_reached\",\"direction\":" + jsStr(curUp ? "up" : "down") + ",\"target\":" + jsStr(tgtCode(k)) + ",\"main\":" + (isMain ? "true" : "false") + ",\"price_level\":" + str.tostring(cVals.get(k)) + abcJs() + "}"
    msgOf(t, j)
reachOn(int k) =>
    bool isMain = (k == 1 and curMainN) or (k == 0 and not curMainN)
    alOn and alReach and evR.get(k) and dirOk(curUp) and tgtOk(k, isMain)
if reachOn(0)
    alert(reachMsg(0), alert.freq_once_per_bar)
if reachOn(1)
    alert(reachMsg(1), alert.freq_once_per_bar)
if reachOn(2)
    alert(reachMsg(2), alert.freq_once_per_bar)
if reachOn(3)
    alert(reachMsg(3), alert.freq_once_per_bar)
 
nearMsg(int k) =>
    bool isMain = (k == 1 and curMainN) or (k == 0 and not curMainN)
    float away = math.abs(cVals.get(k) - close)
    string t = (curUp ? "Upside " : "Downside ") + tgtName(k, isMain) + " " + fmtP(cVals.get(k)) + " approaching: " + fmtSize(away, close) + " away"
    string j = "{\"event\":\"target_approaching\",\"direction\":" + jsStr(curUp ? "up" : "down") + ",\"target\":" + jsStr(tgtCode(k)) + ",\"main\":" + (isMain ? "true" : "false") + ",\"price_level\":" + str.tostring(cVals.get(k)) + ",\"distance\":" + str.tostring(away) + abcJs() + "}"
    msgOf(t, j)
nearOn(int k) =>
    bool isMain = (k == 1 and curMainN) or (k == 0 and not curMainN)
    alOn and alNear and evNr.get(k) and dirOk(curUp) and tgtOk(k, isMain)
if nearOn(0)
    alert(nearMsg(0), alert.freq_once_per_bar)
if nearOn(1)
    alert(nearMsg(1), alert.freq_once_per_bar)
if nearOn(2)
    alert(nearMsg(2), alert.freq_once_per_bar)
if nearOn(3)
    alert(nearMsg(3), alert.freq_once_per_bar)
 
if alOn and alForm and evForm and dirOk(fUp)
    alert(msgOf("Forming " + (fUp ? "rise" : "drop") + " reached " + str.tostring(formRatio, "#0.00") + "× the prior " + (fUp ? "rise" : "drop") + " (" + fmtSize(fPrior, close) + ")",
         "{\"event\":\"forming_ratio_reached\",\"direction\":" + jsStr(fUp ? "up" : "down") + ",\"ratio\":" + str.tostring(formRatio) + ",\"prior_size\":" + str.tostring(fPrior) + "}"), alert.freq_once_per_bar)
 
alertcondition(evSwH, "Swing high confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Swing high confirmed. Price {{close}}")
alertcondition(evSwL, "Swing low confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Swing low confirmed. Price {{close}}")
alertcondition(evHH, "Higher high (HH) confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Higher high (HH) confirmed. Price {{close}}")
alertcondition(evLH, "Lower high (LH) confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Lower high (LH) confirmed. Price {{close}}")
alertcondition(evHL, "Higher low (HL) confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Higher low (HL) confirmed. Price {{close}}")
alertcondition(evLL, "Lower low (LL) confirmed", "[Saikix-Nehaba] {{ticker}} {{interval}} Lower low (LL) confirmed. Price {{close}}")
alertcondition(evUpN, "Up N wave formed", "[Saikix-Nehaba] {{ticker}} {{interval}} Up N wave formed: upside targets drawn. Price {{close}}")
alertcondition(evDnN, "Down N wave formed", "[Saikix-Nehaba] {{ticker}} {{interval}} Down N wave formed: downside targets drawn. Price {{close}}")
alertcondition(evMain, "Main target reached", "[Saikix-Nehaba] {{ticker}} {{interval}} Main target reached. Price {{close}}")
alertcondition(evR.get(0), "V target reached", "[Saikix-Nehaba] {{ticker}} {{interval}} V target reached. Price {{close}}")
alertcondition(evR.get(1), "N target reached", "[Saikix-Nehaba] {{ticker}} {{interval}} N target reached. Price {{close}}")
alertcondition(evR.get(2), "E target reached", "[Saikix-Nehaba] {{ticker}} {{interval}} E target reached. Price {{close}}")
alertcondition(evR.get(3), "NT target reached", "[Saikix-Nehaba] {{ticker}} {{interval}} NT target reached. Price {{close}}")
alertcondition(evMainNear, "Main target approaching", "[Saikix-Nehaba] {{ticker}} {{interval}} Main target approaching. Price {{close}}")
alertcondition(evBrk, "C broken", "[Saikix-Nehaba] {{ticker}} {{interval}} C broken: a bar closed beyond C. Price {{close}}")
alertcondition(evForm, "Forming wave reached the ratio", "[Saikix-Nehaba] {{ticker}} {{interval}} The forming wave reached the set ratio of the prior wave in the same direction. Price {{close}}")

← 返回列表