TRADLEWARE-HODL
Buy and Hold Benchmark
This is a passive reference strategy, not a signal-based trading system. It exists to give an honest baseline: buy once, hold through everything, and see what an active strategy actually needs to beat.
How it works
Buy-and-hold ("HODL") is the simplest possible approach to markets: put the money in once and do nothing else, regardless of what price does afterward. There is no attempt to time entries or exits, no reaction to drawdowns, and no risk management of any kind. Any active strategy that cannot beat this, risk-adjusted, over the same period has not demonstrated an edge.
Entry
The entire starting capital is deployed in a single buy, on the first bar at or after the start date.
Exit
The position is held until the end date, or the end of the chart's available history, whichever comes first — at which point it is closed once so the backtest can report a final equity figure. This is bookkeeping, not a trading decision; the whole point of the strategy is that it does not exit early.
Parameters
Start Date / End Date: the single buy fires on the first bar at or after the start date; the position is held until the end date
Position sizing is set to 99.95% of equity rather than a full 100%. That small gap avoids a PulseWire position-sizing rounding artifact that can otherwise show up as an extra "Margin call" row even on a strategy with only one real trade; the effect on the actual result is negligible.
Costs modelled
0.1% commission per side, 3 ticks slippage.
Intended assets and timeframe
Works on any asset or timeframe — there is no technical logic to adapt, just a buy date and a hold period.
Known limitations
Full exposure to every drawdown the asset experiences, for the entire holding period, by design. This is not a flaw to fix — it is the deliberate point of comparison for any strategy that claims to manage risk better than doing nothing.
Strategy

TRADLEWARE-DCA
Dollar-Cost Averaging Benchmark
This is a passive reference strategy, not a signal-based trading system. It exists to give an honest, apples-to-apples comparison for active strategies: instead of trying to time entries, it buys a fixed amount of the asset on a regular schedule until a set capital budget is fully deployed.
How it works
Dollar-cost averaging (DCA) means investing a fixed amount of money at regular intervals, regardless of price. Some buys land at high prices, some at low prices, and over time the average purchase price smooths out. There is no attempt to predict direction — the schedule is the whole strategy.
This script buys on either a fixed day of the week (e.g. every Monday) or every fixed number of bars (e.g. every 30 daily bars, roughly monthly), and keeps buying until the total amount invested reaches the strategy's starting capital. After that, no more buys are placed — the same total capital pool as whatever active strategy this is being compared against, with no extra money added along the way.
Entry
A buy is placed each time the schedule fires, as long as the running total invested plus the next buy amount does not exceed the starting capital. If a scheduled buy would push the total over budget, it is skipped, but the schedule keeps advancing rather than getting stuck retrying.
Exit
There is no exit signal in the usual sense — the strategy only ever adds to its position. The full position is closed out once, on the final bar of the chart's history, purely so the backtest can report a final equity figure. This is bookkeeping, not a trading decision.
Parameters
Start Date / End Date: window during which buys are allowed
Use Day of Week Mode: switch between "buy on a specific weekday" and "buy every N bars"
Day of Week: which weekday to buy on, when day-of-week mode is on
Every X Bars: how many bars between buys, when day-of-week mode is off (30 on a daily chart is roughly monthly)
Amount per buy: fixed amount invested at each scheduled buy
The strategy allows up to 500 stacked buy layers to accumulate into a single overall position — that number just needs to be large enough to never run out before the capital budget is spent; it is not a trading parameter to tune.
Costs modelled
0.1% commission per side, 3 ticks slippage, fills at the same bar's close (this benchmark intentionally fills immediately rather than waiting for the next bar's open, since there is no signal timing to protect).
Intended assets and timeframe
Works on any asset or timeframe — the frequency inputs just need to be set to match (e.g. 30 bars on a daily chart for roughly monthly buys, 7 for weekly). For higher-priced assets, check that the per-buy amount converts to at least a fraction PulseWire will actually simulate.
Known limitations
The starting capital, buy amount, and buy frequency together decide how long full deployment actually takes — and depending on the chart's date range, that can run out in either direction. With the default settings (10,000 starting capital, 100 per buy, roughly monthly), full deployment takes 100 buys — about 8 years of monthly investing. Starting from 2018-01-01, that budget is exhausted by roughly mid-2026, so on a chart that runs through mid-2026 or later, this script will have already placed its last scheduled buy weeks or months before the present: it simply holds the fully-invested position afterward and stops buying, exactly as designed by the "never invest more than the starting capital" rule, not because of an error. On a shorter chart window relative to the amount and frequency chosen, the opposite can happen instead — the window ends before the full budget is spent, leaving some capital undeployed. Either way, check the strategy's equity and invested-capital tracking rather than assuming full deployment by the end of the chart. This script also has no risk management of any kind by design: it never sells until the very end, so it carries full exposure to any drawdown the asset experiences. That is the intended comparison point for an active strategy, not a flaw to fix.
Strategy

Stocks vs Sector Leaderboard**Stocks vs Sector Leaderboard** compares the performance of up to 10 selected stocks against a sector index or other benchmark.
The indicator is designed to quickly show which stocks are **outperforming or underperforming their sector** over a configurable lookback period.
The default configuration compares a selection of ASX Energy stocks against the **S&P/ASX 200 Energy Index (XEJ)**, but both the stocks and benchmark are fully configurable.
**How it works**
For each selected stock, the indicator:
* Calculates performance over the selected number of bars.
* Calculates the benchmark's performance over the same period.
* Calculates relative performance as **Stock Performance − Sector Performance**.
* Estimates market capitalization using the latest available shares outstanding and current share price.
* Ranks the selected stocks by estimated market capitalization.
* Displays the results in a configurable leaderboard directly on the chart.
A positive **vs Sector** value means the stock has outperformed the benchmark over the selected period. A negative value means it has underperformed.
The lookback uses the **current chart timeframe**. For example, a lookback of 60 means 60 daily bars on a daily chart, 60 hourly bars on a 1-hour chart, or 60 weekly bars on a weekly chart.
**Configuration**
The indicator allows you to configure the benchmark, up to 10 stock symbols, performance lookback, table position, font size, normal text color, outperforming color, and underperforming color.
Although the default configuration uses ASX Energy stocks and XEJ, the indicator can be used with other sectors, indices, exchanges, or groups of stocks by changing the symbols in the settings.
**PulseWire request limit**
The indicator intentionally supports a maximum of **10 stocks** because it needs to retrieve external price and financial data for each symbol using Pine Script `request.*()` functions.
PulseWire imposes limits on the number of unique `request.*()` calls a script may make. On plans with a **40 unique-request limit**, increasing the number of stocks can cause the script to exceed that limit and fail to execute.
Because request limits and access to financial data can depend on the user's PulseWire plan, **this indicator may not work, or may have limited functionality, on PulseWire's free plan**.
**Note**
Market capitalization is an estimate based on share price and the latest shares-outstanding data available through PulseWire. It should be used for ranking and comparison rather than as an authoritative real-time market-cap figure.
This indicator is intended as an analysis tool and does not provide trading or investment advice.
Indicator

