本页源码来自 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/
// Concept credit: "Stochastic RSI + Heikin-Ashi" (Stocashi) (c) CoffeeshopCrypto - this is an independent, extended re-work.
//
// FishStoc v7 - Fisher Transform of Stochastic RSI, rendered as synthetic Heikin-Ashi-style candles
// built from the Fisher / Trigger pair (NOT price candles), with momentum, acceleration,
// pivot-based regular/hidden divergence, oversold/overbought turn markers, long/short exhaustion,
// early reversal detection and a compact dashboard.
//
// v7 CHANGES
// 1) Defaults: "Highlight Extreme Zones (Background)", "Show Acceleration Line" and "Show Dashboard" are OFF out of the box.
// 2) Divergence: new "Min Fisher Difference Between Pivots" filter removes near-equal pivots that produced
// marginal, low-quality divergences (set to 0 to restore the v6 behaviour).
// 3) Alerts: overbought / oversold zone-entry alerts now fire on confirmed bar close only (no intrabar flicker);
// new alerts for Fisher crossing the zero line.
// 4) Dashboard: new "Last Signal" row (BUY / BUY+ / SELL / SELL+ and its age).
// 5) Cross-filter tooltip corrected: the filter tests the Trigger line, which is what the code does.
// 6) Label overlap fix: BUY / SELL, LX / SX and ER markers on the same bar are merged into one stacked label per side,
// and divergence tags are drawn as separate centred tags with an auto-scaled offset.
// 7) Short script title for the Pine editor / publishing rules; all strings kept plain ASCII-safe text.
//
// v6 CHANGES
// 1) Long / Short Exhaustion (LX / SX): Fisher is stretched beyond the exhaustion level while momentum still
// points the same way but is decelerating and has faded to a fraction of its recent peak.
// 2) Early Reversal Detection (ER): Fisher touched an extreme zone recently, has not crossed its Trigger yet,
// and acceleration has flipped to the reversal side for N consecutive bars with a minimum intensity.
// 3) Confluence labels: a BUY / SELL cross that follows an ER or opposite exhaustion signal within N bars
// is upgraded to BUY+ / SELL+.
// 4) All text markers are drawn with label.new() instead of plotshape(), so they do not count toward the plot limit.
// All exhaustion / early-reversal / cross signals are evaluated on confirmed bars only (no repaint).
//
// DISCLAIMER: Educational/analytical tool. It is not financial advice and does not guarantee results.
//@version=6
indicator(title="FishStoc", shorttitle="FishStoc", overlay=false, max_lines_count=500, max_labels_count=500, precision=2)
// ============================================================================
// === INPUTS: CORE ===
// ============================================================================
grp_core = "Core Settings"
src = input.source(close, "Source", group=grp_core)
lengthRSI = input.int(14, "RSI Length", minval=1, group=grp_core)
lengthStoch = input.int(14, "Stochastic Length", minval=1, group=grp_core)
fisherLen = input.int(9, "Fisher Normalization Length", minval=1, group=grp_core, tooltip="Lookback used to normalise Stochastic RSI to 0..1 before the Fisher Transform.")
showFisherLine = input.bool(true, "Show Fisher / Trigger Lines", group=grp_core)
grp_trig = "Trigger Line"
trigMode = input.string("Classic (previous Fisher)", "Trigger Type", options=["Classic (previous Fisher)", "Smoothed (EMA of Fisher)"], group=grp_trig,
tooltip="Classic: Trigger = Fisher of the previous bar (Ehlers). Every one-bar reversal counts as a cross. Smoothed: Trigger = EMA of Fisher, fewer and cleaner crosses with a small lag.")
trigLen = input.int(3, "EMA Length (Smoothed type)", minval=2, group=grp_trig)
grp_zone = "Overbought / Oversold Zones"
obInner = input.float(0.75, "Zone Inner Level (+/-)", minval=0.1, step=0.05, group=grp_zone, tooltip="Entry level of the overbought/oversold bands. Also used by the zone filter, turn markers and dashboard.")
obOuter = input.float(1.5, "Zone Outer Level (+/-)", minval=0.2, step=0.05, group=grp_zone, tooltip="Outer edge of the bands and the extreme-zone background trigger. Keep it above the Inner Level.")
obColor = input.color(color.rgb(255, 82, 82, 92), "Overbought Band", inline="OBOS", group=grp_zone)
osColor = input.color(color.rgb(122, 255, 82, 92), "Oversold Band", inline="OBOS", group=grp_zone)
// ============================================================================
// === INPUTS: THEME / VISUALS ===
// ============================================================================
grp_vis = "Theme & Visuals"
theme = input.string("Ocean", "Colour Theme", options=["Ocean", "Classic", "Neon", "Custom"], group=grp_vis, tooltip="Ocean (blue/orange) is the default because it stays readable for colour-blind users. Classic = green/red family, Neon = bright variant. 'Custom' uses the four colours below.")
bullStartIn = input.color(#00a86b, "Custom: Bullish Start", inline="CB", group=grp_vis)
bullEndIn = input.color(#00e5ff, "Custom: Bullish End", inline="CB", group=grp_vis)
bearStartIn = input.color(#d50000, "Custom: Bearish Start", inline="CR", group=grp_vis)
bearEndIn = input.color(#ff9100, "Custom: Bearish End", inline="CR", group=grp_vis)
showZoneBg = input.bool(false, "Highlight Extreme Zones (Background)", group=grp_vis, tooltip="Off by default. Tints the pane background while Fisher is beyond the Zone Outer Level.")
showFill = input.bool(true, "Fill Between Fisher and Trigger", group=grp_vis)
showDash = input.bool(false, "Show Dashboard", group=grp_vis, tooltip="Off by default. Shows a compact status table: Fisher, zone, momentum, acceleration, exhaustion, early reversal, HTF bias, last signal and last divergence.")
dashPosIn = input.string("Top Right", "Dashboard Position", options=["Top Right", "Top Left", "Bottom Right", "Bottom Left"], group=grp_vis)
colorMode = input.string("Position (Level)", "Candle Colour Mode", options=["Position (Level)", "Momentum", "Speedometer"], group=grp_vis,
tooltip="Position: gradient by Fisher level. Momentum: gradient by bar-to-bar change. Speedometer: green, yellow, red by momentum intensity.")
autoGradientRange = input.bool(true, "Auto Gradient Scale (StdDev-based)", group=grp_vis)
gradientRangeManual = input.float(2.0, "Manual Gradient Limit (+/-)", minval=0.1, group=grp_vis)
gradientRangeLookback = input.int(100, "Auto Scale Lookback (bars)", minval=10, group=grp_vis)
gradientRangeMult = input.float(2.0, "Auto Scale Multiplier (x StdDev)", minval=0.1, group=grp_vis)
// Bullish family = blue/green to cyan, bearish family = red/orange to amber: the two families never share a hue,
// and each family keeps a narrow tonal range so the shades inside a family do not blur together
bullStart = switch theme
"Classic" => #00a86b
"Neon" => #00b0ff
"Ocean" => #1565c0
=> bullStartIn
bullEnd = switch theme
"Classic" => #00e5ff
"Neon" => #00ffa3
"Ocean" => #4fc3f7
=> bullEndIn
bearStart = switch theme
"Classic" => #d50000
"Neon" => #f50057
"Ocean" => #e65100
=> bearStartIn
bearEnd = switch theme
"Classic" => #ff9100
"Neon" => #ff9100
"Ocean" => #ffb300
=> bearEndIn
dashPos = switch dashPosIn
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
// ============================================================================
// === RSI -> STOCHASTIC -> FISHER TRANSFORM ===
// ============================================================================
rsi1 = ta.rsi(src, lengthRSI)
stochRsi = ta.stoch(rsi1, rsi1, rsi1, lengthStoch)
fisherHigh = ta.highest(stochRsi, fisherLen)
fisherLow = ta.lowest(stochRsi, fisherLen)
f_clamp(val) => val > 0.999 ? 0.999 : val < -0.999 ? -0.999 : val
range_ = fisherHigh - fisherLow
normalizedStoch = range_ == 0 ? 0.5 : (stochRsi - fisherLow) / range_
var float fishInput = 0.0
fishInput := f_clamp(0.66 * (normalizedStoch - 0.5) + 0.67 * nz(fishInput[1]))
var float k = 0.0
k := 0.5 * math.log((1 + fishInput) / (1 - fishInput)) + 0.5 * nz(k[1])
// Stateful ta.* call is evaluated on every bar, outside the conditional expression
kEma = ta.ema(k, trigLen)
d = trigMode == "Smoothed (EMA of Fisher)" ? kEma : nz(k[1], k)
// Synthetic Heikin-Ashi-style candle built from Fisher (k) and Trigger (d); it is not a price candle
ha_open = (nz(k[1], k) + nz(d[1], d)) / 2
ha_close = (k + d) / 2
ha_high = math.max(k, math.max(d, math.max(ha_open, ha_close)))
ha_low = math.min(k, math.min(d, math.min(ha_close, ha_open)))
// ============================================================================
// === HIGHER-TIMEFRAME BIAS (non-repainting) ===
// ============================================================================
grp_htf = "Higher-Timeframe Filter"
useHtf = input.bool(false, "Filter BUY / SELL by HTF Bias", group=grp_htf, tooltip="BUY labels need a bullish HTF bias, SELL labels a bearish one. Uses the last CONFIRMED higher-timeframe bar, so it never repaints. The HTF must be above the chart timeframe.")
htfTf = input.timeframe("240", "HTF Timeframe", group=grp_htf)
htfMode = input.string("Direction (Fisher vs Trigger)", "HTF Bias Mode", options=["Direction (Fisher vs Trigger)", "Level (Fisher vs 0)"], group=grp_htf)
htfValid = timeframe.in_seconds(htfTf) > timeframe.in_seconds()
[kHtf, dHtf] = request.security(syminfo.tickerid, htfTf, [k[1], d[1]], lookahead=barmerge.lookahead_on)
htfBull = htfValid and not na(kHtf) and (htfMode == "Level (Fisher vs 0)" ? kHtf > 0 : kHtf > dHtf)
htfBear = htfValid and not na(kHtf) and (htfMode == "Level (Fisher vs 0)" ? kHtf < 0 : kHtf < dHtf)
htfOkBuy = not useHtf or not htfValid or htfBull
htfOkSell = not useHtf or not htfValid or htfBear
// ============================================================================
// === HELPERS ===
// ============================================================================
f_autoScaleRange(_raw, _lookback, _mult, _manual, _useAuto) =>
_stdev = ta.stdev(_raw, _lookback)
_useAuto ? (_stdev > 0.0001 ? _stdev * _mult : _manual) : _manual
f_intensity(_val, _range) =>
_range > 0.0001 ? math.min(math.abs(_val) / _range, 1.0) : 0.0
// ============================================================================
// === MOMENTUM ===
// ============================================================================
grp_mom = "Momentum"
momentumSource = input.string("Bar-to-Bar Change (k - k[1])", "Momentum Source",
options=["Bar-to-Bar Change (k - k[1])", "Fisher-Trigger Spread (k - d)"], group=grp_mom)
momentumSmooth = input.int(1, "Momentum Smoothing (EMA, 1 = off)", minval=1, group=grp_mom)
autoMomRange = input.bool(true, "Auto Momentum Scale (StdDev-based)", group=grp_mom)
momRangeManual = input.float(0.5, "Manual Momentum Scale (+/-)", minval=0.01, group=grp_mom)
momRangeLookback = input.int(100, "Auto Scale Lookback (bars)", minval=10, group=grp_mom)
momRangeMult = input.float(2.0, "Auto Scale Multiplier (x StdDev)", minval=0.1, group=grp_mom)
neutralMomColor = input.color(color.gray, "Neutral Momentum Colour", group=grp_mom)
showMomentumHist = input.bool(true, "Show Momentum Histogram", group=grp_mom)
autoHistScale = input.bool(true, "Auto Histogram Scale", group=grp_mom)
momentumDisplayScaleManual = input.float(4.0, "Manual Histogram Multiplier", minval=0.1, group=grp_mom)
showMomentumGauge = input.bool(true, "Momentum Candle Border (Position mode)", group=grp_mom, tooltip="When momentum intensity is above the threshold, the candle border and wick take the momentum colour. No extra symbols on the chart.")
momBorderThreshold = input.float(0.5, "Border Intensity Threshold (0-1)", minval=0.05, maxval=1.0, step=0.05, group=grp_mom)
gaugeColorBull = input.color(#ffee00, "Border Colour (Rising)", inline="Gauge", group=grp_mom, tooltip="Defaults are complementary to the Ocean theme bodies: yellow stands out on blue (rising), cyan stands out on orange (falling). The wick takes the same colour.")
gaugeColorBear = input.color(#00e5ff, "Border Colour (Falling)", inline="Gauge", group=grp_mom)
rawMomentum = momentumSource == "Bar-to-Bar Change (k - k[1])" ? k - nz(k[1], k) : k - d
momentum = ta.ema(rawMomentum, momentumSmooth)
momentumRange = f_autoScaleRange(momentum, momRangeLookback, momRangeMult, momRangeManual, autoMomRange)
momentumDisplayScale = autoHistScale
? (momentumRange > 0.0001 ? 0.375 / momentumRange : momentumDisplayScaleManual)
: momentumDisplayScaleManual
// ============================================================================
// === SPEEDOMETER ===
// ============================================================================
grp_speed = "Speedometer Mode"
speedLowColor = input.color(color.lime, "Low Speed", inline="SpeedCol", group=grp_speed)
speedMidColor = input.color(color.yellow, "Mid Speed", inline="SpeedCol", group=grp_speed)
speedHighColor = input.color(color.red, "High Speed", inline="SpeedCol", group=grp_speed)
speedMidThreshold = input.float(0.5, "Yellow Threshold (intensity 0-1)", minval=0.05, maxval=0.95, step=0.05, group=grp_speed)
showSpeedBorder = input.bool(true, "Direction Border", group=grp_speed)
speedBorderUpColor = input.color(color.white, "Border (Up)", inline="SpeedBorder", group=grp_speed)
speedBorderDownColor = input.color(color.black, "Border (Down)", inline="SpeedBorder", group=grp_speed)
// ============================================================================
// === ACCELERATION ===
// ============================================================================
// Momentum = speed of k. Acceleration = how fast that speed changes (momentum - momentum[1]).
grp_accel = "Acceleration"
showAcceleration = input.bool(false, "Show Acceleration Line", group=grp_accel, tooltip="Off by default for a cleaner chart. Acceleration is still read from the histogram tone (solid = momentum strengthening, faded = weakening), the triangles and the Data Window.")
accelSmooth = input.int(1, "Acceleration Smoothing (EMA, 1 = off)", minval=1, group=grp_accel)
autoAccelRange = input.bool(true, "Auto Acceleration Scale (StdDev-based)", group=grp_accel)
accelRangeManual = input.float(0.25, "Manual Acceleration Scale", minval=0.01, group=grp_accel)
accelRangeLookback = input.int(100, "Auto Scale Lookback (bars)", minval=10, group=grp_accel)
accelRangeMult = input.float(2.0, "Auto Scale Multiplier (x StdDev)", minval=0.1, group=grp_accel)
accelColorUp = input.color(color.orange, "Accelerating", inline="AccelCol", group=grp_accel)
accelColorDown = input.color(color.teal, "Decelerating", inline="AccelCol", group=grp_accel)
showAccelMarkers = input.bool(true, "Strong Acceleration Triangles", group=grp_accel)
accelMarkerThreshold = input.float(0.75, "Marker Threshold (intensity 0-1)", minval=0.1, maxval=1.0, step=0.05, group=grp_accel)
autoAccelDisplayScale = input.bool(true, "Auto Acceleration Line Scale", group=grp_accel)
accelDisplayScaleManual = input.float(4.0, "Manual Acceleration Line Multiplier", minval=0.1, group=grp_accel)
rawAccel = momentum - nz(momentum[1], momentum)
accel = ta.ema(rawAccel, accelSmooth)
accelRange = f_autoScaleRange(accel, accelRangeLookback, accelRangeMult, accelRangeManual, autoAccelRange)
accelIntensity = f_intensity(accel, accelRange)
accelDisplayScale = autoAccelDisplayScale
? (accelRange > 0.0001 ? 0.375 / accelRange : accelDisplayScaleManual)
: accelDisplayScaleManual
accelColor = accel >= 0 ? accelColorUp : accelColorDown
// ============================================================================
// === COLOURS ===
// ============================================================================
gradientRange = f_autoScaleRange(k, gradientRangeLookback, gradientRangeMult, gradientRangeManual, autoGradientRange)
gradientColourBull = color.from_gradient(k, -gradientRange, gradientRange, bullStart, bullEnd)
gradientColourBear = color.from_gradient(k, -gradientRange, gradientRange, bearEnd, bearStart)
positionColor = ha_close >= ha_open ? gradientColourBull : gradientColourBear
momentumIntensity = f_intensity(momentum, momentumRange)
gaugeColor = momentum >= 0 ? gaugeColorBull : gaugeColorBear
momentumColor = momentum >= 0
? color.from_gradient(momentum, 0, momentumRange, neutralMomColor, bullEnd)
: color.from_gradient(momentum, -momentumRange, 0, bearStart, neutralMomColor)
speedColor = momentumIntensity <= speedMidThreshold
? color.from_gradient(momentumIntensity, 0.0, speedMidThreshold, speedLowColor, speedMidColor)
: color.from_gradient(momentumIntensity, speedMidThreshold, 1.0, speedMidColor, speedHighColor)
bar_color = switch colorMode
"Momentum" => momentumColor
"Speedometer" => speedColor
=> positionColor
border_color = colorMode == "Speedometer" and showSpeedBorder
? (ha_close >= ha_open ? speedBorderUpColor : speedBorderDownColor)
: colorMode == "Position (Level)" and showMomentumGauge and momentumIntensity >= momBorderThreshold
? gaugeColor
: bar_color
// ============================================================================
// === DRAWING: BACKGROUND, ZONES, CANDLES, LINES ===
// ============================================================================
bgcolor(showZoneBg ? (k >= obOuter ? color.new(bearStart, 88) : k <= -obOuter ? color.new(bullStart, 88) : na) : na, title="Extreme Zone Background")
hline(0, "Zero", color=#d47305a1)
obHigh = hline(obOuter, "OB Upper", color=obColor, linestyle=hline.style_dotted, editable=false)
obLow = hline(obInner, "OB Lower", color=obColor, linestyle=hline.style_dotted, editable=false)
osHigh = hline(-obInner, "OS Upper", color=osColor, linestyle=hline.style_dotted, editable=false)
osLow = hline(-obOuter, "OS Lower", color=osColor, linestyle=hline.style_dotted, editable=false)
fill(obHigh, obLow, color=obColor, title="OB Zone")
fill(osHigh, osLow, color=osColor, title="OS Zone")
// Histogram tone encodes acceleration: solid = momentum strengthening (same sign as its change), faded = weakening
momStrengthening = momentum * accel > 0
momHistTransp = momStrengthening ? 0 : 72
momHistColor = momentum >= 0 ? color.new(bullEnd, momHistTransp) : color.new(bearStart, momHistTransp)
plot(showMomentumHist ? momentum * momentumDisplayScale : na, title="Momentum Histogram", style=plot.style_columns, color=momHistColor)
// The wick shares the highlight colour: borders are only 1px wide, so a coloured wick makes the signal visible at a glance
highlightOn = colorMode == "Position (Level)" and showMomentumGauge and momentumIntensity >= momBorderThreshold
wick_color = highlightOn ? gaugeColor : bar_color
plotcandle(ha_open, ha_high, ha_low, ha_close, title="Fisher Stochastic HA Gradient", color=bar_color, wickcolor=wick_color, bordercolor=border_color)
pK = plot(showFisherLine ? k : na, color=#2962FF, title="Fisher", linewidth=1)
pD = plot(showFisherLine ? d : na, color=#FF6D00, title="Trigger", linewidth=1)
fill(pK, pD, color=showFill ? (k >= d ? color.new(bullEnd, 82) : color.new(bearStart, 82)) : na, title="Fisher/Trigger Fill")
plot(accel * accelDisplayScale, title="Acceleration Line", style=plot.style_line, color=accelColor, linewidth=2, display=showAcceleration ? display.all : display.none)
// Always available in the Data Window (hover over a bar), even when the line is hidden
plot(accel, title="Acceleration (raw)", color=accelColor, display=display.data_window)
plot(accelIntensity, title="Acceleration Intensity (0-1)", color=accelColor, display=display.data_window)
plotshape(showAccelMarkers and accelIntensity >= accelMarkerThreshold and accel >= 0, title="Strong Acceleration", style=shape.triangleup, location=location.top, size=size.tiny, color=accelColorUp)
plotshape(showAccelMarkers and accelIntensity >= accelMarkerThreshold and accel < 0, title="Strong Deceleration", style=shape.triangledown, location=location.bottom, size=size.tiny, color=accelColorDown)
// ============================================================================
// === EXHAUSTION & EARLY REVERSAL (bar close only) ===
// ============================================================================
grp_exh = "Exhaustion (Long / Short)"
showExh = input.bool(true, "Show Long / Short Exhaustion", group=grp_exh, tooltip="LX (Long Exhaustion): Fisher is stretched high, upside momentum is still positive but fading, so buyers are running out of fuel. SX (Short Exhaustion): the mirror image at the lower extreme. Fires once when the condition starts, on confirmed bars only.")
exhLevel = input.float(1.0, "Exhaustion Zone Level (+/-)", minval=0.1, step=0.05, group=grp_exh, tooltip="Fisher must be beyond this level. The default sits between the inner and outer zone levels.")
exhLookback = input.int(5, "Peak Momentum Lookback (bars)", minval=2, group=grp_exh)
exhFade = input.float(0.6, "Fade Ratio (momentum / recent peak)", minval=0.1, maxval=0.95, step=0.05, group=grp_exh, tooltip="Momentum must fall to this fraction of its recent peak while still pointing the same way and decelerating. Lower value = stricter.")
exhColorLong = input.color(#ff4081, "Long Exhaustion (LX)", inline="ExhCol", group=grp_exh)
exhColorShort = input.color(#69f0ae, "Short Exhaustion (SX)", inline="ExhCol", group=grp_exh)
markGap = input.float(0.25, "Manual Marker Offset", minval=0.05, step=0.05, group=grp_exh, tooltip="Used only when Auto Marker Offset (Label Layout group) is off. Distance of the divergence tags from the candles, in Fisher units.")
grp_er = "Early Reversal Detection"
showEarly = input.bool(true, "Show Early Reversal (ER)", group=grp_er, tooltip="Fires BEFORE the Fisher/Trigger cross: Fisher touched an extreme zone recently, it is still on the old side of its Trigger, and acceleration has turned toward the reversal for several consecutive bars.")
erLevel = input.float(0.5, "Zone Level (+/-)", minval=0.1, step=0.05, group=grp_er, tooltip="Fisher must have reached at least this level (low side for bullish, high side for bearish) within the lookback below.")
erZoneLookback = input.int(5, "Zone Touch Lookback (bars)", minval=1, group=grp_er)
erBars = input.int(2, "Acceleration Confirmation Bars", minval=1, group=grp_er, tooltip="Acceleration must stay on the reversal side for this many consecutive bars. Higher = later but cleaner.")
erMinIntensity = input.float(0.15, "Min Acceleration Intensity (0-1)", minval=0.0, maxval=1.0, step=0.05, group=grp_er, tooltip="Filters out tiny accelerations. Intensity is acceleration relative to its own StdDev-based scale.")
erColorBull = input.color(#ffd600, "Early Bullish (ER)", inline="ErCol", group=grp_er)
erColorBear = input.color(#b388ff, "Early Bearish (ER)", inline="ErCol", group=grp_er)
grp_conf = "Confluence Labels"
confMark = input.bool(true, "Upgrade BUY / SELL to BUY+ / SELL+", group=grp_conf, tooltip="A BUY (SELL) that comes within the window below after an Early Bullish Reversal or Short Exhaustion (Early Bearish Reversal or Long Exhaustion) is labelled BUY+ (SELL+).")
confWindow = input.int(3, "Confluence Window (bars)", minval=1, group=grp_conf)
warmBars = lengthRSI + lengthStoch + fisherLen
// --- Exhaustion: stretched Fisher, momentum still in the same direction but decelerating and faded from its peak ---
momPeakUp = ta.highest(momentum, exhLookback)
momPeakDn = ta.lowest(momentum, exhLookback)
exhLongCond = showExh and k >= exhLevel and momentum > 0 and accel < 0 and momentum <= momPeakUp * exhFade
exhShortCond = showExh and k <= -exhLevel and momentum < 0 and accel > 0 and momentum >= momPeakDn * exhFade
exhLongSig = exhLongCond and not exhLongCond[1] and barstate.isconfirmed and bar_index >= warmBars
exhShortSig = exhShortCond and not exhShortCond[1] and barstate.isconfirmed and bar_index >= warmBars
// --- Early reversal: zone touched recently, Fisher still on the old side of Trigger, acceleration turned ---
var int accelUpCnt = 0
var int accelDnCnt = 0
accelUpCnt := accel > 0 ? accelUpCnt + 1 : 0
accelDnCnt := accel < 0 ? accelDnCnt + 1 : 0
kLowRecent = ta.lowest(k, erZoneLookback)
kHighRecent = ta.highest(k, erZoneLookback)
earlyBullCond = showEarly and kLowRecent <= -erLevel and k < d and accelUpCnt >= erBars and accelIntensity >= erMinIntensity
earlyBearCond = showEarly and kHighRecent >= erLevel and k > d and accelDnCnt >= erBars and accelIntensity >= erMinIntensity
earlyBullSig = earlyBullCond and not earlyBullCond[1] and barstate.isconfirmed and bar_index >= warmBars
earlyBearSig = earlyBearCond and not earlyBearCond[1] and barstate.isconfirmed and bar_index >= warmBars
// --- Pre-signals feed the BUY+ / SELL+ confluence ---
preBull = earlyBullSig or exhShortSig
preBear = earlyBearSig or exhLongSig
barsPreBull = ta.barssince(preBull)
barsPreBear = ta.barssince(preBear)
// (LX / SX / ER markers are drawn together with the BUY / SELL labels in the Label Layout block below)
// ============================================================================
// === TURN MARKERS (Fisher/Trigger cross, optionally only from OB/OS zones, bar close only) ===
// ============================================================================
grp_turn = "Fisher / Trigger Cross Labels"
showTurns = input.bool(true, "Show BUY / SELL Labels", group=grp_turn, tooltip="Labels the Fisher line crossing its Trigger. Evaluated on confirmed bars only (no intrabar flicker). A study aid, not financial advice.")
crossFilter = input.string("Only From OB/OS Zones", "Cross Filter", options=["Only From OB/OS Zones", "All Crosses"], group=grp_turn, tooltip="'Only From OB/OS Zones' requires the Trigger line to be beyond the Zone Inner Level at the cross (below the negative level for BUY, above the positive level for SELL), which removes most noise.")
sigCooldown = input.int(0, "Signal Cooldown (bars, 0 = off)", minval=0, group=grp_turn, tooltip="Minimum number of bars between two signals of the same direction.")
buyTxtColor = input.color(color.white, "Label Text", inline="LblCol", group=grp_turn)
buyLblColor = input.color(#1565c0, "BUY Fill", inline="LblCol", group=grp_turn)
sellLblColor = input.color(#e65100, "SELL Fill", inline="LblCol", group=grp_turn)
crossUp = ta.crossover(k, d)
crossDn = ta.crossunder(k, d)
buyRaw = crossUp and barstate.isconfirmed and (crossFilter == "All Crosses" or d <= -obInner) and htfOkBuy
sellRaw = crossDn and barstate.isconfirmed and (crossFilter == "All Crosses" or d >= obInner) and htfOkSell
var int lastBuyBar = na
var int lastSellBar = na
buySig = buyRaw and (na(lastBuyBar) or bar_index - lastBuyBar > sigCooldown)
sellSig = sellRaw and (na(lastSellBar) or bar_index - lastSellBar > sigCooldown)
if buySig
lastBuyBar := bar_index
if sellSig
lastSellBar := bar_index
// Confluence: the cross follows an early-reversal / opposite-exhaustion signal within the window
buyConf = confMark and buySig and not na(barsPreBull) and barsPreBull <= confWindow
sellConf = confMark and sellSig and not na(barsPreBear) and barsPreBear <= confWindow
buyPlain = buySig and not buyConf
sellPlain = sellSig and not sellConf
// ============================================================================
// === LABEL LAYOUT (one label per bar and side, no overlapping) ===
// ============================================================================
// Simultaneous markers on the same bar (BUY, SX, ER / SELL, LX, ER) are stacked as lines of text inside ONE label,
// so they can never be drawn on top of each other. Divergence tags are placed farther out, as separate centred tags.
grp_lbl = "Label Layout"
autoGap = input.bool(true, "Auto Marker Offset", group=grp_lbl, tooltip="Scales the distance of the divergence tags from the candles to the current Fisher range, so labels stay clear of each other on any chart scale. Turn off to use the manual offset from the Exhaustion group.")
kSpan = ta.highest(k, 200) - ta.lowest(k, 200)
gap = autoGap ? math.max(0.1, kSpan * 0.06) : markGap
f_join(_a, _b, _c) =>
string _r = _a
if _b != ""
_r := _r == "" ? _b : _r + "\n" + _b
if _c != ""
_r := _r == "" ? _c : _r + "\n" + _c
_r
bullLine1 = showTurns and buyConf ? "BUY+" : showTurns and buyPlain ? "BUY" : ""
bullLine2 = exhShortSig ? "SX" : ""
bullLine3 = earlyBullSig ? "ER" : ""
bullTxt = f_join(bullLine1, bullLine2, bullLine3)
bullFill = bullLine1 != "" ? buyLblColor : bullLine2 != "" ? exhColorShort : erColorBull
bullTxtCol = bullLine1 != "" ? buyTxtColor : color.black
bearLine1 = showTurns and sellConf ? "SELL+" : showTurns and sellPlain ? "SELL" : ""
bearLine2 = exhLongSig ? "LX" : ""
bearLine3 = earlyBearSig ? "ER" : ""
bearTxt = f_join(bearLine1, bearLine2, bearLine3)
bearFill = bearLine1 != "" ? sellLblColor : bearLine2 != "" ? exhColorLong : erColorBear
bearTxtCol = bearLine1 != "" ? buyTxtColor : bearLine2 != "" ? color.white : color.black
if bullTxt != ""
label.new(bar_index, ha_low, bullTxt, xloc=xloc.bar_index, yloc=yloc.price, color=bullFill, textcolor=bullTxtCol, style=label.style_label_up, size=size.tiny)
if bearTxt != ""
label.new(bar_index, ha_high, bearTxt, xloc=xloc.bar_index, yloc=yloc.price, color=bearFill, textcolor=bearTxtCol, style=label.style_label_down, size=size.tiny)
// Last signal memory for the dashboard
var string lastSig = "None"
var int lastSigBar = na
if buyPlain
lastSig := "BUY"
lastSigBar := bar_index
if buyConf
lastSig := "BUY+"
lastSigBar := bar_index
if sellPlain
lastSig := "SELL"
lastSigBar := bar_index
if sellConf
lastSig := "SELL+"
lastSigBar := bar_index
// Zone entry and zero-line events (used by alerts); stateful ta.* calls first, bar-close gate second
crossOBraw = ta.crossover(k, obInner)
crossOSraw = ta.crossunder(k, -obInner)
crossZeroUp = ta.crossover(k, 0.0)
crossZeroDn = ta.crossunder(k, 0.0)
enterOB = crossOBraw and barstate.isconfirmed
enterOS = crossOSraw and barstate.isconfirmed
zeroUpSig = crossZeroUp and barstate.isconfirmed
zeroDnSig = crossZeroDn and barstate.isconfirmed
// ============================================================================
// === DIVERGENCE ===
// ============================================================================
grp_div = "Divergence"
showRegular = input.bool(true, "Show Regular Divergences", group=grp_div)
showHidden = input.bool(true, "Show Hidden Divergences", group=grp_div)
onlyZones = input.bool(false, "Only Pivots Inside OB/OS Zones", group=grp_div, tooltip="Uses the Zone Inner Level as the threshold.")
lbR = input.int(5, "Pivot Right Bars", minval=1, group=grp_div, tooltip="A divergence is only confirmed this many bars after the pivot. Labels are drawn back on the pivot bar; they do not move once printed.")
lbL = input.int(5, "Pivot Left Bars", minval=1, group=grp_div)
rangeUpper = input.int(60, "Max Bars Between Pivots", minval=1, group=grp_div)
rangeLower = input.int(5, "Min Bars Between Pivots", minval=1, group=grp_div)
minFishDiff = input.float(0.10, "Min Fisher Difference Between Pivots", minval=0.0, step=0.05, group=grp_div, tooltip="The two Fisher pivots must differ by at least this amount. Removes near-equal pivots that create marginal divergences. 0 = off (v6 behaviour). Price is read from the high / low of the pivot bar.")
colRegBull = input.color(color.green, "Regular Bullish", inline="DivR", group=grp_div)
colRegBear = input.color(color.red, "Regular Bearish", inline="DivR", group=grp_div)
colHidBull = input.color(color.new(color.green, 50), "Hidden Bullish", inline="DivH", group=grp_div)
colHidBear = input.color(color.new(color.red, 50), "Hidden Bearish", inline="DivH", group=grp_div)
showDivLines = input.bool(true, "Connect Pivots With Lines", group=grp_div)
divLineWidth = input.int(1, "Line Width", minval=1, maxval=4, group=grp_div)
minBarsWarmup = lengthRSI + lengthStoch + fisherLen + lbL + lbR
validData = bar_index >= minBarsWarmup
pivHigh = ta.pivothigh(k, lbL, lbR)
pivLow = ta.pivotlow(k, lbL, lbR)
zoneOkHigh = not onlyZones or nz(k[lbR]) >= obInner
zoneOkLow = not onlyZones or nz(k[lbR]) <= -obInner
// barstate.isconfirmed: the right side of a pivot includes the current bar, which can still change on a live bar
condHigh = not na(pivHigh) and zoneOkHigh and barstate.isconfirmed
condLow = not na(pivLow) and zoneOkLow and barstate.isconfirmed
// Current pivot (lbR bars back) and the previously stored pivot of the same side
float curLowK = k[lbR]
float curLowP = low[lbR]
int curLowB = bar_index - lbR
float curHighK = k[lbR]
float curHighP = high[lbR]
int curHighB = bar_index - lbR
var float prevLowK = na
var float prevLowP = na
var int prevLowB = na
var float prevHighK = na
var float prevHighP = na
var int prevHighB = na
// True pivot-to-pivot distance
barsLow = curLowB - prevLowB
barsHigh = curHighB - prevHighB
inRangeLow = not na(prevLowB) and barsLow >= rangeLower and barsLow <= rangeUpper
inRangeHigh = not na(prevHighB) and barsHigh >= rangeLower and barsHigh <= rangeUpper
// Bullish: price makes the lower low / higher low, oscillator does the opposite
regBull = showRegular and condLow and curLowK - prevLowK >= minFishDiff and curLowK > prevLowK and curLowP < prevLowP and inRangeLow and validData
hidBull = showHidden and condLow and prevLowK - curLowK >= minFishDiff and curLowK < prevLowK and curLowP > prevLowP and inRangeLow and validData
// Bearish: price makes the higher high / lower high, oscillator does the opposite
regBear = showRegular and condHigh and prevHighK - curHighK >= minFishDiff and curHighK < prevHighK and curHighP > prevHighP and inRangeHigh and validData
hidBear = showHidden and condHigh and curHighK - prevHighK >= minFishDiff and curHighK > prevHighK and curHighP < prevHighP and inRangeHigh and validData
divBullTxt = regBull ? "R-Bull" : hidBull ? "H-Bull" : ""
divBearTxt = regBear ? "R-Bear" : hidBear ? "H-Bear" : ""
divBullCol = regBull ? colRegBull : colHidBull
divBearCol = regBear ? colRegBear : colHidBear
if divBullTxt != ""
label.new(curLowB, math.min(nz(ha_low[lbR], curLowK), curLowK) - 3.5 * gap, divBullTxt, xloc=xloc.bar_index, yloc=yloc.price, color=divBullCol, textcolor=color.white, style=label.style_label_center, size=size.tiny)
if divBearTxt != ""
label.new(curHighB, math.max(nz(ha_high[lbR], curHighK), curHighK) + 3.5 * gap, divBearTxt, xloc=xloc.bar_index, yloc=yloc.price, color=divBearCol, textcolor=color.white, style=label.style_label_center, size=size.tiny)
if showDivLines and regBull
line.new(prevLowB, prevLowK, curLowB, curLowK, xloc=xloc.bar_index, color=colRegBull, width=divLineWidth)
if showDivLines and hidBull
line.new(prevLowB, prevLowK, curLowB, curLowK, xloc=xloc.bar_index, color=colHidBull, width=divLineWidth)
if showDivLines and regBear
line.new(prevHighB, prevHighK, curHighB, curHighK, xloc=xloc.bar_index, color=colRegBear, width=divLineWidth)
if showDivLines and hidBear
line.new(prevHighB, prevHighK, curHighB, curHighK, xloc=xloc.bar_index, color=colHidBear, width=divLineWidth)
// Store the current pivot only AFTER it has been compared with the previous one
if condLow
prevLowK := curLowK
prevLowP := curLowP
prevLowB := curLowB
if condHigh
prevHighK := curHighK
prevHighP := curHighP
prevHighB := curHighB
// ============================================================================
// === DASHBOARD ===
// ============================================================================
var string lastDiv = "None"
var int lastDivBar = na
if regBull
lastDiv := "Regular Bull"
lastDivBar := curLowB
if hidBull
lastDiv := "Hidden Bull"
lastDivBar := curLowB
if regBear
lastDiv := "Regular Bear"
lastDivBar := curHighB
if hidBear
lastDiv := "Hidden Bear"
lastDivBar := curHighB
var table dash = table.new(dashPos, 2, 10, bgcolor=color.new(color.gray, 85), frame_color=color.new(color.gray, 50), frame_width=1, border_color=color.new(color.gray, 70), border_width=1)
zoneTxt = k >= obInner ? "Overbought" : k <= -obInner ? "Oversold" : "Neutral"
zoneCol = k >= obInner ? bearStart : k <= -obInner ? bullStart : color.gray
divAge = na(lastDivBar) ? "" : " (" + str.tostring(bar_index - lastDivBar) + " bars ago)"
sigAge = na(lastSigBar) ? "" : " (" + str.tostring(bar_index - lastSigBar) + " bars ago)"
sigCol = str.startswith(lastSig, "BUY") ? bullStart : str.startswith(lastSig, "SELL") ? bearStart : color.gray
htfTxt = not useHtf ? "Off" : not htfValid ? "n/a (HTF <= chart)" : htfBull ? "Bullish" : htfBear ? "Bearish" : "Neutral"
htfCol = not useHtf or not htfValid ? color.gray : htfBull ? bullStart : htfBear ? bearStart : color.gray
exhTxt = not showExh ? "Off" : exhLongCond ? "Long exhaustion" : exhShortCond ? "Short exhaustion" : "None"
exhCol = exhLongCond ? exhColorLong : exhShortCond ? exhColorShort : color.gray
erTxt = not showEarly ? "Off" : earlyBullCond ? "Bullish (early)" : earlyBearCond ? "Bearish (early)" : "None"
erCol = earlyBullCond ? erColorBull : earlyBearCond ? erColorBear : color.gray
if showDash and barstate.islast
table.cell(dash, 0, 0, "FishStoc", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_center)
table.merge_cells(dash, 0, 0, 1, 0)
table.cell(dash, 0, 1, "Fisher", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 1, str.tostring(k, "0.00") + (k >= d ? " Up" : " Down"), text_color=k >= d ? bullStart : bearStart, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 2, "Zone", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 2, zoneTxt, text_color=zoneCol, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 3, "Momentum", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 3, str.tostring(momentum, "0.000"), text_color=momentum >= 0 ? bullStart : bearStart, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 4, "Acceleration", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 4, accel >= 0 ? "Rising" : "Fading", text_color=accelColor, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 5, "Exhaustion", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 5, exhTxt, text_color=exhCol, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 6, "Early Reversal", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 6, erTxt, text_color=erCol, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 7, "HTF Bias", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 7, htfTxt, text_color=htfCol, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 8, "Last Signal", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 8, lastSig + sigAge, text_color=sigCol, text_size=size.small, text_halign=text.align_right)
table.cell(dash, 0, 9, "Last Divergence", text_color=chart.fg_color, text_size=size.small, text_halign=text.align_left)
table.cell(dash, 1, 9, lastDiv + divAge, text_color=chart.fg_color, text_size=size.small, text_halign=text.align_right)
// ============================================================================
// === ALERTS ===
// ============================================================================
alertcondition(regBull, title="Regular Bullish Divergence", message="FishStoc: {{ticker}} ({{interval}}) - Regular Bullish (R-Bull) divergence")
alertcondition(regBear, title="Regular Bearish Divergence", message="FishStoc: {{ticker}} ({{interval}}) - Regular Bearish (R-Bear) divergence")
alertcondition(hidBull, title="Hidden Bullish Divergence", message="FishStoc: {{ticker}} ({{interval}}) - Hidden Bullish (H-Bull) divergence")
alertcondition(hidBear, title="Hidden Bearish Divergence", message="FishStoc: {{ticker}} ({{interval}}) - Hidden Bearish (H-Bear) divergence")
alertcondition(buySig, title="BUY (Fisher crosses above Trigger)", message="FishStoc: {{ticker}} ({{interval}}) - BUY: Fisher crossed above Trigger")
alertcondition(sellSig, title="SELL (Fisher crosses below Trigger)", message="FishStoc: {{ticker}} ({{interval}}) - SELL: Fisher crossed below Trigger")
alertcondition(enterOB, title="Fisher Enters Overbought Zone", message="FishStoc: {{ticker}} ({{interval}}) - Fisher entered the overbought zone")
alertcondition(enterOS, title="Fisher Enters Oversold Zone", message="FishStoc: {{ticker}} ({{interval}}) - Fisher entered the oversold zone")
alertcondition(zeroUpSig, title="Fisher Crosses Above Zero", message="FishStoc: {{ticker}} ({{interval}}) - Fisher crossed above the zero line")
alertcondition(zeroDnSig, title="Fisher Crosses Below Zero", message="FishStoc: {{ticker}} ({{interval}}) - Fisher crossed below the zero line")
alertcondition(exhLongSig, title="Long Exhaustion (LX)", message="FishStoc: {{ticker}} ({{interval}}) - Long Exhaustion: upside momentum is fading at the extreme")
alertcondition(exhShortSig, title="Short Exhaustion (SX)", message="FishStoc: {{ticker}} ({{interval}}) - Short Exhaustion: downside momentum is fading at the extreme")
alertcondition(earlyBullSig, title="Early Bullish Reversal (ER)", message="FishStoc: {{ticker}} ({{interval}}) - Early Bullish Reversal detected, cross not confirmed yet")
alertcondition(earlyBearSig, title="Early Bearish Reversal (ER)", message="FishStoc: {{ticker}} ({{interval}}) - Early Bearish Reversal detected, cross not confirmed yet")
alertcondition(buyConf, title="BUY+ (cross after early signal)", message="FishStoc: {{ticker}} ({{interval}}) - BUY+: cross confirmed after an early reversal / short exhaustion")
alertcondition(sellConf, title="SELL+ (cross after early signal)", message="FishStoc: {{ticker}} ({{interval}}) - SELL+: cross confirmed after an early reversal / long exhaustion")