Squeeze Momentum Gold Buy-Only Stats

edwinardyanto · strategy · 203 行 · 点赞 93 · TradingView 原页

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

Pine Script

//@version=6
// Squeeze Momentum Gold Buy-Only Stats
// Based on the open-source "Squeeze Momentum Indicator [LazyBear]" by LazyBear (2014):
// https://www.tradingview.com/script/nqQ1DT5a-Squeeze-Momentum-Indicator-LazyBear/
// The indicator math is ported to Pine v6 unchanged. Added: rule-based entries/exits, BUY / EXIT markers on the price chart,
// a stop loss, and a statistics panel that compares the author's rule with a buy-only variant on the same chart.
// Signals on candle close, fills on the next candle open. Historical statistics only.
strategy("Squeeze Momentum Gold Buy-Only Stats", shorttitle = "SQZ Gold Stats", overlay = false, initial_capital = 10000,
     default_qty_type = strategy.percent_of_equity, default_qty_value = 10, commission_type = strategy.commission.percent,
     commission_value = 0.02, max_labels_count = 500)
 
// ---- original LazyBear inputs ----
length = input.int(20, "BB Length", minval = 2)
mult = input.float(2.0, "BB MultFactor")
lengthKC = input.int(20, "KC Length", minval = 2)
multKC = input.float(1.5, "KC MultFactor")
useTrueRange = input.bool(true, "Use TrueRange (KC)")
origBB = input.bool(true, "Original formula (BB width uses KC MultFactor, as in LazyBear's code)")
// ---- added: rules and costs ----
slAtr = input.float(2.0, "Best row: stop loss (x ATR 14)", step = 0.5)
buyOnly = input.bool(true, "Best row: buy only")
spreadPct = input.float(0.02, "Spread per side (%)", step = 0.01)
swapYr = input.float(5.0, "Swap / financing per year (%)", step = 0.5)
tStart = input.time(timestamp("2023-09-08T05:00:00+00:00"), "Start date")
tEnd = input.time(timestamp("2026-10-15T09:00:00+00:00"), "End date (last candle used)")
tSplit = input.time(timestamp("2025-03-27T19:00:00+00:00"), "Sample In / Sample Out split")
spread = spreadPct / 100
swapDay = swapYr / 100 / 365
 
