Stoch

mikey369 · study · 401 行 · 点赞 373 · TradingView 原页

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

Pine Script

//@version=6
indicator(title = 'Stoch', max_lines_count = 500, max_labels_count = 500)
 
//===================================================================
//=== Divergence - Pivot Settings (Mode + Lookbacks) ===
//===================================================================
detectionMode = input.string('Live', title = 'Divergence Detection Mode', options = ['Live', 'Confirmed'], group = 'Divergence - Pivots', tooltip = 'Live: detects divergence as price moves (fast but less stable)\nConfirmed: waits for pivot validation (slower but more reliable)')
lbL = input.int(5, title = 'Pivot Left Lookback', group = 'Divergence - Pivots')
lbR = input.int(5, title = 'Pivot Right Lookback (Confirmed mode only)', group = 'Divergence - Pivots')
liveLbR = input.int(1, title = 'Live Right Lookback', minval = 1, maxval = 10, group = 'Divergence - Pivots', tooltip = 'How many bars must confirm a turn before Live mode marks it as a pivot. Higher = cleaner lines but slower; Lower = faster but noisier.')
pivotDepth = input.int(6, title = 'Pivots to Look Back', minval = 1, maxval = 8, group = 'Divergence - Pivots', tooltip = 'How many prior pivots a new pivot can connect back to. Only the farthest structurally and price-valid pivot is used, which keeps lines on the outside of the pattern instead of cutting through intermediate pivots. Live mode forms pivots more often than Confirmed mode, so it may need a higher value here to reach the same meaningful swing points.')
rangeUpper = input.int(60, title = 'Max of Lookback Range', group = 'Divergence - Pivots')
rangeLower = input.int(5, title = 'Min of Lookback Range', group = 'Divergence - Pivots')
delOldDiv = input.bool(true, title = 'Delete Superseded Divergence Lines', group = 'Divergence - Pivots', tooltip = 'When a new divergence line reaches back to the same or an earlier pivot than an existing one, the older, now-redundant line is removed.')
onlyTrending = input.bool(false, title = 'Only Trending Divergences', group = 'Divergence - Pivots', tooltip = 'Only draws bullish divergences while price is above its 200 EMA, and bearish divergences while price is below it.')
priceTolerancePct = input.float(0.05, title = 'Price Wick Tolerance (%)', minval = 0, maxval = 5, step = 0.05, group = 'Divergence - Pivots', tooltip = 'Every divergence line, whether or not Show on Chart is enabled, must also form a valid line on price. A candle wick crossing that line is always ignored. A candle close crossing it invalidates the pivot unless the close is within this percentage of the line, which allows a small buffer for near-misses. A pivot that fails this check is skipped in favor of a nearer one that passes.')
 
