メインコンテンツへスキップ
見出し画像

鏡写しトレード

    //@version=6
    indicator("三尊ミラー投影", overlay=true, max_lines_count=500, max_labels_count=300, max_bars_back=3000, calc_bars_count=2500)

    // ── 入力 ──
    tHead = input.time(timestamp("2026-01-01 00:00"), "トップ日時(チャート上でドラッグ)", confirm=true)
    tL = input.time(timestamp("2025-10-01 00:00"), "オレンジ 左点", inline="L", confirm=true)
    pLo = input.price(0.0, "", inline="L", confirm=true)
    tR = input.time(timestamp("2026-06-01 00:00"), "オレンジ 右点", inline="R", confirm=true)
    pRo = input.price(0.0, "", inline="R", confirm=true)
    useFit = input.bool(false, "傾きを自動計算(オンでオレンジ点を無視)")
    autoRo = input.bool(true, "横軸自動倍率(オレンジ左点0トップ=1、トップ0右点の長さで倍率)", group="横倍率")
    autoR = input.bool(false, "形の一致率で自動(横軸自動が使えない時)", group="横倍率")
    rIn = input.float(1.0, "手動の横倍率(自動が使えない時に適用)", minval=0.1, maxval=5.0, step=0.01, group="横倍率")
    autoVo = input.bool(false, "縦軸自動倍率(オン=自動/オフ=下の手動の値)", group="縦倍率")
    vIn = input.float(1.0, "手動の縦倍率(自動がオフ・使えない時に適用)", minval=0.1, maxval=5.0, step=0.01, group="縦倍率")
    pur1 = input.bool(false, "紫は等倍1.0で出す(オフ=緑と同じ倍率)", group="表示")
    showOTxt = input.bool(false, "オレンジの文字を表示", group="表示")
    showBTxt = input.bool(true, "青の文字を表示(一致率など)", group="表示")
    wFit = input.int(2, "緑ラインの太さ", minval=1, maxval=10, group="表示")
    wPred = input.int(2, "紫ラインの太さ", minval=1, maxval=10, group="表示")
    showFit = input.bool(true, "既存足に鏡写しを表示(緑)", group="表示")
    useAuto = input.bool(false, "トップ自動判定(オンでドラッグ位置を無視)", group="その他")
    len = input.int(200, "予測本数", minval=20, maxval=300, group="その他")
    pv = input.int(5, "波形感度(ピボット左右本数)", minval=2, maxval=30, group="その他")
    look = input.int(300, "自動判定の探索範囲(本)", minval=30, maxval=600, group="その他")

    cAxis = #2962FF
    cTilt = #FF9800
    cHi = #F23645
    cLo = #089981
    cPred = #B04BC8
    cFit = #00C853
    cTxt = #B2B5BE

    KMAX = 800 // 計算負荷と参照上限の制限

    // ── ピボット記録 ──
    pH = ta.pivothigh(high, pv, pv)
    pL = ta.pivotlow(low, pv, pv)

    var hB = array.new<int>()
    var lB = array.new<int>()
    if not na(pH)
    hB.push(bar_index - pv)
    if hB.size() > 60
    hB.shift()
    if not na(pL)
    lB.push(bar_index - pv)
    if lB.size() > 60
    lB.shift()

    // ドラッグ位置のバー
    var int manHead = na
    if na(manHead) and time >= tHead
    manHead := bar_index

    // オレンジ点のバー位置(未来側は平均足間隔で換算)
    var int bLo = na
    var int bRo = na
    // 計算範囲より前に置かれた点は先頭足に吸着させず、時間から換算する
    var int firstT = time
    var float hiAll = high
    var float loAll = low
    hiAll := math.max(hiAll, high)
    loAll := math.min(loAll, low)
    if na(bLo) and time >= tL and tL >= firstT
    bLo := bar_index
    if na(bRo) and time >= tR and tR >= firstT
    bRo := bar_index

    // 配列を波形(ジグザグ)化:x0 が ys[0] の位置
    zigzag(array<float> ys, int x0, int w) =>
    array<int> px = array.new<int>()
    array<float> py = array.new<float>()
    array<int> pt = array.new<int>()
    int n = ys.size() - 1
    px.push(x0)
    py.push(ys.get(0))
    pt.push(0)
    if n >= 2 * w
    for j = w to n - w
    float v = ys.get(j)
    bool isH = true
    bool isL = true
    for q = j - w to j + w
    if q != j
    if ys.get(q) > v
    isH := false
    if ys.get(q) < v
    isL := false
    int typ = isH ? 1 : isL ? -1 : 0
    if typ != 0
    if pt.last() == typ
    if (typ == 1 and v > py.last()) or (typ == -1 and v < py.last())
    px.set(px.size() - 1, x0 + j)
    py.set(py.size() - 1, v)
    else
    px.push(x0 + j)
    py.push(v)
    pt.push(typ)
    if n > 0 and px.last() != x0 + n
    float vEnd = ys.get(n)
    pt.push(vEnd >= py.last() ? 1 : -1)
    px.push(x0 + n)
    py.push(vEnd)
    [px, py, pt]

    // 小数位置の終値(線形補間)
    srcAt(float off) =>
    int o = int(math.floor(off))
    float f = off - o
    f > 0 ? close[o] * (1 - f) + close[o + 1] * f : close[o]

    // 倍率 r(横)・v(縦)で鏡写し判定
    // 右 d本目 = c0 + v・(左 d/r本目 " c0) + s・(d + v・d/r) c0 = 基準価格(通常はトップの終値)
    // 戻り値 [傾き, 一致率]
    mirrorFit(int K, int hb, float r, float v, bool fixS, float sFix, float piv) =>
    float s = fixS ? sFix : 0.0
    float c = na
    if K >= 2
    float c0 = piv
    float lim = math.min(float(hb), 2998.0 - K)
    float sxy = 0.0
    float sxx = 0.0
    int n = 0
    for d = 1 to K
    float k = d / r
    if k > lim
    break
    float x = d + v * k
    sxy += (close[K - d] - (c0 + v * (srcAt(K + k) - c0))) * x
    sxx += x * x
    n += 1
    if not fixS and sxx > 0
    s := sxy / sxx
    if n >= 2
    float sa = 0.0
    float sb = 0.0
    float saa = 0.0
    float sbb = 0.0
    float sab = 0.0
    for d = 1 to n
    float k = d / r
    float a = close[K - d]
    float m = c0 + v * (srcAt(K + k) - c0) + s * (d + v * k)
    sa += a
    sb += m
    saa += a * a
    sbb += m * m
    sab += a * m
    float vA = n * saa - sa * sa
    float vB = n * sbb - sb * sb
    c := vA > 0 and vB > 0 ? (n * sab - sa * sb) / math.sqrt(vA * vB) : na
    [s, c]

    var array<line> lns = array.new<line>()
    var array<label> lbs = array.new<label>()

    if barstate.islast
    for ln in lns
    ln.delete()
    lns.clear()
    for lb in lbs
    lb.delete()
    lbs.clear()

    int minK = math.max(10, pv * 2)
    
    // オレンジの傾き(1本あたり)
    int   nb    = math.min(500, bar_index)   // 夜間・休日の空白も含めた平均足間隔
    float barMs = nb > 0 ? float(time - time[nb]) / nb : 86400000.0
    barMs := barMs > 0 ? barMs : 86400000.0
    float xL = na(bLo) ? float(bar_index) + float(tL - time) / barMs : float(bLo)
    float xR = na(bRo) ? float(bar_index) + float(tR - time) / barMs : float(bRo)
    // 点が価格範囲・時間範囲の外(銘柄変更などで見えない所)にあれば無効扱い
    bool  manIn  = pLo >= loAll * 0.7 and pLo <= hiAll * 1.3 and pRo >= loAll * 0.7 and pRo <= hiAll * 1.3 and tL >= firstT and tR >= firstT and xL <= bar_index + 500 and xR <= bar_index + 500
    bool  manSet = not useFit and pLo > 0 and pRo > 0
    bool  useMan = manSet and manIn and math.abs(xR - xL) >= 1
    float manS   = useMan ? (pRo - pLo) / (xR - xL) : 0.0
    
    // ── 鏡写し判定:右(h+k) ≒ 左(h-k) + 2・s・k ──
    int   head  = na
    float slope = na
    float score = na
    
    array<int> cand = array.new<int>()
    if useAuto
        for b in hB
            if bar_index - b <= look
                cand.push(b)
    else
        // 手動:未来側に置かれていたら現在足をトップ扱い
        cand.push(na(manHead) ? bar_index : manHead)
    
    float rBase = autoR ? 1.0 : rIn   // オレンジ基準が使えない時は入力値
    float rUse  = rBase
    float vUse  = vIn
    string rMode = autoR ? "自動" : rIn == 1.0 ? "等倍" : "手動"
    string vMode = vIn == 1.0 ? "等倍" : "手動"
    string why = ""
    for hb in cand
        int K  = bar_index - hb
        int Kf = math.min(K, hb, KMAX)   // 比較できる本数(左右の短い方)
        bool ok = useAuto ? (K >= minK and K <= KMAX and Kf >= minK) : (K <= KMAX and hb >= 1)
        if not ok and not useAuto
            why := hb < 1 ? "トップが計算範囲(直近2500本)より前です" : "トップが現在から" + str.tostring(KMAX) + "本より遠いです"
        if ok
            [s, c] = mirrorFit(K, hb, rBase, vUse, useMan, manS, close[K])
            if useAuto
                if not na(c) and (na(score) or c > score)
                    score := c
                    head  := hb
                    slope := s
            else
                score := c
                head  := hb
                slope := s
    
    // ── 縦軸自動倍率:トップがオレンジより下なら トップ最安値⇔左右点の高値、上なら トップ最高値⇔左右点の安値 ──
    // 左点側の高さを1として右点側の高さで倍率。この時は傾き分も高さの比に含まれるので傾き項は使わない
    float piv0 = na
    bool  fixS = useMan
    float sFix = manS
    if not na(head)
        piv0 := close[bar_index - head]
    if autoVo and useMan and not na(head) and not na(bLo) and xL < head and xR > head
        int   Kv  = bar_index - head
        float oAt = pLo + manS * (head - xL)
        bool  below = close[Kv] < oAt
        float base = below ? low[Kv] : high[Kv]
        float vL   = below ? high[bar_index - bLo] : low[bar_index - bLo]
        float vR   = pRo   // 右点が未来側ならつまみの価格
        if not na(bRo)
            vR := below ? high[bar_index - bRo] : low[bar_index - bRo]
        float vv   = vL != base ? (vR - base) / (vL - base) : na
        if not na(vv) and vv > 0
            vUse  := vv
            vMode := "オレンジ基準"
            piv0  := base
            fixS  := true
            sFix  := 0.0
            [sV, cV] = mirrorFit(Kv, head, rUse, vUse, fixS, sFix, piv0)
            slope := sV
            score := cV
    
    // ── 横軸自動倍率:オレンジ左点0トップ を1、トップ0右点 の長さで倍率 ──
    bool roDone = false
    if autoRo and useMan and not na(head) and xL < head and xR > head
        rUse  := (xR - head) / (head - xL)
        rMode := "オレンジ基準"
        [sO, cO] = mirrorFit(bar_index - head, head, rUse, vUse, fixS, sFix, piv0)
        slope := sO
        score := cO
        roDone := true
    
    // ── 右側倍率の自動合わせ(粗く探して細かく詰める) ──
    if autoR and not roDone and not na(head)
        int   Ka = bar_index - head
        float bestR = rUse
        float bestC = score
        float bestS = slope
        for i = 0 to 54
            float r = 0.3 + 0.05 * i
            [s1, c1] = mirrorFit(Ka, head, r, vUse, fixS, sFix, piv0)
            if not na(c1) and (na(bestC) or c1 > bestC)
                bestC := c1
                bestR := r
                bestS := s1
        float r0 = bestR
        for i = -5 to 5
            float r = r0 + 0.01 * i
            if r >= 0.1
                [s2, c2] = mirrorFit(Ka, head, r, vUse, fixS, sFix, piv0)
                if not na(c2) and (na(bestC) or c2 > bestC)
                    bestC := c2
                    bestR := r
                    bestS := s2
        rUse  := bestR
        score := bestC
        slope := bestS
    
    if na(head)
        // 出せない時も縦線は常に表示
        int xPos = useAuto or na(manHead) ? bar_index : manHead
        lns.push(line.new(xPos, high, xPos, low, color=cAxis, width=2, style=line.style_dashed, extend=extend.both))
        if showBTxt
            lbs.push(label.new(xPos, high, "今は出せません\n" + (why == "" ? "鏡写しできるトップがありません" : why), style=label.style_label_down, color=#00000000, textcolor=cAxis))
    else
        int   K     = bar_index - head
        float hHead = high[K]
    
        // ── 鏡写しペア(赤=高値、緑=安値) ──
        for b in hB
            int lb2 = head - int(math.round((b - head) / rUse))
            if b > head and lb2 >= 0 and bar_index - lb2 <= 2998
                lbs.push(label.new(b,   high[bar_index - b],   "◯", style=label.style_none, textcolor=cHi, size=size.large))
                lbs.push(label.new(lb2, high[bar_index - lb2], "◯", style=label.style_none, textcolor=cHi, size=size.large))
        for b in lB
            int lb2 = head - int(math.round((b - head) / rUse))
            if b > head and lb2 >= 0 and bar_index - lb2 <= 2998
                lbs.push(label.new(b,   low[bar_index - b],   "◯", style=label.style_none, textcolor=cLo, size=size.large))
                lbs.push(label.new(lb2, low[bar_index - lb2], "◯", style=label.style_none, textcolor=cLo, size=size.large))
    
        // ── 予測:トップより右の未描画部分 = 左側のさらに先を鏡写し ──
        array<float> ys = array.new<float>()
        ys.push(close)
        float rP = pur1 ? 1.0 : rUse
        float vP = pur1 ? 1.0 : vUse
        for j = 1 to len
            int   d   = K + j
            float k   = K / rUse + j / rP   // 緑が使った左側の続きから
            float off = K + k
            if off > bar_index or off > 2998
                break
            ys.push(piv0 + vP * (srcAt(off) - piv0) + slope * (d + vP * k))
    
        [px, py, pt] = zigzag(ys, bar_index, pv)
    
        // 緑:既存足への鏡写し(トップ→現在)
        if showFit
            array<float> yg = array.new<float>()
            for d = 0 to K
                float k   = d / rUse
                float off = K + k
                if off > bar_index or off > 2998
                    break
                yg.push(piv0 + vUse * (srcAt(off) - piv0) + slope * (d + vUse * k))
            if yg.size() > 1
                [gx, gy, gt] = zigzag(yg, head, pv)
                if gx.size() > 1
                    for i = 1 to gx.size() - 1
                        lns.push(line.new(gx.get(i - 1), gy.get(i - 1), gx.get(i), gy.get(i), color=cFit, width=wFit))
    
        // 紫:予測ライン
        if px.size() > 1
            for i = 1 to px.size() - 1
                lns.push(line.new(px.get(i - 1), py.get(i - 1), px.get(i), py.get(i), color=cPred, width=wPred))
                bool up = pt.get(i) == 1
                lbs.push(label.new(px.get(i), py.get(i), "(" + str.tostring(i) + ")", style=up ? label.style_label_down : label.style_label_up, color=#00000000, textcolor=cPred))
        else
            lbs.push(label.new(bar_index, high, "予測に使う左側データ不足", style=label.style_label_down, color=#00000000, textcolor=cPred))
    
        if showBTxt
            lbs.push(label.new(head, hHead, "一致率 " + (na(score) ? " (右側の足が足りません)" : str.tostring(score * 100, "#.0") + "%") + "\n横倍率 " + str.tostring(rUse, "#.00") + "(" + rMode + ") 縦倍率 " + str.tostring(vUse, "#.00") + "(" + vMode + ")\n紫 " + (pur1 ? "等倍1.0" : "緑と同じ倍率"), style=label.style_label_down, color=#00000000, textcolor=cAxis))
    
    // ── 青軸とオレンジは最後に描画(描画本数の上限で古い線から消されるため) ──
    if not na(head)
        int   K2 = bar_index - head
        float hH = high[K2]
        lns.push(line.new(head, hH, head, low[K2], color=cAxis, width=2, extend=extend.both))
    // 自動の傾き(手動時の目安用)
    float autoS = slope
    if useMan and not na(head)
        [sA, cA] = mirrorFit(bar_index - head, head, rUse, 1.0, false, 0.0, close[bar_index - head])
        autoS := sA
    // オレンジ:bar_index座標で直接描画(時間座標・延長は使わない)
    float oS  = useMan ? manS : slope
    float oX0 = na
    float oY0 = na
    if useMan
        oX0 := xL
        oY0 := pLo
    else if not na(head)
        oX0 := float(head)
        oY0 := high[bar_index - head]
    string oMode = useMan ? "手動" : "自動"
    if useMan
        lns.push(line.new(tL, pLo, tR, pRo, xloc=xloc.bar_time, color=cTilt, width=2, extend=extend.both))
    else if not na(oS) and not na(oX0) and not na(oY0)
        int xa = math.max(0, bar_index - 600)
        int xb = bar_index + 490
        lns.push(line.new(xa, oY0 + oS * (xa - oX0), xb, oY0 + oS * (xb - oX0), color=cTilt, width=2))
    else
        // 傾き不明時はトップ位置の高値から水平で仮表示
        int xq = useAuto or na(manHead) ? bar_index : manHead
        int oq = math.min(bar_index - xq, 2499)
        float hq = high[oq]
        int xa = math.max(0, bar_index - 600)
        lns.push(line.new(xa, hq, bar_index + 490, hq, color=cTilt, width=2, style=line.style_dashed))
        oMode := "仮(水平)"
    // 手動点の目安:自動の位置を点線で表示し、置き直し先の日時・価格を表示
    if not useFit and not na(head)
        int   Kg = bar_index - head
        float hG = high[Kg]
        int   gL = math.max(0, head - Kg)
        int   gR = bar_index
        float yL = hG + autoS * (gL - head)
        float yR = hG + autoS * (gR - head)
        if useMan
            lns.push(line.new(gL, yL, gR, yR, color=cTilt, width=1, style=line.style_dotted, extend=extend.both))
        if showOTxt
            lbs.push(label.new(gL, yL, "◆左点の目安\n" + str.format_time(time[bar_index - gL], "yyyy-MM-dd HH:mm") + "\n" + str.tostring(yL, format.mintick), style=label.style_label_up, color=#00000000, textcolor=cTilt))
        if showOTxt
            lbs.push(label.new(gR, yR, "◆右点の目安\n" + str.format_time(time, "yyyy-MM-dd HH:mm") + "\n" + str.tostring(yR, format.mintick), style=label.style_label_up, color=#00000000, textcolor=cTilt))
    if manSet and not manIn
        oMode := "手動点が範囲外→自動で表示中"
    if showOTxt
        lbs.push(label.new(bar_index + 5, close, "オレンジ " + oMode + " / 傾き " + str.tostring(nz(oS), "#.####") + "/本", style=label.style_label_left, color=#00000000, textcolor=cTilt))

    あなたへのおすすめ