[Viprasol] Real Relative StrengthOverview
This indicator is based on the open-source "Real Relative Strength" (RRS) concept, which measures how an asset is performing against a benchmark after normalising for volatility. The original plots ATR-normalised relative momentum versus a benchmark (e.g. SPY) with zero-cross arrows and strong/weak zones. This version keeps that calculation and adds RRS/price divergence detection, a second-benchmark agreement filter, a signal cooldown, an RRS acceleration read, and a compact dashboard.
How It Works
Real Relative Strength (from original concept):
Relative momentum = (asset momentum − benchmark momentum) / average ATR × multiplier, where momentum is close − close for both the asset and the benchmark, and the divisor is the average of the asset and benchmark ATR. The result is smoothed with an EMA. Positive = the asset is outperforming the benchmark on a volatility-adjusted basis; negative = underperforming. Strong/weak zones mark RRS beyond a configurable level.
Divergence (new):
Using pivots on the smoothed RRS, a bearish divergence is flagged when RRS makes a lower pivot high while price makes a higher high; bullish when RRS makes a higher pivot low while price makes a lower low.
Second-Benchmark Agreement (new):
Optionally compute RRS against a second benchmark and only confirm a zero-cross when both agree in sign — a confluence filter against single-benchmark noise.
Signal Cooldown (new):
A minimum bar gap between confirmed zero-cross signals to prevent clustering.
RRS Acceleration (new):
The bar-to-bar change in smoothed RRS, shown as a rising/falling momentum read in the dashboard.
What Is Original (Viprasol Additions)
1. RRS/price divergence detection (regular bullish and bearish).
2. Optional second-benchmark agreement filter on zero-cross signals.
3. Signal cooldown.
4. RRS acceleration (momentum-of-RRS) state.
5. Compact relative-strength dashboard.
Key Features
From the Original:
- ATR-normalised relative strength vs a benchmark
- EMA smoothing, zero-cross arrows, strong/weak zones, extreme background tint
Added in This Version (Viprasol):
- Divergence detection, dual-benchmark agreement, cooldown, acceleration read, dashboard
- Six alerts with dynamic {{ticker}}/{{close}}/{{interval}} messages
How to Use
1. Set the benchmark to match your asset class (SPY/QQQ stocks, IWM small-caps, BTCUSD crypto).
2. Above zero (aqua/green area) = outperforming; below zero (red area) = underperforming.
3. Zero-cross arrows mark fresh shifts; circles mark divergences; the strong/weak zones flag standout strength.
Recommended Starting Points:
- Intraday (15m-1H): Length 10-14
- Swing (Daily/4H): Length 14-20
- Use dual-benchmark agreement for higher-conviction crosses
These are starting points only — backtest and adjust before trading live.
Settings
Core: benchmark symbol, momentum length, ATR multiplier, RRS smoothing.
Confluence & Filters: 2nd-benchmark agreement (+ symbol), signal cooldown, strong/weak zone level.
Divergence: detect divergence toggle, pivot length.
Visuals: zero-cross arrows, RRS line, RRS area.
Dashboard: toggle and position.
Alerts
1. Bullish Cross — now outperforming the benchmark
2. Bearish Cross — now underperforming the benchmark
3. Strong Outperformance — RRS beyond the strong level
4. Strong Underperformance — RRS below the weak level
5. Bullish Divergence — RRS/price bullish divergence
6. Bearish Divergence — RRS/price bearish divergence
All alerts include {{ticker}}, {{close}}, and {{interval}}.
Limitations & Disclaimer
- RRS uses request.security for the benchmark; benchmark data quality and session alignment affect readings, especially across asset classes/exchanges.
- Divergence uses confirmed pivots, which lag by the pivot length.
- Relative strength shows leadership, not absolute direction — a rising RRS in a falling market only means the asset is falling less.
- Past performance does not guarantee future results. This indicator is for educational purposes only and is not financial advice. Always use proper risk management and test on historical data before trading live.
Credits & Attribution
Based on the open-source "Real Relative Strength" concept (community / SMB-style), which provided the ATR-normalised relative-momentum calculation, EMA smoothing, zero-cross signals, and strong/weak zones. Added by Viprasol: RRS/price divergence detection, optional second-benchmark agreement, signal cooldown, RRS acceleration, and the dashboard.
Published open-source per PulseWire House Rules.
Indicator

Relative Strength Pullback Map [AGPro Series]Relative Strength Pullback Map
🧠 Core Idea
Is the pullback happening while the asset remains a relative leader against its benchmark?
📌 Overview / What it does
Relative Strength Pullback Map is a benchmark-relative price-action tool built to study whether an asset is pulling back from strength or breaking down into weakness.
The script compares the active symbol against a selected benchmark, builds a relative-strength baseline, evaluates leader status, measures pullback depth, maps a pullback pocket, marks the recovery rail, and summarizes the full context inside a compact AG Pro panel.
It does not predict future price, automate trades, or claim that every leader pullback must recover. It is a structured decision-support map for reading relative strength, benchmark leadership, pullback health, recovery readiness, and relative breakdown risk.
🎯 Purpose & Design Philosophy
Pullbacks are not all equal.
Some pullbacks happen while the asset continues to outperform its benchmark.
Other pullbacks happen because relative strength is already breaking down.
This script was built to separate those two conditions. The design goal is to help traders identify whether a pullback belongs to a still-strong relative leader or a weakening laggard.
⚡ Why This Script Is Different
Most pullback tools focus only on price.
Most relative-strength tools focus only on the ratio line.
This script does NOT treat pullback quality and relative strength as separate ideas.
Instead, it combines benchmark-relative leadership, price pullback depth, trend shelf behavior, recovery rail reclaim, and relative breakdown risk into one visual map.
The focus is not only whether price pulled back.
The focus is whether the asset remained a leader while pulling back.
⚙️ Methodology
1. Benchmark Comparison
The script compares the active symbol against a selected benchmark using a relative-strength ratio.
2. Relative Strength Baseline
The ratio is smoothed into a baseline so leadership can be evaluated against its own recent behavior.
3. Leader Status Scoring
Leader status combines relative-strength distance, relative-strength slope, and price trend structure.
4. Pullback Depth Measurement
The script measures how far price has pulled back from the recent high using ATR-normalized depth and percentage depth.
5. Pullback Pocket Mapping
The pullback pocket is mapped between the fast recovery rail and the deeper trend shelf.
6. Recovery Evaluation
The script checks whether price is reclaiming the recovery rail while relative strength remains constructive.
7. Visual Output
The chart displays the pullback pocket, recovery rail, relative-strength rail, leader/laggard labels, right-side context tags, alerts, and a compact AG Pro panel.
🗺️ How to Read the Chart
Relative Pullback Pocket = the area where a leader pullback can remain structurally constructive.
Recovery Rail = the fast trend rail used to evaluate whether price is starting to recover from the pullback.
RS LEADER tag = the active symbol is outperforming the selected benchmark with constructive relative strength.
PULLBACK tag = the current pullback depth measured in ATR.
LEADER PULLBACK = the asset remains a relative leader while pulling into a meaningful pullback area.
RS HOLD = relative strength remains constructive during the pullback.
RECOVERY READY = price reclaimed the recovery rail while relative strength remained constructive.
RS BREAK = relative strength weakened or price broke the deeper pullback shelf.
Panel = summarizes relative state, quality score, leader status, pullback depth, recovery trigger, benchmark, and next context.
🚦 Signals & States
• LEADER PULLBACK → the asset remains a relative leader while pulling back.
• RS HOLD → relative strength is still holding during the pullback.
• RECOVERY READY → price reclaimed the recovery rail with constructive relative strength.
• RS BREAK → relative strength weakened or the pullback shelf broke.
• LAGGARD RISK → price is pulling back while the asset is no longer a clear relative leader.
🔔 Alerts Logic
Alerts can trigger when a leader pullback appears, relative strength holds, recovery becomes ready, or relative breakdown appears.
These alerts are attention markers only.
They are not trade instructions, entry signals, exit signals, or guaranteed outcomes.
🧩 Confluence Logic
The context becomes stronger when the active symbol remains above its relative-strength baseline, relative-strength slope is constructive, pullback depth is meaningful but not too deep, and price starts reclaiming the recovery rail.
The context becomes weaker when relative strength drops below its baseline, the slope turns down, or price breaks below the deeper trend shelf.
📊 When to Use
• During trend pullbacks
• When comparing an asset against a benchmark
• In crypto rotation analysis
• In stock or ETF relative-strength review
• When looking for leader pullbacks rather than weak pullbacks
• When filtering pullbacks by benchmark-relative performance
⚠️ When NOT to Use
• On symbols with poor benchmark fit
• During extremely noisy sideways markets
• In low-liquidity markets with unreliable candles
• When benchmark data is missing or unsuitable
• As a standalone buy or sell system
🎛️ Key Inputs
• Benchmark Symbol → defines the market used for relative comparison.
• Relative Strength Baseline → controls the smoothing length of the RS ratio.
• RS Slope Lookback → controls how relative-strength direction is evaluated.
• Minimum Leader Score → controls how strict leader classification should be.
• Fast Trend Length → controls the recovery rail.
• Slow Trend Length → controls the deeper pullback shelf.
• Pullback Lookback → controls the recent high used to measure pullback depth.
• Maximum Healthy Pullback ATR → controls when a pullback becomes too deep.
• Label and Panel Font Size → controls chart readability.
🖥️ Interface & Visual Design
The visual design is built around one question:
Is this still a leader pullback?
The pullback pocket shows the structural area, the recovery rail marks the reclaim reference, the relative-strength rail keeps benchmark context visible, the labels mark state changes, and the AG Pro panel summarizes the current decision context.
🧪 Practical Usage Workflow
1. Select an appropriate benchmark.
2. Read the panel first.
3. Check whether the asset is a relative leader.
4. Review pullback depth.
5. Look at the pullback pocket.
6. Watch whether price reclaims the recovery rail.
7. Confirm the broader market structure independently.
🔍 Interpretation Guidelines
A leader pullback means the asset is pulling back while still holding relative strength.
An RS hold means relative leadership has not broken yet.
Recovery ready means price has started reclaiming the recovery rail while relative strength remains constructive.
An RS break means the pullback may no longer be a clean leader pullback.
None of these states guarantee what happens next.
🚫 What This Script Is NOT
This script is not a prediction engine.
It is not a financial advice tool.
It is not an automated trading system.
It does not guarantee recovery after a leader pullback.
It does not guarantee that relative leaders will continue outperforming.
It does not replace risk management or independent analysis.
⚠️ Limitations & Transparency
Relative strength depends heavily on benchmark selection.
Different benchmarks may produce different interpretations.
Different timeframes may show different relative-strength states.
Fast markets can move through the pullback pocket quickly.
Sideways markets may create unclear relative-strength readings.
🧠 Market Context Notes
Relative strength is most useful when combined with structure, trend, volatility, and market regime.
A pullback in a relative leader can be constructive if leadership remains intact.
A pullback with relative breakdown is a weaker context and should be interpreted with caution.
Benchmark choice matters: crypto pairs may use BTCUSDT, stock charts may use SPY, sector ETFs, or another relevant benchmark.
🧾 Use Case Examples
When ETH pulls back while still outperforming BTC, the script can identify whether the pullback remains constructive or starts losing relative strength.
When a stock pulls back against SPY but relative strength holds above baseline, the script can highlight a leader pullback context.
When price breaks the pullback shelf while RS weakens, the script can flag relative breakdown risk.
🧱 System Philosophy
Relative Strength Pullback Map is part of the AGPro Series approach:
Build visual tools that explain market context clearly, avoid hype, avoid prediction claims, and support structured decision-making.
The goal is not to tell users what to do.
The goal is to help users see whether a pullback belongs to a strong leader or a weakening asset.
🔐 Non-Promise Statement
No script can remove uncertainty from trading.
This tool does not promise accuracy, certainty, profitability, or future performance.
📉 Risk Disclosure
Trading involves risk.
Market conditions can change quickly.
Users are responsible for their own decisions, position sizing, risk management, benchmark selection, and interpretation.
This script is for educational and analytical purposes only and does not provide financial advice.
📚 Educational Note
Use this script as a structured way to study relative strength, benchmark leadership, pullback depth, and recovery context.
The most valuable output is not a single label.
The value is the full map: relative state, leader status, pullback pocket, recovery rail, and next context.
Indicator

