本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("BOS Margin [Zen]", overlay = true, max_labels_count = 200, max_lines_count = 200)
// BOS Margin [Zen]
// Sweep and BOS are detected exactly as in Sweep Entry Zone [Zen]. For every BOS the script measures how far the
// candle closed beyond the broken level, in ATR, and sorts the BOS into THIN / MID / CLEAN.
// The table shows what happened after past BOS of each class on this chart. Descriptive statistics, not a forecast.
// ---------- Inputs ----------
gP = "Sweep & BOS (rules of Sweep Entry Zone)"
poolLen = input.int(20, "Pool length (candles)", minval = 5, group = gP, display = display.none, tooltip = "Pool = highest high / lowest low of the previous N closed candles. Sweep = wick beyond the pool and close back inside, on a closed candle.")
waitBars = input.int(48, "BOS wait (candles)", minval = 12, maxval = 200, group = gP, display = display.none, tooltip = "How long a sweep waits for its BOS. BOS = a close beyond the opposite end of the sweep candle.")
gC = "Margin classes"
atrLen = input.int(14, "ATR length", minval = 1, group = gC, display = display.none, tooltip = "ATR of the candles before the BOS candle.")
thinMax = input.float(0.25, "THIN: margin below (ATR)", minval = 0.01, step = 0.05, group = gC, display = display.none, tooltip = "Margin = distance from the broken level to the close of the BOS candle, in ATR.")
cleanMin = input.float(0.75, "CLEAN: margin from (ATR)", minval = 0.02, step = 0.05, group = gC, display = display.none)
gO = "Outcome"
moveAtr = input.float(1.0, "Move size (ATR)", minval = 0.1, step = 0.1, group = gO, display = display.none, tooltip = "After a BOS the script watches which comes first: a move of this size in the BOS direction or the same move against it, counted from the close of the BOS candle.")
resBars = input.int(12, "Outcome window (candles)", minval = 1, maxval = 100, group = gO, display = display.none)
minN = input.int(30, "Minimum sample", minval = 1, group = gO, display = display.none, tooltip = "Percentages are shown only when a class has at least this many finished BOS.")
gV = "Display"
showLabels = input.bool(true, "Show BOS labels", group = gV, display = display.none, tooltip = "The label shows the class and the margin. Hover over it to see what happened after that BOS.")
showTable = input.bool(true, "Show table", group = gV, display = display.none)
tablePos = input.string("Top right", "Table position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = gV, display = display.none)
if cleanMin <= thinMax
runtime.error("CLEAN threshold must be greater than THIN threshold")
// ---------- ChartZenFX palette (auto light / dark) ----------
bool isLight = (color.r(chart.bg_color) + color.g(chart.bg_color) + color.b(chart.bg_color)) / 3 > 128
color cHI = isLight ? #AD4A12 : #D9703A
color cLO = isLight ? #1B46B4 : #6F88EE
color cMUTED = isLight ? #647482 : #8391A4
const int NEAR_BARS = 12 // labels of the same side closer than this are put on separate text rows
const int LBL_SPAN = 6 // a label is kept clear of the candles this many candles to each side of its BOS candle
// ---------- Pool and sweep (closed candles), as in Sweep Entry Zone ----------
float atrPrev = ta.atr(atrLen)[1]
float hh = ta.highest(high, poolLen)[1]
float ll = ta.lowest(low, poolLen)[1]
bool ok = bar_index >= poolLen
bool swH = ok and high > hh and close <= hh
bool swL = ok and low < ll and close >= ll
bool swHonly = swH and not swL // a candle that sweeps both pools is skipped
bool swLonly = swL and not swH
float loN = ta.lowest(low, LBL_SPAN + 1) // local low / high around the current candle: labels are placed beyond it
float hiN = ta.highest(high, LBL_SPAN + 1)
// ---------- Pending sweeps (one per side, waiting for BOS) ----------
var int pHbar = na
var float pHhi = na
var float pHlo = na
var int pLbar = na
var float pLhi = na
var float pLlo = na
// ---------- BOS events and statistics ----------
type Ev
int cls // 1 THIN, 2 MID, 3 CLEAN
int dir // 1 = BOS up (after a low sweep), -1 = BOS down (after a high sweep)
int born
float tgt
float stp
label lb
string base
var array<Ev> evs = array.new<Ev>()
// index 0 = ALL, 1 = THIN, 2 = MID, 3 = CLEAN
var array<int> nFin = array.new<int>(4, 0) // finished BOS (the denominator)
var array<int> nWith = array.new<int>(4, 0) // move in the BOS direction came first
var array<int> nAgst = array.new<int>(4, 0) // move against the BOS came first
var array<int> nNone = array.new<int>(4, 0) // neither within the window
var array<int> nBoth = array.new<int>(4, 0) // both on one candle, order unknown
var int nNoAtr = 0
// last label of each side (0 = BOS up, 1 = BOS down): its candle and its text row
var array<int> stBar = array.new<int>(2, na)
var array<int> stRow = array.new<int>(2, 0)
var array<label> stLb = array.new<label>(2, na)
// fresh labels that are still being kept clear of the candles printing next to them
var array<label> adjLb = array.new<label>()
var array<int> adjBorn = array.new<int>()
var array<int> adjDir = array.new<int>()
bool bosThin = false
bool bosMid = false
bool bosClean = false
string msg = ""
f_inc(array<int> a, int cls) =>
a.set(0, a.get(0) + 1)
a.set(cls, a.get(cls) + 1)
f_name(int cls) =>
cls == 1 ? "THIN" : cls == 2 ? "MID" : "CLEAN"
f_move(bool along) =>
(along ? "+" : "-") + str.tostring(moveAtr) + " ATR"
f_share(array<int> a, int cls) =>
int n = nFin.get(cls)
n >= minN ? str.tostring(a.get(cls)) + " (" + str.tostring(100.0 * a.get(cls) / n, "#") + "%)" : str.tostring(a.get(cls))
f_tip(int dir, string base, string res) =>
(dir == 1 ? "BOS up after a low sweep" : "BOS down after a high sweep") + "\n" + base + "\nOutcome: " + res
f_bos(int dir, int swBar, float level) =>
int cls = 0
if not na(atrPrev) and atrPrev > 0
float margin = dir * (close - level) / atrPrev
cls := margin < thinMax ? 1 : margin < cleanMin ? 2 : 3
color c = dir == 1 ? cLO : cHI
string base = f_name(cls) + " " + str.tostring(margin, "0.00") + " ATR"
label lb = na
if showLabels
// neighbouring labels of the same side go to the next text row so that they do not overlap
int si = dir == 1 ? 0 : 1
int row = 0
float y = dir == 1 ? loN : hiN // beyond the local low / high, not on the BOS candle itself
if not na(stBar.get(si)) and bar_index - stBar.get(si) <= NEAR_BARS
row := (stRow.get(si) + 1) % 3
float py = label.get_y(stLb.get(si))
if not na(py)
y := dir == 1 ? math.min(y, py) : math.max(y, py)
stBar.set(si, bar_index)
stRow.set(si, row)
string pad = row == 0 ? "" : row == 1 ? "\n" : "\n\n"
line.new(swBar, level, bar_index, level, color = color.new(c, 30), width = 1, style = line.style_solid)
lb := label.new(bar_index, y, dir == 1 ? pad + base : base + pad, style = dir == 1 ? label.style_label_up : label.style_label_down, color = color.new(c, 100), textcolor = c, size = size.small, tooltip = f_tip(dir, base, "not finished yet (window " + str.tostring(resBars) + " candles)"))
stLb.set(si, lb)
adjLb.push(lb)
adjBorn.push(bar_index)
adjDir.push(dir)
evs.push(Ev.new(cls, dir, bar_index, close + dir * moveAtr * atrPrev, close - dir * moveAtr * atrPrev, lb, base))
cls
if barstate.isconfirmed
// ----- fresh labels: step away if a new candle prints through them (position only, nothing is recalculated) -----
int a = adjLb.size() - 1
while a >= 0
if bar_index - adjBorn.get(a) > LBL_SPAN
adjLb.remove(a)
adjBorn.remove(a)
adjDir.remove(a)
else if bar_index > adjBorn.get(a)
label q = adjLb.get(a)
if adjDir.get(a) == 1 and low < label.get_y(q)
label.set_y(q, low)
if adjDir.get(a) == -1 and high > label.get_y(q)
label.set_y(q, high)
a -= 1
// ----- open BOS events: which move came first (checked from the candle after the BOS) -----
int k = evs.size() - 1
while k >= 0
Ev e = evs.get(k)
int age = bar_index - e.born
if age > 0
bool hitT = e.dir == 1 ? high >= e.tgt : low <= e.tgt
bool hitS = e.dir == 1 ? low <= e.stp : high >= e.stp
string res = ""
if hitT and hitS
f_inc(nBoth, e.cls)
res := "both moves on one candle (candle " + str.tostring(age) + "), order unknown"
else if hitT
f_inc(nWith, e.cls)
res := f_move(true) + " first, candle " + str.tostring(age)
else if hitS
f_inc(nAgst, e.cls)
res := f_move(false) + " first, candle " + str.tostring(age)
else if age >= resBars
f_inc(nNone, e.cls)
res := "neither move in " + str.tostring(resBars) + " candles"
if res != ""
f_inc(nFin, e.cls)
if not na(e.lb)
label.set_tooltip(e.lb, f_tip(e.dir, e.base, res))
evs.remove(k)
k -= 1
// ----- pending high sweep: cancelled / BOS down / timed out (Sweep Entry Zone rules) -----
if not na(pHbar)
if high > pHhi
pHbar := na
else if close < pHlo
int cls = f_bos(-1, pHbar, pHlo)
if cls > 0
bosThin := bosThin or cls == 1
bosMid := bosMid or cls == 2
bosClean := bosClean or cls == 3
Ev ne = evs.last()
msg += "BOS down after high sweep: " + ne.base + " | level " + str.tostring(pHlo, format.mintick) + " | past " + f_name(cls) + ": " + f_move(true) + " first " + f_share(nWith, cls) + " of " + str.tostring(nFin.get(cls)) + "\n"
else
nNoAtr += 1
pHbar := na
else if bar_index - pHbar >= waitBars
pHbar := na
// ----- pending low sweep: cancelled / BOS up / timed out -----
if not na(pLbar)
if low < pLlo
pLbar := na
else if close > pLhi
int cls = f_bos(1, pLbar, pLhi)
if cls > 0
bosThin := bosThin or cls == 1
bosMid := bosMid or cls == 2
bosClean := bosClean or cls == 3
Ev ne = evs.last()
msg += "BOS up after low sweep: " + ne.base + " | level " + str.tostring(pLhi, format.mintick) + " | past " + f_name(cls) + ": " + f_move(true) + " first " + f_share(nWith, cls) + " of " + str.tostring(nFin.get(cls)) + "\n"
else
nNoAtr += 1
pLbar := na
else if bar_index - pLbar >= waitBars
pLbar := na
// ----- new sweeps on this candle (a new same-side sweep replaces the pending one) -----
if swHonly
pHbar := bar_index
pHhi := high
pHlo := low
if swLonly
pLbar := bar_index
pLhi := high
pLlo := low
// ---------- Table ----------
f_pos(string s) =>
s == "Top right" ? position.top_right : s == "Bottom right" ? position.bottom_right : s == "Top left" ? position.top_left : position.bottom_left
f_row(table t, int row, string name, int cls, color txt, color bg) =>
table.cell(t, 0, row, name, text_color = txt, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
table.cell(t, 1, row, str.tostring(nFin.get(cls)), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 2, row, f_share(nWith, cls), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 3, row, f_share(nAgst, cls), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 4, row, f_share(nNone, cls), text_color = txt, bgcolor = bg, text_size = size.small)
table.cell(t, 5, row, f_share(nBoth, cls), text_color = txt, bgcolor = bg, text_size = size.small)
var table panel = table.new(f_pos(tablePos), 6, 7, border_width = 0)
if barstate.islast and showTable
color txt = chart.fg_color
color hdr = color.new(cMUTED, 65)
color bg = color.new(chart.bg_color, 15) // own background, so the numbers stay readable over candles
int r0 = 0
if str.startswith(tablePos, "Top")
// empty row: keeps the table below the chart status line on narrow charts
table.cell(panel, 0, 0, "", height = 7)
table.merge_cells(panel, 0, 0, 5, 0)
r0 := 1
table.cell(panel, 0, r0, "BOS margin", text_color = txt, bgcolor = hdr, text_size = size.small, text_halign = text.align_left, tooltip = "Distance from the broken level to the close of the BOS candle, in ATR.")
table.cell(panel, 1, r0, "N", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Finished BOS of the row on this chart. Every percentage in the row is a share of this N.")
table.cell(panel, 2, r0, f_move(true) + " first", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Price moved " + str.tostring(moveAtr) + " ATR in the BOS direction before it moved the same distance against it, within " + str.tostring(resBars) + " candles.")
table.cell(panel, 3, r0, f_move(false) + " first", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Price moved " + str.tostring(moveAtr) + " ATR against the BOS first, within " + str.tostring(resBars) + " candles.")
table.cell(panel, 4, r0, "Neither", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Neither move happened within " + str.tostring(resBars) + " candles.")
table.cell(panel, 5, r0, "Both", text_color = txt, bgcolor = hdr, text_size = size.small, tooltip = "Both moves happened on the same candle, so the order is unknown.")
f_row(panel, r0 + 1, "ALL", 0, txt, bg)
f_row(panel, r0 + 2, "THIN < " + str.tostring(thinMax), 1, txt, bg)
f_row(panel, r0 + 3, "MID", 2, txt, bg)
f_row(panel, r0 + 4, "CLEAN >= " + str.tostring(cleanMin), 3, txt, bg)
table.cell(panel, 0, r0 + 5, "% of N | window " + str.tostring(resBars) + " | not finished: " + str.tostring(evs.size()), text_color = cMUTED, bgcolor = bg, text_size = size.small, text_halign = text.align_left)
table.merge_cells(panel, 0, r0 + 5, 5, r0 + 5)
// ---------- Alerts ----------
if barstate.isconfirmed and msg != ""
alert(msg + syminfo.ticker + " " + timeframe.period, alert.freq_once_per_bar_close)
alertcondition(bosThin or bosMid or bosClean, "BOS (any class)", "BOS on {{ticker}} {{interval}}")
alertcondition(bosThin, "BOS: THIN", "THIN BOS on {{ticker}} {{interval}}")
alertcondition(bosMid, "BOS: MID", "MID BOS on {{ticker}} {{interval}}")
alertcondition(bosClean, "BOS: CLEAN", "CLEAN BOS on {{ticker}} {{interval}}")