SuperTrend [OrbitOne]

orbitonetv · study · 199 行 · 点赞 8 · 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("SuperTrend [OrbitOne]", "SuperTrend [OrbitOne]", overlay = true, 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 signal labels, dashboard and alert() messages on the chart.")
 
// ════════ SUPERTREND ════════
gT     = "SuperTrend"
stTf   = input.timeframe("", "Timeframe", group = gT, tooltip = "Empty = chart timeframe. A higher timeframe uses its last closed bar, so it does not repaint.")
atrP   = input.int(10, "ATR period", minval = 1, group = gT)
src    = input.source(hl2, "Source", group = gT)
mult   = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1, group = gT, tooltip = "Higher = fewer, slower signals. Lower = more, faster signals.")
useRma = input.bool(true, "Classic ATR (RMA)", group = gT, tooltip = "On: Wilder's ATR (classic SuperTrend). Off: simple moving average of true range.")
 
// ════════ SIGNALS ════════
gS       = "Signals"
confirm  = input.bool(true, "Wait for bar close", group = gS, tooltip = "Signals appear only on closed bars and never repaint.")
side     = input.string("Both", "Direction", options = ["Both", "Buy only", "Sell only"], group = gS)
showRt   = input.bool(false, "Mark retests of the line", group = gS, tooltip = "A small diamond when price touches the SuperTrend line during a trend and closes back on the trend side.")
 
// ════════ FILTERS ════════
gF       = "Filters (all off by default)"
useTrend = input.bool(false, "Trend EMA filter", inline = "t", group = gF)
trendLen = input.int(200, "", minval = 2, inline = "t", group = gF, tooltip = "Buy signals only above this EMA, sell signals only below it.")
useAdx   = input.bool(false, "ADX filter, minimum", inline = "a", group = gF)
adxMin   = input.int(20, "", minval = 1, inline = "a", group = gF, tooltip = "Signals only when ADX(14) is at or above this value.")
useVol   = input.bool(false, "Volume above its 20-bar average", group = gF)
useHtf   = input.bool(false, "Higher timeframe SuperTrend agrees", inline = "h", group = gF)
htf      = input.timeframe("240", "", inline = "h", group = gF, tooltip = "Buy signals only when the SuperTrend on this timeframe is up, sell signals only when it is down.")
 