AG Pro Correlation Breakdown Map [AGPro Series]AG Pro Correlation Breakdown Map
Overview / What it does
AG Pro Correlation Breakdown Map is an overlay indicator designed to monitor whether a chart symbol is maintaining, weakening, breaking, or repairing its relationship with a benchmark symbol.
The default benchmark in this version is Bitcoin via BINANCE:BTCUSDT, which makes the tool especially useful for crypto traders who want to understand whether an altcoin is still moving in line with BTC or beginning to decouple from it.
This script does not attempt to answer whether correlation is simply high or low in isolation. Its purpose is more specific: it first checks whether a meaningful benchmark relationship existed, then evaluates whether that relationship is starting to deteriorate, whether the deterioration is becoming a confirmed breakdown, and whether the relationship is later stabilizing again.
The result is a regime-style map that helps users read benchmark dependency through distinct states such as coupled, strained, breaking, broken, repairing, and recoupled. This makes the script useful for contextual analysis, benchmark-relative behavior studies, and chart review workflows where users want more than a single rolling-correlation number.
Unique Edge
The main difference of this script is that it is not a generic correlation line, not a spread-trading engine, and not a simple benchmark overlay.
Its focus is the structure of relationship failure.
Instead of only plotting short-term correlation, the script combines four layers:
1. prior relationship validation,
2. short-vs-long correlation deterioration,
3. independent price behavior,
4. persistence and repair logic.
That combination is what separates a temporary wobble from a more meaningful benchmark breakdown event.
This also makes the script distinct from tools that measure correlation pressure or synchronized stress. Correlation Breakdown Map is built around the question: “A relationship existed before, but is it now failing, and if so, how cleanly?”
Methodology
The script starts by selecting a benchmark series and transforming price data into returns. Users can choose between log returns and percent returns.
A short correlation window and a long correlation window are then calculated between the chart symbol and the benchmark. The long window is used to judge whether a stable benchmark relationship has existed, while the short window is used to detect more recent deterioration.
The model then evaluates the gap between long and short correlation, along with short-correlation slope behavior. A benchmark relationship is considered more vulnerable when the short window weakens materially relative to the long window and the short-correlation slope also softens.
To avoid treating every statistical wobble as a true event, the script also checks for independent price behavior. This layer measures whether the chart symbol is beginning to move in a way that is meaningfully different from the benchmark over a configurable lookback period.
Finally, persistence and repair conditions are applied. This allows the script to separate brief instability from a more durable breakdown state, and later identify whether the relationship is beginning to normalize again.
Signals & Alerts / States
This script is primarily a state-mapping tool rather than a directional buy/sell engine.
The core states are:
Coupled
The chart symbol remains meaningfully aligned with the benchmark relationship structure.
Strained
The prior relationship still exists, but weakness is starting to appear.
Breaking
The relationship is under active deterioration and may be transitioning into a more meaningful failure.
Broken
The chart symbol is behaving as if benchmark linkage has materially weakened.
Repairing
The breakdown is no longer cleanly expanding, and the relationship may be stabilizing.
Recoupled
The benchmark relationship has improved enough to suggest that the prior structure is functioning again.
The Breakdown Score is used as a compact summary value. It is not intended to be interpreted as a trade signal on its own. It is a regime-strength readout that helps users compare the current condition of the relationship with the underlying state labels.
Key Inputs
Benchmark Symbol
Sets the comparison symbol. The default is BINANCE:BTCUSDT.
Benchmark Timeframe
Allows users to keep the benchmark on chart timeframe or compare against another timeframe.
Source
Selects Close, HLC3, or OHLC4 for the benchmark study.
Short Correlation Length / Long Correlation Length
Define the fast and slow windows used to evaluate current deterioration versus prior relationship structure.
Stable Relationship Threshold
Controls how strong the historical relationship must be before the script treats later weakness as a true breakdown candidate.
Breakdown Threshold / Repair Threshold
Control how strict the transition logic is for deterioration and recovery.
Min Long/Short Correlation Gap
Requires a meaningful difference between longer-term and shorter-term correlation before escalation.
Independent Move Threshold
Defines how much benchmark-relative price independence is required before the script treats the event as more than a statistical fluctuation.
Breakdown Confirmation Bars / Repair Confirmation Bars
Control persistence and confirmation sensitivity.
Visual Settings
Users can customize theme, visual intensity, panel font size, panel position, event visibility, trail visibility, and chart context density.
Limitations & Transparency
Correlation is a descriptive relationship metric, not a causal model.
A relationship breakdown does not automatically imply immediate continuation, reversal, trend acceleration, or trade opportunity. It only means the chart symbol is no longer behaving as consistently relative to the selected benchmark under the current settings.
Different assets, timeframes, and volatility regimes can produce different correlation behavior. A benchmark relationship that looks stable on one timeframe may be much less stable on another.
Short lookbacks can react faster but may create more noise. Longer lookbacks can be more stable but slower to react.
This script should be interpreted in the context of market structure, volatility, liquidity, and the chosen benchmark. It is a framework for reading relationship quality, not a guarantee engine.
Risk Disclosure
This indicator is for analytical and educational use.
It does not provide financial advice, does not predict future price direction, and should not be used in isolation for trading decisions. Users should perform their own analysis, validate settings on the markets they follow, and apply appropriate risk management. Indicator

