Dow Structure - Swings, BOS & CHoCH

uezokazu · study · 261 行 · 点赞 36 · TradingView 原页

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

Pine Script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) K'u Hero
//@version=6
// Dow Structure - Swings, BOS & CHoCH  v1.0
//
// Swing structure (HH / HL / LH / LL), trend state and structure breaks for the chart timeframe only.
//  - Swing high/low: fractal with L bars on the left (strictly lower) and R bars on the right (lower or equal).
//    A swing is known only R bars later, so its label appears R bars after the swing bar (it never moves afterwards).
//  - Method "Pullback low / rally high":
//      Uptrend   = the last pullback low has not been broken. When price breaks above the reference swing high,
//                  the lowest low since that swing high becomes the new pullback low (BOS).
//                  The reference swing high is the trend high (a lower high does not move the pullback low).
//      Downtrend = mirror image with rally highs.
//      Breaking the pullback low (rally high) changes the trend (CHoCH).
//  - Method "HH-HL / LH-LL": up when the last two swing highs AND lows are higher, down when both are lower, otherwise range.
//  - Only closed bars are processed (barstate.isconfirmed), so nothing on past bars changes.
// Display only. This is not a buy/sell signal.
indicator("Dow Structure - Swings, BOS & CHoCH", shorttitle = "Dow Structure", overlay = true, max_labels_count = 500, max_lines_count = 500, max_bars_back = 1001)
 
// ---------- Inputs ----------
grpS = "Structure"
inLeft   = input.int(3, "Swing: left bars", minval = 1, maxval = 20, group = grpS)
inRight  = input.int(3, "Swing: right bars", minval = 1, maxval = 20, group = grpS)
inMethod = input.string("Pullback low / rally high", "Trend method", options = ["Pullback low / rally high", "HH-HL / LH-LL"], group = grpS)
inBreak  = input.string("Close", "Break by", options = ["Close", "Wick"], group = grpS)
 
