Fib OTE Sniper | Supertrend Pullback Strategy with Fib Zones

blitz_algo · strategy · 407 行 · 点赞 256 · TradingView 原页

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

Pine Script

//@version=6
// ============================================================================
//  Fib OTE Pullback Strategy [Evidence-Gated]
// ----------------------------------------------------------------------------
//  1. Supertrend sets the trend. The leg runs from the previous trend's
//     extreme to the current trend's extreme (no pivots, no confirmation lag).
//  2. The entry zone is a band of that leg (default 38.2% to 78.6%).
//  3. Enter on the first reversal bar after price pulls back into the zone.
//     One signal per swing. A new trend extreme re-arms it.
//  4. Stop beyond the pullback extreme. T1 = retest of the extreme (50% off),
//     T2 = 1.272 extension. Breakeven after T1. Exit if the trend flips.
//  5. Each depth band (38-50 / 50-62 / 62-79) keeps its own record of
//     "T1 before stop" and is traded only while that record is positive.
//
//  Closed-bar logic only. Orders fill on the next bar's open.
// ============================================================================
strategy("Fib OTE Pullback Strategy [Evidence-Gated]", "FOP", overlay = true,
     initial_capital = 10000, pyramiding = 0, calc_on_every_tick = false,
     commission_type = strategy.commission.percent, commission_value = 0.05, slippage = 2,
     max_lines_count = 300, max_labels_count = 300, max_boxes_count = 20)
 
// ─────────────────────────────────────────────────────────────────────────
//  INPUTS
// ─────────────────────────────────────────────────────────────────────────
gT = "Trend"
stFactor = input.float(3.0, "Supertrend multiplier", minval = 0.5, step = 0.1, group = gT)
stLen    = input.int(10, "Supertrend ATR length", minval = 2, group = gT)
side     = input.string("Both", "Direction", options = ["Both", "Long only", "Short only"], group = gT)
 
gZ = "Entry zone"
zoneLo = input.float(0.382, "Zone starts at (fraction of the leg)", minval = 0.236, maxval = 0.7, step = 0.01, group = gZ)
zoneHi = input.float(0.786, "Zone ends at (fraction of the leg)", minval = 0.5, maxval = 0.95, step = 0.01, group = gZ,
     tooltip = "A pullback deeper than this cancels the setup until the trend makes a new extreme.")
legMin = input.float(2.0, "Min. leg size (× ATR)", minval = 0.5, maxval = 20.0, step = 0.5, group = gZ)
 
gE = "Risk"
stopBuf   = input.float(0.5, "Stop buffer beyond the pullback extreme (× ATR)", minval = 0.0, maxval = 3.0, step = 0.1, group = gE)
minRR     = input.float(1.0, "Min. reward:risk to T1", minval = 0.3, maxval = 5.0, step = 0.1, group = gE)
riskPct   = input.float(1.0, "Risk per trade (% of equity)", minval = 0.1, maxval = 10.0, step = 0.1, group = gE)
maxLev    = input.float(2.0, "Max. position value (× equity)", minval = 0.5, maxval = 20.0, step = 0.5, group = gE)
holdBars  = input.int(80, "Time stop (bars after entry)", minval = 5, maxval = 1000, group = gE)
beAfterT1 = input.bool(true, "Move stop to breakeven after T1", group = gE)
exitFlip  = input.bool(true, "Exit when the trend flips against the trade", group = gE)
 
gG = "Evidence gate"
useGate = input.bool(true, "Trade a depth band only if its record is positive", group = gG)
warmN   = input.int(8, "Signals per band before the gate decides", minval = 3, maxval = 100, group = gG)
tradeLearning = input.bool(true, "Trade while a band is still learning", group = gG)
minExp  = input.float(0.0, "Min. expectancy to trade (R per signal)", minval = -1.0, maxval = 2.0, step = 0.05, group = gG)
 
