Auto Support & Resistance [OrbitOne]

orbitonetv · study · 213 行 · 点赞 53 · TradingView 原页

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

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © orbitonetv
//@version=6
indicator("Auto Support & Resistance [OrbitOne]", "Auto Support & Resistance [OrbitOne]", overlay = true, max_boxes_count = 100, max_labels_count = 500)
 
// ════════ LANGUAGE ════════
lang = input.string("English", "Chart language", options = ["English", "Türkçe", "Español", "Português", "Deutsch", "Français", "Русский", "中文"], tooltip = "Language of the zone labels, signals, dashboard and alert() messages on the chart.")
 
// ════════ ZONES ════════
gZ     = "Zones"
lbL    = input.int(10, "Pivot lookback left", minval = 2, maxval = 50, group = gZ)
lbR    = input.int(10, "Pivot lookback right", minval = 2, maxval = 50, group = gZ, tooltip = "A swing high / low is confirmed after this many bars. Larger = fewer, more important levels.")
maxPiv = input.int(40, "Swing points used", minval = 10, maxval = 150, group = gZ, tooltip = "How many of the most recent swing highs and lows are grouped into zones.")
zoneW  = input.float(0.5, "Zone width (x ATR)", minval = 0.1, step = 0.1, group = gZ, tooltip = "Swing points closer than this distance are merged into one zone. Uses ATR(200), so it adapts to any symbol.")
minT   = input.int(2, "Min touches", minval = 1, group = gZ, tooltip = "A zone needs at least this many swing points to be shown.")
maxZ   = input.int(6, "Zones shown", minval = 1, maxval = 20, group = gZ)
pick   = input.string("Nearest to price", "Which zones", options = ["Nearest to price", "Most touches"], group = gZ, tooltip = "Nearest to price: the zones closest to the current price, above and below. Most touches: the zones price reacted to most often, wherever they are.")
extR   = input.int(20, "Extend right (bars)", minval = 0, group = gZ)
 
// ════════ SIGNALS ════════
gS      = "Signals"
showSig = input.bool(true, "Show breakout labels", group = gS)
confirm = input.bool(true, "Wait for bar close", group = gS, tooltip = "Breakouts are confirmed on closed bars only and never repaint.")
sigGap  = input.int(10, "Min bars between breakouts", minval = 0, group = gS, tooltip = "Hides repeated breakout labels in choppy markets. A breakout in the opposite direction is always shown.")
 