//===================================================================
//=== Divergence - Regular (Bullish + Bearish share these settings) ===
//===================================================================
showReg = input.bool(true, title = 'Show', group = 'Divergence - Regular')
showRegChart = input.bool(true, title = 'Show on Chart', group = 'Divergence - Regular')
regColor = input.color(color.new(#00ffdd, 0), title = 'Color', group = 'Divergence - Regular')
regStyleStr = input.string('Solid', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Divergence - Regular')
regWidth = input.int(1, title = 'Line Width', minval = 1, maxval = 5, group = 'Divergence - Regular')
 
//===================================================================
//=== Divergence - Hidden (Bullish + Bearish share these settings) ===
//===================================================================
showHid = input.bool(true, title = 'Show', group = 'Divergence - Hidden')
showHidChart = input.bool(false, title = 'Show on Chart', group = 'Divergence - Hidden')
hidColor = input.color(color.new(#00ffdd, 0), title = 'Color', group = 'Divergence - Hidden')
hidStyleStr = input.string('Dotted', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Divergence - Hidden')
hidWidth = input.int(1, title = 'Line Width', minval = 1, maxval = 5, group = 'Divergence - Hidden')
 
//===================================================================
//=== Overbought/Oversold ===
//===================================================================
showOB = input.bool(true, title = 'Show', group = 'Overbought')
valOB = input.float(60, title = 'Value', group = 'Overbought')
colorOB = input.color(color.new(#2e2e2e, 0), title = 'Color', group = 'Overbought')
 
showOS = input.bool(true, title = 'Show', group = 'Oversold')
valOS = input.float(-60, title = 'Value', group = 'Oversold')
colorOS = input.color(color.new(#2e2e2e, 0), title = 'Color', group = 'Oversold')
 
//===================================================================
//=== Custom Lines ===
//===================================================================
lineStyle(str) =>
    str == 'Dashed' ? line.style_dashed : str == 'Dotted' ? line.style_dotted : line.style_solid
 
showCustom1 = input.bool(false, title = 'Show', group = 'Custom Line 1')
valCustom1 = input.float(40, title = 'Value', group = 'Custom Line 1')
colorCustom1 = input.color(color.new(#ffffff, 75), title = 'Color', group = 'Custom Line 1')
styleCustom1Str = input.string('Dotted', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Custom Line 1')
widthCustom1 = input.int(1, title = 'Width', minval = 1, maxval = 5, group = 'Custom Line 1')
 
showCustom2 = input.bool(false, title = 'Show', group = 'Custom Line 2')
valCustom2 = input.float(-40, title = 'Value', group = 'Custom Line 2')
colorCustom2 = input.color(color.new(#ffffff, 75), title = 'Color', group = 'Custom Line 2')
styleCustom2Str = input.string('Dotted', title = 'Line Style', options = ['Solid', 'Dashed', 'Dotted'], group = 'Custom Line 2')
widthCustom2 = input.int(1, title = 'Width', minval = 1, maxval = 5, group = 'Custom Line 2')
 
//===================================================================
//=== Display ===
//===================================================================
showLevelLabels = input.bool(false, title = 'Show Level Line Price Labels', group = 'Display', tooltip = 'Shows/hides the price-scale labels for Overbought, Oversold, Custom Line 1, Custom Line 2, and the Zero line. Oscillator and signal labels always stay visible.')
labelDisp = showLevelLabels ? display.all : display.pane
 
//===================================================================
//=== Fill (the shaded area between K and D, drawn behind both lines) ===
//===================================================================
fillColor1 = input.color(color.new(#00ffdd, 71), title = 'Color 1', group = 'Fill')
fillColor2 = input.color(color.new(#9c9c9c, 84), title = 'Color 2', group = 'Fill')
 
//===================================================================
//=== Stochastic ===
//===================================================================
periodK = input.int(14, title = '%K Length', minval = 1, group = 'Stochastic')
smoothK = input.int(4, title = '%K Smoothing', minval = 1, group = 'Stochastic')
periodD = input.int(3, title = '%D Smoothing', minval = 1, group = 'Stochastic')
kColor = input.color(color.new(#00ffdd, 0), title = 'K Color', group = 'Stochastic')
dColor = input.color(color.new(#ffffff, 0), title = 'D Color', group = 'Stochastic')
 
//===================================================================
//=== Money Flow ===
//===================================================================
mfBullColor = input.color(color.new(#4a4a4a, 31), title = 'Bullish Color', group = 'Money Flow')
mfBearColor = input.color(color.new(#4a4a4a, 31), title = 'Bearish Color', group = 'Money Flow')
zeroLineColor = input.color(color.new(#4a4a4a, 31), title = 'Zero Line Color', group = 'Money Flow')
 
//===================================================================
//=== Signals ===
//===================================================================
showCrossSignal = input.bool(true, title = 'Show', group = 'Signals')
crossZone = input.float(50, title = 'Crossing Zone Threshold', minval = 10, maxval = 75, step = 5, group = 'Signals', tooltip = 'Crossing Up only fires when K and D are both below -Threshold (oversold). Crossing Down only fires when both are above +Threshold (overbought).')
crossUpColor = input.color(color.new(#00ffbb, 0), title = 'Crossing Up Color', group = 'Signals')
crossDownColor = input.color(color.new(#00ffbb, 0), title = 'Crossing Down Color', group = 'Signals')
 
//===================================================================
//=== Divergence Signals (crossings that follow shortly after a divergence) ===
//===================================================================
showDivSignal = input.bool(true, title = 'Show', group = 'Divergence Signals')
divSignalZone = input.float(30, title = 'Crossing Zone Threshold', minval = 10, maxval = 75, step = 5, group = 'Divergence Signals', tooltip = 'Independent of the regular Signals threshold. A cross-up must clear -Threshold (both K and D) following a bullish divergence; a cross-down must clear +Threshold following a bearish divergence.')
divSignalBars = input.int(3, title = 'Bars After Divergence', minval = 1, maxval = 20, group = 'Divergence Signals', tooltip = 'How many bars after a divergence line is drawn the follow-up crossing signal is allowed to fire.')
divUpColor = input.color(color.new(#b2ebf2, 0), title = 'Crossing Up Color', group = 'Divergence Signals')
divDownColor = input.color(color.new(#b2ebf2, 0), title = 'Crossing Down Color', group = 'Divergence Signals')
 
//===================================================================
//=== Overbought/Oversold drawing ===
//===================================================================
plot(showOB ? valOB : na, title = 'overbought', color = colorOB, style = plot.style_line, linewidth = 2, display = labelDisp)
plot(showOS ? valOS : na, title = 'oversold', color = colorOS, style = plot.style_line, linewidth = 2, display = labelDisp)
//
//===================================================================
//=== Custom Lines drawing (dotted/dashed line + a near-invisible plot overlay to host the price-scale label) ===
//===================================================================
var line custom1Line = na
var line custom2Line = na
if not na(custom1Line)
    line.delete(custom1Line)
if not na(custom2Line)
    line.delete(custom2Line)
if showCustom1
    custom1Line := line.new(bar_index - 1, valCustom1, bar_index, valCustom1, xloc = xloc.bar_index, extend = extend.both, color = colorCustom1, style = lineStyle(styleCustom1Str), width = widthCustom1)
if showCustom2
    custom2Line := line.new(bar_index - 1, valCustom2, bar_index, valCustom2, xloc = xloc.bar_index, extend = extend.both, color = colorCustom2, style = lineStyle(styleCustom2Str), width = widthCustom2)
 
plot(showCustom1 ? valCustom1 : na, title = 'Custom Line 1 Label', color = color.new(colorCustom1, 90), linewidth = 1, trackprice = true, display = showLevelLabels ? display.all : display.none)
plot(showCustom2 ? valCustom2 : na, title = 'Custom Line 2 Label', color = color.new(colorCustom2, 90), linewidth = 1, trackprice = true, display = showLevelLabels ? display.all : display.none)
//
//===================================================================
//=== Money Flow ===
//===================================================================
m = ta.sma(hlc3, 5)
f = ta.sma(math.abs(hlc3 - m), 5)
i = (hlc3 - m) / (0.015 * f)
mf = ta.sma(i, 60)
 
mfColor = mf > 0 ? mfBullColor : mfBearColor
zeroLine = plot(0, title = 'zero', color = zeroLineColor, linewidth = 1, display = labelDisp, trackprice = true)
mfLine = plot(mf, title = 'mfi', color = mfColor, linewidth = 1)
fill(mfLine, zeroLine, mf, 0, mfColor, color.new(mfColor, 100), title = 'Money Flow Fade')
//
//===================================================================
//=== Stochastic K/D (fill drawn first via invisible anchors so it sits behind the lines) ===
//===================================================================
kRaw = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
dRaw = ta.sma(kRaw, periodD)
osc = (kRaw - 50) * 2.0
dOsc = (dRaw - 50) * 2.0
 
kAnchor = plot(osc, title = 'K Anchor', display = display.none)
dAnchor = plot(dOsc, title = 'D Anchor', display = display.none)
fill(kAnchor, dAnchor, color = kRaw > dRaw ? fillColor1 : fillColor2, title = 'Fill')
 
kLine = plot(osc, title = 'K', color = kColor, linewidth = 1)
dLine = plot(dOsc, title = 'D', color = dColor, linewidth = 1)
//
//===================================================================
//=== Divergence Logic ===
//===================================================================
divLineStyle(str) =>
    str == 'Dashed' ? line.style_dashed : str == 'Dotted' ? line.style_dotted : line.style_solid
 
regStyle = divLineStyle(regStyleStr)
hidStyle = divLineStyle(hidStyleStr)
 
trendEMA = ta.ema(close, 200)
 
type Pivot
    float price
    float ind
    int ndx
 
type DivRecord
    line ln
    line lnChart
    int ndx1
 
const int MAX_PIV = 8
 
var array<Pivot> lowPivots = array.new<Pivot>()
var array<Pivot> highPivots = array.new<Pivot>()
 
var array<DivRecord> regBullRecords = array.new<DivRecord>()
var array<DivRecord> hidBullRecords = array.new<DivRecord>()
var array<DivRecord> regBearRecords = array.new<DivRecord>()
var array<DivRecord> hidBearRecords = array.new<DivRecord>()
 
var int lastBullDivBar = na
var int lastBearDivBar = na
 
addPivot(arr, newP) =>
    array.unshift(arr, newP)
    if array.size(arr) > MAX_PIV
        array.pop(arr)
 
// Removes existing lines of this type whose anchor pivot is at or after the new
// line's anchor, since the new line already reaches back at least as far.
supersede(array<DivRecord> arr, int newNdx1) =>
    if array.size(arr) > 0
        for idx = array.size(arr) - 1 to 0
            rec = array.get(arr, idx)
            if rec.ndx1 < newNdx1
                break
            line.delete(rec.ln)
            if not na(rec.lnChart)
                line.delete(rec.lnChart)
            array.remove(arr, idx)
 
// Always applied when selecting a pivot to connect to, whether or not Show on
// Chart is enabled. Walks the candles between the two pivots and rejects the
// pivot if a candle's close breaches the projected price line beyond the
// tolerance. Wicks are ignored entirely.
checkPriceEnvelope(startBar, startPrice, endBar, endPrice, isLow) =>
    valid = true
    len = endBar - startBar
    if len > 1
        slope = (endPrice - startPrice) / len
        for offset = 1 to len - 1
            checkBar = startBar + offset
            barsAgo = bar_index - checkBar
            projected = startPrice + slope * offset
            c = close[barsAgo]
            if isLow and c < projected * (1 - priceTolerancePct / 100)
                valid := false
                break
            if not isLow and c > projected * (1 + priceTolerancePct / 100)
                valid := false
                break
    valid
 
effLbR = detectionMode == 'Live' ? liveLbR : lbR
 
plFound = not na(ta.pivotlow(osc, lbL, effLbR))
phFound = not na(ta.pivothigh(osc, lbL, effLbR))
 
bool regBullCond = false
bool hidBullCond = false
 
if plFound
    curLowOsc = osc[effLbR]
    curLowPrice = low[effLbR]
    curLowBar = bar_index[effLbR]
 
    int regDepth = na
    int hidDepth = na
 
    maxD = math.min(pivotDepth, array.size(lowPivots))
    if maxD > 0
        for d = maxD to 1
            far = array.get(lowPivots, d - 1)
            bars = curLowBar - far.ndx
            if bars >= rangeLower and bars <= rangeUpper
                structureOK = true
                belowInterm = true
                if d >= 2
                    for k = 0 to d - 2
                        interK = array.get(lowPivots, k)
                        if interK.ind <= far.ind
                            structureOK := false
                        if curLowOsc >= interK.ind
                            belowInterm := false
                if structureOK and belowInterm
                    if na(regDepth) and curLowOsc > far.ind and curLowPrice < far.price
                        if checkPriceEnvelope(far.ndx, far.price, curLowBar, curLowPrice, true)
                            regDepth := d
                    if na(hidDepth) and curLowOsc < far.ind and curLowPrice > far.price
                        if checkPriceEnvelope(far.ndx, far.price, curLowBar, curLowPrice, true)
                            hidDepth := d
 
    regBullCond := not na(regDepth) and (not onlyTrending or close > trendEMA)
    hidBullCond := not na(hidDepth) and (not onlyTrending or close > trendEMA)
 
    if regBullCond
        far1 = array.get(lowPivots, regDepth - 1)
        if showReg
            newLn = line.new(far1.ndx, far1.ind, curLowBar, curLowOsc, color = regColor, width = regWidth, style = regStyle)
            newLnChart = line(na)
            if showRegChart
                newLnChart := line.new(far1.ndx, far1.price, curLowBar, curLowPrice, color = regColor, width = regWidth, style = regStyle, force_overlay = true)
            if delOldDiv
                supersede(regBullRecords, far1.ndx)
            array.push(regBullRecords, DivRecord.new(newLn, newLnChart, far1.ndx))
 
    if hidBullCond
        far2 = array.get(lowPivots, hidDepth - 1)
        if showHid
            newLn2 = line.new(far2.ndx, far2.ind, curLowBar, curLowOsc, color = hidColor, width = hidWidth, style = hidStyle)
            newLnChart2 = line(na)
            if showHidChart
                newLnChart2 := line.new(far2.ndx, far2.price, curLowBar, curLowPrice, color = hidColor, width = hidWidth, style = hidStyle, force_overlay = true)
            if delOldDiv
                supersede(hidBullRecords, far2.ndx)
            array.push(hidBullRecords, DivRecord.new(newLn2, newLnChart2, far2.ndx))
 
    if regBullCond or hidBullCond
        lastBullDivBar := bar_index
 
    addPivot(lowPivots, Pivot.new(curLowPrice, curLowOsc, curLowBar))
 
bool regBearCond = false
bool hidBearCond = false
 
if phFound
    curHighOsc = osc[effLbR]
    curHighPrice = high[effLbR]
    curHighBar = bar_index[effLbR]
 
    int regDepthH = na
    int hidDepthH = na
 
    maxDH = math.min(pivotDepth, array.size(highPivots))
    if maxDH > 0
        for d = maxDH to 1
            farH = array.get(highPivots, d - 1)
            barsH = curHighBar - farH.ndx
            if barsH >= rangeLower and barsH <= rangeUpper
                structureOKH = true
                aboveInterm = true
                if d >= 2
                    for k = 0 to d - 2
                        interKH = array.get(highPivots, k)
                        if interKH.ind >= farH.ind
                            structureOKH := false
                        if curHighOsc <= interKH.ind
                            aboveInterm := false
                if structureOKH and aboveInterm
                    if na(regDepthH) and curHighOsc < farH.ind and curHighPrice > farH.price
                        if checkPriceEnvelope(farH.ndx, farH.price, curHighBar, curHighPrice, false)
                            regDepthH := d
                    if na(hidDepthH) and curHighOsc > farH.ind and curHighPrice < farH.price
                        if checkPriceEnvelope(farH.ndx, farH.price, curHighBar, curHighPrice, false)
                            hidDepthH := d
 
    regBearCond := not na(regDepthH) and (not onlyTrending or close < trendEMA)
    hidBearCond := not na(hidDepthH) and (not onlyTrending or close < trendEMA)
 
    if regBearCond
        far3 = array.get(highPivots, regDepthH - 1)
        if showReg
            newLn3 = line.new(far3.ndx, far3.ind, curHighBar, curHighOsc, color = regColor, width = regWidth, style = regStyle)
            newLnChart3 = line(na)
            if showRegChart
                newLnChart3 := line.new(far3.ndx, far3.price, curHighBar, curHighPrice, color = regColor, width = regWidth, style = regStyle, force_overlay = true)
            if delOldDiv
                supersede(regBearRecords, far3.ndx)
            array.push(regBearRecords, DivRecord.new(newLn3, newLnChart3, far3.ndx))
 
    if hidBearCond
        far4 = array.get(highPivots, hidDepthH - 1)
        if showHid
            newLn4 = line.new(far4.ndx, far4.ind, curHighBar, curHighOsc, color = hidColor, width = hidWidth, style = hidStyle)
            newLnChart4 = line(na)
            if showHidChart
                newLnChart4 := line.new(far4.ndx, far4.price, curHighBar, curHighPrice, color = hidColor, width = hidWidth, style = hidStyle, force_overlay = true)
            if delOldDiv
                supersede(hidBearRecords, far4.ndx)
            array.push(hidBearRecords, DivRecord.new(newLn4, newLnChart4, far4.ndx))
 
    if regBearCond or hidBearCond
        lastBearDivBar := bar_index
 
    addPivot(highPivots, Pivot.new(curHighPrice, curHighOsc, curHighBar))
 
alertRegBull = detectionMode == 'Live' ? (regBullCond and barstate.isconfirmed) : regBullCond
alertHidBull = detectionMode == 'Live' ? (hidBullCond and barstate.isconfirmed) : hidBullCond
alertRegBear = detectionMode == 'Live' ? (regBearCond and barstate.isconfirmed) : regBearCond
alertHidBear = detectionMode == 'Live' ? (hidBearCond and barstate.isconfirmed) : hidBearCond
//
//===================================================================
//=== Crossing Signals ===
//===================================================================
buy = ta.crossover(osc, dOsc) and osc < -crossZone and dOsc < -crossZone
sell = ta.crossunder(osc, dOsc) and osc > crossZone and dOsc > crossZone
 
divBuySignal = showDivSignal and ta.crossover(osc, dOsc) and osc < -divSignalZone and dOsc < -divSignalZone and not na(lastBullDivBar) and (bar_index - lastBullDivBar) <= divSignalBars
divSellSignal = showDivSignal and ta.crossunder(osc, dOsc) and osc > divSignalZone and dOsc > divSignalZone and not na(lastBearDivBar) and (bar_index - lastBearDivBar) <= divSignalBars
 
plot(showCrossSignal and buy and not divBuySignal ? dOsc : na, title = 'crossing up', color = crossUpColor, style = plot.style_circles, linewidth = 3)
plot(showCrossSignal and sell and not divSellSignal ? dOsc : na, title = 'crossing down', color = crossDownColor, style = plot.style_circles, linewidth = 3)
plot(divBuySignal ? dOsc : na, title = 'divergence buy signal', color = divUpColor, style = plot.style_circles, linewidth = 3)
plot(divSellSignal ? dOsc : na, title = 'divergence sell signal', color = divDownColor, style = plot.style_circles, linewidth = 3)
//
//===================================================================
//=== Alerts ===
//===================================================================
alertcondition(buy, title = 'Buy', message = 'Stoch: Buy signal (K/D cross up in oversold)')
alertcondition(sell, title = 'Sell', message = 'Stoch: Sell signal (K/D cross down in overbought)')
alertcondition(divBuySignal, title = 'Divergence Buy Signal', message = 'Stoch: Buy signal following a bullish divergence')
alertcondition(divSellSignal, title = 'Divergence Sell Signal', message = 'Stoch: Sell signal following a bearish divergence')
alertcondition(divBuySignal or divSellSignal, title = 'Any Divergence Signal', message = 'Stoch: Divergence signal detected')
alertcondition(alertRegBull, title = 'Regular Bullish Divergence', message = 'Stoch: Regular Bullish Divergence detected')
alertcondition(alertHidBull, title = 'Hidden Bullish Divergence', message = 'Stoch: Hidden Bullish Divergence detected')
alertcondition(alertRegBear, title = 'Regular Bearish Divergence', message = 'Stoch: Regular Bearish Divergence detected')
alertcondition(alertHidBear, title = 'Hidden Bearish Divergence', message = 'Stoch: Hidden Bearish Divergence detected')
alertcondition(alertRegBull or alertHidBull or alertRegBear or alertHidBear, title = 'Any Divergence', message = 'Stoch: Divergence detected')
alertcondition(ta.cross(mf, 0), title = 'Money Flow Zero Cross', message = 'Stoch: Money Flow crossed zero line')
//

← 返回列表