Market Regime [OrbitOne]

orbitonetv · study · 185 行 · 点赞 10 · 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("Market Regime [OrbitOne]", "Market Regime [OrbitOne]", overlay = true, max_labels_count = 500, max_boxes_count = 200)
 
// ════════ LANGUAGE ════════
lang = input.string("English", "Chart language", options = ["English", "Türkçe", "Español", "Português", "Deutsch", "Français", "Русский", "中文"], tooltip = "Language of the labels, dashboard and alert() messages on the chart.")
 
// ════════ REGIME ════════
gR       = "Regime detection"
diLen    = input.int(14, "ADX / DI length", minval = 2, group = gR)
chopLen  = input.int(14, "Choppiness length", minval = 2, group = gR)
erLen    = input.int(20, "Efficiency ratio length", minval = 2, group = gR)
thr      = input.int(50, "Trend score threshold", minval = 10, maxval = 90, group = gR, tooltip = "The trend score (0-100) combines ADX, the Choppiness Index and Kaufman's Efficiency Ratio. At or above this value the market is treated as trending, below it as ranging. Higher = stricter.")
confirmN = input.int(3, "Bars to confirm a change", minval = 1, maxval = 20, group = gR, tooltip = "A new regime must hold for this many bars before it is accepted. Reduces flicker.")
confirm  = input.bool(true, "Wait for bar close", group = gR, tooltip = "Regime-change labels and alerts appear only on closed bars.")
 
