Square Root Angle Zones

fahadoverland · study · 246 行 · 点赞 30 · TradingView 原页

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

Pine Script

//@version=6
indicator("Square Root Angle Zones", "√ Angle Zones", overlay = true, max_lines_count = 500, max_labels_count = 500)
 
// Sell zone:  Price = (sqrt(High) - angle)^2      Buy zone:  Price = (sqrt(Low) + angle)^2
// angle = degrees / 360  (your table: 45° = 0.125, 90° = 0.250 ... 360° = 1.000, 720° = 2.000)
//      or degrees / 180  (classic Gann Square of 9: 45° = 0.250, 90° = 0.500 ... 360° = 2.000)   setting "Angle scale"
// High / Low = the last completed candle of the timeframe, the latest swing high / swing low on it,
// or one candle you choose. Lines from: sell lines down from the High and buy lines up from the Low,
// or (one point) lines up AND down from only the High or only the Low
 
// ───── Source ─────
string G1 = "Source"
string tfIn = input.timeframe("D", "Timeframe", group = G1, tooltip = "Last candle: uses the last COMPLETED candle of this timeframe (on D that is yesterday's high and low). Swing High / Low: finds the swings on this timeframe. Chosen candle: uses the candle of this timeframe at the time you choose.")
 
// ───── Angles ─────
string G2 = "Angles"
bool a45  = input.bool(true, "45°", inline = "1", group = G2)
bool a90  = input.bool(true, "90°", inline = "1", group = G2)
bool a135 = input.bool(true, "135°", inline = "2", group = G2)
bool a180 = input.bool(true, "180°", inline = "2", group = G2)
bool a225 = input.bool(true, "225°", inline = "3", group = G2)
bool a270 = input.bool(true, "270°", inline = "3", group = G2)
bool a315 = input.bool(true, "315°", inline = "4", group = G2)
bool a360 = input.bool(true, "360°", inline = "4", group = G2)
 
// ───── Display ─────
string G3 = "Display"
bool   sellIn   = input.bool(true, "Sell / down lines   (sqrt - angle)^2", group = G3, tooltip = "High and Low: lines going down from the High. High only / Low only: lines going down from that point.")
bool   buyIn    = input.bool(true, "Buy / up lines   (sqrt + angle)^2", group = G3, tooltip = "High and Low: lines going up from the Low. High only / Low only: lines going up from that point.")
bool   srcIn    = input.bool(true, "Source High / Low (0°)", group = G3)
bool   labelsIn = input.bool(true, "Show labels", group = G3)
int    lblOffIn = input.int(3, "Label position (bars right of last candle)", minval = 0, maxval = 100, group = G3, tooltip = "All labels start at this point, so buy and sell labels line up in one column.")
int    keepIn   = input.int(3, "Periods to keep", minval = 1, maxval = 20, group = G3)
color  sellCol  = input.color(color.red, "Sell", inline = "c", group = G3)
color  buyCol   = input.color(color.green, "Buy", inline = "c", group = G3)
color  srcCol   = input.color(color.gray, "High / Low", inline = "c", group = G3)
string styleIn  = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = G3)
int    widthIn  = input.int(1, "Line width", minval = 1, maxval = 4, group = G3)
bool   priceIn  = input.bool(false, "Show price in labels", group = G3)
int    circIn   = input.int(2, "Circles  (each circle adds 360°)", minval = 1, maxval = 4, group = G2, tooltip = "1 = angles up to 360°. 2 = also 405° to 720°. 3 = up to 1080°. 4 = up to 1440°. The angle boxes apply to every circle: 45° also turns on 405°, 765° and so on.")
string LAST_CANDLE = "Last candle"
string SWINGS      = "Swing High / Low"
string PICKED      = "Chosen candle"
string modeIn   = input.string(LAST_CANDLE, "Calculate from", options = [LAST_CANDLE, SWINGS, PICKED], group = G1, tooltip = "Last candle = High and Low of the last completed candle of the timeframe. Swing High / Low = the latest confirmed swing high and swing low on that timeframe. Chosen candle = the candle you choose with the time below.")
int    swLenIn  = input.int(5, "Swing strength (candles each side)", minval = 1, maxval = 50, group = G1, tooltip = "Swing High / Low only. A swing high needs this many lower highs on each side, a swing low this many higher lows, on the chosen timeframe. A swing is used once it is confirmed, so it does not repaint.")
int    pickIn   = input.time(timestamp("22 Oct 2026 00:00 +0300"), "Chosen candle time", confirm = true, group = G1, tooltip = "Chosen candle only. The candle of the timeframe above that contains this time is used, once it has closed. Set the timeframe to your chart's timeframe to use exactly the candle you pick.")
string BOTH      = "High and Low"
string HIGH_ONLY = "High only (up and down)"
string LOW_ONLY  = "Low only (up and down)"
string sideIn   = input.string(BOTH, "Lines from", options = [BOTH, HIGH_ONLY, LOW_ONLY], group = G1, tooltip = "High and Low = sell lines down from the High and buy lines up from the Low (they can land close together in pairs). High only / Low only = lines up AND down from that one point, so there are no pairs.")
string SCALE_360 = "÷ 360   (45° = 0.125 … 360° = 1)"
string SCALE_180 = "÷ 180   (45° = 0.25 … 360° = 2)"
string scaleIn  = input.string(SCALE_360, "Angle scale", options = [SCALE_360, SCALE_180], group = G2, tooltip = "How an angle becomes the number added to or taken from the square root. ÷ 360 = your table: 45° = 0.125, 90° = 0.25, 180° = 0.5, 360° = 1. ÷ 180 = classic Gann Square of 9: 45° = 0.25, 90° = 0.5, 180° = 1, 360° = 2, so every line is about twice as far from the High / Low.")
 
