本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// (c) BY_Tse
//
// Bressert Cycle Signals
// A reconstruction of the published parts of Walter Bressert's cycle method: the Double Stochastic
// (reconstructed; Bressert never published its arithmetic) or RSI3M3, setup bars with buy and sell stop
// triggers, a higher time frame trend filter, walk-forward timing bands, and protective and trailing stops.
// Every rule and its source is listed in SPEC.md. Rules Bressert did not state are inputs.
//@version=6
indicator("Bressert Cycle Signals", shorttitle = "BCS", overlay = false, max_bars_back = 2000, max_boxes_count = 500, max_labels_count = 500)
// ───── Inputs ─────
const string G_OSC = "Oscillator"
const string G_SIG = "Setup and trigger"
const string G_TREND = "Trend filter"
const string G_BAND = "Timing bands"
const string G_STOP = "Stops"
const string G_VIS = "Display"
oscType = input.string("Double Stochastic", "Signal oscillator", options = ["Double Stochastic", "RSI3M3"], group = G_OSC)
dsLen = input.int(10, "Double Stochastic length", minval = 2, group = G_OSC, tooltip = "Bressert's default 10, about half the trading cycle.")
showDs2 = input.bool(true, "Show second Double Stochastic", group = G_OSC, inline = "ds2")
ds2Len = input.int(5, "length", minval = 2, group = G_OSC, inline = "ds2", tooltip = "Bressert's DBS5 for the half cycle.")
dsBuy = input.float(40, "Double Stochastic buy line", group = G_OSC, inline = "dsl")
dsSell = input.float(70, "sell line", group = G_OSC, inline = "dsl")
rsiBuy = input.float(30, "RSI3M3 buy line", group = G_OSC, inline = "rsl")
rsiSell = input.float(70, "sell line", group = G_OSC, inline = "rsl")
deg = input.float(0, "Turn threshold", minval = 0, step = 0.5, group = G_SIG, tooltip = "How far the oscillator must turn from its low (or high) to mark a setup bar. 0 means any turn.")
td = input.int(4, "Trigger window (bars)", minval = 1, group = G_SIG, tooltip = "The trigger can fill on bars 1 to N after the setup bar.")
offTicks = input.int(1, "Trigger offset (ticks)", minval = 0, group = G_SIG, tooltip = "Buy stop this many ticks above the setup bar's high; sell stop below its low.")
trendMode = input.string("HTF oscillator direction", "Trend filter", options = ["None", "HTF oscillator direction", "HTF EMA pair", "HTF EMA %Diff"], group = G_TREND)
htfAuto = input.bool(true, "Automatic higher time frame", group = G_TREND, tooltip = "Daily to weekly, weekly to monthly, monthly to quarterly, intraday times 4.")
htfManual = input.timeframe("W", "Manual higher time frame", group = G_TREND)
emaFast = input.int(10, "HTF EMA fast", minval = 1, group = G_TREND, inline = "ema")
emaSlow = input.int(20, "slow", minval = 2, group = G_TREND, inline = "ema", tooltip = "Bressert did not publish his EMA lengths. These are placeholders.")
cycMin = input.int(14, "Trading cycle, shortest (bars)", minval = 4, group = G_BAND)
cycMax = input.int(27, "Trading cycle, longest (bars)", minval = 6, group = G_BAND)
pivK = input.int(4, "Trough and crest strength", minval = 1, group = G_BAND, tooltip = "A trough is the lowest low of 2N+1 bars, confirmed N bars later. Price only, so the oscillator is not used to label its own targets.")
ivMax = input.int(54, "Longest interval kept", minval = 6, group = G_BAND, tooltip = "Trough-to-trough intervals above this are left out of the band history.")
bandWidth = input.string("40% (ProfitTrader)", "Band width", options = ["40% (ProfitTrader)", "70% (1991 book)"], group = G_BAND)
bandSrc = input.string("Walk-forward history", "Band source", options = ["Walk-forward history", "Generic 20-bar (1998)"], group = G_BAND)
bandN = input.int(20, "Cycles in history", minval = 3, group = G_BAND)
bandMin = input.int(6, "Cycles needed before drawing", minval = 2, group = G_BAND)
bandAdj = input.bool(false, "Trend-adjusted T-C and C-T halves", group = G_BAND)
bandFilt = input.string("Off", "Signal band filter", options = ["Off", "Inside a band", "On or after band start"], group = G_BAND)
trailMode = input.string("At oscillator extreme", "Trailing stop", options = ["At oscillator extreme", "Always", "Off"], group = G_STOP)
trailN = input.int(2, "Trailing stop bars", minval = 1, group = G_STOP, tooltip = "N-bar reversal stop. The price rule is an interpretation; Bressert published only the default of 2 bars.")
showBlocked = input.bool(true, "Show filtered-out setups", group = G_VIS, inline = "blk")
blockedCol = input.color(color.yellow, "", group = G_VIS, inline = "blk")
showBands = input.bool(true, "Show timing bands", group = G_VIS)
showTable = input.bool(false, "Show band calibration table", group = G_VIS)
showCycles = input.bool(true, "Show troughs and crests", group = G_VIS)
// ───── Oscillators ─────
f_ratio(float src, float hi, float lo, int n, int startBar) =>
var float r = na
float hh = ta.highest(hi, n)
float ll = ta.lowest(lo, n)
if bar_index >= startBar and bar_index >= n - 1 and hh - ll > 0
r := 100.0 * (src - ll) / (hh - ll)
r
f_smooth(float x) =>
var float s = na
if not na(x)
s := na(s) ? x : s + 0.5 * (x - s)
s
f_dbs(int n) =>
float k1 = f_smooth(f_ratio(close, high, low, n, n - 1))
f_smooth(f_ratio(k1, k1, k1, n, 2 * (n - 1)))
f_rsi3m3() =>
ta.sma(ta.rsi(close, 3), 3)
f_ema(float x, int n) =>
var float e = na
float a = 2.0 / (n + 1)
if not na(x)
e := na(e) ? x : a * x + (1 - a) * e
e
f_htfState(string mode, string otype, int n, int ef, int es) =>
float d = f_dbs(n)
float r3 = f_rsi3m3()
float o = otype == "RSI3M3" ? r3 : d
float fe = f_ema(close, ef)
float se = f_ema(close, es)
float dd = 100.0 * (fe - se) / se
int st = 0
if mode == "HTF oscillator direction"
st := o > o[1] ? 1 : o < o[1] ? -1 : 0
else if mode == "HTF EMA pair"
st := fe > se and fe > fe[1] ? 1 : fe < se and fe < fe[1] ? -1 : 0
else if mode == "HTF EMA %Diff"
st := dd > dd[1] ? 1 : dd < dd[1] ? -1 : 0
st[1]
f_autoHTF() =>
string tf = timeframe.isintraday ? timeframe.from_seconds(timeframe.in_seconds() * 4) : timeframe.isdaily ? "W" : timeframe.isweekly ? "M" : "3M"
tf
f_pct(array<int> a, float pct) =>
array<int> b = array.copy(a)
array.sort(b, order.ascending)
int rank = math.max(int(math.ceil(pct / 100.0 * array.size(b))), 1)
array.get(b, rank - 1)
float dsVal = f_dbs(dsLen)
float rsiVal = f_rsi3m3()
float ds2Val = f_dbs(ds2Len)
float osc = oscType == "RSI3M3" ? rsiVal : dsVal
float buyL = oscType == "RSI3M3" ? rsiBuy : dsBuy
float sellL = oscType == "RSI3M3" ? rsiSell : dsSell
string htfTF = htfAuto ? f_autoHTF() : htfManual
int htfState = request.security(syminfo.tickerid, htfTF, f_htfState(trendMode, oscType, dsLen, emaFast, emaSlow), lookahead = barmerge.lookahead_on)
int trend = trendMode == "None" ? 0 : nz(htfState, 0)
float pLo = str.startswith(bandWidth, "40") ? 30.0 : 15.0
float pHi = str.startswith(bandWidth, "40") ? 70.0 : 85.0
float off = offTicks * syminfo.mintick
bool generic = str.startswith(bandSrc, "Generic")
// ───── Troughs, crests and timing bands ─────
var array<int> ttArr = array.new<int>()
var array<int> tcArr = array.new<int>()
var array<int> ctArr = array.new<int>()
var int trBar = na // latest trough
var float trPrice = na
var int trBarPrev = na // trough before it
var bool provValid = false
var float ttLo = na
var float ttHi = na
var float tcLo = na
var float tcHi = na
var float ctLo = na
var float ctHi = na
var bool fCurOk = false
var float fCurTTlo = na
var float fCurTThi = na
var float fCurTClo = na
var float fCurTChi = na
var bool fPrevOk = false
var float fPrevTTlo = na
var float fPrevTThi = na
var float fPrevTClo = na
var float fPrevTChi = na
var int crestBar = na
var float crestPrice = na
var array<int> calTT = array.from(0, 0, 0)
var array<int> calTC = array.from(0, 0, 0)
var array<int> calCT = array.from(0, 0, 0)
var box bxTT = na
var box bxTC = na
var box bxCT = na
var label lbTrough = na
var label lbCrest = na
// highest-high bar strictly between two troughs (earliest bar on ties)
f_crestBetween(int a, int b) =>
int cb = a + 1
float mx = high[bar_index - cb]
for j = a + 2 to math.max(b - 1, a + 2)
float hj = high[bar_index - j]
if hj > mx
mx := hj
cb := j
cb
f_outcome(int x, float lo, float hi) =>
x < lo ? 0 : x <= hi ? 1 : 2
f_push(int tt, int tc, int ct) =>
array.push(ttArr, tt)
array.push(tcArr, tc)
array.push(ctArr, ct)
if array.size(ttArr) > bandN
array.shift(ttArr)
array.shift(tcArr)
array.shift(ctArr)
f_pop() =>
array.pop(ttArr)
array.pop(tcArr)
array.pop(ctArr)
int troughFlag = 0
float rightLow = ta.lowest(low, pivK)
float leftLow = ta.lowest(low[pivK + 1], pivK)
float rightHigh = ta.highest(high, pivK)
float leftHigh = ta.highest(high[pivK + 1], pivK)
bool isPL = bar_index >= 2 * pivK and low[pivK] < rightLow and low[pivK] <= leftLow
bool isPH = bar_index >= 2 * pivK and high[pivK] > rightHigh and high[pivK] >= leftHigh
int pb = bar_index - pivK
// forecast from a trough at bar t0 (updates ttLo/ttHi/tcLo/tcHi and the current forecast)
f_forecast(int t0) =>
float a1 = na
float a2 = na
float b1 = na
float b2 = na
bool ok = false
if generic
a1 := t0 + 15
a2 := t0 + 22
b1 := t0 + 8
b2 := t0 + 14
ok := true
else if array.size(ttArr) >= bandMin
a1 := t0 + f_pct(ttArr, pLo)
a2 := t0 + f_pct(ttArr, pHi)
int l1 = f_pct(tcArr, pLo)
int l2 = f_pct(tcArr, pHi)
if bandAdj and trend != 0
int m = math.min(math.max(int(math.round(array.avg(tcArr))), l1), l2)
if trend > 0
l1 := m
else
l2 := m
b1 := t0 + l1
b2 := t0 + l2
ok := true
[ok, a1, a2, b1, b2]
if isPL
float pl = low[pivK]
bool newForecast = false
if na(trBar)
trBar := pb
trPrice := pl
troughFlag := 1
newForecast := true
else if pb - trBar < cycMin
if pl < trPrice
trBar := pb
trPrice := pl
troughFlag := 2
if not na(trBarPrev)
if provValid
f_pop()
int cb = f_crestBetween(trBarPrev, pb)
int ivTT = pb - trBarPrev
provValid := ivTT >= cycMin and ivTT <= ivMax
if provValid
f_push(ivTT, cb - trBarPrev, pb - cb)
if showCycles and not na(lbCrest)
label.set_x(lbCrest, cb)
newForecast := true
else
// finalize the cycle that ends at the current trough, then accept the new one
if not na(trBarPrev) and fPrevOk
int cbAB = f_crestBetween(trBarPrev, trBar)
array.set(calTT, f_outcome(trBar, fPrevTTlo, fPrevTThi), array.get(calTT, f_outcome(trBar, fPrevTTlo, fPrevTThi)) + 1)
array.set(calTC, f_outcome(cbAB, fPrevTClo, fPrevTChi), array.get(calTC, f_outcome(cbAB, fPrevTClo, fPrevTChi)) + 1)
float hLo = ctLo[bar_index - trBar]
float hHi = ctHi[bar_index - trBar]
if not na(hLo)
array.set(calCT, f_outcome(trBar, hLo, hHi), array.get(calCT, f_outcome(trBar, hLo, hHi)) + 1)
trBarPrev := trBar
trBar := pb
trPrice := pl
troughFlag := 1
int cb = f_crestBetween(trBarPrev, pb)
int ivTT = pb - trBarPrev
provValid := ivTT >= cycMin and ivTT <= ivMax
if provValid
f_push(ivTT, cb - trBarPrev, pb - cb)
if showCycles
lbCrest := label.new(cb, 97, "", xloc.bar_index, yloc.price, color.new(color.green, 0), label.style_triangledown, size = size.tiny)
fPrevOk := fCurOk
fPrevTTlo := fCurTTlo
fPrevTThi := fCurTThi
fPrevTClo := fCurTClo
fPrevTChi := fCurTChi
newForecast := true
if newForecast
[ok, a1, a2, b1, b2] = f_forecast(trBar)
fCurOk := ok
fCurTTlo := a1
fCurTThi := a2
fCurTClo := b1
fCurTChi := b2
ttLo := a1
ttHi := a2
tcLo := b1
tcHi := b2
crestBar := na
crestPrice := na
ctLo := na
ctHi := na
if showCycles
if troughFlag == 2 and not na(lbTrough)
label.set_x(lbTrough, pb)
else
lbTrough := label.new(pb, 3, "", xloc.bar_index, yloc.price, color.new(color.red, 0), label.style_triangleup, size = size.tiny)
if showBands
if troughFlag == 2
box.delete(bxTT)
box.delete(bxTC)
box.delete(bxCT)
bxCT := na
if ok
bxTT := box.new(int(a1), 15, int(a2), 0, border_color = na, bgcolor = color.new(color.red, 75))
bxTC := box.new(int(b1), 100, int(b2), 85, border_color = na, bgcolor = color.new(color.green, 75))
if isPH and not na(trBar) and pb > trBar
float ph = high[pivK]
if na(crestBar) or ph > crestPrice
crestBar := pb
crestPrice := ph
if not generic and array.size(ctArr) >= bandMin
int c1 = f_pct(ctArr, pLo)
int c2 = f_pct(ctArr, pHi)
if bandAdj and trend != 0
int m = math.min(math.max(int(math.round(array.avg(ctArr))), c1), c2)
if trend > 0
c2 := m
else
c1 := m
ctLo := pb + c1
ctHi := pb + c2
if showBands
box.delete(bxCT)
bxCT := box.new(int(ctLo), 30, int(ctHi), 15, border_color = na, bgcolor = color.new(color.orange, 75))
// ───── Exits for an open position ─────
var int pos = 0
var float stopP = na
var int entryBar = -1
var bool trailOn = false
if pos == 1 and bar_index > entryBar and low <= stopP
pos := 0
else if pos == -1 and bar_index > entryBar and high >= stopP
pos := 0
// ───── Triggers from pending setups ─────
var float bStop = na
var int bExp = na
var int bStart = na
var float sStop = na
var int sExp = na
var int sStart = na
bool trigB = false
bool trigS = false
int bStartAtTrig = na
int sStartAtTrig = na
if not na(bStop)
trigB := bar_index <= bExp and high >= bStop
bStartAtTrig := bStart
if trigB or bar_index >= bExp
bStop := na
bExp := na
if not na(sStop)
trigS := bar_index <= sExp and low <= sStop
sStartAtTrig := sStart
if trigS or bar_index >= sExp
sStop := na
sExp := na
// ───── Entries ─────
f_lowestSince(int s0) =>
float m = low
if bar_index - s0 >= 1
for j = 1 to bar_index - s0
m := math.min(m, low[j])
m
f_highestSince(int s0) =>
float m = high
if bar_index - s0 >= 1
for j = 1 to bar_index - s0
m := math.max(m, high[j])
m
if trigB and not trigS and pos != 1
pos := 1
entryBar := bar_index
trailOn := trailMode == "Always"
stopP := f_lowestSince(math.max(bStartAtTrig, 0)) - syminfo.mintick
else if trigS and not trigB and pos != -1
pos := -1
entryBar := bar_index
trailOn := trailMode == "Always"
stopP := f_highestSince(math.max(sStartAtTrig, 0)) + syminfo.mintick
// ───── Setup bars at this bar's close ─────
var float extB = na
var bool doneB = true
var int startB = -1
var float extS = na
var bool doneS = true
var int startS = -1
bool setupB = false
bool setupS = false
if not na(osc) and not na(osc[1])
if osc < osc[1]
if doneB or osc[1] - extB > deg
extB := osc
doneB := false
startB := bar_index - 1
else
extB := math.min(extB, osc)
else if osc > osc[1] and not doneB
if extB < buyL and osc - extB > deg
setupB := true
doneB := true
if osc > osc[1]
if doneS or extS - osc[1] > deg
extS := osc
doneS := false
startS := bar_index - 1
else
extS := math.max(extS, osc)
else if osc < osc[1] and not doneS
if extS > sellL and extS - osc > deg
setupS := true
doneS := true
bool inTT = not na(ttLo) and bar_index >= ttLo and bar_index <= ttHi
bool inCT = not na(ctLo) and bar_index >= ctLo and bar_index <= ctHi
bool inTC = not na(tcLo) and bar_index >= tcLo and bar_index <= tcHi
bool bandOkB = bandFilt == "Off" ? true : bandFilt == "Inside a band" ? (inTT or inCT) : ((not na(ttLo) and bar_index >= ttLo) or (not na(ctLo) and bar_index >= ctLo))
bool bandOkS = bandFilt == "Off" ? true : bandFilt == "Inside a band" ? inTC : (not na(tcLo) and bar_index >= tcLo)
bool allowB = setupB and (trendMode == "None" or trend >= 0) and bandOkB
bool allowS = setupS and (trendMode == "None" or trend <= 0) and bandOkS
if allowB
bStop := high + off
bExp := bar_index + td
bStart := startB
if allowS
sStop := low - off
sExp := bar_index + td
sStart := startS
// ───── Trailing stop at the close ─────
float lowN = ta.lowest(low, trailN)
float highN = ta.highest(high, trailN)
if pos != 0
if trailMode == "At oscillator extreme" and not na(osc)
if (pos == 1 and osc >= sellL) or (pos == -1 and osc <= buyL)
trailOn := true
if trailOn and bar_index >= trailN - 1
if pos == 1
stopP := math.max(stopP, lowN - syminfo.mintick)
else
stopP := math.min(stopP, highN + syminfo.mintick)
// ───── Plots: oscillator pane ─────
hline(buyL, "Buy line", color = color.new(color.teal, 30), linestyle = hline.style_dashed)
hline(sellL, "Sell line", color = color.new(color.maroon, 30), linestyle = hline.style_dashed)
plot(osc, "Oscillator", color = color.blue, linewidth = 2)
plot(showDs2 ? ds2Val : na, "Second Double Stochastic", color = color.new(color.gray, 20))
plotshape(allowB ? osc : na, "Buy setup", shape.triangleup, location.absolute, color.teal, size = size.tiny)
plotshape(allowS ? osc : na, "Sell setup", shape.triangledown, location.absolute, color.maroon, size = size.tiny)
plotshape(showBlocked and setupB and not allowB ? osc : na, "Filtered buy setup", shape.circle, location.absolute, blockedCol, size = size.tiny)
plotshape(showBlocked and setupS and not allowS ? osc : na, "Filtered sell setup", shape.circle, location.absolute, blockedCol, size = size.tiny)
// ───── Plots: price chart ─────
plotshape(trigB, "Buy trigger", shape.labelup, location.belowbar, color.teal, text = "B", textcolor = color.white, size = size.tiny, force_overlay = true)
plotshape(trigS, "Sell trigger", shape.labeldown, location.abovebar, color.maroon, text = "S", textcolor = color.white, size = size.tiny, force_overlay = true)
plot(pos != 0 ? stopP : na, "Stop", color = pos == 1 ? color.teal : color.maroon, style = plot.style_steplinebr, force_overlay = true)
// ───── Calibration table ─────
var table tbl = table.new(position.top_right, 4, 4, border_width = 1)
f_row(table t_, int r, string name, array<int> a) =>
int n = array.sum(a)
table.cell(t_, 0, r, name, text_size = size.small)
for j = 0 to 2
string t = n > 0 ? str.tostring(math.round(100.0 * array.get(a, j) / n)) + "%" : "-"
table.cell(t_, j + 1, r, t + (j == 2 ? " (n=" + str.tostring(n) + ")" : ""), text_size = size.small)
if showTable and barstate.islast
string nom = str.startswith(bandWidth, "40") ? "30 / 40 / 30" : "15 / 70 / 15"
table.cell(tbl, 0, 0, "Nominal " + nom, text_size = size.small)
table.cell(tbl, 1, 0, "Before", text_size = size.small)
table.cell(tbl, 2, 0, "Inside", text_size = size.small)
table.cell(tbl, 3, 0, "After", text_size = size.small)
f_row(tbl, 1, "T-T band", calTT)
f_row(tbl, 2, "T-C band", calTC)
f_row(tbl, 3, "C-T band", calCT)
// ───── Alerts ─────
alertcondition(allowB, "Buy setup", "Bressert Cycle Signals: buy setup bar")
alertcondition(allowS, "Sell setup", "Bressert Cycle Signals: sell setup bar")
alertcondition(trigB, "Buy trigger", "Bressert Cycle Signals: buy trigger")
alertcondition(trigS, "Sell trigger", "Bressert Cycle Signals: sell trigger")
alertcondition(troughFlag == 1, "Trough confirmed", "Bressert Cycle Signals: trough confirmed")
// ───── Data window values (used to reconcile against the Python reference) ─────
plot(setupB ? 1 : 0, "d_setupB", display = display.data_window)
plot(setupS ? 1 : 0, "d_setupS", display = display.data_window)
plot(allowB ? 1 : 0, "d_allowB", display = display.data_window)
plot(allowS ? 1 : 0, "d_allowS", display = display.data_window)
plot(trigB ? 1 : 0, "d_trigB", display = display.data_window)
plot(trigS ? 1 : 0, "d_trigS", display = display.data_window)
plot(trend, "d_trend", display = display.data_window)
plot(troughFlag, "d_trough", display = display.data_window)
plot(ttLo, "d_ttLo", display = display.data_window)
plot(ttHi, "d_ttHi", display = display.data_window)
plot(tcLo, "d_tcLo", display = display.data_window)
plot(tcHi, "d_tcHi", display = display.data_window)
plot(ctLo, "d_ctLo", display = display.data_window)
plot(ctHi, "d_ctHi", display = display.data_window)
plot(pos, "d_pos", display = display.data_window)
plot(pos != 0 ? stopP : na, "d_stop", display = display.data_window)
plot(bar_index, "d_bar", display = display.data_window)