Geometric Price Time Square Projection - Ver 1.0

TimePriceDecoder · study · 556 行 · 点赞 463 · TradingView 原页

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

Pine Script

//@version=6
// Geometric Price Time Square Projection - by TimePriceDecoder
// ONE fixed swing = the MASTER square: plain highest / lowest CLOSE of the last window of CLOSED bars, taken once per
// session (intraday) or every N bars (D/W/M). Nothing is moved or redrawn afterwards (no repainting of the grid).
// The master pattern (box, X diagonals, inner blue 1/√2 square, diamonds, centre lines/COG) is repeated as a GRID:
// past + future columns, rows above + below. Master also has 4 quadrants and time cycles (master + quadrants).
// Signals (arrows only, no text): square base / top / COG levels, time-cycle nodes, diagonals (graded 1-3 by confluence).
// Optional hindsight marks (drawn when a master is created): swing high / low pivots and back-filled signals in its window.
indicator("Geometric Price Time Square Projection", shorttitle="Geometric Price Time Square Projection", overlay=true, max_boxes_count=500, max_lines_count=500, max_labels_count=500, max_bars_back=5000)
 
// ── Inputs ──────────────────────────────────────────────
gannSel     = input.int(88, "Gann number", options=[44, 88, 176], group="① Swing engine")
tfSel       = input.int(10, "Swing TF (minutes)", options=[3, 10, 30, 45], group="① Swing engine", tooltip="Swing window = max(Gann, session ÷ TF) bars of this TF, whatever the chart TF. If the chart TF is larger than this TF, the chart bar is used. Daily and above: Gann number of chart bars.")
sessionMins = input.float(375.0, "Session length in minutes", minval=60, step=15, group="① Swing engine", tooltip="Minutes in one trading day of your exchange (e.g. 375 for 9:15-15:30, 390 for 9:30-16:00).")
refreshN    = input.int(0, "Daily and above: new master every N bars (0 = Gann number)", minval=0, maxval=500, group="① Swing engine")
 
colsBack    = input.int(4, "Grid: columns before the master (past)", minval=0, maxval=6, group="② Grid", tooltip="Big grids switch the outer cells to a lighter drawing (no diamonds) to stay inside TradingView's 500-line limit.")
colsFwd     = input.int(4, "Grid: columns after the master (future)", minval=0, maxval=6, group="② Grid")
rowsUp      = input.int(2, "Grid: rows above the master", minval=0, maxval=3, group="② Grid")
rowsDn      = input.int(2, "Grid: rows below the master", minval=0, maxval=3, group="② Grid")
 
innerMode   = input.string("Halves only", "Diamond style", options=["Diamond", "Halves only", "Diamond + halves", "Box 1/√2", "Off"], group="③ Square geometry", tooltip="'Diamond' = one big diamond per cell. 'Halves only' = 2x2 lattice: one diamond inside each of the 4 mid squares. 'Diamond + halves' = both.")
extraCells  = input.bool(true, "Diamonds also in the 2 cells right after the master (where price is now)", group="③ Square geometry", tooltip="Big grids draw diamonds only in the master to stay inside the 500-line limit. This adds the cell right of the master (same row) and the one above / below it, where the latest price action happens.")
extraRow    = input.string("Above", "Second extra cell is", options=["Above", "Below"], group="③ Square geometry")
showBox     = input.bool(true, "Inner blue square 1/√2 in every cell", group="③ Square geometry")
frameMode   = input.string("Off", "Outer frame of the major (same COG)", options=["Off", "√2", "2"], group="③ Square geometry")
dgMode      = input.string("Both", "Diagonals", options=["Both", "Swing only", "Off"], group="③ Square geometry")
showMidL    = input.bool(true, "Centre lines (price COG + time mid) in every cell", group="③ Square geometry")
cogMode     = input.string("Master", "COG label (price + time)", options=["Master", "All cells", "Off"], group="③ Square geometry")
quadOn      = input.bool(true, "Master quadrants (4 mid squares): COG lines, cycles", group="③ Square geometry")
rbTags      = input.bool(true, "Right-edge price tags (top, quadrant COGs, COG, bottom)", group="③ Square geometry")
swInfo      = input.bool(true, "Swing line and H / L markers (yellow)", group="③ Square geometry")
statsMode   = input.string("Label", "Swing range / bars / price per bar / ratio text", options=["Label", "Off"], group="③ Square geometry")
tcOn        = input.bool(true, "Show time cycles (on / off)", group="④ Time cycles")
tcPreset    = input.string("Major + smaller", "Which time cycles", options=["Major + smaller", "Major ½ + full", "Smaller ½ + full", "Pythagorean", "Fibonacci", "Gann fractions", "Off"], group="④ Time cycles", tooltip="The first three repeat continuously over the whole grid, past and future. Major = master square side n: ½ and full. Smaller = the 4 mid squares (n/2): ½ and full. The others are measured from the master's left edge only.")
tcLabels    = input.bool(true, "Node labels (name + bars from left edge + bars to go)", group="④ Time cycles")
tcQuad      = input.bool(true, "Cycles of the 4 mid squares (labels below the grid)", group="④ Time cycles")
pastCyc     = input.bool(true, "Past cycles: same nodes mirrored before the left edge", group="④ Time cycles")
 