if timeframe.in_seconds(tfIn) < timeframe.in_seconds(timeframe.period)
    runtime.error("Choose a timeframe that is the same as or higher than the chart's timeframe.")
 
// latest CONFIRMED swing high / low on the chosen timeframe, and the time of the swing candles
swings(int len) =>
    float ph  = ta.pivothigh(high, len, len)
    float pl  = ta.pivotlow(low, len, len)
    float sh  = ta.valuewhen(not na(ph), ph, 0)
    float sl  = ta.valuewhen(not na(pl), pl, 0)
    int   shT = ta.valuewhen(not na(ph), time[len], 0)
    int   slT = ta.valuewhen(not na(pl), time[len], 0)
    [sh[1], sl[1], shT[1], slT[1]]
 
// ticker.standard = real candle prices, even if the chart uses Heikin Ashi or other special candles.
// [1] + lookahead_on = only completed candles of the chosen timeframe are used (no repainting)
string SYM = ticker.standard(syminfo.tickerid)
[hCandle, lCandle, tCandle]  = request.security(SYM, tfIn, [high[1], low[1], time[1]], lookahead = barmerge.lookahead_on)
[hSwing, lSwing, hSwT, lSwT] = request.security(SYM, tfIn, swings(swLenIn), lookahead = barmerge.lookahead_on)
int tfOpenTime = time(tfIn)
 
bool useSwing = modeIn == SWINGS
bool usePick  = modeIn == PICKED
 
// chosen candle: caught once, on the first bar after it has closed
var float hPick   = na
var float lPick   = na
var int   tPick   = na
bool      pickNew = false
if usePick and na(hPick) and not na(tCandle) and tCandle <= pickIn and pickIn < tfOpenTime
    hPick   := hCandle
    lPick   := lCandle
    tPick   := tCandle
    pickNew := true
 
float hPrev = usePick ? hPick : useSwing ? hSwing : hCandle
float lPrev = usePick ? lPick : useSwing ? lSwing : lCandle
 
string lineStyle = switch styleIn
    "Solid"  => line.style_solid
    "Dotted" => line.style_dotted
    => line.style_dashed
 
int barMs = timeframe.in_seconds(timeframe.period) * 1000
 
// the number for each angle: degrees ÷ 360 (your table) or degrees ÷ 180 (classic Square of 9)
float DIV = scaleIn == SCALE_180 ? 180.0 : 360.0
 
// every label starts at the same point right of the last candle and sits just above its line,
// so buy and sell labels line up in one column
string LBL_STYLE = label.style_label_lower_left
 
var array<int>  ANGLES = array.from(45, 90, 135, 180, 225, 270, 315, 360)
var array<bool> ACTIVE = array.from(a45, a90, a135, a180, a225, a270, a315, a360)
 
type Period
    array<line>  lines
    array<label> labels
 
// one label entry, before entries on the same line are joined into one label
type Tag
    float  y
    string txt
    color  col
 
// (sqrt(price) +/- angle)^2    dir = -1 for sell (from High), +1 for buy (from Low)
levelAt(float price, float dec, int dir) =>
    float r = math.sqrt(price) + dir * dec
    r > 0 ? r * r : na
 
// a line from time x1 to the right
addLine(Period p, float y, color col, string st, int w, int x1) =>
    p.lines.push(line.new(x1, y, time + barMs, y, xloc = xloc.bar_time, extend = extend.right, color = col, style = st, width = w))
 
// label text = the angle, plus the price when "Show price in labels" is on
labelText(string name, float y) =>
    priceIn ? name + " · " + str.tostring(y, format.mintick) : name
 
addLevel(Period p, array<Tag> tags, float src, int angle, int dir, color col, int x1) =>
    float y = levelAt(src, angle / DIV, dir)
    if not na(y)
        addLine(p, y, col, lineStyle, widthIn, x1)
        if labelsIn
            tags.push(Tag.new(y, labelText(str.tostring(angle) + "°", y), col))
 