// ════════ DISPLAY ════════
gV       = "Display"
showBg   = input.bool(true, "Background color by regime", group = gV)
bgTr     = input.int(90, "Background transparency", minval = 50, maxval = 98, group = gV)
bullCol  = input.color(#089981, "Trend up", inline = "c", group = gV)
bearCol  = input.color(#F23645, "Trend down", inline = "c", group = gV)
rngCol   = input.color(#787B86, "Range", inline = "c", group = gV)
showZone = input.bool(true, "Draw range zones", group = gV, tooltip = "While the market is ranging, a box tracks the high and low of the range.")
maxZones = input.int(20, "Range zones kept", minval = 1, maxval = 200, group = gV)
showLbl  = input.bool(true, "Label regime changes", group = gV)
barCol   = input.bool(false, "Color bars by regime", 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
 
txtUp    = t("▲ Trend up", "▲ Yükselen trend", "▲ Tendencia alcista", "▲ Tendência de alta", "▲ Aufwärtstrend", "▲ Tendance haussière", "▲ Восходящий тренд", "▲ 上升趋势")
txtDn    = t("▼ Trend down", "▼ Düşen trend", "▼ Tendencia bajista", "▼ Tendência de baixa", "▼ Abwärtstrend", "▼ Tendance baissière", "▼ Нисходящий тренд", "▼ 下降趋势")
txtRng   = t("◆ Range", "◆ Yatay", "◆ Rango", "◆ Lateral", "◆ Seitwärts", "◆ Range", "◆ Флэт", "◆ 震荡")
txtReg   = t("Regime", "Piyasa durumu", "Régimen", "Regime", "Marktphase", "Régime", "Режим", "市场状态")
txtBars  = t("Bars in regime", "Kaç mumdur", "Velas en régimen", "Velas no regime", "Kerzen in Phase", "Bougies dans le régime", "Свечей в режиме", "持续K线")
txtScore = t("Trend score", "Trend puanı", "Puntuación de tendencia", "Pontuação de tendência", "Trend-Score", "Score de tendance", "Оценка тренда", "趋势评分")
txtChop  = t("Choppiness", "Kararsızlık", "Indecisión", "Indecisão", "Choppiness", "Indécision", "Хаотичность", "震荡度")
txtEff   = t("Efficiency", "Verimlilik", "Eficiencia", "Eficiência", "Effizienz", "Efficacité", "Эффективность", "效率")
txtVol   = t("Volatility", "Oynaklık", "Volatilidad", "Volatilidade", "Volatilität", "Volatilité", "Волатильность", "波动率")
txtHigh  = t("High", "Yüksek", "Alta", "Alta", "Hoch", "Haute", "Высокая", "高")
txtNorm  = t("Normal", "Normal", "Normal", "Normal", "Normal", "Normale", "Норма", "正常")
txtLow   = t("Low", "Düşük", "Baja", "Baixa", "Niedrig", "Basse", "Низкая", "低")
 
// ════════ CALCULATION ════════
f_chop(int n) =>
    float s   = math.sum(ta.atr(1), n)
    float rng = ta.highest(high, n) - ta.lowest(low, n)
    rng > 0 ? 100 * math.log10(s / rng) / math.log10(n) : 50.0
 
f_er(int n) =>
    float d = math.sum(math.abs(close - close[1]), n)
    d > 0 ? math.abs(close - close[n]) / d : 0.0
 
f_score() =>
    [dp, dm, adx] = ta.dmi(diLen, diLen)
    float ch   = f_chop(chopLen)
    float er   = f_er(erLen)
    float adxN = math.max(0.0, math.min(1.0, (adx - 10) / 30))
    float chN  = math.max(0.0, math.min(1.0, (61.8 - ch) / 23.6))
    float erN  = math.max(0.0, math.min(1.0, er / 0.6))
    [(adxN + chN + erN) / 3 * 100, dp > dm ? 1 : -1, adx, ch, er]
 
f_htf() =>
    [sc, d, a, c, e] = f_score()
    int r = sc >= thr ? d : 0
    r[1]
 
[score, dir, adxV, chopV, erV] = f_score()
raw = score >= thr ? dir : 0
 
var int reg = 0
held = ta.barssince(raw != raw[1])
if held >= confirmN - 1
    reg := raw
 
okBar   = not confirm or barstate.isconfirmed
changed = reg != reg[1] and okBar
 
var int regStart = 0
if reg != reg[1]
    regStart := bar_index
 
atrV  = ta.atr(14)
volPr = ta.percentrank(atrV, 100)
 
r1 = request.security(syminfo.tickerid, tf1, f_htf(), lookahead = barmerge.lookahead_on)
r2 = request.security(syminfo.tickerid, tf2, f_htf(), lookahead = barmerge.lookahead_on)
r3 = request.security(syminfo.tickerid, tf3, f_htf(), lookahead = barmerge.lookahead_on)
 
// ════════ VISUALS ════════
regCol(int r) =>
    r == 1 ? bullCol : r == -1 ? bearCol : rngCol
regTxt(int r) =>
    r == 1 ? txtUp : r == -1 ? txtDn : txtRng
 
bgcolor(showBg ? color.new(regCol(reg), bgTr) : na, title = "Regime background")
barcolor(barCol ? regCol(reg) : na)
 
if showLbl and changed
    if reg == 1
        label.new(bar_index, low, txtUp, yloc = yloc.belowbar, style = label.style_label_up, color = bullCol, textcolor = color.white, size = size.small)
    else if reg == -1
        label.new(bar_index, high, txtDn, yloc = yloc.abovebar, style = label.style_label_down, color = bearCol, textcolor = color.white, size = size.small)
    else
        label.new(bar_index, high, txtRng, yloc = yloc.abovebar, style = label.style_label_down, color = rngCol, textcolor = color.white, size = size.small)
 
// range zones
var array<box> zones = array.new<box>()
var box   zb = na
var float zH = na
var float zL = na
if showZone
    if reg == 0 and reg[1] != 0
        zH := high
        zL := low
        zb := box.new(bar_index, high, bar_index, low, border_color = color.new(rngCol, 40), bgcolor = color.new(rngCol, 85), border_style = line.style_dashed)
        zones.push(zb)
        while zones.size() > maxZones
            box.delete(zones.shift())
    else if reg == 0 and not na(zb)
        zH := math.max(zH, high)
        zL := math.min(zL, low)
        box.set_top(zb, zH)
        box.set_bottom(zb, zL)
        box.set_right(zb, bar_index)
    else if reg != 0
        zb := na
 
// ════════ 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, 11, 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)
 
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, "Market Regime · OrbitOne", bgcolor = color.new(color.black, 30), text_color = color.white, text_size = tSize)
    f_row(1, txtReg, regTxt(reg), regCol(reg))
    f_row(2, txtBars, str.tostring(bar_index - regStart + 1), nc)
    f_row(3, txtScore, str.tostring(score, "0") + " / 100", score >= thr ? color.new(color.blue, 30) : nc)
    f_row(4, "ADX", str.tostring(adxV, "0.0"), nc)
    f_row(5, txtChop, str.tostring(chopV, "0.0"), nc)
    f_row(6, txtEff, str.tostring(erV, "0.00"), nc)
    f_row(7, txtVol, volPr >= 80 ? txtHigh : volPr <= 20 ? txtLow : txtNorm, volPr >= 80 ? color.new(color.orange, 20) : nc)
    f_row(8, f_tf(tf1), regTxt(r1), regCol(r1))
    f_row(9, f_tf(tf2), regTxt(r2), regCol(r2))
    f_row(10, f_tf(tf3), regTxt(r3), regCol(r3))
 
// ════════ ALERTS ════════
alertcondition(changed and reg == 1, "Trend up started", "Market Regime: trend up | {{ticker}} | {{interval}} | {{close}}")
alertcondition(changed and reg == -1, "Trend down started", "Market Regime: trend down | {{ticker}} | {{interval}} | {{close}}")
alertcondition(changed and reg == 0, "Range started", "Market Regime: range | {{ticker}} | {{interval}} | {{close}}")
alertcondition(changed, "Any regime change", "Market Regime changed | {{ticker}} | {{interval}} | {{close}}")
 
// alert() messages follow the chart language. Create the alert with "Any alert() function call".
if changed
    alert("Market Regime: " + regTxt(reg) + " | " + syminfo.ticker + " | " + timeframe.period + " | " + str.tostring(close, format.mintick), confirm ? alert.freq_once_per_bar_close : alert.freq_once_per_bar)

← 返回列表