Not-So-Average True Range (nsATR)Not-So-Average True Range (nsATR)
*By Sherlock_MacGyver*
---
Long Story Short
The nsATR is a complete overhaul of traditional ATR analysis. It was designed to solve the fundamental issues with standard ATR, such as lag, lack of contextual awareness, and equal treatment of all volatility events.
Key innovations include:
* A smarter ATR that reacts dynamically when price movement exceeds normal expectations.
* Envelope zones that distinguish between moderate and extreme volatility conditions.
* A long-term ATR baseline that adds historical context to current readings.
* A compression detection system that flags when the market is coiled and ready to break out.
This indicator is designed for traders who want to see volatility the way it actually behaves — contextually, asymmetrically, and with predictive power.
---
What Is This Thing?
Standard ATR (Average True Range) has limitations:
* It smooths too slowly (using Wilder's RMA), which delays detection of meaningful moves.
* It lacks context — no way to know if current volatility is high or low relative to history.
* It treats all volatility equally, regardless of scale or significance.
nsATR** was built from scratch to overcome these weaknesses by applying:
* Amplification of large True Range spikes.
* Visual envelope zones for detecting volatility regimes.
* A long-term context line to anchor current readings.
* Multi-factor compression analysis to anticipate breakouts.
---
Core Features
1. Breach Detection with Amplification
When True Range exceeds a user-defined threshold (e.g., ATR × 1.2), it is amplified using a power function to reflect nonlinear volatility. This amplified value is then smoothed and cascades into future ATR values, affecting the indicator beyond a single bar.
2. Direction Tagging
Volatility spikes are tagged as upward or downward based on basic price momentum (close vs previous close). This provides visual context for how volatility is behaving in real-time.
3. Envelope Zones
Two adaptive envelopes highlight the current volatility regime:
* Stage 1: Moderate volatility (default: ATR × 1.5)
* Stage 2: Extreme volatility (default: ATR × 2.0)
Breaching these zones signals meaningful expansion in volatility.
4. Long-Term Context Baseline
A 200-period simple moving average of the classic ATR establishes whether current readings are above or below long-term volatility expectations.
5. Multi-Signal Compression Detection
Flags potential breakout conditions when:
* ATR is below its long-term baseline
* Price Bollinger Bands are compressed
* RSI Bollinger Bands are also compressed
All three signals must align to plot a "Volatility Confluence Dot" — an early warning of potential expansion.
---
Chart Outputs
In the Indicator Pane:
* Breach Amplified ATR (Orange line)
* Classic ATR baseline (White line)
* Long-Term context baseline (Cyan line)
* Stage 1 and Stage 2 Envelopes (Purple and Yellow lines)
On the Price Chart:
* Triangles for breach direction (green/red)
* Diamonds for compression zones
* Optional background coloring for visual clarity
---
Alerts
Built-in alert conditions:
1. ATR breach detected
2. Stage 1 envelope breached
3. Stage 2 envelope breached
4. Compression zone detected
---
Customization
All components are modular. Traders can adjust:
* Display toggles for each visual layer
* Colors and line widths
* Breach threshold and amplification power
* Envelope sensitivity
* Compression sensitivity and lookback windows
Some options are disabled by default to reduce clutter but can be turned on for more aggressive signal detection.
---
Real-Time Behavior (Non-Repainting Clarification)
The indicator updates in real time on the current bar as new data comes in. This is expected behavior for live trading tools. Once a bar closes, values do not change. In other words, the indicator *does not repaint history* — but the current bar can update dynamically until it closes.
---
Use Cases
* Day traders: Use compression zones to anticipate volatility surges.
* Swing traders: Use envelope breaches for regime awareness.
* System developers: Replace standard ATR in your logic for better responsiveness.
* Risk managers: Use directional volatility signals to better model exposure.
---
About the Developer
Sherlock_MacGyver develops original trading systems that question default assumptions and solve real trader problems.
Göstergeler ve stratejiler
Daily S&P BreadthS&P breadth
measures stock percentages against their moving averages
5, 20, 50, 200
Grid TLong V1The “Grid TLong V1” strategy is based on the classic Grid strategy, but in the mode of buying and selling in favor of the trend and only on Long. This allows to take advantage of large uptrend movements to maximize profits in bull markets. For this reason, excessively sideways or bearish markets may not be very conducive to this strategy.
Like our Grid strategies in favor of the trend, you can enter and exit with the balance with controlled risk, as the distance between each grid functions as a natural and adaptable stop loss and take profit. What differentiates it from bidirectional strategies is that Short uses a minimum amount of follow-through, so that the percentage distance between the grids is maintained.
In this version of the script the entries and exits can be chosen at market or limit , and are based on the profit or loss of the current position, not on the percentage change in price.
The user may also notice that the strategy setup is risk-controlled, because it risks 5% on each trade, has a fairly standard commission and modest initial capital, all in order to protect the strategy user from unrealistic results.
As with all strategies, it is strongly recommended to optimize the parameters for the strategy to be effective for each asset and for each time frame.
改良版 TOP/END 検知(シンプル動作確認版)//@version=6
indicator("改良版 TOP/END 検知(シンプル動作確認版)", overlay = true, max_labels_count = 100)
// ──────────────────────────────────────────
// 1. 基本パラメータ(シンプル版)
// ──────────────────────────────────────────
// 基本設定
adxLen = input.int(14, "ADX期間", group="基本設定")
rsiLen = input.int(14, "RSI期間", group="基本設定")
// 天井検知設定
topAdxThreshold = input.int(25, "天井ADX閾値", group="天井検知")
topRsiThreshold = input.int(70, "天井RSI閾値", group="天井検知")
// 強い下落検知設定(精度重視版)
enableStrongDecline = input.bool(true, "強い下落検知", group="強い下落検知")
strongDeclineAdx = input.int(22, "強下落ADX閾値", minval=15, maxval=35, group="強い下落検知")
strongDeclineRsi = input.int(52, "強下落RSI閾値", minval=40, maxval=65, group="強い下落検知")
strongDeclineVolume = input.float(1.3, "強下落出来高倍率", minval=0.8, maxval=2.5, group="強い下落検知")
earlyDetection = input.bool(true, "初動検知モード", tooltip="ONで早期検知、OFFで確実性重視", group="強い下落検知")
minDeclineForSignal = input.float(1.0, "最小価格下落(%)", minval=0.5, maxval=3.0, group="強い下落検知")
// 底検知設定(精度重視版)
bottomRsiThreshold = input.int(32, "底RSI閾値", minval=20, maxval=45, group="底検知")
minDeclineRate = input.float(2.8, "最小下落率(%)", minval=1.5, maxval=8.0, group="底検知")
bounceThreshold = input.float(1.2, "反発検知(%)", minval=0.5, maxval=2.5, group="底検知")
rsiRecoveryStrength = input.int(3, "RSI回復強度", minval=1, maxval=5, group="底検知")
requireVolumeConfirmation = input.bool(true, "出来高確認必須", group="底検知")
// 精度向上設定(新機能)
enableQualityFilter = input.bool(true, "品質フィルタ", tooltip="低品質シグナルを除去", group="精度向上")
minSignalGap = input.int(8, "シグナル間隔(最小足数)", minval=3, maxval=20, group="精度向上")
trendFilter = input.bool(true, "トレンドフィルタ", tooltip="トレンドに逆らうシグナルを除去", group="精度向上")
strengthThreshold = input.float(1.5, "シグナル強度閾値", minval=1.0, maxval=3.0, group="精度向上")
// 調整用設定(精度重視)
sensitivity = input.string("標準", "全体感度", options= , group="調整設定")
confirmationMode = input.bool(true, "確認モード", tooltip="ONで誤検知減少、OFFで早期検知", group="調整設定")
strictMode = input.bool(false, "厳格モード", tooltip="最高精度、シグナル数減少", group="調整設定")
// 表示設定
showTopLabels = input.bool(true, "天井ラベル表示", group="表示設定")
showBottomLabels = input.bool(true, "底ラベル表示", group="表示設定")
showStrongDecline = input.bool(true, "強い下落表示", group="表示設定")
// デバッグ設定
debugMode = input.bool(false, "デバッグモード", group="デバッグ")
// ──────────────────────────────────────────
// 2. インジケータ計算(精度向上版)
// ──────────────────────────────────────────
// ★変数の初期化(エラー回避)
enableOptionStrategy = true
hedgeRatio = 0.3
expectedDeclineTarget = 5.0
optionHoldingPeriod = 14
showOptionSignals = true
// ★ノイズ除去関連変数の初期化(バランス調整)
noiseReductionLevel = "標準"
consecutiveDeclineRequired = 1
minTrendStrength = 1.5
requireSignificantMove = false
// 基本指標
= ta.dmi(14, adxLen)
rsi = ta.rsi(close, rsiLen)
vol_avg = ta.sma(volume, 20)
// 移動平均(精度向上用)
sma20 = ta.sma(close, 20)
sma50 = ta.sma(close, 50)
ema12 = ta.ema(close, 12)
ema26 = ta.ema(close, 26)
// 高値追跡(改良版)
var float lastHigh = na
var int lastHighBar = na
if high > nz(lastHigh, high)
lastHigh := high
lastHighBar := bar_index
// 市場環境判定(新機能)
trendUp = close > sma20 and sma20 > sma50 and ema12 > ema26
trendDown = close < sma20 and sma20 < sma50 and ema12 < ema26
sideways = not trendUp and not trendDown
// ボラティリティ測定
atr14 = ta.atr(14)
atr20 = ta.atr(20)
highVolatility = atr14 > atr20 * 1.3
lowVolatility = atr14 < atr20 * 0.7
// 価格位置判定
pricePosition = (close - ta.lowest(low, 20)) / (ta.highest(high, 20) - ta.lowest(low, 20))
nearHigh = pricePosition > 0.8
nearLow = pricePosition < 0.2
// ──────────────────────────────────────────
// 3. 精密な天井検知
// ──────────────────────────────────────────
// 感度調整(厳格モード対応)
sensitivityMultiplier = strictMode ? 1.3 : sensitivity == "高" ? 0.8 : sensitivity == "標準" ? 1.0 : 1.2
// 天井条件(精度重視)
basicTopCondition = adx >= topAdxThreshold * sensitivityMultiplier and dip >= topAdxThreshold * sensitivityMultiplier and rsi >= topRsiThreshold
// 価格確認(厳格化)
priceHigh = high >= ta.highest(high, 8) * 0.995
hasDeclined = close < close and close < close
significantDecline = (high - close) / high > 0.015
// 品質フィルタ(新機能)
qualityFilter = true
if enableQualityFilter
// RSIダイバージェンス確認
rsiDivergence = rsi < rsi and high >= high
// 出来高確認
volumeOk = na(volume) ? true : volume > vol_avg * 0.8
// トレンド確認
trendOk = not trendFilter or (trendUp or sideways)
qualityFilter := (rsiDivergence or significantDecline) and volumeOk and trendOk
// 最終天井シグナル(精度重視)
topCondition = basicTopCondition and priceHigh and hasDeclined and qualityFilter
topSignal = topCondition
// ──────────────────────────────────────────
// 4. 強い下落検知(ノイズ除去強化版)
// ──────────────────────────────────────────
// ノイズ除去レベルに応じた調整
noiseMultiplier = noiseReductionLevel == "弱" ? 0.8 : noiseReductionLevel == "標準" ? 1.0 : noiseReductionLevel == "強" ? 1.3 : 1.6
// シグナル強度計算(改良版)
calculateSignalStrength() =>
strength = 0.0
// ADX強度(より厳格)
if adx >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier
strength += (adx / 40.0) * 1.5
// DI-優勢度(より重要視)
if dim > dip and dim >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier * 0.9
strength += ((dim - dip) / 30.0) * 2.0
// RSI位置(より厳格)
if rsi < strongDeclineRsi * noiseMultiplier
strength += ((strongDeclineRsi - rsi) / 30.0) * 1.5
// 出来高強度(重要度向上)
if not na(volume) and volume > vol_avg * strongDeclineVolume * noiseMultiplier
strength += ((volume / vol_avg - 1.0) * 2.0)
// 価格下落強度(最重要)
priceDeclinePercent = (close - close) / close * 100
if priceDeclinePercent >= minDeclineForSignal * noiseMultiplier
strength += (priceDeclinePercent / 3.0) * 2.5
// 連続下落ボーナス
consecutiveDeclines = 0
for i = 0 to consecutiveDeclineRequired - 1
if close < close
consecutiveDeclines += 1
else
break
if consecutiveDeclines >= consecutiveDeclineRequired
strength += consecutiveDeclines * 0.8
// トレンド強度ボーナス
if dim > dip * 1.3 and adx > 20
strength += minTrendStrength * 0.5
strength
// 強い下落条件(大幅強化)
strongDeclineCondition = false
if enableStrongDecline
// 基本条件(厳格化)
adxCondition = adx >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier
dimCondition = dim >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier * 0.8 and dim > dip
rsiCondition = rsi < strongDeclineRsi * noiseMultiplier
volumeCondition = na(volume) ? false : volume > vol_avg * strongDeclineVolume * noiseMultiplier
// 価格下落確認(厳格化)
priceDeclinePercent = (close - close) / close * 100
priceDeclineCondition = priceDeclinePercent >= minDeclineForSignal * noiseMultiplier
// 連続下落確認
consecutiveDeclines = 0
for i = 0 to consecutiveDeclineRequired - 1
if close < close
consecutiveDeclines += 1
else
break
consecutiveCondition = consecutiveDeclines >= consecutiveDeclineRequired
// シグナル強度確認(厳格化)
signalStrength = calculateSignalStrength()
strengthCondition = signalStrength >= strengthThreshold * noiseMultiplier
// 重要な動きのみ検知
significantMoveCondition = true
if requireSignificantMove
// より大きな動きのみを重要とみなす
atrRatio = (high - low) / ta.atr(14)
priceImpact = priceDeclinePercent >= minDeclineForSignal * 1.5
volumeImpact = na(volume) ? false : volume > vol_avg * 1.8
significantMoveCondition := (atrRatio > 1.2) and (priceImpact or volumeImpact)
// トレンドフィルタ(厳格化)
trendCondition = not trendFilter or (trendDown or (dim > dip * 1.2 and adx > 18))
// すべての条件をAND結合(バランス調整)
if earlyDetection
// 早期検知:重要な下落を見逃さないよう条件緩和
basicCondition = (adxCondition or adx > 18) and dimCondition and rsiCondition
priceCondition = priceDeclineCondition or close < close * 0.995
consecutiveOk = consecutiveCondition or consecutiveDeclines >= 1 // 最低1足下落があればOK
strongDeclineCondition := basicCondition and (priceCondition or consecutiveOk) and strengthCondition and trendCondition
else
// 確実性重視:それでも少し緩和
basicCondition = adxCondition and dimCondition and rsiCondition and (volumeCondition or significantMoveCondition)
priceCondition = priceDeclineCondition and close < open
strongDeclineCondition := basicCondition and priceCondition and consecutiveCondition and strengthCondition and trendCondition
// 確認モード(バランス調整)
strongDeclineSignal = false
if confirmationMode
// 確認モード:2本での確認(3本から2本に緩和)
var int strongDeclineCount = 0
var float cumulativeStrength = 0.0
currentStrength = calculateSignalStrength()
if strongDeclineCondition
strongDeclineCount += 1
cumulativeStrength += currentStrength
else
strongDeclineCount := 0
cumulativeStrength := 0.0
// 確認の条件を緩和
confirmationThreshold = strictMode ? 2 : 1 // 厳格モードでも2本、通常は1本
highStrengthThreshold = strengthThreshold * 2.0
ultraHighStrengthThreshold = strengthThreshold * 3.0 // 4.0から3.0に緩和
strongDeclineSignal := (strongDeclineCount >= confirmationThreshold) or (strongDeclineCount >= 1 and currentStrength >= ultraHighStrengthThreshold)
else
// 通常モード:即座に反応
strongDeclineSignal := strongDeclineCondition
// ──────────────────────────────────────────
// 5. 底検知(精度重視版)
// ──────────────────────────────────────────
// 下落率計算(改良版)
declineFromHigh = nz(lastHigh) > 0 ? (nz(lastHigh) - low) / nz(lastHigh) * 100 : 0
// 時間経過チェック(高値からの経過時間)
barsFromHigh = nz(lastHighBar) > 0 ? bar_index - nz(lastHighBar) : 999
timeFilter = barsFromHigh >= 5 // 高値から最低5本経過
// 底検知条件(精度重視)
// 基本条件(厳格化)
basicBottomCondition = rsi <= bottomRsiThreshold * sensitivityMultiplier and declineFromHigh >= minDeclineRate and timeFilter
// 反発検知(改良版)
priceBounce = close > close * (1 + bounceThreshold/100)
strongBounce = close > low * (1 + bounceThreshold*1.5/100) and close > open * 1.005
// RSI回復検知(強度調整可能)
rsiRecoveryCondition = false
rsiRecoveryCount = 0
for i = 1 to rsiRecoveryStrength
if rsi > rsi
rsiRecoveryCount += 1
rsiRecoveryCondition := rsiRecoveryCount >= math.ceil(rsiRecoveryStrength * 0.6)
// 出来高分析(精度向上)
volumeAnalysis = true
if requireVolumeConfirmation
// 出来高枯渇確認
volumeDrying = na(volume) ? true : volume < vol_avg * 0.6
// 反発時の出来高増加
volumeIncrease = na(volume) ? true : volume > vol_avg * 1.1
volumeAnalysis := volumeDrying or (priceBounce and volumeIncrease)
// 価格安定確認(改良版)
priceStabilizing = math.abs(close - close ) / close < 0.015
lowTesting = low <= ta.lowest(low, 5) * 1.002 // 安値テスト
// ADX収束確認(トレンド終了の兆候)
adxDeclining = adx < adx and adx < adx
// 最終底シグナル(複数パターン - 精度重視)
// パターン1: 標準的な底(厳格化)
standardBottomCondition = basicBottomCondition and (priceBounce or strongBounce) and rsiRecoveryCondition and volumeAnalysis
standardBottom = standardBottomCondition
// パターン2: 強い反発底(条件追加)
strongBottomCondition = rsi <= bottomRsiThreshold * sensitivityMultiplier + 8 and strongBounce and rsiRecoveryCondition and volumeAnalysis and adxDeclining
strongBottom = strongBottomCondition
// パターン3: 大底パターン(精密化)
dryingBottomCondition = declineFromHigh >= minDeclineRate * 1.8 and volumeAnalysis and rsiRecoveryCondition and (priceStabilizing or lowTesting) and barsFromHigh >= 10
dryingBottom = dryingBottomCondition
// 品質フィルタ(底用)
bottomQualityFilter = true
if enableQualityFilter
// 位置確認(安値圏であること)
positionOk = nearLow or pricePosition < 0.3
// RSI売られすぎ確認
rsiOversoldOk = rsi <= 45
// トレンド確認
trendOk = not trendFilter or (trendDown or sideways or not trendUp)
bottomQualityFilter := positionOk and rsiOversoldOk and trendOk
// 最終判定(品質フィルタ適用)
bottomSignal = (standardBottom or strongBottom or dryingBottom) and bottomQualityFilter
// ──────────────────────────────────────────
// 6. シグナル管理(ノイズ除去強化版)
// ──────────────────────────────────────────
var int lastTopBar = na
var int lastBottomBar = na
var int lastStrongDeclineBar = na
// 動的間隔調整(ノイズ除去強化)
baseDynamicGap = minSignalGap * noiseMultiplier // ノイズレベルに応じて間隔調整
dynamicGap = baseDynamicGap
if highVolatility
dynamicGap := math.min(baseDynamicGap, math.max(baseDynamicGap - 3, 8)) // 高ボラでも最小8足は確保
else if lowVolatility
dynamicGap := baseDynamicGap + 5 // 低ボラ時は更に間隔延長
// 厳格な間隔チェック
topAllowed = na(lastTopBar) or bar_index - lastTopBar >= dynamicGap + 5
bottomAllowed = na(lastBottomBar) or bar_index - lastBottomBar >= dynamicGap + 2
strongDeclineAllowed = na(lastStrongDeclineBar) or bar_index - lastStrongDeclineBar >= math.max(dynamicGap, 10)
// 基本シグナル(競合チェック前)
basicFinalTopSignal = topSignal and topAllowed
basicFinalStrongDeclineSignal = strongDeclineSignal and strongDeclineAllowed
basicFinalBottomSignal = bottomSignal and bottomAllowed
// 競合シグナル排除(強化版)
// 天井と強い下落の適切な間隔確保
topConflict = basicFinalStrongDeclineSignal and not na(lastStrongDeclineBar) and bar_index - lastStrongDeclineBar <= 5
strongDeclineConflict = basicFinalTopSignal and not na(lastTopBar) and bar_index - lastTopBar <= 5
// 最終シグナル(競合排除 + 品質確認)
finalTopSignal = basicFinalTopSignal and not topConflict
finalStrongDeclineSignal = basicFinalStrongDeclineSignal and not strongDeclineConflict
finalBottomSignal = basicFinalBottomSignal
// 厳格モードでの追加フィルタ(大幅強化)
if strictMode
// 厳格モード:更に厳しい条件
topStrengthOk = adx >= topAdxThreshold * 1.3 and rsi >= topRsiThreshold + 8
declineStrengthOk = calculateSignalStrength() >= strengthThreshold * 1.5
bottomStrengthOk = declineFromHigh >= minDeclineRate * 1.3 and rsi <= bottomRsiThreshold - 5
finalTopSignal := finalTopSignal and topStrengthOk
finalStrongDeclineSignal := finalStrongDeclineSignal and declineStrengthOk
finalBottomSignal := finalBottomSignal and bottomStrengthOk
// 最終品質チェック(ノイズ除去の最後の砦)
if requireSignificantMove and finalStrongDeclineSignal
// 本当に重要な動きかをチェック
recentVolatility = ta.stdev(ta.change(close), 10)
currentMove = math.abs(ta.change(close))
isSignificant = currentMove > recentVolatility * 1.5
finalStrongDeclineSignal := finalStrongDeclineSignal and isSignificant
// バー番号更新
if finalTopSignal
lastTopBar := bar_index
if finalBottomSignal
lastBottomBar := bar_index
if finalStrongDeclineSignal
lastStrongDeclineBar := bar_index
// ──────────────────────────────────────────
// 7. ラベル表示(改良版)
// ──────────────────────────────────────────
labelOffset = ta.atr(14) * 1.5
// 天井ラベル
if showTopLabels and finalTopSignal
label.new(bar_index, high + labelOffset, "TOP", style=label.style_label_down, color=color.red, textcolor=color.white, size=size.normal)
// 強い下落ラベル(詳細情報付き)
if showStrongDecline and finalStrongDeclineSignal
// ラベルテキストを状況に応じて変更
labelText = earlyDetection ? "初動" : "強下落"
labelColor = earlyDetection ? color.orange : color.maroon
// 確認モードの場合は追加情報
if confirmationMode
labelText := labelText + "確認"
label.new(bar_index, high + labelOffset * 0.7, labelText, style=label.style_label_down, color=labelColor, textcolor=color.white, size=size.normal)
// 底ラベル(パターン別表示)
if showBottomLabels and finalBottomSignal
// 底のパターンを判定してラベル変更
endLabelText = "END"
endLabelColor = color.green
if strongBottom
endLabelText := "強反発"
endLabelColor := color.lime
else if dryingBottom
endLabelText := "大底"
endLabelColor := color.purple
label.new(bar_index, low - labelOffset, endLabelText, style=label.style_label_up, color=endLabelColor, textcolor=color.white, size=size.normal)
// ──────────────────────────────────────────
// 8. デバッグ表示(改良版)
// ──────────────────────────────────────────
// デバッグ条件を事前定義
showTopCondition = debugMode and basicTopCondition
showStrongDeclineCondition = debugMode and strongDeclineCondition
showBasicBottomCondition = debugMode and basicBottomCondition
// 強度とフィルタ状況
showStrengthOk = debugMode and calculateSignalStrength() >= strengthThreshold
showStrengthValue = debugMode and calculateSignalStrength() > 0
// 主要デバッグ情報
plotchar(showTopCondition, "TopCondition", "T", location.top, color.yellow)
plotchar(showStrongDeclineCondition, "StrongDecline", "D", location.top, color.red)
plotchar(showBasicBottomCondition, "BasicBottom", "B", location.bottom, color.blue)
// 強度マーカー(重要)- 説明付き
plotchar(showStrengthOk, "StrengthOk", "!", location.top, color.orange) // シグナル強度が閾値以上
// 最終シグナル確認マーカー(最重要)
plotchar(debugMode and finalStrongDeclineSignal, "FinalDecline", "F", location.abovebar, color.red) // 最終的にシグナル発生
plotchar(debugMode and finalBottomSignal, "FinalBottom", "E", location.belowbar, color.green)
// ★フィルタリング状況の詳細表示(新機能)
showFilterBlocked = debugMode and strongDeclineCondition and not finalStrongDeclineSignal
plotchar(showFilterBlocked, "FilterBlocked", "X", location.top, color.gray) // 条件は満たすがフィルタで除去
// ★各条件の個別チェック(新機能)
showAdxOk = debugMode and adx >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier
showDimOk = debugMode and dim >= strongDeclineAdx * sensitivityMultiplier * noiseMultiplier * 0.8 and dim > dip
showRsiOk = debugMode and rsi < strongDeclineRsi * noiseMultiplier
showVolumeOk = debugMode and (na(volume) ? false : volume > vol_avg * strongDeclineVolume * noiseMultiplier)
plotchar(showAdxOk, "ADX_OK", "A", location.bottom, color.blue)
plotchar(showDimOk, "DIM_OK", "M", location.bottom, color.orange)
plotchar(showRsiOk, "RSI_OK", "R", location.bottom, color.purple)
plotchar(showVolumeOk, "VOL_OK", "V", location.bottom, color.teal)
// 背景色でトレンド表示(簡素化)
trendBg = debugMode ? (trendUp ? color.new(color.green, 97) : trendDown ? color.new(color.red, 97) : na) : na
bgcolor(trendBg, title="トレンド")
// ──────────────────────────────────────────
// 9. アラート(ノイズ除去強化版)
// ──────────────────────────────────────────
if finalTopSignal
// 天井の品質情報を含む
qualityInfo = enableQualityFilter ? " (品質フィルタ適用)" : ""
strengthInfo = strictMode ? " " : ""
alertMsg = "🔴 精密天井検知" + strengthInfo + qualityInfo + ": ADX=" + str.tostring(adx, "#.#") + " RSI=" + str.tostring(rsi, "#.#") + " DI+=" + str.tostring(dip, "#.#")
alert(alertMsg, alert.freq_once_per_bar)
if finalStrongDeclineSignal
// 基本アラート情報
alertType = earlyDetection ? "🟠 クラッシュ初動検知" : "🔻 強い下落"
confirmInfo = confirmationMode ? " (確認済み)" : ""
strengthValue = calculateSignalStrength()
strengthInfo = strictMode ? " 強度:" + str.tostring(strengthValue, "#.##") : ""
baseAlert = alertType + strengthInfo + confirmInfo + ": ADX=" + str.tostring(adx, "#.#") + " DI-=" + str.tostring(dim, "#.#") + " RSI=" + str.tostring(rsi, "#.#")
// ★オプション戦略アラート(条件簡素化)
if showOptionSignals // enableOptionStrategyを削除
// シグナル強度に基づくリスク評価
signalStrength = calculateSignalStrength()
// リスクレベル別推奨アクション(閾値緩和)
putAction = ""
riskLvl = "低"
if signalStrength >= strengthThreshold * 1.8
putAction := "【PUT積極推奨】"
riskLvl := "高"
else if signalStrength >= strengthThreshold * 1.3
putAction := "【PUT検討推奨】"
riskLvl := "中"
else if signalStrength >= strengthThreshold * 0.8
putAction := "【PUT軽量推奨】"
riskLvl := "低"
// ヘッジ戦略情報
hedgeInfo = " | ヘッジ比率:" + str.tostring(hedgeRatio * 100, "#") + "%"
profitTarget = " | 想定下落:" + str.tostring(expectedDeclineTarget, "#.#") + "%"
holdingPeriod = " | 推奨期間:" + str.tostring(optionHoldingPeriod) + "日"
optionAlert = putAction + hedgeInfo + profitTarget + holdingPeriod
// 統合アラート
fullAlert = baseAlert + " " + optionAlert
alert(fullAlert, alert.freq_once_per_bar)
else
alert(baseAlert, alert.freq_once_per_bar)
if finalBottomSignal
// 底のパターン別メッセージ
bottomType = "🟢 底検知"
if strongBottomCondition
bottomType := "🟢 強反発底"
else if dryingBottomCondition
bottomType := "🟣 大底"
qualityInfo = enableQualityFilter ? " (品質確認済み)" : ""
timeInfo = " 高値から" + str.tostring(barsFromHigh) + "本経過"
strengthInfo = strictMode ? " " : ""
baseBottomAlert = bottomType + strengthInfo + qualityInfo + timeInfo + ": RSI=" + str.tostring(rsi, "#.#") + " 下落率=" + str.tostring(declineFromHigh, "#.#") + "%"
// ★オプション利確アラート(条件簡素化)
if showOptionSignals and not na(lastStrongDeclineBar) // enableOptionStrategyを削除
barsFromDecline = bar_index - lastStrongDeclineBar
if barsFromDecline <= math.max(optionHoldingPeriod, 30) // 期間延長
actualDecline = declineFromHigh
profitRatio = actualDecline / expectedDeclineTarget * 100
optionExitInfo = ""
if actualDecline >= expectedDeclineTarget * 0.5 // 0.7から0.5に緩和
optionExitInfo := " 【PUT利確推奨】達成度:" + str.tostring(profitRatio, "#") + "% | 経過:" + str.tostring(barsFromDecline) + "日"
else if actualDecline >= expectedDeclineTarget * 0.3 // 30%達成でも表示
optionExitInfo := " 【PUT利確検討】達成度:" + str.tostring(profitRatio, "#") + "% | 経過:" + str.tostring(barsFromDecline) + "日"
if optionExitInfo != ""
fullBottomAlert = baseBottomAlert + optionExitInfo
alert(fullBottomAlert, alert.freq_once_per_bar)
else
alert(baseBottomAlert, alert.freq_once_per_bar)
else
alert(baseBottomAlert, alert.freq_once_per_bar)
else
alert(baseBottomAlert, alert.freq_once_per_bar)
Clean XRP/USDT Alert & MarkerClean XRP/USDT Alert & Marker is a precision trading tool designed for futures traders. It highlights high-probability entry zones using visual markers and real-time alerts for both short and long breakouts.
🔍 Features:
Visual markers for short entry and long breakout
Real-time alerts at key levels (configurable)
Ideal for 1H and 4H strategies
Clean layout optimized for fast decision-making
Built for leverage-based futures trading
Use this script to improve timing, reduce noise, and trade XRP/USDT with clearer setups and better risk management.
♒Hurst Cycle Channel Oscillator v4.0 by IRUNTV
Hurst Cycle Channel Oscillator v4.0 by IRUNTV W/ Advanced Divergence
Short Title: HCCO_v4_IRUNTV
📜 Script Description
//Disclaimer//
* What could be considered a clone of Hurst Cycle Channel Oscillator v1.0 by Cryptorhythms with arguably some improvements, since the original was locked i opted to creating my own version with much more flexibility in mind. I also used the original Hurst Cycle Channels by Lazybear as foundation for some of my primary logic and intentionally made it visually identical to the already popular Cryptorhythms version.
// End Disclaimer //
Unlock deeper market insights with the Hurst Cycle Channel Oscillator v4.0 by IRUNTV , a sophisticated oscillator meticulously designed to visualize cyclical price movements and pinpoint potential turning points through an advanced divergence detection engine. This indicator is rooted in the foundational principles of J.M. Hurst's cycle theory, offering a nuanced view of market dynamics by illustrating how current price interacts with dynamic, Hurst-style cycle channels.
At its core, the Hurst Cycle Channel Oscillator v4.0 transforms complex cycle analysis into an intuitive oscillator format. It aims to go beyond simple overbought or oversold conditions, highlighting the inherent rhythm of the market. This can empower you to anticipate shifts in momentum and identify higher-probability trading setups with greater confidence.
This v4.0 features a significantly enhanced divergence engine capable of identifying both Regular and Hidden bullish/bearish divergences with improved accuracy and extensive user customization.
📊 What It Displays & How It Works
Main Oscillator (-F - White Line): This is your primary plot. It represents the normalized position of the selected Source price (default: close) within a dynamically calculated medium-term Hurst-style channel.
Values typically range from 0 (price at channel bottom) to 1 (price at channel top).
Values above 1.0 suggest price has broken robustly above the medium-term channel (potentially overbought or indicating strong bullish momentum).
Values below 0.0 suggest price has broken robustly below the medium-term channel (potentially oversold or indicating strong bearish momentum).
Signal Line (H F - Yellow Line): This line represents the normalized position of the short-term cycle's median within the same medium-term Hurst-style channel. It acts as a dynamic signal line, providing context to the Main Oscillator's movements.
Secondary Oscillator (L F - Aqua Line): Offers a longer-term or smoothed perspective, by default an EMA of the H F Signal Line. Its calculation method and length are configurable.
Dynamic Channels (Internal Calculation): The oscillator values are derived from channels constructed using Running Moving Averages (RMA) of price and Average True Range (ATR) for dynamic width. These calculations incorporate Hurst's concepts of half-span cycle lengths and forward displacement, aiming for a more adaptive and responsive market analysis.
Key Visual Cues:
Divergence Markers (R / H): Clearly marked on the oscillator.
R ( Regular Divergence ): Signals potential trend exhaustion and upcoming reversals.
Bullish (Green R): Price forms Lower Lows (LL) while the Main Oscillator (-F) forms Higher Lows (HL).
Bearish (Red R): Price forms Higher Highs (HH) while the Main Oscillator (-F) forms Lower Highs (LH).
H ( Hidden Divergence ): Signals potential trend continuations, often appearing during corrections.
Bullish (Green H): Price forms Higher Lows (HL) while the Main Oscillator (-F) forms Lower Lows (LL).
Bearish (Red H): Price forms Lower Highs (LH) while the Main Oscillator (-F) forms Higher Highs (HH).
Divergence Lines: Lines are automatically drawn on the oscillator connecting the two pivot points that form a confirmed divergence, providing clear visual confirmation of the pattern. A configurable maximum number of lines are displayed to maintain chart clarity.
Background Shading: The oscillator pane's background is dynamically colored to offer an at-a-glance indication of prevailing market sentiment or conditions:
Green Zones: Typically indicate bullish conditions or oscillator strength (e.g., above the mid-level or signal line).
Red Zones: Typically indicate bearish conditions or oscillator weakness.
(The script includes logic for granular shading based on user-configurable overbought/oversold warning levels and the 0.5 mid-level).
Reference Levels: Horizontal lines are plotted at 0.0, 0.5, and 1.0, along with user-configurable "Warning Levels" (defaulting to 0.2 and 0.8) to help define critical zones of interest and potential price reactions.
💡 How to Use It - Potential Strategies
The Hurst Cycle Channel Oscillator v4.0 is a versatile tool. Here are some ways it can be incorporated into your trading analysis:
Divergence Trading (Primary Use):
Regular Divergences (R): Identify these as leading indicators that an existing trend might be losing momentum and could be approaching a reversal. Always seek confirmation from other technical analysis tools or price action.
Hidden Divergences (H): These often occur during pullbacks or consolidations within an established trend, potentially signaling an opportune moment to enter in the direction of the primary trend.
Oscillator / Signal Line Crosses:
When the Main Oscillator (-F) crosses above the Signal Line (H F): Potential bullish signal or strengthening momentum.
When the Main Oscillator (-F) crosses below the Signal Line (H F): Potential bearish signal or weakening momentum.
Overbought / Oversold (OB/OS) Conditions:
Extreme Levels: osc_F > 1.0 (extreme overbought) or osc_F < 0.0 (extreme oversold) can highlight unsustainable price extensions, often preceding periods of consolidation or potential reversals.
Warning Levels: Utilize the configurable levels (e.g., 0.8 and 0.2 by default) as earlier indications of potential overbought or oversold conditions, allowing for proactive adjustments.
Mid-Level (0.5) Dynamics:
osc_F crossing above 0.5 can suggest a shift towards a more bullish market bias.
osc_F crossing below 0.5 can suggest a shift towards a more bearish market bias. The 0.5 level often acts as a dynamic support/resistance within the oscillator's range.
Trend Confirmation & Strength: The color of the background shading can serve as a quick visual guide to the dominant short-term market sentiment as interpreted by the oscillator's position and behavior.
⚙️ Key Features & Customization (by IRUNTV)
Adjustable Cycle Parameters: Fully customize the Short Term Cycle Length, Medium Term Cycle Length, and their respective Multipliers to tailor the indicator's responsiveness to different assets, volatility, and timeframes.
Customizable Source: Select your preferred input source (close, hl2, hlc3, etc.) for the core calculations.
Comprehensive Plot Customization: Toggle the visibility and personalize the colors and line styles for all major plotted elements (oscillators, signal lines, divergence markers) through an intuitive "Plot Visibility & Style" settings group.
Advanced Divergence Engine Settings:
Div Pivot Left/Right Lookback: Fine-tune the sensitivity of pivot point detection for divergences.
Max Bars Between Div Pivots: Define the maximum historical window for identifying valid divergence formations.
Max Stored Pivots for Divs: Optimize performance by managing the memory used for storing historical pivot data, while still enabling detection of relevant long-term divergences.
Max Div Lines to Show: Maintain chart clarity by controlling the number of concurrently displayed divergence lines.
Built-in Alerts: Stay informed with comprehensive, configurable alerts for:
Main Oscillator / Signal Line crosses.
All four identified types of Divergences (Regular Bullish/Bearish, Hidden Bullish/Bearish).
Oscillator crossing into user-defined Overbought/Oversold warning levels.
Oscillator breaching the extreme 0.0 or 1.0 channel boundaries.
⚠️ Disclaimer
The "Hurst Cycle Channel Oscillator v4.0 by IRUNTV" is provided for educational and informational purposes only and does not constitute financial advice or a recommendation to buy or sell any asset. Trading and investing in financial markets involve substantial risk of loss. Past performance is not indicative of future results. All users should conduct their own thorough research, backtesting, and due diligence before making any trading or investment decisions. Use this tool responsibly and as part of a comprehensive trading strategy. IRUNTV assumes no liability for any trading or investment decisions made based on this indicator.
Fibonacci PivotsCreates Golden Zones based off the Pivots Standard with Daily Timeframe
-updated version with selectable TF
Previous Highs & Lows (Customizable)Previous Highs & Lows (Customizable)
This Pine Script indicator displays horizontal lines and labels for high, low, and midpoint levels across multiple timeframes. The indicator plots levels from the following periods:
Today's session high, low, and midpoint
Yesterday's high, low, and midpoint
Current week's high, low, and midpoint
Last week's high, low, and midpoint
Last month's high, low, and midpoint
Last quarter's high, low, and midpoint
Last year's high, low, and midpoint
Features
Individual Controls: Each timeframe has separate toggles for showing/hiding high/low levels and midpoint levels.
Custom Colors: Independent color selection for lines and labels for each timeframe group.
Display Options:
Adjustable line width (1-5 pixels)
Variable label text size (tiny, small, normal, large, huge)
Configurable label offset positioning
Organization: Settings are grouped by timeframe in a logical sequence from most recent (today) to least recent (last year).
Display Logic: Lines span the current trading day only. Labels are positioned to the right of the price action. The indicator automatically removes previous drawings to prevent chart clutter.
NSE/BSE Derivative - Next Expiry Date With HolidaysNSE & BSE Expiry Tracker with Holiday Adjustments
This Pine Script is a TradingView indicator that helps traders monitor upcoming expiry dates for major Indian derivative contracts. It dynamically adjusts these expiry dates based on weekends and holidays, and highlights any expiry that falls on the current day.
⸻
Key Features
1. Tracks Expiry Dates for Major Contracts
The script calculates and displays the next expiry dates for the following instruments:
• NIFTY (weekly expiry every Thursday)
• BANKNIFTY, FINNIFTY, MIDCPNIFTY, NIFTYNXT50 (monthly expiry on the last Thursday of the month)
• SENSEX (weekly expiry every Tuesday)
• BANKEX and SENSEX 50 (monthly expiry on the last Tuesday of the month)
• Stocks in the F&O segment (monthly expiry on the last Thursday)
2. Holiday Awareness
Users can input a list of holiday dates in the format YYYY-MM-DD,YYYY-MM-DD,.... If any calculated expiry falls on one of these holidays or a weekend, the script automatically adjusts the expiry to the previous working day (Monday to Friday).
3. Customization Options
The user can:
• Choose the position of the expiry table on the chart (e.g. top right, bottom left).
• Select the font size for the expiry table.
• Enable or disable the table entirely (if implemented as an input toggle).
4. Visual Expiry Highlighting
If today is an expiry day for any instrument, the script highlights that instrument in the display. This makes it easy to spot significant expiry days, which are often associated with increased volatility and trading volume.
⸻
How It Works
• The script calculates the next expiry for each index using built-in date/time functions.
• For weekly expiries, it finds the next occurrence of the designated weekday.
• For monthly expiries, it finds the last Thursday or Tuesday of the month.
• Each expiry date is passed through a check to adjust for holidays or weekends.
• If today matches the adjusted expiry date, that row is visually emphasized.
⸻
Use Case
This script is ideal for traders who want a quick glance at which instruments are expiring soon — especially those managing options, futures, or expiry-based strategies.
Session High/Low: Asia & LondonIndicator to automatically mark the lower low and the higher high of the Asian and London sessions.
Scalping EMA Crossover (EMA 9 / EMA 21 + EMA 200)scalping ema crossover u can change ema
ema 9
ema 21
ema 200
GV Reddy Strategy v2//@version=5
strategy("GV Reddy Strategy v2", overlay=true, default_qty_type=strategy.cash, default_qty_value=10000)
// === INPUTS ===
emaLength = input.int(200, title="EMA Length")
tp_points = input.int(100, title="Target (Points)")
sl_points = input.int(50, title="Stop Loss (Points)")
// === CALCULATIONS ===
ema = ta.ema(close, emaLength)
// Strong candles (body > 60% of total range)
bullCandle = close > open and (close - open) > (high - low) * 0.6
bearCandle = open > close and (open - close) > (high - low) * 0.6
// === ENTRY CONDITIONS ===
longCondition = bullCandle and close > ema
shortCondition = bearCandle and close < ema
// === ENTRY EXECUTION ===
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
// === EXIT EXECUTION ===
strategy.exit("TP/SL Long", from_entry="Long", profit=tp_points, loss=sl_points)
strategy.exit("TP/SL Short", from_entry="Short", profit=tp_points, loss=sl_points)
// === PLOTS ===
plot(ema, color=color.orange, linewidth=2, title="EMA 200")
EMA Hierarchy Alternating Alert MarkersThis script allows you to set EMA 5, 13 & 26 in a single indicator.
It allows you to set an alert when PCO or NCO happens where 5>13>26 (PCO) or 5<13<26 (NCO).
It has been designed in such a way that the alert will only be sounded on the first PCO or NCO.
Once a PCO has happened then the next PCO alert will only come after the NCO has happened.
This feature helps you to avoid getting multiple alerts specially if you are using a lower timeframe.
Scripts: Equities, F&O, Commodity, Crypto, Currency
Time Frame: All
By TrustingOwl83470
Support Resistance + Trendlines StrategyCheck out this YouTube video for a detailed tutorial on how to start this trading rally.
Смотрите на ютубе подробное видео как запустить эту торговую стратегию.
5-Minute Scalping Botkrozz indicator working on all time frames . take profit and stop lose on chart.
WT 4H + 1D Oscillator + Cross Dots + Alert TrianglesThis indicator will help on trigger buy and sell alerts when you get confluence signals in 1D Momentum above or below +-30 (adjustable) and 4H momentum waves crossing (meaning overbought / oversold). Excellent for catching early swing breakout trades.
Random State Machine Strategy📌 Random State Machine Strategy (Educational)
This strategy showcases a randomized entry model driven by a finite state machine, integrated with user-defined exit controls and a full-featured moving average filter.
🧠 Trade Entry Logic
Entries occur only when:
A random trigger occurs (~5% probability per bar)
The state machine accepts a new transition (sm.step())
Price is:
Above the selected MA for long entries
Below the selected MA for short entries
This ensures that entries are both stochastically driven and trend-aligned, avoiding frequent or arbitrary trades.
⚙️ How It Works
Randomized Triggers
A pseudo-random generator (seeded with time and volume) attempts to trigger state transitions.
Finite State Machine
Transitions are managed using the StateMachine from robbatt/lib_statemachine — credit to @robbatt for the modular FSM design.
Controlled Reset
The state machine resets every N bars (default: 100) if at least two transitions have occurred. This prevents stale or locked states.
Backtest Range
Define a specific test window using Start and End Date inputs.
Risk & Exits
Specify risk in points and a target risk/reward ratio. TP is auto-computed. Timed and MA-based exits can be toggled.
🧪 How to Use
Enable Long or Short trades
Choose your Moving Average type and length
Set Risk per trade and R/R ratio
Toggle TP/SL, timed exit, or MA cross exit
Adjust the State Reset Interval to suit your signal frequency
📘 Notes
Educational use only — not financial advice
Random logic is used to model structure, not predict movement
Thanks to @robbatt for the lib_statemachine integration
45 Second Futures Session Open RangeThis indicator plots the 45-second Opening Range Breakout (ORB) for futures, allowing users to select a specific trading session (Asia, Europe, or NY) to display on the chart. It visualizes the high, low, and midpoint of the opening range for the chosen session and includes dynamic price targets for breakout trading strategies.
Key Features:
Customizable Session Selection: Choose between Asia (17:00), Europe (2:00), or NY (8:30) sessions (Chicago time) to display only the relevant ORB levels.
45-Second Timeframe: Captures the high and low of the first 45 seconds of the selected session using request.security_lower_tf.
Visualized ORB Levels: Plots the high, low, and midpoint lines with session-specific colors:
Asia: Orange (high/low), Fuchsia (mid)
Europe: Olive (high/low), Lime (mid)
NY: Aqua (high/low), Yellow (mid)
Dynamic Price Targets: Draws breakout target lines above or below the ORB when price exceeds the range, with customizable percentage, color, style, and width.
Debug Labels: Displays warnings if the 45-second timeframe is unsupported or no valid ORB data is available for the selected session.
How It Works:
The indicator fetches 45-second high and low data at the start of the selected session (e.g., 8:30:00 for NY).
It plots the ORB high, low, and midpoint as step lines, with labels showing price values.
Price targets are drawn as horizontal lines when the price breaks above the ORB high or below the ORB low, based on a user-defined percentage of the ORB width.
Targets reset at the start of each new session.
Settings:
Select Session: Choose "Asia", "Europe", or "NY" to display the corresponding ORB.
Display Targets: Toggle price target lines on or off.
Target %: Set the percentage of the ORB width for target levels (default: 50%).
Target Color: Customize the color of target lines (default: silver).
Target Style: Select solid, dashed, dotted, or none for target line style.
Target Width: Adjust the thickness of target lines (default: 1).
Usage Tips:
Best for Futures: Optimized for futures contracts like ES (S&P 500 futures) that support lower timeframes.
Check Timeframe Support: The 45-second timeframe is non-standard. If no lines appear, a red debug label will indicate if the timeframe is unsupported. Consider using a premium TradingView plan or a supported symbol.
Timezone Alignment: Ensure your chart’s data aligns with Chicago time (America/Chicago) for accurate session timing (Asia: 17:00, Europe: 2:00, NY: 8:30).
Scaling: Adjust chart scaling if lines are off-screen due to large price ranges.
Notes:
Requires Pine Script v6 and a TradingView plan supporting lower timeframes for 45-second data.
If the 45-second timeframe is unsupported, contact the author for a fallback version (e.g., 1-minute ORB).
Licensed under Mozilla Public License 2.0.
Happy trading!
Media 10 y 20 con Señales de Compra y Ventaemas 10 20 50 100 200 con señal de cruce 10 y 20 cualquier temporalidad
CBC Flip with Volume [Pt]CBC Flip with Volume
A volume-enhanced take on the classic Candle-By-Candle (CBC) Flip strategy.
This tool highlights when market control flips between bulls and bears, using both candle structure and volume confirmation.
█ How It Works
• Bull Flip: Close > previous high, bullish candle, and volume > previous bar
• Bear Flip: Close < previous low, bearish candle, and volume > previous bar
• Strong flips occur when volume is also above its moving average
█ Features
• Visual flip markers (triangles) for both normal and strong flips
• Background color shading on flip candles
• Customizable volume MA length (default: 50)
• Real-time alerts when a flip occurs
█ Use Cases
• Confirm breakout strength with volume
• Filter out weak flips on low volume
• Spot early trend reversals with added confidence
Inspired by MapleStax’s original CBC method, enhanced with volume-based filtering.