AG Pro Relative Strength Rotation Map [AGPro Series]AG Pro Relative Strength Rotation Map
OVERVIEW / WHAT IT DOES
AG Pro Relative Strength Rotation Map is a relative leadership framework designed to evaluate how the active symbol is behaving versus a user-defined reference symbol. Instead of focusing only on absolute price movement, this script studies whether the active market is strengthening, weakening, stabilizing, or rotating relative to its benchmark.
The script builds a smoothed relative-strength backbone, measures rotation pressure through fast-versus-slow internal comparison, and classifies the current environment into clear structural states. The goal is not to predict future price, but to help the user read whether relative leadership is improving, fading, or losing quality.
This makes the script useful when the question is not simply “is price going up or down?” but rather:
- Is this symbol outperforming or underperforming a chosen benchmark?
- Is leadership gaining traction or fading?
- Is the current rotation constructive, weak, or at risk of deterioration?
Because of that, the script can be used across multiple workflows, including:
- crypto asset vs BTC or another reference asset
- stock vs index benchmark
- sector ETF vs broader market ETF
- instrument vs instrument relative comparison
UNIQUE EDGE
This script is not a simple ratio line, not a screener, and not a classic momentum oscillator.
Its main distinction is that it separates relative-strength behavior into a structured rotation model built from:
- relative-strength bias
- rotation pressure
- persistence
- state transitions
In other words, it does not stop at showing whether one asset is stronger than another. It also attempts to show whether that leadership is building, stable, fading, or structurally vulnerable.
Compared with many standard relative-strength tools, this script is designed to be more state-driven and map-oriented rather than just line-oriented.
Compared with other AG Pro scripts, this one addresses a different problem set:
- it does not grade breakout quality
- it does not analyze reclaim behavior around a single moving average or level
- it does not map exhaustion or pressure inside one symbol in isolation
- it does not classify broad market regime
- it does not function as a multi-symbol screener
Instead, it focuses on one specific task:
reading relative leadership rotation between the active chart and a chosen benchmark.
That makes it structurally different from the rest of the AG Pro catalog and useful as a complementary layer rather than an overlapping one.
METHODOLOGY
The script starts by building a relative-strength ratio between the active symbol and the selected reference symbol. That ratio is then normalized around its own baseline and smoothed into an RS backbone so that the user can observe directional leadership more clearly.
A rotation-pressure engine is then derived from the relationship between faster and slower internal measures of that backbone. This helps estimate whether relative movement is gaining traction, losing traction, or transitioning.
A persistence component is also included so short-lived fluctuations are not treated the same way as more durable relative-strength behavior.
Using those building blocks, the script classifies market structure into states such as:
- Leadership Rising
- Leadership Stable
- Rotation Building
- Leadership Fading
- Breakdown Risk
- Neutral / Mixed
This is intended as a decision-support framework for context reading, not a standalone execution model.
SIGNALS & ALERTS
The script can mark structural events such as:
- Leadership Reclaim
- Rotation Build
- Leadership Fade
- Breakdown Risk Rising
- State Changed
These events are derived from the internal relative-strength and rotation conditions of the model. They are intended to help the user notice structural changes in leadership behavior, not to serve as guaranteed entry or exit instructions.
KEY INPUTS
Important controls include:
- Reference Symbol
- Timeframe source selection
- RS Baseline Length
- Backbone Smoothing
- Pressure Fast Length
- Pressure Slow Length
- Threshold Length
- Persistence Length
- Signal Sensitivity
- Zone visibility
- Histogram visibility
- Event label visibility
- Panel position and style controls
These inputs allow the user to adapt the script to different symbols, volatility profiles, and chart-reading preferences.
LIMITATIONS & TRANSPARENCY
This script does not measure intrinsic value, fundamentals, liquidity quality, or macro context. It only evaluates relative-strength behavior through its own internal model.
Like any state-based framework, it can produce transitions that later reverse, especially in noisy or low-conviction market conditions. Relative-strength leadership can also change quickly when the benchmark itself becomes unstable or when both assets move in the same direction with changing intensity.
This script should therefore be used as a contextual and comparative tool, not as a promise of continuation, reversal, or future performance.
It is also important to understand what this script is not:
- not a prediction engine
- not a full portfolio allocator
- not a complete trading system
- not a substitute for confirmation, risk management, or broader market context
RISK DISCLOSURE
This script is for chart analysis and research support only. It does not provide financial, investment, legal, or tax advice. Markets involve risk, and no indicator can guarantee performance or prevent loss. Decisions involving real capital should be made only with appropriate risk controls and independent judgment.
Indicator

AG Pro Correlation Stress Meter [AGPro Series]AG Pro Correlation Stress Meter
Overview / What it does
AG Pro Correlation Stress Meter is an overlay indicator designed to estimate when an instrument is becoming increasingly synchronized with a selected benchmark and whether that relationship is developing into a higher-stress market condition.
Instead of treating correlation as a standalone number, this script converts multiple correlation-related components into a structured stress framework. The goal is not to predict direction. The goal is to help the user judge whether market behavior is becoming more tightly linked, more fragile, and potentially less independent than usual.
The script combines smoothed rolling correlation, short-term correlation acceleration, persistence of elevated correlation, and a simple fragility layer based on price behavior versus an internal backbone EMA. The result is a normalized stress score and a state model that classifies conditions as Stable, Building, Pressured, Stressed, or Critical.
Because the script is plotted directly on price, it is intended to function as a context layer. It can be used to evaluate whether a chart is trading in a relatively independent manner or whether it is increasingly behaving like a benchmark-driven instrument.
Unique Edge
The main difference in this script is that it does not treat correlation as a single readout. It treats correlation as a pressure structure.
Many correlation tools stop at the raw coefficient. This script goes further by asking four separate questions:
1. How strong is the current relationship?
2. Is that relationship tightening or loosening?
3. Has elevated correlation persisted for long enough to matter?
4. Is price behavior becoming fragile at the same time?
That combination is what makes this script different from many standard overlays, matrix-style correlation displays, or simple coefficient dashboards.
It is also different from several other AG Pro scripts in the catalog. Some AG Pro tools focus on trend quality, pullback quality, squeeze behavior, reclaim structure, momentum pressure, or reaction mapping around known reference levels. This script does not focus on any of those themes. Its job is narrower and more diagnostic: it measures how much benchmark-linked stress is building inside the chart. In other words, it is less about trend or structure classification, and more about whether the instrument is becoming increasingly dependent on external benchmark behavior.
Methodology
The script starts with log returns for both the chart symbol and the selected benchmark symbol. A rolling correlation is then calculated over the chosen correlation window and smoothed to reduce noise.
From there, the model evaluates four components:
1. Correlation strength
This is the normalized level of the smoothed rolling correlation. Higher positive correlation generally contributes more to the final stress score.
2. Correlation velocity
This measures how much the smoothed correlation has changed over a short lookback. A rising relationship can matter even when the absolute coefficient is not yet extreme.
3. Correlation persistence
This evaluates how consistently correlation has remained above a user-defined threshold over a recent window. Short spikes and sustained linkage should not be treated as the same condition, so persistence is included as a separate layer.
4. Fragility layer
This component looks at whether price is trading below the internal backbone EMA, whether short-term rate of change is weak, how stretched price is relative to the EMA, and whether ATR percentage is elevated. The purpose of this layer is not to predict reversals. Its purpose is to distinguish a calm, orderly correlation regime from a more fragile one.
These components are weighted into a composite stress score, then mapped into five states:
- Stable
- Building
- Pressured
- Stressed
- Critical
The script also provides a backdrop layer, optional event labels, a backbone EMA for context, and a compact information panel.
Signals & Alerts
This script is primarily a state-classification and context tool. It is not a direct entry system and should not be interpreted as a standalone buy or sell engine.
Available alert logic includes:
- Stress Building
- Stress Pressured
- Stress Stressed
- Stress Critical
- Stress Cooling
These alerts are designed to notify the user when the internal state model changes. They can be used to monitor regime transitions, benchmark sensitivity changes, or shifts in how tightly a symbol is tracking the selected benchmark.
Practical interpretation examples:
- Building may suggest that correlation-linked influence is starting to develop.
- Pressured may suggest that the relationship is no longer background noise and is becoming relevant to decision-making.
- Stressed may suggest that the symbol is trading with notable benchmark dependency.
- Critical may suggest that benchmark-linked pressure is unusually elevated relative to the script’s internal framework.
- Cooling may suggest that the prior stress state is easing.
These are contextual interpretations, not trade instructions.
Key Inputs
Benchmark Symbol
Selects the reference instrument used for the correlation calculation.
Benchmark Timeframe
Allows the benchmark series to follow the chart timeframe or use a different one.
Correlation Length
Defines the rolling window used for correlation.
Correlation Smoothing
Smooths the raw correlation series.
Velocity Lookback
Controls how quickly changes in correlation are measured.
Persistence Window
Defines how far back the script checks for sustained elevated correlation.
Persistence Threshold
Defines what the script considers “elevated” for persistence purposes.
Fragility EMA Length
Controls the internal backbone EMA used in the fragility layer and optional overlay line.
Fragility ROC Length
Defines the short-term price change measurement inside the fragility model.
ATR Length
Controls the volatility input used in the fragility model.
Label Trigger State
Sets the minimum state required before labels can appear.
Minimum Bars Between Labels
Reduces label clustering.
Background From State
Sets the minimum state required before the stress backdrop is shown.
Label ATR Offset
Controls how far event labels are plotted from price.
Panel / Visual Inputs
Allow control over panel visibility, panel position, panel theme, panel font size, label size, backdrop visibility, backbone visibility, and backbone label visibility.
Limitations & Transparency
This script is a contextual model, not a statement of causality. A high reading does not prove that the benchmark is causing the move. It only indicates that the symbol is trading in a way that is more tightly aligned with the selected benchmark according to the model inputs.
Correlation is also regime-dependent. A symbol may appear highly linked during one period and much less linked during another. Different benchmarks, timeframes, and windows can produce different readings.
The fragility layer is intentionally simple. It is included to refine the stress framework, not to replace full market structure analysis. Users who rely on this script should still examine trend structure, volatility context, liquidity conditions, and the behavior of the benchmark itself.
This script also does not claim to identify tops, bottoms, crashes, breakouts, or future returns. It measures an internal definition of correlation-linked stress and presents that information visually.
Risk Disclosure
This indicator is for analytical and educational use. It does not provide financial advice, investment advice, or guaranteed outcomes.
No indicator can remove market risk. Correlation regimes can change quickly, benchmark relationships can decouple without warning, and any model based on historical data can fail in live conditions.
This tool should be used as one part of a broader chart review process, not as a substitute for independent judgment, risk management, or position sizing discipline. Indicator