// ════════ DISPLAY ════════
gV      = "Display"
resCol  = input.color(#F23645, "Resistance", inline = "c", group = gV)
supCol  = input.color(#089981, "Support", inline = "c", group = gV)
inCol   = input.color(#FF9800, "Price inside", inline = "c", group = gV)
boxTr   = input.int(85, "Zone transparency", minval = 50, maxval = 98, group = gV)
showLbl = input.bool(true, "Show zone labels", group = gV)
showDb  = input.bool(true, "Show dashboard", group = gV)
dbPos   = input.string("Top right", "Dashboard position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gV)
dbSize  = input.string("Tiny", "Dashboard size", options = ["Tiny", "Small", "Normal"], group = gV)
 
// ════════ TRANSLATIONS ════════
t(string en, string tr, string es, string pt, string de, string fr, string ru, string zh) =>
    switch lang
        "Türkçe"    => tr
        "Español"   => es
        "Português" => pt
        "Deutsch"   => de
        "Français"  => fr
        "Русский"   => ru
        "中文"       => zh
        => en
 
txtRes   = t("Resistance", "Direnç", "Resistencia", "Resistência", "Widerstand", "Résistance", "Сопротивление", "阻力")
txtSup   = t("Support", "Destek", "Soporte", "Suporte", "Unterstützung", "Support", "Поддержка", "支撑")
txtIn    = t("In zone", "Bölge içinde", "En zona", "Na zona", "In Zone", "Dans la zone", "В зоне", "区域内")
txtTouch = t("touches", "temas", "toques", "toques", "Berührungen", "touches", "касаний", "次触及")
txtBrkUp = t("BREAK ▲", "KIRILIM ▲", "RUPTURA ▲", "ROMPIMENTO ▲", "AUSBRUCH ▲", "CASSURE ▲", "ПРОБОЙ ▲", "突破 ▲")
txtBrkDn = t("BREAK ▼", "KIRILIM ▼", "RUPTURA ▼", "ROMPIMENTO ▼", "AUSBRUCH ▼", "CASSURE ▼", "ПРОБОЙ ▼", "突破 ▼")
txtNRes  = t("Nearest resistance", "En yakın direnç", "Resistencia cercana", "Resistência próxima", "Nächster Widerstand", "Résistance proche", "Ближ. сопротивление", "最近阻力")
txtNSup  = t("Nearest support", "En yakın destek", "Soporte cercano", "Suporte próximo", "Nächste Unterstützung", "Support proche", "Ближ. поддержка", "最近支撑")
txtZones = t("Zones", "Bölge sayısı", "Zonas", "Zonas", "Zonen", "Zones", "Зон", "区域数")
txtLast  = t("Last breakout", "Son kırılım", "Última ruptura", "Último rompimento", "Letzter Ausbruch", "Dernière cassure", "Последний пробой", "最近突破")
txtAgo   = t("Bars ago", "Kaç mum önce", "Velas atrás", "Velas atrás", "Kerzen her", "Bougies depuis", "Свечей назад", "K线前")
 
// ════════ SWING POINTS ════════
ph = ta.pivothigh(high, lbL, lbR)
pl = ta.pivotlow(low, lbL, lbR)
 
var array<float> pv = array.new<float>()
var array<int>   pb = array.new<int>()
if not na(ph)
    pv.push(ph)
    pb.push(bar_index - lbR)
if not na(pl)
    pv.push(pl)
    pb.push(bar_index - lbR)
while pv.size() > maxPiv
    pv.shift()
    pb.shift()
 
atrL = ta.atr(200)
atrS = ta.atr(14)
w    = (na(atrL) ? atrS : atrL) * zoneW
 
// ════════ ZONE BUILDING ════════
type Zone
    float lo
    float hi
    int   touches
    int   first
 
f_zones(float width) =>
    array<Zone> all = array.new<Zone>()
    int n = pv.size()
    if n > 0 and not na(width)
        array<int> idx = pv.sort_indices(order.ascending)
        float cLo = pv.get(idx.get(0))
        float cHi = cLo
        int   cnt = 1
        int   fst = pb.get(idx.get(0))
        if n > 1
            for k = 1 to n - 1
                int   j = idx.get(k)
                float p = pv.get(j)
                if p - cLo <= width
                    cHi := p
                    cnt += 1
                    fst := math.min(fst, pb.get(j))
                else
                    all.push(Zone.new(cLo, cHi, cnt, fst))
                    cLo := p
                    cHi := p
                    cnt := 1
                    fst := pb.get(j)
        all.push(Zone.new(cLo, cHi, cnt, fst))
    // keep zones with enough touches, strongest first
    array<Zone>  ok    = array.new<Zone>()
    array<float> score = array.new<float>()
    for z in all
        if z.touches >= minT
            float minH = width * 0.5
            if z.hi - z.lo < minH
                float pad = (minH - (z.hi - z.lo)) / 2
                z.lo := z.lo - pad
                z.hi := z.hi + pad
            ok.push(z)
            score.push(pick == "Most touches" ? z.touches * 1e7 + z.first : -math.abs((z.hi + z.lo) / 2 - close))
    array<Zone> sel = array.new<Zone>()
    if ok.size() > 0
        array<int> ord = score.sort_indices(order.descending)
        for k = 0 to math.min(maxZ, ok.size()) - 1
            sel.push(ok.get(ord.get(k)))
    sel
 
zones = f_zones(w)
 
// ════════ BREAKOUTS ════════
okBar = not confirm or barstate.isconfirmed
bool brkUp = false
bool brkDn = false
float nRes = na
float nSup = na
for z in zones
    if close > z.hi and close[1] <= z.hi
        brkUp := true
    if close < z.lo and close[1] >= z.lo
        brkDn := true
    if z.lo > close
        nRes := na(nRes) ? z.lo : math.min(nRes, z.lo)
    if z.hi < close
        nSup := na(nSup) ? z.hi : math.max(nSup, z.hi)
var int lastDir = 0
var int lastBar = na
gapUp = na(lastBar) or bar_index - lastBar >= sigGap or lastDir != 1
gapDn = na(lastBar) or bar_index - lastBar >= sigGap or lastDir != -1
brkUp := brkUp and okBar and gapUp
brkDn := brkDn and okBar and gapDn and not brkUp
 
if brkUp or brkDn
    lastDir := brkUp ? 1 : -1
    lastBar := bar_index
 
if showSig and brkUp
    label.new(bar_index, low, txtBrkUp, yloc = yloc.belowbar, style = label.style_label_up, color = supCol, textcolor = color.white, size = size.small)
if showSig and brkDn
    label.new(bar_index, high, txtBrkDn, yloc = yloc.abovebar, style = label.style_label_down, color = resCol, textcolor = color.white, size = size.small)
 
// ════════ DRAWING (last bar only) ════════
var array<box>   bxs = array.new<box>()
var array<label> lbs = array.new<label>()
if barstate.islast
    while bxs.size() > 0
        box.delete(bxs.shift())
    while lbs.size() > 0
        label.delete(lbs.shift())
    for z in zones
        color c    = close > z.hi ? supCol : close < z.lo ? resCol : inCol
        string role = close > z.hi ? txtSup : close < z.lo ? txtRes : txtIn
        bxs.push(box.new(z.first, z.hi, bar_index + extR, z.lo, border_color = color.new(c, 40), bgcolor = color.new(c, boxTr)))
        if showLbl
            string txt = role + " · " + str.tostring(z.touches) + " " + txtTouch + " · " + str.tostring((z.hi + z.lo) / 2, format.mintick)
            lbs.push(label.new(bar_index + extR, (z.hi + z.lo) / 2, txt, style = label.style_label_left, color = color.new(c, 20), textcolor = color.white, size = size.tiny))
 
// ════════ DASHBOARD ════════
var table db = table.new(dbPos == "Top right" ? position.top_right : dbPos == "Bottom right" ? position.bottom_right : dbPos == "Top left" ? position.top_left : position.bottom_left, 2, 6, border_width = 1)
tSize = dbSize == "Tiny" ? size.tiny : dbSize == "Normal" ? size.normal : size.small
 
f_row(int r, string k, string v, color c) =>
    table.cell(db, 0, r, k, bgcolor = color.new(color.gray, 35), text_color = color.white, text_size = tSize)
    table.cell(db, 1, r, v, bgcolor = c, text_color = color.white, text_size = tSize)
 
f_lvl(float p) =>
    na(p) ? "—" : str.tostring(p, format.mintick) + "  (" + str.tostring(math.abs(p - close) / close * 100, "0.00") + "%)"
 
if showDb and barstate.isfirst
    table.merge_cells(db, 0, 0, 1, 0)
 
if showDb and barstate.islast
    color nc = color.new(color.gray, 20)
    table.cell(db, 0, 0, "Auto S&R · OrbitOne", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = tSize)
    f_row(1, txtNRes, f_lvl(nRes), na(nRes) ? nc : color.new(resCol, 20))
    f_row(2, txtNSup, f_lvl(nSup), na(nSup) ? nc : color.new(supCol, 20))
    f_row(3, txtZones, str.tostring(zones.size()), nc)
    f_row(4, txtLast, lastDir == 1 ? txtBrkUp : lastDir == -1 ? txtBrkDn : "—", lastDir == 1 ? supCol : lastDir == -1 ? resCol : color.gray)
    f_row(5, txtAgo, na(lastBar) ? "—" : str.tostring(bar_index - lastBar), nc)
 
// ════════ ALERTS ════════
alertcondition(brkUp, "Breakout above resistance", "Auto S&R: breakout UP | {{ticker}} | {{interval}} | {{close}}")
alertcondition(brkDn, "Breakdown below support", "Auto S&R: breakdown DOWN | {{ticker}} | {{interval}} | {{close}}")
alertcondition(brkUp or brkDn, "Any breakout", "Auto S&R: breakout | {{ticker}} | {{interval}} | {{close}}")
 
// alert() messages follow the chart language. Create the alert with "Any alert() function call".
freq = confirm ? alert.freq_once_per_bar_close : alert.freq_once_per_bar
if brkUp
    alert("Auto S&R " + txtBrkUp + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)
if brkDn
    alert("Auto S&R " + txtBrkDn + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)

← 返回列表