Indicator · Pine Script v6 · Own pane

TradingFlow: Stoch X

by realanthonyc

TradingFlow: Stoch X is a Stochastic oscillator indicator plotted in a separate pane.

View on GitHub

GitHub stars3on the repository
Pine versionv6current
Lines of code126
Settings15inputs
LicenceMPL-2.0
Last update2 months ago9 Aug 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

126 lines of Pine Script v6 from stoch-x.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

stoch-x.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © realanthonyc https://www.tradingview.com/u/realanthonyc

//@version=6
// --------------------------------------------------------------------
//  TradingFlow: Stoch X
//  On Github: https://github.com/realanthonyc/Stoch-X
// --------------------------------------------------------------------
indicator(title="TradingFlow: Stoch X (SX) v1.2.1", shorttitle="TF: SX", format=format.price, precision=1, timeframe="", timeframe_gaps=true)

// === Inputs ===

// Colors
bearColor = color.new(color.red, 35)
bullColor = color.new(color.green, 35)
noneColor = color.new(color.white, 100)

// Settings
grpStoch = "Settings"
periodK = input.int(14, title="%K", minval=1, group=grpStoch)
smoothK = input.int(1, title="%K Smoothing", minval=1, group=grpStoch, tooltip = "To ensure optimal divergence detection, set it to 1.")
periodD = input.int(3, title="%D", minval=1, group=grpStoch)
valUpper  = input.int(80, title="Upper Band Value", group=grpStoch)
valLower  = input.int(20, title="Lower Band Value", group=grpStoch)

// Settings for Cross Signals
grpStochCross = "Settings for Cross Signals"
crossNote1 = "Cross signals occur when %K2 crosses %S outside the band."
crossNote2 = "Increase this value for smoother, slower signals; decrease it for higher sensitivity."
crossNote3 = "Less sensitive and more accurate signals for lower timeframes."
periodK2     = input.int(1, title="%K2", minval=1, group=grpStochCross, tooltip = crossNote1, display = display.data_window)
periodS      = input.int(5, title="%S", minval=1, group=grpStochCross, tooltip = crossNote2, display = display.data_window)
periodK2_Low = input.int(2, title="%K2 for 30m or Below", minval=1, group=grpStochCross, tooltip = crossNote3, display = display.data_window)
periodS_Low  = input.int(6, title="%S for 30m or Below", minval=1, group=grpStochCross, tooltip = crossNote3, display = display.data_window)
valCrossLevel = input.int(-10, title="Cross Signals Plot Level", group=grpStochCross, display = display.data_window)

// Divergence Settings
grpDiv = "Divergence Settings"
calculateDivergence = input.bool(true, title="Calculate Divergence", group=grpDiv, display = display.data_window, tooltip ="Based on %K")
lookbackLeft  = input.int(5, title="Pivot Lookback Left", group=grpDiv, display = display.data_window)
lookbackRight = input.int(3, title="Pivot Lookback Right", group=grpDiv, display = display.data_window)
rangeUpper    = input.int(60, title="Max Lookback Range", group=grpDiv, display = display.data_window)
rangeLower    = input.int(5, title="Min Lookback Range", group=grpDiv, display = display.data_window)

// === Stochastic Calculation ===
k = ta.sma(ta.stoch(close, high, low, periodK), smoothK)
d = ta.sma(k, periodD)

// Dynamic Period Logic
// 30 minutes = 1800 seconds
// Logic handles Ticks/Range/Volume (na seconds) by defaulting to Regular (false on isLowTF)
currentSeconds = timeframe.in_seconds(timeframe.period)
isLowTF = not na(currentSeconds) and currentSeconds <= 1800
periodS_Dynamic = isLowTF ? periodS_Low : periodS
periodK2_Dynamic = isLowTF ? periodK2_Low : periodK2
s  = ta.sma(k, periodS_Dynamic)
k2 = ta.sma(k, periodK2_Dynamic) 

// === Plotting: Stochastic Lines ===