Master Portfolio Lab PRO [The Quant Science]The Master Portfolio Lab PRO is an advanced quantitative analysis terminal designed to transform PulseWire into a powerful multi-asset portfolio management engine. Developed with institutional-grade calculation logic, this tool allows you to simulate, monitor, and analyze the combined performance of 12 customizable assets within a single, dynamic environment.
In a world where trading is often hyper-focused on a single ticker, the Master Lab enables you to level up: stop looking at the tree and start managing the forest.
🧪 USAGE
The script is designed for traders and investors looking to validate asset allocation strategies or monitor their real-market exposure against a specific benchmark.
🧬 How to configure it:
Asset Allocation: Enter your desired tickers (Crypto, Stocks, Forex, or Commodities) and assign a percentage weight to each slot. Ensure the total weight equals 100%.
Capital Configuration: Choose from predefined capital profiles (from $1k to $1M) or set a custom capital amount for precise simulations.
Costs & Fees: Set a "Portfolio Fee" to reflect transaction costs and generate a realistic, non-theoretical equity curve.
Benchmark Comparison: Select a reference index (e.g., S&P 500 or Bitcoin) to measure the Alpha generated by your active management.
🧪 DETAILS
🧬 Multi-Mode Analysis Engine
The script offers four independent visualization modes, instantly switchable via the settings menu:
Cumulative (%): Comparative analysis between the portfolio's percentage return and the benchmark.
Equity ($): Monetary monitoring of net liquidity and cash growth.
SMA Ribbon: Identification of the portfolio's trend regime using moving averages applied directly to the equity curve.
Volatility: Real-time monitoring of portfolio "thermal stress" via smoothed Standard Deviation (WMA).
🧬 Alpha-Glow Logic
The system utilizes a high-fidelity visual architecture based on dynamic gradients. When the portfolio outperforms the benchmark (Positive Alpha), the fill area illuminates, providing immediate psychological feedback on the quality of your management.
🧬 Real-Time Dashboard
An integrated table in the bottom-right corner processes live data to provide:
Net Value: Current portfolio value, including PnL and costs.
Return %: Total return from the selected starting anchor point.
Alpha vs Index: The "holy grail" of trading—exactly how much value you are adding compared to a passive investment.
🧪 SETTINGS
🧬 Capital Configuration
1) Fixed Capital: Toggle quick selectors for standard account sizes.
2) Custom Capital: Manual input for simulating specific real-world accounts.
🧬 Date Period Analysis
Allows you to set a precise start date (Day/Month/Year) to analyze portfolio performance during specific macroeconomic events or historical cycles.
The Master Portfolio Lab PRO was born from the need to overcome PulseWire's native limitations in multi-symbol management. By utilizing normalization techniques and iterative Rate of Change (ROC) calculations, we have created a framework capable of simulating an entire investment fund with surgical precision. Indicator

VWAP [crlmx] Flexible Volume Weighted Average Price (VWAP) for clean
volume-weighted fair value benchmark and trend direction.
Key Features
- Adjustable VWAP Anchor
- 30min, 1H, 2H, 4H, 8H, 12H, D, W, M, Q, Y
- Sessions New York, London, Asia, with adjustable time
- Clean session breaks, no skews in VWAP line
- Period limit fearure (default 3) hides older periods
- Streamlined inputs/UI brought to you by crlmx
Trading Applications
- Intraday anchors (30min-12H): scalping and day trading
- Daily anchor: traditional intraday analysis
- Weekly/Monthly/Quarterly: swing trading context
- Yearly: long-term fair value
- Configuration examples:
Scalping: 30min-1H anchor | Limit: 5-10 | Bands: On | Multiplier: 1.0-1.5
Intraday: Day anchor | Limit: 3-5 | Bands: On | Multiplier: 1.0-2.0
Swing: Week-Month | Limit: 3-5 | Bands: Off | VWAP line only
Position: Quarter-Year | Limit: 3 | Bands: Off | Fair value reference
Version History
v1.56 (Latest - 22 Feb 2026)
- VWAP display limit feature: shows set amount of periods
- Added Market Sessions
- Streamlined input panel organisation
Indicator

