Auto Support & Resistance From Option Strike Price + PercentagesAUTO SUPPORT AND RESISTANCE FROM OPTIONS STRIKE PRICES WITH PERCENTAGE GAPS
This is an auto support and resistance level indicator that uses options strike prices or psychological numbers as the relevant levels. Set your starting level or strike price and input the options strike price gaps for that ticker and 15 lines in either direction will automatically populate on the chart. It also has a table in the bottom right corner that tells you how far the current price is from the next closest support and resistance levels.
Everything is easily customizable in the indicator input settings including turning the lines on/off, turning the percentage gaps table on/off, setting the options strike price gaps, setting the starting level, setting the position of the percentage gaps table, changing support and resistance line colors all at once and updating the linewidth of all of the support and resistance lines at once.
***HOW TO USE***
First, go into the indicator settings and set the starting level to use. If you are trading SPY and it is near 450, then set your starting level at 450. If you are trading SQQQ and it is near 38, set your starting level to 38. If you are trading crypto, set your levels to the nearest psychological or round number such as 40,000 for BTC or 2,500 for ETH or 16.50 for LINK.
Second, set your options strike price gaps. If you are trading SPY, this will be 2.5. If you are trading SQQQ this number would be 1. If you are trading crypto, try using psychological price levels instead of strike prices, such as 500, 1000 or 5000 for BTC and 100, 250 or 500 for ETH. For small priced cryptos, use decimals such as .25, .50, etc.
Once these inputs are filled in, 15 levels in each direction will automatically populate on the chart for you.
If price is above a level, it will paint green. If price is below a level it will paint red. These colors represent support and resistance visually for you on the chart and will change dynamically as price moves above or below these levels. These colors can be customized in the indicator input settings to change all lines by only updating one color.
There is a table of percentage gap updates that will tell you in real time how far away the price is from the nearest support and resistance lines so you always know your risk to reward ratios. Each label will also be colored the same as the corresponding support or resistance line as a visual aid.
***MARKETS***
This indicator can be used as a signal on all markets, including stocks, crypto, futures and forex.
***TIMEFRAMES***
This support and resistance indicator can be used on all timeframes.
***TIPS***
Try using numerous indicators of ours on your chart so you can instantly see the bullish or bearish trend of multiple indicators in real time without having to analyze the data. Some of our favorites are our Auto Fibonacci, Directional Movement Index, Volume Profile, Momentum and Money Flow Index in combination with this auto support and resistance indicator. They all have real time Bullish and Bearish labels as well so you can immediately understand each indicator's trend.
Pesquisar nos scripts por "美股标普500"
S&P Sector Advance/Decline Weighted -Tom1traderEnjoy, enhance your trading (I hope), copy or adapt to your needs and keep smiling!
Thanks to @MartinShkreli. The sector variables and the "repaint" option (approx lines 20 through 32 of this script) are used directly from your script "Sectors"
RECOMMENDATION: Update the sector weightings -inputs are provided. They change as often as monthly and the
annual changes are certainly significant. When updating weighting percentages use the decimal value. I.E. 29% is .29
Good on any time frame. Especially SPY, SPX and ES scalpers and 0DTE options traders may like this a lot.
This gives good signals on S & P and related (ES, SPY) and indicates / plots differently than the AD line or ratio.
Each sector's entire % weight is added or subtracted depending of whether that sector advanced or declined.
Example: Information Tech weight at 29% so that % of 500 (145) is added if InfoTech is up a penny and subtracted if it is
down a penny. All sectors processed the same way so that for a given bar/candle the value will be between +500 (all
sectors up) and -500 (all sectors down). This weighted AD line of sectors is scaled to +/- 350 and plotted as a red/green line
along with aqua/fuchsia columns of its 5 period ema. The line is actual sector behavior and the columns seem to make a
good signal with column zero crosses standing out.
The columns aqua / fuchsia are a 5 period ema of the Sector AD line and give pretty good signals at
zero cross for SPX. I colored the AD red green line also to emphasize the times it opposes the ema
for example the histo/colums zero cross signal is NOT true when the AD line is showing all or most sectors
going the other way.
For readability, the AD line itself is scaled to 350. This lets the columns of the ema stand out better. The hlines at
350 and at 175 give an idea for the AD green red line how much of the sector's weight is up or down.
350 is all sectors up (advancing) and -350 is all sectors down (declining). The hlines at +/- 175 seem to outline
a more or less "neutral" zone. For example in an uptrend with most of the AD level positive and the columns positive;
a negative spike that does not pass the -175 line and returns positive does not seem to impact the price as much as
a deeper negative spike.
RS Line - Relative Strength Line [LevelUp]Overview:
This implementation of the RS Line mimics how Investor's Business Daily and CANSLIM investors measure growth stock performance versus the S&P 500.
If you are looking at a weekly chart, the RS Line is the performance of the stock over the past week versus the S&P 500 over that same time frame. The same logic applies to the daily and monthly charts, only the time frames are different.
If a stock moves up for the day/week/month and the S&P 500 does not, the RS Line will move up. If a stock ends the day/week/month flat, yet the S&P 500 moves up, the RS Line will go down.
Usage:
- Look for an upward sloping line.
- The steeper the line, the better.
- Can be used for viewing long-term trend.
Ivan_Long_Term_Cloud_BandThis is a combination of the 200 300 400 and 500 long terms weighted moving average.
The color code reflected the current uptrend or downtrend that the market is in by showing light green when 200 WMA is above the 300 WMA as well as showing darker green when 400 WMA is above the 500 WMA. On the other hand, when the 200 WMA is below the 300 WMA and the 400 beneath the 500, the band would be color-coded as light and deep red respectively to reflect the current level of support and resistance level.
ANN MACD : 25 IN 1 SCRIPTIn this script, I tried to fit deep learning series to 1 command system up to the maximum point.
After selecting the ticker, select the instrument from the menu and the system will automatically turn on the appropriate ann system.
Listed instruments with alternative tickers and error rates:
WTI : West Texas Intermediate (WTICOUSD , USOIL , CL1! ) Average error : 0.007593
BRENT : Brent Crude Oil (BCOUSD , UKOIL , BB1! ) Average error : 0.006591
GOLD : XAUUSD , GOLD , GC1! Average error : 0.012767
SP500 : S&P 500 Index (SPX500USD , SP1!) Average error : 0.011650
EURUSD : Eurodollar (EURUSD , 6E1! , FCEU1!) Average error : 0.005500
ETHUSD : Ethereum (ETHUSD , ETHUSDT ) Average error : 0.009378
BTCUSD : Bitcoin (BTCUSD , BTCUSDT , XBTUSD , BTC1!) Average error : 0.01050
GBPUSD : British Pound (GBPUSD,6B1! , GBP1!) Average error : 0.009999
USDJPY : US Dollar / Japanese Yen (USDJPY , FCUY1!) Average error : 0.009198
USDCHF : US Dollar / Swiss Franc (USDCHF , FCUF1! ) Average error : 0.009999
USDCAD : Us Dollar / Canadian Dollar (USDCAD) Average error : 0.012162
SOYBNUSD : Soybean (SOYBNUSD , ZS1!) Average error : 0.010000
CORNUSD : Corn (ZC1! ) Average error : 0.007574
NATGASUSD : Natural Gas (NATGASUSD , NG1!) Average error : 0.010000
SUGARUSD : Sugar (SUGARUSD , SB1! ) Average error : 0.011081
WHEATUSD : Wheat (WHEATUSD , ZW1!) Average error : 0.009980
XPTUSD : Platinum (XPTUSD , PL1! ) Average error : 0.009964
XU030 : Borsa Istanbul 30 Futures ( XU030 , XU030D1! ) Average error : 0.010727
VIX : S & P 500 Volatility Index (VX1! , VIX ) Average error : 0.009999
YM : E - Mini Dow Futures (YM1! ) Average error : 0.010819
ES : S&P 500 E-Mini Futures (ES1! ) Average error : 0.010709
GAZP : Gazprom Futures (GAZP , GZ1! ) Average error : 0.008442
SSE : Shangai Stock Exchange Composite (Index ) ( 000001 ) Average error : 0.011287
XRPUSD : Ripple (XRPUSD , XRPUSDT ) Average error : 0.009803
Note 1 : Australian Dollar (AUDUSD , AUD1! , FCAU1! ) : Instrument has been removed because it has an average error rate of over 0.13.
The average error rate is 0.1850.
I didn't delete it from the menu just because there was so much request,
You can use.
Note 2 : Friends have too many requests, it took me a week in total and 1 other script that I'll share in 2 days.
Reaching these error rates is a very difficult task, and when I keep at a low learning rate, they are trained for a very long time.
If I don't see the error rate at an average low, I increase the layers and go back into a longer process.
It takes me 45 minutes per instrument to command artificial neural networks, so I'll release one more open source, and then we'll be laying 70-80 percent of the world trade volume with artificial neural networks.
Note 3 :
I would like to thank wroclai for helping me with this script.
This script is subject to MIT License on behalf of both of us.
You can review my original idea scripts from my Github page.
You can use it free but if you are going to modify it, just quote this script .
I hope it will help everyone, after 1-2 days I will share another ann script that I think is of the same importance as this, stay tuned.
Regards , Noldo .
3 EMAS strategy to define trendsBasic script that allows you to have 3 scripts all in one EMA (exponential moving averages). They are useful to know the general trends of your chart: current long-term trend, short-term (or immediately) and general.
1 ° EMA 36 serves to define or mark action of the market trend price.
At the moment of crossing EMA 36 with EMA 200 upwards it indicates continuation to level 2 ...
2 ° EMA 200 serves as support or resistance according to the case, confirms continuation of trend in medium or long term when crossing with EMA 500, upward trend probability level 3 confirmed. As the case may be, cross up or down.
3 ° EMA 500 serves as support or resistance of the price action.
EMAS 200 and 500 give you a probability of Starting Area ...
Confirming with support or resistance.
Complementation with Stochastics ..
MACD
Note: Remember that "exponential" means that these indicators give more weight to the most recent data, making them more reactive to price changes (react faster to changes in recent prices than simple moving averages)
GROWINGS CRYPTOTRADERS
Liquidity & SMT Detector//@version=5
indicator("Liquidity & SMT Detector", overlay=true, max_lines_count=500, max_labels_count=500)
// ============================================
// INPUT SETTINGS
// ============================================
// Group 1: Liquidity Detection
swing_length = input.int(15, "Swing Length", minval=5, maxval=50, group="Liquidity Detection")
swing_strength = input.int(3, "Swing Strength (bars clear)", minval=1, maxval=10, group="Liquidity Detection")
max_lines = input.int(10, "Max Lines Displayed", minval=3, maxval=50, group="Liquidity Detection")
line_color_high = input.color(color.red, "High Line Color", group="Liquidity Detection")
line_color_low = input.color(color.green, "Low Line Color", group="Liquidity Detection")
line_width = input.int(2, "Line Width", minval=1, maxval=5, group="Liquidity Detection")
show_labels = input.bool(true, "Show H/L Labels", group="Liquidity Detection")
// Group 2: Displacement Detection
enable_displacement = input.bool(true, "Enable Displacement Detection", group="Displacement")
displacement_multiplier = input.float(3.5, "Size Multiplier", minval=2.0, maxval=10.0, step=0.5, group="Displacement")
displacement_period = input.int(30, "Average Period", minval=10, maxval=100, group="Displacement")
displacement_min_percent = input.float(0.3, "Min Move %", minval=0.1, maxval=2.0, step=0.1, group="Displacement")
displacement_color_bull = input.color(color.new(color.aqua, 70), "Bullish Color", group="Displacement")
displacement_color_bear = input.color(color.new(color.orange, 70), "Bearish Color", group="Displacement")
show_displacement_label = input.bool(true, "Show Labels", group="Displacement")
// Group 3: SMT Detection
enable_smt = input.bool(true, "Enable SMT Detection", group="SMT Divergence")
nq_symbol = input.string("NQ1!", "Nasdaq Symbol", group="SMT Divergence")
es_symbol = input.string("ES1!", "S&P500 Symbol", group="SMT Divergence")
smt_lookback = input.int(20, "Lookback Period", minval=5, maxval=100, group="SMT Divergence")
smt_line_color = input.color(color.yellow, "SMT Line Color", group="SMT Divergence")
smt_text_color = input.color(color.yellow, "SMT Text Color", group="SMT Divergence")
// ============================================
// ARRAYS FOR LINE/LABEL MANAGEMENT
// ============================================
var line high_lines = array.new_line()
var line low_lines = array.new_line()
var label high_labels = array.new_label()
var label low_labels = array.new_label()
var float high_levels = array.new_float()
var float low_levels = array.new_float()
// ============================================
// FUNCTION: DETECT SWING HIGHS (STRONGER)
// ============================================
isSwingHigh(len, strength) =>
is_pivot = true
pivot_high = high
for i = 1 to strength
if high >= pivot_high or high >= pivot_high
is_pivot := false
break
if is_pivot
for i = strength + 1 to len
if high > pivot_high or high > pivot_high
is_pivot := false
break
is_pivot
// ============================================
// FUNCTION: DETECT SWING LOWS (STRONGER)
// ============================================
isSwingLow(len, strength) =>
is_pivot = true
pivot_low = low
for i = 1 to strength
if low <= pivot_low or low <= pivot_low
is_pivot := false
break
if is_pivot
for i = strength + 1 to len
if low < pivot_low or low < pivot_low
is_pivot := false
break
is_pivot
// ============================================
// SWING HIGH DETECTION & LINE DRAWING
// ============================================
if isSwingHigh(swing_length, swing_strength)
swing_high = high
new_line = line.new(bar_index - swing_length, swing_high, bar_index, swing_high, color=line_color_high, width=line_width, style=line.style_dashed)
array.push(high_lines, new_line)
array.push(high_levels, swing_high)
if show_labels
new_label = label.new(bar_index - swing_length, swing_high, "H", color=color.new(line_color_high, 80), textcolor=line_color_high, style=label.style_label_down, size=size.small)
array.push(high_labels, new_label)
// Limit number of lines
if array.size(high_lines) > max_lines
line.delete(array.shift(high_lines))
array.shift(high_levels)
if show_labels and array.size(high_labels) > 0
label.delete(array.shift(high_labels))
// ============================================
// SWING LOW DETECTION & LINE DRAWING
// ============================================
if isSwingLow(swing_length, swing_strength)
swing_low = low
new_line = line.new(bar_index - swing_length, swing_low, bar_index, swing_low, color=line_color_low, width=line_width, style=line.style_dashed)
array.push(low_lines, new_line)
array.push(low_levels, swing_low)
if show_labels
new_label = label.new(bar_index - swing_length, swing_low, "L", color=color.new(line_color_low, 80), textcolor=line_color_low, style=label.style_label_up, size=size.small)
array.push(low_labels, new_label)
// Limit number of lines
if array.size(low_lines) > max_lines
line.delete(array.shift(low_lines))
array.shift(low_levels)
if show_labels and array.size(low_labels) > 0
label.delete(array.shift(low_labels))
// ============================================
// UPDATE EXISTING LINES & CHECK FOR SWEEPS
// ============================================
if array.size(high_lines) > 0
for i = array.size(high_lines) - 1 to 0
current_line = array.get(high_lines, i)
current_level = array.get(high_levels, i)
if close > current_level
line.delete(current_line)
array.remove(high_lines, i)
array.remove(high_levels, i)
if show_labels and i < array.size(high_labels)
label.delete(array.get(high_labels, i))
array.remove(high_labels, i)
else
line.set_x2(current_line, bar_index)
if array.size(low_lines) > 0
for i = array.size(low_lines) - 1 to 0
current_line = array.get(low_lines, i)
current_level = array.get(low_levels, i)
if close < current_level
line.delete(current_line)
array.remove(low_lines, i)
array.remove(low_levels, i)
if show_labels and i < array.size(low_labels)
label.delete(array.get(low_labels, i))
array.remove(low_labels, i)
else
line.set_x2(current_line, bar_index)
// ============================================
// DISPLACEMENT CANDLE DETECTION
// ============================================
body_size = math.abs(close - open)
avg_body = ta.sma(math.abs(close - open), displacement_period)
candle_range = high - low
avg_range = ta.sma(high - low, displacement_period)
price_move_percent = (body_size / close) * 100
// Stricter criteria for true displacement
is_strong_body = body_size > (avg_body * displacement_multiplier)
is_strong_range = candle_range > (avg_range * displacement_multiplier)
is_significant_move = price_move_percent >= displacement_min_percent
is_impulsive = body_size > (candle_range * 0.6)
is_displacement = enable_displacement and is_strong_body and is_strong_range and is_significant_move and is_impulsive
is_bullish = close > open
bgcolor(is_displacement ? (is_bullish ? displacement_color_bull : displacement_color_bear) : na)
if is_displacement and show_displacement_label
label.new(bar_index, is_bullish ? high : low, "D", color=color.new(is_bullish ? color.aqua : color.orange, 50), textcolor=is_bullish ? color.aqua : color.orange, style=is_bullish ? label.style_label_up : label.style_label_down, size=size.tiny)
// ============================================
// SMT DIVERGENCE DETECTION
// ============================================
current_symbol = syminfo.ticker
comparison_symbol = str.contains(current_symbol, "NQ") ? es_symbol : nq_symbol
comparison_high = request.security(comparison_symbol, timeframe.period, high, lookahead=barmerge.lookahead_off)
comparison_low = request.security(comparison_symbol, timeframe.period, low, lookahead=barmerge.lookahead_off)
var float prev_current_low = na
var float prev_comparison_low = na
var int prev_swing_bar = na
current_is_swing_low = isSwingLow(swing_length, swing_strength)
comparison_is_swing_low = ta.lowestbars(comparison_low, swing_length * 2 + 1) == -swing_length
if enable_smt and current_is_swing_low
current_swing_low = low
comparison_swing_low = comparison_low
if not na(prev_current_low) and not na(prev_comparison_low)
current_lower = current_swing_low < prev_current_low
comparison_lower = comparison_swing_low < prev_comparison_low
is_smt = (current_lower and not comparison_lower) or (not current_lower and comparison_lower)
if is_smt
smt_line = line.new(prev_swing_bar, prev_current_low, bar_index - swing_length, current_swing_low, color=smt_line_color, width=2, style=line.style_solid)
mid_bar = math.round((prev_swing_bar + bar_index - swing_length) / 2)
mid_price = (prev_current_low + current_swing_low) / 2
label.new(mid_bar, mid_price, "SMT", color=color.new(smt_line_color, 80), textcolor=smt_text_color, style=label.style_label_center, size=size.normal)
prev_current_low := current_swing_low
prev_comparison_low := comparison_swing_low
prev_swing_bar := bar_index - swing_length
// ============================================
// ALERTS
// ============================================
alertcondition(array.size(high_lines) < array.size(high_lines) , title="Liquidity Sweep High", message="High liquidity swept at {{close}}")
alertcondition(array.size(low_lines) < array.size(low_lines) , title="Liquidity Sweep Low", message="Low liquidity swept at {{close}}")
alertcondition(is_displacement, title="Displacement Candle", message="Displacement candle detected at {{close}}")
Liquidity & SMT Detector//@version=5
indicator("Liquidity & SMT Detector", overlay=true, max_lines_count=500, max_labels_count=500)
// ============================================
// INPUT SETTINGS
// ============================================
// Group 1: Liquidity Detection
swing_length = input.int(10, "Swing Length", minval=3, maxval=50, group="Liquidity Detection")
max_lines = input.int(20, "Max Lines Displayed", minval=5, maxval=100, group="Liquidity Detection")
line_color_high = input.color(color.red, "High Line Color", group="Liquidity Detection")
line_color_low = input.color(color.green, "Low Line Color", group="Liquidity Detection")
line_width = input.int(2, "Line Width", minval=1, maxval=5, group="Liquidity Detection")
show_labels = input.bool(true, "Show H/L Labels", group="Liquidity Detection")
// Group 2: Displacement Detection
enable_displacement = input.bool(true, "Enable Displacement Detection", group="Displacement")
displacement_multiplier = input.float(2.0, "Size Multiplier", minval=1.5, maxval=5.0, step=0.1, group="Displacement")
displacement_period = input.int(20, "Average Period", minval=10, maxval=50, group="Displacement")
displacement_color_bull = input.color(color.new(color.aqua, 70), "Bullish Color", group="Displacement")
displacement_color_bear = input.color(color.new(color.orange, 70), "Bearish Color", group="Displacement")
show_displacement_label = input.bool(true, "Show Labels", group="Displacement")
// Group 3: SMT Detection
enable_smt = input.bool(true, "Enable SMT Detection", group="SMT Divergence")
nq_symbol = input.string("NQ1!", "Nasdaq Symbol", group="SMT Divergence")
es_symbol = input.string("ES1!", "S&P500 Symbol", group="SMT Divergence")
smt_lookback = input.int(20, "Lookback Period", minval=5, maxval=100, group="SMT Divergence")
smt_line_color = input.color(color.yellow, "SMT Line Color", group="SMT Divergence")
smt_text_color = input.color(color.yellow, "SMT Text Color", group="SMT Divergence")
// ============================================
// ARRAYS FOR LINE/LABEL MANAGEMENT
// ============================================
var line high_lines = array.new_line()
var line low_lines = array.new_line()
var label high_labels = array.new_label()
var label low_labels = array.new_label()
var float high_levels = array.new_float()
var float low_levels = array.new_float()
// ============================================
// FUNCTION: DETECT SWING HIGHS
// ============================================
isSwingHigh(len) =>
highestBar = ta.highestbars(high, len * 2 + 1)
highestBar == -len
// ============================================
// FUNCTION: DETECT SWING LOWS
// ============================================
isSwingLow(len) =>
lowestBar = ta.lowestbars(low, len * 2 + 1)
lowestBar == -len
// ============================================
// SWING HIGH DETECTION & LINE DRAWING
// ============================================
if isSwingHigh(swing_length)
swing_high = high
new_line = line.new(bar_index - swing_length, swing_high, bar_index, swing_high, color=line_color_high, width=line_width, style=line.style_dashed)
array.push(high_lines, new_line)
array.push(high_levels, swing_high)
if show_labels
new_label = label.new(bar_index - swing_length, swing_high, "H", color=color.new(line_color_high, 80), textcolor=line_color_high, style=label.style_label_down, size=size.small)
array.push(high_labels, new_label)
// Limit number of lines
if array.size(high_lines) > max_lines
line.delete(array.shift(high_lines))
array.shift(high_levels)
if show_labels and array.size(high_labels) > 0
label.delete(array.shift(high_labels))
// ============================================
// SWING LOW DETECTION & LINE DRAWING
// ============================================
if isSwingLow(swing_length)
swing_low = low
new_line = line.new(bar_index - swing_length, swing_low, bar_index, swing_low, color=line_color_low, width=line_width, style=line.style_dashed)
array.push(low_lines, new_line)
array.push(low_levels, swing_low)
if show_labels
new_label = label.new(bar_index - swing_length, swing_low, "L", color=color.new(line_color_low, 80), textcolor=line_color_low, style=label.style_label_up, size=size.small)
array.push(low_labels, new_label)
// Limit number of lines
if array.size(low_lines) > max_lines
line.delete(array.shift(low_lines))
array.shift(low_levels)
if show_labels and array.size(low_labels) > 0
label.delete(array.shift(low_labels))
// ============================================
// UPDATE EXISTING LINES & CHECK FOR SWEEPS
// ============================================
if array.size(high_lines) > 0
for i = array.size(high_lines) - 1 to 0
current_line = array.get(high_lines, i)
current_level = array.get(high_levels, i)
if close > current_level
line.delete(current_line)
array.remove(high_lines, i)
array.remove(high_levels, i)
if show_labels and i < array.size(high_labels)
label.delete(array.get(high_labels, i))
array.remove(high_labels, i)
else
line.set_x2(current_line, bar_index)
if array.size(low_lines) > 0
for i = array.size(low_lines) - 1 to 0
current_line = array.get(low_lines, i)
current_level = array.get(low_levels, i)
if close < current_level
line.delete(current_line)
array.remove(low_lines, i)
array.remove(low_levels, i)
if show_labels and i < array.size(low_labels)
label.delete(array.get(low_labels, i))
array.remove(low_labels, i)
else
line.set_x2(current_line, bar_index)
// ============================================
// DISPLACEMENT CANDLE DETECTION
// ============================================
body_size = math.abs(close - open)
avg_body = ta.sma(math.abs(close - open), displacement_period)
is_displacement = enable_displacement and body_size > (avg_body * displacement_multiplier)
is_bullish = close > open
bgcolor(is_displacement ? (is_bullish ? displacement_color_bull : displacement_color_bear) : na)
if is_displacement and show_displacement_label
label.new(bar_index, is_bullish ? high : low, "D", color=color.new(is_bullish ? color.aqua : color.orange, 50), textcolor=is_bullish ? color.aqua : color.orange, style=is_bullish ? label.style_label_up : label.style_label_down, size=size.tiny)
// ============================================
// SMT DIVERGENCE DETECTION
// ============================================
current_symbol = syminfo.ticker
comparison_symbol = str.contains(current_symbol, "NQ") ? es_symbol : nq_symbol
comparison_high = request.security(comparison_symbol, timeframe.period, high, lookahead=barmerge.lookahead_off)
comparison_low = request.security(comparison_symbol, timeframe.period, low, lookahead=barmerge.lookahead_off)
var float prev_current_low = na
var float prev_comparison_low = na
var int prev_swing_bar = na
current_is_swing_low = isSwingLow(swing_length)
comparison_is_swing_low = ta.lowestbars(comparison_low, swing_length * 2 + 1) == -swing_length
if enable_smt and current_is_swing_low
current_swing_low = low
comparison_swing_low = comparison_low
if not na(prev_current_low) and not na(prev_comparison_low)
current_lower = current_swing_low < prev_current_low
comparison_lower = comparison_swing_low < prev_comparison_low
is_smt = (current_lower and not comparison_lower) or (not current_lower and comparison_lower)
if is_smt
smt_line = line.new(prev_swing_bar, prev_current_low, bar_index - swing_length, current_swing_low, color=smt_line_color, width=2, style=line.style_solid)
mid_bar = math.round((prev_swing_bar + bar_index - swing_length) / 2)
mid_price = (prev_current_low + current_swing_low) / 2
label.new(mid_bar, mid_price, "SMT", color=color.new(smt_line_color, 80), textcolor=smt_text_color, style=label.style_label_center, size=size.normal)
prev_current_low := current_swing_low
prev_comparison_low := comparison_swing_low
prev_swing_bar := bar_index - swing_length
// ============================================
// ALERTS
// ============================================
alertcondition(array.size(high_lines) < array.size(high_lines) , title="Liquidity Sweep High", message="High liquidity swept at {{close}}")
alertcondition(array.size(low_lines) < array.size(low_lines) , title="Liquidity Sweep Low", message="Low liquidity swept at {{close}}")
alertcondition(is_displacement, title="Displacement Candle", message="Displacement candle detected at {{close}}")
Liquidity & SMT Detector//@version=5
indicator("Liquidity & SMT Detector", overlay=true, max_lines_count=500, max_labels_count=500)
// ============================================
// INPUT SETTINGS
// ============================================
// Group 1: Liquidity Detection
swing_length = input.int(10, "Swing Length", minval=3, maxval=50, group="Liquidity Detection")
line_color_high = input.color(color.red, "High Line Color", group="Liquidity Detection")
line_color_low = input.color(color.green, "Low Line Color", group="Liquidity Detection")
line_width = input.int(2, "Line Width", minval=1, maxval=5, group="Liquidity Detection")
show_labels = input.bool(true, "Show H/L Labels", group="Liquidity Detection")
// Group 2: Displacement Detection
enable_displacement = input.bool(true, "Enable Displacement Detection", group="Displacement")
displacement_multiplier = input.float(2.0, "Size Multiplier", minval=1.5, maxval=5.0, step=0.1, group="Displacement")
displacement_period = input.int(20, "Average Period", minval=10, maxval=50, group="Displacement")
displacement_color_bull = input.color(color.new(color.aqua, 70), "Bullish Color", group="Displacement")
displacement_color_bear = input.color(color.new(color.orange, 70), "Bearish Color", group="Displacement")
show_displacement_label = input.bool(true, "Show Labels", group="Displacement")
// Group 3: SMT Detection
enable_smt = input.bool(true, "Enable SMT Detection", group="SMT Divergence")
nq_symbol = input.string("NQ1!", "Nasdaq Symbol", group="SMT Divergence")
es_symbol = input.string("ES1!", "S&P500 Symbol", group="SMT Divergence")
smt_lookback = input.int(20, "Lookback Period", minval=5, maxval=100, group="SMT Divergence")
smt_line_color = input.color(color.yellow, "SMT Line Color", group="SMT Divergence")
smt_text_color = input.color(color.yellow, "SMT Text Color", group="SMT Divergence")
// ============================================
// ARRAYS FOR LINE/LABEL MANAGEMENT
// ============================================
var line high_lines = array.new_line()
var line low_lines = array.new_line()
var label high_labels = array.new_label()
var label low_labels = array.new_label()
var float high_levels = array.new_float()
var float low_levels = array.new_float()
// ============================================
// FUNCTION: DETECT SWING HIGHS
// ============================================
isSwingHigh(len) =>
highestBar = ta.highestbars(high, len * 2 + 1)
highestBar == -len
// ============================================
// FUNCTION: DETECT SWING LOWS
// ============================================
isSwingLow(len) =>
lowestBar = ta.lowestbars(low, len * 2 + 1)
lowestBar == -len
// ============================================
// SWING HIGH DETECTION & LINE DRAWING
// ============================================
if isSwingHigh(swing_length)
swing_high = high
new_line = line.new(bar_index - swing_length, swing_high, bar_index, swing_high, color=line_color_high, width=line_width, style=line.style_dashed)
array.push(high_lines, new_line)
array.push(high_levels, swing_high)
if show_labels
new_label = label.new(bar_index - swing_length, swing_high, "H", color=color.new(line_color_high, 80), textcolor=line_color_high, style=label.style_label_down, size=size.small)
array.push(high_labels, new_label)
// ============================================
// SWING LOW DETECTION & LINE DRAWING
// ============================================
if isSwingLow(swing_length)
swing_low = low
new_line = line.new(bar_index - swing_length, swing_low, bar_index, swing_low, color=line_color_low, width=line_width, style=line.style_dashed)
array.push(low_lines, new_line)
array.push(low_levels, swing_low)
if show_labels
new_label = label.new(bar_index - swing_length, swing_low, "L", color=color.new(line_color_low, 80), textcolor=line_color_low, style=label.style_label_up, size=size.small)
array.push(low_labels, new_label)
// ============================================
// UPDATE EXISTING LINES & CHECK FOR SWEEPS
// ============================================
if array.size(high_lines) > 0
for i = array.size(high_lines) - 1 to 0
current_line = array.get(high_lines, i)
current_level = array.get(high_levels, i)
if close > current_level
line.delete(current_line)
array.remove(high_lines, i)
array.remove(high_levels, i)
if show_labels and i < array.size(high_labels)
label.delete(array.get(high_labels, i))
array.remove(high_labels, i)
else
line.set_x2(current_line, bar_index)
if array.size(low_lines) > 0
for i = array.size(low_lines) - 1 to 0
current_line = array.get(low_lines, i)
current_level = array.get(low_levels, i)
if close < current_level
line.delete(current_line)
array.remove(low_lines, i)
array.remove(low_levels, i)
if show_labels and i < array.size(low_labels)
label.delete(array.get(low_labels, i))
array.remove(low_labels, i)
else
line.set_x2(current_line, bar_index)
// ============================================
// DISPLACEMENT CANDLE DETECTION
// ============================================
body_size = math.abs(close - open)
avg_body = ta.sma(math.abs(close - open), displacement_period)
is_displacement = enable_displacement and body_size > (avg_body * displacement_multiplier)
is_bullish = close > open
bgcolor(is_displacement ? (is_bullish ? displacement_color_bull : displacement_color_bear) : na)
if is_displacement and show_displacement_label
label.new(bar_index, is_bullish ? high : low, "D", color=color.new(is_bullish ? color.aqua : color.orange, 50), textcolor=is_bullish ? color.aqua : color.orange, style=is_bullish ? label.style_label_up : label.style_label_down, size=size.tiny)
// ============================================
// SMT DIVERGENCE DETECTION
// ============================================
current_symbol = syminfo.ticker
comparison_symbol = str.contains(current_symbol, "NQ") ? es_symbol : nq_symbol
comparison_high = request.security(comparison_symbol, timeframe.period, high, lookahead=barmerge.lookahead_off)
comparison_low = request.security(comparison_symbol, timeframe.period, low, lookahead=barmerge.lookahead_off)
var float prev_current_low = na
var float prev_comparison_low = na
var int prev_swing_bar = na
current_is_swing_low = isSwingLow(swing_length)
comparison_is_swing_low = ta.lowestbars(comparison_low, swing_length * 2 + 1) == -swing_length
if enable_smt and current_is_swing_low
current_swing_low = low
comparison_swing_low = comparison_low
if not na(prev_current_low) and not na(prev_comparison_low)
current_lower = current_swing_low < prev_current_low
comparison_lower = comparison_swing_low < prev_comparison_low
is_smt = (current_lower and not comparison_lower) or (not current_lower and comparison_lower)
if is_smt
smt_line = line.new(prev_swing_bar, prev_current_low, bar_index - swing_length, current_swing_low, color=smt_line_color, width=2, style=line.style_solid)
mid_bar = math.round((prev_swing_bar + bar_index - swing_length) / 2)
mid_price = (prev_current_low + current_swing_low) / 2
label.new(mid_bar, mid_price, "SMT", color=color.new(smt_line_color, 80), textcolor=smt_text_color, style=label.style_label_center, size=size.normal)
prev_current_low := current_swing_low
prev_comparison_low := comparison_swing_low
prev_swing_bar := bar_index - swing_length
// ============================================
// ALERTS
// ============================================
alertcondition(array.size(high_lines) < array.size(high_lines) , title="Liquidity Sweep High", message="High liquidity swept at {{close}}")
alertcondition(array.size(low_lines) < array.size(low_lines) , title="Liquidity Sweep Low", message="Low liquidity swept at {{close}}")
alertcondition(is_displacement, title="Displacement Candle", message="Displacement candle detected at {{close}}")
Power RSI Segment Runner [CHE] Power RSI Segment Runner — Tracks RSI momentum across higher timeframe segments to detect directional switches for trend confirmation.
Summary
This indicator calculates a running Relative Strength Index adapted to segments defined by changes in a higher timeframe, such as daily closes, providing a smoothed view of momentum within each period. It distinguishes between completed segments, which fix the final RSI value, and ongoing ones, which update in real time with an exponential moving average filter. Directional switches between bullish and bearish momentum trigger visual alerts, including overlay lines and emojis, while a compact table displays current trend strength as a progress bar. This segmented approach reduces noise from intra-period fluctuations, offering clearer signals for trend persistence compared to standard RSI on lower timeframes.
Motivation: Why this design?
Standard RSI often generates erratic signals in choppy markets due to constant recalculation over fixed lookback periods, leading to false reversals that mislead traders during range-bound or volatile phases. By resetting the RSI accumulation at higher timeframe boundaries, this indicator aligns momentum assessment with broader market cycles, capturing sustained directional bias more reliably. It addresses the gap between short-term noise and long-term trends, helping users filter entries without over-relying on absolute overbought or oversold thresholds.
What’s different vs. standard approaches?
- Baseline Reference: Diverges from the classic Wilder RSI, which uses a fixed-length exponential moving average of gains and losses across all bars.
- Architecture Differences:
- Segments momentum resets at higher timeframe changes, isolating calculations per period instead of continuous history.
- Employs persistent sums for ups and downs within segments, with on-the-fly RSI derivation and EMA smoothing.
- Integrates switch detection logic that clears prior visuals on reversal, preventing clutter from outdated alerts.
- Adds overlay projections like horizontal price lines and dynamic percent change trackers for immediate trade context.
- Practical Effect: Charts show discrete RSI endpoints for past segments alongside a curved running trace, making momentum evolution visually intuitive. Switches appear as clean, extendable overlays, reducing alert fatigue and highlighting only confirmed directional shifts, which aids in avoiding whipsaws during minor pullbacks.
How it works (technical)
The indicator begins by detecting changes in the specified higher timeframe, such as a new daily bar, to define segment boundaries. At each boundary, it finalizes the prior segment's RSI by summing positive and negative price changes over that period and derives the value from the ratio of those sums, then applies an exponential moving average for smoothing. Within the active segment, it accumulates ongoing ups and downs from price changes relative to the source, recalculating the running RSI similarly and smoothing it with the same EMA length.
Points for the running RSI are collected into an array starting from the segment's onset, forming a curved polyline once sufficient bars accumulate. Comparisons between the running RSI and the last completed segment's value determine the current direction as long, short, or neutral, with switches triggering deletions of old visuals and creation of new ones: a label at the RSI pane, a vertical dashed line across the RSI range, an emoji positioned via ATR offset on the price chart, a solid horizontal line at the switch price, a dashed line tracking current close, and a midpoint label for percent change from the switch.
Initialization occurs on the first bar by resetting accumulators, and visualization gates behind a minimum bar count since the segment start to avoid early instability. The trend strength table builds vertically with filled cells proportional to the rounded RSI value, colored by direction. All drawing objects update or extend on subsequent bars to reflect live progress.
Parameter Guide
EMA Length — Controls the smoothing applied to the running RSI; higher values increase lag but reduce noise. Default: 10. Trade-offs: Shorter settings heighten sensitivity for fast markets but risk more false switches; longer ones suit trending conditions for stability.
Source — Selects the price data for change calculations, typically close for standard momentum. Default: close. Trade-offs: Open or high/low may emphasize gaps, altering segment intensity.
Segment Timeframe — Defines the higher timeframe for segment resets, like daily for intraday charts. Default: D. Trade-offs: Shorter frames create more frequent but shorter segments; longer ones align with major cycles but delay resets.
Overbought Level — Sets the upper threshold for potential overbought conditions (currently unused in visuals). Default: 70. Trade-offs: Adjust for asset volatility; higher values delay bearish warnings.
Oversold Level — Sets the lower threshold for potential oversold conditions (currently unused in visuals). Default: 30. Trade-offs: Lower values permit deeper dips before signaling bullish potential.
Show Completed Label — Toggles labels at segment ends displaying final RSI. Default: true. Trade-offs: Enables historical review but can crowd charts on dense timeframes.
Plot Running Segment — Enables the curved polyline for live RSI trace. Default: true. Trade-offs: Visualizes intra-segment flow; disable for cleaner panes.
Running RSI as Label — Displays current running RSI as a forward-projected label on the last bar. Default: false. Trade-offs: Useful for quick reads; may overlap in tight scales.
Show Switch Label — Activates RSI pane labels on directional switches. Default: true. Trade-offs: Provides context; omit to minimize pane clutter.
Show Switch Line (RSI) — Draws vertical dashed lines across the RSI range at switches. Default: true. Trade-offs: Marks reversal bars clearly; extends both ways for reference.
Show Solid Overlay Line — Projects a horizontal line from switch price forward. Default: true. Trade-offs: Acts as dynamic support/resistance; wider lines enhance visibility.
Show Dashed Overlay Line — Tracks a dashed line from switch to current close. Default: true. Trade-offs: Shows price deviation; thinner for subtlety.
Show Percent Change Label — Midpoint label tracking percent move from switch. Default: true. Trade-offs: Quantifies progress; centers dynamically.
Show Trend Strength Table — Displays right-side table with direction header and RSI bar. Default: true. Trade-offs: Instant strength gauge; fixed position avoids overlap.
Activate Visualization After N Bars — Delays signals until this many bars into a segment. Default: 3. Trade-offs: Filters immature readings; higher values miss early momentum.
Segment End Label — Color for completed RSI labels. Default: 7E57C2. Trade-offs: Purple tones for finality.
Running RSI — Color for polyline and running elements. Default: yellow. Trade-offs: Bright for live tracking.
Long — Color for bullish switch visuals. Default: green. Trade-offs: Standard for uptrends.
Short — Color for bearish switch visuals. Default: red. Trade-offs: Standard for downtrends.
Solid Line Width — Thickness of horizontal overlay line. Default: 2. Trade-offs: Bolder for emphasis on key levels.
Dashed Line Width — Thickness of tracking and vertical lines. Default: 1. Trade-offs: Finer to avoid dominance.
Reading & Interpretation
Completed segment RSIs appear as static points or labels in purple, indicating the fixed momentum at period close—values drifting toward the upper half suggest building strength, while lower half implies weakness. The yellow curved polyline traces the live smoothed RSI within the current segment, rising for accumulating gains and falling for losses. Directional labels and lines in green or red flag switches: green for running momentum exceeding the prior segment's, signaling potential uptrend continuation; red for the opposite.
The right table's header colors green for long, red for short, or gray for neutral/wait, with filled purple bars scaling from bottom (low RSI) to top (high), topped by the numeric value. Overlay elements project from switch bars: the solid green/red line as a price anchor, dashed tracker showing pullback extent, and percent label quantifying deviation—positive for alignment with direction, negative for counter-moves. Emojis (up arrow for long, down for short) float above/below price via ATR spacing for quick chart scans.
Practical Workflows & Combinations
- Trend Following: Enter long on green switch confirmation after a higher high in structure; filter with table strength above midpoint for conviction. Pair with volume surge for added weight.
- Exits/Stops: Trail stops to the solid overlay line on pullbacks; exit if percent change reverses beyond 2 percent against direction. Use wait bars to confirm without chasing.
- Multi-Asset/Multi-TF: Defaults suit forex/stocks on 1H-4H with daily segments; for crypto, shorten EMA to 5 for volatility. Scale segment TF to weekly for daily charts across indices.
- Combinations: Overlay on EMA clouds for confluence—switch aligning with cloud break strengthens signal. Add volatility filters like ATR bands to debounce in low-volume regimes.
Behavior, Constraints & Performance
Signals confirm on bar close within segments, with running polyline updating live but gated by minimum bars to prevent flicker. Higher timeframe changes may introduce minor repaints on timeframe switches, mitigated by relying on confirmed HTF closes rather than intrabar peeks. Resource limits cap at 500 labels/lines and 50 polylines, pruning old objects on switches to stay efficient; no explicit loops, but array growth ties to segment length—suitable for up to 500-bar histories without lag.
Known limits include delayed visualization in short segments and insensitivity to overbought/oversold levels, as thresholds are inputted but not actively visualized. Gaps in source data reset accumulators prematurely, potentially skewing early RSI.
Sensible Defaults & Quick Tuning
Start with EMA length 10, daily segments, and 3-bar wait for balanced responsiveness on hourly charts. For excessive switches in ranging markets, increase wait bars to 5 or EMA to 14 to dampen noise. If signals lag in trends, drop EMA to 5 and use 1H segments. For stable assets like indices, widen to weekly segments; tune colors for dark/light themes without altering logic.
What this indicator is—and isn’t
This tool serves as a momentum visualization and switch detector layered over price action, aiding trend identification and confirmation in segmented contexts. It is not a standalone trading system, predictive model, or risk calculator—always integrate with broader analysis, position sizing, and stop-loss discipline. View it as an enhancement for discretionary setups, not automated alerts without validation.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Luxy BIG beautiful Dynamic ORBThis is an advanced Opening Range Breakout (ORB) indicator that tracks price breakouts from the first 5, 15, 30, and 60 minutes of the trading session. It provides complete trade management including entry signals, stop-loss placement, take-profit targets, and position sizing calculations.
The ORB strategy is based on the concept that the opening range of a trading session often acts as support/resistance, and breakouts from this range tend to lead to significant moves.
What Makes This Different?
Most ORB indicators simply draw horizontal lines and leave you to figure out the rest. This indicator goes several steps further:
Multi-Stage Tracking
Instead of just one ORB timeframe, this tracks FOUR simultaneously (5min, 15min, 30min, 60min). Each stage builds on the previous one, giving you multiple trading opportunities throughout the session.
Active Trade Management
When a breakout occurs, the indicator automatically calculates and displays entry price, stop-loss, and multiple take-profit targets. These lines extend forward and update in real-time until the trade completes.
Cycle Detection
Unlike indicators that only show the first breakout, this tracks the complete cycle: Breakout → Retest → Re-breakout. You can see when price returns to test the ORB level after breaking out (potential re-entry).
Failed Breakout Warning
If price breaks out but quickly returns inside the range (within a few bars), the label changes to "FAILED BREAK" - warning you to exit or avoid the trade.
Position Sizing Calculator
Built-in risk management that tells you exactly how many shares to buy based on your account size and risk tolerance. No more guessing or manual calculations.
Advanced Filtering
Optional filters for volume confirmation, trend alignment, and Fair Value Gaps (FVG) to reduce false signals and improve win rate.
Core Features Explained
### 1. Multi-Stage ORB Levels
The indicator builds four separate Opening Range levels:
ORB 5 - First 5 minutes (fastest signals, most volatile)
ORB 15 - First 15 minutes (balanced, most popular)
ORB 30 - First 30 minutes (slower, more reliable)
ORB 60 - First 60 minutes (slowest, most confirmed)
Each level is drawn as a horizontal range on your chart. As time progresses, the ranges expand to include more price action. You can enable or disable any stage and assign custom colors to each.
How it works: During the opening minutes, the indicator tracks the highest high and lowest low. Once the time period completes, those levels become your ORB high and low for that stage.
### 2. Breakout Detection
When price closes outside the ORB range, a label appears:
BREAK UP (green label above price) - Price closed above ORB High
BREAK DOWN (red label below price) - Price closed below ORB Low
The label shows which ORB stage triggered (ORB5, ORB15, etc.) and the cycle number if tracking multiple breakouts.
Important: Signals appear on bar close only - no repainting. What you see is what you get.
### 3. Retest Detection
After price breaks out and moves away, if it returns to test the ORB level, a "RETEST" label appears (orange). This indicates:
The original breakout level is now acting as support/resistance
Potential re-entry opportunity if you missed the first breakout
Confirmation that the level is significant
The indicator requires price to move a minimum distance away before considering it a valid retest (configurable in settings).
### 4. Failed Breakout Detection
If price breaks out but returns inside the ORB range within a few bars (before the breakout is "committed"), the original label changes to "FAILED BREAK" in orange.
This warns you:
The breakout lacked conviction
Consider exiting if already in the trade
Wait for better setup
Committed Breakout: The indicator tracks how many bars price stays outside the range. Only after staying outside for the minimum number of bars does it become a committed breakout that can be retested.
### 5. TP/SL Lines (Trade Management)
When a breakout occurs, colored horizontal lines appear showing:
Entry Line (cyan for long, orange for short) - Your entry price (the ORB level)
Stop Loss Line (red) - Where to exit if trade goes against you
TP1, TP2, TP3 Lines (same color as entry) - Profit targets at 1R, 2R, 3R
These lines extend forward as new bars form, making it easy to track your trade. When a target is hit, the line turns green and the label shows a checkmark.
Lines freeze (stop updating) when:
Stop loss is hit
The final enabled take-profit is hit
End of trading session (optional setting)
### 6. Position Sizing Dashboard
The dashboard (bottom-left corner by default) shows real-time information:
Current ORB stage and range size
Breakout status (Inside Range / Break Up / Break Down)
Volume confirmation (if filter enabled)
Trend alignment (if filter enabled)
Entry and Stop Loss prices
All enabled Take Profit levels with percentages
Risk/Reward ratio
Position sizing: Max shares to buy and total risk amount
Position Sizing Example:
If your account is $25,000 and you risk 1% per trade ($250), and the distance from entry to stop loss is $0.50, the calculator shows you can buy 500 shares (250 / 0.50 = 500).
### 7. FVG Filter (Fair Value Gap)
Fair Value Gaps are price inefficiencies - gaps left by strong momentum where one candle's high doesn't overlap with a previous candle's low (or vice versa).
When enabled, this filter:
Detects bullish and bearish FVGs
Draws semi-transparent boxes around these gaps
Only allows breakout signals if there's an FVG near the breakout level
Why this helps: FVGs indicate institutional activity. Breakouts through FVGs tend to be stronger and more reliable.
Proximity setting: Controls how close the FVG must be to the ORB level. 2.0x means the breakout can be within 2 times the FVG size - a reasonable default.
### 8. Volume & Trend Filters
Volume Filter:
Requires current volume to be above average (customizable multiplier). High volume breakouts are more likely to sustain.
Set minimum multiplier (e.g., 1.5x = 50% above average)
Set "strong volume" multiplier (e.g., 2.5x) that bypasses other filters
Dashboard shows current volume ratio
Trend Filter:
Only shows breakouts aligned with a higher timeframe trend. Choose from:
VWAP - Price above/below volume-weighted average
EMA - Price above/below exponential moving average
SuperTrend - ATR-based trend indicator
Combined modes (VWAP+EMA, VWAP+SuperTrend) for stricter filtering
### 9. Pullback Filter (Advanced)
Purpose:
Waits for price to pull back slightly after initial breakout before confirming the signal.
This reduces false breakouts from immediate reversals.
How it works:
- After breakout is detected, indicator waits for a small pullback (default 2%)
- Once pullback occurs AND price breaks out again, signal is confirmed
- If no pullback within timeout period (5 bars), signal is issued anyway
Settings:
Enable Pullback Filter: Turn this filter on/off
Pullback %: How much price must pull back (2% is balanced)
Timeout (bars): Max bars to wait for pullback (5 is standard)
When to use:
- Choppy markets with many fake breakouts
- When you want higher quality signals
- Combine with Volume filter for maximum confirmation
Trade-off:
- Better signal quality
- May miss some valid fast moves
- Slight entry delay
How to Use This Indicator
### For Beginners - Simple Setup
Add the indicator to your chart (5-minute or 15-minute timeframe recommended)
Leave all default settings - they work well for most stocks
Watch for BREAK UP or BREAK DOWN labels to appear
Check the dashboard for entry, stop loss, and targets
Use the position sizing to determine how many shares to buy
Basic Trading Plan:
Wait for a clear breakout label
Enter at the ORB level (or next candle open if you're late)
Place stop loss where the red line indicates
Take profit at TP1 (50% of position) and TP2 (remaining 50%)
### For Advanced Traders - Customized Setup
Choose which ORB stages to track (you might only want ORB15 and ORB30)
Enable filters: Volume (stocks) or Trend (trending markets)
Enable FVG filter for institutional confirmation
Set "Track Cycles" mode to catch retests and re-breakouts
Customize stop loss method (ATR for volatile stocks, ORB% for stable ones)
Adjust risk per trade and account size for accurate position sizing
Advanced Strategy Example:
Enable ORB15 only (disable others for cleaner chart)
Turn on Volume filter at 1.5x with Strong at 2.5x
Enable Trend filter using VWAP
Set Signal Mode to "Track Cycles" with Max 3 cycles
Wait for aligned breakouts (Volume + Trend + Direction)
Enter on retest if you missed the initial break
### Timeframe Recommendations
5-minute chart: Scalping, very active trading, crypto
15-minute chart: Day trading, balanced approach (most popular)
30-minute chart: Swing entries, less screen time
60-minute chart: Position trading, longer holds
The indicator works on any intraday timeframe, but ORB is fundamentally a day trading strategy. Daily charts don't make sense for ORB.
DEFAULT CONFIGURATION
ON by Default:
• All 4 ORB stages (5/15/30/60)
• Breakout Detection
• Retest Labels
• All TP levels (1/1.5/2/3)
• TP/SL Lines (Detailed mode)
• Dashboard (Bottom Left, Dark theme)
• Position Size Calculator
OFF by Default (Optional Filters):
• FVG Filter
• Pullback Filter
• Volume Filter
• Trend Filter
• HTF Bias Check
• Alerts
Recommended for Beginners:
• Leave all defaults
• Session Mode: Auto-Detect
• Signal Mode: Track Cycles
• Stop Method: ATR
• Add Volume Filter if trading stocks
Recommended for Advanced:
• Enable ORB15 + ORB30 only (disable 5 & 60)
• Enable: Volume + Trend + FVG
• Signal Mode: Track Cycles, Max 3
• Stop Method: ATR or Safer
• Enable HTF Daily bias check
## Settings Guide
The settings are organized into logical groups. Here's what each section controls:
### ORB COLORS Section
Show Edge Labels: Display "ORB 5", "ORB 15" labels at the right edge of the levels
Background: Fill the area between ORB high/low with color
Transparency: How see-through the background is (95% is nearly invisible)
Enable ORB 5/15/30/60: Turn each stage on or off individually
Colors: Assign colors to each ORB stage for easy identification
### SESSION SETTINGS Section
Session Mode: Choose trading session (Auto-Detect works for most instruments)
Custom Session Hours: Define your own hours if needed (format: HHMM-HHMM)
Auto-Detect uses the instrument's natural hours (stocks use exchange hours, crypto uses 24/7).
### BREAKOUT DETECTION Section
Enable Breakout Detection: Master switch for signals
Show Retest Labels: Display retest signals
Label Size: Visual size for all labels (Small recommended)
Enable FVG Filter: Require Fair Value Gap confirmation
Show FVG Boxes: Display the gap boxes on chart
Signal Mode: "First Only" = one signal per direction per day, "Track Cycles" = multiple signals
Max Cycles: How many breakout-retest cycles to track (6 is balanced)
Breakout Buffer: Extra distance required beyond ORB level (0.1-0.2% recommended)
Min Distance for Retest: How far price must move away before retest is valid (2% recommended)
Min Bars Outside ORB: Bars price must stay outside for committed breakout (2 is balanced)
### TARGETS & RISK Section
Enable Targets & Stop-Loss: Calculate and show trade management
TP1/TP2/TP3 checkboxes: Select which profit targets to display
Stop Method: How to calculate stop loss placement
- ATR: Based on volatility (best for most cases)
- ORB %: Fixed % of ORB range
- Swing: Recent swing high/low
- Safer: Widest of all methods
ATR Length & Multiplier: Controls ATR stop distance (14 period, 1.5x is standard)
ORB Stop %: Percentage beyond ORB for stop (20% is balanced)
Swing Bars: Lookback period for swing high/low (3 is recent)
### TP/SL LINES Section
Show TP/SL Lines: Display horizontal lines on chart
Label Format: "Short" = minimal text, "Detailed" = shows prices
Freeze Lines at EOD: Stop extending lines at session close
### DASHBOARD Section
Show Info Panel: Display the metrics dashboard
Theme: Dark or Light colors
Position: Where to place dashboard on chart
Toggle rows: Show/hide specific information rows
Calculate Position Size: Enable the position sizing calculator
Risk Mode: Risk fixed $ amount or % of account
Account Size: Your total trading capital
Risk %: Percentage to risk per trade (0.5-1% recommended)
### VOLUME FILTER Section
Enable Volume Filter: Require volume confirmation
MA Length: Average period (20 is standard)
Min Volume: Required multiplier (1.5x = 50% above average)
Strong Volume: Multiplier that bypasses other filters (2.5x)
### TREND FILTER Section
Enable Trend Filter: Require trend alignment
Trend Mode: Method to determine trend (VWAP is simple and effective)
Custom EMA Length: If using EMA mode (50 for swing, 20 for day trading)
SuperTrend settings: Period and Multiplier if using SuperTrend mode
### HIGHER TIMEFRAME Section
Check Daily Trend: Display higher timeframe bias in dashboard
Timeframe: What TF to check (D = daily, recommended)
Method: Price vs MA (stable) or Candle Direction (reactive)
MA Period: EMA length for Price vs MA method (20 is balanced)
Min Strength %: Minimum strength threshold for HTF bias to be considered
- For "Price vs MA": Minimum distance (%) from moving average
- For "Candle Direction": Minimum candle body size (%)
- 0.5% is balanced - increase for stricter filtering
- Lower values = more signals, higher values = only strong trends
### ALERTS Section
Enable Alerts: Master switch (must be ON to use any alerts)
Breakout Alerts: Notify on ORB breakouts
Retest Alerts: Notify when price retests after breakout
Failed Break Alerts: Notify on failed breakouts
Stage Complete Alerts: Notify when each ORB stage finishes forming
After enabling desired alert types, click "Create Alert" button, select this indicator, choose "Any alert() function call".
## Tips & Best Practices
### General Trading Tips
ORB works best on liquid instruments (stocks with good volume, major crypto pairs)
First hour of the session is most important - that's when ORB is forming
Breakouts WITH the trend have higher success rates - use the trend filter
Failed breakouts are common - use the "Min Bars Outside" setting to filter weak moves
Not every day produces good ORB setups - be patient and selective
### Position Sizing Best Practices
Never risk more than 1-2% of your account on a single trade
Use the built-in calculator - don't guess your position size
Update your account size monthly as it grows
Smaller accounts: use $ Amount mode for simplicity
Larger accounts: use % of Account mode for scaling
### Take Profit Strategy
Most traders use: 50% at TP1, 50% at TP2
Aggressive: Hold through TP1 for TP2 or TP3
Conservative: Full exit at TP1 (1:1 risk/reward)
After TP1 hits, consider moving stop to breakeven
TP3 rarely hits - only on strong trending days
### Filter Combinations
Maximum Quality: Volume + Trend + FVG (fewest signals, highest quality)
Balanced: Volume + Trend (good quality, reasonable frequency)
Active Trading: No filters or Volume only (many signals, lower quality)
Trending Markets: Trend filter essential (indices, crypto)
Range-Bound: Volume + FVG (avoid trend filter)
### Common Mistakes to Avoid
Chasing breakouts - wait for the bar to close, don't FOMO into wicks
Ignoring the stop loss - always use it, move it manually if needed
Over-leveraging - the calculator shows MAX shares, you can buy less
Trading every signal - quality > quantity, use filters
Not tracking results - keep a journal to see what works for YOU
## Pros and Cons
### Advantages
Complete all-in-one solution - from signal to position sizing
Multiple timeframes tracked simultaneously
Visual clarity - easy to see what's happening
Cycle tracking catches opportunities others miss
Built-in risk management eliminates guesswork
Customizable filters for different trading styles
No repainting - what you see is locked in
Works across multiple markets (stocks, forex, crypto)
### Limitations
Intraday strategy only - doesn't work on daily charts
Requires active monitoring during first 1-2 hours of session
Not suitable for after-hours or extended sessions by default
Can produce many signals in choppy markets (use filters)
Dashboard can be overwhelming for complete beginners
Performance depends on market conditions (trends vs ranges)
Requires understanding of risk management concepts
### Best For
Day traders who can watch the first 1-2 hours of market open
Traders who want systematic entry/exit rules
Those learning proper position sizing and risk management
Active traders comfortable with multiple signals per day
Anyone trading liquid instruments with clear sessions
### Not Ideal For
Swing traders holding multi-day positions
Set-and-forget / passive investors
Traders who can't watch market open
Complete beginners unfamiliar with trading concepts
Low volume / illiquid instruments
## Frequently Asked Questions
Q: Why are no signals appearing?
A: Check that you're on an intraday timeframe (5min, 15min, etc.) and that the current time is within your session hours. Also verify that "Enable Breakout Detection" is ON and at least one ORB stage is enabled. If using filters, they might be blocking signals - try disabling them temporarily.
Q: What's the best ORB stage to use?
A: ORB15 (15 minutes) is most popular and balanced. ORB5 gives faster signals but more noise. ORB30 and ORB60 are slower but more reliable. Many traders use ORB15 + ORB30 together.
Q: Should I enable all the filters?
A: Start with no filters to see all signals. If too many false signals, add Volume filter first (stocks) or Trend filter (trending markets). FVG filter is most restrictive - use for maximum quality but fewer signals.
Q: How do I know which stop loss method to use?
A: ATR works for most cases - it adapts to volatility. Use ORB% if you want predictable stop placement. Swing is for respecting chart structure. Safer gives you the most room but largest risk.
Q: Can I use this for swing trading?
A: Not really - ORB is fundamentally an intraday strategy. The ranges reset each day. For swing trading, look at weekly support/resistance or moving averages instead.
Q: Why do TP/SL lines disappear sometimes?
A: Lines freeze (stop extending) when: stop loss is hit, the last enabled take-profit is hit, or end of session arrives (if "Freeze at EOD" is enabled). This is intentional - the trade is complete.
Q: What's the difference between "First Only" and "Track Cycles"?
A: "First Only" shows one breakout UP and one DOWN per day maximum - clean but might miss opportunities. "Track Cycles" shows breakout-retest-rebreak sequences - more signals but busier chart.
Q: Is position sizing accurate for options/forex?
A: The calculator is designed for shares (stocks). For options, ignore the share count and use the risk amount. For forex, you'll need to adapt the lot size calculation manually.
Q: How much capital do I need to use this?
A: The indicator works for any account size, but practical day trading typically requires $25,000 in the US due to Pattern Day Trader rules. Adjust the "Account Size" setting to match your capital.
Q: Can I backtest this strategy?
A: This is an indicator, not a strategy script, so it doesn't have built-in backtesting. You can visually review historical signals or code a strategy script using similar logic.
Q: Why does the dashboard show different entry price than the breakout label?
A: If you're looking at an old breakout, the ORB levels may have changed when the next stage completed. The dashboard always shows the CURRENT active range and trade setup.
Q: What's a good win rate to expect?
A: ORB strategies typically see 40-60% win rate depending on market conditions and filters used. The strategy relies on positive risk/reward ratios (2:1 or better) to be profitable even with moderate win rates.
Q: Does this work on crypto?
A: Yes, but crypto trades 24/7 so you need to define what "session start" means. Use Session Mode = Custom and set your preferred daily reset time (e.g., 0000-2359 UTC).
## Credits & Transparency
### Development
This indicator was developed with the assistance of AI technology to implement complex ORB trading logic.
The strategy concept, feature specifications, and trading logic were designed by the publisher. The implementation leverages modern development tools to ensure:
Clean, efficient, and maintainable code
Comprehensive error handling and input validation
Detailed documentation and user guidance
Performance optimization
### Trading Concepts
This indicator implements several public domain trading concepts:
Opening Range Breakout (ORB): Trading strategy popularized by Toby Crabel, Mark Fisher and many more talanted traders.
Fair Value Gap (FVG): Price imbalance concept from ICT methodology
SuperTrend: ATR-based trend indicator using public formula
Risk/Reward Ratio: Standard risk management principle
All mathematical formulas and technical concepts used are in the public domain.
### Pine Script
Uses standard TradingView built-in functions:
ta.ema(), ta.atr(), ta.vwap(), ta.highest(), ta.lowest(), request.security()
No external libraries or proprietary code from other authors.
## Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice.
Trading involves substantial risk of loss and is not suitable for every investor. Past performance shown in examples is not indicative of future results.
The indicator provides signals and calculations, but trading decisions are solely your responsibility. Always:
Test strategies on paper before using real money
Never risk more than you can afford to lose
Understand that all trading involves risk
Consider seeking advice from a licensed financial advisor
The publisher makes no guarantees regarding accuracy, profitability, or performance. Use at your own risk.
---
Version: 3.0
Pine Script Version: v6
Last Updated: October 2024
For support, questions, or suggestions, please comment below or send a private message.
---
Happy trading, and remember: consistent risk management beats perfect entry timing every time.
Holt Damped Forecast [CHE]A Friendly Note on These Pine Script Scripts
Hey there! Just wanted to share a quick, heartfelt heads-up: All these Pine Script examples come straight from my own self-study adventures as a total autodidact—think late nights tinkering and learning on my own. They're purely for educational vibes, helping me (and hopefully you!) get the hang of Pine Script basics, cool indicators, and building simple strategies.
That said, please know this isn't any kind of financial advice, investment nudge, or pro-level trading blueprint. I'd love for you to dive in with your own research, run those backtests like a champ, and maybe bounce ideas off a qualified expert before trying anything in a real trading setup. No guarantees here on performance or spot-on accuracy—trading's got its risks, and those are totally on each of us.
Let's keep it fun and educational—happy coding! 😊
Holt Damped Forecast — Damped trend forecasts with fan bands for uncertainty visualization and momentum integration
Summary
This indicator applies damped exponential smoothing to generate forward price forecasts, displaying them as probabilistic fan bands to highlight potential ranges rather than point estimates. It incorporates residual-based uncertainty to make projections more reliable in varying market conditions, reducing overconfidence in strong trends. Momentum from the trend component is shown in an optional label alongside signals, aiding quick assessment of direction and strength without relying on lagging oscillators.
Motivation: Why this design?
Standard exponential smoothing often extrapolates trends indefinitely, leading to unrealistic forecasts during mean reversion or weakening momentum. This design uses damping to gradually flatten long-term projections, better suiting real markets where trends fade. It addresses the need for visual uncertainty in forecasts, helping traders avoid entries based on overly optimistic point predictions.
What’s different vs. standard approaches?
- Reference baseline: Diverges from basic Holt's linear exponential smoothing, which assumes persistent trends without decay.
- Architecture differences:
- Adds damping to the trend extrapolation for finite-horizon realism.
- Builds fan bands from historical residuals for probabilistic ranges at multiple confidence levels.
- Integrates a dynamic label combining forecast details, scaled momentum, and directional signals.
- Applies tail background coloring to recent bars based on forecast direction for immediate visual cues.
- Practical effect: Charts show converging forecast bands over time, emphasizing shorter horizons where accuracy is higher. This visibly tempers aggressive projections in trends, making it easier to spot when uncertainty widens, which signals potential reversals or consolidation.
How it works (technical)
The indicator maintains two persistent components: a level tracking the current price baseline and a trend capturing directional slope. On each bar, the level updates by blending the current source price with a one-step-ahead expectation from the prior level and damped trend. The trend then adjusts by weighting the change in level against the prior damped trend. Forecasts extend this forward over a user-defined number of steps, with damping ensuring the trend influence diminishes over distance.
Uncertainty derives from the standard deviation of historical residuals—the differences between actual prices and one-step expectations—scaled by the damping structure for the forecast horizon. Bands form around the median forecast at specified confidence intervals using these scaled errors. Initialization seeds the level to the first bar's price and trend to zero, with persistence handling subsequent updates. A security call fetches the last bar index for tail logic, using lookahead to align with realtime but introducing minor repaint on unconfirmed bars.
Parameter Guide
The Source parameter selects the price input for level and residual calculations, defaulting to close; consider using high or low for assets sensitive to volatility, as close works well for most trend-following setups. Forecast Steps (h) defines the number of bars ahead for projections, defaulting to 4—shorter values like 1 to 5 suit intraday trading, while longer ones may widen bands excessively in choppy conditions. The Color Scheme (2025 Trends) option sets the base, up, and down colors for bands, labels, and backgrounds, starting with Ruby Dawn; opt for serene schemes on clean charts or vibrant ones to stand out in dark themes.
Level Smoothing α controls the responsiveness of the price baseline, defaulting to 0.3—values above 0.5 enhance tracking in fast markets but may amplify noise, whereas lower settings filter disturbances better. Trend Smoothing β adjusts sensitivity to slope changes, at 0.1 by default; increasing to 0.2 helps detect emerging shifts quicker, but keeping it low prevents whipsaws in sideways action. Damping φ (0..1) governs trend persistence, defaulting to 0.8—near 0.9 preserves carryover in sustained moves, while closer to 0.5 curbs overextensions more aggressively.
Show Fan Bands (50/75/95) toggles the probabilistic range display, enabled by default; disable it in oscillator panes to reduce clutter, but it's key for overlay forecasts. Residual Window (Bars) sets the length for deviation estimates, at 400 bars initially—100 to 200 works for short timeframes, and 500 or more adds stability over extended histories. Line Width determines the thickness of band and median lines, defaulting to 2; go thicker at 3 to 5 for emphasis on higher timeframes or thinner for layered indicators.
Show Median/Forecast Line reveals the central projection, on by default—hide if bands provide enough detail, or keep for pinpoint entry references. Show Integrated Label activates the combined view of forecast, momentum, and signal, defaulting to true; it's right-aligned for convenience, so turn it off on smaller screens to save space. Show Tail Background colors the last few bars by forecast direction, enabled initially; pair low transparency for subtle hints or higher for bolder emphasis.
Tail Length (Bars) specifies bars to color backward from the current one, at 3 by default—1 to 2 fits scalping, while 5 or more underscores building momentum. Tail Transparency (%) fades the background intensity, starting at 80; 50 to 70 delivers strong signals, and 90 or above allows seamless blending. Include Momentum in Label adds the scaled trend value, defaulting to true—ATR% scaling here offers relative strength context across assets.
Include Long/Short/Neutral Signal in Label displays direction from the trend sign, on by default; neutral helps in ranging markets, though it can be overlooked during strong trends. Scaling normalizes momentum output (raw, ATR-relative, or level-relative), set to ATR% initially—ATR% ensures cross-asset comparability, while %Level provides percentage perspectives. ATR Length defines the period for true range averaging in scaling, at 14; align it with your chart timeframe or shorten for quicker volatility responses.
Decimals sets precision in the momentum label, defaulting to 2—0 to 1 yields clean integers, and 3 or more suits detailed forex views. Show Zero-Cross Markers places arrows at direction changes, enabled by default; keep size small to minimize clutter, with text labels for fast scanning.
Reading & Interpretation
Fan bands expand outward from the current bar, with the median line as the central forecast—narrower bands indicate lower uncertainty, wider suggest caution. Colors tint up (positive forecast vs. prior level) in the scheme's up hue and down otherwise. The optional label lists the horizon, median, and range brackets at 50%, 75%, and 95% levels, followed by momentum (scaled per mode) and signal (Long if positive trend, Short if negative, Neutral if zero). Zero-cross arrows mark trend flips: upward triangle below bar for bullish cross, downward above for bearish. Tail background reinforces the forecast direction on recent bars.
Practical Workflows & Combinations
- Trend following: Enter long on upward zero-cross if median forecast rises above price and bands contain it; confirm with higher highs/lows. Short on downward cross with falling median.
- Exits/Stops: Trail stops below 50% lower band in longs; exit if momentum drifts negative or signal turns neutral. Use wider bands (75/95%) for conservative holds in volatile regimes.
- Multi-asset/Multi-TF: Defaults work across stocks, forex, crypto on 5m-1D; scale steps by TF (e.g., 10+ on daily). Layer with volume or structure tools—avoid over-reliance on isolated crosses.
Behavior, Constraints & Performance
Closed-bar logic ensures stable historical plots, but realtime updates via security lookahead may shift forecasts until bar confirmation, introducing minor repaint on the last bar. No explicit HTF calls beyond bar index fetch, minimizing gaps but watch for low-liquidity assets. Resources include a 2000-bar lookback for residuals and up to 500 labels, with no loops—efficient for most charts. Known limits: Early bars show wide bands due to sparse residuals; assumes stationary errors, so gaps or regime shifts widen inaccuracies.
Sensible Defaults & Quick Tuning
Start with defaults for balanced smoothing on 15m-4H charts. For choppy conditions (too many crosses), lower β to 0.05 and raise residual window to 600 for stability. In trending markets (sluggish signals), increase α/β to 0.4/0.2 and shorten steps to 2. If bands overexpand, boost φ toward 0.95 to preserve trend carry. Tune colors for theme fit without altering logic.
What this indicator is—and isn’t
This is a visualization and signal layer for damped forecasts and momentum, complementing price action analysis. It isn’t a standalone system—pair with risk rules and broader context. Not predictive beyond the horizon; use for confirmation, not blind entries.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Trading Toolkit - Comprehensive AnalysisTrading Toolkit – Comprehensive Analysis
A unified trading analysis toolkit with four sections:
📊 Company Info
Fundamentals, market cap, sector, and earnings countdown.
📅 Performance
Date‑range analysis with key metrics.
🎯 Market Sentiment
CNN‑style Fear & Greed Index (7 components) + 150‑SMA positioning.
🛡️ Risk Levels
ATR/MAD‑based stop‑loss and take‑profit calculations.
Key Features
CNN‑style Fear & Greed approximation using:
Momentum: S&P 500 vs 125‑DMA
Price Strength: NYSE 52‑week highs vs lows
Market Breadth: McClellan Volume Summation (Up/Down volume)
Put/Call Ratio: 5‑day average (inverted)
Volatility: VIX vs 50‑DMA (inverted)
Safe‑Haven Demand: 20‑day SPY–IEF return spread
Junk‑Bond Demand: HY vs IG credit spread (inverted)
Normalization: z‑score → percentile (0–100) with ±3 clipping.
CNN‑aligned thresholds:
Extreme Fear: 0–24 | Fear: 25–44 | Neutral: 45–54 | Greed: 55–74 | Extreme Greed: 75+.
Risk tools: ATR & MAD volatility measures with configurable multipliers.
Flexible layout: vertical or side‑by‑side columns.
Data Sources
S&P 500: CBOE:SPX or AMEX:SPY
NYSE: INDEX:HIGN, INDEX:LOWN, USI:UVOL, USI:DVOL
Options: USI:PCC (Total PCR), fallback INDEX:CPCS (Equity PCR)
Volatility: CBOE:VIX
Treasuries: NASDAQ:IEF
Credit Spreads: FRED:BAMLH0A0HYM2, FRED:BAMLC0A0CM
Risk Management
ATR risk bands: 🟢 ≤3%, 🟡 3–6%, ⚪ 6–10%, 🟠 10–15%, 🔴 >15%
MAD‑based stop‑loss and take‑profit calculations.
Author: Daniel Dahan
(AI Generated, Merged & enhanced version with CNN‑style Fear & Greed)
Fib OscillatorWhat is Fib Oscillator and How to Use it?
🔶 1. Conceptual Overview
The Fib Oscillator is a Fibonacci-based relative position oscillator.
Instead of measuring momentum (like RSI or MACD), it measures where price currently sits between the recent swing high and swing low, expressed as a percentage within the Fibonacci range.
In other words:
It answers: “Where is price right now within its most recent dynamic range?”
It visualizes retracement and extension zones numerically, providing continuous feedback between 0% and 100% (and beyond if extended).
🔶 2. What the Script Does
The indicator:
Automatically detects recent high and low levels using an adaptive lookback window, which depends on ATR volatility.
Calculates the current price’s position between those levels as a percentage (0–100).
Plots that percentage as an oscillator — showing visually whether price is near the top, middle, or bottom of its recent range.
Overlays Fibonacci retracement levels (23.6%, 38.2%, 50%, 61.8%, 78.6%) as reference zones.
Generates alerts when the oscillator crosses key Fib thresholds — which can signal retracement completion, breakout potential, or pullback exhaustion.
🔶 3. Technical Flow Breakdown
(a) Inputs
Input Description Default Notes
atrLength ATR period used for volatility estimation 14 Used to dynamically tune lookback sensitivity
minLookback Minimum lookback window (candles) 20 Ensures stability even in low volatility
maxLookback Maximum lookback window 100 Limits over-expansion during high volatility
isInverse Inverts chart orientation false Useful for inverse markets (e.g. shorts or inverse BTC view)
(b) Volatility-Adaptive Lookback
Instead of using a fixed lookback, it calculates:
lookback
=
SMA(ATR,10)
/
SMA(Close,10)
×
500
lookback=SMA(ATR,10)/SMA(Close,10)×500
Then it clamps this between minLookback and maxLookback.
This makes the oscillator:
More reactive during high volatility (shorter lookback)
More stable during calm markets (longer lookback)
Essentially, it self-adjusts to market rhythm — you don’t have to constantly tweak lookback manually.
(c) High-Low Reference Points
It takes the highest and lowest points within the dynamic lookback window.
If isInverse = true, it flips the candle logic (useful if viewing inverse instruments like stablecoin pairs or when analyzing bearish setups invertedly).
(d) Oscillator Core
The main oscillator line:
osc
=
(
close
−
low
)
(
high
−
low
)
×
100
osc=
(high−low)
(close−low)
×100
0% = Price is at the lookback low.
100% = Price is at the lookback high.
50% = Midpoint (balanced).
Between Fibonacci percentages (23.6%, 38.2%, 61.8%, etc.), the oscillator indicates retracement stages.
(e) Fibonacci Levels as Reference
It overlays horizontal reference lines at:
0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, 100%
These act as support/resistance bands in oscillator space.
You can read it similar to how traders use Fibonacci retracements on charts, but compressed into a single line oscillator.
(f) Alerts
The script includes built-in alert conditions for crossovers at each major Fibonacci level.
You can set TradingView alerts such as:
“Oscillator crossed above 61.8%” → possible bullish continuation or breakout.
“Oscillator crossed below 38.2%” → possible pullback or correction starting.
This allows automated monitoring of fib retracement completions without manually drawing fib levels.
🔶 4. How to Use It
🔸 Visual Interpretation
Oscillator Value Zone Market Context
0–23.6% Deep Retracement Potential exhaustion of a down-move / early reversal
23.6–38.2% Shallow retracement zone Possible continuation phase
38.2–50% Mid retracement Neutral or indecisive structure
50–61.8% Key pivot region Common trend resumption zone
61.8–78.6% Late retracement Often “last pullback” area
78.6–100% Near high range Possible overextension / profit-taking
>100% Range breakout New leg formation / expansion
🔸 Practical Application Steps
Load the indicator on your chart (set overlay = false, so it’s below the main price chart).
Observe oscillator position relative to fib bands:
Use it to determine retracement depth.
Combine with structure tools:
Trend lines, swing points, or HTF market structure.
Use crossovers for timing:
Crossing above 61.8% in an uptrend often confirms breakout continuation.
Crossing below 38.2% in a downtrend signals renewed downside momentum.
For range markets, oscillator swings between 23.6% and 78.6% can define accumulation/distribution boundaries.
🔶 5. When to Use It
During Retracements: To gauge how deep the pullback has gone.
During Range Markets: To identify relative overbought/oversold positions.
Before Breakouts: Crossovers of 61.8% or 78.6% often precede impulsive moves.
In Multi-Timeframe Contexts:
LTF (15M–1H): Detect intraday retracement exhaustion.
HTF (4H–1D): Confirm major range expansions or key reversal zones.
🔶 6. Ideal Companion Indicators
The Fib Oscillator works best when contextualized with structure, volatility, and trend bias indicators.
Below are optimal pairings:
Companion Indicator Purpose Integration Insight
Market Structure MTF Tool Identify active trend direction Use Fib Oscillator only in trend direction for cleaner signals
EMA Ribbon / Supertrend Trend confirmation Align oscillator crossovers with EMA bias
ATR Bands / Volatility Envelope Validate breakout strength If oscillator >78.6% & ATR rising → valid breakout
Volume Oscillator Confirm retracement strength Volume contraction + oscillator under 38.2% → potential reversal
HTF Fib Retracement Tool Combine LTF oscillator with HTF fib confluence Powerful multi-timeframe setups
RSI or Stochastic Measure momentum relative to position RSI divergence while oscillator near 78.6% → exhaustion clue
🔶 7. Understanding the Settings
Setting Function Practical Impact
ATR Period (14) Controls volatility sampling Higher = smoother lookback adaptation
Min Lookback (20) Smallest window allowed Lower = more reactive but noisier
Max Lookback (100) Largest window allowed Higher = smoother but slower to react
Inverse Candle Chart Flips oscillator vertically Useful when analyzing bearish or inverse scenarios (e.g. short-side fib mapping)
Recommended Configs:
For scalping/intraday: ATR 10–14, lookback 20–50
For swing/position trading: ATR 14–21, lookback 50–100
🔶 8. Example Trade Logic (Practical Use)
Scenario: Uptrend on 4H chart
Oscillator drops to below 38.2% → retracement zone
Price consolidates → oscillator stabilizes
Oscillator crosses above 50% → pullback ending
Entry: Long when oscillator crosses above 61.8%
Exit: Near 78.6–100% zone or upon divergence with RSI
For Short Bias (Inverse Setup):
Enable isInverse = true to visually flip the oscillator (so lows become highs).
Use the same thresholds inversely.
🔶 9. Strengths & Limitations
✅ Strengths
Dynamic, self-adapting to volatility
Quantifies Fib retracement as a continuous function
Compact oscillator view (no clutter on chart)
Works well across all timeframes
Compatible with both trending and ranging markets
⚠️ Limitations
Doesn’t define trend direction — must be used with structure filters
Can whipsaw during choppy consolidations
The “lookback auto-adjust” may lag in sudden volatility shifts
Shouldn’t be used standalone for entries without structural confluence
🔶 10. Summary
The “Fib Oscillator” is a dynamic Fibonacci-relative positioning tool that merges retracement theory with adaptive volatility logic.
It gives traders an intuitive, quantified view of where price sits within its recent fib range, allowing anticipation of pullbacks, reversals, or breakout momentum.
Think of it as a "Fibonacci RSI", but instead of momentum strength, it shows positional depth — the vibrational location of price within its natural swing cycle.
Relative Valuation OscillatorRelative Valuation Oscillator (RVO) Description
The Valuation_OTC.pine script is a Relative Valuation Oscillator for TradingView that compares the current asset against a reference asset (like Bitcoin, S&P 500, or Gold) to determine if it's relatively overvalued or undervalued.
Key Features:
1. Multiple Calculation Methods:
Simple Ratio - Compares price ratio deviation from average
Percentage Difference - Direct percentage comparison between assets
Ratio Z-Score - Statistical measure (standard deviations from mean)
Rate of Change Comparison - Compares momentum/performance
Normalized Ratio - 0-100 scale centered at zero
2. Customizable Settings:
Reference asset selection (default: BTC/USDT)
Adjustable lookback period (10-500 bars)
Optional smoothing with configurable period
Overbought/oversold level thresholds (default: ±1.5)
3. Trading Signals:
Overvalued - Oscillator above overbought level (red zone)
Undervalued - Oscillator below oversold level (green zone)
Neutral - Between thresholds
Crossover alerts for key levels
Divergence detection (bullish/bearish)
4. Visual Components:
Color-coded oscillator line (green when positive, red when negative)
Optional signal line for additional smoothing
Background shading for valuation zones
Information table showing current metrics and status
Shape markers for crossovers and divergences
5. Alert Conditions:
Overvalued/undervalued alerts
Zero-line crossovers
Divergence signals
This indicator is useful for pairs trading, relative strength analysis, and identifying when an asset is trading at extremes relative to a benchmark asset.
SPX / Silver (XAGUSD) RatioThis script visualizes the S&P 500 Index to Silver ratio (SPX/Silver) — a powerful tool for monitoring the relative strength of equities vs. precious metals over time.
📊 Use Case:
Helps traders assess macro sentiment shifts between risk-on (equities) and risk-off (commodities).
A rising ratio indicates equity outperformance vs Silver, often in growth-driven bull markets.
A falling ratio suggests Silver is outperforming — potentially due to inflation, geopolitical risk, or weakening equities.
⚙️ Data & Calculation:
SPX: SP:SPX (S&P 500 Index)
Silver: TVC:SILVER
Formula:
SPX / Silver
(Both are spot/index prices, updated on daily timeframe)
📈 Interpretation:
📈 Ratio Rising → SPX outperforming Silver → Risk-on sentiment
📉 Ratio Falling → Silver outperforming SPX → Possible flight to safety or inflation hedge
🧠 Ideal For:
Macro trend analysis
Intermarket strategy development
Asset rotation decision-making
Spotting Silver bottoms during SPX/Silver peak zones
Experimental Supertrend [CHE]Experimental Supertrend — Combines EMA crossovers for trend regime detection with an adaptive ATR-based hull that selects the narrowest band to contain recent highs and lows, minimizing false breaks in varying volatility.
Summary
This indicator overlays a dynamic supertrend boundary around a midline derived from dual EMAs, using EMA crossovers to switch between bullish and bearish regimes. The hull adapts by evaluating multiple ATR periods and selecting the tightest one that fully encloses price action over a specified window, which helps in creating more stable trend lines that hug price without excessive gaps or breaches. Fills between the midline and hull provide visual cues for trend strength, darkening temporarily after regime changes to highlight transitions. Alerts trigger on crossovers, and markers label entry points, making it suitable for trend-following setups where standard supertrends might whipsaw. Overall, it offers robustness through auto-adjustment, reducing sensitivity to noise while maintaining responsiveness to genuine shifts.
Motivation: Why this design?
Standard supertrend indicators often flip prematurely in choppy markets due to fixed multipliers that do not account for localized volatility patterns, leading to frequent false signals and eroded confidence in trends. This design addresses that by incorporating an EMA-based regime filter for directional bias and an auto-adaptive hull that dynamically tunes the band width based on recent price containment needs. By prioritizing the narrowest effective enclosure, it avoids over-wide bands in calm periods that cause lag or under-wide ones in volatility spikes that invite breaks, providing a more consistent trailing reference without manual tweaking.
What’s different vs. standard approaches?
- Reference baseline: Diverges from the classic ATR-multiplier supertrend, which uses a single fixed period and constant factor applied to close or high/low deviations.
- Architecture differences:
- Auto-selection from candidate ATR lengths to find the optimal period for current conditions.
- Dynamic multiplier clamped between floor and cap values, adjusted by padding to ensure reliable containment.
- Regime-gated rendering, where hull position flips based on EMA relative positioning.
- Post-transition visual fading to emphasize change points without altering core logic.
- Practical effect: Charts show tighter, more reactive bands that rarely breach during trends, reducing visual clutter from flips; the adaptive nature means less intervention across assets, as the hull self-adjusts to volatility clusters rather than applying a one-size-fits-all scale.
How it works (technical)
The indicator first computes two EMAs from close prices using lengths derived from a preset pair or manual inputs, establishing a midline as their average. This midline serves as the central reference for the hull. True range values are then smoothed into multiple ATR candidates using exponential weighting over the specified lengths. For each candidate, deviations of recent highs and lows from the midline are ratioed against the ATR to determine a required multiplier that would enclose all extremes in the containment window—the highest ratio plus padding sets the base, clamped to user-defined bounds. Among valid candidates (those with sufficient history), the one yielding the narrowest overall band width is selected. The hull boundaries are then offset from the midline by this multiplier times the chosen ATR, and further smoothed with a fixed EMA to reduce jitter. Regime direction from EMA comparison gates which boundary acts as support or resistance, with initialization seeding arrays on the first bar to handle state persistence. No higher timeframe data is used, so all logic runs on the chart's native bars without lookahead.
Parameter Guide
EMA Pair — Selects preset lengths for fast and slow EMAs, influencing regime sensitivity and midline stability. Default: "21/55". Trade-offs/Tips: Faster pairs like "9/21" increase cross frequency for scalping but raise false signals; slower like "50/200" smooths for swings, potentially missing early turns. Use Manual for fine control.
Manual Fast — Sets fast EMA length when Manual mode is active; shorter values make regime switches quicker. Default: 21. Trade-offs/Tips: Lower than 10 risks over-reactivity; pair with slow at least double for clear separation.
Manual Slow — Sets slow EMA length when Manual mode is active; longer values anchor the midline more firmly. Default: 55. Trade-offs/Tips: Above 100 adds lag in trends; balance with fast to avoid perpetual neutrality.
ATR Lengths (comma-separated) — Defines candidate periods for ATR smoothing; more options allow finer auto-selection. Default: "7,10,14,21,28,35". Trade-offs/Tips: Fewer candidates speed computation but may miss optimal fits; keep under 10 for efficiency.
Containment Window — Number of recent bars the hull must fully enclose highs/lows of; larger windows favor stability. Default: 50. Trade-offs/Tips: Shorter (under 20) adapts faster to breaks but increases breach risk; longer smooths but delays response.
Min Multiplier Floor — Lowest allowed multiplier for hull width; prevents overly tight bands in low volatility. Default: 0.5. Trade-offs/Tips: Raise to 0.75 for conservative enclosures; too low allows pinches that flip easily.
Max Multiplier Cap — Highest allowed multiplier; caps expansion in spikes to avoid wide, lagging bands. Default: 1.0. Trade-offs/Tips: Lower to 0.75 tightens overall; higher permits more room but risks detachment from price.
Padding (+) — Adds buffer to the auto-multiplier for safer containment without exact touches. Default: 0.05. Trade-offs/Tips: Increase to 0.10 in gappy markets; minimal values hug closer but may still breach on outliers.
Fill Between (Mid ↔ Supertrend) — Toggles shaded area between midline and active hull for trend visualization. Default: true. Trade-offs/Tips: Disable for cleaner charts; pairs well with transparency tweaks.
Base Fill Transparency (0..100) — Sets default opacity of fills; higher values make them subtler. Default: 80. Trade-offs/Tips: Under 50 overwhelms price action; adjust with darken boost for emphasis.
Darken on Trend Change — Enables temporary opacity increase after regime shifts to spotlight transitions. Default: true. Trade-offs/Tips: Off for steady visuals; on aids spotting reversals in real-time.
Darken Fade Bars — Duration in bars for the darken effect to ramp back to base; longer prolongs highlight. Default: 8. Trade-offs/Tips: Shorter (4-6) for fast-paced charts; longer holds attention on changes.
Darken Boost at Change (Δ transp) — Intensity of opacity reduction at crossover; higher values make shifts more prominent. Default: 50. Trade-offs/Tips: Cap at 70 to avoid blackout; tune down if fades obscure details.
Show Supertrend Line — Displays the active hull boundary as a line. Default: true. Trade-offs/Tips: Hide for fill-only views; linewidth fixed at 3 for visibility.
Show EMA Cross Markers — Places circles and labels at crossover points for entry cues. Default: true. Trade-offs/Tips: Disable in clutter; labels show "Buy"/"Sell" at absolute positions.
Alert: EMA Cross Up (Long) — Triggers notification on bullish crossover. Default: true. Trade-offs/Tips: Pair with filters; once-per-bar frequency.
Alert: EMA Cross Down (Short) — Triggers notification on bearish crossover. Default: true. Trade-offs/Tips: Use for exits; ensure broker integration.
Show Debug — Reveals internal diagnostics like selected ATR details (if implemented). Default: false. Trade-offs/Tips: Enable for troubleshooting selections; minimal overhead.
Reading & Interpretation
Bullish regime shows a green line below price as support, with upward fill from midline; bearish uses red line above as resistance, downward fill. Crossovers flip the active boundary, marked by tiny green/red circles and "Buy"/"Sell" labels at the hull level. Fills start at base transparency but darken sharply at changes, fading over the specified bars to signal fresh momentum. If the hull rarely breaches during trends, containment is effective; frequent touches without flips indicate tight adaptation. Debug mode (when enabled) overlays text or plots for selected length and multiplier, helping verify auto-choices.
Practical Workflows & Combinations
- Trend following: Enter long on green "Buy" label above prior low structure; confirm with higher high. Trail stops along the green hull line, tightening as fills stabilize post-fade.
- Exits/Stops: Conservative exit on opposite crossover or hull breach; aggressive hold until fade completes if volume supports. Use darken boost as a volatility cue—high delta suggests waiting for confirmation.
- Multi-asset/Multi-TF: Defaults suit forex/stocks on 15m-4h; for crypto, widen containment to 75 for gaps. Layer on volume oscillator for cross filters; avoid on low-liquidity assets where ATR candidates skew.
Behavior, Constraints & Performance
Closed-bar logic ensures signals confirm at bar end, with live bars updating hull adaptively but no repaints since no future data or security calls are used. Arrays persist ATR states across bars, initialized once with candidates parsed from string. Small fixed loops (over 6 lengths max, inner up to 50) run per bar, capped by max_bars_back=500 for history needs. Resources stay low with 500 labels/lines limits, but dense charts may hit on markers. Known limits include initial lag until containment history builds (50+ bars), potential wide bands on gaps, and suboptimal selections if candidates omit ideal lengths.
Sensible Defaults & Quick Tuning
Start with "21/55" pair, 50-window, 0.5-1.0 multipliers, and 80% transparency for balanced responsiveness on daily charts. For too many flips, raise min floor to 0.75 or add lengths like "42"; for sluggishness, shorten window to 30 or pick faster pair. In high-vol environments, boost padding to 0.10; for smoother visuals, extend fade bars to 12.
What this indicator is—and isn’t
This is a visualization and signal layer for trend regime and adaptive boundaries, aiding entry/exit timing in directional markets. It is not a standalone system—pair with price structure, risk sizing, and broader context. Not predictive of turns, just reactive to containment and crosses.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Happy trading
Chervolino
Squeeze Weekday Frequency [CHE] Squeeze Weekday Frequency — Tracks historical frequency of low-volatility squeezes by weekday to inform timing of low-risk setups.
Summary
This indicator monitors periods of unusually low volatility, defined as when the average true range falls below a percentile threshold, and tallies their occurrences across each weekday. By aggregating these counts over the chart's history, it reveals patterns in squeeze frequency, helping traders avoid or target specific days for reduced noise. The approach uses persistent counters to ensure accurate daily tallies without duplicates, providing a robust view of weekday biases in volatility regimes.
Motivation: Why this design?
Traders often face inconsistent signal quality due to varying volatility patterns tied to the trading calendar, such as quieter mid-week sessions or busier Mondays. This indicator addresses that by binning low-volatility events into weekday buckets, allowing users to spot recurring low-activity days where trends may develop with less whipsaw. It focuses on historical aggregation rather than real-time alerts, emphasizing pattern recognition over prediction.
What’s different vs. standard approaches?
- Reference baseline: Traditional volatility trackers like simple moving averages of range or standalone Bollinger Band squeezes, which ignore temporal distribution.
- Architecture differences:
- Employs array-based persistent counters for each weekday to accumulate events without recounting.
- Includes duplicate prevention via day-key tracking to handle sparse data.
- Features on-demand sorting and conditional display modes for focused insights.
- Practical effect: Charts show a persistent table of ranked weekdays instead of transient plots, making it easier to glance at biases like higher squeezes on Fridays, which reduces the need for manual logging and highlights calendar-driven edges.
How it works (technical)
The indicator first computes the average true range over a specified lookback period to gauge recent volatility. It then ranks this value against its own history within a sliding window to identify squeezes when the rank drops below the threshold. Each bar's timestamp is resolved to a weekday using the selected timezone, and a unique day identifier is generated from the date components.
On detecting a squeeze and valid price data, it checks against a stored last-marked day for that weekday to avoid multiple counts per day. If it's a new occurrence, the corresponding weekday counter in an array increments. Total days and data-valid days are tracked separately for context.
At the chart's last bar, it sums all counters to compute shares, sorts weekdays by their squeeze proportions, and populates a table with the selected subset. The table alternates row colors and highlights the peak weekday. An info label above the final bar summarizes totals and the top day. Background shading applies a faint red to squeeze bars for visual confirmation. State persists via variable arrays initialized once, ensuring counts build incrementally without resets.
Parameter Guide
ATR Length — Sets the lookback for measuring average true range, influencing squeeze sensitivity to short-term swings. Default: 14. Trade-offs/Tips: Shorter values increase responsiveness but raise false positives in chop; longer smooths for stability, potentially missing early squeezes.
Percentile Window (bars) — Defines the history length for ranking the current ATR, balancing recent relevance with sample size. Default: 252. Trade-offs/Tips: Narrower windows adapt faster to regime shifts but amplify noise; wider ones stabilize ranks yet lag in fast markets—aim for 100-500 bars on daily charts.
Squeeze threshold (PR < x) — Determines the cutoff for low-volatility classification; lower values flag rarer, tighter squeezes. Default: 10.0. Trade-offs/Tips: Tighter thresholds (under 5) yield fewer but higher-quality signals, reducing clutter; looser (over 20) captures more events at the cost of relevance.
Timezone — Selects the reference for weekday assignment; exchange default aligns with asset's session. Default: Exchange. Trade-offs/Tips: Use custom for cross-market analysis, but verify alignment to avoid offset errors in global pairs.
Show — Toggles the results table visibility for quick on/off of the display. Default: true. Trade-offs/Tips: Disable in multi-indicator setups to save screen space; re-enable for periodic reviews.
Pos — Positions the table on the chart pane for optimal viewing. Default: Top Right. Trade-offs/Tips: Bottom options suit long-term charts; test placements to avoid overlapping price action.
Font — Adjusts text size in the table for readability at different zooms. Default: normal. Trade-offs/Tips: Smaller fonts fit more data but strain eyes on small screens; larger for presentations.
Dark — Applies a dark color scheme to the table for contrast against chart backgrounds. Default: true. Trade-offs/Tips: Toggle false for light themes; ensures legibility without manual recoloring.
Display — Filters table rows to show all, top three, or bottom three weekdays by squeeze share. Default: All. Trade-offs/Tips: Use "Top 3" for focus on high-frequency days in active trading; "All" for full audits.
Reading & Interpretation
Red-tinted backgrounds mark individual squeeze bars, indicating current low-volatility conditions. The table's summary row shows the highest squeeze count, its percentage of total events, and the associated weekday in teal. Detail rows list selected weekdays with their absolute counts, proportional shares, and a left arrow for the peak day—higher percentages signal days where squeezes cluster, suggesting potential for calmer trend development. The info label reports overall days observed, valid data days, and reiterates the top weekday with its count. Drifting counts toward zero on a weekday imply rarity, while elevated ones point to habitual low-activity sessions.
Practical Workflows & Combinations
- Trend following: Scan for squeezes on high-frequency weekdays as entry filters, confirming with higher highs or lower lows in the structure; pair with momentum oscillators to time breaks.
- Exits/Stops: On low-squeeze days, widen stops for breathing room, tightening them during peak squeeze periods to guard against false breaks—use the table's percentages as a regime proxy.
- Multi-asset/Multi-TF: Defaults work across forex and indices on hourly or daily frames; for stocks, adjust percentile window to 100 for shorter histories. Scale thresholds up by 5-10 points for high-vol assets like crypto to maintain signal sparsity.
Behavior, Constraints & Performance
- Repaint/confirmation: Counts update only on confirmed bars via day-key changes, with no future references—live bars may shade red tentatively but tallies finalize at session close.
- security()/HTF: Not used, so no higher-timeframe repaint risks; all computations stay in the chart's resolution.
- Resources: Relies on a fixed-size array of seven elements and small loops for sorting and table fills, capped at 5000 bars back—efficient for most charts but may slow on very long intraday histories.
- Known limits: Ignores weekends and holidays implicitly via data presence; early chart bars lack full percentile context, leading to initial undercounting; assumes continuous sessions, so gaps in data (e.g., news halts) skew totals.
Sensible Defaults & Quick Tuning
Start with the built-in values for broad-market daily charts: ATR at 14, window at 252, threshold at 10. For noisier environments, lower the threshold to 5 and shorten the window to 100 to prioritize rare squeezes. If too few events appear, raise the threshold to 15 and extend ATR to 20 for broader capture. To combat overcounting in sparse data, widen the window to 500 while keeping others stock—monitor the info label's data-days count before trusting patterns.
What this indicator is—and isn’t
This serves as a statistical overlay for spotting calendar-based volatility biases, aiding in session selection and filter design. It is not a standalone signal generator, predictive model, or risk manager—integrate it with price action, volume, and broader strategy rules for decisions.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino
Adaptive Trend Breaks Adaptive Trend Breaks
## WHAT IT DOES
This script is a modified and enhanced version of "Trendline Breakouts With Targets" concept by ChartPrime.
Adaptive Trend Breaks (ATB) is a trendline breakout system optimized for scalping liquid futures contracts. The indicator automatically draws dynamic support and resistance trendlines based on pivot points, then generates trade signals when price breaks through these levels with confirmation filters. It includes automated target and stop-loss placement with real-time P&L tracking in dollars.
## HOW IT WORKS
**Trendline Detection Method:**
The indicator uses pivot high/low detection to identify significant price turning points. When a new pivot forms, it calculates the slope between consecutive pivots to draw dynamic trendlines. These lines extend forward based on the established trend angle, creating actionable support and resistance zones.
**Band System:**
Around each trendline, the script creates a "band" using a volatility-adjusted calculation: `ATR(14) * 0.2 * bandwidth multiplier / 2`. This adaptive band accounts for current market conditions - wider during volatile periods, tighter during quiet markets.
**Breakout Logic:**
A breakout signal triggers when:
1. Price closes beyond the trendline + band zone
2. Volume exceeds the 20-period moving average by your set multiplier (default 1.2x)
3. Price is within Regular Trading Hours (9:30-16:00 EST) if session filter enabled
4. Current ATR meets minimum volatility threshold (prevents trading dead markets)
**Target & Stop Calculation:**
Upon breakout confirmation:
- **Entry**: Trendline breach point
- **Target**: Entry ± (bandwidth × target multiplier) - default 8x for quick scalps
- **Stop**: Entry ± (bandwidth × stop multiplier) - default 8x for 1:1 risk/reward
- Multipliers adjust automatically to market volatility through the ATR-based band
**P&L Conversion:**
The script converts point movements to dollars using:
```
Dollar P&L = (Price Points × Contract Point Value × Quantity)
```
For example, a 10-point NQ move with 2 contracts = 10 × $20 × 2 = $400
## HOW TO USE IT
**Setup:**
1. Select your instrument (NQ/ES/YM/RTY) - point values auto-configure
2. Set contract quantity for accurate dollar P&L
3. Choose pivot period (lower = more signals but more noise, default 5 for scalping)
4. Adjust bandwidth multiplier if trendlines are too tight/loose (1-5 range)
**Filters Configuration:**
- **Volume Filter**: Requires breakout volume > moving average × multiplier. Increase multiplier (1.5-2.0) for higher conviction trades
- **Session Filter**: Enable to trade only RTH. Disable for 24-hour trading
- **ATR Filter**: Prevents signals during low volatility. Increase minimum % for more active markets only
**Risk Management:**
- Set target/stop multipliers based on your risk tolerance
- 8x bandwidth = approximately 1:1 risk/reward for most liquid futures
- Enable trailing stops for trend-following approach (moves stop to protect profits)
- Adjust line length to see targets further into the future
**Statistics Table:**
- Choose timeframe to analyze: all-time, today, this week, custom days
- Monitor win rate, profit factor, and net P&L in dollars
- Track long vs short performance separately
- See real-time unrealized P&L on active trades
**Reading Signals:**
- **Green triangle below bar** = Long breakout (resistance broken)
- **Red triangle above bar** = Short breakout (support broken)
- **White dashed line** = Entry price
- **Orange line** = Take profit target with dollar value
- **Red line** = Stop loss with dollar value
- **Green checkmark (✓)** = Target hit, winning trade
- **Red X (✗)** = Stop hit, losing trade
## WHAT IT DOES NOT DO
**Limitations to Understand:**
- Does not predict future trendline formations - it reacts to breakouts after they occur
- Historical trendlines disappear after breakout (not kept on chart for clarity)
- Requires sufficient volatility - may not signal in extremely quiet markets
- Volume filter requires exchange volume data (not available on all symbols)
- Statistics are indicator-based simulations, not actual trading results
- Does not account for slippage, commissions, or order fills
## BEST PRACTICES
**Recommended Settings by Market:**
- **NQ (Nasdaq)**: Default settings work well, consider volume multiplier 1.3-1.5
- **ES (S&P 500)**: Slightly slower, try period 7-8, volume 1.2
- **YM (Dow)**: Lower volatility, reduce bandwidth to 1.5-2
- **RTY (Russell)**: Higher volatility, increase bandwidth to 3-4
**Risk Management:**
- Never risk more than 2-3% of account per trade
- Use contract quantity calculator: Max Risk $ ÷ (Stop Distance × Point Value)
- Start with 1 contract while learning the system
- Backtest your specific timeframe and instrument before live trading
**Optimization Tips:**
- Increase pivot period (7-10) for fewer but higher-quality signals
- Raise volume multiplier (1.5-2.0) in choppy markets
- Lower target/stop multipliers (5-6x) for tighter profit taking
- Use trailing stops in strong trending conditions
- Disable session filter for overnight gaps and Asia session moves
## TECHNICAL DETAILS
**Key Calculations:**
- Pivot Detection: `ta.pivothigh(high, period, period/2)` and `ta.pivotlow(low, period, period/2)`
- Slope Calculation: `(newPivot - oldPivot) / (newTime - oldTime)`
- Adaptive Band: `min(ATR(14) * 0.2, close * 0.002) * multiplier / 2`
- Breakout Confirmation: Price crosses trendline + 10% of band threshold
**Data Requirements:**
- Minimum bars in view: 500 for proper pivot calculation
- Volume data required for volume filter accuracy
- Intraday timeframes recommended (1min - 15min) for scalping
- Works on any timeframe but optimized for fast execution
**Performance Metrics:**
All statistics calculate based on indicator signals:
- Tracks every signal as a trade from entry to TP/SL
- P&L in actual contract dollar values
- Win rate = (Winning trades / Total trades) × 100
- Profit factor = Gross profit / Gross loss
- Separates long/short performance for bias analysis
## IDEAL FOR
- Futures scalpers and day traders
- Traders who prefer visual trendline breakouts
- Those wanting automated TP/SL placement
- Traders tracking performance in dollar terms
- Multiple timeframe analysis (compare 1min vs 5min signals)
## NOT SUITABLE FOR
- Swing trading (targets too close)
- Stocks/forex without modifying point values
- Extremely low timeframes (<30 seconds) - too much noise
- Markets without volume data if using volume filter
- Illiquid contracts (signals may not execute at shown prices)
---
**Settings Summary:**
- Core: Period, bandwidth, extension, trendline style
- Filters: Volume, RTH session, ATR volatility
- Risk: R:R ratio, target/stop multipliers, trailing stop
- Display: Stats table position, size, colors
- Stats: Timeframe selection (all-time to custom days)
**License:** This indicator is published open-source under Mozilla Public License 2.0. You may use and modify the code with proper attribution.
**Disclaimer:** This indicator is for educational purposes. Past performance does not guarantee future results. Always practice proper risk management and test thoroughly before live trading.
---
## CREDITS & ATTRIBUTION
This script builds upon the "Trendline Breakouts With Targets" concept by ChartPrime with significant enhancements:
**Major Improvements Added:**
- **Futures-Specific Calculations**: Automated dollar P&L conversion using actual contract point values (NQ=$20, ES=$50, YM=$5, RTY=$50)
- **Advanced Statistics Engine**: Comprehensive performance tracking with customizable timeframe analysis (today, week, month, custom ranges)
- **Multi-Layer Filtering System**: Volume confirmation, RTH session filter, and ATR volatility filter to reduce false signals
- **Professional Trade Management**: Enhanced visual trade tracking with separate TP/SL lines, dollar value labels, and optional trailing stops
- **Optimized for Scalping**: Faster pivot periods (5 vs 10), tighter bands, and reduced extension bars for quick entries
Original trendline detection methodology by ChartPrime - used with modification under Mozilla Public License 2.0.
Global Risk Terminal – Multi-Asset Macro Sentiment IndicatorDescription:
The Global Risk Terminal is a sophisticated macro sentiment indicator that synthesizes signals from three key cross-asset relationships to produce a single, actionable risk appetite score. It is designed to help traders and investors identify whether global markets are in a risk-on (growth-seeking) or risk-off (defensive) regime. The indicator analyzes the behavior of commodities, equities, bonds, and currencies to generate a comprehensive view of market conditions.
Indicator Output:
The Global Risk Terminal produces a normalized risk score ranging from -1 to +1:
Positive values indicate risk-on conditions (growth assets favored)
Negative values indicate risk-off conditions (safe-haven assets favored)
Core Components:
Growth Pulse (Copper to Gold Ratio, HG/GC)
Purpose: Measures investor preference for industrial growth versus safe-haven assets.
Interpretation:
Rising ratio → Copper outperforming gold → Risk-on environment
Falling ratio → Gold outperforming copper → Risk-off environment
Flat ratio → Transitional market phase
Technical Implementation: Dual moving average slope method (fast MA default 20, slow MA default 40). Positive slope = +1, negative slope = -1, flat slope = 0
Equity Rotation (Russell 2000 to S&P 500 Ratio, RTY/ES)
Purpose: Tracks rotation between small-cap and large-cap equities, revealing market risk appetite.
Interpretation:
Rising ratio → Small-caps outperforming → Strong risk-on
Falling ratio → Large-caps outperforming → Defensive positioning
Technical Implementation: Dual moving average slope method (same as Growth Pulse)
Flow Gauge (10-Year Treasury to US Dollar Index, ZN/DXY)
Purpose: Captures liquidity conditions and cross-asset capital flows.
Interpretation:
Rising ratio → Treasury prices rising or USD weakening → Liquidity expansion, risk-on environment
Falling ratio → Treasury prices falling or USD strengthening → Liquidity contraction, risk-off environment
Technical Implementation: Dual moving average slope method
Composite Risk Score Calculation:
Analyze each component for trend using dual moving averages
Assign signal values: +1 (risk-on), -1 (risk-off), 0 (neutral)
Average the three signals:
Risk Score = (Growth Pulse + Equity Rotation + Flow Gauge) / 3
Optional smoothing with exponential moving average (default 3 periods) to reduce noise
Interpreting the Risk Score:
+0.66 to +1.0: Full risk-on – favor cyclical sectors, small-caps, growth strategies
+0.33 to +0.66: Moderate risk-on – mostly bullish environment, watch for fading momentum
-0.33 to +0.33: Neutral/transition – markets in flux, signals mixed, exercise caution
-0.66 to -0.33: Cautious risk-off – favor defensive sectors, reduce high-beta exposure
-1.0 to -0.66: Full risk-off – strong defensive positioning, prioritize safe-haven assets
How to Use the Global Risk Terminal to Frame Trades:
Aligning Trades with Market Regime
Risk-On (+0.33 and above): Look for buying opportunities in cyclical stocks, high-beta equities, commodities, and emerging markets. Use long entries for swing trades or intraday positions, following confirmed price action.
Risk-Off (-0.33 and below): Shift focus to defensive sectors, large-cap quality stocks, U.S. Treasuries, and safe-haven currencies. Prefer short entries or reduced exposure in risky assets.
Entry and Exit Framing
Use the risk score as a macro filter before executing trades:
Example: The risk score is +0.7 (strong risk-on). Prefer long positions in equities or commodities that are showing bullish confirmation on your regular chart.
Conversely, if the risk score is -0.7 (strong risk-off), avoid aggressive longs and consider short or defensive trades.
Watch for threshold crossings (+/-0.33, +/-0.66) as potential inflection points for adjusting position size, stop-loss levels, or sector rotation.
Confirming Trade Decisions
Combine the Global Risk Terminal with price action, volume, and trend indicators:
If equities rally but the risk score is declining, this may indicate a fragile rally driven by few leaders—trade cautiously.
If equities fall but the risk score is rising, consider counter-trend entries or buying dips.
Risk Management and Position Sizing
Strong alignment across components → increase position size and hold with wider stops
Mixed or neutral signals → reduce exposure, tighten stops, or avoid new trades
Defensive regimes → rotate into stable, low-volatility assets and increase cash buffer
Framing Trades Across Timeframes
Use the indicator as a strategic guide rather than a precise timing tool. Even without the MTF table:
Daily trend alignment → Guide swing trade bias
Shorter timeframe price action → Refine entry points and stop placement
Example: Daily chart shows +0.6 risk score → identify high-probability long setups using intraday technical patterns (breakouts, trend continuation).
Sector and Asset Rotation
Risk-On: Focus on cyclical sectors (financials, industrials, materials, energy), small-caps, high-beta instruments
Risk-Off: Focus on defensive sectors (utilities, consumer staples, healthcare), large-caps, safe-haven instruments
Alert Integration
Set alerts on the risk score to notify you when markets move from neutral to risk-on or risk-off regimes. Use these alerts to plan entries, exits, or portfolio adjustments in advance.
Customization Options:
Moving Average Length (5–100): Adjust sensitivity of trend detection
Score Smoothing (1–10): Reduce noise or see raw risk score
Visual Themes: Six preset themes (Cyber, Ocean, Sunset, Monochrome, Matrix, Custom)
Display Options: Show or hide component dashboards, main header, risk level lines, gradient fill, and component signals
Label Size: Tiny, Small, Normal, Large
Alert Conditions:
Risk score crosses above +0.66 → Strong risk-on
Risk score crosses below -0.66 → Strong risk-off
Risk score crosses zero → Neutral line
Risk score crosses above +0.33 → Moderate risk-on
Risk score crosses below -0.33 → Moderate risk-off
Data Sources:
HG1! – Copper Futures (COMEX)
GC1! – Gold Futures (COMEX)
RTY1! – Russell 2000 E-mini Futures (CME)
ES1! – S&P 500 E-mini Futures (CME)
ZN1! – 10-Year U.S. Treasury Note Futures (CBOT)
DXY – U.S. Dollar Index (ICE)
Notes and Limitations:
Works best during clear macro regimes and aligned trends
Use with price action, volume, and other technical tools
Not a standalone trading system; serves as a macro context filter
Equal weighting assumes all three components are equally important, but market conditions may vary
Past performance does not guarantee future results
Conclusion:
The Global Risk Terminal consolidates complex cross-asset signals into a simple, actionable score that informs market regime, portfolio positioning, sector rotation, and trading decisions. Its user-friendly layout and extensive customization options make it suitable for traders of all experience levels seeking macro-driven insights. By framing trades around risk score thresholds and combining macro context with tactical execution, traders can identify higher-probability opportunities and optimize position sizing, entries, and exits across a wide range of market conditions.
S&P500 Net Issues - Block 1Description:
This indicator calculates and plots net advancers minus decliners for 13 predefined blocks of S&P 500 stocks. Each block represents a sector or a selected subset of stocks.
Features:
Shows net issues (advancers – decliners) for each block separately.
13 blocks plotted with distinct colors for easy identification.
Fully compatible with 1-minute, intraday, or higher timeframe charts.
Ideal for identifying sector momentum and market breadth trends.
Can be used standalone or combined with other indicators such as market indices (e.g., S&P 500 futures or TICK).
Usage:
Green/red/blue/orange lines represent different blocks; positive values indicate more advancing stocks than declining, negative values indicate more declining stocks.
Best viewed on intraday charts for short-term market breadth analysis.
Disclaimer:
This indicator is for educational and analytical purposes only. Not a buy/sell signal. Use proper risk management and verify data before trading.
Parthiban Stock Market Buy V2 - Buy onlyFor BUY, condition
continuos 3 down candle
then forms Indecision candle
next candle close above Indecision candle
price above 500 EMA
For sell, condition
continuos 3 up candle
then forms Indecision candle
next candle close below Indecision candle
price below 500 EMA
Parthiban - Stock Market BuyParthiban - Stock Market Buy
For BUY, condition
continuos 3 down candle
then forms Indecision candle
next candle close above Indecision candle
price above 500 EMA
For sell, condition
continuos 3 up candle
then forms Indecision candle
next candle close below Indecision candle
price below 500 EMA






