plot(k,  title="%K",  color=#2962FF)
plot(k2, title="%K2", color=color.new(#9C27B0, 30), display=display.none)
plot(d,  title="%D",  color=#FF6D00)
plot(s,  title="%S",  color=color.new(#018383, 30), display=display.none)

// Dynamic Band
h0 = hline(valUpper, "Upper Band", color=color.new(#27c5ff, 50), linestyle=hline.style_dotted, editable=false)
hline(50, "Middle Band", color=color.new(#787B86, 50))
h1 = hline(valLower, "Lower Band", color=color.new(#27c5ff, 50), linestyle=hline.style_dotted, editable=false)
fill(h0, h1, color=color.rgb(33, 150, 243, 92), title="Background")

// === Plotting: Cross Signals ===

// Use %K2 and %S for crossing logic
bullCross = ta.crossover(k2, s) and k2 < valLower
bearCross = ta.crossunder(k2, s) and k2 > valUpper

// Uses valCrossLevel for vertical positioning
plotshape(bearCross ? valCrossLevel : na, title="Bearish Cross", style=shape.xcross, location=location.absolute, color=bearColor, size=size.tiny, display=display.none)
plotshape(bullCross ? valCrossLevel : na, title="Bullish Cross", style=shape.xcross, location=location.absolute, color=bullColor, size=size.tiny, display=display.none)

// === Plotting: Divergence ===

_inRange(bool cond) =>
    bars = ta.barssince(cond)
    rangeLower <= bars and bars <= rangeUpper
plFound = false
phFound = false
bullCond = false
bearCond = false

// Source for pivots remains K (Standard Divergence)
srcLBR = k[lookbackRight]

if calculateDivergence
    // Regular Bullish
    // Osc: Higher Low
    plFound := not na(ta.pivotlow(k, lookbackLeft, lookbackRight))    
    // Calculate range check separately to prevent short-circuiting of ta.barssince
    bool rangeConditionBull = _inRange(plFound[1])
    oscHL = srcLBR > ta.valuewhen(plFound, srcLBR, 1) and rangeConditionBull
    // Price: Lower Low
    lowLBR = low[lookbackRight]
    priceLL = lowLBR < ta.valuewhen(plFound, lowLBR, 1)
    bullCond := priceLL and oscHL and plFound
    // Regular Bearish
    // Osc: Lower High
    phFound := not na(ta.pivothigh(k, lookbackLeft, lookbackRight))
    // Calculate range check separately to prevent short-circuiting
    bool rangeConditionBear = _inRange(phFound[1])
    oscLH = srcLBR < ta.valuewhen(phFound, srcLBR, 1) and rangeConditionBear
    // Price: Higher High
    highLBR = high[lookbackRight]
    priceHH = highLBR > ta.valuewhen(phFound, highLBR, 1)
    bearCond := priceHH and oscLH and phFound

// Divergence Lines
plot(plFound ? srcLBR : na, offset = -lookbackRight, title = "Regular Bullish", linewidth = 1, color = (bullCond ? bullColor : noneColor), display = display.pane, editable = calculateDivergence)
plot(phFound ? srcLBR : na, offset = -lookbackRight, title = "Regular Bearish", linewidth = 1, color = (bearCond ? bearColor : noneColor), display = display.pane, editable = calculateDivergence)

// === Alerts ===

alertcondition(bullCond, title='Regular Bullish Divergence', message="Found a new Regular Bullish Divergence")
alertcondition(bearCond, title='Regular Bearish Divergence', message='Found a new Regular Bearish Divergence')
alertcondition(bullCross, title='Stoch Bullish Cross', message='Stoch Bullish Cross in Oversold Zone')
alertcondition(bearCross, title='Stoch Bearish Cross', message='Stoch Bearish Cross in Overbought Zone')

Overview

TradingFlow: Stoch X calculates standard percent K and percent D lines along with secondary crossover lines to generate trade signals outside overbought and oversold bands. The indicator automatically adapts signal smoothing parameters when viewed on timeframes of thirty minutes or below. It also detects bullish and bearish divergences between price and the percent K oscillator using customizable pivot lookback ranges.

Details

Published by

realanthonyc on GitHub

Draws

Separate pane below the chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

indicatorpinescripttradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
%Kint14periodK
%K Smoothingint1smoothK
%Dint3periodD
Upper Band Valueint80valUpper
Lower Band Valueint20valLower
%K2int1periodK2
%Sint5periodS
%K2 for 30m or Belowint2periodK2_Low
%S for 30m or Belowint6periodS_Low
Cross Signals Plot Levelint-10valCrossLevel
Calculate DivergencebooltruecalculateDivergence
Pivot Lookback Leftint5lookbackLeft
Show all 15 settings
SettingTypeDefaultVariable
Pivot Lookback Rightint3lookbackRight
Max Lookback Rangeint60rangeUpper
Min Lookback Rangeint5rangeLower
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
330 stars

This indicator calculates the MACD oscillator from a configurable source with fast and slow lengths, then plots the histogram, MACD line, and signal line in a separate pane. It detects regular bullish divergences (price lower lows with oscillator higher lows),

Indicator v5 Oscillators & momentumDivergence
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]
228 stars

This indicator calculates the Relative Strength Index (RSI) across four user-selected timeframes and plots the results in a separate pane. It identifies regular bullish and bearish divergences between price pivot points and the primary timeframe RSI value. Add

Indicator v6 Oscillators & momentumDivergence
Updated 3 months ago · None stated GitHub repository of Multi-Timeframe RSI with Divergence

Bubbles Indicator

by capissimo
114 stars

The Bubbles Indicator measures volatility squeezes and expansion bursts using Bollinger Bands combined with a sinusoid oscillator and RSI divergence. It processes price data through scaled Bollinger Bands to highlight volatility changes while confirming trend

Indicator v4 Volatility & bandsOscillators & momentum Repaints
Updated 1 year ago · None stated GitHub repository of Bubbles Indicator

RSI [SystemAlpha]

by iamc1oud
56 stars

This indicator plots a standard Relative Strength Index (RSI) in a separate pane alongside customizable overbought and oversold threshold levels with shaded fills. It identifies pivot highs and lows on the oscillator to detect regular and hidden bullish and be

Indicator v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of RSI [SystemAlpha]
55 stars

This indicator calculates a 14-period RSI from close and plots it in a separate pane with dotted overbought and dashed oversold lines at 70 and 30. It marks bullish divergence when a five-bar pivot low in price is lower than the price twenty bars earlier while

Indicator v6 Oscillators & momentumDivergence
Updated 6 months ago · Apache-2.0 GitHub repository of RSI Divergence Detector

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers