FOMC Sweep Reaction AP Capital – FOMC Sweep Reaction v1.0
AP Capital – FOMC Sweep Reaction v1.0 is a news-reaction and liquidity-based trading tool designed specifically to track and trade FOMC volatility on Gold (XAUUSD) and other highly reactive instruments.
The indicator focuses on liquidity sweeps, structure breaks, and EMA reclaims that commonly occur around Federal Reserve interest-rate decisions and Powell speeches, helping traders identify high-probability reversal or continuation moves after the initial spike.
🔍 What This Indicator Detects
This tool highlights the most repeatable FOMC behaviours observed across multiple months of broker data:
• Sweeps of previous day’s high or low
• Stop-hunt wicks into liquidity pools
• EMA13 reclaim after the news spike
• Break and close beyond short-term structure
• Momentum shift following volatility exhaustion
The goal is not to predict the news, but to react to confirmed price behaviour after liquidity has been taken.
📌 Core Features
• FOMC Sweep Detection
Identifies aggressive wicks into prior highs/lows during news volatility
• EMA Reclaim Confirmation
Uses EMA13 to validate momentum shift after the sweep
• Market Structure Awareness
Filters reactions that fail to break structure to avoid false reversals
• Session-Aligned Logic
Designed around London → NY → FOMC release timing
• Clean Visuals
Minimal chart clutter for fast decision-making during volatile conditions
🧠 How to Use
Wait for FOMC release / Powell speech
Allow price to sweep previous liquidity (PDH / PDL / local extremes)
Observe reclaim of EMA13
Enter only after structure confirmation
Manage trade using EMA trailing or structure-based exits
⚠️ This is a reaction system, not a prediction tool.
📊 Best Use Cases
• XAUUSD (Gold)
• NASDAQ / US indices
• High-impact macro news events
• 5-min to 15-min timeframes
⚠️ Important Notes
• News volatility is extreme — risk management is essential
• Not designed for low-volatility or ranging markets
• Best combined with a clear trading plan and strict risk rules
📎 Disclaimer
This indicator is for educational purposes only and does not constitute financial advice. Trading during high-impact news events involves significant risk.
指標和策略
Relative Strength IndexRSI for indian market buy low and sell high.
rsi 3 low belo 15 buy and rsi high above 85 sell
TTM Squeeze Candles (Custom Colors) with Dynamic Strength Bar V2Here is my tribute, tip of the cap to one of the greatest traders of our generation John F. Carter
It was my goal to try and simply visualize the squeeze with candle sticks, dynamic momentum, and signals all on one chart in one indicator. Please study and master the squeeze setup before trying to apply this indicator . You must have a deep understanding of how to trade the squeeze. Read "Mastering The Trade " watch JC's videos etc, and practice with a simulated or paper account before ever trying out new strategies with real money. Not financial advice, I am not a financial advisor! DYOR- with that said - I hope you like it :)
TTM squeeze candles **custom TradingView Pine Script (v6)** indicator that visualizes the **TTM Squeeze** strategy — a popular volatility-based momentum system originally developed by John Carter of TradeTheMarkets (TTM). This version enhances the classic TTM Squeeze with **custom candle coloring**, **dynamic momentum strength**, **visual alerts**, and a **real-time strength meter**.
---
## OVERVIEW: What is the TTM Squeeze?
The **TTM Squeeze** identifies periods when **volatility is contracting** (price is consolidating), followed by a **potential explosive breakout** when volatility expands.
It combines:
1. **Bollinger Bands (BB)** – measure statistical volatility
2. **Keltner Channels (KC)** – measure average true range (ATR) volatility
3. **Momentum Oscillator** – determines direction and strength of potential breakout
> **Squeeze ON** = BB inside KC → Low volatility (consolidation)
> **Squeeze OFF** = BB outside KC → Volatility expanding (breakout possible)
---
## DETAILED BREAKDOWN OF THIS INDICATOR
---
### 1. **User Inputs (Customizable Settings)**
| Input | Default | Purpose |
|------|--------|--------|
| `length` | 20 | Period for SMA, BB, KC |
| `bbMult` | 2.0 | Bollinger Band multiplier |
| `kcMult` | 1.5 | Keltner Channel ATR multiplier |
| `momentumLen` | 12 | Length for momentum regression |
| `showHistogram` | true | Show momentum histogram |
| `showStrengthMeter` | true | Show dynamic strength bar |
| `useSqueezeCandle` | true | Replace chart candles with colored squeeze candles |
---
### 2. **Core Calculations**
#### A. **Bollinger Bands**
```pinescript
basis = ta.sma(close, length)
dev = ta.stdev(close, length)
bbUpper = basis + bbMult * dev
bbLower = basis - bbMult * dev
```
- Standard BB using SMA and standard deviation.
#### B. **Keltner Channels (ATR-based)**
```pinescript
kcBasis = ta.sma(close, length)
atrv = ta.atr(length)
kcUpper = kcBasis + kcMult * atrv
kcLower = kcBasis - kcMult * atrv
```
- Uses ATR instead of stdev → more adaptive to recent volatility.
#### C. **Squeeze Condition**
```pinescript
squeezeOn = (bbUpper < kcUpper) and (bbLower > kcLower)
```
- **Squeeze ON**: BB completely inside KC → **low volatility**
- **Squeeze OFF**: BB breaks outside KC → **volatility expansion**
---
### 3. **Momentum Calculation (TTM Style)**
```pinescript
momRaw = close - basis
mom = ta.linreg(momRaw, momentumLen, 0)
```
- Measures **price deviation from the basis (SMA)** via **linear regression**
- Positive = bullish momentum, Negative = bearish
```pinescript
momRising = ta.change(mom) > 0
```
- Tracks whether momentum is increasing.
---
### 4. **Dynamic Momentum Strength (Key Feature)**
```pinescript
absMom = math.abs(mom)
strength = absMom / ta.highest(absMom, 50)
strengthSmooth = ta.sma(strength, 5)
```
- **Normalizes momentum** over last 50 bars
- **Smooths** with 5-period SMA → avoids jitter
- Result: `strengthSmooth` = **0 to 1** (0% to 100% of recent peak)
> **Strong Momentum** = `>= 50%` of recent peak
> **Weak Momentum** = `< 50%`
---
### 5. **Custom Candle Coloring Logic**
| Condition | Candle Color |
|--------|-------------|
| **Squeeze ON** | Semi-transparent **Gray** (`colSqueeze`) |
| **Squeeze OFF + Bullish + Strong** | **Cyan** (`#00FFFF`) |
| **Squeeze OFF + Bullish + Weak** | **Dark Blue** (`#00008B`) |
| **Squeeze OFF + Bearish + Strong** | **Red** (`#FF0000`) |
| **Squeeze OFF + Bearish + Weak** | **Yellow** (`#FFFF00`) |
> Wicks use same color as body
> Optional: Overrides chart candles (`useSqueezeCandle = true`)
---
### 6. **Visual Plot Elements**
| Element | Description |
|-------|-----------|
| `plotcandle()` | Draws **custom colored candles** (if enabled) |
| **Red Dots (below bar)** | Squeeze **ON** |
| **Green Triangle Up (above bar)** | Squeeze **OFF + Bullish** |
| **Red Triangle Down (above bar)** | Squeeze **OFF + Bearish** |
| **Histogram** | Momentum value, colored by direction & strength |
| **BB Lines** | Faint blue |
| **KC Lines** | Faint orange |
---
### 7. **Dynamic Squeeze Strength Bar (Bottom Center)**
```pinescript
table.new(position.bottom_center, 101, 1)
```
- A **101-cell horizontal bar** (0–100%)
- **Filled up to current `strengthSmooth * 100`**
- **Color-coded** by momentum direction & strength
- **Fades out** from filled → empty for smooth gradient
- Updates **only on last bar**
> Example:
> - 78% strength, bullish, strong → **Cyan bar filled to 78%**, fading to gray
---
### 8. **Info Label (Top-Right of Last Bar)**
```pinescript
Squeeze: ON/OFF
Momentum: +0.45
Strength: 72%
```
- Real-time status box
- Auto-updates on new bars
---
### 9. **Alert Conditions**
| Alert | Trigger |
|------|--------|
| `"Squeeze Started"` | `squeezeOn` becomes true |
| `"Squeeze Released"` | `squeezeOff AND bbUpper crosses above kcUpper` |
> Note: Only triggers on **bullish release** via `crossUp`.
> You can modify to add bearish release.
---
## HOW TO INTERPRET THE INDICATOR
| Signal | Meaning | Action |
|-------|--------|-------|
| **Gray Candles + Red Dots** | Squeeze ON → Consolidation | **Prepare** |
| **Cyan/Blue Candle + Green ▲** | Squeeze OFF → **Bullish Breakout** | **Go Long** |
| **Red/Yellow Candle + Red ▼** | Squeeze OFF → **Bearish Breakout** | **Go Short** |
| **Bright Color (Cyan/Red)** | **Strong Momentum** | Higher conviction |
| **Dim Color (Dark Blue/Yellow)** | **Weak Momentum** | Caution / possible fakeout |
| **Strength Bar >70%** | High momentum relative to recent history | Strong trend likely |
---
## TRADING STRATEGY EXAMPLE
1. **Wait for Squeeze ON** (gray candles, red dots)
2. **Watch momentum histogram** turning positive/negative
3. **Enter on Squeeze OFF** with:
- **Green triangle + cyan/dark blue candle**
- **Strength > 50%**
4. **Exit** on momentum fade or opposite signal
---
## UNIQUE FEATURES OF THIS VERSION
| Feature | Benefit |
|-------|--------|
| **Custom candle override** | Replaces default chart for clarity |
| **Dynamic strength normalization** | Compares current momentum to recent peaks |
| **Smooth strength bar** | Visual momentum intensity meter |
| **Color-coded strength levels** | Instantly see weak vs strong moves |
| **Info label** | At-a-glance stats |
| **Clean visuals** | No clutter, intuitive |
---
## LIMITATIONS & NOTES
- **Lagging by design** (uses SMAs, regression)
- **Repaints slightly** due to `ta.linreg(..., 0)` on current bar
- **Strength bar uses last 50 bars** — may vary by timeframe
- **No built-in stop-loss or TP** — use with price action or other tools
---
## BEST USED ON
- **Timeframes**: 15m, 1H, 4H, Daily
- **Markets**: Stocks, Forex, Crypto, Futures
- **Pairs well with**: Volume, VWAP, Support/Resistance
---
## SUMMARY
> **This is a highly visual, trader-friendly version of the TTM Squeeze** that:
> - **Colors candles** based on squeeze state and momentum strength
> - **Shows real-time momentum intensity** via histogram + strength bar
> - **Alerts on squeeze start/release**
> - **Normalizes momentum** for fair strength comparison
> - **Provides clean, actionable signals** for breakout trading
---
**Ideal for swing traders and day traders** looking to catch **high-momentum breakouts from low-volatility consolidations** with **clear entry signals and conviction levels**.
SCOTTGO - RVOL Bull/Bear Painter (Real-Time) SCOTTGO - RVOL Bull/Bear Painter (Real-Time Momentum Detection)
📌Overview
The RVOL Bull/Bear Painter is a Pine Script indicator designed to instantly highlight high-momentum candles driven by significant Relative Volume (RVOL).
It provides a clear visual signal (bar color, shape, and label) when a candle's volume exceeds its average by a user-defined threshold, confirming strong bullish or bearish interest in real-time. This helps traders quickly identify potential institutional accumulation/distribution or breakout/breakdown attempts.
✨ Key Features
Relative Volume (RVOL) Calculation: Automatically calculates the ratio of the current bar's volume to its moving average (SMA or EMA) over a customizable lookback period.
Momentum Confirmation: Paints the candle green (bullish) or red (bearish) only when both price direction and high RVOL criteria are met.
Real-Time Detection: Uses a plotshape method to display the signal triangle as soon as the RVOL and direction conditions are met on the currently forming candle, aiming for faster alerts than bar-close coloring.
Customizable Threshold: Easily adjust the RVOL multiplier (e.g., 1.5x, 2.0x, 3.0x) to filter out noise and only focus on truly significant volume events.
Labels and Alerts: Displays a volume multiplier label (e.g., BULL 2.55x) and includes pre-configured alert conditions for automated notifications.
🛠️ How to Use It
1. Identify High-Conviction Moves
Look for the painted candles and the corresponding labels. A candle painted green with a BULL label (e.g., BULL 2.5x) indicates that buyers stepped in with 2.5 times the typical volume to drive the price higher.
2. Configure Your Sensitivity
The power of the script lies in customizing the inputs:
RVOL Lookback Period: Determines the length of the volume moving average.
Shorter periods (e.g., 9-20) make the indicator more reactive to recent volume changes.
Longer periods (e.g., 50-200) require a much larger volume spike to trigger a signal.
RVOL Threshold: This is the multiplier.
Lower values (e.g., 1.5) will generate more signals.
Higher values (e.g., 3.0) will generate fewer, but generally higher-conviction, signals.
3. Set Up Alerts
Use the pre-configured alert conditions (Bullish RVOL Signal and Bearish RVOL Signal) in TradingView's alert menu. Crucially, set the alert frequency to "Once per bar" or "Once per minute" to receive notifications as soon as the high RVOL event occurs, without waiting for the bar to close.
EM Levelsstdv levels for you using VIX and VXN for ES and NQ so hopefully it helps you try it out and have fun
Danny Gee EMA Trend RibbonDanny Gee EMA Trend Ribbon - Multi-Timeframe Trend Analysis
A sophisticated 9-EMA ribbon system designed to visualize trend strength and direction with precision. This indicator creates a dynamic color-coded ribbon that adapts to market conditions, making trend identification effortless.
Key Features:
9 Customizable EMAs - Default periods: 8, 14, 20, 26, 32, 38, 44, 50, and 60
Intelligent Ribbon Coloring - Automatically displays bullish (green), bearish (red), or neutral (gray) based on EMA consensus
Smoothing Control - Adjustable smoothing period (default 2) reduces noise and false signals
Real-Time Trend Status - Live dashboard showing current trend state and EMA agreement count (e.g., "Bullish 8/9")
Visual Clarity - Color-coded EMA lines with the 60 EMA highlighted for key support/resistance
How It Works:
The indicator analyzes the slope direction of all 9 EMAs. When 7 or more EMAs agree on direction, the ribbon displays a clear bullish or bearish color. This consensus-based approach helps filter out weak or conflicting trends, keeping you focused on high-probability setups.
Best Used For:
✓ Identifying strong trending conditions
✓ Avoiding choppy, sideways markets
✓ Confirming trade direction with other indicators
✓ Multi-timeframe analysis (works on any chart timeframe)
Customization Options:
Adjust all EMA periods to match your trading style
Customize ribbon colors for personal preference
Toggle ribbon visibility on/off
Modify smoothing sensitivity
Perfect for swing traders, scalpers, and day traders looking for a clean, reliable trend filter that works across all markets - forex, crypto, stocks, and indices.
Raeinex Momentum Liquidity IndexEntry arrow signals with volumetric momentum (buying and selling pressure) and the possibility to use all entry signals as liquidity area for price retest.
BOS Wick Zones Retestwhen retest happens of lines with rejection place trade on 5m first you should identify trend on 1h and go with trend
Session HeatmapIntraday Seasonality
Overview
Analyzes historical patterns by time of day. Identifies when volatility, volume, and open interest changes tend to be highest or lowest.
Features
Multiple Metrics: TR (volatility), Volume, and Open Interest changes
Flexible Grouping: View patterns by weekday or month to spot day-of-week or seasonal effects
Heatmap Visualization: Blue (low) to Red (high) color scale for quick pattern recognition
Percentile Mode: Reduces outlier impact by using 5th-95th percentile range
Timezone Support: Display in UTC alongside your local time
Metrics Explained
TR: Volatility - when markets move most
Volume: Liquidity - when participation is highest
OI Increase: When new positions are opened
OI Decrease: When positions are closed
OI Net: Net open interest change
Usage
Set your timezone and preferred slot size (30min/1H)
Choose a date range (relative or custom)
Select a metric to analyze
Use "Group By" to see weekday or monthly patterns
Switch to Percentile color scale if outliers dominate
Notes
Chart timeframe should be equal to or smaller than Slot Size
OI metrics require Binance Perpetual symbols
DST is not automatically adjusted; consider seasonal shifts for US/EU sessions
Probability-Based Adaptive Detection🙏🏻 PBAD (Probability-Based Adaptive Detection) : adaptive control tool for outliers || novelty detection, made for worst case data & processes, for the highest time complexity O(n^2) compared with the alternatives (would be explained in a sec). Thresholds are completely data driven and axiomatic, no need in provided hyperparameters, are not learned or optimized. The method accepts multiple weights, e.g. both temporal and volatility weights.
Method briefly explained (I can go deeper if any1 asks explicitly):
Performs weighted KDE on initial input data, finds KDE global maximum (mode), creates new “residuals” dataset by centering initial data around this value;
Performs weighted KDE on residuals, uses sigmoid based probability mass targets with increasing probability coverage to construct a set of non-disjoint High Density Intervals (also called HDR, HPD in Bayesian terms);
Uses these intervals to calculate analogs of centralized & standardized moments;
Uses these ^^ moments to construct a set of control thresholds. The scheme used in PBAD is not only based on a central threshold, or on neighboring ones, it utilizes all previous thresholds, gaining more information.
...
The most important part is to understand whether you really need PBAD. Because even tho it seems to be the best one given highest algocomplexity, irl it would work worse in cases when it’s not required by your data.
Here’s the menu (aka taxonomy omg) of methods you can use that would let you make the right choice:
Moment-Based Adaptive Detection (MBAD) :
Norm: L2
Time complexity: original O(n), successfully reduced to O(1) in online version
Use case: default, general purpose
Based on: method of moments (powers of residuals from mean)
Thresholds architecture: centralized
Quantile-Based Adaptive Detection (QBAD):
Norm: L1
Time complexity: O(nlogn)
Use case: either bad data Or process instability
Based on: quantile moments (dyadic percentiles of residuals from median)
Thresholds architecture: chained/recursive/sequential
Probability-Based Adaptive Detection (PBAD):
Norm: L0
Time complexity: O(n^2)
Use case: both bad data And process instability
Based on: probability moments (target probability masses of residuals from KDE mode)
Thresholds architecture: decentralized (for lack of a better name xd, the idea is that these thresholds gain information from the all other threshold and are Not exclusively based on the central or neighboring thresholds)
...
Examples of true use cases:
^^ an appropriate financial instrument to use PBAD
^^ and another one
...
Additional details about how to use it:
Keep the student5 kernel, it’s the best you can do. I added others mostly for comparisons and if you want to use the tool Not for its primary purpose (on a fine data)
“Calculate for N bars” and “Starting at bar N” options allow to reduce calculation period only on the N number of last bars or next bars from a chosen one. It's vital, because calculations here are heavy
Keep plotting offset at 1 (allows to visually compare current bar with the previous threshold values). This is the way it should be done on price data.
HLC3 is the optimal source input, unless you want to use your own better one point estimate of each datapoint (in the best case done by using PBAD itself on OHLC+ values).
In essence it should be used just like MBAD or QBAD, fade/push extensions and limit, fade/push/skip deviations & basis, or other strategies of your. Again, the only reason for 3 methods to exist is to be chosen for according data characteristics.
Btw:
This is the initial version, I don’t consider it perfected tbh, even tho it works as expected, however this method is very situational anyways.
In this script KDE function is modified to ensure the outcoming probabilities Do sum up to 1. I didn’t do this normalization in Weighted KDE Mode script , but there it’s not required since we just need a KDE global max.
see ya
∞
Box Indicator - Auto Draw Previous Day's - High / Midline / LowThis indicator draws a box around the previous day’s high and low, calculates the midline, and displays them on the current day’s chart. It helps visualize key support/resistance levels from the prior trading day.
This script gives you a static reference box from the prior day’s trading range, including a midpoint. It’s useful for spotting potential reversal zones, breakout levels, or intraday targets based on yesterday’s price action.
15min Candle > 20% of Daily ATRThis Pine Script® (v6) indicator, titled "15min Candle > 20% of Daily ATR", detects unusually large 15-minute candles by comparing their size (full range or body) to a user-defined percentage (default 20%) of the previous day's Average True Range (ATR, default 14-period).
Current and Previous Period Anchored VWAPanchored VVWAPS and previous month VWAP extend out into the following month. Includes 1SD for both
SHAP-Aligned BUY Signal (Daily, Edge-Triggered)Based on the XGBoost + SHAP interpretation report, I'll explain which indicators to monitor for buying NVO. However, I must emphasize that this model performed poorly (47.5% accuracy) and should NOT be used for actual trading! That said, here's what the model learned (for educational purposes):
📊 Top Indicators to Monitor for BUY Signals
1. Days_Since_Low (Most Important - 1.264)
Direction: BULLISH ↑
Interpretation: Higher values → UP prediction
What to monitor: Track how many days since the stock hit its recent low
Buy signal: When the stock has been recovering for an extended period (e.g., 100+ days from low)
Why it matters: The model learned that stocks in long-term recovery tend to continue rising
2. SMA_50 (50-day Moving Average) (0.413)
Direction: BULLISH ↑
Interpretation: Higher absolute SMA_50 values → UP prediction
What to monitor: The 50-day simple moving average price level
Buy signal: When SMA_50 is at higher levels (e.g., above $80-90)
Why it matters: Higher moving averages indicate stronger long-term trends
3. SMA_200 (200-day Moving Average) (0.274)
Direction: BULLISH ↑
Interpretation: Higher SMA_200 → UP prediction
What to monitor: The 200-day simple moving average
Buy signal: When SMA_200 is trending upward and at elevated levels
Why it matters: Long-term trend indicator; golden cross (SMA_50 > SMA_200) is traditionally bullish
4. BB_Width (Bollinger Band Width) (0.199)
Direction: BULLISH ↑
Interpretation: WIDER Bollinger Bands → UP prediction
What to monitor: The distance between upper and lower Bollinger Bands
Buy signal: When BB_Width is expanding (increasing volatility often precedes trend moves)
Why it matters: Widening bands can signal the start of a new trend
5. Price_SMA_50_Ratio (0.158)
Direction: BULLISH ↑
Interpretation: When price is ABOVE the 50-day MA → UP prediction
What to monitor: Current price ÷ SMA_50
Buy signal: When ratio > 1.0 (price is above the 50-day average)
Why it matters: Price above moving averages indicates uptrend
6. Momentum_21D (21-day Momentum) (0.152)
Direction: BULLISH ↑
Interpretation: Positive 21-day momentum → UP prediction
What to monitor: 21-day rate of change
Buy signal: When momentum is positive and increasing
Why it matters: Positive momentum suggests continuation
7. Stoch_K (Stochastic Oscillator) (0.142)
Direction: BULLISH ↑
Interpretation: Higher Stochastic K → UP prediction
What to monitor: Stochastic oscillator (0-100 scale)
Buy signal: When Stoch_K is rising from oversold (<20) or in mid-range (40-60)
Why it matters: Measures momentum and overbought/oversold conditions
Multi-TF RSI+EMA+Clean S/R v6Visual Confirmation (What You'll See)
✅ EMAs: Blue (9) + Red (21) lines
✅ Pivot Points: Red circles (high) + Green circles (low)
✅ S/R Lines: Red resistance + Green support
✅ MTF Table: Top-right corner (RSI/ADX values)
✅ Signals: 🚀 STRONG BUY / 🔻 STRONG SELL labels
✅ Background: Green/Red tint during strong trends
Price Crossing 144 EMA Alert (No Visuals)Price Crossing 144 EMA Alert (No VisuPrice Crossing 144 EMA Alert (No Visuals)Price Crossing 144 EMA Alert (No Visuals)Price Crossing 144 EMA Alert (No Visuals)Price Crossing 144 EMA Alert (No Visuals)als)
Monthly Hotness RSI (Auto-Calibrated)Indicator of the previous months volatility/vol compared to averages over the last 3-5 years. helps show trend and if the market is 'hot'. indicator is good for showing favourable market conditions.
Relative Strength Index_YJ//@version=5
indicator(title="MACD_YJ", shorttitle="MACD_YJ",format=format.price, precision=2)
source = close
useCurrentRes = input.bool(true, title="Use Current Chart Resolution?")
resCustom = input.timeframe("60", title="Use Different Timeframe? Uncheck Box Above")
smd = input.bool(true, title="Show MacD & Signal Line? Also Turn Off Dots Below")
sd = input.bool(false, title="Show Dots When MacD Crosses Signal Line?")
sh = input.bool(true, title="Show Histogram?")
macd_colorChange = input.bool(true, title="Change MacD Line Color-Signal Line Cross?")
hist_colorChange = input.bool(true, title="MacD Histogram 4 Colors?")
// === Divergence inputs ===
grpDiv = "Divergence"
calculateDivergence = input.bool(true, title="Calculate Divergence", group=grpDiv, tooltip="피벗 기반 정/역배 다이버전스 탐지 및 알람 사용")
lookbackRight = input.int(5, "Lookback Right", group=grpDiv, minval=1)
lookbackLeft = input.int(5, "Lookback Left", group=grpDiv, minval=1)
rangeUpper = input.int(60, "Bars Range Upper", group=grpDiv, minval=1)
rangeLower = input.int(5, "Bars Range Lower", group=grpDiv, minval=1)
bullColor = input.color(color.new(#4CAF50, 0), "Bull Color", group=grpDiv)
bearColor = input.color(color.new(#F23645, 0), "Bear Color", group=grpDiv)
textColor = color.white
noneColor = color.new(color.white, 100)
res = useCurrentRes ? timeframe.period : resCustom
fastLength = input.int(12, minval=1)
slowLength = input.int(26, minval=1)
signalLength= input.int(9, minval=1)
fastMA = ta.ema(source, fastLength)
slowMA = ta.ema(source, slowLength)
macd = fastMA - slowMA
signal = ta.sma(macd, signalLength)
hist = macd - signal
outMacD = request.security(syminfo.tickerid, res, macd)
outSignal = request.security(syminfo.tickerid, res, signal)
outHist = request.security(syminfo.tickerid, res, hist)
// 가격도 같은 res로
hi_res = request.security(syminfo.tickerid, res, high)
lo_res = request.security(syminfo.tickerid, res, low)
// ── Histogram 색
histA_IsUp = outHist > outHist and outHist > 0
histA_IsDown = outHist < outHist and outHist > 0
histB_IsDown = outHist < outHist and outHist <= 0
histB_IsUp = outHist > outHist and outHist <= 0
macd_IsAbove = outMacD >= outSignal
plot_color = hist_colorChange ? (histA_IsUp ? color.new(#00FF00, 0) :
histA_IsDown ? color.new(#006900, 0) :
histB_IsDown ? color.new(#FF0000, 0) :
histB_IsUp ? color.new(#670000, 0) : color.yellow) : color.gray
macd_color = macd_colorChange ? color.new(#00ffff, 0) : color.new(#00ffff, 0)
signal_color = color.rgb(240, 232, 166)
circleYPosition = outSignal
// 골든/데드 크로스 (경고 해결: 먼저 계산)
isBullCross = ta.crossover(outMacD, outSignal)
isBearCross = ta.crossunder(outMacD, outSignal)
cross_color = isBullCross ? color.new(#00FF00, 0) : isBearCross ? color.new(#FF0000, 0) : na
// ── 플롯
plot(sh and outHist ? outHist : na, title="Histogram", color=plot_color, style=plot.style_histogram, linewidth=5)
plot(smd and outMacD ? outMacD : na, title="MACD", color=macd_color, linewidth=1)
plot(smd and outSignal? outSignal: na, title="Signal Line", color=signal_color, style=plot.style_line, linewidth=1)
plot(sd and (isBullCross or isBearCross) ? circleYPosition : na,
title="Cross", style=plot.style_circles, linewidth=3, color=cross_color)
hline(0, "0 Line", linestyle=hline.style_dotted, color=color.white)
// =====================
// Divergence (정배/역배) - 피벗 비교
// =====================
_inRange(cond) =>
bars = ta.barssince(cond)
rangeLower <= bars and bars <= rangeUpper
plFound = false
phFound = false
bullCond = false
bearCond = false
macdLBR = outMacD
if calculateDivergence
// 정배: 가격 LL, MACD HL
plFound := not na(ta.pivotlow(outMacD, lookbackLeft, lookbackRight))
macdHL = macdLBR > ta.valuewhen(plFound, macdLBR, 1) and _inRange(plFound )
lowLBR = lo_res
priceLL = lowLBR < ta.valuewhen(plFound, lowLBR, 1)
bullCond := priceLL and macdHL and plFound
// 역배: 가격 HH, MACD LH
phFound := not na(ta.pivothigh(outMacD, lookbackLeft, lookbackRight))
macdLH = macdLBR < ta.valuewhen(phFound, macdLBR, 1) and _inRange(phFound )
highLBR = hi_res
priceHH = highLBR > ta.valuewhen(phFound, highLBR, 1)
bearCond := priceHH and macdLH and phFound
// 시각화 (editable 파라미터 삭제)
plot(plFound ? macdLBR : na, offset=-lookbackRight, title="Regular Bullish (MACD)",
linewidth=2, color=(bullCond ? bullColor : noneColor), display=display.pane)
plotshape(bullCond ? macdLBR : na, offset=-lookbackRight, title="Bullish Label",
text=" Bull ", style=shape.labelup, location=location.absolute, color=bullColor, textcolor=textColor, display=display.pane)
plot(phFound ? macdLBR : na, offset=-lookbackRight, title="Regular Bearish (MACD)",
linewidth=2, color=(bearCond ? bearColor : noneColor), display=display.pane)
plotshape(bearCond ? macdLBR : na, offset=-lookbackRight, title="Bearish Label",
text=" Bear ", style=shape.labeldown, location=location.absolute, color=bearColor, textcolor=textColor, display=display.pane)
// 알람
alertcondition(bullCond, title="MACD Regular Bullish Divergence",
message="MACD 정배 다이버전스 발견: 현재 봉에서 lookbackRight 만큼 좌측.")
alertcondition(bearCond, title="MACD Regular Bearish Divergence",
message="MACD 역배 다이버전스 발견: 현재 봉에서 lookbackRight 만큼 좌측.")




