grpV = "Display"
showSw   = input.bool(true, "Swing labels (HH/HL/LH/LL)", group = grpV, display = display.none)
showEv   = input.bool(true, "Structure breaks (BOS / CHoCH)", group = grpV, display = display.none)
showLv   = input.bool(true, "Key level line (pullback low / rally high)", group = grpV, display = display.none)
showBg   = input.bool(false, "Trend background", group = grpV, display = display.none)
showSt   = input.bool(true, "Trend state box", group = grpV, display = display.none)
stPos    = input.string("Middle right", "Trend state box position", options = ["Middle right", "Bottom right", "Top right", "Bottom left", "Top left"], group = grpV, display = display.none)
cUp      = input.color(#26A69A, "Up color", group = grpV, inline = "col", display = display.none)
cDn      = input.color(#EF5350, "Down color", group = grpV, inline = "col", display = display.none)
cRg      = input.color(#9E9E9E, "Range color", group = grpV, inline = "col", display = display.none)
 
const int MAXLOOK = 1000
bool useM1 = inMethod == "Pullback low / rally high"
bool useWick = inBreak == "Wick"
 
// ---------- Helpers ----------
// lowest low in (fromBar, current bar], returns [bar index, price]; earliest bar wins ties
f_minLow(int fromBar) =>
    int n = math.min(bar_index - fromBar, MAXLOOK)
    int bb = na
    float bp = na
    if n >= 1
        for k = 0 to n - 1
            if na(bp) or low[k] <= bp
                bp := low[k]
                bb := bar_index - k
    [bb, bp]
 
f_maxHigh(int fromBar) =>
    int n = math.min(bar_index - fromBar, MAXLOOK)
    int bb = na
    float bp = na
    if n >= 1
        for k = 0 to n - 1
            if na(bp) or high[k] >= bp
                bp := high[k]
                bb := bar_index - k
    [bb, bp]
 
// swing at offset R: left bars strictly lower/higher, right bars lower-or-equal / higher-or-equal
f_isSwingHigh(int L, int R) =>
    bool ok = bar_index >= L + R
    if ok
        float p = high[R]
        for k = 1 to L
            if not (p > high[R + k])
                ok := false
        for k = 0 to R - 1
            if not (p >= high[k])
                ok := false
    ok
 
f_isSwingLow(int L, int R) =>
    bool ok = bar_index >= L + R
    if ok
        float p = low[R]
        for k = 1 to L
            if not (p < low[R + k])
                ok := false
        for k = 0 to R - 1
            if not (p <= low[k])
                ok := false
    ok
 
// ---------- Core ----------
// returns [dir, level, levelBar, evt, evtLevel, evtFromBar, swH, swL]
//  dir: 1 up, -1 down, 0 range/undetermined
//  evt: 1 BOS up, -1 BOS down, 2 CHoCH up, -2 CHoCH down, 3 range (method 2), 0 none
//  swH: 0 none, 1 H, 2 HH, 3 LH, 4 EQH  (swing bar = bar_index - R) ; swL: 0 none, 1 L, 2 HL, 3 LL, 4 EQL
f_dow(int L, int R, bool m1, bool wick, bool gate) =>
    var int dir = 0
    var float lvl = na
    var int lvlBar = na
    var int refH = na
    var float refHp = na
    var int refL = na
    var float refLp = na
    var float lastH = na
    var float prevH = na
    var float lastL = na
    var float prevL = na
    var int lastHb = na
    var int lastLb = na
    var float hiBase = na
    var float loBase = na
    var int m2 = 0
    int evt = 0
    float evtLv = na
    int evtFrom = na
    int swH = 0
    int swL = 0
    if gate
        hiBase := na(hiBase) ? high : math.max(hiBase, high)
        loBase := na(loBase) ? low : math.min(loBase, low)
        int i = bar_index - R
        // (1) swings confirmed on this bar
        if f_isSwingHigh(L, R)
            float p = high[R]
            swH := na(lastH) ? 1 : p > lastH ? 2 : p < lastH ? 3 : 4
            prevH := lastH
            lastH := p
            lastHb := i
            if not m1 or dir != 1 or p >= hiBase
                refH := i
                refHp := p
        if f_isSwingLow(L, R)
            float p = low[R]
            swL := na(lastL) ? 1 : p > lastL ? 2 : p < lastL ? 3 : 4
            prevL := lastL
            lastL := p
            lastLb := i
            if not m1 or dir != -1 or p <= loBase
                refL := i
                refLp := p
        if m1
            float up = wick ? high : close
            float dn = wick ? low : close
            bool reset = false
            if dir == 1
                if not na(lvl) and dn < lvl
                    evt := -2
                    evtLv := lvl
                    evtFrom := lvlBar
                    [hb, hp] = f_maxHigh(lvlBar)
                    dir := -1
                    lvl := na(hp) ? high : hp
                    lvlBar := na(hb) ? bar_index : hb
                    refL := na
                    reset := true
                else if not na(refH) and up > refHp
                    evt := 1
                    evtLv := refHp
                    evtFrom := refH
                    [lb, lp] = f_minLow(refH)
                    if not na(lb)
                        lvl := lp
                        lvlBar := lb
                    refH := na
                    reset := true
            else if dir == -1
                if not na(lvl) and up > lvl
                    evt := 2
                    evtLv := lvl
                    evtFrom := lvlBar
                    [lb, lp] = f_minLow(lvlBar)
                    dir := 1
                    lvl := na(lp) ? low : lp
                    lvlBar := na(lb) ? bar_index : lb
                    refH := na
                    reset := true
                else if not na(refL) and dn < refLp
                    evt := -1
                    evtLv := refLp
                    evtFrom := refL
                    [hb, hp] = f_maxHigh(refL)
                    if not na(hb)
                        lvl := hp
                        lvlBar := hb
                    refL := na
                    reset := true
            else
                if not na(refH) and up > refHp
                    evt := 2
                    evtLv := refHp
                    evtFrom := refH
                    [lb, lp] = f_minLow(refH)
                    dir := 1
                    lvl := na(lp) ? low : lp
                    lvlBar := na(lb) ? bar_index : lb
                    refH := na
                    reset := true
                else if not na(refL) and dn < refLp
                    evt := -2
                    evtLv := refLp
                    evtFrom := refL
                    [hb, hp] = f_maxHigh(refL)
                    dir := -1
                    lvl := na(hp) ? high : hp
                    lvlBar := na(hb) ? bar_index : hb
                    refL := na
                    reset := true
            if reset
                hiBase := high
                loBase := low
        else
            if not na(lastH) and not na(prevH) and not na(lastL) and not na(prevL)
                int c = lastH > prevH and lastL > prevL ? 1 : lastH < prevH and lastL < prevL ? -1 : 0
                if c != m2
                    evt := c == 1 ? 2 : c == -1 ? -2 : 3
                    evtLv := c == 1 ? lastL : c == -1 ? lastH : close
                    evtFrom := c == 1 ? lastLb : c == -1 ? lastHb : bar_index
                    m2 := c
                dir := m2
                lvl := dir == 1 ? lastL : dir == -1 ? lastH : na
                lvlBar := dir == 1 ? lastLb : dir == -1 ? lastHb : na
    [dir, lvl, lvlBar, evt, evtLv, evtFrom, swH, swL]
 
// ---------- Chart timeframe ----------
[cDir, cLvl, cLvlBar, cEvt, cEvtLv, cEvtFrom, cSwH, cSwL] = f_dow(inLeft, inRight, useM1, useWick, barstate.isconfirmed)
 
// ---------- Drawing ----------
f_col(int d) =>
    d == 1 ? cUp : d == -1 ? cDn : cRg
 
if showSw and cSwH > 0
    string t = cSwH == 1 ? "H" : cSwH == 2 ? "HH" : cSwH == 3 ? "LH" : "EQH"
    label.new(bar_index - inRight, high[inRight], t, style = label.style_label_down, color = color.new(color.black, 100),
         textcolor = cSwH == 2 ? cUp : cSwH == 3 ? cDn : cRg, size = size.small)
if showSw and cSwL > 0
    string t = cSwL == 1 ? "L" : cSwL == 2 ? "HL" : cSwL == 3 ? "LL" : "EQL"
    label.new(bar_index - inRight, low[inRight], t, style = label.style_label_up, color = color.new(color.black, 100),
         textcolor = cSwL == 2 ? cUp : cSwL == 3 ? cDn : cRg, size = size.small)
 
if showEv and cEvt != 0 and cEvt != 3 and not na(cEvtLv) and not na(cEvtFrom)
    color c = cEvt > 0 ? cUp : cDn
    string t = math.abs(cEvt) == 1 ? "BOS" : "CHoCH"
    int x1 = math.max(cEvtFrom, bar_index - 4999)
    line.new(x1, cEvtLv, bar_index, cEvtLv, color = c, style = math.abs(cEvt) == 1 ? line.style_dashed : line.style_solid, width = 1)
    label.new(math.round((x1 + bar_index) / 2), cEvtLv, t, style = cEvt > 0 ? label.style_label_down : label.style_label_up,
         color = color.new(color.black, 100), textcolor = c, size = size.small)
 
// the line breaks for one bar where the level moves (no vertical connector)
plot(showLv and cDir != 0 and cDir == cDir[1] and cLvl == cLvl[1] ? cLvl : na, "Key level", color = f_col(cDir), style = plot.style_linebr, linewidth = 2)
bgcolor(showBg ? color.new(f_col(cDir), 92) : na, title = "Trend background")
 
// ---------- Trend state (small box, last bar) ----------
f_state(int d) =>
    d == 1 ? "Up" : d == -1 ? "Down" : "Range"
f_pos(string p) =>
    p == "Bottom right" ? position.bottom_right : p == "Top right" ? position.top_right : p == "Bottom left" ? position.bottom_left : p == "Top left" ? position.top_left : position.middle_right
var table stTbl = table.new(f_pos(stPos), 1, 2, border_width = 0)
if barstate.islast and showSt
    string lvTxt = cDir != 0 and not na(cLvl) ? (useM1 ? (cDir == 1 ? "Pullback low " : "Rally high ") : (cDir == 1 ? "Last swing low " : "Last swing high ")) + str.tostring(cLvl, format.mintick) : "-"
    table.cell(stTbl, 0, 0, "Trend: " + f_state(cDir), text_color = color.white, bgcolor = color.new(f_col(cDir), 15), text_size = size.small)
    table.cell(stTbl, 0, 1, lvTxt, text_color = color.white, bgcolor = color.new(f_col(cDir), 40), text_size = size.small)

← 返回列表