TNZ - Index above MA Use this indicator to filter stock selection based on the relevant index value being above the selected simple moving average. 
For example, only buying the S+P 500 stock if the S+P 500 index value is above the 10 period moving average. 
The time frame used is that displayed
"美股标普500" için komut dosyalarını ara
Macroeconomic Artificial Neural Networks
This script was created by training 20 selected macroeconomic data to construct artificial neural networks on the S&P 500 index.
No technical analysis data were used.
The average error rate is 0.01.
In this respect, there is a strong relationship between the index and macroeconomic data.
 Although it affects the whole world,I personally recommend using it under the following conditions: S&P 500 and related ETFs in 1W time-frame (TF = 1W  SPX500USD, SP1!, SPY, SPX etc. )
 
 Macroeconomic Parameters 
Effective Federal Funds Rate (FEDFUNDS)
Initial Claims (ICSA)
Civilian Unemployment Rate (UNRATE)
10 Year Treasury Constant Maturity Rate (DGS10)
Gross Domestic Product , 1 Decimal (GDP)
Trade Weighted US Dollar Index : Major Currencies (DTWEXM)
Consumer Price Index For All Urban Consumers (CPIAUCSL)
M1 Money Stock (M1) 
M2 Money Stock (M2)
2 - Year Treasury Constant Maturity Rate (DGS2)
30 Year Treasury Constant Maturity Rate (DGS30)
Industrial Production Index (INDPRO)
5-Year Treasury Constant Maturity Rate (FRED : DGS5)
Light Weight Vehicle Sales: Autos and Light Trucks (ALTSALES)
Civilian Employment Population Ratio (EMRATIO)
Capacity Utilization (TOTAL INDUSTRY) (TCU)
Average (Mean) Duration Of Unemployment (UEMPMEAN)
Manufacturing Employment Index (MAN_EMPL)
Manufacturers' New Orders (NEWORDER)
ISM Manufacturing Index (MAN : PMI)
 Artificial Neural Network (ANN) Training Details :  
Learning cycles:	16231
AutoSave cycles:	100
 Grid 
Input columns:		19
Output columns:		1
Excluded columns:		0
Training example rows:	998
Validating example rows:	0
Querying example rows:	0
Excluded example rows:	0
Duplicated example rows:	0
 Network 
Input nodes connected:	19
Hidden layer 1 nodes:	2
Hidden layer 2 nodes:	0
Hidden layer 3 nodes:	0
Output nodes:		1
 Controls 
Learning rate:		0.1000
Momentum:		0.8000 (Optimized) 
Target error:		0.0100
 Training error:	0.010000 
NOTE : Alerts added . The red histogram represents the bear market and the green histogram represents the bull market.
Bars subject to region changes are shown as background colors. (Teal = Bull , Maroon = Bear Market )
I hope it will be useful in your studies and analysis, regards. 
Damped Sine Wave Weighted FilterIntroduction 
Remember that we can make filters by using convolution, that is summing the product between the input and the filter coefficients, the set of filter coefficients is sometime denoted "kernel", those coefficients can be a same value (simple moving average), a linear function (linearly weighted moving average), a gaussian function (gaussian filter), a polynomial function (lsma of degree p with p = order of the polynomial), you can make many types of kernels, note however that it is easy to fall into the redundancy trap.
Today a low-lag filter who weight the price with a damped sine wave is proposed, the filter characteristics are discussed below.
 A Damped Sine Wave 
A damped sine wave is a like a sine wave with the difference that the sine wave peak amplitude decay over time.
  
A damped sine wave
 Used Kernel 
We use a damped sine wave of period  length  as kernel.
  
The coefficients underweight older values which allow the filter to reduce lag.
 Step Response 
  
Because the filter has overshoot in the step response we can conclude that there are frequencies amplified in the passband, we could have reached to this conclusion by simply seeing the negative values in the kernel or the "zero-lag" effect on the closing price.
 Enough ! We Want To See The Filter ! 
I should indeed stop bothering you with transient responses but its always good to see how the filter act on simpler signals before seeing it on the closing price. The filter has low-lag and can be used as input for other indicators
  
Filter with length = 100 as input for the rsi.
  
The bands trailing stop utility using rolling squared mean average error with length 500  using the filter of length 500 as input.
 Approximating A Least Squares Moving Average 
A least squares moving average has a linear kernel with certain values under 0, a lsma of length  k  can be approximated using the proposed filter using period  p  where  p = k + k/4 .
  
Proposed filter (red) with length = 250 and lsma (blue) with length = 200. 
 Conclusions 
The use of damping in filter design can provide extremely useful filters, in fact the ideal kernel, the sinc function, is also a damped sine wave. 
VIX reversion-Buschi
 English: 
A significant intraday reversion (commonly used: 3 points) on a high (over 20 points) S&P 500 Volatility Index (VIX) can be a sign of a market bottom, because there is the assumption that some of the "big guys" liquidated their options / insurances because the worst is over.
This indicator shows these reversions (3 points as default) when the VIX was over 20 points. The character "R" is then shown directly over the daily column, the VIX need not to be loaded explicitly.
 Deutsch: 
Eine deutliche Intraday-Umkehr (3 Punkte im Normalfall) bei einem hohen (über 20 Punkte) S&P 500 Volatility Index (VIX) kann ein Zeichen für eine Bodenbildung im Markt sein, weil möglicherweise einige "große Jungs" ihre Optionen / Versicherungen auflösen, weil das schlimmste vorbei ist.
Dieser Indikator zeigt diese Umkehr (Standardwert: 3 Punkte), wenn der VIX vorher über 20 Punkte lag. Der Buchstabe "R" wird dabei direkt über dem Tagesbalken angezeigt, wobei der VIX nicht explizit geladen werden muss.
Relative Price StrengthThe strength of a stock relative to the S&P 500 is key part of most traders decision making process. Hence the default reference security is SPY, the most commonly  trades S&P 500 ETF.
 Most profitable traders buy stocks that are showing persistence  intermediate strength verses the S&P as this has been shown to work. Hence the default period is 63 days or 3 months.
