Trading Strategy

Stochastic Oscillator

A momentum indicator comparing a particular closing price of a security to a range of its prices over a certain period of time.

The Cycle Finder

Stochastics focus on the closing price relative to the high-low range over a set period. This "momentum of momentum" approach excels at finding local bottoms in an uptrend or local tops in a downtrend, especially when signals are confirmed by a 200 EMA baseline to ensure you stay on the right side of the macro cycle.

Momentum Type
4h Chart Timeframe
Beginner Complexity
Ranging Best Market

Signal Logic

Long Signal

Triggered when %K line crosses above %D line below 20 (Oversold), and price is above the 200 EMA trend filter.

Short Signal

Triggered when %K line crosses below %D line above 80 (Overbought), and price is below the 200 EMA trend filter.

Implementation

//@version=6
strategy("Stochastic Strategy", overlay=true, initial_capital=1000000, default_qty_type=strategy.cash, default_qty_value=1000000)

// ==========================================
// 🔹 INPUTS
// ==========================================

kLength = input.int(14, "K Length", minval=1)
kSmoothing = input.int(3, "K Smoothing", minval=1)
dSmoothing = input.int(3, "D Smoothing", minval=1)
overbought = input.int(80, "Overbought Level")
oversold = input.int(20, "Oversold Level")
emaFilterLen = input.int(200, "EMA Filter Length")

// --- Calculations ---
// Standard Stochastic Formula
stochK = ta.sma(ta.stoch(close, high, low, kLength), kSmoothing)
stochD = ta.sma(stochK, dSmoothing)
emaFilter = ta.ema(close, emaFilterLen)

// --- Signals ---
// Entry: Stoch Cross Up + Below Oversold + Price Above 200 EMA
longCondition = ta.crossover(stochK, stochD) and stochK < oversold and close > emaFilter

// Exit: Stoch Cross Down + Above Overbought
exitCondition = ta.crossunder(stochK, stochD) and stochK > overbought

// --- Execution ---
if (longCondition)
    strategy.entry("Long", strategy.long)

if (exitCondition)
    strategy.close("Long")

// --- Visuals ---
plot(emaFilter, color=color.new(color.gray, 50), title="Trend Filter (EMA 200)")

// Background highlights for signals
bgcolor(longCondition ? color.new(color.green, 90) : na)
bgcolor(exitCondition ? color.new(color.red, 90) : na)