smartAitrade Complete FocusTrendPajinko-SmartAiTrade Complete is an all-in-one price-action technical system designed for high-precision entries, intelligent trade management, and fully automated exit logic.
The system combines RSI swings, advanced divergence detection, ATR-based PJK Bands, smart retest logic, swing-break POI zones, trend filters (ADX), and automated breakeven/TP management into a single integrated indicator.
It is built to support traders who want structured, rule-based entries with minimal discretion, while still maintaining the flexibility of price-action behavior.
🔍 Core Components
1. RSI System
Standard RSI for overbought/oversold levels.
RSI Swing High/Low detection (using pivots).
Used for:
momentum confirmation
swing structure alignment
divergence detection filters
2. Advanced Divergence Engine
The indicator features a high-accuracy divergence module that detects:
• Bullish Divergence
Price makes a lower low
RSI makes a higher low
Pivot distances must fall within a valid bar-range
Optional filter: RSI must be in oversold zone
• Bearish Divergence
Price makes a higher high
RSI makes a lower high
Optional filter: RSI must be in overbought zone
You can choose to draw divergence lines on either:
RSI only
Price chart
Both
This system is optimized for low repaint and filters weak divergence signals.
3. ATR-Based PJK Bands System
A volatility-adaptive band system similar to Keltner/Bollinger hybrids:
Middle line uses SMA/EMA/VWMA
Upper/lower bands = middle ± ATR × multiplier
Bands detect:
momentum breakouts
band touch signals
high-probability reversal zones
Buy signal:
Price touches lower band and shifts upward
Sell signal:
Price touches upper band and shifts downward
4. Smart Retest System
After a momentum breakout or band touch signal:
A “smart retest zone” is created
The system waits for price to come back to the zone
If retest occurs within a user-defined timeout window, the signal is validated
Used to avoid chasing entries and reduce false breakouts
5. Swing Break & POI Zones
The indicator automatically detects price-swing structure:
Swing High Break → Sell POI box created
Swing Low Break → Buy POI box created
POI zones:
Represent potential liquidity pockets
Drawn with customizable height and width
Work as target areas or confirmation zones
6. ADX Trend Filter
ADX trend strength filter ensures signals are valid only when:
Trend strength > threshold (default 20)
Avoids signals in flat, low-volatility markets
7. Auto Trade Management (Breakeven System)
Fully automated exit logic:
TP1 distance set in pips
Once TP1 is reached → move Stop Loss to breakeven + offset
Additional option:
Close all open positions automatically when trend bias changes
Everything works even with multiple open trades.
8. Dashboard & Visual Interface
The indicator includes a clean dashboard showing:
Trend condition
RSI status
Advanced divergence status
Band and swing conditions
Active signals
Breakeven status
Total signals statistics
All visual components can be enabled/disabled individually.
🎯 Trading Philosophy
The system is built on three core principles:
1. Confirm Trend
ADX + ATR Bands define direction and strength.
2. Identify High-Probability Reversal or Continuation Zones
Smart Retest + Swing Structure + POI + Divergence.
3. Automate the Exit
Breakeven, TP1, and automatic closing keep emotions out of the decision.
Statistics
COT Index by Luis TrompeterThe COT Index transforms the weekly COT net positions of Commercial traders into a normalized mathematical model.
Instead of displaying raw net positioning, the COT Index processes the data through a cyclical normalization algorithm (commonly using a 26-week or alternatively a 52-week cycle).
This makes it easier to identify bullish or bearish extremes in Commercial activity.
The index is plotted as a color-coded line:
• Green Zone – Commercials are mathematically classified as bullish.
Historically, bullish Commercial positioning often aligns with upward market pressure.
• Red Zone – Commercials are mathematically classified as bearish.
This typically corresponds with increased downward pressure in the underlying market.
• Neutral Zone – Neither bull nor bear dominance; positioning is mid-range.
Since COT data is published only once per week and the COT Index is built on cyclical multi-week analysis, the indicator is intended to be used exclusively on the weekly timeframe.
Using lower timeframes will not reflect the structure of the data accurately.
The selected cycle length (typically 26 weeks, optionally 52 weeks) determines how net positions are compared and normalized, and can influence how quickly extreme zones appear.
The COT Index provides an objective way to interpret Commercial trader sentiment and to identify potential directional bias in the market.
Volatility Signal-to-Noise Ratio🙏🏻 this is VSNR: the most effective and simple volatility regime detector & automatic volatility threshold scaler that somehow no1 ever talks about.
This is simply an inverse of the coefficient of variation of absolute returns, but properly constructed taking into account temporal information, and made online via recursive math with algocomplexity O(1) both in expanding and moving windows modes.
How do the available alternatives differ (while some’re just worse)?
Mainstream quant stat tests like Durbin-Watson, Dickey-Fuller etc: default implementations are ALL not time aware. They measure different kinds of regime, which is less (if at all) relevant for actual trading context. Mix of different math, high algocomplexity.
The closest one is MMI by financialhacker, but his approach is also not time aware, and has a higher algocomplexity anyways. Best alternative to mine, but pls modify it to use a time-weighted median.
Fractal dimension & its derivatives by John Ehlers: again not time aware, very low info gain, relies on bar sizes (high and lows), which don’t always exist unlike changes between datapoints. But it’s a geometric tool in essence, so this is fundamental. Let it watch your back if you already use it.
Hurst exponent: much higher algocomplexity, mix of parametric and non-parametric math inside. An invention, not a math entity. Again, not time aware. Also measures different kinds of regime.
How to set it up:
Given my other tools, I choose length so that it will match the amount of data that your trading method or study uses multiplied by ~ 4-5. E.g if you use some kind of bands to trade volatility and you calculate them over moving window 64, put VSNR on 256.
However it depends mathematically on many things, so for your methods you may instead need multipliers of 1 or ~ 16.
Additionally if you wanna use all data to estimate SNR, put 0 into length input.
How to use for regime detection:
First we define:
MR bias: mean reversion bias meaning volatility shorts would work better, fading levels would work better
Momo bias: momentum bias meaning volatility longs would work better, trading breakouts of levels would work better.
The study plots 3 horizontal thresholds for VSNR, just check its location:
Above upper level: significant Momo bias
Above 1 : Momo bias
Below 1 : MR bias
Below lower level: significant MR bias
Take a look at the screenshots, 2 completely different volatility regimes are spotted by VSNR, while an ADF does not show different regime:
^^ CBOT:ZN1!
^^ INDEX:BTCUSD
How to use as automatic volatility threshold scaler
Copy the code from the script, and use VSNR as a multiplier for your volatility threshold.
E.g you use a regression channel and fade/push upper and lower thresholds which are RMSEs multiples. Inside the code, multiply RMSE by VSNR, now you’re adaptive.
^^ The same logic as when MM bots widen spreads with vola goes wild.
How it works:
Returns follow Laplace distro -> logically abs returns follow exponential distro , cuz laplace = double exponential.
Exponential distro has a natural coefficient of variation = 1 -> signal to noise ratio defined as mean/stdev = 1 as well. The same can be said for Student t distro with parameter v = 4. So 1 is our main threshold.
We can add additional thresholds by discovering SNRs of Student t with v = 3 and v = 5 (+- 1 from baseline v = 4). These have lighter & heavier tails each favoring mean reversion or momentum more. I computed the SNR values you see in the code with mpmath python module, with precision 256 decimals, so you can trust it I put it on my momma.
Then I use exponential smoothing with properly defined alphas (one matches cumulative WMA and another minimizes error with WMA in moving window mode) to estimate SNR of abs returns.
…
Lightweight huh?
∞
MarketSmith / MarketSurge Style VolumesPurpose
Emulates MarketSmith-style volume analysis in TradingView.
Focused on abnormal volume, institutional footprints, and volume vs. average.
Core Display
Plots a volume histogram with a volume moving average (daily or weekly length).
Optional truncation: caps bars at 2× average volume for cleaner scaling.
Bar colors:
Up/down based on current vs. previous close.
Optional special colour for low relative volume (10-bar lows).
Highest-Volume Logic (HVE / HV1)
Detects:
HVE – Highest Volume Ever.
HV1 – Highest Volume in Over a Year (252D / 52W / 12M).
Labels key peaks with:
“HVE” / “HV1” tags.
Optional shares traded (K/M/B) and % above volume MA.
Uses pivot logic over a configurable Peak Length to anchor volume peaks.
Current Bar Labels
On the latest bar, shows:
Formatted volume (K/M/B).
Volume buzz = % above/below average volume.
Buzz label colored green/red depending on positive or negative reading.
Volume Buzz & Trend Context
volBuzz = 100 * (vol / MA – 1) plotted as a separate series.
Highlights stretches of unusually high or low activity relative to the norm.
Up / Down Volume Ratio
Sums up-volume and down-volume over the last 50 bars.
Computes Up/Down Volume Ratio = sumUp / sumDn to gauge buying vs. selling pressure.
Info Table (Top-Right)
Optional small table showing:
Avg Volume (K/M/B).
Avg Dollar Volume (close × MA).
U/D Volume Ratio.
Optional current volume and current buzz with positive/negative colors.
Overall
Not a signal system—it's a volume-reading assistant.
Helps identify true standout volume, institutional spikes, and quiet vs. aggressive trading conditions at a glance.
IBD Style - EPS & SalesPurpose
Brings MarketSmith/MarketSurge-style fundamentals directly into TradingView.
Designed for growth traders using EPS, sales, and acceleration as core criteria.
Data & Detection
Automatically detects earnings events from TradingView data.
Reconstructs up to 8 quarters of EPS and revenue.
Distinguishes actual vs. standardized EPS, fills missing values, fixes irregularities.
Weekly Earnings Table
Shows EPS, YoY & QoQ growth, EPS surprises, sales, sales growth, margin, ROE.
Dynamically scales revenue (millions/billions).
Alternating row colours + MarketSmith / MarketSurge themes.
Daily HeadBand Table
Condensed view of last 4 quarters.
Shows growth metrics + next earnings date.
Chart Annotations
Optional earnings arrows with EPS% (and sales%).
MarketSmith-style coloring and ±999% limits.
“Digits-only” mode for clean charts.
Data Safeguards
Handles negative EPS cases (#), duplicated values, missing quarters, and reporting irregularities.
Overall
Not a signal tool—an integrated fundamental visualization framework.
Lets traders see earnings acceleration, revenue strength, and profitability without leaving the chart.
IBD Style RS Rating Line IndicatorPurpose
Measures relative performance, not just price action.
Recreates the IBD-style 1–99 RS Rating inside TradingView.
RS Line
Plots stock price relative to a benchmark (default: SPX).
Scaled for readability; supports indices and sectors.
Optional MA overlays and positive/negative fill zones.
RS New Highs / New Lows
Scans a user-defined lookback.
Marks RS new highs (blue) and new lows (red).
Modes for historical, last-bar-only, or “RS leads price.”
RS Rating (1–99)
Calculates a weighted performance score over 1–12 months.
Compares this score to market-wide thresholds pulled via request.seed().
Converts score into percentile bands (e.g., 70–89, 90–98).
Assigns 99 to top leaders and 1 to laggards.
Fallback Logic
Missing environment data = shows “RS” without a number.
Replay mode uses fixed thresholds to approximate ratings.
Output
Clean label showing RS Rating near the RS line.
Helps traders instantly judge whether a stock is a true leader.
Z-Score Regime DetectorThe Z-Score Regime Detector is a statistical market regime indicator that helps identify bullish and bearish market conditions based on normalized momentum of three core metrics:
- Price (Close)
- Volume
- Market Capitalization (via CRYPTOCAP:TOTAL)
Each metric is standardized using the Z-score over a user-defined period, allowing comparison of relative extremes across time. This removes raw value biases and reveals underlying momentum structure.
📊 How it Works
- Z-Score: Measures how far a current value deviates from its average in terms of standard deviations.
- A Bullish Regime is identified when both price and market cap Z-scores are above the volume Z-score.
- A Bearish Regime occurs when price and market cap Z-scores fall below volume Z-score.
Bias Signal:
- Bullish Bias = Price Z-score > Market Cap Z-score
- Bearish Bias = Market Cap Z-score > Price Z-score
This provides a statistically consistent framework to assess whether the market is flowing with strength or stress.
✅ Why This Might Be Effective
- Normalizing the data via Z-scores allows comparison of diverse metrics on a common scale.
- Using market cap offers broader insight than price alone, especially for crypto.
- Volume as a reference threshold helps identify accumulation/distribution regimes.
- Simple regime logic makes it suitable for trend confirmation, filtering, or position biasing in systems.
⚠️ Disclaimer
This script is for educational purposes only and should not be considered financial advice. Always perform your own research and risk management. Past performance is not indicative of future results. Use at your own discretion.
NeuraAlgo - Market DynamicsNeuraAlgo – Market Dynamics
Simplyfying the Market Dynamics
Unlock the complexity of financial markets with NeuraAlgo – Market Dynamics. Designed for traders and investors alike, this intelligent tool distills the chaos of price movements, volume fluctuations, and trend directions into clear, actionable insights. With advanced algorithms working behind the scenes, it simplifies market dynamics so you can focus on making informed decisions, spotting opportunities, and managing risk with confidence.
Behind this simple overlay lies a powerful, complex algorithm.
Main Settings -Main Algorithm
Timeframe – Choose the chart timeframe that the indicator will analyze. It adapts the calculations to the selected interval for precise market insights.
Preset – Select the operating mode:
Main Trend: Focuses on the dominant market trend.
Multi Trend: Analyzes multiple trend layers for a broader perspective.
Sensitivity – Adjusts the indicator’s responsiveness to price changes. Higher values make the system more reactive to market fluctuations, while lower values smooth out minor noise.
Smooth Tuner – Controls the smoothing of the underlying calculations, helping to reduce false signals and provide cleaner trend visualization.
Orderflow Statistics – Toggle to display detailed order flow statistics directly on the chart for deeper market analysis.
Performance Statistics – Toggle to enable backtesting tables, showing historical performance metrics of the indicator for strategy evaluation.
2.Art Settings -Change Visuals
Color Scheme – Select a pre-defined visual theme for your charts:
Bright Light – High-contrast, vibrant colors for maximum clarity.
Freezer Mode – Cool-toned palette for calm, visually comfortable analysis.
Standard Mode – Balanced, neutral colors for everyday use.
Delta Mode – Highlights key differences and movements with distinct colors.
Custom – Fully customize the colors of bullish, bearish, and range elements.
Green / Red / Range (Custom Colors) – When “Custom” is selected, these options allow you to define the colors for bullish (Green), bearish (Red), and neutral/range areas (Range) according to your preference.
Candle Coloring Type – Choose how candles are highlighted based on market signals:
Confirmation Simple – Basic signal-based coloring for clear, direct visualization.
Confirmation Gradient – Smooth gradient-based coloring for more dynamic and aesthetic signal representation.
3.Dashboard -Market Statistics
The Dashboard provides a compact, at-a-glance overview of key market conditions and indicator metrics, helping traders make faster and more informed decisions.
Functionality & Layout – The dashboard dynamically displays multiple sections:
Optimal Scale ⚖️ – Shows key market scaling metrics like volatility for better decision-making.
Risk Manager 📊 – Indicates the active risk management strategy (e.g., Risk-Reward, Partial Exits, or Trailing Stop Loss).
Orderflow Statistics 📈 – Displays market sentiment, footprint strength, and delta trends for precise order flow analysis.
Market Status 🌐 – Highlights current trend conditions and trend strength across different timeframes.
Bias Scores 🎯 – Provides trend strength percentages across multiple timeframes (5min, 15min, 30min, 1H, 4H, 1D) to quickly gauge market bias.
Backtest Performance -A summary panel showing the overall performance of the strategy.
Deposit -The starting capital used for backtesting.
Win Trades -Total number of profitable trades.
Winrate -Percentage of winning trades out of all trades.
Max DD -Maximum drawdown — the largest peak-to-trough loss.
PnL -Net profit or loss generated by the strategy.
Return -Percentage growth of the account during the test.
Profit Factor -Ratio of total profits to total losses.
The dashboard uses color-coded indicators (green for bullish, red for bearish, yellow for neutral) and merged cells for a clean and organized display.
It’s designed to simplify complex market dynamics into a visually intuitive interface, giving traders real-time insights without cluttering the chart.
4.Neura Engineering – Enhancements
This section provides advanced filtering options to fine-tune market analysis, reduce noise, and highlight meaningful trends.
Noise Filter – Smoothens minor price fluctuations to reduce false signals.Noise Sensitivity helps Adjust how aggressively the filter suppresses noise.
Gap Filter – Detects and smooths price gaps to improve trend clarity.Gap Sensitivity helps Controls the responsiveness of the gap filter.
Range Filter – Filters out small-range price movements to focus on significant market swings.helps Adjusts how tightly the filter defines meaningful ranges.
Volatility Filter – Highlights periods of high market volatility while filtering less active periods.helps Sets the threshold for what constitutes high volatility.
Trend Filter – Focuses analysis on strong trends by filtering out weaker signals.helps Determines the minimum strength required for a trend to be considered valid.helps Uses Average True Range to dynamically adjust trend filtering based on market movement.
These enhancement tools allow traders to customize signal clarity, reduce noise, and focus on meaningful market dynamics, creating a cleaner and more actionable charting experience.
5.Neura Overlays – Market Visual Enhancements
These overlays add visual intelligence to your chart, helping you instantly understand trend behavior, sentiment shifts, and price structure.
Reversal Cloud - Highlights potential reversal zones where price may change direction.Reversal Sensitivity helps Controls how quickly the cloud reacts to shifts in momentum.
Sentiment Cloud -Maps the underlying market mood—bullish, bearish, or neutral—directly onto the chart.Sentiment Sensitivity helps Adjusts how sensitive the sentiment readings are.
Price Steps -Draws structured “price steps” that reveal hidden market rhythm, impulse strength, and trend flow.Price Step Depth helps Determines the size and spacing of these steps.
Market Bias -Shows directional bias based on deeper trend pressure and underlying orderflow.Bias Sensitivity helps Controls how strict or lenient the bias detection is.
6.Risk Management Settings – Intelligent Trade Control
This module controls how your trades manage themselves after entry. Choose between traditional Risk/Reward exits, partial profit-taking, or an adaptive trailing stop system.
RiskReward
A classic risk-to-reward exit system.You set a risk multiple (e.g., 1:2), and the indicator automatically sets one Stop Loss and one Take Profit based on that ratio.
Partials
Scales out your position at multiple take-profit levels.Instead of closing the entire trade at once, the system secures profits gradually at TP1, TP2, and TP3 while keeping the remainder running.
TrailingStop
Uses a dynamic stop loss that follows price as it moves in your favor.There is no fixed Take Profit; instead, the trailing stop locks in profit and exits the trade automatically when momentum reverses.
7.Automatic Alert System
This is the System that organizes all settings related to the automatic webhook alert creator inside the indicator.
Rule No. 1 is never lose money. Rule No. 2 is never forget Rule No. 1.
Warren Buffet
NeuraAlgo – Market Dynamics transforms complex market behavior into clear, actionable insights for smarter trading decisions.
Relative PerformanceCompare the relative and actual performance of up to 15 tickers against the current market being charted across multiple timeframes. Customisable look back periods and alerts configured. All data is displayed in a dynamic table for the market selected.
Shareline_Momentum_DataFeedupdated version for data feed indicator to feed data to other indicators and strategys.
Shareline_Momentum_DataFeed.V1.0This script is a data feed script which provides data to other indicators and strategys. It is the master to understand how indicators can work.
Leverage LineLeverage Line is an indicator represented by a simple line. This line corresponds to the average of three other values:
- The current price of the listed asset
- The average price calculated since the asset's listing based on TradingView data
- The equilibrium price between supply and demand
This indicator can be used on all assets. Regarding timeframes, they can be used on all of them, although the line's movements and position will not change in any case. However, if you want a broader view, you absolutely can. But for the best views, for bounces or breakout confirmations, I highly recommend the weekly timeframe, and occasionally the daily one as well, but the weekly one is truly the best.
I hope this indicator will allow you to better visualize where the price is supposed to be, and that you will adapt it to your trading or even create your own strategies with it.
Glebesqu,
Sincerely.
P/E, EPS, Price & Price-to-Sales DisplayPrice to earning ratio,
EPS,
Price ANd
Price-to-Sales Display
ATR multiple from High & LowA simple numerical indicator measuring ATR multiple from recent 252 days high and low.
ATR multiples from high (and low) are used as a base in many systematic trading and trend following systems. As an example many systems buy after a 2.5–4 ATR multiple pullback in a strong stock if the regime allows it. This would then be paired with an entry tactic, for example buy as it recaptures the a pivot within the upper range, a MA or breaks out again after this mid term pullback/shakeout.
This indicator uses a function which captures the recent high and low no matter if we have 252 bars or not, which is not how standard high/low works in Tradingview. This means it also works with recent IPO:s.
I prefer to overlay the indicator in one of the lower panes, for example the volume pane and then right click on the indicator and select Pin to scale > No scale (fullscreen).
Static K-means Clustering | InvestorUnknownStatic K-Means Clustering is a machine-learning-driven market regime classifier designed for traders who want a data-driven structure instead of subjective indicators or manually drawn zones.
This script performs offline (static) K-means training on your chosen historical window. Using four engineered features:
RSI (Momentum)
CCI (Price deviation / Mean reversion)
CMF (Money flow / Strength)
MACD Histogram (Trend acceleration)
It groups past market conditions into K distinct clusters (regimes). After training, every new bar is assigned to the nearest cluster via Euclidean distance in 4-dimensional standardized feature space.
This allows you to create models like:
Regime-based long/short filters
Volatility phase detectors
Trend vs. chop separation
Mean-reversion vs. breakout classification
Volume-enhanced money-flow regime shifts
Full machine-learning trading systems based solely on regimes
Note:
This script is not a universal ML strategy out of the box.
The user must engineer the feature set to match their trading style and target market.
K-means is a tool, not a ready made system, this script provides the framework.
Core Idea
K-means clustering takes raw, unlabeled market observations and attempts to discover structure by grouping similar bars together.
// STEP 1 — DATA POINTS ON A COORDINATE PLANE
// We start with raw, unlabeled data scattered in 2D space (x/y).
// At this point, nothing is grouped—these are just observations.
// K-means will try to discover structure by grouping nearby points.
//
// y ↑
// |
// 12 | •
// | •
// 10 | •
// | •
// 8 | • •
// |
// 6 | •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 2 — RANDOMLY PLACE INITIAL CENTROIDS
// The algorithm begins by placing K centroids at random positions.
// These centroids act as the temporary “representatives” of clusters.
// Their starting positions heavily influence the first assignment step.
//
// y ↑
// |
// 12 | •
// | •
// 10 | • C2 ×
// | •
// 8 | • •
// |
// 6 | C1 × •
// |
// 4 | •
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
//
//
// STEP 3 — ASSIGN POINTS TO NEAREST CENTROID
// Each point is compared to all centroids.
// Using simple Euclidean distance, each point joins the cluster
// of the centroid it is closest to.
// This creates a temporary grouping of the data.
//
// (Coloring concept shown using labels)
//
// - Points closer to C1 → Cluster 1
// - Points closer to C2 → Cluster 2
//
// y ↑
// |
// 12 | 2
// | 1
// 10 | 1 C2 ×
// | 2
// 8 | 1 2
// |
// 6 | C1 × 2
// |
// 4 | 1
// |
// 2 |______________________________________________→ x
// 2 4 6 8 10 12 14
//
// (1 = assigned to Cluster 1, 2 = assigned to Cluster 2)
// At this stage, clusters are formed purely by distance.
Your chosen historical window becomes the static training dataset , and after fitting, the centroids never change again.
This makes the model:
Predictable
Repeatable
Consistent across backtests
Fast for live use (no recalculation of centroids every bar)
Static Training Window
You select a period with:
Training Start
Training End
Only bars inside this range are used to fit the K-means model. This window defines:
the market regime examples
the statistical distributions (means/std) for each feature
how the centroids will be positioned post-trainin
Bars before training = fully transparent
Training bars = gray
Post-training bars = full colored regimes
Feature Engineering (4D Input Vector)
Every bar during training becomes a 4-dimensional point:
This combination balances: momentum, volatility, mean-reversion, trend acceleration giving the algorithm a richer "market fingerprint" per bar.
Standardization
To prevent any feature from dominating due to scale differences (e.g., CMF near zero vs CCI ±200), all features are standardized:
standardize(value, mean, std) =>
(value - mean) / std
Centroid Initialization
Centroids start at diverse coordinates using various curves:
linear
sinusoidal
sign-preserving quadratic
tanh compression
init_centroids() =>
// Spread centroids across using different shapes per feature
for c = 0 to k_clusters - 1
frac = k_clusters == 1 ? 0.0 : c / (k_clusters - 1.0) // 0 → 1
v = frac * 2 - 1 // -1 → +1
array.set(cent_rsi, c, v) // linear
array.set(cent_cci, c, math.sin(v)) // sinusoidal
array.set(cent_cmf, c, v * v * (v < 0 ? -1 : 1)) // quadratic sign-preserving
array.set(cent_mac, c, tanh(v)) // compressed
This makes initial cluster spread “random” even though true randomness is hardly achieved in pinescript.
K-Means Iterative Refinement
The algorithm repeats these steps:
(A) Assignment Step, Each bar is assigned to the nearest centroid via Euclidean distance in 4D:
distance = sqrt(dx² + dy² + dz² + dw²)
(B) Update Step, Centroids update to the mean of points assigned to them. This repeats iterations times (configurable).
LIVE REGIME CLASSIFICATION
After training, each new bar is:
Standardized using the training mean/std
Compared to all centroids
Assigned to the nearest cluster
Bar color updates based on cluster
No re-training occurs. This ensures:
No lookahead bias
Clean historical testing
Stable regimes over time
CLUSTER BEHAVIOR & TRADING LOGIC
Clusters (0, 1, 2, 3…) hold no inherent meaning. The user defines what each cluster does.
Example of custom actions:
Cluster 0 → Cash
Cluster 1 → Long
Cluster 2 → Short
Cluster 3+ → Cash (noise regime)
This flexibility means:
One trader might have cluster 0 as consolidation.
Another might repurpose it as a breakout-loading zone.
A third might ignore 3 clusters entirely.
Example on ETHUSD
Important Note:
Any change of parameters or chart timeframe or ticker can cause the “order” of clusters to change
The script does NOT assume any cluster equals any actionable bias, user decides.
PERFORMANCE METRICS & ROC TABLE
The indicator computes average 1-bar ROC for each cluster in:
Training set
Test (live) set
This helps measure:
Cluster profitability consistency
Regime forward predictability
Whether a regime is noise, trend, or reversion-biased
EQUITY SIMULATION & FEES
Designed for close-to-close realistic backtesting.
Position = cluster of previous bar
Fees applied only on regime switches. Meaning:
Staying long → no fee
Switching long→short → fee applied
Switching any→cash → fee applied
Fee input is percentage, but script already converts internally.
Disclaimers
⚠️ This indicator uses machine-learning but does not predict the future. It classifies similarity to past regimes, nothing more.
⚠️ Backtest results are not indicative of future performance.
⚠️ Clusters have no inherent “bullish” or “bearish” meaning. You must interpret them based on your testing and your own feature engineering.
Huli-Huli (Reversal) WindowHuli-Huli (Reversal) Time-Zone Highlighter
Huli (Hawaiian for "turn/flip") highlights specific time regions on your chart where price reversals and pivots are statistically more common during major trading sessions (Asian, London, NY).
This indicator identifies potential turning points based on historical session transitions and market behavior patterns. It does NOT predict or guarantee reversals - it simply marks time zones where pivots frequently occur.
When combined with key support/resistance levels, supply/demand zones, or other confluence factors, these highlighted periods may provide additional context for timing entries and exits.
Use this indicator as one piece of your trading puzzle, not as a standalone signal. Always combine with proper risk management and other technical analysis tools.
Note: Past performance and statistical tendencies do not guarantee future results. Trade responsibly.
***UTC Time should match EST - So depending on Daylight Savings or not you will want to select UTC 4 or UTC 5***
GVI-1 - Guendogan Valuation Index 1The Guendogan Valuation Index 1 (GVI-1) incorporates the total market capitalization of all U.S. companies, U.S. GDP, and the share of revenues generated outside the United States to provide an undistorted long-term valuation of the U.S. equity market across the past decades.
Disclaimer: The Guendogan Valuation Index 1 (GVI-1) is a research-based macro indicator provided solely for educational and informational purposes. It does not constitute financial advice, investment advice, trading advice, or a recommendation to buy or sell any asset. Financial markets involve risk, and past performance does not guarantee future results. All users are solely responsible for their own investment decisions.
Open Interest Anomaly DetectorOpen Interest Anomaly Indicator
This indicator is designed to detect anomalies in Open Interest (OI) and highlight moments when capital is aggressively entering or exiting the market.
The indicator plots raw Open Interest values as a column histogram. A moving average is applied to establish the baseline behavior of OI, while standard deviation bands define thresholds for abnormal deviations. These deviation levels can be customized in the settings.
When Open Interest rises above the upper deviation band, the indicator marks these events in green, signaling positive anomalies, often associated with sudden inflows of capital.
When Open Interest falls below the lower deviation band, it highlights these points in red, indicating negative anomalies, which may reflect capital leaving the market due to stop-loss triggers, take-profit executions, or liquidations.
It is important to note that Open Interest alone does not generate entry signals. Instead, it serves as a contextual layer, helping traders understand market dynamics and confirm other tools. For cleaner signals with reduced noise, we recommend using the indicator on the 15-minute timeframe.
Using Open Interest Together With Delta
The indicator becomes even more powerful when combined with Delta, providing clear insight into who is entering or exiting the market:
Delta > 0 and Open Interest rising → Long positions are entering the market.
Delta < 0 and Open Interest rising → Short positions are entering the market.
Open Interest falling (regardless of Delta) → Money is leaving the market; long or short positions are being closed, either by profit-taking or by forced exits.
This synergy between Open Interest and Delta offers a deeper understanding of market flow and can produce highly informative signals when used together.
Bar Count Per SessionCount K bars based on sessions, supporting at most 3 sessions
- Customize the session's timezone and period
- Set the steps between each number
- Use with the built-in `Trading Session` is a great convenience
Digital Credit Market ValueDigital Credit Frontier
Script for tracking total notional value and total market value for the Digital Credit Market. Needs be manually updated. You can open it twice to get the total value in one pane and the oscillator in the other pane.
Uptrick: Dynamic Z-Score DivergenceIntroduction
Uptrick: Dynamic Z-Score Divergence is an oscillator that combines multiple momentum sources within a Z-Score framework, allowing for the detection of statistically significant mean-reversion setups, directional shifts, and divergence signals. It integrates a multi-source normalized oscillator, a slope-based signal engine, structured divergence logic, a slope-adaptive EMA with dynamic bands, and a modular bar coloring system. This script is designed to help traders identify statistically stretched conditions, evolving trend dynamics, and classical divergence behavior using a unified statistical approach.
Overview
At its core, this script calculates the Z-Score of three momentum sources—RSI, Stochastic RSI, and MACD—using a user-defined lookback period. These are averaged and smoothed to form the main oscillator line. This normalized oscillator reflects how far short-term momentum deviates from its mean, highlighting statistically extreme areas.
Signals are triggered when the oscillator reverses slope within defined inner zones, indicating a shift in direction while the signal remains in a statistically stretched state. These mean-reversion flips (referred to as TP signals) help identify turning points when price momentum begins to revert from extended zones.
In addition, the script includes a divergence detection engine that compares oscillator pivot points with price pivot points. It confirms regular bullish and bearish divergence by validating spacing between pivots and visualizes both the oscillator-side and chart-side divergences clearly.
A dynamic trend overlay system is included using a Slope Adaptive EMA (SA-EMA). This trend line becomes more responsive when Z-Score deviation increases, allowing the trend line to adapt to market conditions. It is paired with ATR-based bands that are slope-sensitive and selectively visible—offering context for dynamic support and resistance.
The script includes configurable bar coloring logic, allowing users to color candles based on oscillator slope, last confirmed divergence, or the most recent signal of any type. A full alert system is also built-in for key signals.
Originality
The script is based on the well-known concept of Z-Score valuation, which is a standard statistical method for identifying how far a signal deviates from its mean. This foundation—normalizing momentum values such as RSI or MACD to measure relative strength or weakness—is not unique to this script and is widely used in quantitative analysis.
What makes this implementation original is how it expands the Z-Score foundation into a fully featured, signal-producing system. First, it introduces a multi-source composite oscillator by combining three momentum inputs—RSI, Stochastic RSI, and MACD—into a unified Z-Score stream. Second, it builds on that stream with a directional slope logic that identifies turning points inside statistical zones.
The most distinctive additions are the layered features placed on top of this normalized oscillator:
A structured divergence detection engine that compares oscillator pivots with price pivots to validate regular bullish and bearish divergence using precise spacing and timing filters.
A fully integrated slope-adaptive EMA overlay, where the smoothing dynamically adjusts based on real-time Z-Score movement of RSI, allowing the trend line to become more reactive during high-momentum environments and slower during consolidation.
ATR-based dynamic bands that adapt to slope direction and offer real-time visual zones for support and resistance within trend structures.
These features are not typically found in standard Z-Score indicators and collectively provide a unique approach that bridges statistical normalization, structure detection, and adaptive trend modeling within one script.
Features
Z-Score-based oscillator combining RSI, StochRSI, and MACD
Configurable smoothing for stable composite signal output
Buy/Sell TP signals based on slope flips in defined zones
Background highlighting for extreme outer bands
Inner and outer zones with fill logic for statistical context
Pivot-based divergence detection (regular bullish/bearish)
Divergence markers on oscillator and price chart
Slope-Adaptive EMA (SA-EMA) with real-time adaptivity based on RSI Z-Score
ATR-based upper and lower bands around the SA-EMA, visibility tied to slope direction
Configurable bar coloring (oscillator slope, divergence, or most recent signal)
Alerts for TP signals and confirmed divergences
Optional fixed Y-axis scaling for consistent oscillator view
The full setup mode can be seen below:
Input Parameters
General Settings
Full Setup: Enables rendering of the full visual system (lines, bands, signals)
Z-Score Lookback: Lookback period for normalization (mean and standard deviation)
Main Line Smoothing: EMA length applied to the averaged Z-Score
Slope Detection Index: Used to calculate directional flips for signal logic
Enable Background Highlighting: Enables visual region coloring in
overbought/oversold areas
Force Visible Y-Axis Scale: Forces max/min bounds for a consistent oscillator range
Divergence Settings
Enable Divergence Detection: Toggles divergence logic
Pivot Lookback Left / Right: Defines the structure of oscillator pivot points
Minimum / Maximum Bars Between Pivots: Controls the allowed spacing range for divergence validation
Bar Coloring Settings
Bar Coloring Mode:
➜ Line Color: Colors bars based on oscillator slope
➜ Latest Confirmed Signal: Colors bars based on the most recent confirmed divergence
➜ Any Latest Signal: Colors based on the most recent signal (TP or divergence)
SA-EMA Settings
RSI Length: RSI period used to determine adaptivity
Z-Score Length: Lookback for normalizing RSI in adaptive logic
Base EMA Length: Base length for smoothing before adaptivity
Adaptivity Intensity: Scales the smoothing responsiveness based on RSI deviation
Slope Index: Determines slope direction for coloring and band logic
Band ATR Length / Band Multiplier: Controls the width and responsiveness of the trend-following bands
Alerts
The script includes the following alert conditions:
Buy Signal (TP reversal detected in oversold zone)
Sell Signal (TP reversal detected in overbought zone)
Confirmed Bullish Divergence (oscillator HL, price LL)
Confirmed Bearish Divergence (oscillator LH, price HH)
These alerts allow integration into automation systems or signal monitoring setups.
Summary
Uptrick: Dynamic Z-Score Divergence is a statistically grounded trading indicator that merges normalized multi-momentum analysis with real-time slope logic, divergence detection, and adaptive trend overlays. It helps traders identify mean-reversion conditions, divergence structures, and evolving trend zones using a modular system of statistical and structural tools. Its alert system, layered visuals, and flexible input design make it suitable for discretionary traders seeking to combine quantitative momentum logic with structural pattern recognition.
Disclaimer
This script is for educational and informational purposes only. No indicator can guarantee future performance, and trading involves risk. Always use risk management and test strategies in a simulated environment before deploying with live capital.
Now PDC ±0.5% & ±0.7% Levels (Custom Lines)Net Change of Instrument movement for the day. Enhances perception of price action
Pair Cointegration & Static Beta Analyzer (v6)Pair Cointegration & Static Beta Analyzer (v6)
This indicator evaluates whether two instruments exhibit statistical properties consistent with cointegration and tradable mean reversion.
It uses long-term beta estimation, spread standardization, AR(1) dynamics, drift stability, tail distribution analysis, and a multi-factor scoring model.
1. Static Beta and Spread Construction
A long-horizon static beta is estimated using covariance and variance of log-returns.
This beta does not update on every bar and is used throughout the entire model.
Beta = Cov(r1, r2) / Var(r2)
Spread = PriceA - Beta * PriceB
This “frozen” beta provides structural stability and avoids rolling noise in spread construction.
2. Correlation Check
Log-price correlation ensures the instruments move together over time.
Correlation ≥ 0.85 is required before deeper cointegration diagnostics are considered meaningful.
3. Z-Score Normalization and Distribution Behavior
The spread is standardized:
Z = (Spread - MA(Spread)) / Std(Spread)
The following statistical properties are examined:
Z-Mean: Should be close to zero in a stationary process
Z-Variance: Measures amplitude of deviations
Tail Probability: Frequency of |Z| being larger than a threshold (e.g. 2)
These metrics reveal whether the spread behaves like a mean-reverting equilibrium.
4. Mean Drift Stability
A rolling mean of the spread is examined.
If the rolling mean drifts excessively, the spread may not represent a stable long-term equilibrium.
A normalized drift ratio is used:
Mean Drift Ratio = Range( RollingMean(Spread) ) / Std(Spread)
Low drift indicates stable long-run equilibrium behavior.
5. AR(1) Dynamics and Half-Life
An AR(1) model approximates mean reversion:
Spread(t) = Phi * Spread(t-1) + error
Mean reversion requires:
0 < Phi < 1
Half-life of reversion:
Half-life = -ln(2) / ln(Phi)
Valid half-life for 10-minute bars typically falls between 3 and 80 bars.
6. Composite Scoring Model (0–100)
A multi-factor weighted scoring system is applied:
Component Score
Correlation 0–20
Z-Mean 0–15
Z-Variance 0–10
Tail Probability 0–10
Mean Drift 0–15
AR(1) Phi 0–15
Half-Life 0–15
Score interpretation:
70–100: Strong Cointegration Quality
40–70: Moderate
0–40: Weak
A pair is classified as cointegrated when:
Total Score ≥ Threshold (default = 70)
7. Main Cointegration Panel
Displays:
Static beta
Log-price correlation
Z-Mean, Z-Variance, Tail Probability
Drift Ratio
AR(1) Phi and Half-life
Composite score
Overall cointegration assessment
8. Beta Hedge Position Sizing (Average-Price Based)
To provide a more stable hedge ratio, hedge sizing is computed using average prices, not instantaneous prices:
AvgPriceA = SMA(PriceA, N)
AvgPriceB = SMA(PriceB, N)
Required B per 1 A = Beta * (AvgPriceA / AvgPriceB)
Using averaged prices results in a smoother, more reliable hedge ratio, reducing noise from bar-to-bar volatility.
The panel displays:
Required B security for 1 A security (average)
This represents the beta-neutral quantity of B required to hedge one unit of A.
Overview of Classical Stationarity & Cointegration Methods
The principal econometric tools commonly used in assessing stationarity and cointegration include:
Augmented Dickey–Fuller (ADF) Test
Phillips–Perron (PP) Test
KPSS Test
Engle–Granger Cointegration Test
Phillips–Ouliaris Cointegration Test
Johansen Cointegration Test
Since these procedures rely on regression residuals, matrix operations, and distribution-based critical values that are not supported in TradingView Pine Script, a practical multi-criteria scoring approach is employed instead. This framework leverages metrics that are fully computable in Pine and offers an operational proxy for evaluating cointegration-like behavior under platform constraints.
References
Engle & Granger (1987), Co-integration and Error Correction
Poterba & Summers (1988), Mean Reversion in Stock Prices
Vidyamurthy (2004), Pairs Trading
Explanation structured with assistance from OpenAI’s ChatGPT
Regards.






