stock-vs-industry using NQUSB benchmark idexesOriginal idea from Stock versus Industry by Tr33man .
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ PRIMARY IMPROVEMENT: NQUSB Hierarchical Index Benchmarks ═══
The KEY improvement: Multi-Level Industry Granularity with Drill-Down/Drill-Up Navigation
From: Simple ETF Comparison (1 Level) Stock → Industry ETF (e.g., "SOXX" for all semiconductors)
To: NQUSB Hierarchical Comparison (4 Levels)
Level 4 (Primary): NQUSB10102010 → Semiconductors (most specific)
Level 3 (Secondary): NQUSB101020 → Technology Hardware and Equipment
Level 2 (Tertiary): NQUSB101010 → Software and Computer Services
Level 1 (Quaternary): NQUSB10 → Technology (broadest sector)
Users can now drill up and down the industry hierarchy to see how their stock performs against different levels of industry classification!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ WHY THIS MATTERS ═══
Original Limitations:
Single comparison level - ETF only
No drill-down capability - Can't zoom in to more specific industries
No drill-up capability - Can't zoom out to broader sectors
ETF limitations - Not all industries have dedicated ETFs
Arbitrary mappings - Manual ETF selection may not represent true industry
Improved Capabilities:
4-level hierarchical navigation - Drill-down and drill-up through industry classifications
361 NQUSB official indices - NASDAQ US Benchmark Index structure
Official NASDAQ classification - Industry-standard taxonomy
Large Mid Cap (LM) option - Focus on larger companies when needed
Enhanced UI - Clear level indicators and full index descriptions
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ EXAMPLE: ANALYZING NVDA (Semiconductors) ═══
Level 4 - Primary (Most Specific):
NQUSB10102010 - Semiconductors
→ NVDA vs. AMD, AVGO, QCOM, TXN, etc. (direct competitors)
Level 3 - Secondary (Broader):
NQUSB101020 - Tech Hardware & Equipment
→ NVDA vs. AAPL, CSCO + semiconductors
Level 2 - Tertiary (Even Broader):
NQUSB101010 - Software and Computer Services
→ NVDA vs. all tech hardware
Level 1 - Quaternary (Broadest):
NQUSB10 - Technology Sector
→ NVDA vs. entire technology sector
You can now zoom in to see direct competitors or zoom out to understand macro sector trends - all in one indicator!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ COMPARISON SUMMARY ═══
Original Version:
Comparison System: Industry ETFs
Industry Levels: 1 (flat ETF mapping)
Total Classifications: ~140 industries
Hierarchy Navigation: ❌ No
Data Source: Manual ETF curation
Improved Version:
Comparison System: NQUSB Official Indices
Industry Levels: 4 (hierarchical drill-down/up)
Total Classifications: 361 NQUSB indices
Hierarchy Navigation: ✅ 4-level drill navigation
Data Source: NASDAQ official taxonomy
Large/Mid Cap Option: ✅ LM variant toggle
Level Indicator: ✅ to labels
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
═══ ADDITIONAL FEATURES ═══
Dual Comparison System - Toggle between ETF mode (original) and Index Benchmark mode (NQUSB hierarchy)
Better Fallback Logic - Manual Override > NQUSB Index > ETF > SPY default
Enhanced Display - 4-row information table with full NQUSB index description
Backward Compatible - All original ETF mappings still work, existing charts won't break
Large Mid Cap Toggle - Optional "LM" suffix for focusing on larger companies only
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
For complete documentation, data files, technical details, and the full NQUSB hierarchy structure, visit the GitHub repository.
The result: More accurate, more flexible, and more comprehensive industry strength analysis - enabling traders to understand exactly where their stock's performance comes from by drilling through multiple levels of industry classification. Indicator

Indicator

Crypto Index Price# Crypto Index Price - Indicator Description
## 📊 What is this indicator?
**Crypto Index Price** is an indicator for creating your own cryptocurrency index based on an equal-weighted portfolio. It allows you to track the overall dynamics of the cryptocurrency market through a composite index of selected assets.
## 🎯 Key Features
- **Up to 20 assets in the index** — create an index from any trading pairs
- **Equal-weighted methodology** — each asset has the same weight in the index
- **Moving average** — optional trend filter for the index
- **Flexible visualization settings** — customizable colors and line thickness
## 📈 How to Use
The indicator is displayed in a separate pane below the chart and shows:
1. **Blue line** — crypto index value
2. **Orange line** (optional) — moving average of the index
### Trading Applications:
- **Identify overall market trend** — if the index is rising, most coins are in an uptrend
- **Divergences** — divergence between your asset and the index may signal local opportunities
- **Signal confirmation** — use the index to confirm trading decisions on individual coins
- **Market condition filter** — trade longs when index is above MA, shorts when below
## ⚙️ Settings
### Assets (Symbols)
- **Asset 1-10** — main cryptocurrencies (default: BTC, ETH, BNB, SOL, XRP, ADA, AVAX, LINK, DOGE, TRX)
- **Asset 11-20** — additional slots for index expansion
### Visual Parameters
- **Index line color** — main line color (default: blue)
- **Line width** — from 1 to 5 pixels
- **Show moving average** — enable/disable MA
- **MA period** — moving average calculation period (default: 20)
- **MA color** — moving average line color (default: orange)
## 💡 Recommendations
- For a top coins index, use 5-10 largest cryptocurrencies by market cap
- For an altcoin index, add medium and small coins from your sector
- Use MA to filter false signals and identify the global trend
- Compare individual asset behavior with the index to find anomalies
## ⚠️ Important
The indicator uses equal-weighted methodology — each coin contributes equally regardless of price or market cap. This differs from cap-weighted indices and may provide a different market perspective.
---
*This indicator is intended for analysis and is not trading advice. Always conduct your own analysis before making trading decisions.*
--- Indicator

Indicator

