本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Auto Fib Major Swing + GZ 2-TF [Kami] v3.2 FINAL LOCKED", shorttitle = "AutoFib GZ v3.2 [Kami]", overlay = true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, max_bars_back = 500)
// ═══════════════════════════════════════════════════════════════════
// AUTO FIB MAJOR SWING + GOLDEN ZONE 2-TF STRATEGY [Kami] v3.2 FINAL
// • Finds the latest MAJOR swing high + swing low by itself
// • Draws Fibonacci levels + Golden Zone (default 0.5 – 0.618)
// • STRATEGY:
// BUY = BULL swing, price dips to the zone, candle CLOSES back above 0.5
// SELL = BEAR swing, price rallies to the zone, candle CLOSES back below 0.5
// SL = beyond the dip + ATR buffer | TP1 = 2R (then BE) | TP2 = fib 0
// • v3.2: compact dashboards (tiny text, fewer rows)
// • v3.1: RSI filters (ON by default, LOCKED final setup)
// BUY only if RSI on the entry candle ≥ 30
// SELL only if RSI on the entry candle < 50
// • BTC AUTO PRESETS (Fib Timeframe = chart):
// 1D swing 5 | 12H swing 8 | 4H swing 13 + TP1 1.5R | 1H swing 40 | 30m swing 10
// • Honest results: entry at signal-candle close, cost per trade, gap fills,
// stop counted first when stop and target hit in the same candle
// • Non-repainting: only CLOSED candles are used, no future data
// LOCKED RESULT (Capital.com XAUUSD 1H, 2023-01-02 → 2026-11-06, costs incl.):
// 51 trades | 62.7% win | +38.18R | +0.75R avg | max DD -3.08R | PASS
// (RSI levels were picked on this same history → expect live results lower)
// Fib 0 = END of swing (newest point) | Fib 1 = START of swing
// ═══════════════════════════════════════════════════════════════════
// ───────── 1) SWING DETECTION ─────────
G1 = "1) Swing Detection"
presetMode = input.string("Auto (BTC presets)", "Settings mode", options = ["Auto (BTC presets)", "Manual"], group = G1, tooltip = "Auto = on BTC charts your tested settings are used by chart timeframe:\n1D swing 5 | 12H swing 8 | 4H swing 13 + TP1 1.5R | 1H swing 40 | 30m swing 10 (Fib Timeframe = chart).\nGold, other symbols and other timeframes use the Manual settings below.")
tfIn = input.timeframe("60", "Fib Timeframe", group = G1, tooltip = "Manual mode. 1 hour = gold strategy default.\nIf this is lower than the chart, the chart timeframe is used.")
swLen = input.int(10, "Swing Strength (candles)", minval = 2, maxval = 100, group = G1, tooltip = "Manual mode. A swing high/low must hold this many candles to count as MAJOR.\nGold 1H tested = 10.")
minPB = input.float(0.236, "Min pullback for new swing", minval = 0.0, maxval = 1.0, step = 0.01, group = G1, tooltip = "How deep a pullback must be (fib level) before a breakout starts a NEW swing.")
// ───────── 2) FIB LEVELS ─────────
G2 = "2) Fib Levels"
s236 = input.bool(true, "0.236", inline = "a", group = G2)
s382 = input.bool(true, "0.382", inline = "a", group = G2)
s500 = input.bool(true, "0.5", inline = "a", group = G2)
s618 = input.bool(true, "0.618", inline = "b", group = G2)
s786 = input.bool(true, "0.786", inline = "b", group = G2)
sE1 = input.bool(true, "1.272 ext", inline = "c", group = G2)
sE2 = input.bool(true, "1.618 ext", inline = "c", group = G2, tooltip = "Extensions = possible TARGETS beyond the swing.")
// ───────── 3) GOLDEN ZONE ─────────
G3 = "3) Golden Zone"
showZone = input.bool(true, "Show Golden Zone box", group = G3)
zA = input.float(0.5, "Zone from", minval = 0.0, maxval = 1.0, step = 0.001, inline = "z", group = G3)
zB = input.float(0.618, "to", minval = 0.0, maxval = 1.0, step = 0.001, inline = "z", group = G3, tooltip = "Pullback area. Tested best on gold 1H: 0.5 – 0.618.\nEntry edge = the lower number (0.5).")
zCol = input.color(#ffb3002e, "Zone colour", group = G3)
// ───────── 4) DISPLAY ─────────
G4 = "4) Display"
showLbl = input.bool(true, "Level labels with price", group = G4)
showAnc = input.bool(true, "Swing High / Swing Low labels", group = G4)
showLeg = input.bool(true, "Dashed swing line", group = G4)
lblOff = input.int(3, "Label distance from last candle", minval = 0, maxval = 50, group = G4)
lnW = input.int(1, "Line width", minval = 1, maxval = 4, group = G4)
showDash = input.bool(true, "Show fib dashboard", group = G4)
dashPos = input.string("Top Right", "Fib dashboard position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = G4)
txtIn = input.string("Tiny", "Dashboard text size", options = ["Tiny", "Small", "Normal"], group = G4, tooltip = "Size of the text in BOTH tables. Tiny = smallest, covers the least chart.")
// ───────── 5) STRATEGY: GOLDEN ZONE 2-TF ─────────
G5 = "5) Strategy: Golden Zone 2-TF"
showSig = input.bool(true, "Show BUY/SELL signals + trade boxes", group = G5)
exitMode = input.string("Split: TP1 + Swing High", "Exit mode", options = ["Split: TP1 + Swing High", "Single TP"], group = G5, tooltip = "Split = close part at TP1, the rest runs to fib 0 (Swing High / Low).\nSingle TP = close everything at TP1.")
tp1R = input.float(2.0, "TP1 (R)", minval = 0.5, maxval = 10.0, step = 0.25, group = G5, tooltip = "Manual mode. In Auto (BTC presets) mode: 4H = 1.5R, other preset timeframes = 2R.")
tp1Pct = input.int(50, "TP1 close %", minval = 10, maxval = 90, step = 5, group = G5)
useBE = input.bool(true, "Move SL to breakeven after TP1", group = G5)
slBuf = input.float(0.3, "SL buffer (x ATR)", minval = 0.0, maxval = 3.0, step = 0.1, group = G5)
minStop = input.float(1.0, "Min stop (x ATR)", minval = 0.0, maxval = 5.0, step = 0.1, group = G5)
atrLen = input.int(14, "ATR length", minval = 1, maxval = 100, group = G5)
onePer = input.bool(true, "One trade per fib zone", group = G5)
// ───────── 6) COSTS & RESULTS ─────────
G6 = "6) Costs & Results"
costPts = input.float(0.4, "Cost per trade (price, round trip)", minval = 0.0, step = 0.05, group = G6, tooltip = "Spread + slippage in price units, charged on every trade. Gold default 0.4.")
showRes = input.bool(true, "Show results table", group = G6)
resStyle = input.string("Simple", "Table style", options = ["Simple", "Detailed"], group = G6)
riskPct = input.float(1.0, "Risk per trade (%)", minval = 0.1, maxval = 10.0, step = 0.1, group = G6, tooltip = "Only for the Return % column. Return % = NET R × this.")
resPos = input.string("Bottom Right", "Results table position", options = ["Top Right", "Bottom Right", "Top Left", "Bottom Left"], group = G6)
// ───────── 7) RSI FILTER (NEW v3.1) ─────────
G7 = "7) RSI Filter"
rsiLen = input.int(14, "RSI length", minval = 2, maxval = 100, group = G7)
useRB = input.bool(true, "BUY only if RSI ≥", inline = "rb", group = G7)
rbMin = input.float(30, "", minval = 0, maxval = 100, step = 1, inline = "rb", group = G7, tooltip = "RSI on the entry candle. Study: BUYs with RSI below 30 all lost (small sample).")
useRS = input.bool(true, "SELL only if RSI <", inline = "rs", group = G7)
rsMax = input.float(50, "", minval = 0, maxval = 100, step = 1, inline = "rs", group = G7, tooltip = "RSI on the entry candle. Study: SELLs with RSI 50 or higher all lost (small sample).")
// ═════════════════════════ BTC AUTO PRESETS (by chart timeframe) ═════════════════════════
isBTC = syminfo.basecurrency == "BTC"
chSec = timeframe.in_seconds(timeframe.period)
usePre = presetMode == "Auto (BTC presets)" and isBTC and (chSec == 86400 or chSec == 43200 or chSec == 14400 or chSec == 3600 or chSec == 1800)
swUse = usePre ? (chSec == 86400 ? 5 : chSec == 43200 ? 8 : chSec == 14400 ? 13 : chSec == 3600 ? 40 : 10) : swLen
tp1Use = usePre ? (chSec == 14400 ? 1.5 : 2.0) : tp1R
// ═════════════════════════ HELPERS ═════════════════════════
f_better(float a, float b, int d) =>
d == 1 ? a > b : a < b
f_lvl(float s, float e, float r) =>
e + (s - e) * r
f_tfName(int sec) =>
sec < 60 ? str.tostring(sec) + "s" : sec < 3600 ? str.tostring(math.round(sec / 60)) + "m" : sec < 86400 ? str.tostring(math.round(sec / 3600)) + "H" : sec < 604800 ? str.tostring(math.round(sec / 86400)) + "D" : sec < 2592000 ? str.tostring(math.round(sec / 604800)) + "W" : str.tostring(math.round(sec / 2592000)) + "M"
f_rTxt(float x) =>
na(x) ? "—" : (x >= 0 ? "+" : "") + str.tostring(x, "#.##") + " R"
// ═════════════════════════ SWING ENGINE ═════════════════════════
f_swing(int len, float pbMin) =>
int n = len * 2
float hh = ta.highest(high, n)
int hhB = ta.highestbars(high, n)
float ll = ta.lowest(low, n)
int llB = ta.lowestbars(low, n)
var int d = 0
var float sP = na
var int sT = na
var float eP = na
var int eT = na
var int eB = na
var float xP = na
var int xT = na
var int xB = na
var float yP = na
var int yT = na
var int yB = na
if d == 0
if bar_index >= n
bool up = hhB > llB
int hiAgo = -hhB
int loAgo = -llB
d := up ? 1 : -1
sP := up ? ll : hh
sT := up ? time[loAgo] : time[hiAgo]
eP := up ? hh : ll
eT := up ? time[hiAgo] : time[loAgo]
eB := up ? bar_index - hiAgo : bar_index - loAgo
else
float tP = d == 1 ? high : low
float cP = d == 1 ? low : high
if f_better(sP, close, d)
bool curEnd = na(xP) or not f_better(cP, xP, d)
bool curX = na(yP) or f_better(tP, yP, d)
float nEP = curEnd ? cP : xP
int nET = curEnd ? time : xT
int nEB = curEnd ? bar_index : xB
float nXP = curEnd ? na : curX ? tP : yP
int nXT = curEnd ? na : curX ? time : yT
int nXB = curEnd ? na : curX ? bar_index : yB
sP := eP
sT := eT
eP := nEP
eT := nET
eB := nEB
xP := nXP
xT := nXT
xB := nXB
yP := na
yT := na
yB := na
d := -d
else if f_better(tP, eP, d)
float rng = math.abs(eP - sP)
float depth = na(xP) or rng == 0 ? 0.0 : math.abs(eP - xP) / rng
bool major = not na(xP) and bar_index - eB >= len and depth >= pbMin
if f_better(close, eP, d)
if major
sP := xP
sT := xT
eP := tP
eT := time
eB := bar_index
xP := na
xT := na
xB := na
yP := na
yT := na
yB := na
else
eP := tP
eT := time
if major
yP := tP
yT := time
yB := bar_index
else
eB := bar_index
xP := na
xT := na
xB := na
yP := na
yT := na
yB := na
else
if na(xP) or f_better(xP, cP, d)
xP := cP
xT := time
xB := bar_index
yP := tP
yT := time
yB := bar_index
else if na(yP) or f_better(tP, yP, d)
yP := tP
yT := time
yB := bar_index
[d[1], sP[1], sT[1], eP[1], eT[1]]
// ═════════════════════════ RUN (non-repainting) ═════════════════════════
tfRaw = usePre ? timeframe.period : tfIn == "" ? timeframe.period : tfIn
tfLow = timeframe.in_seconds(tfRaw) < timeframe.in_seconds(timeframe.period)
tfUse = tfLow ? timeframe.period : tfRaw
[fDirS, fSP, fST, fEP, fET] = request.security(syminfo.tickerid, tfUse, f_swing(swUse, minPB), lookahead = barmerge.lookahead_on)
fDir = nz(fDirS)
ok = fDir != 0 and not na(fSP) and not na(fEP) and not na(fST) and not na(fET) and fSP != fEP
bull = fDir == 1
zLo = math.min(zA, zB)
zHi = math.max(zA, zB)
ret = ok ? (fEP - close) / (fEP - fSP) : na
rsi = ta.rsi(close, rsiLen)
// ═════════════════════════ FIB DRAWING ═════════════════════════
var lvR = array.from(0.0, 0.236, 0.382, 0.5, 0.618, 0.786, 1.0, -0.272, -0.618)
var lvN = array.from("0", "0.236", "0.382", "0.5", "0.618", "0.786", "1", "1.272 ext", "1.618 ext")
var lvC = array.from(#787b86, #f23645, #ff9800, #4caf50, #089981, #2962ff, #787b86, #9c27b0, #e91e63)
var lvS = array.from(true, s236, s382, s500, s618, s786, true, sE1, sE2)
var fibLn = array.new<line>()
var fibLb = array.new<label>()
var box zBox = na
var line legLn = na
var label hiLb = na
var label loLb = na
if barstate.islast
while fibLn.size() > 0
fibLn.pop().delete()
while fibLb.size() > 0
fibLb.pop().delete()
zBox.delete()
legLn.delete()
hiLb.delete()
loLb.delete()
if ok
for i = 0 to lvR.size() - 1
if lvS.get(i)
float lv = lvR.get(i)
float p = f_lvl(fSP, fEP, lv)
color c = lvC.get(i)
fibLn.push(line.new(fST, p, time, p, xloc = xloc.bar_time, color = c, width = lnW, style = lv < 0 ? line.style_dashed : line.style_solid))
if showLbl
fibLb.push(label.new(bar_index + lblOff, p, lvN.get(i) + " " + str.tostring(p, format.mintick), style = label.style_label_left, color = color.new(color.black, 100), textcolor = c, size = size.small))
if showZone
float z1 = f_lvl(fSP, fEP, zLo)
float z2 = f_lvl(fSP, fEP, zHi)
zBox := box.new(fET, math.max(z1, z2), time, math.min(z1, z2), xloc = xloc.bar_time, border_color = color.new(zCol, 40), bgcolor = zCol, text = "GOLDEN ZONE", text_color = color.new(zCol, 0), text_size = size.small)
if showLeg
legLn := line.new(fST, fSP, fET, fEP, xloc = xloc.bar_time, color = bull ? color.new(#089981, 20) : color.new(#f23645, 20), style = line.style_dashed, width = 1)
if showAnc
float hP = bull ? fEP : fSP
int hT = bull ? fET : fST
float lP = bull ? fSP : fEP
int lT = bull ? fST : fET
hiLb := label.new(hT, hP, "Swing High\n" + str.tostring(hP, format.mintick), xloc = xloc.bar_time, style = label.style_label_down, color = #f23645, textcolor = color.white, size = size.small)
loLb := label.new(lT, lP, "Swing Low\n" + str.tostring(lP, format.mintick), xloc = xloc.bar_time, style = label.style_label_up, color = #089981, textcolor = color.white, size = size.small)
// ═════════════════════════ FIB DASHBOARD ═════════════════════════
dashLoc = dashPos == "Top Right" ? position.top_right : dashPos == "Bottom Right" ? position.bottom_right : dashPos == "Top Left" ? position.top_left : position.bottom_left
var dash = table.new(dashLoc, 2, 5, bgcolor = color.new(#131722, 5), frame_color = color.new(#787b86, 50), frame_width = 1, border_color = color.new(#787b86, 80), border_width = 1)
txtSz = txtIn == "Tiny" ? size.tiny : txtIn == "Small" ? size.small : size.normal
f_cell(table t, int col, int row, string txt, color tc) =>
table.cell(t, col, row, txt, text_color = tc, text_size = txtSz, text_halign = col == 0 ? text.align_left : text.align_right)
if barstate.islast and showDash
string tfTxt = f_tfName(timeframe.in_seconds(tfUse))
color legCol = not ok ? color.gray : bull ? #089981 : #f23645
float zp1 = ok ? f_lvl(fSP, fEP, zLo) : na
float zp2 = ok ? f_lvl(fSP, fEP, zHi) : na
string hiTxt = ok ? str.tostring(math.max(fSP, fEP), format.mintick) : "—"
string loTxt = ok ? str.tostring(math.min(fSP, fEP), format.mintick) : "—"
string pbTxt = not ok ? "—" : ret < 0 ? "beyond 0" : str.tostring(ret * 100, "#") + "%"
string zTxt = ok ? str.tostring(math.min(zp1, zp2), format.mintick) + " – " + str.tostring(math.max(zp1, zp2), format.mintick) : "—"
string stTxt = not ok ? "—" : ret < 0 ? "growing" : ret < zLo ? "waiting" : ret <= zHi ? (bull ? "IN ZONE ✅ BUY?" : "IN ZONE ✅ SELL?") : ret <= 1 ? "deep ⚠" : "broken ✖"
color stCol = not ok ? color.gray : ret < 0 ? color.white : ret < zLo ? color.silver : ret <= zHi ? #ffb300 : ret <= 1 ? #ff9800 : #f23645
bool rOkNow = not ok ? false : bull ? (not useRB or rsi >= rbMin) : (not useRS or rsi < rsMax)
bool rOn = bull ? useRB : useRS
string rTxt = na(rsi) ? "—" : str.tostring(rsi, "#.#") + (not ok ? "" : not rOn ? " · off" : rOkNow ? (bull ? " · BUY ok" : " · SELL ok") : (bull ? " · BUY no" : " · SELL no"))
string swTxt = not ok ? "waiting…" : (bull ? "▲ BULL " + loTxt + " → " + hiTxt : "▼ BEAR " + hiTxt + " → " + loTxt)
f_cell(dash, 0, 0, "AUTO FIB", #ffb300)
f_cell(dash, 1, 0, tfTxt, color.white)
f_cell(dash, 0, 1, "Swing", color.silver)
f_cell(dash, 1, 1, swTxt, legCol)
f_cell(dash, 0, 2, "Zone", color.silver)
f_cell(dash, 1, 2, zTxt, #ffb300)
f_cell(dash, 0, 3, "Now", color.silver)
f_cell(dash, 1, 3, pbTxt + " · " + stTxt, stCol)
f_cell(dash, 0, 4, "RSI", color.silver)
f_cell(dash, 1, 4, rTxt, not rOn ? color.white : rOkNow ? #089981 : #f23645)
// ═════════════════════════ STRATEGY ENGINE: GOLDEN ZONE 2-TF ═════════════════════════
atr = ta.atr(atrLen)
splitMode = exitMode == "Split: TP1 + Swing High"
pNear = ok ? f_lvl(fSP, fEP, zLo) : na // zone edge nearest fib 0 (entry level)
p0 = ok ? fEP : na // fib 0 = Swing High (bull) / Swing Low (bear)
p1 = ok ? fSP : na // fib 1 = start of the swing
zoneChg = ok and (fDir != fDir[1] or na(fSP[1]) or fSP != fSP[1] or na(fEP[1]) or fEP != fEP[1])
// zone watch
var bool zArmed = false
var bool zUsed = false
var bool zDead = false
var float zDip = na
// open trade
var bool inTr = false
var int tDir = 0
var float tEn = na
var float tSL = na
var float tT1 = na
var float tT2 = na
var float tRisk = na
var float tCost = 0.0
var bool tSplit = false
var bool tHit1 = false
var float tReal = 0.0
var int tBar = 0
var box bSL = na
var box bTP = na
var line lT2 = na
// results
var int nTr = 0
var int nWin = 0
var int nNeg = 0
var int nSL = 0
var int nT1 = 0
var int nT2 = 0
var int nTie = 0
var int nSkip = 0
var int nRsiSk = 0
var int nL = 0
var int nS = 0
var int nWL = 0
var int nWS = 0
var int curLS = 0
var int maxLS = 0
var float sumR = 0.0
var float sumPos = 0.0
var float sumNeg = 0.0
var float sumCost = 0.0
var float sL = 0.0
var float sS = 0.0
var float eqR = 0.0
var float pkR = 0.0
var float ddR = 0.0
var int t0 = time
bool newSig = false
bool exNow = false
float exG = na
float exPx = na
if barstate.isconfirmed
// 1) new fib zone → reset the watch
if zoneChg
zArmed := false
zUsed := false
zDead := false
zDip := na
// 2) manage the open trade (from the candle after entry)
if inTr and bar_index > tBar
bool isL = tDir == 1
float pct = tSplit ? tp1Pct / 100.0 : 1.0
float r1 = (tT1 - tEn) * tDir / tRisk
float r2 = (tT2 - tEn) * tDir / tRisk
if not tHit1
bool hitSL = isL ? low <= tSL : high >= tSL
bool hitT1 = isL ? high >= tT1 : low <= tT1
if hitSL
// stop counted first if stop + TP1 share a candle; a gap through the stop fills at the open
float px = isL ? math.min(open, tSL) : math.max(open, tSL)
exNow := true
exG := (px - tEn) * tDir / tRisk
exPx := px
nSL += 1
if hitT1
nTie += 1
else if hitT1
nT1 += 1
if not tSplit
exNow := true
exG := r1
exPx := tT1
else
tHit1 := true
tReal := pct * r1
bool beHit = useBE and (isL ? low <= tEn : high >= tEn)
bool t2Hit = isL ? high >= tT2 : low <= tT2
if beHit
// worst case: runner stopped at breakeven inside the TP1 candle
exNow := true
exG := tReal
exPx := tEn
if t2Hit
nTie += 1
else if t2Hit
exNow := true
exG := tReal + (1 - pct) * r2
exPx := tT2
nT2 += 1
else
float stopNow = useBE ? tEn : tSL
bool hitStop = isL ? low <= stopNow : high >= stopNow
bool t2Hit = isL ? high >= tT2 : low <= tT2
if hitStop
float px = isL ? math.min(open, stopNow) : math.max(open, stopNow)
exNow := true
exG := tReal + (1 - pct) * (px - tEn) * tDir / tRisk
exPx := px
if t2Hit
nTie += 1
else if t2Hit
exNow := true
exG := tReal + (1 - pct) * r2
exPx := tT2
nT2 += 1
// 3) book a closed trade
if exNow
float net = exG - tCost
nTr += 1
sumR += net
sumCost += tCost
eqR += net
pkR := math.max(pkR, eqR)
ddR := math.max(ddR, pkR - eqR)
if net > 0
nWin += 1
sumPos += net
curLS := 0
else
nNeg += 1
sumNeg += net
curLS += 1
maxLS := math.max(maxLS, curLS)
if tDir == 1
nL += 1
sL += net
if net > 0
nWL += 1
else
nS += 1
sS += net
if net > 0
nWS += 1
if showSig
box.set_right(bSL, bar_index)
box.set_right(bTP, bar_index)
if not na(lT2)
line.set_x2(lT2, bar_index)
label.new(bar_index, exPx, (net > 0 ? "✓ +" : "✗ ") + str.tostring(net, "#.##") + "R", style = label.style_label_left, color = color.new(color.black, 100), textcolor = net > 0 ? #089981 : #f23645, size = size.small)
inTr := false
tHit1 := false
tReal := 0.0
else if inTr and showSig
box.set_right(bSL, bar_index + 1)
box.set_right(bTP, bar_index + 1)
if not na(lT2)
line.set_x2(lT2, bar_index + 1)
// 4) watch the Golden Zone and fire the entry
if ok and not inTr and not exNow and not na(atr)
bool isBull = fDir == 1
if not zUsed and not zDead
bool broke = isBull ? close < p1 : close > p1
if broke
// candle closed beyond fib 1 → swing broken, no trade in this zone
zDead := true
zArmed := false
zDip := na
else
bool touch = isBull ? low <= pNear : high >= pNear
if touch
zArmed := true
if zArmed
zDip := na(zDip) ? (isBull ? low : high) : isBull ? math.min(zDip, low) : math.max(zDip, high)
bool trig = isBull ? close > pNear : close < pNear
if trig
float en = close
float slX = isBull ? zDip - slBuf * atr : zDip + slBuf * atr
float risk = math.max(math.abs(en - slX), minStop * atr)
float sl = en - fDir * risk
float t2 = p0
float room = risk > 0 ? (t2 - en) * fDir / risk : 0.0
float t1 = en + fDir * tp1Use * risk
bool spl = splitMode
bool rOk = isBull ? (not useRB or (not na(rsi) and rsi >= rbMin)) : (not useRS or (not na(rsi) and rsi < rsMax))
if spl and room <= tp1Use
// fib 0 is closer than TP1 → one target at fib 0
t1 := t2
spl := false
if room < 1.0
// less than 1R of room to fib 0 → skip this zone
nSkip += 1
zUsed := true
zArmed := false
zDip := na
else if not rOk
// RSI filter says no → skip this zone
nRsiSk += 1
zUsed := true
zArmed := false
zDip := na
if showSig
label.new(bar_index, isBull ? low : high, "RSI " + str.tostring(rsi, "#") + "\nskip", style = isBull ? label.style_label_up : label.style_label_down, color = color.new(#787b86, 30), textcolor = color.white, size = size.tiny)
else
inTr := true
tDir := fDir
tEn := en
tSL := sl
tT1 := t1
tT2 := t2
tRisk := risk
tCost := costPts / risk
tSplit := spl
tHit1 := false
tReal := 0.0
tBar := bar_index
zUsed := onePer
zArmed := false
zDip := na
newSig := true
if showSig
bSL := box.new(bar_index, math.max(en, sl), bar_index + 1, math.min(en, sl), border_color = color.new(#f23645, 60), bgcolor = color.new(#f23645, 85))
bTP := box.new(bar_index, math.max(en, t1), bar_index + 1, math.min(en, t1), border_color = color.new(#089981, 60), bgcolor = color.new(#089981, 85))
lT2 := spl ? line.new(bar_index, t2, bar_index + 1, t2, color = #089981, style = line.style_dotted, width = 1) : na
alert((fDir == 1 ? "BUY " : "SELL ") + syminfo.ticker + " @ " + str.tostring(en, format.mintick) + " | SL " + str.tostring(sl, format.mintick) + " | TP1 " + str.tostring(t1, format.mintick) + (spl ? " | TP2 " + str.tostring(t2, format.mintick) : "") + " | RSI " + str.tostring(rsi, "#.#") + " | Golden Zone 2-TF v3.2", alert.freq_once_per_bar_close)
buySig = newSig and tDir == 1
sellSig = newSig and tDir == -1
plotshape(showSig and buySig, title = "BUY", style = shape.labelup, location = location.belowbar, color = #089981, text = "BUY", textcolor = color.white, size = size.small)
plotshape(showSig and sellSig, title = "SELL", style = shape.labeldown, location = location.abovebar, color = #f23645, text = "SELL", textcolor = color.white, size = size.small)
// ═════════════════════════ RESULTS TABLE ═════════════════════════
resLoc = resPos == "Top Right" ? position.top_right : resPos == "Bottom Right" ? position.bottom_right : resPos == "Top Left" ? position.top_left : position.bottom_left
simple_ = resStyle == "Simple"
var res = table.new(resLoc, simple_ ? 8 : 2, simple_ ? 6 : 20, bgcolor = color.new(#131722, 5), frame_color = color.new(#787b86, 50), frame_width = 1, border_color = color.new(#787b86, 80), border_width = 1)
var bool merged = false
f_row(table t, int row, string name, color col, int n, int w, float sum, float dd) =>
float avg = n > 0 ? sum / n : na
string v = n < 50 ? str.tostring(n) + "/50" : avg >= 0.15 ? "PASS ✅" : "FAIL ❌"
color vc = n < 50 ? color.silver : avg >= 0.15 ? #089981 : #f23645
color rc = n == 0 ? color.white : sum >= 0 ? #089981 : #f23645
f_cell(t, 0, row, name, col)
f_cell(t, 1, row, str.tostring(n), color.white)
f_cell(t, 2, row, n > 0 ? str.tostring(100.0 * w / n, "#") + "%" : "—", color.white)
f_cell(t, 3, row, f_rTxt(n > 0 ? sum : na), rc)
f_cell(t, 4, row, n > 0 ? (sum >= 0 ? "+" : "") + str.tostring(sum * riskPct, "#.#") + "%" : "—", rc)
f_cell(t, 5, row, f_rTxt(avg), na(avg) ? color.white : avg >= 0.15 ? #089981 : avg >= 0 ? #ffb300 : #f23645)
f_cell(t, 6, row, na(dd) ? "—" : "-" + str.tostring(dd, "#.#") + "R", na(dd) ? color.silver : #f23645)
f_cell(t, 7, row, v, vc)
if barstate.islast and showRes
float avgR = nTr > 0 ? sumR / nTr : na
float winP = nTr > 0 ? 100.0 * nWin / nTr : na
float avgW = nWin > 0 ? sumPos / nWin : na
float avgLs = nNeg > 0 ? -sumNeg / nNeg : na
float needP = not na(avgW) and not na(avgLs) and avgW + avgLs > 0 ? 100.0 * avgLs / (avgW + avgLs) : na
float pf = sumNeg < 0 ? sumPos / -sumNeg : na
float t1P = nTr > 0 ? 100.0 * nT1 / nTr : na
float slP = nTr > 0 ? 100.0 * nSL / nTr : na
float t2P = nTr > 0 ? 100.0 * nT2 / nTr : na
float cAvg = nTr > 0 ? sumCost / nTr : na
int days = math.round((time - t0) / 86400000.0)
float pctO = tSplit ? tp1Pct / 100.0 : 1.0
float openR = inTr ? tReal + (tHit1 ? 1 - pctO : 1.0) * (close - tEn) * tDir / tRisk : na
string rsiSet = useRB or useRS ? "RSI " + (useRB ? "BUY≥" + str.tostring(rbMin, "#") : "") + (useRB and useRS ? " " : "") + (useRS ? "SELL<" + str.tostring(rsMax, "#") : "") : "RSI off"
string setTxt = (usePre ? "BTC " + f_tfName(chSec) + " preset" : "Manual") + " · swing " + str.tostring(swUse) + " · zone " + str.tostring(zLo, "#.###") + "–" + str.tostring(zHi, "#.###") + " · TP1 " + str.tostring(tp1Use, "#.##") + "R " + (splitMode ? "Split " + str.tostring(tp1Pct) + "%" : "Single") + (useBE ? " · BE" : "") + " · " + rsiSet
string sinceTx = str.format_time(t0, "yyyy-MM-dd", syminfo.timezone) + " (" + str.tostring(days) + " days)"
string verdict = nTr < 50 ? "TOO FEW (" + str.tostring(nTr) + "/50)" : avgR >= 0.15 ? "PASS ✅" : "FAIL ❌"
color vCol = nTr < 50 ? color.silver : avgR >= 0.15 ? #089981 : #f23645
string openTx = inTr ? (tDir == 1 ? "BUY " : "SELL ") + f_rTxt(openR) + " · entry " + str.tostring(tEn, format.mintick) + " · SL " + str.tostring(tHit1 and useBE ? tEn : tSL, format.mintick) + " · TP1 " + str.tostring(tT1, format.mintick) + (tSplit ? " · TP2 " + str.tostring(tT2, format.mintick) : "") : "none"
if simple_
if not merged
table.merge_cells(res, 1, 0, 7, 0)
table.merge_cells(res, 0, 5, 7, 5)
merged := true
string shortSet = f_tfName(chSec) + " · sw" + str.tostring(swUse) + " · " + str.tostring(zLo, "#.###") + "–" + str.tostring(zHi, "#.###") + " · TP1 " + str.tostring(tp1Use, "#.##") + "R · " + (useRB or useRS ? "RSI on" : "RSI off") + " · since " + str.format_time(t0, "yyyy-MM-dd", syminfo.timezone)
string openSh = inTr ? (tDir == 1 ? "BUY " : "SELL ") + f_rTxt(openR) + " · SL " + str.tostring(tHit1 and useBE ? tEn : tSL, format.mintick) + " · TP1 " + str.tostring(tT1, format.mintick) : "none"
f_cell(res, 0, 0, "GZ v3.2", #ffb300)
f_cell(res, 1, 0, shortSet, color.white)
f_cell(res, 0, 1, "", color.silver)
f_cell(res, 1, 1, "N", color.silver)
f_cell(res, 2, 1, "Win", color.silver)
f_cell(res, 3, 1, "R", color.silver)
f_cell(res, 4, 1, "%", color.silver)
f_cell(res, 5, 1, "Avg", color.silver)
f_cell(res, 6, 1, "DD", color.silver)
f_cell(res, 7, 1, "Verdict", color.silver)
f_row(res, 2, "ALL", #ffb300, nTr, nWin, sumR, ddR)
f_row(res, 3, "BUY", #089981, nL, nWL, sL, na)
f_row(res, 4, "SELL", #f23645, nS, nWS, sS, na)
f_cell(res, 0, 5, "Open: " + openSh + " · skipped " + str.tostring(nSkip) + " room / " + str.tostring(nRsiSk) + " RSI · costs incl.", inTr ? #ffb300 : color.silver)
else
f_cell(res, 0, 0, "GZ 2-TF RESULTS v3.2", #ffb300)
f_cell(res, 1, 0, f_tfName(chSec) + " chart · Fib " + f_tfName(timeframe.in_seconds(tfUse)), color.white)
f_cell(res, 0, 1, "Settings", color.silver)
f_cell(res, 1, 1, setTxt, usePre ? #ffb300 : color.white)
f_cell(res, 0, 2, "Tested since", color.silver)
f_cell(res, 1, 2, sinceTx, color.white)
f_cell(res, 0, 3, "Closed trades", color.silver)
f_cell(res, 1, 3, str.tostring(nTr), color.white)
f_cell(res, 0, 4, "Win rate (need)", color.silver)
f_cell(res, 1, 4, na(winP) ? "—" : str.tostring(winP, "#.#") + "%" + (na(needP) ? "" : " (need " + str.tostring(needP, "#.#") + "%)"), color.white)
f_cell(res, 0, 5, "TP1 hit / Full SL", color.silver)
f_cell(res, 1, 5, na(t1P) ? "—" : str.tostring(t1P, "#.#") + "% / " + str.tostring(slP, "#.#") + "%", color.white)
f_cell(res, 0, 6, "Reached fib 0 (TP2)", color.silver)
f_cell(res, 1, 6, splitMode and not na(t2P) ? str.tostring(t2P, "#.#") + "%" : "—", color.white)
f_cell(res, 0, 7, "NET R", color.silver)
f_cell(res, 1, 7, f_rTxt(nTr > 0 ? sumR : na), sumR >= 0 ? #089981 : #f23645)
f_cell(res, 0, 8, "AVG R / trade", color.silver)
f_cell(res, 1, 8, f_rTxt(avgR), na(avgR) ? color.white : avgR >= 0.15 ? #089981 : avgR >= 0 ? #ffb300 : #f23645)
f_cell(res, 0, 9, "Profit factor", color.silver)
f_cell(res, 1, 9, na(pf) ? "—" : str.tostring(pf, "#.##"), color.white)
f_cell(res, 0, 10, "Max drawdown", color.silver)
f_cell(res, 1, 10, "-" + str.tostring(ddR, "#.##") + " R", #f23645)
f_cell(res, 0, 11, "Max loss streak", color.silver)
f_cell(res, 1, 11, str.tostring(maxLS), color.white)
f_cell(res, 0, 12, "BUY trades", color.silver)
f_cell(res, 1, 12, str.tostring(nL) + " · " + (nL > 0 ? str.tostring(100.0 * nWL / nL, "#") + "% win · " : "") + f_rTxt(nL > 0 ? sL / nL : na) + " avg", color.white)
f_cell(res, 0, 13, "SELL trades", color.silver)
f_cell(res, 1, 13, str.tostring(nS) + " · " + (nS > 0 ? str.tostring(100.0 * nWS / nS, "#") + "% win · " : "") + f_rTxt(nS > 0 ? sS / nS : na) + " avg", color.white)
f_cell(res, 0, 14, "Avg cost / trade", color.silver)
f_cell(res, 1, 14, na(cAvg) ? "—" : str.tostring(cAvg, "#.###") + " R", color.white)
f_cell(res, 0, 15, "Same-candle ties", color.silver)
f_cell(res, 1, 15, str.tostring(nTie) + " (worst case)", color.white)
f_cell(res, 0, 16, "Skipped (no room)", color.silver)
f_cell(res, 1, 16, str.tostring(nSkip), color.white)
f_cell(res, 0, 17, "Skipped (RSI filter)", color.silver)
f_cell(res, 1, 17, str.tostring(nRsiSk), color.white)
f_cell(res, 0, 18, "Open trade", color.silver)
f_cell(res, 1, 18, openTx, inTr ? #ffb300 : color.silver)
f_cell(res, 0, 19, "VERDICT (+0.15R, 50+)", color.silver)
f_cell(res, 1, 19, verdict, vCol)
// ═════════════════════════ ALERTS ═════════════════════════
newSwing = ok and (fDir != fDir[1] or na(fSP[1]) or fSP != fSP[1])
inZone = ok and ret >= zLo and ret <= zHi
zoneHit = inZone and not inZone[1] and barstate.isconfirmed
alertcondition(newSwing and bull, "New BULL swing", "Auto Fib: new BULLISH major swing (Low → High) on {{ticker}}")
alertcondition(newSwing and not bull, "New BEAR swing", "Auto Fib: new BEARISH major swing (High → Low) on {{ticker}}")
alertcondition(zoneHit and bull, "Golden Zone (BULL swing)", "Auto Fib: {{ticker}} is in the GOLDEN ZONE of a BULL swing – watch for BUY. Price {{close}}")
alertcondition(zoneHit and not bull, "Golden Zone (BEAR swing)", "Auto Fib: {{ticker}} is in the GOLDEN ZONE of a BEAR swing – watch for SELL. Price {{close}}")
alertcondition(buySig, "GZ BUY signal", "Golden Zone 2-TF: BUY on {{ticker}} at {{close}}")
alertcondition(sellSig, "GZ SELL signal", "Golden Zone 2-TF: SELL on {{ticker}} at {{close}}")
// Data Window values
plot(ok ? math.max(fSP, fEP) : na, "Swing High", color = #f23645, display = display.data_window)
plot(ok ? math.min(fSP, fEP) : na, "Swing Low", color = #089981, display = display.data_window)
plot(ok ? f_lvl(fSP, fEP, 0.5) : na, "Fib 0.5", color = #4caf50, display = display.data_window)
plot(ok ? f_lvl(fSP, fEP, 0.618) : na, "Fib 0.618", color = #089981, display = display.data_window)
plot(ok ? f_lvl(fSP, fEP, 0.786) : na, "Fib 0.786", color = #2962ff, display = display.data_window)
plot(rsi, "RSI", color = #ffb300, display = display.data_window)