pastN       = input.int(1, "Past masters kept", minval=0, maxval=40, group="⑤ History")
pastFade    = input.int(55, "Past masters fade %", minval=0, maxval=95, group="⑤ History")
 
cMaj  = input.color(#8E24AA, "Master square", group="⑥ Colours", inline="c1")
cBlue = input.color(#2962FF, "Inner square", group="⑥ Colours", inline="c1")
cDg   = input.color(#F23645, "Diagonals", group="⑥ Colours", inline="c2")
cDm   = input.color(#00BFA5, "Diamond", group="⑥ Colours", inline="c2")
cCg   = input.color(#FF9800, "Centre / COG", group="⑥ Colours", inline="c3")
cNode = input.color(#00C853, "Time node", group="⑥ Colours", inline="c4")
cSq   = input.color(#FF6D00, "Square node (1x)", group="⑥ Colours", inline="c4")
cQd   = input.color(#00B8D4, "Quadrant cycles", group="⑥ Colours", inline="c4")
cSw   = input.color(#FFD600, "Swing line / H / L (yellow)", group="⑥ Colours", inline="c5")
cSt   = input.color(#FF4081, "Swing details label", group="⑥ Colours", inline="c5")
colBuy  = input.color(#00E676, "Buy", group="⑥ Colours", inline="c6")
colSell = input.color(#FF1744, "Sell", group="⑥ Colours", inline="c6")
 
sigPrice    = input.bool(true, "Price signal: support at base, rejection at top, either at COG lines", group="⑦ Signals")
sigTolPct   = input.float(1.5, "Level / angle tolerance (% of square height)", minval=0.0, maxval=10.0, step=0.1, group="⑦ Signals", tooltip="How close a wick must come to a level or diagonal. Scales with the swing, so it works on any instrument.")
sigTime     = input.bool(true, "Time signal: reversal candle on a time-cycle node", group="⑦ Signals")
revLook     = input.int(38, "Prior move lookback into the node (bars)", minval=2, maxval=100, group="⑦ Signals")
sigQuad     = input.bool(false, "Time component also counts the smaller-square nodes", group="⑦ Signals")
sigTol      = input.int(1, "Node tolerance (bars)", minval=0, maxval=10, group="⑦ Signals")
sigAngle    = input.bool(true, "Angle component: price on a square diagonal", group="⑦ Signals")
minConf     = input.int(2, "Minimum confluence (time + price + angle) for a signal", minval=1, maxval=3, group="⑦ Signals", tooltip="1 = single touch (symbol, many signals), 2 = triangle (two of time / price / angle agree), 3 = large triangle (all three agree).")
sigCool     = input.int(10, "Bars before the same direction can signal again", minval=1, maxval=200, group="⑦ Signals")
sigMax      = input.int(8, "Maximum signals per master square", minval=1, maxval=50, group="⑦ Signals", tooltip="Applies separately to live signals and to the back-filled window signals.")
sigHalf     = input.bool(true, "Rejection candle must close in the favourable half of its range (buy: upper half, sell: lower half)", group="⑦ Signals")
sigPivot    = input.bool(true, "Mark the master's swing high (sell) / swing low (buy) - hindsight, drawn when the master is created", group="⑦ Signals")
sigBack     = input.bool(true, "Back-fill signals inside the master window - hindsight, drawn when the master is created", group="⑦ Signals")
 
lblSize     = input.string("Small", "Label size (all labels)", options=["Tiny", "Small", "Normal", "Large"], group="⑧ Labels")
statSize    = input.string("Normal", "Swing details label size", options=["Tiny", "Small", "Normal", "Large"], group="⑧ Labels")
arrSize     = input.string("Normal", "Signal arrow size (triangles for 3-of-3 are one step larger)", options=["Tiny", "Small", "Normal", "Large", "Huge"], group="⑧ Labels")
arrStyle    = input.string("Circle", "Symbol for weakest signals (1 of 3)", options=["Circle", "Diamond", "Square", "Arrow"], group="⑧ Labels", tooltip="Pine arrows stay thin whatever the size. Circle / Diamond / Square are solid shapes and stay clearly visible. 2 of 3 and 3 of 3 stay triangles.")
 
type Sn
    box bx
    line sw
    array<line> ln
    array<box> bs
    array<label> lb
    array<int> nb
    array<int> nr
    array<int> nk
    array<string> nm
    array<label> nl
    array<label> sg
    int xr
    int l
    int n
    bool up
    bool full = true
    float H
    float L
    float R
 
// ── Globals ─────────────────────────────────────────────
float chartMin = timeframe.in_seconds() / 60.0
float effTf = math.max(float(tfSel), chartMin)
float wcB = timeframe.isintraday ? math.max(float(gannSel), math.round(sessionMins / effTf)) : float(gannSel)
int wB = math.min(int(math.round(wcB * effTf / chartMin)), 4900)
int rfN = refreshN > 0 ? refreshN : gannSel
string lsz = lblSize == "Tiny" ? size.tiny : (lblSize == "Small" ? size.small : (lblSize == "Large" ? size.large : size.normal))
string ssz = statSize == "Tiny" ? size.tiny : (statSize == "Small" ? size.small : (statSize == "Large" ? size.large : size.normal))
string asz = arrSize == "Tiny" ? size.tiny : (arrSize == "Small" ? size.small : (arrSize == "Large" ? size.large : (arrSize == "Huge" ? size.huge : size.normal)))
string asz3 = arrSize == "Tiny" ? size.small : (arrSize == "Small" ? size.normal : (arrSize == "Normal" ? size.large : size.huge))
string sym1B = arrStyle == "Diamond" ? label.style_diamond : (arrStyle == "Square" ? label.style_square : (arrStyle == "Arrow" ? label.style_arrowup : label.style_circle))
string sym1S = arrStyle == "Diamond" ? label.style_diamond : (arrStyle == "Square" ? label.style_square : (arrStyle == "Arrow" ? label.style_arrowdown : label.style_circle))
color lbBg = color.new(color.gray, 100)   // labels never have a background
var float tolPx = 0.0
var array<Sn> sqs = array.new<Sn>()
var Sn cur = na
var int sigN = 0
var int lastDir = 0
var int lastAny = -999
 
// ── Helpers ─────────────────────────────────────────────
tripleB(float q) =>
    float dA = math.abs(q - 4.0 / 3.0)
    float dB = math.abs(q - 1.0)
    float dC = math.abs(q - 0.75)
    dA <= dB and dA <= dC ? 3.0 : (dB <= dC ? 1.0 : 4.0)
 
tripleA(float b) => b == 3.0 ? 4.0 : (b == 1.0 ? 1.0 : 3.0)
 
tripleName(float b) => b == 3.0 ? "4-3-5" : (b == 1.0 ? "1-1-√2" : "3-4-5")
 
nodeSet(float hypR) =>
    array<float> m = array.new<float>()
    if not tcOn
        m := array.new<float>()
    else if tcPreset == "Pythagorean"
        m := array.from(0.5, hypR / 2.0, 1.0, hypR, 2.0)
    else if tcPreset == "Fibonacci"
        m := array.from(0.382, 0.5, 0.618, 1.0, 1.618, 2.618)
    else if tcPreset == "Gann fractions"
        m := array.from(0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0)
    m
 
nodeName(float m, int i) =>
    tcPreset == "Pythagorean" ? array.get(array.from("½", "½H", "Sq", "Hyp", "2Sq"), i) : str.tostring(m, "#.###")
 
// blank lines stagger neighbouring labels (3 rows)
rowPad(int r) => r > 0 ? str.repeat(" \n", r) : ""
rowSfx(int r) => r > 0 ? str.repeat("\n ", r) : ""
 
// drawing is clamped to 490 bars ahead (Pine allows 500)
mkLine(int x1, float y1, int x2, float y2, color c, string st, int w) =>
    int lim = bar_index + 490
    int xe = math.min(x2, lim)
    float ye = x2 > lim and x2 != x1 ? y1 + (y2 - y1) * (xe - x1) / (x2 - x1) : y2
    line.new(x1, y1, xe, ye, xloc=xloc.bar_index, color=c, style=st, width=w)
 
mkBox(int l, float top, int r, float bot, color bc, string st, int w) =>
    box.new(l, top, math.min(r, bar_index + 490), bot, border_color=bc, border_width=w, border_style=st, xloc=xloc.bar_index, bgcolor=color(na))
 
// one diamond: left tip xl, top/bottom tips at xm, right tip xr, side tips on price cy
diamond(Sn s, int xl, int xm, int xr, float cy, float top, float bot, color c) =>
    s.ln.push(mkLine(xm, top, xr, cy, c, line.style_solid, 1))
    s.ln.push(mkLine(xr, cy, xm, bot, c, line.style_solid, 1))
    s.ln.push(mkLine(xm, bot, xl, cy, c, line.style_solid, 1))
    s.ln.push(mkLine(xl, cy, xm, top, c, line.style_solid, 1))
 
// one grid cell: X diagonals, inner blue square, diamond(s), COG marker + label
cell(Sn s, int x0, int x1, float top, float bot, bool dUp, bool mst, bool ext, string ct, bool lite) =>
    int cx = int(math.round((x0 + x1) / 2.0))
    float cy = (top + bot) / 2.0
    color kd = color.new(cDg, mst ? 0 : 35)
    if dgMode != "Off"
        s.ln.push(mkLine(x0, dUp ? bot : top, x1, dUp ? top : bot, kd, line.style_solid, 1))
        if dgMode == "Both"
            s.ln.push(mkLine(x0, dUp ? top : bot, x1, dUp ? bot : top, kd, line.style_solid, 1))
    if showBox or innerMode == "Box 1/√2"
        int iw = int(math.round((x1 - x0) / 2.0 / math.sqrt(2.0)))
        float ih = (top - bot) / 2.0 / math.sqrt(2.0)
        s.bs.push(mkBox(cx - iw, cy + ih, cx + iw, cy - ih, color.new(cBlue, mst ? 0 : 20), line.style_solid, 1))
    bool dmBig = innerMode == "Diamond" or innerMode == "Diamond + halves"
    bool dmQd = innerMode == "Diamond + halves" or innerMode == "Halves only"
    if (dmBig or dmQd) and (mst or ext or not lite)
        color kdm = color.new(cDm, (mst or ext) ? 0 : 30)
        if dmBig
            diamond(s, x0, cx, x1, cy, top, bot, kdm)
        if dmQd
            // 2x2 lattice: one diamond inscribed in each of the 4 mid squares (tips on the midpoints of each mid square's sides)
            int xa = int(math.round((x0 + cx) / 2.0))
            int xb = int(math.round((cx + x1) / 2.0))
            float yT = (top + cy) / 2.0
            float yB = (bot + cy) / 2.0
            diamond(s, x0, xa, cx, yT, top, cy, kdm)
            diamond(s, cx, xb, x1, yT, top, cy, kdm)
            diamond(s, x0, xa, cx, yB, cy, bot, kdm)
            diamond(s, cx, xb, x1, yB, cy, bot, kdm)
    if ct != ""
        s.lb.push(label.new(cx, cy, "◎", xloc=xloc.bar_index, style=label.style_label_center, color=color.new(cCg, 100), textcolor=cCg, size=lsz))
        s.lb.push(label.new(cx, cy, ct, xloc=xloc.bar_index, style=label.style_label_lower_left, color=lbBg, textcolor=cCg, size=lsz))
 
// Past master: keep only its box + swing line, faded. Everything else goes.
demote(Sn s) =>
    s.full := false
    for t in s.ln
        line.delete(t)
    for t in s.bs
        box.delete(t)
    for t in s.lb
        label.delete(t)
    s.ln.clear()
    s.bs.clear()
    s.lb.clear()
    box.set_border_color(s.bx, color.new(cMaj, pastFade))
    box.set_border_width(s.bx, 1)
    if not na(s.sw)
        line.set_color(s.sw, color.new(cSw, pastFade))
 
killSq(Sn s) =>
    box.delete(s.bx)
    if not na(s.sw)
        line.delete(s.sw)
    for t in s.ln
        line.delete(t)
    for t in s.bs
        box.delete(t)
    for t in s.lb
        label.delete(t)
    for t in s.sg
        label.delete(t)
 
// ── Master square + grid builder ────────────────────────
mkSn(float H, float L, int hb, int lbr) =>
    int l = math.min(hb, lbr)
    int r = math.max(hb, lbr)
    int n = r - l
    bool up = hb > lbr
    float R = H - L
    float cy = (H + L) / 2.0
    int cx = int(math.round((l + r) / 2.0))
    string fmt = format.mintick
    float q = wcB / math.max(n * chartMin / effTf, 1.0)
    float ptB = tripleB(q)
    float hypR = math.sqrt(1.0 + math.pow(ptB / tripleA(ptB), 2))
    // grid extent (columns of width n, rows of height R, anchored on the master)
    int kLo = -math.min(colsBack, int(math.floor(l / float(n))))
    int kHi = math.min(colsFwd, int(math.floor((bar_index + 480 - l) / float(n))) - 1)
    int jLo = -rowsDn
    int jHi = rowsUp
    int xGL = l + kLo * n
    int xGR = l + (kHi + 1) * n
    float yGLo = L + jLo * R
    float yGHi = L + (jHi + 1) * R
    int perCell = innerMode == "Diamond + halves" ? 22 : (innerMode == "Halves only" ? 18 : 6)
    bool lite = (kHi - kLo + 1) * (jHi - jLo + 1) * perCell + (kHi - kLo + 1) * 6 + 60 > 450
    Sn s = Sn.new()
    s.ln := array.new<line>()
    s.bs := array.new<box>()
    s.lb := array.new<label>()
    s.nb := array.new<int>()
    s.nr := array.new<int>()
    s.nk := array.new<int>()
    s.nm := array.new<string>()
    s.nl := array.new<label>()
    s.sg := array.new<label>()
    s.xr := xGR
    s.l := l
    s.n := n
    s.up := up
    s.H := H
    s.L := L
    s.R := R
    // cells
    string tfmt = timeframe.isintraday ? "dd MMM HH:mm" : "dd MMM yyyy"
    string mTxt = "COG " + str.tostring(cy, fmt) + "\n" + str.format_time(time[bar_index - cx], tfmt)
    for k = kLo to kHi
        for j = jLo to jHi
            float yb = L + j * R
            bool mst = k == 0 and j == 0
            bool ext = extraCells and k == 1 and (j == 0 or j == (extraRow == "Above" ? 1 : -1))
            string ct = cogMode == "Off" ? "" : (mst ? mTxt : (cogMode == "All cells" ? str.tostring(yb + R / 2.0, fmt) : ""))
            cell(s, l + k * n, l + (k + 1) * n, yb + R, yb, up, mst, ext, ct, lite)
    // centre lines of every row / column
    if showMidL
        for j = jLo to jHi
            s.ln.push(mkLine(xGL, L + (j + 0.5) * R, xGR, L + (j + 0.5) * R, color.new(cCg, j == 0 ? 0 : 35), line.style_dashed, 1))
        for k = kLo to kHi
            int xc = int(math.round(l + (k + 0.5) * n))
            s.ln.push(mkLine(xc, yGLo, xc, yGHi, color.new(cCg, k == 0 ? 0 : 35), line.style_dashed, 1))
    // grid lines
    color kg = color.new(chart.fg_color, 30)
    for k = kLo to kHi + 1
        s.ln.push(mkLine(l + k * n, yGLo, l + k * n, yGHi, kg, line.style_solid, 1))
    for j = jLo to jHi + 1
        s.ln.push(mkLine(xGL, L + j * R, xGR, L + j * R, kg, line.style_solid, 1))
    s.bx := mkBox(l, H, r, L, cMaj, line.style_solid, 2)
    if frameMode != "Off"
        float fs = frameMode == "2" ? 2.0 : math.sqrt(2.0)
        int fw = int(math.round(n * fs / 2.0))
        s.bs.push(box.new(cx - fw, cy + R * fs / 2.0, math.min(cx + fw, bar_index + 490), cy - R * fs / 2.0, xloc=xloc.bar_index, border_color=color.new(cMaj, 40), border_style=line.style_dashed, bgcolor=color(na)))
    // quadrants: 4 mid squares of the master
    if quadOn
        color kq = color.new(cCg, 0)
        float pT = (H + cy) / 2.0
        float pB = (L + cy) / 2.0
        s.ln.push(mkLine(l, pT, r, pT, kq, line.style_dashed, 1))
        s.ln.push(mkLine(l, pB, r, pB, kq, line.style_dashed, 1))
        s.ln.push(mkLine(int(math.round(l + n / 4.0)), L, int(math.round(l + n / 4.0)), H, kq, line.style_dashed, 1))
        s.ln.push(mkLine(int(math.round(l + 3.0 * n / 4.0)), L, int(math.round(l + 3.0 * n / 4.0)), H, kq, line.style_dashed, 1))
    if rbTags
        array<float> pv = array.from(H, (H + cy) / 2.0, cy, (L + cy) / 2.0, L)
        array<string> pn = array.from("TOP ", "COG-T ", "COG ", "COG-B ", "BOT ")
        for i = 0 to 4
            s.lb.push(label.new(xGR, pv.get(i), pn.get(i) + str.tostring(pv.get(i), fmt), xloc=xloc.bar_index, style=label.style_label_left, color=color.new(chart.bg_color, 100), textcolor=(i > 0 and i < 4) ? cCg : cMaj, size=lsz))
    // time cycles: master nodes (labels above the grid), quadrant nodes (labels below), past nodes mirrored
    array<float> mults = nodeSet(hypR)
    if mults.size() > 0
        for i = 0 to mults.size() - 1
            float mv = mults.get(i)
            int off = int(math.round(mv * n))
            int x = l + off
            if off >= 1 and x <= bar_index + 480
                color nc = mv == 1.0 ? cSq : cNode
                if not (showMidL and mv == 0.5)
                    s.ln.push(mkLine(x, yGLo, x, yGHi, color.new(nc, mv == 1.0 ? 0 : 15), mv == 1.0 ? line.style_solid : line.style_dashed, mv == 1.0 ? 2 : 1))
                string nt = nodeName(mv, i) + " " + str.tostring(off)
                label nlb = na
                if tcLabels
                    nlb := label.new(x, yGHi, rowPad(i % 3) + nt, xloc=xloc.bar_index, style=label.style_label_up, color=color.new(nc, 100), textcolor=nc, size=lsz)
                    s.lb.push(nlb)
                s.nb.push(x)
                s.nr.push(i % 3)
                s.nk.push(0)
                s.nm.push(nt)
                s.nl.push(nlb)
        if pastCyc
            for i = 0 to mults.size() - 1
                float pmv = mults.get(i)
                int poff = int(math.round(pmv * n))
                int px = l - poff
                if poff >= 1 and px >= 0
                    color pnc = pmv == 1.0 ? cSq : cNode
                    s.ln.push(mkLine(px, yGLo, px, yGHi, color.new(pnc, 45), line.style_dotted, 1))
                    if tcLabels
                        s.lb.push(label.new(px, yGHi, rowPad(i % 3) + "‹" + nodeName(pmv, i) + " " + str.tostring(poff), xloc=xloc.bar_index, style=label.style_label_up, color=color.new(pnc, 100), textcolor=pnc, size=lsz))
        if quadOn and tcQuad
            float half = n / 2.0
            for i = 0 to mults.size() - 1
                int off = int(math.round(mults.get(i) * half))
                for k = 0 to 1
                    int x = (k == 0 ? l : cx) + off
                    if off >= 1 and x <= bar_index + 480 and not s.nb.includes(x)
                        if not (showMidL and mults.get(i) == 0.5)
                            s.ln.push(mkLine(x, L, x, H, color.new(cQd, 15), line.style_dashed, 1))
                        string qt = "q" + nodeName(mults.get(i), i) + " " + str.tostring(off)
                        label ql = na
                        if tcLabels
                            ql := label.new(x, yGLo, qt + rowSfx(i % 3), xloc=xloc.bar_index, style=label.style_label_down, color=color.new(cQd, 100), textcolor=cQd, size=lsz)
                            s.lb.push(ql)
                        s.nb.push(x)
                        s.nr.push(i % 3)
                        s.nk.push(1)
                        s.nm.push(qt)
                        s.nl.push(ql)
    // continuous time cycles over the whole grid, past + future: major ½ / full, smaller ½ / full
    if tcOn and (tcPreset == "Major ½ + full" or tcPreset == "Smaller ½ + full" or tcPreset == "Major + smaller")
        bool mjOnly = tcPreset == "Major ½ + full"
        float stp = mjOnly ? n / 2.0 : n / 4.0
        for kk = int(math.ceil((xGL - l) / stp)) to int(math.floor((xGR - l) / stp))
            int ak = math.abs(kk)
            int x = int(math.round(l + kk * stp))
            // typ: 0 major full, 1 major half, 2 smaller full, 3 smaller half
            int typ = mjOnly ? (ak % 2 == 0 ? 0 : 1) : (tcPreset == "Smaller ½ + full" ? (ak % 2 == 0 ? 2 : 3) : (ak % 4 == 0 ? 0 : (ak % 4 == 2 ? 1 : 3)))
            if kk != 0 and x >= 0 and x <= bar_index + 480
                color nc = typ == 0 ? cSq : (typ == 1 ? cNode : cQd)
                int fm = int(kk / (mjOnly ? 2.0 : 4.0))
                string nt = (typ == 0 ? str.tostring(fm) + "Sq" : (typ == 1 ? "½" : (typ == 2 ? "q" : "q½"))) + " " + str.tostring(x - l)
                if not (showMidL and typ == 1)
                    s.ln.push(mkLine(x, yGLo, x, yGHi, color.new(nc, x < l ? 45 : (typ == 3 ? 35 : 15)), (typ == 0 or typ == 2) ? line.style_solid : (typ == 3 ? line.style_dotted : line.style_dashed), typ == 0 ? 2 : 1))
                label nlb = na
                if tcLabels
                    if typ < 2
                        nlb := label.new(x, yGHi, rowPad(typ) + nt, xloc=xloc.bar_index, style=label.style_label_up, color=color.new(nc, 100), textcolor=nc, size=lsz)
                    else
                        nlb := label.new(x, yGLo, nt + rowSfx(typ == 2 ? 0 : 1), xloc=xloc.bar_index, style=label.style_label_down, color=color.new(nc, 100), textcolor=nc, size=lsz)
                    s.lb.push(nlb)
                s.nb.push(x)
                s.nr.push(typ < 2 ? typ : (typ == 2 ? 0 : 1))
                s.nk.push(typ < 2 ? 0 : 1)
                s.nm.push(nt)
                s.nl.push(nlb)
    // swing info (yellow, thin)
    if swInfo
        s.sw := mkLine(hb, H, lbr, L, cSw, line.style_solid, 1)
        s.lb.push(label.new(hb, H, "H " + str.tostring(H, fmt), xloc=xloc.bar_index, style=label.style_label_down, color=lbBg, textcolor=cSw, size=lsz))
        s.lb.push(label.new(lbr, L, "L " + str.tostring(L, fmt), xloc=xloc.bar_index, style=label.style_label_up, color=lbBg, textcolor=cSw, size=lsz))
    if statsMode == "Label"
        string t1 = "SWING " + (up ? "▲ " : "▼ ") + str.tostring(n) + " bars · Gann " + str.tostring(gannSel) + " · " + str.tostring(effTf, "#") + "m"
        string t2 = "R " + str.tostring(R, fmt) + " · " + str.tostring(R / n, fmt) + "/bar · q " + str.tostring(q, "#.##") + " " + tripleName(ptB)
        string t3 = "H " + str.tostring(H, fmt) + " · L " + str.tostring(L, fmt)
        s.lb.push(label.new(l, yGHi, rowPad(3) + t1 + "\n" + t2 + "\n" + t3, xloc=xloc.bar_index, style=label.style_label_up, color=lbBg, textcolor=cSt, size=ssz, textalign=text.align_left, text_formatting=text.format_bold))
    s
 
// bars-to-go on future nodes (last bar only; the nodes themselves never move)
cdown(Sn s) =>
    if s.nb.size() > 0
        for i = 0 to s.nb.size() - 1
            int away = s.nb.get(i) - bar_index
            label lb0 = s.nl.get(i)
            if away > 0 and not na(lb0)
                string tx = s.nm.get(i) + " · +" + str.tostring(away)
                label.set_text(lb0, s.nk.get(i) == 0 ? rowPad(s.nr.get(i)) + tx : tx + rowSfx(s.nr.get(i)))
 
// ── Signal engine (shared by live bars and the back-fill) ───────────────────
lvTouch(float p, bool allowBuy, bool allowSell, float hi, float lw, float cl, float op, float tol) =>
    bool b = allowBuy and lw <= p + tol and cl > p and cl > op
    bool s2 = allowSell and hi >= p - tol and cl < p and cl < op
    [b, s2]
 
// confluence score (time node + price level + angle/diagonal) of one bar against the grid of master s
sigEval(Sn s, int bi, float hi, float lw, float cl, float op, float cl1, float clP, float tol) =>
    bool nearNode = false
    bool lvBuy = false
    bool lvSell = false
    bool agBuy = false
    bool agSell = false
    if bi >= s.l and bi <= s.xr
        if s.nb.size() > 0
            for i = 0 to s.nb.size() - 1
                if (s.nk.get(i) == 0 or sigQuad) and math.abs(s.nb.get(i) - bi) <= sigTol
                    nearNode := true
        float fr = (bi - s.l) % s.n / float(s.n)
        for j = -rowsDn to rowsUp
            float b0 = s.L + j * s.R
            for m = 0 to (quadOn ? 4 : 2)
                float p = b0 + s.R * (m == 0 ? 0.0 : (m == 1 ? 1.0 : (m == 2 ? 0.5 : (m == 3 ? 0.75 : 0.25))))
                [bb, ss] = lvTouch(p, m != 1, m != 0, hi, lw, cl, op, tol)
                lvBuy := lvBuy or bb
                lvSell := lvSell or ss
            // angle: price on the square diagonals (same pattern in every cell of this row)
            if dgMode != "Swing only" or s.up
                [a1, a2] = lvTouch(b0 + s.R * fr, true, true, hi, lw, cl, op, tol)
                agBuy := agBuy or a1
                agSell := agSell or a2
            if dgMode != "Swing only" or not s.up
                [a3, a4] = lvTouch(b0 + s.R * (1.0 - fr), true, true, hi, lw, cl, op, tol)
                agBuy := agBuy or a3
                agSell := agSell or a4
    bool tB = sigTime and nearNode and cl > op and cl1 < clP
    bool tS = sigTime and nearNode and cl < op and cl1 > clP
    int scB = (tB ? 1 : 0) + (sigPrice and lvBuy ? 1 : 0) + (sigAngle and agBuy ? 1 : 0)
    int scS = (tS ? 1 : 0) + (sigPrice and lvSell ? 1 : 0) + (sigAngle and agSell ? 1 : 0)
    bool okB = not sigHalf or cl >= (hi + lw) / 2.0
    bool okS = not sigHalf or cl <= (hi + lw) / 2.0
    [okB ? scB : 0, okS ? scS : 0]
 
// hindsight pass, run once when a master is created: swing high / low pivots + signals of the bars inside its window.
// Uses the same rules as live signals. Marks belong to the master and are deleted with it.
backfill(Sn s, int hb, int lbr) =>
    float tol = s.R * sigTolPct / 100.0
    int lastD = 0
    int lastA = -999
    int cnt = 0
    for bi = math.max(s.l, 1) to bar_index - 1
        int kk = bar_index - bi
        float hi = high[kk]
        float lw = low[kk]
        float cl = close[kk]
        float op = open[kk]
        if sigPivot and (bi == hb or bi == lbr)
            bool pu = bi == lbr
            s.sg.push(label.new(bi, pu ? lw : hi, "", xloc=xloc.bar_index, yloc=pu ? yloc.belowbar : yloc.abovebar, color=pu ? colBuy : colSell, style=pu ? label.style_triangleup : label.style_triangledown, size=asz3))
            lastD := pu ? 1 : -1
            lastA := bi
        else if sigBack
            [sB, sS] = sigEval(s, bi, hi, lw, cl, op, close[kk + 1], close[kk + 1 + revLook], tol)
            bool cB = cnt < sigMax and (lastD != 1 or bi - lastA >= sigCool)
            bool cS = cnt < sigMax and (lastD != -1 or bi - lastA >= sigCool)
            bool aB = sB >= minConf and cB
            bool aS = sS >= minConf and cS
            bool uB = aB and (not aS or sB >= sS)
            bool uS = aS and not uB
            if uB or uS
                int sc = uB ? sB : sS
                string stl = sc == 1 ? (uB ? sym1B : sym1S) : (uB ? label.style_triangleup : label.style_triangledown)
                s.sg.push(label.new(bi, uB ? lw : hi, "", xloc=xloc.bar_index, yloc=uB ? yloc.belowbar : yloc.abovebar, color=uB ? colBuy : colSell, style=stl, size=sc == 3 ? asz3 : asz))
                lastD := uB ? 1 : -1
                lastA := bi
                cnt += 1
    cnt
 
// ── New master: once per session (intraday) or every N bars (D/W/M), from CLOSED bars only ──
bool isSnap = timeframe.isintraday ? session.isfirstbar : bar_index % rfN == 0
if isSnap and bar_index > 2
    float hh = na
    float ll = na
    int hb2 = 0
    int lb2 = 0
    for k = 1 to math.min(wB, bar_index - 1)
        float hk = close[k]
        float lk2 = close[k]
        if na(hh) or hk > hh
            hh := hk
            hb2 := bar_index - k
        if na(ll) or lk2 < ll
            ll := lk2
            lb2 := bar_index - k
    int nB = math.abs(hb2 - lb2)
    if not na(hh) and hh > ll and nB >= 2 and nB * chartMin / effTf >= math.max(3.0, math.floor(gannSel / 8.0))
        for s in sqs
            if s.full
                demote(s)
        Sn ns = mkSn(hh, ll, hb2, lb2)
        sqs.push(ns)
        cur := ns
        tolPx := (hh - ll) * sigTolPct / 100.0
        sigN := 0
        if sigBack or sigPivot
            int nbk = backfill(ns, hb2, lb2)
        while sqs.size() > pastN + 1
            killSq(sqs.shift())
 
if barstate.islast and tcLabels and not na(cur)
    cdown(cur)
 
// ── Live signals (closed bars only, grid levels of the current master) ──
float pc1 = close[1]
float pcP = close[1 + revLook]
bool okBar = barstate.isconfirmed and not isSnap and not na(cur)
int scB = 0
int scS = 0
if okBar
    if bar_index <= cur.xr
        [sB, sS] = sigEval(cur, bar_index, high, low, close, open, pc1, pcP, tolPx)
        scB := sB
        scS := sS
 
bool canBuy = sigN < sigMax and (lastDir != 1 or bar_index - lastAny >= sigCool)
bool canSell = sigN < sigMax and (lastDir != -1 or bar_index - lastAny >= sigCool)
bool anyBuy = scB >= minConf and canBuy
bool anySell = scS >= minConf and canSell
// if both qualify on the same bar, the stronger one wins
bool useB = anyBuy and (not anySell or scB >= scS)
bool useS = anySell and not useB
if useB
    lastDir := 1
    lastAny := bar_index
    sigN += 1
if useS
    lastDir := -1
    lastAny := bar_index
    sigN += 1
 
// signal marks belong to their master: they are deleted together with it, so no signal is left outside a drawn grid
// 1 of 3 = small arrow, 2 of 3 = small triangle, 3 of 3 = larger triangle (no text)
if useB or useS
    int sc = useB ? scB : scS
    string stl = sc == 1 ? (useB ? sym1B : sym1S) : (useB ? label.style_triangleup : label.style_triangledown)
    cur.sg.push(label.new(bar_index, useB ? low : high, "", xloc=xloc.bar_index, yloc=useB ? yloc.belowbar : yloc.abovebar, color=useB ? colBuy : colSell, style=stl, size=sc == 3 ? asz3 : asz))
 
alertcondition(useB, "Buy", "Square buy signal")
alertcondition(useS, "Sell", "Square sell signal")

← 返回列表