TimeSeriesBenchmarkMeasuresLibrary "TimeSeriesBenchmarkMeasures"
Time Series Benchmark Metrics. \
Provides a comprehensive set of functions for benchmarking time series data, allowing you to evaluate the accuracy, stability, and risk characteristics of various models or strategies. The functions cover a wide range of statistical measures, including accuracy metrics (MAE, MSE, RMSE, NRMSE, MAPE, SMAPE), autocorrelation analysis (ACF, ADF), and risk measures (Theils Inequality, Sharpness, Resolution, Coverage, and Pinball).
___
Reference:
- github.com .
- medium.com .
- www.salesforce.com .
- towardsdatascience.com .
- github.com .
mae(actual, forecasts)
In statistics, mean absolute error (MAE) is a measure of errors between paired observations expressing the same phenomenon. Examples of Y versus X include comparisons of predicted versus observed, subsequent time versus initial time, and one technique of measurement versus an alternative technique of measurement.
Parameters:
actual (array) : List of actual values.
forecasts (array) : List of forecasts values.
Returns: - Mean Absolute Error (MAE).
___
Reference:
- en.wikipedia.org .
- The Orange Book of Machine Learning - Carl McBride Ellis .
mse(actual, forecasts)
The Mean Squared Error (MSE) is a measure of the quality of an estimator. As it is derived from the square of Euclidean distance, it is always a positive value that decreases as the error approaches zero.
Parameters:
actual (array) : List of actual values.
forecasts (array) : List of forecasts values.
Returns: - Mean Squared Error (MSE).
___
Reference:
- en.wikipedia.org .
rmse(targets, forecasts, order, offset)
Calculates the Root Mean Squared Error (RMSE) between target observations and forecasts. RMSE is a standard measure of the differences between values predicted by a model and the values actually observed.
Parameters:
targets (array) : List of target observations.
forecasts (array) : List of forecasts.
order (int) : Model order parameter that determines the starting position in the targets array, `default=0`.
offset (int) : Forecast offset related to target, `default=0`.
Returns: - RMSE value.
nmrse(targets, forecasts, order, offset)
Normalised Root Mean Squared Error.
Parameters:
targets (array) : List of target observations.
forecasts (array) : List of forecasts.
order (int) : Model order parameter that determines the starting position in the targets array, `default=0`.
offset (int) : Forecast offset related to target, `default=0`.
Returns: - NRMSE value.
rmse_interval(targets, forecasts)
Root Mean Squared Error for a set of interval windows. Computes RMSE by converting interval forecasts (with min/max bounds) into point forecasts using the mean of the interval bounds, then compares against actual target values.
Parameters:
targets (array) : List of target observations.
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - RMSE value for the combined interval list.
mape(targets, forecasts)
Mean Average Percentual Error.
Parameters:
targets (array) : List of target observations.
forecasts (array) : List of forecasts.
Returns: - MAPE value.
smape(targets, forecasts, mode)
Symmetric Mean Average Percentual Error. Calculates the Mean Absolute Percentage Error (MAPE) between actual targets and forecasts. MAPE is a common metric for evaluating forecast accuracy, expressed as a percentage, lower values indicate a better forecast accuracy.
Parameters:
targets (array) : List of target observations.
forecasts (array) : List of forecasts.
mode (int) : Type of method: default=0:`sum(abs(Fi-Ti)) / sum(Fi+Ti)` , 1:`mean(abs(Fi-Ti) / ((Fi + Ti) / 2))` , 2:`mean(abs(Fi-Ti) / (abs(Fi) + abs(Ti))) * 100`
Returns: - SMAPE value.
mape_interval(targets, forecasts)
Mean Average Percentual Error for a set of interval windows.
Parameters:
targets (array) : List of target observations.
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - MAPE value for the combined interval list.
acf(data, k)
Autocorrelation Function (ACF) for a time series at a specified lag.
Parameters:
data (array) : Sample data of the observations.
k (int) : The lag period for which to calculate the autocorrelation. Must be a non-negative integer.
Returns: - The autocorrelation value at the specified lag, ranging from -1 to 1.
___
The autocorrelation function measures the linear dependence between observations in a time series
at different time lags. It quantifies how well the series correlates with itself at different
time intervals, which is useful for identifying patterns, seasonality, and the appropriate
lag structure for time series models.
ACF values close to 1 indicate strong positive correlation, values close to -1 indicate
strong negative correlation, and values near 0 indicate no linear correlation.
___
Reference:
- statisticsbyjim.com
acf_multiple(data, k)
Autocorrelation function (ACF) for a time series at a set of specified lags.
Parameters:
data (array) : Sample data of the observations.
k (array) : List of lag periods for which to calculate the autocorrelation. Must be a non-negative integer.
Returns: - List of ACF values for provided lags.
___
The autocorrelation function measures the linear dependence between observations in a time series
at different time lags. It quantifies how well the series correlates with itself at different
time intervals, which is useful for identifying patterns, seasonality, and the appropriate
lag structure for time series models.
ACF values close to 1 indicate strong positive correlation, values close to -1 indicate
strong negative correlation, and values near 0 indicate no linear correlation.
___
Reference:
- statisticsbyjim.com
adfuller(data, n_lag, conf)
: Augmented Dickey-Fuller test for stationarity.
Parameters:
data (array) : Data series.
n_lag (int) : Maximum lag.
conf (string) : Confidence Probability level used to test for critical value, (`90%`, `95%`, `99%`).
Returns: - `adf` The test statistic.
- `crit` Critical value for the test statistic at the 10 % levels.
- `nobs` Number of observations used for the ADF regression and calculation of the critical values.
___
The Augmented Dickey-Fuller test is used to determine whether a time series is stationary
or contains a unit root (non-stationary). The null hypothesis is that the series has a unit root
(is non-stationary), while the alternative hypothesis is that the series is stationary.
A stationary time series has statistical properties that do not change over time, making it
suitable for many time series forecasting models. If the test statistic is less than the
critical value, we reject the null hypothesis and conclude the series is stationary.
___
Reference:
- www.jstor.org
- en.wikipedia.org
theils_inequality(targets, forecasts)
Calculates Theil's Inequality Coefficient, a measure of forecast accuracy that quantifies the relative difference between actual and predicted values.
Parameters:
targets (array) : List of target observations.
forecasts (array) : Matrix with list of forecasts, ordered column wise.
Returns: - Theil's Inequality Coefficient value, value closer to 0 is better.
___
Theil's Inequality Coefficient is calculated as: `sqrt(Sum((y_i - f_i)^2)) / (sqrt(Sum(y_i^2)) + sqrt(Sum(f_i^2)))`
where `y_i` represents actual values and `f_i` represents forecast values.
This metric ranges from 0 to infinity, with 0 indicating perfect forecast accuracy.
___
Reference:
- en.wikipedia.org
sharpness(forecasts)
The average width of the forecast intervals across all observations, representing the sharpness or precision of the predictive intervals.
Parameters:
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - Sharpness The sharpness level, which is the average width of all prediction intervals across the forecast horizon.
___
Sharpness is an important metric for evaluating forecast quality. It measures how narrow or wide the
prediction intervals are. Higher sharpness (narrower intervals) indicates greater precision in the
forecast intervals, while lower sharpness (wider intervals) suggests less precision.
The sharpness metric is calculated as the mean of the interval widths across all observations, where
each interval width is the difference between the upper and lower bounds of the prediction interval.
Note: This function assumes that the forecasts matrix has at least 2 columns, with the first column
representing the lower bounds and the second column representing the upper bounds of prediction intervals.
___
Reference:
- Hyndman, R. J., & Athanasopoulos, G. (2018). Forecasting: principles and practice. OTexts. otexts.com
resolution(forecasts)
Calculates the resolution of forecast intervals, measuring the average absolute difference between individual forecast interval widths and the overall sharpness measure.
Parameters:
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - The average absolute difference between individual forecast interval widths and the overall sharpness measure, representing the resolution of the forecasts.
___
Resolution is a key metric for evaluating forecast quality that measures the consistency of prediction
interval widths. It quantifies how much the individual forecast intervals vary from the average interval
width (sharpness). High resolution indicates that the forecast intervals are relatively consistent
across observations, while low resolution suggests significant variation in interval widths.
The resolution is calculated as the mean absolute deviation of individual interval widths from the
overall sharpness value. This provides insight into the uniformity of the forecast uncertainty
estimates across the forecast horizon.
Note: This function requires the forecasts matrix to have at least 2 columns (min, max) representing
the lower and upper bounds of prediction intervals.
___
Reference:
- (sites.stat.washington.edu)
- (www.jstor.org)
coverage(targets, forecasts)
Calculates the coverage probability, which is the percentage of target values that fall within the corresponding forecasted prediction intervals.
Parameters:
targets (array) : List of target values.
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - Percent of target values that fall within their corresponding forecast intervals, expressed as a decimal value between 0 and 1 (or 0% and 100%).
___
Coverage probability is a crucial metric for evaluating the reliability of prediction intervals.
It measures how well the forecast intervals capture the actual observed values. An ideal forecast
should have a coverage probability close to the nominal confidence level (e.g., 90%, 95%, or 99%).
For example, if a 95% prediction interval is used, we expect approximately 95% of the actual
target values to fall within those intervals. If the coverage is significantly lower than the
nominal level, the intervals may be too narrow; if it's significantly higher, the intervals may
be too wide.
Note: This function requires the targets array and forecasts matrix to have the same number of
observations, and the forecasts matrix must have at least 2 columns (min, max) representing
the lower and upper bounds of prediction intervals.
___
Reference:
- (www.jstor.org)
pinball(tau, target, forecast)
Pinball loss function, measures the asymmetric loss for quantile forecasts.
Parameters:
tau (float) : The quantile level (between 0 and 1), where 0.5 represents the median.
target (float) : The actual observed value to compare against.
forecast (float) : The forecasted value.
Returns: - The Pinball loss value, which quantifies the distance between the forecast and target relative to the specified quantile level.
___
The Pinball loss function is specifically designed for evaluating quantile forecasts. It is
asymmetric, meaning it penalizes underestimates and overestimates differently depending on the
quantile level being evaluated.
For a given quantile τ, the loss function is defined as:
- If target >= forecast: (target - forecast) * τ
- If target < forecast: (forecast - target) * (1 - τ)
This loss function is commonly used in quantile regression and probabilistic forecasting
to evaluate how well forecasts capture specific quantiles of the target distribution.
___
Reference:
- (www.otexts.com)
pinball_mean(tau, targets, forecasts)
Calculates the mean pinball loss for quantile regression.
Parameters:
tau (float) : The quantile level (between 0 and 1), where 0.5 represents the median.
targets (array) : The actual observed values to compare against.
forecasts (matrix) : The forecasted values in matrix format with at least 2 columns (min, max).
Returns: - The mean pinball loss value across all observations.
___
The pinball_mean() function computes the average Pinball loss across multiple observations,
making it suitable for evaluating overall forecast performance in quantile regression tasks.
This function leverages the asymmetric Pinball loss function to evaluate how well forecasts
capture specific quantiles of the target distribution. The choice of which column from the
forecasts matrix to use depends on the quantile level:
- For τ ≤ 0.5: Uses the first column (min) of forecasts
- For τ > 0.5: Uses the second column (max) of forecasts
This loss function is commonly used in quantile regression and probabilistic forecasting
to evaluate how well forecasts capture specific quantiles of the target distribution.
___
Reference:
- (www.otexts.com) Library

Indicator