TICK Extremes IndicatorSimple TICK indicator, plots candles and HL2 line
Conditional green/red coloring for highs above 500, 900 and lows above 0, and for lows below -500, -900, and highs above 0
Probably best used for 1 - 5 min timeframes
Always open to suggestions if criteria needs tweaking or if something else would make it more useful or user-friendly!
Market direction and pullback based on S&P 500.A simple indicator based on www.swing-trade-stocks.com The link is also the guide for how to use it.
0 - nothing. If the indicator is showing 0 for a prolonged amount of time, it is likely the market is in "momentum mode" (referred to in the link above).
1 - indicates an uptrend based on SMA and EMA and also a place where a reversal to the upside is likely to occur. You should look only for long trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
-1 - indicates a downtrend based on SMA and EMA and also a place where a reversal to the downside is likely to occur. You should look only for short trades in the stock market when you see a spike upwards and S&P 500 is showing an obvious uptrend.
Net XRP Margin PositionTotal XRP Longs minus XRP Shorts in order to give you the total outstanding XRP margin debt. 
ie: If 500,000 XRP has been longed, and 400,000 XRP has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 XRP (net) remaining to be sold to give us an overall neutral margin position. 
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances. 
Net DASH Margin PositionTotal DASH Longs minus DASH Shorts in order to give you the total outstanding DASH margin debt. 
ie: If 500,000 DASH has been longed, and 400,000 DASH has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 DASH (net) remaining to be sold to give us an overall neutral margin position. 
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances. 
(Anyone know what category this script should be in?)
Net NEO Margin PositionTotal NEO Longs  minus NEO Shorts in order to give you the total outstanding NEO margin debt. 
ie: If 500,000 NEO has been longed, and 400,000 NEO has been shorted, then 500,000 has been bought, and 400,000 sold, leaving us with 100,000 NEO (net) remaining to be sold to give us an overall neutral margin position. 
That isn't to say that the net margin position must move towards zero, but it is a sensible reference point, and historical net values may provide useful insights into the current circumstances. 
(Anyone know what category this script should be in?)
Everyday 0002 _ MAC 1st Trading Hour WalkoverThis is the second strategy for my Everyday project. 
Like I wrote the last time - my goal is to create a new strategy everyday 
for the rest of 2016 and post it here on TradingView. 
I'm a complete beginner so this is my way of learning about coding strategies. 
I'll give myself between 15 minutes and 2 hours to complete each creation. 
This is basically a repetition of the first strategy I wrote - a Moving Average Crossover, 
but I added a tiny thing. 
I read that "Statistics have proven that the daily high or low is established within the first hour of trading on more than 70% of the time." 
(source: ) 
My first Moving Average Crossover strategy, tested on VOLVB daily, got stoped out by the volatility 
and because of this missed one nice bull run and a very nice bear run. 
So I added this single line: if time("60", "1000-1600") regarding when to take exits: 
if time("60", "1000-1600") 
strategy.exit("Close Long", "Long", profit=2000, loss=500) 
strategy.exit("Close Short", "Short", profit=2000, loss=500) 
Sweden is UTC+2 so I guess UTC 1000 equals 12.00 in Stockholm. Not sure if this is correct, actually. 
Anyway, I hope this means the strategy will only take exits based on price action which occur in the afternoon, when there is a higher probability of a lower volatility. 
When I ran the new modified strategy on the same VOLVB daily it didn't get stoped out so easily. 
On the other hand I'll have to test this on various stocks . 
Reading and learning about how to properly test strategies is on my todo list - all tips on youtube videos or blogs 
to read on this topic is very welcome! 
Like I said the last time, I'm posting these strategies hoping to learn from the community - so any feedback, advice, or corrections is very much welcome and appreciated! 
/pbergden
Multi-TF Gates (Labels + Alerts)//@version=6
indicator("PO9 – Multi-TF Gates (Labels + Alerts)", overlay=true, max_lines_count=500)
iYear=input.int(2024,"Anchor Year",minval=1970)
iMonth=input.int(11,"Anchor Month",minval=1,maxval=12)
iDay=input.int(6,"Anchor Day",minval=1,maxval=31)
useSymbolTZ=input.bool(true,"Use symbol's exchange timezone (syminfo.timezone)")
tzChoice=input.string("Etc/UTC","Custom timezone (if not using symbol TZ)",options= )
anchorType=input.string("FX NY 17:00","Anchor at",options= )
showEvery=input.int(9,"Mark every Nth candle",minval=1)
showD=input.bool(true,"Show Daily")
show3H=input.bool(true,"Show 3H")
show1H=input.bool(true,"Show 1H")
show15=input.bool(true,"Show 15M")
show5=input.bool(false,"Show 5M (optional)")
colD=input.color(color.new(color.red,0),"Daily color")
col3H=input.color(color.new(color.orange,0),"3H color")
col1H=input.color(color.new(color.yellow,0),"1H color")
col15=input.color(color.new(color.teal,0),"15M color")
col5=input.color(color.new(color.gray,0),"5M color")
styStr=input.string("dashed","Line style",options= )
lnW=input.int(2,"Line width",minval=1,maxval=4)
extendTop=input.float(1.5,"ATR multiples above high",minval=0.1)
extendBottom=input.float(1.5,"ATR multiples below low",minval=0.1)
showLabels=input.bool(true,"Show labels")
enableAlerts=input.bool(true,"Enable alerts")
f_style(s)=>s=="solid"?line.style_solid:s=="dashed"?line.style_dashed:line.style_dotted
var lines=array.new_line()
f_prune(maxKeep)=>
    if array.size(lines)>maxKeep
        old=array.shift(lines)
        line.delete(old)
tzEff=useSymbolTZ?syminfo.timezone:tzChoice
anchorTs=anchorType=="FX NY 17:00"?timestamp("America/New_York",iYear,iMonth,iDay,17,0):timestamp(tzEff,iYear,iMonth,iDay,0,0)
atr=ta.atr(14)
f_vline(_color,_tf,_idx)=>
    y1=low-atr*extendBottom
    y2=high+atr*extendTop
    lid=line.new(x1=bar_index,y1=y1,x2=bar_index,y2=y2,xloc=xloc.bar_index,extend=extend.none,color=_color,style=f_style(styStr),width=lnW)
    if showLabels
        label.new(x=bar_index,y=high+(atr*2),text=_tf+" #"+str.tostring(_idx),xloc=xloc.bar_index,style=label.style_label_down,color=_color,textcolor=color.black)
    array.push(lines,lid)
