本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("CHOSEN FIBONACCI PRO v2", shorttitle="CHOSEN FIB PRO v2", overlay=true, max_lines_count=100, max_labels_count=100, max_boxes_count=20)
//====================================================
// 1. INPUTS
//====================================================
string G1 = "01. Automatic Fibonacci"
int pivotLeft = input.int(5, "Pivot Left Bars", minval=1, maxval=30, group=G1)
int pivotRight = input.int(5, "Pivot Right Bars", minval=1, maxval=30, group=G1)
float minSwingATR = input.float(1.5, "Minimum Swing (ATR)", minval=0.1, step=0.1, group=G1)
int setupExpiry = input.int(120, "Setup Expiry (bars)", minval=10, group=G1, tooltip="Fib setup is dropped after this many bars without a signal.")
bool showFib = input.bool(true, "Show Fibonacci Levels", group=G1)
bool showExt = input.bool(true, "Show Targets / Extensions", group=G1)
int extendBars = input.int(15, "Extend Lines Right (bars)", minval=1, maxval=100, group=G1)
bool showPivots = input.bool(false, "Show Confirmed Pivot Marks", group=G1)
string G2 = "02. Trend Filters"
bool useEMA = input.bool(true, "Enable EMA Filter", group=G2)
int fastLen = input.int(50, "Fast EMA", minval=1, group=G2)
int slowLen = input.int(200, "Slow EMA", minval=2, group=G2)
bool showEMA = input.bool(false, "Show EMA Lines", group=G2)
bool useHTF = input.bool(false, "Enable Higher-Timeframe Filter", group=G2)
string htfTF = input.timeframe("240", "HTF Timeframe", group=G2)
string G3 = "03. Momentum / Confirmation"
bool useRSI = input.bool(true, "Enable RSI Filter", group=G3)
int rsiLen = input.int(14, "RSI Period", minval=2, group=G3)
float rsiBull = input.float(45, "Bullish RSI Above", group=G3, tooltip="Pullbacks usually dip RSI, so 45 is less restrictive than 50.")
float rsiBear = input.float(55, "Bearish RSI Below", group=G3)
bool useCandle = input.bool(true, "Enable Candle Confirmation", group=G3)
float wickRatio = input.float(1.0, "Minimum Wick / Body Ratio", minval=0.1, step=0.1, group=G3)
bool useVolume = input.bool(false, "Enable Volume Filter", group=G3)
int volumeLen = input.int(20, "Volume Average Period", minval=1, group=G3)
bool useSession = input.bool(false, "Enable Session Filter", group=G3)
string sessionInput = input.session("0800-1700", "Session", group=G3)
string G4 = "04. Risk Management"
int atrLen = input.int(14, "ATR Period", minval=1, group=G4)
string slBasis = input.string("0.786 Level", "Stop Placed Beyond", options=["0.786 Level", "Swing Origin (1.0)"], group=G4)
float slBuffer = input.float(0.3, "SL ATR Buffer", minval=0, step=0.1, group=G4)
float minRR = input.float(2.0, "Minimum RR (to Target 1)", minval=0.5, step=0.25, group=G4)
float riskPercent = input.float(1.0, "Risk Per Trade (%)", minval=0.1, maxval=5, step=0.1, group=G4)
float accountSize = input.float(10000, "Reference Account Size", minval=1, group=G4)
int maxTradesDay = input.int(5, "Maximum Signals Per Day", minval=1, group=G4)
int cooldownBars = input.int(5, "Signal Cooldown Bars", minval=0, group=G4)
bool oneTrade = input.bool(true, "One Trade At A Time", group=G4)
string G5 = "05. Dashboard & Alerts"
bool showDashboard = input.bool(true, "Show Dashboard", group=G5)
bool showSignals = input.bool(true, "Show BUY / SELL Labels", group=G5)
bool showResults = input.bool(true, "Show TP / SL Result Marks", group=G5)
bool showTrade = input.bool(true, "Show Active Trade Levels", group=G5)
bool enableDynamicAlerts = input.bool(true, "Enable Dynamic Alerts", group=G5)
string dashPosition = input.string("Top Right", "Dashboard Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=G5)
//====================================================
// 2. CALCULATIONS
//====================================================
float emaFast = ta.ema(close, fastLen)
float emaSlow = ta.ema(close, slowLen)
float rsiValue = ta.rsi(close, rsiLen)
float atrValue = ta.atr(atrLen)
float volAverage = ta.sma(volume, volumeLen)
float pivotHigh = ta.pivothigh(high, pivotLeft, pivotRight)
float pivotLow = ta.pivotlow(low, pivotLeft, pivotRight)
bool newDay = timeframe.change("D")
// Higher timeframe EMAs, previous closed HTF bar only (non-repainting)
float htfFast = request.security(syminfo.tickerid, htfTF, ta.ema(close, fastLen)[1], lookahead=barmerge.lookahead_on)
float htfSlow = request.security(syminfo.tickerid, htfTF, ta.ema(close, slowLen)[1], lookahead=barmerge.lookahead_on)
bool volumeAvailable = not na(volume) and not na(volAverage) and volAverage > 0
bool volumeOK = not useVolume or not volumeAvailable or volume > volAverage
bool inSession = not useSession or not na(time(timeframe.period, sessionInput))
bool bullishTrend = not useEMA or emaFast > emaSlow
bool bearishTrend = not useEMA or emaFast < emaSlow
bool htfBull = not useHTF or (not na(htfFast) and not na(htfSlow) and htfFast > htfSlow)
bool htfBear = not useHTF or (not na(htfFast) and not na(htfSlow) and htfFast < htfSlow)
bool bullishRSI = not useRSI or rsiValue > rsiBull
bool bearishRSI = not useRSI or rsiValue < rsiBear
float bodySize = math.max(math.abs(close - open), syminfo.mintick)
float lowerWick = math.min(open, close) - low
float upperWick = high - math.max(open, close)
bool bullishCandle = close > open and (lowerWick >= bodySize * wickRatio or (close > open[1] and open <= close[1]))
bool bearishCandle = close < open and (upperWick >= bodySize * wickRatio or (close < open[1] and open >= close[1]))
bool bullCandleOK = not useCandle or bullishCandle
bool bearCandleOK = not useCandle or bearishCandle
//====================================================
// 3. SWING DETECTION ENGINE
//====================================================
var float previousSwingPrice = na
var int previousSwingBar = na
var int previousSwingType = 0
var float lastSwingPrice = na
var int lastSwingBar = na
var int lastSwingType = 0
var float fibA = na // impulse origin
var float fibB = na // impulse end
var int fibDir = 0 // 1 = bullish impulse (look for buys), -1 = bearish
var int fibStartBar = na
var int fibBBar = na
var int setupId = 0
bool newImpulse = false
if barstate.isconfirmed
int eventType = 0
float eventPrice = na
int eventBar = bar_index - pivotRight
if not na(pivotHigh) and na(pivotLow)
eventType := 1
eventPrice := pivotHigh
else if not na(pivotLow) and na(pivotHigh)
eventType := -1
eventPrice := pivotLow
if eventType != 0
if lastSwingType == 0
lastSwingPrice := eventPrice
lastSwingBar := eventBar
lastSwingType := eventType
else if eventType == lastSwingType
bool moreExtreme = eventType == 1 ? eventPrice > lastSwingPrice : eventPrice < lastSwingPrice
if moreExtreme
lastSwingPrice := eventPrice
lastSwingBar := eventBar
if previousSwingType != 0 and math.abs(lastSwingPrice - previousSwingPrice) >= atrValue * minSwingATR
fibA := previousSwingPrice
fibB := lastSwingPrice
fibDir := lastSwingType
fibStartBar := previousSwingBar
fibBBar := lastSwingBar
newImpulse := true
else
previousSwingPrice := lastSwingPrice
previousSwingBar := lastSwingBar
previousSwingType := lastSwingType
lastSwingPrice := eventPrice
lastSwingBar := eventBar
lastSwingType := eventType
if math.abs(lastSwingPrice - previousSwingPrice) >= atrValue * minSwingATR
fibA := previousSwingPrice
fibB := lastSwingPrice
fibDir := eventType
fibStartBar := previousSwingBar
fibBBar := lastSwingBar
newImpulse := true
else
fibDir := 0
if newImpulse
setupId += 1
// Drop setup if the origin is broken or it has gone stale
if barstate.isconfirmed and fibDir != 0 and not newImpulse
bool originBroken = (fibDir == 1 and close < fibA) or (fibDir == -1 and close > fibA)
bool expired = not na(fibBBar) and bar_index - fibBBar > setupExpiry
if originBroken or expired
fibDir := 0
//====================================================
// 4. FIBONACCI LEVELS
//====================================================
float fibRange = not na(fibA) and not na(fibB) ? math.abs(fibB - fibA) : na
bool activeSetup = fibDir != 0 and not na(fibRange) and fibRange > 0
float sgn = fibDir == 1 ? 1.0 : -1.0
f_ret(float b, float rng, float s, float r) => b - s * rng * r
f_ext(float b, float rng, float s, float e) => b + s * rng * (e - 1.0)
float fib236 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.236) : na
float fib382 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.382) : na
float fib500 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.500) : na
float fib618 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.618) : na
float fib650 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.650) : na
float fib705 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.705) : na
float fib786 = activeSetup ? f_ret(fibB, fibRange, sgn, 0.786) : na
// Targets: swing end, then 1.272 / 1.618 extensions beyond it
float tp1Level = activeSetup ? fibB : na
float tp2Level = activeSetup ? f_ext(fibB, fibRange, sgn, 1.272) : na
float tp3Level = activeSetup ? f_ext(fibB, fibRange, sgn, 1.618) : na
float zoneHi = math.max(fib618, fib705)
float zoneLo = math.min(fib618, fib705)
bool inGoldenZone = activeSetup and low <= zoneHi and high >= zoneLo
//====================================================
// 5. RISK / REWARD
//====================================================
float slLevel = slBasis == "0.786 Level" ? fib786 : fibA
float slPrice = fibDir == 1 ? slLevel - atrValue * slBuffer : slLevel + atrValue * slBuffer
float risk = fibDir == 1 ? close - slPrice : slPrice - close
float reward = fibDir == 1 ? tp1Level - close : close - tp1Level
float rr = risk > syminfo.mintick ? reward / risk : 0.0
bool rrOK = activeSetup and risk > syminfo.mintick and reward > 0 and rr >= minRR
float posSize = risk > syminfo.mintick ? (accountSize * riskPercent / 100.0) / risk : na
//====================================================
// 6. TRADE MANAGEMENT & SIGNALS
//====================================================
var int tradeDir = 0
var int tradeBar = na
var float tEntry = na
var float tSL = na
var float tTP1 = na
var float tTP2 = na
var float tTP3 = na
var float tRR = na
var float tSize = na
var int lastSignalDir = 0
var int wins = 0
var int losses = 0
var float netR = 0.0
var int tradesToday = 0
var int lastSignalBar = na
var int lastSignaledSetup = -1
if newDay
tradesToday := 0
// Resolve open trade (stop assumed first if both hit in the same bar)
bool slHit = false
bool tpHit = false
if barstate.isconfirmed and tradeDir != 0 and bar_index > tradeBar
if tradeDir == 1
slHit := low <= tSL
tpHit := not slHit and high >= tTP1
else
slHit := high >= tSL
tpHit := not slHit and low <= tTP1
if slHit
losses += 1
netR -= 1.0
tradeDir := 0
else if tpHit
wins += 1
netR += tRR
tradeDir := 0
bool cooldownOK = na(lastSignalBar) or bar_index - lastSignalBar >= cooldownBars
bool dailyOK = tradesToday < maxTradesDay
bool newSetupOK = setupId != lastSignaledSetup
bool tradeFree = not oneTrade or tradeDir == 0
bool commonOK = barstate.isconfirmed and activeSetup and inGoldenZone and volumeOK and inSession and rrOK and cooldownOK and dailyOK and newSetupOK and tradeFree
bool buySignal = commonOK and fibDir == 1 and bullishTrend and htfBull and bullishRSI and bullCandleOK
bool sellSignal = commonOK and fibDir == -1 and bearishTrend and htfBear and bearishRSI and bearCandleOK
if buySignal or sellSignal
tradeDir := buySignal ? 1 : -1
lastSignalDir := tradeDir
tradeBar := bar_index
tEntry := close
tSL := slPrice
tTP1 := tp1Level
tTP2 := tp2Level
tTP3 := tp3Level
tRR := rr
tSize := posSize
tradesToday += 1
lastSignalBar := bar_index
lastSignaledSetup := setupId
//====================================================
// 7. CHART VISUALS
//====================================================
plot(showEMA ? emaFast : na, "EMA Fast", color=color.yellow)
plot(showEMA ? emaSlow : na, "EMA Slow", color=color.blue)
plotshape(showSignals and buySignal, title="BUY", style=shape.labelup, location=location.belowbar, color=color.green, text="BUY", textcolor=color.white, size=size.small)
plotshape(showSignals and sellSignal, title="SELL", style=shape.labeldown, location=location.abovebar, color=color.red, text="SELL", textcolor=color.white, size=size.small)
plotshape(showResults and tpHit, title="TP Hit", style=shape.xcross, location=location.abovebar, color=color.lime, size=size.tiny)
plotshape(showResults and slHit, title="SL Hit", style=shape.xcross, location=location.belowbar, color=color.red, size=size.tiny)
plotshape(showPivots and not na(pivotHigh), title="Swing High", style=shape.triangledown, location=location.abovebar, offset=-pivotRight, color=color.red, size=size.tiny)
plotshape(showPivots and not na(pivotLow), title="Swing Low", style=shape.triangleup, location=location.belowbar, offset=-pivotRight, color=color.lime, size=size.tiny)
f_price(float v) =>
na(v) ? "N/A" : str.tostring(v, format.mintick)
// Drawn levels: only the current setup, extended to the right
var array<line> lvLines = array.new<line>()
var array<label> lvLabels = array.new<label>()
var box zoneBox = na
f_level(array<line> la, array<label> lb, float price, string name, color col, int w, int x1, int x2) =>
if not na(price)
array.push(la, line.new(x1, price, x2, price, color=col, width=w, style=line.style_solid))
array.push(lb, label.new(x2, price, name + " " + f_price(price), style=label.style_label_left, color=color.new(color.black, 100), textcolor=col, size=size.small))
if barstate.islast
for l in lvLines
line.delete(l)
array.clear(lvLines)
for lb in lvLabels
label.delete(lb)
array.clear(lvLabels)
if not na(zoneBox)
box.delete(zoneBox)
zoneBox := na
int xEnd = bar_index + extendBars
if showFib and activeSetup
int xs = fibStartBar
f_level(lvLines, lvLabels, fibB, "0", color.gray, 1, xs, xEnd)
f_level(lvLines, lvLabels, fib236, "0.236", color.aqua, 1, xs, xEnd)
f_level(lvLines, lvLabels, fib382, "0.382", color.blue, 1, xs, xEnd)
f_level(lvLines, lvLabels, fib500, "0.5", color.gray, 1, xs, xEnd)
f_level(lvLines, lvLabels, fib618, "0.618", color.yellow, 2, xs, xEnd)
f_level(lvLines, lvLabels, fib650, "0.65", color.orange, 1, xs, xEnd)
f_level(lvLines, lvLabels, fib705, "0.705", color.orange, 2, xs, xEnd)
f_level(lvLines, lvLabels, fib786, "0.786", color.red, 1, xs, xEnd)
f_level(lvLines, lvLabels, fibA, "1.0", color.gray, 1, xs, xEnd)
zoneBox := box.new(fibBBar, zoneHi, xEnd, zoneLo, border_color=na, bgcolor=color.new(color.orange, 85))
if showExt and activeSetup
f_level(lvLines, lvLabels, tp2Level, "T2 1.272", color.green, 1, fibBBar, xEnd)
f_level(lvLines, lvLabels, tp3Level, "T3 1.618", color.purple, 1, fibBBar, xEnd)
if showTrade and tradeDir != 0
f_level(lvLines, lvLabels, tEntry, "ENTRY", color.white, 2, tradeBar, xEnd)
f_level(lvLines, lvLabels, tSL, "SL", color.red, 2, tradeBar, xEnd)
f_level(lvLines, lvLabels, tTP1, "TP1", color.lime, 2, tradeBar, xEnd)
f_level(lvLines, lvLabels, tTP2, "TP2", color.green, 1, tradeBar, xEnd)
f_level(lvLines, lvLabels, tTP3, "TP3", color.purple, 1, tradeBar, xEnd)
//====================================================
// 8. CONFLUENCE SCORE
//====================================================
int bullScore = (bullishTrend ? 1 : 0) + (htfBull ? 1 : 0) + (bullishRSI ? 1 : 0) + (bullCandleOK ? 1 : 0) + (volumeOK ? 1 : 0) + (inSession ? 1 : 0) + (inGoldenZone ? 1 : 0)
int bearScore = (bearishTrend ? 1 : 0) + (htfBear ? 1 : 0) + (bearishRSI ? 1 : 0) + (bearCandleOK ? 1 : 0) + (volumeOK ? 1 : 0) + (inSession ? 1 : 0) + (inGoldenZone ? 1 : 0)
int score = fibDir == 1 ? bullScore : fibDir == -1 ? bearScore : 0
//====================================================
// 9. DASHBOARD
//====================================================
dashPos = switch dashPosition
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
var table dash = table.new(dashPos, 2, 15, border_width=1, frame_color=color.gray, border_color=color.new(color.gray, 50))
f_row(table t, int r, string label, string value, color valCol, color bg = na) =>
table.cell(t, 0, r, label, text_color=color.white, text_halign=text.align_left, text_size=size.small)
table.cell(t, 1, r, value, text_color=valCol, bgcolor=bg, text_halign=text.align_left, text_size=size.small)
if barstate.islast and showDashboard
int total = wins + losses
string winRate = total > 0 ? str.tostring(wins * 100.0 / total, "#.#") + "% (" + str.tostring(wins) + "W / " + str.tostring(losses) + "L)" : "N/A"
table.cell(dash, 0, 0, "CHOSEN SYSTEM", bgcolor=color.rgb(20, 30, 50), text_color=color.white, text_size=size.small)
table.cell(dash, 1, 0, "FIBONACCI PRO v2", bgcolor=color.rgb(20, 30, 50), text_color=color.yellow, text_size=size.small)
f_row(dash, 1, "Status", activeSetup ? "ACTIVE" : "WAITING", color.white, activeSetup ? color.new(color.green, 30) : color.new(color.gray, 40))
f_row(dash, 2, "EMA Trend", emaFast > emaSlow ? "BULLISH" : emaFast < emaSlow ? "BEARISH" : "NEUTRAL", emaFast > emaSlow ? color.lime : emaFast < emaSlow ? color.red : color.gray)
f_row(dash, 3, "HTF Trend", not useHTF ? "OFF" : htfBull ? "BULLISH" : htfBear ? "BEARISH" : "N/A", not useHTF ? color.gray : htfBull ? color.lime : htfBear ? color.red : color.gray)
f_row(dash, 4, "Fib Direction", fibDir == 1 ? "BULLISH" : fibDir == -1 ? "BEARISH" : "NONE", fibDir == 1 ? color.lime : fibDir == -1 ? color.red : color.gray)
f_row(dash, 5, "Zone", inGoldenZone ? "IN GOLDEN ZONE" : "WAITING", inGoldenZone ? color.orange : color.gray)
f_row(dash, 6, "RSI", str.tostring(rsiValue, "#.#"), color.white)
f_row(dash, 7, "Confluence", str.tostring(score) + " / 7", score >= 6 ? color.lime : score >= 4 ? color.yellow : color.gray)
f_row(dash, 8, "Last Signal", lastSignalDir == 1 ? (tradeDir != 0 ? "BUY (OPEN)" : "BUY") : lastSignalDir == -1 ? (tradeDir != 0 ? "SELL (OPEN)" : "SELL") : "NONE", lastSignalDir == 1 ? color.lime : lastSignalDir == -1 ? color.red : color.gray)
f_row(dash, 9, "Entry / SL", f_price(tEntry) + " / " + f_price(tSL), color.white)
f_row(dash, 10, "TP1 / TP2", f_price(tTP1) + " / " + f_price(tTP2), color.lime)
f_row(dash, 11, "RR / Size", (na(tRR) ? "N/A" : "1:" + str.tostring(tRR, "#.##")) + " / " + (na(tSize) ? "N/A" : str.tostring(tSize, "#.##")), color.white)
f_row(dash, 12, "Signals Today", str.tostring(tradesToday) + " / " + str.tostring(maxTradesDay), color.white)
f_row(dash, 13, "Win Rate (TP1)", winRate, color.white)
f_row(dash, 14, "Net R", str.tostring(netR, "#.##") + "R", netR > 0 ? color.lime : netR < 0 ? color.red : color.gray)
//====================================================
// 10. ALERTS
//====================================================
alertcondition(buySignal, title="FIB PRO BUY", message="CHOSEN FIB PRO: BUY | {{ticker}} | {{interval}} | Close: {{close}}")
alertcondition(sellSignal, title="FIB PRO SELL", message="CHOSEN FIB PRO: SELL | {{ticker}} | {{interval}} | Close: {{close}}")
alertcondition(inGoldenZone and fibDir == 1 and barstate.isconfirmed, title="Bullish Golden Zone", message="Price in bullish Golden Zone: {{ticker}} {{interval}}")
alertcondition(inGoldenZone and fibDir == -1 and barstate.isconfirmed, title="Bearish Golden Zone", message="Price in bearish Golden Zone: {{ticker}} {{interval}}")
alertcondition(tpHit, title="FIB PRO TP1 Hit", message="CHOSEN FIB PRO: TP1 hit | {{ticker}} | {{interval}}")
alertcondition(slHit, title="FIB PRO SL Hit", message="CHOSEN FIB PRO: Stop hit | {{ticker}} | {{interval}}")
if enableDynamicAlerts and (buySignal or sellSignal)
alert("CHOSEN FIB PRO | " + (buySignal ? "BUY" : "SELL") + " | " + syminfo.ticker + " | Entry: " + f_price(close) + " | SL: " + f_price(slPrice) + " | TP1: " + f_price(tp1Level) + " | TP2: " + f_price(tp2Level) + " | TP3: " + f_price(tp3Level) + " | RR: 1:" + str.tostring(rr, "#.##") + " | Size: " + str.tostring(posSize, "#.##"), alert.freq_once_per_bar_close)