Market Strength Buy Sell Indicator [TradeDots]A specialized tool designed to assist traders in evaluating market conditions through a multifaceted analysis of relative performance, beta-adjusted returns, momentum, and volume—allowing you to identify optimal points for long or short trades. By integrating multiple benchmarks (default S&P 500) and percentile-based thresholds, the script provides clear, actionable insights suitable for both day trading and higher-level timeframe assessments.
📝 HOW IT WORKS
1. Multi-Factor Composite Score
Relative Performance (RS Ratio): Compares your asset’s performance to a chosen benchmark (default: SPY). Values above 1.0 indicate outperformance, while below 1.0 suggest underperformance.
Beta-Adjusted Returns: Checks the ticker’s excess movement relative to expected market-related moves. This helps distinguish pure “alpha” from broad market effects.
Volume & Correlation: Volume spikes often confirm the momentum behind a move, while correlation measures how closely the asset tracks or diverges from its benchmark.
These components merge into a 0–100 composite score. Scores above 50 frequently imply bullish strength; drops below 50 often point to underperformance—potentially flagging short opportunities.
2. Intraday & Day Trading Focus
Monitoring Below 50: During the trading day, the script calculates live data against the benchmark, offering an intraday-sensitive composite score. A dip under 50 may indicate a short bias for that session, especially when accompanied by high volume or momentum shifts.
3. Higher Timeframe Monitoring
Daily Strategies: On daily or weekly charts, the script reveals overall relative strength or weakness compared to the S&P 500. This higher-level perspective helps form broader trading biases—crucial for swing or position trades spanning multiple days.
Long/Short Thresholds: Persistent readings above 50 on a daily chart typically reinforce a long bias, while consistent dips below 50 can sustain a short or cautious outlook.
4. Pair Trading Applications
Custom Benchmark Selection: By setting a specific ticker pair as your benchmark instead of the default S&P 500, you can identify spread trading opportunities between two correlated assets. This allows you to go long the outperforming asset while shorting the underperforming one when the spread reaches extreme levels.
4. Color-Coded Signals & Alerts
Visual Zones (25–75): Color-coded bands highlight strong outperformance (above 75) or pronounced underperformance (below 25).
Alerts on Strong Shifts: Automatic alerts can notify you of sudden entries or exits from bullish or bearish zones, so you can potentially act on new market information without delay.
⚙️ HOW TO USE
1. Select Your Timeframe: For scalping or day trading, lower intervals (e.g., 5-minute) offer immediate data resets at the session’s start. For multi-day insight, daily or weekly charts reveal broader performance trends.
2. Watch Key Levels Around 50: Intraday dips under 50 may be a cue to consider short trades, while bounces above 50 can confirm renewed strength.
3. Assess Benchmark Relationships: Compare your asset’s score and signals to the broader market. A stock falling below its pair’s relative strength line might lag overall market momentum.
4. Combine Tools & Validate: This script excels when integrated with other technical analysis methods (e.g., support/resistance, chart patterns) and fundamental factors for a holistic market view.
❗ LIMITATIONS
No Direction Guarantee: The indicator identifies relative strength but does not guarantee directional price moves.
Delayed Updates: Since calculations update after each bar close, sudden intrabar changes may not immediately reflect.
Market-Specific Behaviors: Some assets or unusual market conditions may deviate from typical benchmarks, weakening signal reliability.
Past ≠ Future: High or low relative strength in the past may not predict continued performance.
RISK DISCLAIMER
All forms of trading and investing involve risk, including the possible loss of principal. This indicator analyzes relative performance but cannot assure profits or eliminate losses. Past performance of any strategy does not guarantee future results. Always combine analysis with proper risk management and your broader trading plan. Consult a licensed financial advisor if you are unsure of your individual risk tolerance or investment objectives. Indicator

Custom Index CompositeCustom Index Composite calculates an unweighted composite index by averaging the daily returns of multiple stock tickers. Instead of using price-level weighting, it focuses solely on percentage change, allowing you to compare diverse market themes side by side on a common basis.
Why Use a Custom Index Composite?
Unlike traditional indices that often lean on market capitalization or price-level data, a custom composite based solely on returns strips out the bias inherent to high-priced stocks. This provides several benefits:
Objective Cross-Comparison:
When stocks or market themes trade at very different price levels, it can be difficult to assess performance objectively. Using percentage returns, the composite creates an even playing field, enabling a clear comparison between different assets or themes.
Tailored Benchmarking:
By selecting and combining specific tickers, you can create benchmarks that better represent the segments or strategies you’re interested in. This is particularly useful when standard indices do not capture the nuances of your investment approach.
Performance Normalization:
Converting raw price data into daily percentage returns minimizes distortions that arise from price differences. This normalization helps in understanding true performance trends across the chosen tickers, making the composite index a more reliable gauge of relative market movement.
Custom Analysis Framework:
The indicator offers flexibility to adjust the lookback period (defaulting to about 3 months) so you can fine-tune the sensitivity of the index to recent market behavior. This enables you to either smooth out volatility or capture a more immediate trend, depending on your analytical needs.
Key Features:
Configurable Appearance:
You can easily configure the line color, line width, index name, and index name color via the options panel.
Ticker Configuration:
By default, you can enter up to 15 different tickers into the composite index. Technically, the indicator supports up to 40 tickers (these additional inputs are commented out by default to maintain performance), and you may enable them individually if required.
Calculated Bars Length:
The indicator uses a “Calculated bars length” setting, which is set by default to 63 days (approximately 3 months). This value can be adjusted, and it is recommended to use the greatest common denominator for consistent analysis.
How To Configure Your Chart:
Add the Indicator:
Place the Custom Index Composite on your chart.
Disable Main Symbol Visibility:
Hide the primary symbol’s plot and set its scale to “None” to prevent interference with the composite display.
Pin to Right Scale:
Set the scale of the first composite indicator to “Pinned to right scale.” This helps maintain consistency across different composite indicators.
Add Multiple Composites:
You can add additional composite indicators and set their scales to “Pinned to right scale” (or alternatively to “A”) for convenient comparison.
Limitations:
If a ticker symbol is set once in the options, it cannot be cleared to an empty value later. As a result, the symbol will continue to appear in the indicator’s title on the chart. The only way to remove an unwanted symbol is to completely reset the settings and re-enter your desired tickers.
Indicator

Indicator

Indicator

benchLibrary "bench"
A simple banchmark library to analyse script performance and bottlenecks.
Very useful if you are developing an overly complex application in Pine Script, or trying to optimise a library / function / algorithm...
Supports artificial looping benchmarks (of fast functions)
Supports integrated linear benchmarks (of expensive scripts)
One important thing to note is that the Pine Script compiler will completely ignore any calculations that do not eventually produce chart output. Therefore, if you are performing an artificial benchmark you will need to use the bench.reference(value) function to ensure the calculations are executed.
Please check the examples towards the bottom of the script.
Quick Reference
(Be warned this uses non-standard space characters to get the line indentation to work in the description!)
```
// Looping benchmark style
benchmark = bench.new(samples = 500, loops = 5000)
data = array.new_int()
if bench.start(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.mark(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.mark(benchmark)
while bench.loop(benchmark)
array.unshift(data, timenow)
bench.stop(benchmark)
bench.reference(array.get(data, 0))
bench.report(benchmark, '1x array.unshift()')
// Linear benchmark style
benchmark = bench.new()
data = array.new_int()
bench.start(benchmark)
for i = 0 to 1000
array.unshift(data, timenow)
bench.mark(benchmark)
for i = 0 to 1000
array.unshift(data, timenow)
bench.stop(benchmark)
bench.reference(array.get(data, 0))
bench.report(benchmark,'1000x array.unshift()')
```
Detailed Interface
new(samples, loops) Initialises a new benchmark array
Parameters:
samples : int, the number of bars in which to collect samples
loops : int, the number of loops to execute within each sample
Returns: int , the benchmark array
active(benchmark) Determing if the benchmarks state is active
Parameters:
benchmark : int , the benchmark array
Returns: bool, true only if the state is active
start(benchmark) Start recording a benchmark from this point
Parameters:
benchmark : int , the benchmark array
Returns: bool, true only if the benchmark is unfinished
loop(benchmark) Returns true until call count exceeds bench.new(loop) variable
Parameters:
benchmark : int , the benchmark array
Returns: bool, true while looping
reference(number, string) Add a compiler reference to the chart so the calculations don't get optimised away
Parameters:
number : float, a numeric value to reference
string : string, a string value to reference
mark(benchmark, number, string) Marks the end of one recorded interval and the start of the next
Parameters:
benchmark : int , the benchmark array
number : float, a numeric value to reference
string : string, a string value to reference
stop(benchmark, number, string) Stop the benchmark, ending the final interval
Parameters:
benchmark : int , the benchmark array
number : float, a numeric value to reference
string : string, a string value to reference
report(Prints, benchmark, title, text_size, position)
Parameters:
Prints : the benchmarks results to the screen
benchmark : int , the benchmark array
title : string, add a custom title to the report
text_size : string, the text size of the log console (global size vars)
position : string, the position of the log console (global position vars)
unittest_bench(case) Cache module unit tests, for inclusion in parent script test suite. Usage: bench.unittest_bench(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the bench module unit tests as a stand alone. Usage: bench.unittest()
Parameters:
verbose : bool, optionally disable the full report to only display failures Library

Strategy

Indicator