// one label per line: entries at (almost) the same price are joined into one label, one angle per row
addLabels(Period p, array<Tag> tags) =>
    int n = tags.size()
    if n > 0
        array<float> ys = array.new<float>()
        for t in tags
            ys.push(t.y)
        array<int> idx = ys.sort_indices(order.descending)
        int i = 0
        while i < n
            Tag    first = tags.get(idx.get(i))
            float  top   = first.y
            string txt   = first.txt
            // "same line" = closer than 15% of a 45° step (on gold about 2.4 points with ÷ 360, 4.8 with ÷ 180)
            float  thr   = 0.3 * (45.0 / DIV) * math.sqrt(top)
            int j = i + 1
            while j < n
                Tag t = tags.get(idx.get(j))
                if top - t.y > thr
                    break
                txt := txt + "\n" + t.txt
                j += 1
            p.labels.push(label.new(bar_index + lblOffIn, top, txt, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(color.black, 100), style = LBL_STYLE, textcolor = first.col, size = size.small, textalign = text.align_left))
            i := j
 
var array<Period> periods = array.new<Period>()
 
// a new set of levels starts with every new candle (Last candle), when a new swing is confirmed (Swing High / Low),
// or once when the chosen candle has closed (Chosen candle)
bool tfNew     = timeframe.change(tfIn)
bool hChanged  = not na(hSwing) and hSwing != nz(hSwing[1])
bool lChanged  = not na(lSwing) and lSwing != nz(lSwing[1])
bool swingNew  = sideIn == HIGH_ONLY ? hChanged : sideIn == LOW_ONLY ? lChanged : (hChanged or lChanged)
bool newPeriod = usePick ? pickNew : useSwing ? swingNew : tfNew
 
// which points are used: both, or only the High / only the Low
bool useHigh = sideIn != LOW_ONLY
bool useLow  = sideIn != HIGH_ONLY
bool onePt   = sideIn != BOTH
 
if newPeriod and (not useHigh or not na(hPrev)) and (not useLow or not na(lPrev))
    // end the previous period's lines here and remove its labels
    if periods.size() > 0
        Period prev = periods.last()
        for ln in prev.lines
            ln.set_x2(time)
            ln.set_extend(extend.none)
        for lb in prev.labels
            lb.delete()
        prev.labels.clear()
 
    Period     p    = Period.new(array.new<line>(), array.new<label>())
    array<Tag> tags = array.new<Tag>()
 
    // chosen candle: every line starts at that candle. Swings: the High / Low lines start at the swing candles
    int lvlX = usePick ? tPick : time
    int hiX  = usePick ? tPick : useSwing ? hSwT : time
    int loX  = usePick ? tPick : useSwing ? lSwT : time
 
    if srcIn
        if useHigh
            addLine(p, hPrev, srcCol, line.style_solid, 1, hiX)
            if labelsIn
                tags.push(Tag.new(hPrev, labelText("0°", hPrev), srcCol))
        if useLow
            addLine(p, lPrev, srcCol, line.style_solid, 1, loX)
            if labelsIn
                tags.push(Tag.new(lPrev, labelText("0°", lPrev), srcCol))
 
    // down lines start from the High, up lines from the Low; with one point, both start from that point
    float downFrom = onePt ? (useHigh ? hPrev : lPrev) : hPrev
    float upFrom   = onePt ? (useHigh ? hPrev : lPrev) : lPrev
 
    // every circle repeats the chosen angles, 360° further out
    for c = 0 to circIn - 1
        for [i, a] in ANGLES
            if ACTIVE.get(i)
                int ang = a + 360 * c
                if sellIn
                    addLevel(p, tags, downFrom, ang, -1, sellCol, lvlX)
                if buyIn
                    addLevel(p, tags, upFrom, ang, 1, buyCol, lvlX)
 
    if labelsIn
        addLabels(p, tags)
 
    periods.push(p)
 
    // keep only the last N periods
    if periods.size() > keepIn
        Period old = periods.shift()
        for ln in old.lines
            ln.delete()
        for lb in old.labels
            lb.delete()
 
// keep the current labels at the label point right of the last candle
if barstate.islast and periods.size() > 0
    for lb in periods.last().labels
        lb.set_x(bar_index + lblOffIn)
 
// chosen candle not usable yet: say why, next to the last candle
var label note = na
if barstate.islast
    label.delete(note)
    if usePick and na(hPick)
        string msg = pickIn >= tfOpenTime ? "Chosen candle has not closed yet" : "Chosen candle is not on this chart. Pick a later time"
        note := label.new(bar_index + lblOffIn, close, msg, xloc = xloc.bar_index, yloc = yloc.price, color = color.new(color.black, 100), style = LBL_STYLE, textcolor = srcCol, size = size.small)

← 返回列表