gV = "Visuals"
UP  = input.color(#22C58B, "Bull colour", group = gV)
DN  = input.color(#F0506E, "Bear colour", group = gV)
showCandles = input.bool(true, "Trend-coloured candles", group = gV)
showGrid    = input.bool(true, "Fib grid and entry zone", group = gV)
showTbl     = input.bool(true, "Dashboard", group = gV)
tblPosIn    = input.string("Top right", "Dashboard position", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group = gV)
 
// ─────────────────────────────────────────────────────────────────────────
//  CONSTANTS
// ─────────────────────────────────────────────────────────────────────────
GOLD = #F5B841
MUTE = #8A90A2
INK  = #EEF0F7
HDR  = #232B45
ROW1 = color.new(#0B0F1A, 8)
ROW2 = color.new(#0B0F1A, 24)
KSHR = 10.0
var array<string> BKT = array.from("38-50%", "50-62%", "62-79%")
 
// ─────────────────────────────────────────────────────────────────────────
//  SERIES
// ─────────────────────────────────────────────────────────────────────────
atr = ta.atr(14)
[stLine, stDir] = ta.supertrend(stFactor, stLen)     // -1 = uptrend, 1 = downtrend
tCol = stDir < 0 ? UP : DN
bool ready = not na(stDir) and not na(atr)
 
// ─────────────────────────────────────────────────────────────────────────
//  STATE
//  sgn 1 = long (up-leg, buy the pullback) · -1 = short · armed = a new
//  signal is allowed for this swing
// ─────────────────────────────────────────────────────────────────────────
var int   sgn = 0
var bool  armed = false
var float trAnchor = na
var float trExt = na
var int   trExtBar = na
var float pbExt = na
var float runHi = na
var float runLo = na
var int   runHiBar = na
var int   runLoBar = na
 
// live trade
var bool   live = false
var int    liveBar = 0
var int    trEndBar = na
var int    tDir = 0
var string tId = ""
var float  tStop = na
var float  tT1 = na
var float  tT2 = na
var bool   t1Done = false
var bool   t2Done = false
 
// trade drawings
var line  lnE = na
var line  lnS = na
var line  lnT1 = na
var line  lnT2 = na
var label lbE = na
var label lbS = na
var label lbT1 = na
var label lbT2 = na
 
// grid drawings (rebuilt on the last bar)
var array<line>  gLn = array.new<line>()
var array<label> gLb = array.new<label>()
var box gBx = na
 
// record per depth band: resolved signals, T1 wins, sum of R of the wins
var array<int>   pN = array.new_int(3, 0)
var array<int>   pW = array.new_int(3, 0)
var array<float> pR = array.new_float(3, 0.0)
 
// shadow signals still waiting for T1 or the stop
var array<int>   sBk   = array.new_int()
var array<int>   sDir  = array.new_int()
var array<int>   sBorn = array.new_int()
var array<float> sStop = array.new_float()
var array<float> sT1   = array.new_float()
var array<float> sRR   = array.new_float()
 
bool sigLong  = false
bool sigShort = false
 
tPos = tblPosIn == "Top left" ? position.top_left : tblPosIn == "Bottom right" ? position.bottom_right : tblPosIn == "Bottom left" ? position.bottom_left : position.top_right
var table tb = table.new(tPos, 2, 8, border_width = 0, frame_width = 1, frame_color = color.new(MUTE, 70))
 
// ─────────────────────────────────────────────────────────────────────────
//  HELPERS
// ─────────────────────────────────────────────────────────────────────────
px(float v) =>
    str.tostring(v, format.mintick)
 
baseRate() =>
    int n = array.sum(pN)
    n > 0 ? array.sum(pW) * 1.0 / n : 0.5
 
// win rate of one band, pulled toward the all-band rate while its sample is small
winRate(int p) =>
    float b = baseRate()
    (array.get(pW, p) + KSHR * b) / (array.get(pN, p) + KSHR)
 
// expectancy in R per signal: wr × average win − (1 − wr) × 1
expR(int p, float fallbackR) =>
    float w = array.get(pW, p)
    float avgR = w > 0 ? array.get(pR, p) / w : fallbackR
    float wr = winRate(p)
    wr * avgR - (1 - wr)
 
gateOk(int p, float r1) =>
    bool learning = array.get(pN, p) < warmN
    not useGate or (learning ? tradeLearning : expR(p, r1) >= minExp)
 
row(int r, string k, string v, color vc) =>
    table.cell(tb, 0, r, "  " + k, text_color = MUTE, text_halign = text.align_left, text_size = size.small, bgcolor = r % 2 == 0 ? ROW1 : ROW2)
    table.cell(tb, 1, r, v + "  ", text_color = vc, text_halign = text.align_right, text_size = size.small, bgcolor = r % 2 == 0 ? ROW1 : ROW2)
    true
 
gridLine(float f, string t, color c) =>
    float y = trExt - sgn * f * (math.abs(trExt - trAnchor))
    array.push(gLn, line.new(trExtBar, y, bar_index + 8, y, color = c, style = line.style_dotted, width = 1))
    array.push(gLb, label.new(bar_index + 8, y, t + "  " + px(y), style = label.style_label_left,
         color = color.new(c, 100), textcolor = c, size = size.tiny))
    true
 
// ─────────────────────────────────────────────────────────────────────────
//  1. SHADOW RECORD: resolve earlier signals (stop checked first = conservative)
// ─────────────────────────────────────────────────────────────────────────
int sN = array.size(sBorn)
if sN > 0
    for i = sN - 1 to 0
        int born = array.get(sBorn, i)
        if bar_index > born
            int sd = array.get(sDir, i)
            float st = array.get(sStop, i)
            float tg = array.get(sT1, i)
            bool lost = sd == 1 ? low <= st : high >= st
            bool won  = sd == 1 ? high >= tg : low <= tg
            bool expired = bar_index - born > holdBars
            if lost or won or expired
                if lost or won
                    int p = array.get(sBk, i)
                    array.set(pN, p, array.get(pN, p) + 1)
                    if not lost
                        array.set(pW, p, array.get(pW, p) + 1)
                        array.set(pR, p, array.get(pR, p) + array.get(sRR, i))
                array.remove(sBk, i)
                array.remove(sDir, i)
                array.remove(sBorn, i)
                array.remove(sStop, i)
                array.remove(sT1, i)
                array.remove(sRR, i)
 
// ─────────────────────────────────────────────────────────────────────────
//  2. TREND LEG: anchor = the extreme of the trend that just ended,
//     ext = the running extreme of the current trend
// ─────────────────────────────────────────────────────────────────────────
if ready
    if na(runHi)
        runHi := high
        runLo := low
        runHiBar := bar_index
        runLoBar := bar_index
    else
        if high > runHi
            runHi := high
            runHiBar := bar_index
        if low < runLo
            runLo := low
            runLoBar := bar_index
    bool flip = na(trAnchor) or stDir != stDir[1]
    if flip
        sgn := stDir < 0 ? 1 : -1
        trAnchor := sgn == 1 ? runLo : runHi
        trExt := sgn == 1 ? high : low
        trExtBar := bar_index
        pbExt := sgn == 1 ? low : high
        armed := true
        runHi := high
        runLo := low
        runHiBar := bar_index
        runLoBar := bar_index
    else
        bool newExt = sgn == 1 ? high > trExt : low < trExt
        if newExt
            trExt := sgn == 1 ? high : low
            trExtBar := bar_index
            pbExt := sgn == 1 ? low : high
            armed := true
        else
            pbExt := sgn == 1 ? math.min(pbExt, low) : math.max(pbExt, high)
 
float leg   = na(trAnchor) ? na : math.abs(trExt - trAnchor)
float depth = not na(leg) and leg > 0 ? (trExt - pbExt) * sgn / leg : na
float curDepth = not na(leg) and leg > 0 ? (trExt - close) * sgn / leg : na
bool legOk  = not na(leg) and leg >= legMin * atr
bool allowed = side == "Both" or (side == "Long only" and sgn == 1) or (side == "Short only" and sgn == -1)
 
// ─────────────────────────────────────────────────────────────────────────
//  3. SIGNAL: reversal bar inside the zone, once per swing
// ─────────────────────────────────────────────────────────────────────────
if ready and armed and not na(depth) and depth > zoneHi
    armed := false       // pulled back too deep: wait for a new extreme
 
bool inZone = not na(depth) and depth >= zoneLo and depth <= zoneHi
bool rev = sgn == 1 ? (close > open and close > high[1]) : (close < open and close < low[1])
 
if ready and armed and inZone and rev and legOk and allowed
    armed := false
    int bk = depth < 0.5 ? 0 : depth < 0.618 ? 1 : 2
    float stp = pbExt - sgn * stopBuf * atr
    float t1 = trExt
    float t2 = trExt + sgn * 0.272 * leg
    float risk = math.abs(close - stp)
    float r1 = risk > 0 ? (t1 - close) * sgn / risk : 0.0
    if r1 >= minRR
        bool ok = gateOk(bk, r1)
        // every tradable signal feeds the record, traded or not
        array.push(sBk, bk)
        array.push(sDir, sgn)
        array.push(sBorn, bar_index)
        array.push(sStop, stp)
        array.push(sT1, t1)
        array.push(sRR, r1)
        bool free = strategy.position_size == 0 and not live
        float eq = strategy.equity
        float qty = risk > 0 and eq > 0 ? eq * riskPct / 100 / risk : 0.0
        qty := math.min(qty, eq * maxLev / close)
        string nm = (sgn == 1 ? "LONG " : "SHORT ") + str.tostring(r1, "0.0") + "R"
        if ok and free and qty > 0
            tId := sgn == 1 ? "FOP Long" : "FOP Short"
            strategy.entry(tId, sgn == 1 ? strategy.long : strategy.short, qty = qty)
            live := true
            liveBar := bar_index
            trEndBar := na
            tDir := sgn
            tStop := stp
            tT1 := t1
            tT2 := t2
            t1Done := false
            t2Done := false
            sigLong := sgn == 1
            sigShort := sgn == -1
            label.new(bar_index, sgn == 1 ? low : high, nm, style = sgn == 1 ? label.style_label_up : label.style_label_down,
                 color = sgn == 1 ? UP : DN, textcolor = color.white, size = size.small,
                 tooltip = "Depth band " + array.get(BKT, bk) + " of the leg")
            int x1 = bar_index + 3
            lnE  := line.new(bar_index, close, x1, close, color = MUTE, style = line.style_dashed)
            lnS  := line.new(bar_index, stp, x1, stp, color = DN, width = 2)
            lnT1 := line.new(bar_index, t1, x1, t1, color = UP, style = line.style_dashed)
            lnT2 := line.new(bar_index, t2, x1, t2, color = UP, style = line.style_dashed, width = 2)
            lbE  := label.new(x1, close, "Entry  " + px(close), style = label.style_label_left, color = color.new(MUTE, 25), textcolor = color.white, size = size.tiny)
            lbS  := label.new(x1, stp, "Stop  " + px(stp), style = label.style_label_left, color = color.new(DN, 25), textcolor = color.white, size = size.tiny)
            lbT1 := label.new(x1, t1, "T1  " + px(t1), style = label.style_label_left, color = color.new(UP, 25), textcolor = color.white, size = size.tiny)
            lbT2 := label.new(x1, t2, "T2  " + px(t2), style = label.style_label_left, color = color.new(UP, 25), textcolor = color.white, size = size.tiny)
        else
            string why = not ok ? "gated" : "busy"
            label.new(bar_index, sgn == 1 ? low : high, nm + " (" + why + ")", style = sgn == 1 ? label.style_label_up : label.style_label_down,
                 color = color.new(MUTE, 20), textcolor = color.white, size = size.small)
 
// ─────────────────────────────────────────────────────────────────────────
//  4. MANAGE THE TRADE: partial at T1, breakeven, T2, flip exit, time stop
// ─────────────────────────────────────────────────────────────────────────
if live
    bool flipAgainst = exitFlip and strategy.position_size != 0 and (tDir == 1 ? stDir > 0 : stDir < 0)
    if strategy.position_size == 0 and bar_index > liveBar
        live := false
        trEndBar := bar_index
    else if flipAgainst
        strategy.close(tId, comment = "trend flip")
        live := false
        trEndBar := bar_index
    else if strategy.position_size != 0 and bar_index - liveBar > holdBars
        strategy.close(tId, comment = "time stop")
        live := false
        trEndBar := bar_index
    else
        if strategy.position_size != 0
            if not t1Done and (tDir == 1 ? high >= tT1 : low <= tT1)
                t1Done := true
                label.set_text(lbT1, "T1 ✓  " + px(tT1))
            if not t2Done and (tDir == 1 ? high >= tT2 : low <= tT2)
                t2Done := true
                label.set_text(lbT2, "T2 ✓  " + px(tT2))
        float stp2 = t1Done and beAfterT1 ? strategy.position_avg_price : tStop
        if not t1Done
            strategy.exit("X1", tId, qty_percent = 50, limit = tT1, stop = tStop)
        strategy.exit("X2", tId, limit = tT2, stop = stp2)
 
// trade levels follow the live trade, then freeze where it ended
if not na(lnE) and (live or trEndBar == bar_index)
    int xr = live ? bar_index + 3 : bar_index
    line.set_x2(lnE, xr)
    line.set_x2(lnS, xr)
    line.set_x2(lnT1, xr)
    line.set_x2(lnT2, xr)
    label.set_x(lbE, xr)
    label.set_x(lbS, xr)
    label.set_x(lbT1, xr)
    label.set_x(lbT2, xr)
 
// ─────────────────────────────────────────────────────────────────────────
//  VISUALS: trend candles, Supertrend with fill, fib grid and entry zone
// ─────────────────────────────────────────────────────────────────────────
plotcandle(showCandles ? open : na, showCandles ? high : na, showCandles ? low : na, showCandles ? close : na,
     title = "Trend candles", color = tCol, wickcolor = tCol, bordercolor = tCol)
 
pSt = plot(stDir != stDir[1] ? na : stLine, "Supertrend", color = tCol, linewidth = 2, style = plot.style_linebr)
pCl = plot(close, "Close", display = display.none)
fill(pSt, pCl, stLine, close, color.new(tCol, 82), color.new(tCol, 100), title = "Supertrend fill")
 
if barstate.islast and showGrid and not na(leg) and leg > 0
    while array.size(gLn) > 0
        line.delete(array.pop(gLn))
    while array.size(gLb) > 0
        label.delete(array.pop(gLb))
    box.delete(gBx)
    color zc = sgn == 1 ? UP : DN
    float yLo = trExt - sgn * zoneLo * leg
    float yHi = trExt - sgn * zoneHi * leg
    bool nowIn = not na(curDepth) and curDepth >= zoneLo and curDepth <= zoneHi
    gBx := box.new(trExtBar, math.max(yLo, yHi), bar_index + 8, math.min(yLo, yHi), border_color = color.new(zc, 100),
         bgcolor = color.new(zc, nowIn ? 76 : 90), text = nowIn ? "IN ZONE" : "ENTRY ZONE", text_color = color.new(zc, 20),
         text_size = size.tiny, text_halign = text.align_right)
    gridLine(0.0, "0", MUTE)
    gridLine(0.5, "50%", MUTE)
    gridLine(0.618, "61.8%", GOLD)
    gridLine(1.0, "100%", MUTE)
 
// ─────────────────────────────────────────────────────────────────────────
//  DASHBOARD
// ─────────────────────────────────────────────────────────────────────────
if barstate.islast and showTbl
    table.cell(tb, 0, 0, "  FOP", text_color = INK, text_halign = text.align_left, text_size = size.small, bgcolor = HDR)
    table.cell(tb, 1, 0, syminfo.ticker + "  ·  " + timeframe.period + "  ", text_color = INK, text_halign = text.align_right, text_size = size.small, bgcolor = HDR)
    row(1, "Trend", sgn == 1 ? "Bull" : sgn == -1 ? "Bear" : "–", sgn == 1 ? UP : sgn == -1 ? DN : MUTE)
    row(2, "Pullback", na(curDepth) ? "–" : str.tostring(curDepth * 100, "0") + "% of leg", INK)
    string setup = live ? "in trade" : not legOk ? "leg too small" : not armed ? "wait new swing" : na(curDepth) ? "–" : curDepth < zoneLo ? "waiting pullback" : curDepth > zoneHi ? "too deep" : "in zone"
    row(3, "Setup", setup, setup == "in zone" ? GOLD : INK)
    row(4, "Position", strategy.position_size > 0 ? "Long" : strategy.position_size < 0 ? "Short" : "Flat", strategy.position_size > 0 ? UP : strategy.position_size < 0 ? DN : MUTE)
    for b = 0 to 2
        int n = array.get(pN, b)
        float er = expR(b, 1.0)
        bool learning = n < warmN
        bool pass = not useGate or (learning ? tradeLearning : er >= minExp)
        string gt = learning ? "learning" : pass ? "ON" : "OFF"
        string txt = n > 0 ? str.tostring(n) + " · " + str.tostring(100.0 * array.get(pW, b) / n, "0") + "% · " + str.tostring(er, "+0.00;-0.00") + "R · " + gt : "no signals yet"
        row(5 + b, array.get(BKT, b), txt, n == 0 ? MUTE : learning ? INK : pass ? UP : DN)
 
// ─────────────────────────────────────────────────────────────────────────
//  ALERTS
// ─────────────────────────────────────────────────────────────────────────
alertcondition(sigLong, "FOP long entry", "{{ticker}} Fib OTE pullback long")
alertcondition(sigShort, "FOP short entry", "{{ticker}} Fib OTE pullback short")

← 返回列表