// ---- Squeeze Momentum (LazyBear), ported to v6 ----
source = close
basis = ta.sma(source, length)
dev = (origBB ? multKC : mult) * ta.stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev
ma = ta.sma(source, lengthKC)
rng = useTrueRange ? ta.tr : high - low
rangema = ta.sma(rng, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC
sqzOn = lowerBB > lowerKC and upperBB < upperKC
sqzOff = lowerBB < lowerKC and upperBB > upperKC
noSqz = not sqzOn and not sqzOff
val = ta.linreg(source - math.avg(math.avg(ta.highest(high, lengthKC), ta.lowest(low, lengthKC)), ta.sma(close, lengthKC)), lengthKC, 0)
bcolor = val > 0 ? (val > nz(val[1]) ? color.lime : color.green) : (val < nz(val[1]) ? color.red : color.maroon)
scolor = noSqz ? color.blue : sqzOn ? color.black : color.gray
plot(val, "Momentum", color = bcolor, style = plot.style_histogram, linewidth = 4)
plot(0, "Squeeze", color = scolor, style = plot.style_cross, linewidth = 2)
 
// squeeze release = first gray cross after a black cross
var bool armed = false
bool fire = false
if sqzOn
    armed := true
else if sqzOff and armed
    fire := true
    armed := false
// row 0 = author rule: enter in momentum direction on release, exit when histogram colour changes (momentum turns)
L0 = fire and val > 0
S0 = fire and val < 0
XL0 = val < nz(val[1])
XS0 = val > nz(val[1])
// row 1 = best: same entry, exit when histogram drops below zero, stop loss slAtr x ATR(14)
L1 = fire and val > 0
S1 = fire and val < 0
XL1 = val < 0
XS1 = val > 0
atrNow = ta.atr(14)
atrPrev = atrNow[1]
 
// ---- own trade log: fixed 1x position, % of capital per trade, spread both sides + swap per day held ----
var pos = array.from(0.0, 0.0)
var want = array.from(0.0, 0.0)
var ePx = array.from(0.0, 0.0)
var eT = array.from(0.0, 0.0)
var eSL = array.from(0.0, 0.0)
var sN = array.from(0.0, 0.0)
var sW = array.from(0.0, 0.0)
var sSum = array.from(0.0, 0.0)
var sGW = array.from(0.0, 0.0)
var sGL = array.from(0.0, 0.0)
var sPk = array.from(0.0, 0.0)
var sDD = array.from(0.0, 0.0)
var sIn = array.from(0.0, 0.0)
var sOut = array.from(0.0, 0.0)
var nIn = array.from(0.0, 0.0)
var nOut = array.from(0.0, 0.0)
 
closeT(int r, float px) =>
    p = array.get(pos, r)
    days = (time - array.get(eT, r)) / 86400000.0
    ret = 100 * (p * (px / array.get(ePx, r) - 1) - 2 * spread - swapDay * days)
    array.set(sN, r, array.get(sN, r) + 1)
    array.set(sSum, r, array.get(sSum, r) + ret)
    if ret > 0
        array.set(sW, r, array.get(sW, r) + 1)
        array.set(sGW, r, array.get(sGW, r) + ret)
    else
        array.set(sGL, r, array.get(sGL, r) - ret)
    cum = array.get(sSum, r)
    array.set(sPk, r, math.max(array.get(sPk, r), cum))
    array.set(sDD, r, math.max(array.get(sDD, r), array.get(sPk, r) - cum))
    if array.get(eT, r) < tSplit
        array.set(sIn, r, array.get(sIn, r) + ret)
        array.set(nIn, r, array.get(nIn, r) + 1)
    else
        array.set(sOut, r, array.get(sOut, r) + ret)
        array.set(nOut, r, array.get(nOut, r) + 1)
    array.set(pos, r, 0.0)
 
bool sigExit = false
if time >= tStart and time <= tEnd
    // 1) execute the order decided on the previous candle, at this candle's open
    for r = 0 to 1
        w = array.get(want, r)
        p = array.get(pos, r)
        if w != p
            if p != 0
                closeT(r, open)
            if w != 0
                array.set(pos, r, w)
                array.set(ePx, r, open)
                array.set(eT, r, time)
                array.set(eSL, r, r == 1 ? open - w * slAtr * atrPrev : na)
    // 2) stop loss inside the candle (row 1 only); a gap through the stop fills at the open
    p1 = array.get(pos, 1)
    s1 = array.get(eSL, 1)
    if p1 > 0 and not na(s1)
        if open <= s1
            closeT(1, open)
            sigExit := true
        else if low <= s1
            closeT(1, s1)
            sigExit := true
    else if p1 < 0 and not na(s1)
        if open >= s1
            closeT(1, open)
            sigExit := true
        else if high >= s1
            closeT(1, s1)
            sigExit := true
    array.set(want, 1, array.get(pos, 1))
 
// 3) decide on candle close (stop and reverse allowed only for row 0)
decide(int r, bool L, bool S, bool XL, bool XS, bool okS) =>
    p = array.get(pos, r)
    w = p
    if p > 0 and XL
        w := 0.0
    if p < 0 and XS
        w := 0.0
    if w == 0 or p == 0
        if L and p <= 0
            w := 1.0
        else if S and okS and p >= 0
            w := -1.0
    w
bool sigBuy = false
if time >= tStart and time < tEnd
    array.set(want, 0, decide(0, L0, S0, XL0, XS0, true))
    pB = array.get(pos, 1)
    wB = decide(1, L1, S1, XL1, XS1, not buyOnly)
    array.set(want, 1, wB)
    if wB != pB
        if wB == 1
            strategy.entry("Buy", strategy.long)
            strategy.exit("SL", "Buy", stop = close - slAtr * atrNow)
            sigBuy := true
        else if wB == -1
            strategy.entry("Sell", strategy.short)
            strategy.exit("SL S", "Sell", stop = close + slAtr * atrNow)
        else
            strategy.close_all()
            sigExit := true
else if time >= tEnd
    array.set(want, 0, array.get(pos, 0))
    array.set(want, 1, array.get(pos, 1))
 
plotshape(sigBuy, "BUY", shape.labelup, location.belowbar, color.new(#19b39a, 0), text = "BUY", textcolor = color.white, size = size.small, force_overlay = true)
plotshape(sigExit, "EXIT", shape.labeldown, location.abovebar, color.new(#ff6b78, 0), text = "EXIT", textcolor = color.white, size = size.small, force_overlay = true)
 
fPct(float x) => (x >= 0 ? "+" : "") + str.tostring(x, "#0.0") + "%"
fPF(int r) => array.get(sGL, r) > 0 ? str.tostring(array.get(sGW, r) / array.get(sGL, r), "#.00") : "-"
fLine(int r) =>
    n = array.get(sN, r)
    str.tostring(n, "#") + " trades · WR " + (n > 0 ? str.tostring(100 * array.get(sW, r) / n, "#0.0") : "-") + "% · " + fPct(array.get(sSum, r)) + " · PF " + fPF(r)
var tb = table.new(position.top_right, 2, 7, bgcolor = color.new(#0b1730, 5), border_width = 1, border_color = color.new(color.white, 85), force_overlay = true)
if barstate.islast
    table.cell(tb, 0, 0, "Squeeze Momentum Gold Stats", text_color = color.white, text_size = size.normal)
    table.cell(tb, 1, 0, "spread " + str.tostring(spreadPct) + "%/side · swap " + str.tostring(swapYr) + "%/yr", text_color = color.silver, text_size = size.small)
    table.cell(tb, 0, 1, "Default (author rule, buy+sell)", text_color = color.silver, text_size = size.normal)
    table.cell(tb, 1, 1, fLine(0), text_color = #ff6b78, text_size = size.normal)
    table.cell(tb, 0, 2, "Best (" + (buyOnly ? "buy only" : "buy+sell") + ", exit < 0, SL " + str.tostring(slAtr) + " ATR)", text_color = color.silver, text_size = size.normal)
    table.cell(tb, 1, 2, fLine(1), text_color = #19e3c1, text_size = size.normal)
    table.cell(tb, 0, 3, "Default / Best max drawdown", text_color = color.silver, text_size = size.normal)
    table.cell(tb, 1, 3, str.tostring(array.get(sDD, 0), "#0.0") + "% / " + str.tostring(array.get(sDD, 1), "#0.0") + "%", text_color = #19e3c1, text_size = size.normal)
    table.cell(tb, 0, 4, "Best Sample In / Out", text_color = color.silver, text_size = size.normal)
    table.cell(tb, 1, 4, fPct(array.get(sIn, 1)) + " (" + str.tostring(array.get(nIn, 1), "#") + ") / " + fPct(array.get(sOut, 1)) + " (" + str.tostring(array.get(nOut, 1), "#") + ")", text_color = #19e3c1, text_size = size.normal)
    table.cell(tb, 0, 5, "Default Sample In / Out", text_color = color.silver, text_size = size.normal)
    table.cell(tb, 1, 5, fPct(array.get(sIn, 0)) + " (" + str.tostring(array.get(nIn, 0), "#") + ") / " + fPct(array.get(sOut, 0)) + " (" + str.tostring(array.get(nOut, 0), "#") + ")", text_color = #ff6b78, text_size = size.normal)
    table.cell(tb, 0, 6, "Indicator: Squeeze Momentum by LazyBear · returns = sum of % per trade, fixed 1x", text_color = color.gray, text_size = size.tiny)
 
plot(bar_index, "Bar index", display = display.data_window)

← 返回列表