SW Box MTF

piyacham · study · 379 行 · 点赞 38 · TradingView 原页

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

Pine Script

//@version=6
indicator("SW Box MTF", shorttitle = "SW Box MTF", overlay = true, max_boxes_count = 500, max_labels_count = 500)
 
// ═══════════════════════════════════════════════════════════════
//  SW Box MTF : Multi-timeframe SW consolidation boxes
// ═══════════════════════════════════════════════════════════════
 
// ───────────── Inputs ─────────────
const string G_TF  = "SW Box Timeframes"
bool  useH1 = input.bool(true,  "H1",    inline = "h1", group = G_TF)
color colH1 = input.color(#2962FF, "",   inline = "h1", group = G_TF)
bool  useH4 = input.bool(true,  "H4",    inline = "h4", group = G_TF)
color colH4 = input.color(#FFEB3B, "",   inline = "h4", group = G_TF)
bool  useD  = input.bool(true,  "24H",   inline = "d",  group = G_TF)
color colD  = input.color(#E040FB, "",   inline = "d",  group = G_TF)
bool  useW  = input.bool(false, "W",     inline = "w",  group = G_TF)
color colW  = input.color(#FF7043, "",   inline = "w",  group = G_TF)
bool  useMN = input.bool(false, "Month", inline = "mn", group = G_TF)
color colMN = input.color(#B0BEC5, "",   inline = "mn", group = G_TF)
 
const string G_BOX = "SW Box Rules"
float dojiPct   = input.float(20, "Small-body threshold (body as % of the candle range)", minval = 0, maxval = 100, step = 5, group = G_BOX,
                  tooltip = "Small-bodied candles never count as a STOP and never confirm a box | 0 = only candles where open = close")
int   minRest   = input.int(1, "Min. STOP + Retrace candles before confirming a box", minval = 1, group = G_BOX)
bool  confIn    = input.bool(true, "Always include the confirming candle in the box", group = G_BOX,
                  tooltip = "Off: if the confirming candle closes outside the box, the box is not extended and the candle counts as the first close outside the box")
bool  contOn    = input.bool(false, "Confirming candle closing far outside = trend continues (no box)", group = G_BOX)
float contPct   = input.float(50, "  ↳ Counts as continuation when it closes beyond the edge by (% of box height)", minval = 0, maxval = 500, step = 10, group = G_BOX)
bool  revOn     = input.bool(false, "Retrace closing beyond the leg's start = immediate reversal", group = G_BOX)
bool  restNew   = input.bool(true, "Retrace making a new extreme = restart the box from that candle", group = G_BOX)
bool  restBeyond = input.bool(true, "  ↳ Only when the Retrace closes beyond the leg's start", group = G_BOX)
int   restNewMin = input.int(4, "  ↳ Restart only after at least this many STOP + Retrace candles", minval = 1, maxval = 20, group = G_BOX)
int   restRatio = input.int(0, "Retrace deeper than % of the leg = new leg (0 = off)", minval = 0, maxval = 1000, step = 25, group = G_BOX)
int   maxRest   = input.int(0, "Max. STOP + Retrace candles (0 = unlimited)", minval = 0, maxval = 20, group = G_BOX)
bool  edgeClose = input.string("Close", "Box edges based on", options = ["Close", "Candle body"], group = G_BOX) == "Close"
bool  wickAfter = input.bool(false, "Extend edges with wicks (High/Low) after confirmation", group = G_BOX)
 
const string G_TCH = "Price Reaches SW Box"
bool   alertTouch = input.bool(true, "Alert when a closed candle reaches the SW box", group = G_TCH,
                    tooltip = "Price must first be outside the latest box (any TF) for at least one closed candle, then a closed candle comes back to the box edge. Checked once per chart candle close.")
bool   touchClose = input.string("Wick", "Reach by", options = ["Wick", "Close"], group = G_TCH,
                    tooltip = "Wick: the candle's High/Low touches the box edge | Close: the candle closes at or inside the box edge") == "Close"
bool   showTouch  = input.bool(false, "Show 'Reached' labels on the chart", group = G_TCH)
 
const string G_DRW = "Display"
int    keepBoxes   = input.int(2, "Previous boxes to keep (0 = latest box only)", minval = 0, maxval = 50, group = G_DRW)
int    fillTransp  = input.int(100, "Box fill transparency (100 = no fill)", minval = 0, maxval = 100, group = G_DRW)
int    borderW     = input.int(2, "Box border width", minval = 1, maxval = 5, group = G_DRW)
string boxLblSzStr = input.string("Normal", "Box label size", options = ["Tiny", "Small", "Normal", "Large"], group = G_DRW)
string boxLblSize  = boxLblSzStr == "Tiny" ? size.tiny : boxLblSzStr == "Small" ? size.small : boxLblSzStr == "Large" ? size.large : size.normal
bool   boxLblRight = input.string("Top right", "Box label position", options = ["Top right", "Top left"], group = G_DRW) == "Top right"
int    boxExtBars  = input.int(3, "Extend active box to the right (bars)", minval = 0, maxval = 50, group = G_DRW)
bool   showTable   = input.bool(true, "Show status table", group = G_DRW)
string tblSizeStr  = input.string("Normal", "Table text size", options = ["Small", "Normal", "Large"], group = G_DRW)
string tblPosStr   = input.string("Top Right", "Table position", options = ["Top Left", "Top Right", "Bottom Left", "Bottom Right"], group = G_DRW)
 
// ───────────── Type ─────────────
// phase 0 = Expand (waiting for STOP) | 1 = Retrace (waiting for confirmation) | 2 = active SW box
type Cycle
    string     name
    color      col
    int        phase     = 0
    int        runDir    = 0
    float      lastClose
    int        restDir   = 0
    int        restCount = 0
    float      top
    float      bot
    int        startTime
    int        pendDir   = 0
    float      pendTop
    float      pendBot
    float      pendClose
    float      pendOpen
    float      runStart          // open of the first candle in the current leg
    float      stopOpen          // open of the STOP candle
    box        bx
    array<box> history
    int        lastProc  = 0     // open time of the last processed HTF candle
    bool       newBox    = false // a new box was confirmed on this bar
    bool       endBox    = false // a box ended on this bar
    int        tSide     = 0     // 1 = price is above the box, -1 = below, 0 = at / inside
    int        tLeft             // left edge of the box being watched (detects a new box)
 
method addRange(Cycle s, float hiV, float loV) =>
    s.top := na(s.top) ? hiV : math.max(s.top, hiV)
    s.bot := na(s.bot) ? loV : math.min(s.bot, loV)
 
method finishBox(Cycle s, int rightT) =>
    if not na(s.bx)
        s.bx.set_right(rightT)
        s.history.push(s.bx)
        s.endBox := true
    s.bx := na
 
// phase 0 : Expand → look for STOP
method runStep(Cycle s, int rawDir, bool small, float o, float bTop, float bBot, float c, int t) =>
    int dir = rawDir
    if small and s.runDir != 0 and rawDir != s.runDir
        dir := 0                                   // small-bodied candle never counts as STOP
    if dir != 0
        if s.runDir == 0 or dir == s.runDir
            if s.runDir == 0 or na(s.runStart)
                s.runStart := o
            s.runDir    := dir
            s.lastClose := c
        else
            // STOP
            s.phase     := 1
            s.restDir   := dir
            s.restCount := 1
            s.top       := na
            s.bot       := na
            if not na(s.lastClose)
                s.addRange(s.lastClose, s.lastClose)
            s.addRange(bTop, bBot)
            s.startTime := t
            s.stopOpen  := o
    s.phase
 
// called when one HTF candle has closed
method onHtfClose(Cycle s, float o, float h, float l, float c, int t) =>
    float rng   = h - l
    bool  small = rng <= 0 or math.abs(c - o) / rng * 100 <= dojiPct
    int   dir   = c > o ? 1 : c < o ? -1 : 0
    float bTop  = edgeClose ? c : math.max(o, c)
    float bBot  = edgeClose ? c : math.min(o, c)
 
    if s.phase == 0
        s.runStep(dir, small, o, bTop, bBot, c, t)
 
    else if s.phase == 1
        if small and dir == -s.restDir
            dir := 0
        if dir == -s.restDir
            float bh   = s.top - s.bot
            bool  cont = contOn and (s.runDir == 1 ? c > s.top + bh * contPct / 100 : c < s.bot - bh * contPct / 100)
            if cont
                s.phase     := 0
                s.lastClose := c
                s.restCount := 0
            else
                int outConf = (not confIn and s.restCount >= minRest) ? (c > s.top ? 1 : c < s.bot ? -1 : 0) : 0
                if outConf == 0
                    s.addRange(bTop, bBot)
                if s.restCount >= minRest
                    // SW box confirmed
                    s.phase   := 2
                    s.pendDir := outConf
                    if outConf != 0
                        s.pendTop   := wickAfter ? h : bTop
                        s.pendBot   := wickAfter ? l : bBot
                        s.pendClose := c
                        s.pendOpen  := o
                    while s.history.size() > keepBoxes
                        box.delete(s.history.shift())
                    s.bx := box.new(s.startTime, s.top, time, s.bot, xloc = xloc.bar_time,
                                    border_color = s.col, border_width = borderW, bgcolor = color.new(s.col, fillTransp),
                                    text = "SW " + s.name, text_color = s.col, text_size = boxLblSize,
                                    text_halign = boxLblRight ? text.align_right : text.align_left, text_valign = text.align_top)
                    s.newBox := true
        else if revOn and dir == s.restDir and not na(s.runStart) and (s.restDir == 1 ? c > s.runStart : c < s.runStart)
            // Retrace closed beyond the leg's start → new leg
            s.phase     := 0
            s.runDir    := s.restDir
            s.runStart  := s.stopOpen
            s.lastClose := c
            s.restCount := 0
            s.top       := na
            s.bot       := na
        else if restNew and dir == s.restDir and s.restCount >= restNewMin and (s.restDir == 1 ? c > s.top : c < s.bot) and (not restBeyond or (not na(s.runStart) and (s.restDir == 1 ? c > s.runStart : c < s.runStart)))
            // Retrace made a new extreme → restart the forming box from this candle
            s.top       := na
            s.bot       := na
            s.addRange(bTop, bBot)
            s.startTime := t
            s.restCount += 1
        else if restRatio > 0 and dir == s.restDir and not na(s.runStart) and not na(s.lastClose) and math.abs(s.lastClose - s.runStart) > 0 and (s.restDir == 1 ? c > s.lastClose : c < s.lastClose) and math.abs(c - s.lastClose) > math.abs(s.lastClose - s.runStart) * restRatio / 100.0
            // Retrace deeper than the allowed ratio of the leg → new leg
            s.phase     := 0
            s.runDir    := s.restDir
            s.runStart  := s.stopOpen
            s.lastClose := c
            s.restCount := 0
            s.top       := na
            s.bot       := na
        else if maxRest > 0 and dir == s.restDir and s.restCount >= maxRest and (s.restDir == 1 ? c > s.top : c < s.bot)
            // Retrace too long and closed beyond the forming box → new leg
            s.phase     := 0
            s.runDir    := s.restDir
            s.runStart  := s.stopOpen
            s.lastClose := c
            s.restCount := 0
            s.top       := na
            s.bot       := na
        else
            s.addRange(bTop, bBot)
            if dir == s.restDir
                s.restCount += 1
 
    else if s.phase == 2
        float aTop     = wickAfter ? h : bTop
        float aBot     = wickAfter ? l : bBot
        int   out      = c > s.top ? 1 : c < s.bot ? -1 : 0
        bool  sameSide = s.pendDir != 0 and out == s.pendDir
        if sameSide and not small
            // two consecutive closes outside → box ends, first outside candle starts the leg
            s.finishBox(time)
            s.phase     := 0
            s.runDir    := s.pendDir
            s.runStart  := s.pendOpen
            s.lastClose := s.pendClose
            s.pendDir   := 0
            s.top       := na
            s.bot       := na
            s.runStep(dir, small, o, bTop, bBot, c, t)
        else if not sameSide
            if s.pendDir != 0
                // false break: back inside → include the outside candle in the box
                s.addRange(s.pendTop, s.pendBot)
                s.pendDir := 0
                out := c > s.top ? 1 : c < s.bot ? -1 : 0
            if out != 0
                s.pendDir   := out
                s.pendTop   := aTop
                s.pendBot   := aBot
                s.pendClose := c
                s.pendOpen  := o
            else
                s.addRange(aTop, aBot)
            s.bx.set_top(s.top)
            s.bx.set_bottom(s.bot)
        // sameSide and small → small-bodied candle outside on the same side, wait for the next candle
    s.phase
 
method stateText(Cycle s) =>
    s.phase == 2 ? (s.pendDir == 1 ? "Consolidate (1 close above)" : s.pendDir == -1 ? "Consolidate (1 close below)" : "Consolidate") :
     s.phase == 1 ? (s.restDir == 1 ? "Retrace ▲" : "Retrace ▼") :
     s.runDir == 1 ? "Expand ▲" : s.runDir == -1 ? "Expand ▼" : "-"
 
// ───────────── HTF data (closed candles, no repaint) ─────────────
int chartSec = timeframe.in_seconds()
htfAll(string tf, bool use) =>
    request.security(syminfo.tickerid, use ? tf : timeframe.period,
         [open[1], high[1], low[1], close[1], time[1], open, high, low, close, time, time_close], lookahead = barmerge.lookahead_on)
 
bool okH1 = timeframe.in_seconds("60")   >= chartSec
bool okH4 = timeframe.in_seconds("240")  >= chartSec
bool okD  = timeframe.in_seconds("1440") >= chartSec
bool okW  = timeframe.in_seconds("W")    >= chartSec
bool okMN = timeframe.in_seconds("M")    >= chartSec
 
[oH1, hH1, lH1, cH1, tH1, nOH1, nHH1, nLH1, nCH1, nTH1, ctH1] = htfAll("60",   useH1 and okH1)
[oH4, hH4, lH4, cH4, tH4, nOH4, nHH4, nLH4, nCH4, nTH4, ctH4] = htfAll("240",  useH4 and okH4)
[oD,  hD,  lD,  cD,  tD,  nOD,  nHD,  nLD,  nCD,  nTD,  ctD ] = htfAll("1440", useD  and okD)
[oW,  hW,  lW,  cW,  tW,  nOW,  nHW,  nLW,  nCW,  nTW,  ctW ] = htfAll("W",    useW  and okW)
[oMN, hMN, lMN, cMN, tMN, nOMN, nHMN, nLMN, nCMN, nTMN, ctMN] = htfAll("M",    useMN and okMN)
 
newCycle(string n, color c) =>
    Cycle.new(name = n, col = c, history = array.new<box>())
 
var Cycle sH1 = newCycle("H1",  colH1)
var Cycle sH4 = newCycle("H4",  colH4)
var Cycle sD  = newCycle("24H", colD)
var Cycle sW  = newCycle("W",   colW)
var Cycle sMN = newCycle("MN",  colMN)
 
cycleStep(Cycle s, bool on, float o, float h, float l, float c, int t, bool isNew,
          float no, float nh, float nl, float nc, int nt, bool isLast) =>
    s.newBox := false
    s.endBox := false
    if on and barstate.isconfirmed
        // previous HTF candle not processed yet (fallback)
        if isNew and not na(c) and t != s.lastProc
            s.onHtfClose(o, h, l, c, t)
            s.lastProc := t
        // this chart bar is the last bar of the HTF candle → process now
        if isLast and not na(nc) and nt != s.lastProc
            s.onHtfClose(no, nh, nl, nc, nt)
            s.lastProc := nt
    if on and not na(s.bx)
        s.bx.set_right(time + boxExtBars * chartSec * 1000)
    [s.newBox, s.endBox]
 
[nbH1, ebH1] = cycleStep(sH1, useH1 and okH1, oH1, hH1, lH1, cH1, tH1, tH1 != tH1[1], nOH1, nHH1, nLH1, nCH1, nTH1, time_close == ctH1)
[nbH4, ebH4] = cycleStep(sH4, useH4 and okH4, oH4, hH4, lH4, cH4, tH4, tH4 != tH4[1], nOH4, nHH4, nLH4, nCH4, nTH4, time_close == ctH4)
[nbD,  ebD ] = cycleStep(sD,  useD  and okD,  oD,  hD,  lD,  cD,  tD,  tD  != tD[1],  nOD,  nHD,  nLD,  nCD,  nTD,  time_close == ctD)
[nbW,  ebW ] = cycleStep(sW,  useW  and okW,  oW,  hW,  lW,  cW,  tW,  tW  != tW[1],  nOW,  nHW,  nLW,  nCW,  nTW,  time_close == ctW)
[nbMN, ebMN] = cycleStep(sMN, useMN and okMN, oMN, hMN, lMN, cMN, tMN, tMN != tMN[1], nOMN, nHMN, nLMN, nCMN, nTMN, time_close == ctMN)
 
// ───────────── Alerts (new box / box ended) ─────────────
alertcondition(nbH1 or nbH4 or nbD or nbW or nbMN, "New SW box (any TF)", "New SW box {{ticker}} price {{close}}")
alertcondition(nbH1, "New SW box H1",  "New SW box H1 {{ticker}} price {{close}}")
alertcondition(nbH4, "New SW box H4",  "New SW box H4 {{ticker}} price {{close}}")
alertcondition(nbD,  "New SW box 24H", "New SW box 24H {{ticker}} price {{close}}")
alertcondition(ebH1 or ebH4 or ebD or ebW or ebMN, "SW box ended (any TF)", "SW box ended {{ticker}} price {{close}}")
 
// ───────────── Price reaches SW box (checked on chart candle close) ─────────────
// returns 1 = reached the top edge from above, -1 = reached the bottom edge from below, 0 = none
touchStep(Cycle s, bool on) =>
    int hit = 0
    if on and barstate.isconfirmed
        box b = not na(s.bx) ? s.bx : s.history.size() > 0 ? s.history.last() : na
        if not na(b)
            float bt   = b.get_top()
            float bb   = b.get_bottom()
            int   lf   = b.get_left()
            float hiP  = touchClose ? close : high
            float loP  = touchClose ? close : low
            if na(s.tLeft) or lf != s.tLeft
                s.tLeft := lf                    // new box → wait for price to leave it first
                s.tSide := low > bt ? 1 : high < bb ? -1 : 0
            else
                hit := s.tSide == 1 and loP <= bt ? 1 : s.tSide == -1 and hiP >= bb ? -1 : 0
                if hit != 0
                    s.tSide := 0
                    if showTouch
                        label.new(time, hit == 1 ? low : high, "Reached SW " + s.name, xloc = xloc.bar_time,
                                  style = hit == 1 ? label.style_label_up : label.style_label_down,
                                  color = color.new(s.col, 30), textcolor = color.black, size = size.small)
                else
                    s.tSide := low > bt ? 1 : high < bb ? -1 : s.tSide
    hit
 
int tcH1 = touchStep(sH1, useH1 and okH1)
int tcH4 = touchStep(sH4, useH4 and okH4)
int tcD  = touchStep(sD,  useD  and okD)
int tcW  = touchStep(sW,  useW  and okW)
int tcMN = touchStep(sMN, useMN and okMN)
 
fireTouch(int hit, string boxName) =>
    if hit != 0 and alertTouch
        alert("Price reached SW box " + boxName + " (" + (hit == 1 ? "top edge" : "bottom edge") + ") | " +
              syminfo.ticker + " close " + str.tostring(close, format.mintick), alert.freq_once_per_bar_close)
 
fireTouch(tcH1, "H1")
fireTouch(tcH4, "H4")
fireTouch(tcD,  "24H")
fireTouch(tcW,  "W")
fireTouch(tcMN, "Month")
 
alertcondition(tcH1 != 0 or tcH4 != 0 or tcD != 0 or tcW != 0 or tcMN != 0, "Price reached SW box (any TF)", "Price reached SW box {{ticker}} close {{close}}")
alertcondition(tcH1 != 0, "Price reached SW box H1",  "Price reached SW box H1 {{ticker}} close {{close}}")
alertcondition(tcH4 != 0, "Price reached SW box H4",  "Price reached SW box H4 {{ticker}} close {{close}}")
alertcondition(tcD  != 0, "Price reached SW box 24H", "Price reached SW box 24H {{ticker}} close {{close}}")
 
// ───────────── Status table ─────────────
string tblSz = switch tblSizeStr
    "Small" => size.small
    "Large" => size.large
    => size.normal
string tblPos = switch tblPosStr
    "Top Left"     => position.top_left
    "Bottom Left"  => position.bottom_left
    "Bottom Right" => position.bottom_right
    => position.top_right
 
var table tb = table.new(tblPos, 4, 6, bgcolor = #131722, frame_color = #5D606B, frame_width = 2, border_width = 1, border_color = #363A45)
 
addRow(int r, Cycle s, bool use, bool ok) =>
    bool  on    = use and ok
    int   d     = s.phase == 2 ? s.pendDir : s.phase == 1 ? s.restDir : s.runDir
    color stCol = not on ? #787B86 : s.phase == 2 and s.pendDir == 0 ? s.col : d == 1 ? #26A69A : d == -1 ? #EF5350 : color.white
    color rowBg = on ? color.new(s.col, 85) : #131722
    table.cell(tb, 0, r, s.name, text_color = on ? #131722 : #787B86, bgcolor = on ? s.col : #2A2E39, text_size = tblSz)
    table.cell(tb, 1, r, not use ? "Off" : not ok ? "Below chart TF" : s.stateText(), text_color = stCol, bgcolor = rowBg, text_size = tblSz)
    table.cell(tb, 2, r, on and not na(s.top) ? str.tostring(s.top, format.mintick) : "-", text_color = on ? color.white : #787B86, bgcolor = rowBg, text_size = tblSz)
    table.cell(tb, 3, r, on and not na(s.bot) ? str.tostring(s.bot, format.mintick) : "-", text_color = on ? color.white : #787B86, bgcolor = rowBg, text_size = tblSz)
 
if showTable and barstate.islast
    table.cell(tb, 0, 0, "TF",      text_color = color.white, bgcolor = #434651, text_size = tblSz)
    table.cell(tb, 1, 0, "Status",  text_color = color.white, bgcolor = #434651, text_size = tblSz)
    table.cell(tb, 2, 0, "Top",     text_color = color.white, bgcolor = #434651, text_size = tblSz)
    table.cell(tb, 3, 0, "Bottom",  text_color = color.white, bgcolor = #434651, text_size = tblSz)
    addRow(1, sH1, useH1, okH1)
    addRow(2, sH4, useH4, okH4)
    addRow(3, sD,  useD,  okD)
    addRow(4, sW,  useW,  okW)
    addRow(5, sMN, useMN, okMN)

← 返回列表