// ════════ DISPLAY ════════
gV      = "Display"
upCol   = input.color(#4CAF50, "Up trend", inline = "c", group = gV)
dnCol   = input.color(#FF5252, "Down trend", inline = "c", group = gV)
lnW     = input.int(2, "Line width", minval = 1, maxval = 5, group = gV)
showSig = input.bool(true, "Show buy / sell labels", group = gV)
showDot = input.bool(true, "Show trend-start circles", group = gV)
showHl  = input.bool(true, "Highlighter (fill)", group = gV)
hlTr    = input.int(85, "Highlighter transparency", minval = 50, maxval = 98, group = gV)
barCol  = input.bool(false, "Color bars by trend", group = gV)
showTrM = input.bool(false, "Show trend EMA", group = gV)
 
// ════════ DASHBOARD ════════
gD     = "Dashboard"
showDb = input.bool(true, "Show dashboard", group = gD)
tf1    = input.timeframe("60", "Timeframe 1", group = gD)
tf2    = input.timeframe("240", "Timeframe 2", group = gD)
tf3    = input.timeframe("D", "Timeframe 3", group = gD)
dbPos  = input.string("Bottom right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gD)
dbSize = input.string("Tiny", "Size", options = ["Tiny", "Small", "Normal"], group = gD)
 
// ════════ 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
 
txtBuy   = t("Buy", "Al", "Compra", "Compra", "Kauf", "Achat", "Покупка", "买入")
txtSell  = t("Sell", "Sat", "Venta", "Venda", "Verkauf", "Vente", "Продажа", "卖出")
txtTrend = t("Trend", "Trend", "Tendencia", "Tendência", "Trend", "Tendance", "Тренд", "趋势")
txtUp    = t("▲ Up", "▲ Yükseliş", "▲ Alcista", "▲ Alta", "▲ Aufwärts", "▲ Haussière", "▲ Восходящий", "▲ 上涨")
txtDn    = t("▼ Down", "▼ Düşüş", "▼ Bajista", "▼ Baixa", "▼ Abwärts", "▼ Baissière", "▼ Нисходящий", "▼ 下跌")
txtLast  = t("Last signal", "Son sinyal", "Última señal", "Último sinal", "Letztes Signal", "Dernier signal", "Последний сигнал", "最新信号")
txtAgo   = t("Bars ago", "Kaç mum önce", "Velas atrás", "Velas atrás", "Kerzen her", "Bougies depuis", "Свечей назад", "K线前")
txtMove  = t("Move since signal", "Sinyalden beri", "Desde la señal", "Desde o sinal", "Seit dem Signal", "Depuis le signal", "С момента сигнала", "信号以来")
txtDist  = t("Distance to line", "Çizgiye uzaklık", "Distancia a la línea", "Distância à linha", "Abstand zur Linie", "Distance à la ligne", "Расстояние до линии", "距离趋势线")
 
// ════════ CALCULATION ════════
f_st() =>
    float a  = useRma ? ta.atr(atrP) : ta.sma(ta.tr(true), atrP)
    float up = src - mult * a
    float dn = src + mult * a
    var float upL = na
    var float dnL = na
    var int   tr  = 1
    float pu = nz(upL, up)
    float pd = nz(dnL, dn)
    upL := close[1] > pu ? math.max(up, pu) : up
    dnL := close[1] < pd ? math.min(dn, pd) : dn
    tr  := tr == -1 and close > pd ? 1 : tr == 1 and close < pu ? -1 : tr
    [tr, upL, dnL]
 
f_stPrev() =>
    [tr, u, d] = f_st()
    [tr[1], u[1], d[1]]
 
f_trPrev() =>
    [tr, u, d] = f_st()
    tr[1]
 
[t0, u0, d0] = f_st()
[t1, u1, d1] = request.security(syminfo.tickerid, stTf == "" ? timeframe.period : stTf, f_stPrev(), lookahead = barmerge.lookahead_on)
useH  = stTf != "" and stTf != timeframe.period
trend = useH ? t1 : t0
upL   = useH ? u1 : u0
dnL   = useH ? d1 : d0
stLn  = trend == 1 ? upL : dnL
 
hTr = request.security(syminfo.tickerid, htf, f_trPrev(), lookahead = barmerge.lookahead_on)
r1  = request.security(syminfo.tickerid, tf1, f_trPrev(), lookahead = barmerge.lookahead_on)
r2  = request.security(syminfo.tickerid, tf2, f_trPrev(), lookahead = barmerge.lookahead_on)
r3  = request.security(syminfo.tickerid, tf3, f_trPrev(), lookahead = barmerge.lookahead_on)
 
trendMA = ta.ema(close, trendLen)
[diP, diM, adxV] = ta.dmi(14, 14)
volAvg  = ta.sma(volume, 20)
okBar   = not confirm or barstate.isconfirmed
 
flipUp = trend == 1 and trend[1] == -1
flipDn = trend == -1 and trend[1] == 1
filtOk = (not useAdx or adxV >= adxMin) and (not useVol or volume > volAvg)
buySig  = flipUp and okBar and filtOk and side != "Sell only" and (not useTrend or close > trendMA) and (not useHtf or hTr == 1)
sellSig = flipDn and okBar and filtOk and side != "Buy only" and (not useTrend or close < trendMA) and (not useHtf or hTr == -1)
 
rtUp = showRt and okBar and trend == 1 and not flipUp and low <= upL and close > upL
rtDn = showRt and okBar and trend == -1 and not flipDn and high >= dnL and close < dnL
 
var int   lastBar = na
var int   lastDir = 0
var float lastPx  = na
if buySig or sellSig
    lastBar := bar_index
    lastDir := buySig ? 1 : -1
    lastPx  := close
 
// ════════ PLOTS ════════
mPlot = plot(ohlc4, "Price (hidden)", display = display.none)
pUp   = plot(trend == 1 ? upL : na, "Up trend", color = upCol, linewidth = lnW, style = plot.style_linebr)
pDn   = plot(trend == -1 ? dnL : na, "Down trend", color = dnCol, linewidth = lnW, style = plot.style_linebr)
fill(mPlot, pUp, color = showHl ? color.new(upCol, hlTr) : na, title = "Up highlighter")
fill(mPlot, pDn, color = showHl ? color.new(dnCol, hlTr) : na, title = "Down highlighter")
plot(showTrM ? trendMA : na, "Trend EMA", color = color.new(color.gray, 20), linewidth = 1, display = display.all - display.status_line)
 
plotshape(showDot and flipUp ? upL : na, "Up trend begins", shape.circle, location.absolute, upCol, size = size.tiny, display = display.all - display.status_line)
plotshape(showDot and flipDn ? dnL : na, "Down trend begins", shape.circle, location.absolute, dnCol, size = size.tiny, display = display.all - display.status_line)
plotshape(rtUp, "Retest (up)", shape.diamond, location.belowbar, color.new(upCol, 20), size = size.tiny, display = display.all - display.status_line)
plotshape(rtDn, "Retest (down)", shape.diamond, location.abovebar, color.new(dnCol, 20), size = size.tiny, display = display.all - display.status_line)
 
barcolor(barCol ? (trend == 1 ? upCol : dnCol) : na)
 
if showSig and buySig
    label.new(bar_index, upL, txtBuy, style = label.style_label_up, color = upCol, textcolor = color.white, size = size.small)
if showSig and sellSig
    label.new(bar_index, dnL, txtSell, style = label.style_label_down, color = dnCol, textcolor = color.white, size = size.small)
 
// ════════ 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, 9, border_width = 1)
tSize = dbSize == "Tiny" ? size.tiny : dbSize == "Normal" ? size.normal : size.small
 
f_tf(string tf) =>
    tf == "D" or tf == "1D" ? "1D" : tf == "W" or tf == "1W" ? "1W" : tf == "M" or tf == "1M" ? "1M" : str.endswith(tf, "S") ? tf : timeframe.in_seconds(tf) >= 3600 ? str.tostring(timeframe.in_seconds(tf) / 3600) + "H" : tf + "m"
 
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)
 
trTxt(int d) =>
    d == 1 ? txtUp : d == -1 ? txtDn : "—"
trCol(int d) =>
    d == 1 ? upCol : d == -1 ? dnCol : color.gray
 
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, "SuperTrend · " + str.tostring(atrP) + " / " + str.tostring(mult) + " · OrbitOne", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = tSize)
    f_row(1, txtTrend, trTxt(trend), trCol(trend))
    f_row(2, txtLast, lastDir == 1 ? txtBuy : lastDir == -1 ? txtSell : "—", trCol(lastDir))
    f_row(3, txtAgo, na(lastBar) ? "—" : str.tostring(bar_index - lastBar), nc)
    float mv = na(lastPx) ? na : (close - lastPx) / lastPx * 100
    f_row(4, txtMove, na(mv) ? "—" : (mv >= 0 ? "+" : "") + str.tostring(mv, "0.00") + "%", na(mv) ? color.gray : mv * lastDir >= 0 ? color.new(upCol, 20) : color.new(dnCol, 20))
    float ds = na(stLn) ? na : math.abs(close - stLn) / close * 100
    f_row(5, txtDist, na(ds) ? "—" : str.tostring(ds, "0.00") + "%", nc)
    f_row(6, f_tf(tf1), trTxt(r1), trCol(r1))
    f_row(7, f_tf(tf2), trTxt(r2), trCol(r2))
    f_row(8, f_tf(tf3), trTxt(r3), trCol(r3))
 
// ════════ ALERTS ════════
alertcondition(buySig, "Buy signal", "SuperTrend BUY | {{ticker}} | {{interval}} | {{close}}")
alertcondition(sellSig, "Sell signal", "SuperTrend SELL | {{ticker}} | {{interval}} | {{close}}")
alertcondition(buySig or sellSig, "Any signal", "SuperTrend signal | {{ticker}} | {{interval}} | {{close}}")
alertcondition(flipUp or flipDn, "Trend direction change (unfiltered)", "SuperTrend direction changed | {{ticker}} | {{interval}} | {{close}}")
alertcondition(rtUp or rtDn, "Line retest", "SuperTrend line retest | {{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 buySig
    alert("SuperTrend " + txtBuy + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)
if sellSig
    alert("SuperTrend " + txtSell + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), freq)

← 返回列表