is_tf_open(tf)=> time==request.security(syminfo.tickerid,tf,time,barmerge.gaps_off,barmerge.lookahead_off)
f_tf(_tf,_show,_color,_name)=>
    var bool started=false
    var int idx=0
    isOpen=_show and is_tf_open(_tf)
    firstBar=isOpen and (time>=anchorTs) and (nz(time ,time)
Best Time Slots — Auto-Adapt (v6, TF-safe) + Range AlertsTime & binning
Auto-adapt to timeframe
Makes all time windows scale to your chart’s bar size (so it “just works” on 1m, 15m, 4H, Daily).
• On = recommended. • Off = fixed default lengths.
Minimum Bin (minutes)
The size of each daily time slot we track (e.g., 5-min bins). The script uses the larger of this and your bar size.
• Higher = fewer, broader slots; smoother stats. • Lower = more, narrower slots; needs more history.
• Try: 5–15 on intraday, 60–240 on higher TFs.
Lookback windows (used when Auto-adapt = ON)
Target ER Window (minutes)
How far back we look to judge Efficiency Ratio (how “straight” the move was).
• Higher = stricter/smoother; fewer bars qualify as “movement”. • Lower = more sensitive.
• Try: 60–120 min intraday; 240–600 min for higher TFs.
Target ATR Window (minutes)
How far back we compute ATR (typical range).
• Higher = steadier ATR baseline. • Lower = reacts faster.
• Try: 30–120 min intraday; 240–600 min higher TFs.
Target Normalization Window (minutes)
How far back for the average ATR (the baseline we compare to).
• Higher = stricter “above average range” check. • Lower = easier to pass.
• Try: ~500–1500 min.
What counts as “movement”
ER Threshold (0–1)
Minimum efficiency a bar must have to count as movement.
• Higher = only very “clean, one-direction” bars count. • Lower = more bars count.
• Try: 0.55–0.65. (0.60 = balanced.)
ATR Floor vs SMA(ATR)
Requires range to be at least this many × average ATR.
• Higher (e.g., 1.2) = demand bigger-than-usual ranges. • Lower (e.g., 0.9) = allow smaller ranges.
• Try: 1.0 (above average).
How history is averaged
Recent Days Weight (per-day decay)
Gives more weight to recent days. Example: 0.97 ≈ each day old counts ~3% less.
• Higher (0.99) = slower fade (older days matter more). • Lower (0.95) = faster fade.
• Try: 0.97–0.99.
Laplace Prior Seen / Laplace Prior Hit
“Starter counts” so early stats aren’t crazy when you have little data.
• Higher priors = probabilities start closer to average; need more real data to move.
• Try: Seen=3, Hit=1 (defaults).
Min Samples (effective)
Don’t highlight a slot unless it has at least this many effective samples (after decay + priors).
• Higher = safer, but fewer highlights early.
• Try: 3–10.
When to highlight on the chart
Min Probability to Highlight
We shade/mark bars only if their slot’s historical movement probability is ≥ this.
• Higher = pickier, fewer highlights. • Lower = more highlights.
• Try: 0.45–0.60.
Show Markers on Good Bins
Draws a small square on bars that fall in a “good” slot (in addition to the soft background).
Limit to market hours (optional)
Restrict to Session + Session
Only learn/score inside this time window (e.g., “0930-1600”). Uses the chart/exchange timezone.
• Turn on if you only care about RTH.
Range (chop) alerts
Range START if ER ≤
Triggers range when efficiency drops below this level (price starts zig-zagging).
• Higher = easier to call “range”. • Lower = stricter.
Range START if ATR ≤ this × SMA(ATR)
Also triggers range when ATR shrinks below this fraction of its average (volatility contraction).
• Higher (e.g., 1.0) = stricter (must be at/under average). • Lower (e.g., 0.9) = easier to call range.
Alerts on bar close
If ON, alerts fire once per bar close (cleaner). If OFF, they can trigger intrabar (faster, noisier).
Quick “what happens if I change X?”
Want more highlighted times? ↓ Min Probability, ↓ ER Threshold, or ↓ ATR Floor (e.g., 0.9).
Want stricter highlights? ↑ Min Probability, ↑ ER Threshold, or ↑ ATR Floor (e.g., 1.2).
Want recent days to matter more? ↑ Recent Days Weight toward 0.99.
On 4H/Daily, widen Minimum Bin (e.g., 60–240) and maybe lower Min Probability a bit.
OPADA//@version=5
indicator("Buy/Sell Zones – TV Style", overlay=true, timeframe="", timeframe_gaps=true)
//=====================
// الإعدادات
//=====================
len     = input.int(100,  "Length", minval=10)
useATR  = input.bool(true, "Use ATR (بدل الانحراف المعياري)")
mult    = input.float(2.0, "Band Multiplier", step=0.1)
useRSI  = input.bool(true, "تفعيل فلتر RSI")
rsiOB   = input.int(70, "RSI Overbought", minval=50, maxval=90)
rsiOS   = input.int(30, "RSI Oversold",  minval=10, maxval=50)
//=====================
// القناة: أساس + انحراف
//=====================
basis = ta.linreg(close, len, 0)
off   = useATR ? ta.atr(len) * mult : ta.stdev(close, len) * mult
upper = basis + off
lower = basis - off
// نطاق علوي/سفلي بعيد لعمل تعبئة المناطق
lookback      = math.min(bar_index, 500)
topBand       = ta.highest(high, lookback)  + 50 * syminfo.mintick
bottomBand    = ta.lowest(low, lookback)    - 50 * syminfo.mintick
//=====================
// الرسم
//=====================
pUpper   = plot(upper, "Upper", color=color.new(color.blue, 0), linewidth=1)
pLower   = plot(lower, "Lower", color=color.new(color.red,  0), linewidth=1)
pBasis   = plot(basis, "Basis", color=color.new(color.gray, 60), linewidth=2)
// تعبئة المناطق: فوق القناة (أزرق)، تحت القناة (أحمر)
pTop     = plot(topBand,    display=display.none)
pBottom  = plot(bottomBand, display=display.none)
fill(pUpper, pTop,    color=color.new(color.blue, 80))   // منطقة مقاومة/بيع
fill(pBottom, pLower, color=color.new(color.red,  80))   // منطقة دعم/شراء
//=====================
// خط أفقي من قمّة قريبة (يمثل مقاومة) – قريب من الخط المنقّط في الصورة
//=====================
resLen   = math.round(len * 0.6)
dynRes   = ta.highest(high, resLen)
plot(dynRes, "Recent Resistance", color=color.new(color.white, 0), linewidth=1)
//=====================
// إشارات BUY / SELL + فلتر RSI (اختياري)
//=====================
rsi = ta.rsi(close, 14)
touchLower = ta.crossover(close, lower) or close <= lower
touchUpper = ta.crossunder(close, upper) or close >= upper
buyOK  = useRSI ? (touchLower and rsi <= rsiOS) : touchLower
sellOK = useRSI ? (touchUpper and rsi >= rsiOB) : touchUpper
plotshape(buyOK,  title="BUY",  location=location.belowbar, style=shape.labelup,
     text="BUY",  color=color.new(color.green, 0), textcolor=color.white, size=size.tiny, offset=0)
plotshape(sellOK, title="SELL", location=location.abovebar, style=shape.labeldown,
     text="SELL", color=color.new(color.red,   0), textcolor=color.white, size=size.tiny, offset=0)
// تنبيهات
alertcondition(buyOK,  title="BUY",  message="BUY signal: price touched/closed below lower band (RSI filter may apply).")
alertcondition(sellOK, title="SELL", message="SELL signal: price touched/closed above upper band (RSI filter may apply).")
Buy/Sell Zones – TV Style//@version=5
indicator("Buy/Sell Zones – TV Style", overlay=true, timeframe="", timeframe_gaps=true)
//=====================
// الإعدادات
//=====================
len     = input.int(100,  "Length", minval=10)
useATR  = input.bool(true, "Use ATR (بدل الانحراف المعياري)")
mult    = input.float(2.0, "Band Multiplier", step=0.1)
useRSI  = input.bool(true, "تفعيل فلتر RSI")
rsiOB   = input.int(70, "RSI Overbought", minval=50, maxval=90)
rsiOS   = input.int(30, "RSI Oversold",  minval=10, maxval=50)
//=====================
// القناة: أساس + انحراف
//=====================
basis = ta.linreg(close, len, 0)
off   = useATR ? ta.atr(len) * mult : ta.stdev(close, len) * mult
upper = basis + off
lower = basis - off
// نطاق علوي/سفلي بعيد لعمل تعبئة المناطق
lookback      = math.min(bar_index, 500)
topBand       = ta.highest(high, lookback)  + 50 * syminfo.mintick
bottomBand    = ta.lowest(low, lookback)    - 50 * syminfo.mintick
//=====================
// الرسم
//=====================
pUpper   = plot(upper, "Upper", color=color.new(color.blue, 0), linewidth=1)
pLower   = plot(lower, "Lower", color=color.new(color.red,  0), linewidth=1)
pBasis   = plot(basis, "Basis", color=color.new(color.gray, 60), linewidth=2)
// تعبئة المناطق: فوق القناة (أزرق)، تحت القناة (أحمر)
pTop     = plot(topBand,    display=display.none)
pBottom  = plot(bottomBand, display=display.none)
fill(pUpper, pTop,    color=color.new(color.blue, 80))   // منطقة مقاومة/بيع
fill(pBottom, pLower, color=color.new(color.red,  80))   // منطقة دعم/شراء
//=====================
// خط أفقي من قمّة قريبة (يمثل مقاومة) – قريب من الخط المنقّط في الصورة
//=====================
resLen   = math.round(len * 0.6)
dynRes   = ta.highest(high, resLen)
plot(dynRes, "Recent Resistance", color=color.new(color.white, 0), linewidth=1)
//=====================
// إشارات BUY / SELL + فلتر RSI (اختياري)
//=====================
rsi = ta.rsi(close, 14)
touchLower = ta.crossover(close, lower) or close <= lower
touchUpper = ta.crossunder(close, upper) or close >= upper
buyOK  = useRSI ? (touchLower and rsi <= rsiOS) : touchLower
sellOK = useRSI ? (touchUpper and rsi >= rsiOB) : touchUpper
plotshape(buyOK,  title="BUY",  location=location.belowbar, style=shape.labelup,
     text="BUY",  color=color.new(color.green, 0), textcolor=color.white, size=size.tiny, offset=0)
plotshape(sellOK, title="SELL", location=location.abovebar, style=shape.labeldown,
     text="SELL", color=color.new(color.red,   0), textcolor=color.white, size=size.tiny, offset=0)
// تنبيهات
alertcondition(buyOK,  title="BUY",  message="BUY signal: price touched/closed below lower band (RSI filter may apply).")
alertcondition(sellOK, title="SELL", message="SELL signal: price touched/closed above upper band (RSI filter may apply).")
HalfTrend Adaptive Pro v3half trend version 3.1//@version=6
indicator("Candlestick Recognizer v1 (Praveen Edition)", overlay=true, max_labels_count=500)
// ──────────────────────────────
// Inputs: toggles & thresholds
// ──────────────────────────────
grpUse = "Enable Patterns"
useEngulf     = input.bool(true,  "Engulfing (Bull/Bear)", group=grpUse)
usePiercing   = input.bool(true,  "Piercing Line / Dark Cloud", group=grpUse)
useMarubozu   = input.bool(true,  "Marubozu (Bull/Bear)", group=grpUse)
useHammers    = input.bool(true,  "Hammer / Hanging Man", group=grpUse)
useInverted   = input.bool(true,  "Inverted Hammer / Shooting Star", group=grpUse)
useDoji       = input.bool(true,  "Doji", group=grpUse)
useStars      = input.bool(true,  "Morning/Evening Star", group=grpUse)
useThree      = input.bool(true,  "Three Soldiers / Three Crows", group=grpUse)
grpThr = "Thresholds"
minBodyPct         = input.float(0.6, "Min Body vs Range (0-1) for 'strong body'", step=0.05, group=grpThr)
maxDojiBodyPct     = input.float(0.1, "Max Body vs Range (0-1) for Doji", step=0.02, group=grpThr)
minEngulfFactor    = input.float(1.02, "Engulf body size factor", step=0.01, group=grpThr)
wickRatioHammer    = input.float(2.0, "Hammer lower wick ≥ body ×", step=0.1, group=grpThr)
wickRatioShooting  = input.float(2.0, "Shooting Star upper wick ≥ body ×", step=0.1, group=grpThr)
gapTolerance       = input.float(0.15, "Star gap tolerance as % of ATR", step=0.01, group=grpThr)
grpVis = "Visuals"
showLabels         = input.bool(true, "Show Labels", group=grpVis)
labelSize          = input.string("normal", "Label Size", options= , group=grpVis)
onlyConfirmed      = input.bool(true, "Only on bar close (confirmed)", group=grpVis)
// Colors
bullCol  = color.new(color.green, 0)
bearCol  = color.new(color.red, 0)
warnCol  = color.new(color.yellow, 0)
textCol  = color.black
// Helper to gate by confirmation
confirmed = onlyConfirmed ? barstate.isconfirmed : true
// ──────────────────────────────
// Candle math helpers
// ──────────────────────────────
body(o, c) => math.abs(c - o)
range(h, l) => h - l
isBull(o, c) => c > o
isBear(o, c) => c < o
upperW(h, o, c) => h - math.max(o, c)
lowerW(l, o, c) => math.min(o, c) - l
safeDiv(x, y) => y == 0.0 ? 0.0 : x / y
// Current and previous (p1, p2)
o = open, c = close, h = high, l = low
o1 = open , c1 = close , h1 = high , l1 = low 
o2 = open , c2 = close , h2 = high , l2 = low 
b  = body(o, c)
r  = range(h, l)
ub = upperW(h, o, c)
lb = lowerW(l, o, c)
b1  = body(o1, c1)
r1  = range(h1, l1)
b2  = body(o2, c2)
r2  = range(h2, l2)
bull  = isBull(o, c)
bear  = isBear(o, c)
bull1 = isBull(o1, c1)
bear1 = isBear(o1, c1)
bull2 = isBull(o2, c2)
bear2 = isBear(o2, c2)
bodyVsRange  = safeDiv(b,  r)
bodyVsRange1 = safeDiv(b1, r1)
bodyVsRange2 = safeDiv(b2, r2)
atr = ta.atr(14)
// ──────────────────────────────
/* Pattern logic */
// ──────────────────────────────
// 1) Engulfing
bullEngulf = useEngulf and confirmed and bear1 and bull and (b >= b1 * minEngulfFactor) and (o <= c1) and (c >= o1)
bearEngulf = useEngulf and confirmed and bull1 and bear and (b >= b1 * minEngulfFactor) and (o >= c1) and (c <= o1)
// 2) Piercing Line / Dark Cloud Cover
piercing = usePiercing and confirmed and bear1 and bull and c > (o1 + c1)/2 and o <= l1 + (h1 - l1)*0.25 // open near/below prior low, close into upper half
darkCloud = usePiercing and confirmed and bull1 and bear and c < (o1 + c1)/2 and o >= h1 - (h1 - l1)*0.25 // open near/above prior high, close into lower half
// 3) Marubozu (strong body, tiny wicks)
maruBull = useMarubozu and confirmed and bull and bodyVsRange >= minBodyPct and ub <= b * 0.1 and lb <= b * 0.1
maruBear = useMarubozu and confirmed and bear and bodyVsRange >= minBodyPct and ub <= b * 0.1 and lb <= b * 0.1
// 4) Hammer / Hanging Man (small body, long lower wick)
hammer     = useHammers and confirmed and bull and lb >= b * wickRatioHammer and ub <= b * 0.5
hangingMan = useHammers and confirmed and bear and lb >= b * wickRatioHammer and ub <= b * 0.5
// 5) Inverted Hammer / Shooting Star (small body, long upper wick)
invHammer    = useInverted and confirmed and bull and ub >= b * wickRatioShooting and lb <= b * 0.5
shootingStar = useInverted and confirmed and bear and ub >= b * wickRatioShooting and lb <= b * 0.5
// 6) Doji
doji = useDoji and confirmed and bodyVsRange <= maxDojiBodyPct
// 7) Morning Star
TFRSI & RSI Analog Dial [CHE]  TFRSI & RSI Analog Dial    — Interactive analog visualization for TFRSI or RSI with gradient zones, radial markers, and a trailing hand pointer.
  Summary 
This indicator renders an interactive analog dial for either TFRSI or standard RSI, providing a visual gauge with gradient-filled zones for oversold, neutral, and overbought regions. The hand pointer tracks the current value, with optional trailing dots at recent positions to show momentum direction. Radial lines mark key thresholds, and a digital readout displays the exact value. This design enhances readability over linear plots by leveraging familiar clock-like intuition, reducing cognitive load during quick scans. Signals are robust due to clamping to safe bounds and mode-specific scaling, ensuring consistent display across different volatility regimes.
  Motivation: Why this design? 
Traditional linear RSI or momentum indicators often feel abstract, especially in fast-paced screening where users scan multiple assets. Sharp swings can make thresholds hard to gauge at a glance, leading to missed nuances in overbought or oversold conditions. This dial addresses that by mapping values to a curved scale with color gradients, making extremes visually pop while the hand's trail hints at recent path without cluttering the chart. The dual-mode support allows seamless switching between advanced momentum (TFRSI) and classic RSI, fitting diverse strategies without reloading scripts.
  What’s different vs. standard approaches? 
- Baseline reference: Diverges from linear plotlines like the built-in RSI oscillator, which stacks values vertically and relies on horizontal lines for thresholds.
- Architecture differences:
  - Curved projection with perspective tilt for depth illusion, using polyline arcs instead of straight plots.
  - Mode-aware clamping and scaling to handle TFRSI's extended range versus RSI's standard bounds.
  - Persistent trail array for hand history, capped at three points to avoid performance drag.
  - Gradient segmentation for smooth zone transitions, rendered via multiple thin polylines.
- Practical effect: Charts show a compact, rotatable dial that fits in pane corners, with colors intuitively signaling bias (lime for buy zones, red for sell). The trail adds qualitative flow without numerical overload, helping spot divergences faster than static bars.
  How it works (technical) 
The indicator first computes the selected metric: for TFRSI, it processes price accelerations through a multi-step filter involving differencing, exponential damping, and normalization to a centered scale; for RSI, it uses the standard gain-loss ratio over the specified period. The value is then clamped between mode-specific minimum and maximum bounds to prevent display overflow.
This clamped value drives the hand angle on a 300-degree arc, projected from a 3D-like model rotated for perspective. Arcs for zones are built as segmented polylines, with colors interpolated linearly across the gradient. Key levels are drawn as radial lines from inner to outer radius, colored by zone. The trail maintains up to three prior angles in an array, updated only on confirmed bars to avoid repainting, and rendered as sized dots fading from small to large.
Initialization seeds filter states to zero on first bar, with persistent variables holding smoothing history. Data flows from price to metric computation, clamping, angle mapping, and projection—all executed globally on the last bar for redraw efficiency.
  Parameter Guide 
Mode — Switches between TFRSI (extended momentum gauge) and RSI (classic oscillator); affects bounds, zones, and labels. Default: "TFRSI". Trade-offs: TFRSI adds sensitivity to accelerations but may amplify noise; RSI is more stable for trend confirmation.
Dial Size — Sets radius in pixels, scaling all elements proportionally. Default: 200. Bounds: 50–500. Tips: Larger for detailed views, smaller for multi-pane layouts; auto-scales hand length to match.
Dial Vertical Offset — Shifts entire dial up/down in pixels. Default: 0. Bounds: -200–200. Trade-offs: Negative pulls toward price action; positive spaces below—use to avoid overlap.
Camera Angle — Tilts view from top-down (0) to side (90) for 3D effect. Default: 45. Bounds: 0–90. Tips: Steeper angles emphasize depth but compress horizontally; flat for precision.
Resolution — Polygon sides for smooth arcs. Default: 64. Bounds: 4–64. Trade-offs: Higher reduces jaggedness but increases draw calls—balance with pane zoom.
TFRSI Hand Length — Base pointer length at 200px dial, auto-scaled. Default: 170. Bounds: 10–200. Tips: Longer for emphasis in large dials; shorter avoids edge clipping.
Show TFRSI Hand — Toggles pointer visibility. Default: true. Trade-offs: Off for clean zones only; on for value tracking.
Show Hand Trail Dots — Displays 3 fading dots at recent tips. Default: true. Trade-offs: Adds motion context but may clutter static views—disable in alerts.
TFRSI Hand Color — Pointer hue, used for trail dots too. Default: 7E57C2. Tips: Match strategy theme; gradients auto-blend to zones.
Dial Base Color — Arc outline/fill tint. Default: blue. Trade-offs: Opaque for contrast; transparent blends with background.
Neutral Color (50) — Mid-zone shade. Default: gray. Tips: Neutral tones reduce bias in balanced markets.
Oversold Color — Low-zone fill. Default: lime. Trade-offs: Bright for alerts; muted for subtlety.
Overbought Color — High-zone fill. Default: red. Trade-offs: As above—pair with hand blending.
Label Size — Text scaling for thresholds. Default: "normal". Options: tiny/small/normal/large/huge. Tips: Smaller for dense charts; larger for presentations.
Digital TFRSI Size — Readout font. Default: "large". Options: as above. Trade-offs: Balances visibility without dominating dial.
Digital Vertical Offset — Readout position shift. Default: -50. Bounds: -200–200. Tips: Negative centers above dial; adjust for multi-indicators.
TFRSI Length — Core lookback for accelerations. Default: 6. Min: 1. Trade-offs: Shorter heightens reactivity, risks whipsaws; longer smooths extremes.
TFRSI Trigger Length — Final smoothing passes. Default: 2. Min: 1. Tips: Increase for fewer false crosses; decrease for quicker pivots.
RSI Length — Period for gain-loss averaging. Default: 14. Min: 1. Trade-offs: Classic 14 balances; shorter for scalps, longer for swings.
  Reading & Interpretation 
The dial arcs sweep from overbought (right, red) through neutral (top, gray) to oversold (left, lime), with the hand pointing to the current value—clockwise for rising, counterclockwise for falling. Trail dots grow larger toward the present, colored to match hand zones, indicating recent direction without numbers. Threshold lines thicken at center (50) for quick zeroing; labels confirm levels. Digital readout below shows precise value prefixed by mode. Hand color gradients from neutral to extremes signal building pressure verbally: deepening red warns of potential pullbacks, brightening lime suggests bounces.
  Practical Workflows & Combinations 
Trend following: Enter long when hand crosses above 50 from oversold trail; confirm with higher highs in price structure. Filter shorts below 50 in downtrends using volume spikes.
Exits/Stops: Trail stops to recent dot positions in overbought; tighten on red gradients exceeding thresholds. Conservative: Exit at neutral; aggressive: Hold to extremes if trail aligns with momentum.
Multi-asset/Multi-TF: Defaults suit forex/stocks on 1H–4H; for crypto, shorten lengths by 20% for volatility. Stack with HTF security calls (e.g., daily mode on 15m chart) for confluence—watch for alignment across dials.
  Behavior, Constraints & Performance 
Closed-bar updates ensure no repainting; live bars show provisional hand/trail, confirmed on close. No security or HTF calls, so zero lookahead bias. Resources: Caps at 500 lines/labels/polylines, rebuilds only on last bar; max_bars_back=2000 handles history without lag. Known limits: Trail may stutter in flat markets; gradients approximate smooth fills via segments, visible at low resolution.
  Sensible Defaults & Quick Tuning 
Start with TFRSI mode, length=6, trigger=2 for responsive momentum on daily charts. Too choppy? Bump trigger to 4 for stability. Lagging entries? Drop length to 4, watch for overreactions. For RSI trend filter, set length=21; combine with MA cross for entries when dial nears 30/70.
  What this indicator is—and isn’t 
This is a visualization layer for momentum gauges, aiding quick bias assessment and threshold spotting. Pair it with price action, volume, and risk rules for decisions. It’s not a standalone signal generator or predictive tool—values reflect past data, prone to whipsaws in ranging conditions.
  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
3D Session Clock | Live Time with Sessions [CHE]  3D Session Clock | Live Time with Sessions   — Projects a perspective clock face onto the chart to display current time and market session periods for enhanced situational awareness during trading hours.
  Summary 
This indicator renders a three-dimensional clock projection directly on the price chart, showing analog hands for hours, minutes, and seconds alongside a digital time readout. It overlays session arcs for major markets like New York, London, Tokyo, and Sydney, highlighting the active one with thicker lines and contrasting labels. By centralizing time and session visibility, it reduces the need to reference external clocks, allowing traders to maintain focus on price action while noting overlaps or transitions that influence volatility.
The design uses perspective projection to simulate depth, making the clock appear tilted for better readability on varying chart scales. Sessions are positioned radially outward from the main clock, with the current time marker pulsing on the relevant arc. This setup provides a static yet live-updating view, confirmed on bar close to avoid intrabar shifts.
  Motivation: Why this design? 
Traders often miss subtle session shifts amid fast-moving charts, leading to entries during low-liquidity periods or exits before peak activity. Standard chart tools lack integrated time visualization, forcing constant tab-switching. This indicator addresses that by embedding a customizable clock with session rings, ensuring time context is always in view without disrupting workflow.
  What’s different vs. standard approaches? 
- Reference baseline: Traditional session highlighters use simple background fills or vertical lines, which clutter the chart and ignore global time zones.
- Architecture differences:
  - Perspective projection rotates and scales points to mimic 3D depth, unlike flat 2D drawings.
  - Nested radial arcs for sessions, with dynamic radius assignment to avoid overlap.
  - Live time calculation adjusted for user-selected time zones, including optional daylight savings offset.
- Practical effect: The tilted view prevents labels from bunching at chart edges, and active session emphasis draws the eye to liquidity hotspots, making multi-session overlaps immediately apparent for better timing.
  How it works (technical) 
The indicator calculates current time in the selected time zone by adjusting the system timestamp with a fixed offset, plus an optional one-hour bump for daylight savings. This yields hour, minute, and second values that drive hand positions: the hour hand advances slowly with fractional minute input, the minute hand ticks per 60 seconds, and the second hand sweeps fully each minute.
Points for the clock face and arcs are generated as arrays of coordinates, transformed via rotation around the x-axis to apply tilt, then projected onto chart space using a scaling factor based on depth. Radial lines mark every hour from zero to 23, extending to the outermost session ring. Session arcs span user-defined hour ranges, drawn as open polylines with step interpolation for smoothness.
On the last bar, all prior drawings are cleared, and new elements are added: filled clock circles, hand lines from center to tip, a small orbiting circle at the current time position, and centered labels for hours, sessions, and time. The active session is identified by checking if the current time falls within its range, then its arc thickens and label inverts colors. Initialization populates a timezone array once, with persistent bar time tracking for horizontal positioning.
  Parameter Guide 
Clock Size — Controls overall radius in pixels, affecting visibility on dense charts — Default: 200 — Larger values suit wide screens but may crowd small views; start smaller for mobile.
Camera Angle — Sets tilt from top-down (zero) to side (90 degrees), altering projection depth — Default: 45 — Steeper angles enhance readability on sloped trends but flatten at extremes.
Resolution — Defines polygon sides for circles and arcs, balancing smoothness and draw calls — Default: 64 — Higher improves curves on large clocks; lower aids performance on slow devices.
Hour/Minute/Second Hand Length — Scales each hand from center, with seconds longest for precision — Defaults: 100/150/180 — Proportional sizing prevents overlap; shorten for compact layouts.
Clock Base Color — Tints face and frame — Default: blue — Neutral shades reduce eye strain; match chart theme.
Hand Colors — Assigns distinct hues to each hand — Defaults: red/green/yellow — High contrast aids quick scans; avoid chart-matching to stand out.
Hour Label Size — Text scale for 1-12 markers — Default: normal — Larger for distant views, but risks clutter.
Digital Time Size — Scale for HH:MM:SS readout — Default: large — Matches clock for balance; tiny for minimalism.
Digital Time Vertical Offset — Shifts readout up (negative) or down — Default: -50 — Positions above clock to avoid hand interference.
Timezone — Selects reference city/offset — Default: New York (UTC-05) — Matches trading locale; verify offsets manually.
Summer Time (DST) — Adds one hour if active — Default: false — Enable for regions observing it; test transitions.
Show/Label/Session/Color for Each Market — Toggles arc, sets name, time window, and hue per session (New York/London/Tokyo/Sydney) — Defaults: true/"New York"/1300-2200/orange, etc. — Customize windows to local exchange hours; colors differentiate overlaps.
  Reading & Interpretation 
The analog face shows a blue-tinted circle with white 1-12 labels and gray hour ticks; hands extend from center in assigned colors, pointing to current positions. A white dot with orbiting ring marks exact time on the session arc. Digital readout below displays padded HH:MM:SS in white on black.
Active sessions glow with bold arcs and white labels on colored backgrounds; inactive ones use thin lines and colored text on light fills. Overlaps stack outward, with the innermost (New York) closest to the clock. If no session is active, the marker sits on the base ring.
  Practical Workflows & Combinations 
- Trend following: Enter longs during London-New York overlap (thicker dual arcs) confirmed by higher highs; filter with volume spikes.
- Exits/Stops: Tighten stops pre-Tokyo open if arc thickens, signaling volatility ramp; trail during Sydney for overnight holds.
- Multi-asset/Multi-TF: Defaults work across forex/stocks; on higher timeframes, enlarge clock size to counter bar spacing. Pair with session volume oscillators for confirmation.
  Behavior, Constraints & Performance 
Rendering occurs only on the last bar, using confirmed history for stable display; live bars update hands and marker without repainting prior elements. No security calls or higher timeframe fetches, so no lookahead bias.
Resource limits include 2000 bars back for positioning, 500 each for lines, labels, and boxes—sufficient for full sessions without overflow. Arrays hold timezone data statically. On very wide charts, projection may skew slightly due to fixed scale.
Known limits: Visual positioning drifts on extreme zooms; daylight savings assumes manual toggle, risking one-hour errors during changes.
  Sensible Defaults & Quick Tuning 
Start with New York timezone, 45-degree tilt, and all sessions enabled—these balance global coverage without clutter. For too-small visibility, bump clock size to 300 and resolution to 48. If labels overlap on narrow views, reduce hand lengths proportionally. To emphasize one session (e.g., London), disable others and widen its color contrast. For minimalism, set digital size to small and offset to -100.
  What this indicator is—and isn’t 
This is a visual time and session overlay to contextualize trading windows, not a signal generator or predictive tool. It complements price analysis and risk rules but requires manual interpretation. Use alongside order flow or momentum indicators 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 
  Acknowledgments 
This indicator draws inspiration from the open-source contributions of the TradingView community, whose advanced programming techniques have greatly influenced its development. Special thanks to LonesomeTheBlue for the innovative polyline handling and midpoint centering techniques in RSI Radar Multi Time Frame: 
Gratitude also extends to LuxAlgo for the precise timezone calculations in Sessions: 
Finally, appreciation to TradingView for their comprehensive documentation on polyline features, including the support article at www.tradingview.com and the blog post at www.tradingview.com These resources were instrumental in implementing smooth, dynamic drawings.
Multi-Mode Seasonality Map [BackQuant]Multi-Mode Seasonality Map  
 A fast, visual way to expose repeatable calendar patterns in returns, volatility, volume, and range across multiple granularities (Day of Week, Day of Month, Hour of Day, Week of Month). Built for idea generation, regime context, and execution timing. 
 What is “seasonality” in markets? 
 Seasonality refers to statistically repeatable patterns tied to the calendar or clock, rather than to price levels. Examples include specific weekdays tending to be stronger, certain hours showing higher realized volatility, or month-end flow boosting volumes. This tool measures those effects directly on your charted symbol.
 Why seasonality matters 
  
  It’s orthogonal alpha: timing edges independent of price structure that can complement trend, mean reversion, or flow-based setups.
  It frames expectations: when a session typically runs hot or cold, you size and pace risk accordingly.
  It improves execution: entering during historically favorable windows, avoiding historically noisy windows.
  It clarifies context: separating normal “calendar noise” from true anomaly helps avoid overreacting to routine moves.
  
 How traders use seasonality in practice 
  
  Timing entries/exits : If Tuesday morning is historically weak for this asset, a mean-reversion buyer may wait for that drift to complete before entering.
  Sizing & stops : If 13:00–15:00 shows elevated volatility, widen stops or reduce size to maintain constant risk.
  Session playbooks : Build repeatable routines around the hours/days that consistently drive PnL.
  Portfolio rotation : Compare seasonal edges across assets to schedule focus and deploy attention where the calendar favors you.
  
 Why Day-of-Week (DOW) can be especially helpful 
  
  Flows cluster by weekday (ETF creations/redemptions, options hedging cadence, futures roll patterns, macro data releases), so DOW often encodes a stable micro-structure signal.
  Desk behavior and liquidity provision differ by weekday, impacting realized range and slippage.
  DOW is simple to operationalize: easy rules like “fade Monday afternoon chop” or “press Thursday trend extension” can be tested and enforced.
  
 What this indicator does 
  
  Multi-mode heatmaps : Switch between  Day of Week, Day of Month, Hour of Day, Week of Month .
  Metric selection : Analyze  Returns ,  Volatility  ((high-low)/open),  Volume  (vs 20-bar average), or  Range  (vs 20-bar average).
  Confidence intervals : Per cell, compute mean, standard deviation, and a z-based CI at your chosen confidence level.
  Sample guards : Enforce a minimum sample size so thin data doesn’t mislead.
  Readable map : Color palettes, value labels, sample size, and an optional legend for fast interpretation.
  Scoreboard : Optional table highlights best/worst DOW and today’s seasonality with CI and a simple “edge” tag.
  
 How it’s calculated (under the hood) 
  
  Per bar, compute the chosen  metric  (return, vol, volume %, or range %) over your lookback window.
  Bucket that metric into the active calendar bin (e.g., Tuesday, the 15th, 10:00 hour, or Week-2 of month).
  For each bin, accumulate  sum ,  sum of squares , and  count , then at render compute  mean ,  std dev , and  confidence interval .
  Color scale normalizes to the observed min/max of eligible bins (those meeting the minimum sample size).
  
 How to read the heatmap 
  
  Color : Greener/warmer typically implies higher mean value for the chosen metric; cooler implies lower.
  Value label : The center number is the bin’s mean (e.g., average % return for Tuesdays).
  Confidence bracket : Optional “ ” shows the CI for the mean, helping you gauge stability.
  n = sample size : More samples = more reliability. Treat small-n bins with skepticism.
  
 Suggested workflows 
  
  Pick the lens : Start with  Analysis Type = Returns ,  Heatmap View = Day of Week ,  lookback ≈ 252 trading days . Note the best/worst weekdays and their CI width.
  Sanity-check volatility : Switch to  Volatility  to see which bins carry the most realized range. Use that to plan stop width and trade pacing.
  Check liquidity proxy : Flip to  Volume , identify thin vs thick windows. Execute risk in thicker windows to reduce slippage.
  Drill to intraday : Use  Hour of Day  to reveal opening bursts, lunchtime lulls, and closing ramps. Combine with your main strategy to schedule entries.
  Calendar nuance : Inspect  Week of Month  and  Day of Month  for end-of-month, options-cycle, or data-release effects.
  Codify rules : Translate stable edges into rules like “no fresh risk during bottom-quartile hours” or “scale entries during top-quartile hours.”
  
 Parameter guidance 
  
  Analysis Period (Days) : 252 for a one-year view. Shorten (100–150) to emphasize the current regime; lengthen (500+) for long-memory effects.
  Heatmap View : Start with DOW for robustness, then refine with Hour-of-Day for your execution window.
  Confidence Level : 95% is standard; use 90% if you want wider coverage with fewer false “insufficient data” bins.
  Min Sample Size : 10–20 helps filter noise. For Hour-of-Day on higher timeframes, consider lowering if your dataset is small.
  Color Scheme : Choose a palette with good mid-tone contrast (e.g., Red-Green or Viridis) for quick thresholding.
  
 Interpreting common patterns 
  
  Return-positive but low-vol bins : Favorable drift windows for passive adds or tight-stop trend continuation.
  Return-flat but high-vol bins : Opportunity for mean reversion or breakout scalping, but manage risk accordingly.
  High-volume bins : Better expected execution quality; schedule size here if slippage matters.
  Wide CI : Edge is unstable or sample is thin; treat as exploratory until more data accumulates.
  
 Best practices 
  
  Revalidate after regime shifts (new macro cycle, liquidity regime change, major exchange microstructure updates).
  Use multiple lenses: DOW to find the day, then Hour-of-Day to refine the entry window.
  Combine with your core setup signals; treat seasonality as a filter or weight, not a standalone trigger.
  Test across assets/timeframes—edges are instrument-specific and may not transfer 1:1.
  
 Limitations & notes 
  
  History-dependent: short histories or sparse intraday data reduce reliability.
  Not causal: a hot Tuesday doesn’t guarantee future Tuesday strength; treat as probabilistic bias.
  Aggregation bias: changing session hours or symbol migrations can distort older samples.
  CI is z-approximate: good for fast triage, not a substitute for full hypothesis testing.
  
 Quick setup 
  
  Use  Returns + Day of Week + 252d  to get a clean yearly map of weekday edge.
  Flip to  Hour of Day  on intraday charts to schedule precise entries/exits.
  Keep  Show Values  and  Confidence Intervals  on while you calibrate; hide later for a clean visual.
  
 The Multi-Mode Seasonality Map helps you convert the calendar from an afterthought into a quantitative edge, surfacing when an asset tends to move, expand, or stay quiet—so you can plan, size, and execute with intent.
ProScalper📊 ProScalper - Professional 1-Minute Scalping System
🎯 Overview
ProScalper is a sophisticated, multi-confluence scalping indicator designed specifically for 1-minute chart trading. Combining advanced technical analysis with intelligent signal filtering, it provides high-probability trade setups with clear entry, stop loss, and take profit levels.
✨ Key Features
🔺 Smart Signal Detection
Range Filter Technology: Fast-responding trend detection (25-period) optimized for 1-minute timeframe
Medium-sized triangles appear above/below candles for clear buy/sell signals
Only most recent signal shown - no chart clutter
Automatically deletes old signals when new ones appear
📋 Real-Time Signal Table
Top-center display shows complete trade breakdown
Grade system: A+, A, B+, B, C+ ratings for every setup
All confluence reasons listed with checkmarks
Score and R:R displayed for instant trade quality assessment
Color-coded: Green for LONG, Red for SHORT
📐 Multi-Confluence Analysis
ProScalper combines 10+ technical factors:
✅ EMA Trend: 4 EMAs (200, 48, 13, 8) for multi-timeframe alignment
✅ VWAP: Dynamic support/resistance
✅ Fibonacci Retracement: Golden ratio (61.8%), 50%, 38.2%, 78.6%
✅ Range Filter: Adaptive trend confirmation
✅ Pivot Points: Smart reversal detection
✅ Volume Analysis: Spike detection and volume profile
✅ Higher Timeframe: 5-minute trend confirmation
✅ HTF Support/Resistance: Key levels from higher timeframes
✅ Liquidity Sweeps: Smart money detection
✅ Opening Range Breakout: First 15-minute range
💰 Complete Trade Management
Entry Lines: Dashed green (LONG) or red (SHORT) showing exact entry
Stop Loss: Red dashed line with price label
Take Profit: Blue dashed line with price label and R:R
Partial Exits: 1R level marked with orange dashed line
All lines extend 10 bars for clean alignment with Fibonacci levels
📊 Dynamic Risk/Reward
Adaptive R:R calculation based on market volatility
Targets adjusted for pivot distances
Minimum 1.2:1 to maximum 3.5:1 for scalping
Position sizing based on account risk percentage
🎨 Professional Visualization
Clean chart layout - no clutter, only essential information
Custom EMA colors: Red (200), Aqua (48), Green (13), White (8)
Gold VWAP line for key support/resistance
Color-coded Fibonacci: Bright yellow (61.8%), white (50%), orange (38.2%), fuchsia (78.6%)
No shaded zones - pure price action focus
📈 Performance Tracking
Real-time statistics table (optional)
Win rate, total trades, P&L tracking
Average R:R and win/loss ratios
Setup-specific performance metrics
⚙️ Settings & Customization
Risk Management
Adjustable account risk per trade (default: 0.5%)
ATR-based stop loss multiplier (default: 0.8 for tight scalping)
Dynamic position sizing
Signal Sensitivity
Confluence Score Threshold: 40-100 (default: 55 for balanced signals)
Range Filter Period: 25 bars (fast signals for 1-min)
Range Filter Multiplier: 2.2 (tighter bands for more signals)
Visual Controls
Toggle signal table on/off
Show/hide Fibonacci levels
Control EMA visibility
Adjust table text size
Partial Exits
1R: 50% (default)
2R: 30% (default)
3R: 20% (default)
Fully customizable percentages
Trailing Stops
ATR-Based (best for scalping)
Pivot-Based
EMA-Based
Breakeven trigger at 0.8R
🎯 Best Use Cases
Ideal For:
✅ 1-minute scalping on liquid instruments
✅ Day traders looking for quick 2-8 minute trades
✅ High-frequency trading with 8-15 signals per session
✅ Trending markets where Range Filter excels
✅ Crypto, Forex, Futures - works on all liquid assets
Trading Style:
Timeframe: 1-minute (can work on 3-5 min with adjusted settings)
Hold Time: 3-8 minutes average
Target: 1.2-3R per trade
Frequency: 8-15 signals per day
Win Rate: 45-55% (with proper risk management)
📋 How to Use
Step 1: Wait for Signal
Watch for green triangle (BUY) or red triangle (SELL)
Signal table appears at top center automatically
Step 2: Review Confluence
Check grade (prefer A+, A, B+ for best quality)
Review all reasons listed in table
Confirm score is above your threshold (55+ recommended)
Note the R:R ratio
Step 3: Enter Trade
Enter at current market price
Set stop loss at red dashed line
Set take profit at blue dashed line
Mark 1R level (orange line) for partial exit
Step 4: Manage Trade
Exit 50% at 1R (orange line)
Move to breakeven after 0.8R
Trail remaining position using your chosen method
Exit fully at TP or opposite signal
🎨 Chart Setup Recommendations
Optimal Display:
Timeframe: 1-minute
Chart Type: Candles or Heikin Ashi
Background: Dark theme for best color visibility
Volume: Enable volume bars below chart
Complementary Indicators (optional):
Order flow/Delta for institutional confirmation
Market profile for key levels
Economic calendar for news avoidance
⚠️ Important Notes
Risk Disclaimer:
Not financial advice - for educational purposes only
Always use proper risk management (0.5-1% per trade max)
Past performance doesn't guarantee future results
Test on demo account before live trading
Best Practices:
✅ Trade during high liquidity hours (9:30-11 AM, 2-4 PM EST)
✅ Avoid news events and market open/close (first/last 2 minutes)
✅ Use tight stops (0.8-1.0 ATR) for 1-minute scalping
✅ Take partial profits quickly (1R = 50% off)
✅ Respect max daily loss limits (3% recommended)
✅ Focus on A and B grade setups for consistency
What Makes This Different:
🎯 Complete system - not just signals, but full trade management
📊 Multi-confluence - 10+ factors analyzed per trade
🎨 Professional visualization - clean, focused chart design
⚡ Optimized for 1-min - settings specifically tuned for fast scalping
📋 Transparent reasoning - see exactly why each trade was taken
🏆 Grade system - instantly know trade quality
🔧 Technical Details
Pine Script Version: 5
Overlay: Yes (plots on price chart)
Max Lines: 500
Max Labels: 100
Non-repainting: All signals confirmed on bar close
Alerts: Compatible with TradingView alerts
📞 Support & Updates
This indicator is actively maintained and optimized for 1-minute scalping. Settings can be adjusted for different timeframes and trading styles, but default configuration is specifically tuned for high-frequency 1-minute scalping.
🚀 Get Started
Add ProScalper to your 1-minute chart
Adjust settings to your risk tolerance
Wait for signals (green/red triangles)
Follow the signal table guidance
Manage trades using provided levels
Track performance with stats table
Happy Scalping! 📊⚡💰
Automated Z-scoring - [JTCAPITAL]Automated Z-Scoring -   is a modified way to use  statistical normalization through Z-Scores  for analyzing price deviations, volatility extremes, and mean reversion opportunities in financial markets.
The indicator works by calculating in the following steps:
 
   Source Selection 
The indicator begins by selecting a user-defined price source (default is the  Close  price). Traders can modify this to use any indicator that is deployed on the chart, for accurate and fast Z-scoring.
   Mean Calculation 
A  Simple Moving Average (SMA)  is calculated over the selected  length  period (default 3000). This represents the long-term equilibrium price level or the “statistical mean” of the dataset. It provides the baseline around which all price deviations are measured.
   Standard Deviation Measurement 
The script computes the  Standard Deviation  of the price series over the same period. This value quantifies how far current prices tend to stray from the mean — effectively measuring market volatility. The larger the standard deviation, the more volatile the market environment.
   Z-Score Normalization 
The  Z-Score  is calculated as:
 (Current Price − Mean) ÷ Standard Deviation .
This normalization expresses how many standard deviations the current price is away from its long-term average. A Z-Score above 0 means the price is above average, while a negative score indicates it is below average.
   Visual Representation 
The Z-Score is plotted dynamically, with color-coding for clarity:
Bullish readings (Z > 0) are showing positive deviation from the mean.
Bearish readings (Z < 0) are showing negative deviation from the mean.
 Make sure to select the correct source for what you exactly want to Z-score. 
 
 Buy and Sell Conditions: 
While the indicator itself is designed as a  statistical framework  rather than a direct buy/sell signal generator, traders can derive actionable strategies from its behavior:
 Trend Following:  When the Z-Score crosses above zero after a prolonged negative period, it suggests a return to or above the mean — a possible bullish reversal or trend continuation signal. 
 Mean Reversion:  When the Z-score is below for example -1.5 it indicates a good time for a DCA buying opportunity.
 Trend Following:  When the Z-Score crosses below zero after being positive, it may indicate a momentum slowdown or bearish shift. 
 Mean Reversion:  When the Z-score is above for example 1.5 it indicates a good time for a DCA sell opportunity
 Features and Parameters: 
 Length  – Defines the period for both SMA and Standard Deviation. A longer length smooths the Z-Score and captures broader market context, while a shorter length increases responsiveness.
 Source  – Allows the user to choose which price data is analyzed (Close, Open, High, Low, etc.).
 Fill Visualization  – Highlights the magnitude of deviation between the Z-Score and the zero baseline, enhancing readability of volatility extremes.
 Specifications: 
 Mean (Simple Moving Average) 
The SMA calculates the average of the selected source over the defined length. It provides a central value to which the price tends to revert. In this indicator, the mean acts as the equilibrium point — the “zero” reference for all deviations.
 Standard Deviation 
Standard Deviation measures the dispersion of data points from their mean. In trading, it quantifies volatility. A high standard deviation indicates that prices are spread out (volatile), while a low value means they are clustered near the average (stable). The indicator uses this to scale deviations consistently across different market conditions.
 Z-Score 
The Z-Score converts raw price data into a standardized value measured in units of standard deviation.
A Z-Score of 0 = Price equals its mean.
A Z-Score of +1 = Price is one standard deviation above the mean.
A Z-Score of −1 = Price is one standard deviation below the mean.
This allows comparison of deviation magnitudes across instruments or timeframes, independent of price level.
 Length Parameter 
A long lookback period (e.g., 3000 bars) smooths temporary volatility and reveals long-term mean deviations — ideal for macro trend identification. Shorter lengths (e.g., 100–500) capture quicker oscillations and are useful for short-term mean reversion trades.
 Statistical Interpretation 
From a probabilistic perspective, if the distribution of prices is roughly normal:
About 68% of price observations lie within ±1 standard deviation (Z between −1 and +1).
About 95% lie within ±2 standard deviations.
Therefore, when the Z-Score moves beyond ±2, it statistically represents a rare event — often corresponding to price extremes or potential reversal zones.
 Practical Benefit of Z-Scoring in Trading 
Z-Scoring transforms raw price into a normalized volatility-adjusted metric. This allows traders to:
Compare instruments on a common statistical scale.
Identify mean-reversion setups more objectively.
Spot volatility expansions or contractions early.
Detect when price action significantly diverges from long-term equilibrium.
By automating this process,  Automated Z-Scoring -   provides traders with a powerful analytical lens to measure how “stretched” the market truly is — turning abstract statistics into a visually intuitive and actionable form.
Enjoy!
Pullback Levels from ATH# ATH Pullback Levels  
**Assess correction depth with precision – 5%, 10%, 15%, 20% below All-Time High**
---
### Overview  
This indicator draws **horizontal support lines** at **5%, 10%, 15%, and 20%** below the **All-Time High (ATH)** of any asset. Perfect for **swing traders**, **long-term investors**, and **bull market participants** who want to:
- Measure **pullback depth** in real-time  
- Identify **potential support zones**  
- Set **alerts** when price enters key retracement levels  
---
### Features  
| Feature | Description |
|--------|-------------|
| **Dynamic ATH Tracking** | Automatically updates with every new high |
| **4 Pullback Levels** | 5%, 10%, 15%, 20% below ATH |
| **Live Pullback % Label** | Shows current % drop from ATH (top-right) |
| **Customizable Lines** | Toggle visibility, change colors & styles |
| **Built-in Alerts** | Trigger on entry into each zone |
| **No Errors** | Works on 50k+ bar charts (BTC, SPX, etc.) |
| **Time-Based Lines** | Uses `xloc.bar_time` – no 500-bar future limit |
---
### How to Use  
1. Apply to any chart (stocks, crypto, forex, indices)  
2. Watch the **info box** for current pullback %  
3. Use lines as **potential buy zones** during corrections  
4. Set **alerts** to be notified when price enters a level  
> Example: If ATH = $100 →  
> - 5% = $95  
> - 10% = $90  
> - 15% = $85  
> - 20% = $80  
---
### Inputs  
- **Show 5% / 10% / 15% / 20% Level** → Toggle on/off  
- **Line Colors** → Fully customizable  
- **Line Style** → Solid, Dashed, or Dotted  
---
### Alerts  
Create alerts directly from the indicator:  
- `"Entered 5% Pullback"`  
- `"Entered 10% Pullback"`  
- etc.  
---
### Best For  
- Bull market corrections  
- Long-term position sizing  
- Risk management in uptrends  
- Swing entries on dips  
---
### Notes  
- Works on **all timeframes**  
- **Log scale compatible** (lines adjust correctly)  
- No repainting – ATH only updates on confirmed highs  
---
**Built with Pine Script v6 – Clean, fast, reliable.**
*Happy trading!*  
Easy Read Short‑Term EMA CrossoverThis TradingView panel shows a multi-indicator setup for analyzing the S&P 500 Index (SPX):
Main chart (top): displays price candles with two Exponential Moving Averages (EMA 8 and 21). When the short-term EMA (blue) crosses above the long-term EMA (red), it gives a Buy signal; when it crosses below, a Sell signal appears — helping identify short-term trend shifts.
Middle panel: shows the Easy-Read RSI, highlighting overbought (OB) and oversold (OS) zones. When RSI moves above 70 it signals potential weakness (sell), and below 30 suggests a rebound zone (buy).
Bottom panel: plots the Easy-Read MACD, which tracks momentum by comparing short- and long-term moving averages. When the MACD line crosses above the Signal line, it indicates bullish momentum; crossing below suggests bearish momentum.
Together, these three indicators provide a layered view of trend, momentum, and potential entry/exit points.






















