ATR Regime Study [CHE]  ATR Regime Study   — ATR percentile regimes with clear bands, table and live label 
  Summary 
This study classifies volatility into five regimes by converting ATR into a percentile rank over a rolling window, plotted on a standardized scale between zero and one hundred. Colored bands mark regime thresholds, while a compact table and an optional label report the current percentile and regime. The standardized scale makes symbols and timeframes easier to compare than raw ATR values. Implemented in Pine v6 as a separate pane (overlay set to false), it is a context tool to adapt tactics and risk handling to the prevailing volatility environment.
  Motivation: Why this design? 
Raw ATR varies with price scale and asset characteristics, which makes regime comparison inconsistent and leads to poor transfer of settings across symbols and timeframes. The core idea is to transform ATR into a percentile rank within a user-defined lookback, then map it into discrete regimes. This yields a stable, interpretable context signal that shifts slower than raw ATR while still responding to genuine volatility changes.
  What’s different vs. standard approaches? 
 Reference baseline: Traditional ATR plots or ATR bands using fixed multipliers.
 Architecture differences:
   Percentile ranking of ATR within a rolling window.
   Five discrete regimes with fixed thresholds at ninety, seventy, thirty, and ten.
   Visual fills between thresholds plus a live table and a last-bar label.
 Practical effect: You read a single normalized line between zero and one hundred with consistent thresholds. This improves cross-asset comparison and makes regime shifts obvious at a glance.
  How it works (technical) 
The script computes ATR over a configurable length, then converts that series to a percentile rank over a configurable number of bars. The percentile is naturally scaled and limited between zero and one hundred. That value is mapped to one of five regimes: above ninety (Extreme), between seventy and ninety (Elevated), between thirty and seventy (Normal), between ten and thirty (Calm), and below ten (Squeeze). Horizontal guide lines mark the thresholds, and fills shade the regions. A table is created once and updated on each bar to show regime definitions and highlight the current row. An optional label on the last bar displays the current percentile and regime. No higher-timeframe requests are used, so repaint risk is limited to normal live-bar fluctuation until the bar closes.
  Parameter Guide 
 ATR length — Effect: Controls how fast ATR reacts to new ranges. Default: fourteen. Trade-offs/Tips: Increase to reduce noise in choppy markets; decrease to react faster during regime changes.
 Percentile window (bars) — Effect: Number of bars used for the percentile ranking. Default: two hundred fifty-two. Trade-offs/Tips: Larger windows stabilize the percentile but slow adaptation after structural regime shifts; smaller windows adapt faster but may flip more often.
 Table › Show — Effect: Toggles the regime overview table. Default: enabled. Trade-offs/Tips: Disable on constrained layouts to reduce visual clutter.
 Table › Position — Effect: Anchors the table in a chart corner. Default: Top Right. Trade-offs/Tips: Choose a corner that avoids overlapping other panels or drawings.
 Label › Show — Effect: Toggles a last-bar label with current percentile and regime. Default: enabled. Trade-offs/Tips: Useful for quick reads; disable if it obscures other annotations.
  Reading & Interpretation 
The white line shows ATR percentile between zero and one hundred. Crossing above seventy signals an elevated volatility environment; above ninety indicates event-driven extremes. Between thirty and seventy represents typical conditions. Between ten and thirty indicates calm conditions that often suit mean reversion. Below ten reflects compression, where breakout probability often increases. The colored bands visually reinforce these ranges. The table summarizes regime definitions and highlights the current state. The last-bar label mirrors the current percentile and regime for quick inspection.
  Practical Workflows & Combinations 
 Trend following: Prefer continuation tactics when the percentile holds in the Normal or Elevated bands and structure confirms higher highs and higher lows. Consider wider stops and partial position sizing as percentile rises.
 Mean reversion: Favor fades in Calm regimes within defined ranges; use structure filters and time-of-day constraints to avoid low-liquidity whipsaws.
 Breakout preparation: Track compressions below ten; plan entries only with structure confirmation and risk caps, since compressions can persist.
 Multi-asset/Multi-TF: Defaults travel well on daily charts. For intraday, reduce the percentile window to align with session dynamics. Combine with trend or market structure tools for confirmation.
  Behavior, Constraints & Performance 
 Repaint/confirmation: The percentile updates during live bars and stabilizes on close; closed bars do not repaint.
 security/HTF: Not used. If you add higher-timeframe aggregation externally, account for standard repaint caveats.
 Resources: Declared maximum bars back is two thousand; limits for lines and labels are five hundred each. A short loop updates the table rows; arrays are used for table content only.
 Known limits: Regime boundaries are fixed; assets with persistent volatility shifts may require window retuning. Low-liquidity periods and gaps can produce abrupt percentile changes. ATR is direction-agnostic and should be paired with trend or structure context.
  Sensible Defaults & Quick Tuning 
Start with ATR length fourteen and percentile window two hundred fifty-two on daily charts.
 Too many flips: Increase ATR length or increase the percentile window.
 Too sluggish: Decrease the percentile window or reduce ATR length.
 Intraday noise: Keep ATR length moderate and reduce the window to a session-appropriate size; optionally hide the label to declutter.
 Compressed markets: Maintain defaults but rely more on structure and volume filters before acting.
  What this indicator is—and isn’t 
This is a volatility regime context layer that standardizes ATR into interpretable regimes. It is not a complete trading system, not predictive, and not a stand-alone entry signal. Use it alongside structure analysis, confirmation tools, and disciplined risk management.
 Disclaimer 
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
 Best regards and happy trading
Chervolino 
Cari dalam skrip untuk "one一季度财报"
Cumulative Returns by Session [BackQuant]Cumulative Returns by Session  
 What this is 
 This tool breaks the trading day into three user-defined sessions and tracks how much each session contributes to return, volatility, and volume. It then aggregates results over a rolling window so you can see which session has been pulling its weight, how streaky each session has been, and how sessions relate to one another through a compact correlation heatmap.
We’ve also given the functionality for the user to use a simplified table, just by switching off all settings they are not interested in.
 How it works 
  1) Session segmentation 
 You define APAC, EU, and US sessions with explicit hours and time zones. The script detects when each session starts and ends on every intraday bar and records its open, intraday high and low, close, and summed volume.
 2) Per-session math 
 At each session end the script computes:
  
  Return  — either Percent: (Close−Open)÷Open×100(Close − Open) ÷ Open × 100(Close−Open)÷Open×100 or Points: (Close−Open)(Close − Open)(Close−Open), based on your selection.
  Volatility  — either Range: (High−Low)÷Open×100(High − Low) ÷ Open × 100(High−Low)÷Open×100 or ATR scaled by price: ATR÷Open×100ATR ÷ Open × 100ATR÷Open×100.
  Volume  — total volume transacted during that session.
  
 3) Storage and lookback 
 Each day’s three session stats are stored as a row. You choose how many recent sessions to keep in memory. The script then:
  
  Builds cumulative returns for APAC, EU, US across the lookback.
  Computes averages, win rates, and a Sharpe-like ratio avgreturn÷avgvolatilityavg return ÷ avg volatilityavgreturn÷avgvolatility per session.
  Tracks streaks of positive or negative sessions to show momentum.
  Tracks drawdowns on cumulative returns to show worst runs from peak.
  Computes rolling means over a short window for short-term drift.
  
 4) Correlation heatmap 
 Using the stored arrays of session returns, the script calculates Pearson correlations between APAC–EU, APAC–US, and EU–US, and colors the matrix by strength and sign so you can spot coupling or decoupling at a glance.
 What it plots 
  
  Three lines: cumulative return for APAC, EU, US over the chosen lookback.
  Zero reference line for orientation.
  A statistics table with cumulative %, average %, positive session rate, and optional columns for volatility, average volume, max drawdown, current streak, return-to-vol ratio, and rolling average.
  A small correlation heatmap table showing APAC, EU, US cross-session correlations.
  
 How to use it 
  
  Pick the asset  — leave Custom Instrument empty to use the chart symbol, or point to another symbol for cross-asset studies.
  Set your sessions and time zones  — defaults approximate APAC, EU, and US hours, but you can align them to exchange times or your workflow.
  Choose calculation modes  — Percent vs Points for return, Range vs ATR for volatility. Points are convenient for futures and fixed-tick assets, Percent is comparable across symbols.
  Decide the lookback  — more sessions smooths lines and stats; fewer sessions makes the tool more reactive.
  Toggle analytics  — add volatility, volume, drawdown, streaks, Sharpe-like ratio, rolling averages, and the correlation table as needed.
  
 Why session attribution helps 
 Different sessions are driven by different flows. Asia often sets the overnight tone, Europe adds liquidity and direction changes, and the US session can dominate range expansion. Separating contributions by session helps you:
  
  Identify which session has been the main driver of net trend.
  Measure whether volatility or volume is concentrated in a specific window.
  See if one session’s gains are consistently given back in another.
  Adapt tactics: fade during a mean-reverting session, press during a trending session.
  
 Reading the tables 
  
  Cumulative %  — sum of session returns over the lookback. The sign and slope tell you who is carrying the move.
  Avg Return % and Positive Sessions %  — direction and hit rate. A low average but high hit rate implies many small moves; the reverse implies occasional big swings.
  Avg Volatility %  — typical intrabars range for that session. Compare with Avg Return to judge efficiency.
  Return/Vol Ratio  — return per unit of volatility. Higher is better for stability.
  Max Drawdown %  — worst cumulative give-back within the lookback. A quick way to spot riskiness by session.
  Current Streak  — consecutive up or down sessions. Useful for mean-reversion or regime awareness.
  Rolling Avg %  — short-window drift indicator to catch recent turnarounds.
  Correlation matrix  — green clusters indicate sessions tending to move together; red indicates offsetting behavior.
  
 Settings overview 
  Basic 
  
  Number of Sessions — how many recent days to include.
  Custom Instrument — analyze another ticker while staying on your current chart.
  
  Session Configuration and Times 
  
  Enable or hide APAC, EU, US rows.
  Set hours per session and the specific time zone for each.
  
  Calculation Methods 
  
  Return Calculation — Percent or Points.
  Volatility Calculation — Range or ATR; ATR Length when applicable.
  
  Advanced Analytics 
  
  Correlation, Drawdown, Momentum, Sharpe-like ratio, Rolling Statistics, Rolling Period.
  
  Display Options and Colors 
  
  Show Statistics Table and its position.
  Toggle columns for Volatility and Volume.
  Pick individual colors for each session line and row accents.
  
 Common applications 
  
  Session bias mapping  — find which window tends to trend in your market and plan exposure accordingly.
  Strategy scheduling  — allocate attention or risk to the session with the best return-to-vol ratio.
  News and macro awareness  — see if correlation rises around central bank cycles or major data releases.
  Cross-asset monitoring  — set the Custom Instrument to a driver (index future, DXY, yields) to see if your symbol reacts in a particular session.
  
 Notes 
 This indicator works on intraday charts, since sessions are defined within a day. If you change session clocks or time zones, give the script a few bars to accumulate fresh rows. Percent vs Points and Range vs ATR choices affect comparability across assets, so be consistent when comparing symbols.
Session context is one of the simplest ways to explain a messy tape. By separating the day into three windows and scoring each one on return, volatility, and consistency, this tool shows not just where price ended up but when and how it got there. Use the cumulative lines to spot the steady driver, read the table to judge quality and risk, and glance at the heatmap to learn whether the sessions are amplifying or canceling one another. Adjust the hours to your market and let the data tell you which session deserves your focus.
cd_SMT_Sweep_CISD_CxGeneral 
This indicator is designed to show trading opportunities after sweeps of higher timeframe (HTF) highs/lows and, if available, Smart Money Technique (SMT) divergence with a correlated asset, followed by confirmation from a lower timeframe change in state delivery (CISD).
Users can track SMT, Sweep, and CISD levels across nine different timeframes.
________________________________________
 Usage and Details 
Commonly correlated timeframes are available in the menu by default. Users can also enter other compatible timeframes manually if necessary.
  
The indicator output is presented as:
•	A summary table
•	Display on HTF candles
•	CISD levels shown as lines
Users can disable any of these from the menu.
Presentations of selected timeframes are displayed only if they are greater than or equal to the active chart timeframe.
From the Show/Hide section, you can control the display of:
•	SMT table
•	Sweep table
•	HTF candles
•	CISD levels
•	HTF boxes aligned with the active timeframe
________________________________________
 SMT Analysis 
To receive analysis, users must enter correlated assets in the menu (or adjust them as needed).
If asset X is paired with correlated asset Y, then a separate entry for Y correlated with X is not required.
Four correlation pairs are included by default. Users should check them according to their broker/exchange or define new ones.
Checkboxes at the beginning of each row allow activation/deactivation of pairs.
  
SMT analysis is performed on the last three candles of each selected HTF.
If one asset makes a new high while the correlated one does not (or one makes a new low while the other does not), this is considered SMT and will be displayed both in the table and on the chart.
Charts without defined correlated assets will not display an SMT table.
________________________________________
 Sweep Analysis 
For the selected timeframes, the current candle is compared with the previous one.
If price violates the previous level and then pulls back behind it, this is considered a sweep. It is displayed in both the table and on the chart.
Within correlated pairs, the analysis is done separately and shown only in the table.
Example with correlated and non-correlated pairs:
  
•	In the table, X = false, ✓ = true.
•	The Sweep Table has two columns for Bullish and Bearish results.
•	For correlated pairs, both values appear side by side.
•	For undefined pairs, only the active asset is shown.
Example 1: EURUSD and GBPUSD pair
•	If both sweep → ✓ ✓
•	If one sweeps, the other does not → ✓ X
•	If neither sweeps → X X
Example 2: AUDUSD with no correlated pair defined
•	If sweep → ✓
•	If no sweep → X
________________________________________
 HTF Candles 
For every HTF enabled by the user, the last three candles (including the current one) are shown on the chart.
SMT and sweep signals are marked where applicable.
________________________________________
 CISD Levels 
For the selected timeframes, bullish and bearish CISD levels are plotted on the chart.
________________________________________
 HTF Boxes 
HTF boxes aligned with the active timeframe are displayed on the chart.
Box border colors change according to whether the active HTF candle is bullish or bearish.
________________________________________
 How to Read the Chart? 
Let’s break down the example below:
  
•	Active asset: Nasdaq
•	Correlated asset: US500 (defined in the menu, confirmed in the table bottom row)
•	Active timeframe: H1 → therefore, the HTF box is shown for Daily
•	Since a correlated pair is defined, the indicator runs both SMT and Sweep analysis for the selected timeframes. Without correlation, only Sweep analysis would be shown.
Table is prepared for H1 and higher timeframes (as per user selection and active TF).
Observations:
•	SMT side → H1 timeframe shows a bearish warning
•	Sweep side → Bearish column shows X and ✓
o	X → no sweep on Nasdaq
o	✓ → sweep on US500
Meaning: US500 made a new high (+ sweep) while Nasdaq did not → SMT formed.
The last column of the table shows the compatible LTF for confirmation.
For H1, it suggests checking the 5m timeframe.
On the chart:
•	CISD levels for selected timeframes are drawn
•	SMT line is marked on H1 candles
•	Next step: move to 5m chart for CISD confirmation before trading (with other confluences).
Similarly, the Daily row in the table shows a Bullish Sweep on US500.
________________________________________
 Alerts 
Two alert options are available:
 1. 	Activate Alert (SMT + Sweep):
Triggers if both SMT and Sweep occur in the selected timeframes. (Classic option)
 2. 	Activate Alert (Sweep + Sweep):
Triggers if sweeps occur in both assets of a correlated pair at the same timeframe.
Interpretation:
If SMT + Sweep are already present on higher timeframes, and simultaneous sweeps appear on lower timeframes, this may indicate a strong directional move.
Of course, this must be validated with CISD and other confluences.
________________________________________
 HTF CISD Levels 
Although CISD levels act as confirmation levels in their own timeframe, observing how price reacts to HTF CISD levels can provide valuable insights for intraday analysis.
POIs overlapping with these levels may be higher priority.
________________________________________
 What’s Next in Future Versions? 
•	Completed CISD confirmations
•	Additional alert options
•	Plus your feedback and suggestions
________________________________________
 Final Note 
I’ll be happy to hear your opinions and feedback.
Happy trading! 
CleanBreak Lines (Break + First Retest)CleanBreak lines draws one robust support line (green) from swing lows and one robust resistance line (red) from swing highs, then optionally signals a confirmed break and the first clean retest back to that line. Lines are scored with a transparent W-Score (0–100) so traders can judge quality at a glance. The script is non-repainting and uses only confirmed bar data.
What it does
Auto-builds two trendlines that aim to represent meaningful support and resistance.
Uses a median-based slope so outliers and single spikes do not distort the line.
Computes a W-Score per line from three things: touches, span (how long it held), and respect (staying on the correct side).
Optionally triggers a single, tightly-gated signal on Break + First Retest.
How it works (plain English)
Detect recent swing highs and swing lows.
Fit one line through highs and one through lows using a robust, median-style slope estimate.
Score each line: more clean touches and longer span raise the W-Score; frequent violations lower it.
A break requires a candle close beyond the line by a small ATR margin.
A first retest requires price to come back to the line within a limited number of bars and hold on close.
A single arrow may print on that confirmed retest, with optional alerts.
What it is not
Not a prediction model and not a promises-of-profit tool.
Not a multi-signal spammer: by design it aims to allow one retest entry per break.
Not a regression channel or machine-learning system.
How to use
At a glance: treat the green line as candidate support and the red line as candidate resistance.
Conservative approach: wait for a break on close and then the first retest to hold; use the arrow as a prompt, not a command.
Context-only mode: hide arrows in Style if you want the lines and W-Score only.
Inputs (brief)
Core: Swing Length, Max Pivots, Min Touches, Min Span Bars.
Scoring: Touches Max (cap), Weights for touches vs span, Min W-Score to arm.
Break and Retest: Break Margin x ATR, Retest Tolerance x ATR, Retest Window (bars).
Visuals: Show Labels, Show Table, Line Width, Fade When Refit.
Recommended presets
Cleaner, fewer signals: Min Touches 4–5, Min Span Bars 100–150, Min W-Score 70–80, Break Margin 0.40–0.60 ATR, Retest Tolerance 0.10–0.15 ATR, Retest Window 8–12 bars.
Lines-only: keep defaults and uncheck the two plotshapes in Style.
Alerts
CB Long Retest: break above the red line and first retest holds.
CB Short Retest: break below the green line and first retest holds.
Use “Once per bar close” for consistency.
On-chart table (if enabled)
RES / SUP: W-Score and distance from price in ATR terms.
Status: “Waiting Long RT”, “Waiting Short RT”, or “Idle”.
Thresholds: MinScore and Retest bars for quick context.
Timeframes
Works well on 1h to 1D. On very low timeframes, raise Break Margin x ATR to reduce whipsaw effects. On higher timeframes, increase Min Touches and Min Span Bars.
Non-repainting policy
All logic uses confirmed pivots and confirmed bar closes.
Breaks and retests are validated on close; alerts reference only confirmed conditions.
No lookahead in any request.security call.
Original implementation focused on a median-based robust slope for auto trendlines, plus a transparent W-Score and a single retest gate.
Disclosure
This script is for education and charting. It does not guarantee outcomes, and past behavior does not imply future results. Always validate on historical data and practice risk management.
+ ATR Table and BracketsHi, all. I'm back with a new indicator—one I firmly believe could be one of the most valuable indicators you keep in your indicator toolshed—based around true range.
This is a simple, streamlined indicator utilizing true range and average true range that will help any trader with stoploss, trailing stoploss, and take-profit placement—things that I know many traders use average true range for. It could also be useful for trade entries as well, depending on the trader's style.
Typically, most traders (or at least what I've seen recommended across websites, video tutorials on YouTube, etc.) are taught to simply take the ATR number and use that, and possibly some sort of multiplier, as your stoploss and take-profit. This is fine, but I thought that it might be possible to dive a bit deeper into these values. Because an average is a combination of values, some higher, some lower, and we often see ATR spikes during periods of high volatility, I thought wouldn't it be useful to know what value those ATR spikes are, and how do they relate to the ATR? Then I thought to myself, well, what about the most volatile candle within that ATR (the candle with the greatest true range)? Couldn't knowing that value be useful to a trader? So then the idea of a table displaying these values, along with the ATR and the ATR times some multiplier number, would be a useful, simple way to display this information. That's what we have here.
The table is made up of two columns, one with the name of the metric being measured, and the other with its value. That's it. Simple.
As nice as this was, I thought an additional, great, and perhaps better, way to visualize this information would be in the form of brackets extending from the current bar. These are simply lines/labels plotted at the price values of the ATR, ATR times X, highest ATR, highest ATR times X, and highest TR value. These labels supply the actual values of the ATR, etc., but may also display the price if you should choose (both of these values are toggleable in the 'Inputs' section of the indicator.). Additionally, you can choose to display none of these labels, or all five if you wish (leaves the chart a bit cluttered, as shown in the image below), though I suspect you'll determine your preferences for which information you'd like to see and which not.
  
Chart with all five lines/labels displayed. I adjusted the ATRX value to 3 just to make the screenshot as legible as possible. Default is set to 1.5. As you can see, the label doesn't show the multiplier number, but the table does.
  
Here's a screenshot of the labels showing the price in addition to the value of the ATR, set to "Previous Closing Price," (see next paragraph for what that means) and highest TR. Personally, I don't see the value in the displaying the price, but I thought some people might want that. It's not available in the table as of now, but perhaps if I get enough requests for it I will add it.
That's basically it, but one last detail I need to go over is the dropdown box labeled "Bar Value ATR Levels are Oriented To." Firstly, this has no effect on Highest ATR, Highest ATRX, and Highest TR levels. Those are based on the ATR up to the last closed candle, meaning they aren't including the value of the currently open candle (this would be useless). However, knowing that different traders trade different ways it seemed to me prudent to allow for traders to select which opening or closing value the trader wishes to have the ATR brackets based on. For example, as someone who has consumed much No Nonsense Forex content I know that traders are urged to enter their trades in the last fifteen minutes of the trading day because the ATR is unlikely to change significantly in that period (ATR being the centerpiece of NNFX money management), so one of three selections here is to plot the brackets based on the ATR's inclusion of this value (this of course means the brackets will move while the candle is still open). The other options are to set the brackets to the current opening price, or the previous closing price. Depending on what you're trading many times these prices are virtually identical, but sometimes price gaps (stocks in particular), so, wanting your brackets placed relative to the previous close as opposed to the current open might be preferable for some traders.
And that's it. I really hope you guys like this indicator. I haven't seen anything closely similar to it on TradingView, and I think it will be something you all will find incredibly handy.
Please enjoy!
Color█ OVERVIEW 
This library is a Pine Script® programming tool for advanced color processing. It provides a comprehensive set of functions for specifying and analyzing colors in various color spaces, mixing and manipulating colors, calculating custom gradients and schemes, detecting contrast, and converting colors to or from hexadecimal strings. 
 █ CONCEPTS 
 Color 
Color refers to how we interpret light of different wavelengths in the  visible spectrum . The colors we see from an object represent the light wavelengths that it reflects, emits, or transmits toward our eyes. Some colors, such as blue and red, correspond directly to parts of the spectrum. Others, such as magenta, arise from a combination of wavelengths to which our minds  assign  a single color. 
The human interpretation of color lends itself to many uses in our world. In the context of financial data analysis, the effective use of color helps transform raw data into insights that users can understand at a glance. For example, colors can categorize series, signal market conditions and sessions, and emphasize patterns or relationships in data. 
 Color models and spaces 
A  color model  is a general mathematical framework that describes colors using sets of numbers. A  color space  is an implementation of a specific color model that defines an exact range (gamut) of reproducible colors based on a set of  primary colors , a reference  white point , and sometimes additional parameters such as viewing conditions.
There are numerous different color spaces — each describing the characteristics of color in unique ways. Different spaces carry different advantages, depending on the application. Below, we provide a brief overview of the concepts underlying the color spaces supported by this library.
 RGB 
 RGB  is one of the most well-known color models. It represents color as an additive mixture of three primary colors — red, green, and blue lights — with various intensities. Each cone cell in the human eye responds more strongly to one of the three primaries, and the average person interprets the combination of these lights as a distinct color (e.g., pure red + pure green = yellow). 
The  sRGB  color space is the most common RGB implementation. Developed by HP and Microsoft in the 1990s, sRGB provided a standardized baseline for representing color across CRT monitors of the era, which produced brightness levels that did not increase linearly with the input signal. To match displays and optimize brightness encoding for human sensitivity, sRGB applied a nonlinear transformation to linear RGB signals, often referred to as  gamma correction . The result produced more visually pleasing outputs while maintaining a simple encoding. As such, sRGB quickly became a standard for digital color representation across devices and the web. To this day, it remains the default color space for most web-based content. 
TradingView charts and Pine Script `color.*` built-ins process color data in sRGB. The red, green, and blue channels range from 0 to 255, where 0 represents no intensity, and 255 represents maximum intensity. Each combination of red, green, and blue values represents a distinct color, resulting in a total of 16,777,216  displayable  colors. 
 CIE XYZ and xyY 
The  XYZ  color space, developed by the International Commission on Illumination (CIE) in 1931, aims to describe  all  color sensations that a typical human can perceive. It is a cornerstone of color science, forming the basis for many color spaces used today. XYZ, and the derived  xyY  space, provide a universal representation of color that is not tethered to a particular display. Many widely used color spaces, including sRGB, are defined relative to XYZ or derived from it.
The CIE built the color space based on a series of experiments in which people matched colors they perceived from mixtures of lights. From these experiments, the CIE developed  color-matching  functions to calculate three components —  X, Y, and Z  — which together aim to describe a standard observer's response to visible light. X represents a weighted response to light across the color spectrum, with the highest contribution from long wavelengths (e.g., red). Y represents a weighted response to medium wavelengths (e.g., green), and it corresponds to a color's  relative luminance  (i.e., brightness). Z represents a weighted response to short wavelengths (e.g., blue).  
From the XYZ space, the CIE developed the xyY chromaticity space, which separates a color's  chromaticity  (hue and colorfulness) from luminance. The CIE used this space to define the  CIE 1931 chromaticity diagram , which represents the full range of visible colors at a given luminance. In color science and lighting design, xyY is a common means for specifying colors and visualizing the supported ranges of other color spaces.
 CIELAB and Oklab 
The  CIELAB  (L*a*b*) color space, derived from XYZ by the CIE in 1976, expresses colors based on  opponent process  theory. The L* component represents perceived lightness, and the a* and b* components represent the balance between opposing unique colors. The a* value specifies the balance between  green and red , and the b* value specifies the balance between  blue and yellow . 
The primary intention of CIELAB was to provide a  perceptually uniform  color space, where fixed-size steps through the space correspond to uniform perceived changes in color. Although relatively uniform, the color space has been found to exhibit some non-uniformities, particularly in the blue part of the color spectrum. Regardless, modern applications often use CIELAB to estimate perceived color differences and calculate smooth color gradients. 
In 2020, a new LAB-oriented color space,  Oklab , was introduced by Björn Ottosson as an attempt to rectify the non-uniformities of other perceptual color spaces. Similar to CIELAB, the L value in Oklab represents perceived lightness, and the a and b values represent the balance between opposing unique colors. Oklab has gained widespread adoption as a perceptual space for color processing, with support in the latest CSS Color specifications and many software applications. 
 Cylindrical models 
A  cylindrical-coordinate  model transforms an underlying color model, such as RGB or LAB, into an alternative expression of color information that is often more intuitive for the average person to use and understand. 
Instead of a mixture of primary colors or opponent pairs, these models represent color as a  hue angle  on a  color wheel , with additional parameters that describe other qualities such as lightness and colorfulness (a general term for concepts like chroma and saturation). In cylindrical-coordinate spaces, users can select a color and modify its lightness or other qualities without altering the hue. 
The three most common RGB-based models are  HSL  (Hue, Saturation, Lightness),  HSV  (Hue, Saturation, Value), and  HWB  (Hue, Whiteness, Blackness). All three define hue angles in the same way, but they define colorfulness and lightness differently. Although they are not perceptually uniform, HSL and HSV are commonplace in color pickers and gradients. 
For CIELAB and Oklab, the cylindrical-coordinate versions are  CIELCh  and  Oklch , which express color in terms of perceived lightness, chroma, and hue. They offer perceptually uniform alternatives to RGB-based models. These spaces create unique color wheels, and they have more strict definitions of lightness and colorfulness. Oklch is particularly well-suited for generating smooth, perceptual color gradients. 
 Alpha and transparency 
Many color encoding schemes include an  alpha  channel, representing  opacity . Alpha does  not  help define a color in a color space; it determines how a color  interacts  with other colors in the display. Opaque colors appear with full intensity on the screen, whereas translucent (semi-opaque) colors blend into the background. Colors with zero opacity are invisible. 
In Pine Script, there are two ways to specify a color's alpha:
 • Using the `transp` parameter of the built-in `color.*()` functions. The specified value represents transparency (the opposite of opacity), which the functions translate into an alpha value. 
 • Using eight-digit hexadecimal color codes. The  last two  digits in the code represent alpha directly. 
A process called  alpha compositing  simulates translucent colors in a display. It creates a single displayed color by mixing the RGB channels of two colors (foreground and background) based on alpha values, giving the illusion of a semi-opaque color placed over another color. For example, a red color with 80% transparency on a black background produces a dark shade of red. 
 Hexadecimal color codes 
A hexadecimal color code (hex code) is a compact representation of an RGB color. It encodes a color's red, green, and blue values into a sequence of hexadecimal ( base-16 ) digits. The digits are numerals ranging from `0` to `9` or letters from `a` (for 10) to `f` (for 15). Each set of  two  digits represents an RGB channel ranging from `00` (for 0) to `ff` (for 255). 
Pine scripts can natively define colors using hex codes in the format `#rrggbbaa`. The first set of two digits represents red, the second represents green, and the third represents blue. The fourth set represents  alpha . If unspecified, the value is `ff` (fully opaque). For example, `#ff8b00` and `#ff8b00ff` represent an opaque orange color. The code `#ff8b0033` represents the same color with 80% transparency. 
 Gradients 
A  color gradient  maps colors to numbers over a given range. Most color gradients represent a continuous path in a specific color space, where each number corresponds to a  mix  between a starting color and a stopping color. In Pine, coders often use gradients to visualize value intensities in plots and heatmaps, or to add visual depth to fills. 
The behavior of a color gradient depends on the mixing method and the chosen color space. Gradients in sRGB usually mix along a straight line between the red, green, and blue coordinates of two colors. In cylindrical spaces such as HSL, a gradient often rotates the hue angle through the color wheel, resulting in more pronounced color transitions.
 Color schemes 
A  color scheme  refers to a set of colors for use in aesthetic or functional design. A color scheme usually consists of just a few distinct colors. However, depending on the purpose, a scheme can include many colors.
A user might choose palettes for a color scheme arbitrarily, or generate them algorithmically. There are many techniques for calculating color schemes. A few simple, practical methods are:
 • Sampling a set of distinct colors from a color gradient.
 • Generating monochromatic variants of a color (i.e., tints, tones, or shades with matching hues).
 • Computing color harmonies — such as complements, analogous colors, triads, and tetrads — from a base color. 
This library includes functions for all three of these techniques. See below for details. 
 █ CALCULATIONS AND USE 
 Hex string conversion 
The `getHexString()` function returns a string containing the eight-digit hexadecimal code corresponding to a "color" value or set of sRGB and transparency values. For example, `getHexString(255, 0, 0)` returns the string `"#ff0000ff"`, and `getHexString(color.new(color.red, 80))` returns `"#f2364533"`.
The `hexStringToColor()` function returns the "color" value represented by a string containing a six- or eight-digit hex code. The `hexStringToRGB()` function returns a tuple containing the sRGB and transparency values. For example, `hexStringToColor("#f23645")` returns the same value as  color.red . 
Programmers can use these functions to parse colors from "string" inputs, perform string-based color calculations, and inspect color data in text outputs such as Pine Logs and tables. 
 Color space conversion 
All other `get*()` functions convert a "color" value or set of sRGB channels into coordinates in a specific color space, with transparency information included. For example, the tuple returned by `getHSL()` includes the color's hue, saturation, lightness, and transparency values. 
To convert data from a color space back to colors or sRGB and transparency values, use the corresponding `*toColor()` or `*toRGB()` functions for that space (e.g., `hslToColor()` and `hslToRGB()`). 
Programmers can use these conversion functions to process inputs that define colors in different ways, perform advanced color manipulation, design custom gradients, and more. 
The color spaces this library supports are:
 • sRGB
 • Linear RGB (RGB  without  gamma correction)
 • HSL, HSV, and HWB
 • CIE XYZ and xyY
 • CIELAB and CIELCh
 • Oklab and Oklch
 Contrast-based calculations 
 Contrast  refers to the difference in luminance or color that makes one color visible against another. This library features two functions for calculating luminance-based contrast and detecting themes.  
The `contrastRatio()` function calculates the contrast between two "color" values based on their relative luminance (the Y value from CIE XYZ) using the formula from version 2 of the  Web Content Accessibility Guidelines (WCAG) . This function is useful for identifying colors that provide a sufficient brightness difference for legibility. 
The `isLightTheme()` function determines whether a specified background color represents a light theme based on its contrast with black and white. Programmers can use this function to define conditional logic that responds differently to light and dark themes. 
 Color manipulation and harmonies 
The `negative()` function calculates the  negative  (i.e., inverse) of a color by reversing the color's coordinates in either the sRGB or linear RGB color space. This function is useful for calculating high-contrast colors. 
The `grayscale()` function calculates a grayscale form of a specified color with the same relative luminance. 
The functions `complement()`, `splitComplements()`, `analogousColors()`, `triadicColors()`, `tetradicColors()`, `pentadicColors()`, and `hexadicColors()` calculate  color harmonies  from a specified source color within a given color space (HSL, CIELCh, or Oklch). The returned harmonious colors represent specific  hue rotations  around a color wheel formed by the chosen space, with the same defined lightness, saturation or chroma, and transparency.
 Color mixing and gradient creation 
The `add()` function simulates combining lights of two different colors by additively mixing their linear red, green, and blue components, ignoring transparency by default. Users can calculate a transparency-weighted mixture by setting the `transpWeight` argument to `true`. 
The `overlay()` function estimates the color displayed on a TradingView chart when a specific foreground color is over a background color. This function aids in simulating stacked colors and analyzing the effects of transparency. 
The `fromGradient()` and `fromMultiStepGradient()` functions calculate colors from gradients in any of the supported color spaces, providing flexible alternatives to the RGB-based  color.from_gradient()  function. The `fromGradient()` function calculates a color from a single gradient. The `fromMultiStepGradient()` function calculates a color from a  piecewise  gradient with multiple defined steps. Gradients are useful for heatmaps and for coloring plots or drawings based on value intensities.  
 Scheme creation 
Three functions in this library calculate  palettes  for custom color schemes. Scripts can use these functions to create responsive color schemes that adjust to calculated values and user inputs. 
The `gradientPalette()` function creates an array of colors by sampling a specified number of colors along a gradient from a base color to a target color, in fixed-size steps. 
The `monoPalette()` function creates an array containing monochromatic variants (tints, tones, or shades) of a specified base color. Whether the function mixes the color toward white (for tints), a form of gray (for tones), or black (for shades) depends on the `grayLuminance` value. If unspecified, the function automatically chooses the mix behavior with the highest contrast. 
The `harmonyPalette()` function creates a  matrix  of colors. The first column contains the base color and specified harmonies, e.g., triadic colors. The columns that follow contain tints, tones, or shades of the harmonic colors for additional color choices, similar to `monoPalette()`. 
 █ EXAMPLE CODE 
The example code at the end of the script generates and visualizes color schemes by processing user inputs. The code builds the scheme's palette based on the "Base color" input and the additional inputs in the "Settings/Inputs" tab:
 •  "Palette type" specifies whether the palette uses a custom gradient, monochromatic base color variants, or color harmonies with monochromatic variants. 
 •  "Target color" sets the top color for the "Gradient" palette type. 
 •  The "Gray luminance" inputs determine variation behavior for "Monochromatic" and "Harmony" palette types. If "Auto" is selected, the palette mixes the base color toward white or black based on its brightness. Otherwise, it mixes the color toward the grayscale color with the specified relative luminance (from 0 to 1). 
 •  "Harmony type" specifies the color harmony used in the palette. Each row in the palette corresponds to one of the harmonious colors, starting with the base color. 
The code creates a table on the first bar to display the collection of calculated colors. Each cell in the table shows the color's `getHexString()` value in a tooltip for simple inspection. 
 Look first. Then leap. 
 █ EXPORTED FUNCTIONS 
Below is a complete list of the functions and overloads exported by this library.
 getRGB(source) 
  Retrieves the sRGB red, green, blue, and transparency components of a "color" value.
 getHexString(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channel values to a string representing the corresponding color's hexadecimal form.
 getHexString(source) 
  (Overload 2 of 2) Converts a "color" value to a string representing the sRGB color's hexadecimal form.
 hexStringToRGB(source) 
  Converts a string representing an sRGB color's hexadecimal form to a set of decimal channel values.
 hexStringToColor(source) 
  Converts a string representing an sRGB color's hexadecimal form to a "color" value.
 getLRGB(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channel values to a set of linear RGB values with specified transparency information.
 getLRGB(source) 
  (Overload 2 of 2) Retrieves linear RGB channel values and transparency information from a "color" value.
 lrgbToRGB(lr, lg, lb, t) 
  Converts a set of linear RGB channel values to a set of sRGB values with specified transparency information.
 lrgbToColor(lr, lg, lb, t) 
  Converts a set of linear RGB channel values and transparency information to a "color" value.
 getHSL(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HSL values with specified transparency information.
 getHSL(source) 
  (Overload 2 of 2) Retrieves HSL channel values and transparency information from a "color" value.
 hslToRGB(h, s, l, t) 
  Converts a set of HSL channel values to a set of sRGB values with specified transparency information.
 hslToColor(h, s, l, t) 
  Converts a set of HSL channel values and transparency information to a "color" value.
 getHSV(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HSV values with specified transparency information. 
 getHSV(source) 
  (Overload 2 of 2) Retrieves HSV channel values and transparency information from a "color" value.
 hsvToRGB(h, s, v, t) 
  Converts a set of HSV channel values to a set of sRGB values with specified transparency information.
 hsvToColor(h, s, v, t) 
  Converts a set of HSV channel values and transparency information to a "color" value.
 getHWB(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of HWB values with specified transparency information.
 getHWB(source) 
  (Overload 2 of 2) Retrieves HWB channel values and transparency information from a "color" value.
 hwbToRGB(h, w, b, t) 
  Converts a set of HWB channel values to a set of sRGB values with specified transparency information.
 hwbToColor(h, w, b, t) 
  Converts a set of HWB channel values and transparency information to a "color" value.
 getXYZ(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of XYZ values with specified transparency information.
 getXYZ(source) 
  (Overload 2 of 2) Retrieves XYZ channel values and transparency information from a "color" value.
 xyzToRGB(x, y, z, t) 
  Converts a set of XYZ channel values to a set of sRGB values with specified transparency information
 xyzToColor(x, y, z, t) 
  Converts a set of XYZ channel values and transparency information to a "color" value.
 getXYY(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of xyY values with specified transparency information.
 getXYY(source) 
  (Overload 2 of 2) Retrieves xyY channel values and transparency information from a "color" value.
 xyyToRGB(xc, yc, y, t) 
  Converts a set of xyY channel values to a set of sRGB values with specified transparency information.
 xyyToColor(xc, yc, y, t) 
  Converts a set of xyY channel values and transparency information to a "color" value.
 getLAB(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of CIELAB values with specified transparency information.
 getLAB(source) 
  (Overload 2 of 2) Retrieves CIELAB channel values and transparency information from a "color" value.
 labToRGB(l, a, b, t) 
  Converts a set of CIELAB channel values to a set of sRGB values with specified transparency information.
 labToColor(l, a, b, t) 
  Converts a set of CIELAB channel values and transparency information to a "color" value.
 getOKLAB(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of Oklab values with specified transparency information.
 getOKLAB(source) 
  (Overload 2 of 2) Retrieves Oklab channel values and transparency information from a "color" value.
 oklabToRGB(l, a, b, t) 
  Converts a set of Oklab channel values to a set of sRGB values with specified transparency information.
 oklabToColor(l, a, b, t) 
  Converts a set of Oklab channel values and transparency information to a "color" value.
 getLCH(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of CIELCh values with specified transparency information.
 getLCH(source) 
  (Overload 2 of 2) Retrieves CIELCh channel values and transparency information from a "color" value.
 lchToRGB(l, c, h, t) 
  Converts a set of CIELCh channel values to a set of sRGB values with specified transparency information.
 lchToColor(l, c, h, t) 
  Converts a set of CIELCh channel values and transparency information to a "color" value.
 getOKLCH(r, g, b, t) 
  (Overload 1 of 2) Converts a set of sRGB channels to a set of Oklch values with specified transparency information.
 getOKLCH(source) 
  (Overload 2 of 2) Retrieves Oklch channel values and transparency information from a "color" value.
 oklchToRGB(l, c, h, t) 
  Converts a set of Oklch channel values to a set of sRGB values with specified transparency information.
 oklchToColor(l, c, h, t) 
  Converts a set of Oklch channel values and transparency information to a "color" value.
 contrastRatio(value1, value2) 
  Calculates the contrast ratio between two colors values based on the formula from version 2 of the Web Content Accessibility Guidelines (WCAG).
 isLightTheme(source) 
  Detects whether a background color represents a light theme or dark theme, based on the amount of contrast between the color and the white and black points.
 
 grayscale(source) 
  Calculates the grayscale version of a color with the same relative luminance (i.e., brightness).
 
 negative(source, colorSpace) 
  Calculates the negative (i.e., inverted) form of a specified color.
 
 complement(source, colorSpace) 
  Calculates the complementary color for a `source` color using a cylindrical color space.
 analogousColors(source, colorSpace) 
  Calculates the analogous colors for a `source` color using a cylindrical color space.
 splitComplements(source, colorSpace) 
  Calculates the split-complementary colors for a `source` color using a cylindrical color space.
 triadicColors(source, colorSpace) 
  Calculates the two triadic colors for a `source` color using a cylindrical color space.
 tetradicColors(source, colorSpace, square) 
  Calculates the three square or rectangular tetradic colors for a `source` color using a cylindrical color space.
 pentadicColors(source, colorSpace) 
  Calculates the four pentadic colors for a `source` color using a cylindrical color space.
 hexadicColors(source, colorSpace) 
  Calculates the five hexadic colors for a `source` color using a cylindrical color space.
 add(value1, value2, transpWeight) 
  Additively mixes two "color" values, with optional transparency weighting.
 
 overlay(fg, bg) 
  Estimates the resulting color that appears on the chart when placing one color over another.
 
 fromGradient(value, bottomValue, topValue, bottomColor, topColor, colorSpace) 
  Calculates the gradient color that corresponds to a specific value based on a defined value range and color space.
 
 fromMultiStepGradient(value, steps, colors, colorSpace) 
  Calculates a multi-step gradient color that corresponds to a specific value based on an array of step points, an array of corresponding colors, and a color space.
 gradientPalette(baseColor, stopColor, steps, strength, model) 
  Generates a palette from a gradient between two base colors.
 monoPalette(baseColor, grayLuminance, variations, strength, colorSpace) 
  Generates a monochromatic palette from a specified base color.
 harmonyPalette(baseColor, harmonyType, grayLuminance, variations, strength, colorSpace) 
  Generates a palette consisting of harmonious base colors and their monochromatic variants.
Multi TF Oscillators Screener [TradingFinder] RSI / ATR / Stoch🔵 Introduction 
The oscillator screener is designed to simplify multi-timeframe analysis by allowing traders and analysts to monitor one or multiple symbols across their preferred timeframes—all at the same time. Users can track a single symbol through various timeframes simultaneously or follow multiple symbols in selected intervals. This flexibility makes the tool highly effective for analyzing diverse markets concurrently.
At the core of this screener lie two essential oscillators: RSI (Relative Strength Index) and the Stochastic Oscillator. The RSI measures the speed and magnitude of recent price movements and helps identify overbought or oversold conditions. 
It's one of the most reliable indicators for spotting potential reversals. The Stochastic Oscillator, on the other hand, compares the current price to recent highs and lows to detect momentum strength and potential trend shifts. It’s especially effective in identifying divergences and short-term reversal signals.
In addition to these two primary indicators, the screener also displays helpful supplementary data such as the dominant candlestick type (Bullish, Bearish, or Doji), market volatility indicators like ATR and TR, and the four key OHLC prices (Open, High, Low, Close) for each symbol and timeframe. This combination of data gives users a comprehensive technical view and allows for quick, side-by-side comparison of symbols and timeframes.
  
🔵 How to Use 
This tool is built for users who want to view the behavior of a single symbol across several timeframes simultaneously. Instead of jumping between charts, users can quickly grasp the state of a symbol like gold or Bitcoin across the 15-minute, 1-hour, and daily timeframes at a glance. This is particularly useful for traders who rely on multi-timeframe confirmation to strengthen their analysis and decision-making.
  
The tool also supports simultaneous monitoring of multiple symbols. Users can select and track various assets based on the timeframes that matter most to them. For example, if you’re looking for entry opportunities, the screener allows you to compare setups across several markets side by side—making it easier to choose the most favorable trade. Whether you’re a scalper focused on low timeframes or a swing trader using higher ones, the tool adapts to your workflow.
  
The screener utilizes the widely-used RSI indicator, which ranges from 0 to 100 and highlights market exhaustion levels. Readings above 70 typically indicate potential pullbacks, while values below 30 may suggest bullish reversals. Viewing RSI across timeframes can reveal meaningful divergences or alignments that improve signal quality.
Another key indicator in the screener is the Stochastic Oscillator, which analyzes the closing price relative to its recent high-low range. When the %K and %D lines converge and cross within the overbought or oversold zones, it often signals a momentum reversal. This oscillator is especially responsive in lower timeframes, making it ideal for spotting quick entries or exits.
Beyond these oscillators, the table includes other valuable data such as candlestick type (bullish, bearish, or doji), volatility measures like ATR and TR, and complete OHLC pricing. This layered approach helps users understand both market momentum and structure at a glance.
Ultimately, this screener allows analysts and traders to gain a full market overview with just one look—empowering faster, more informed, and lower-risk decision-making. It not only saves time but also enhances the precision and clarity of technical analysis.
🔵 Settings 
🟣 Display Settings 
 Table Size : Lets you adjust the table’s visual size with options such as: auto, tiny, small, normal, large, huge.
 Table Position : Sets the screen location of the table. Choose from 9 possible positions, combining vertical (top, middle, bottom) and horizontal (left, center, right) alignments.
🟣 Symbol Settings 
 Each of the 10 symbol slots comes with a full set of customizable parameters :
 Enable Symbol : A checkbox to activate or hide each symbol from the table.
 Symbol : Define or select the asset (e.g., XAUUSD, BTCUSD, EURUSD, etc.).
 Timeframe : Set your desired timeframe for each symbol (e.g., 15, 60, 240, 1D).
 RSI Length : Defines the period used in RSI calculation (default is 14).
 Stochastic Length : Sets the period for the Stochastic Oscillator.
 ATR Length : Sets the length used to calculate the Average True Range, a key volatility metric.
🔵 Conclusion 
By combining powerful oscillators like RSI and Stochastic with full customization over symbols and timeframes, this tool provides a fast, flexible solution for technical analysts. Users can instantly monitor one or several assets across multiple timeframes without opening separate charts. 
Individual configuration for each symbol, along with the inclusion of key metrics like candlestick type, ATR/TR, and OHLC prices, makes the tool suitable for a wide range of trading styles—from scalping to swing and position trading.
In summary, this screener enables traders to gain a clear, high-level view of various markets in seconds and make quicker, smarter, and lower-risk decisions. It saves time, streamlines analysis, and boosts overall efficiency and confidence in trading strategies.
Multi Asset Comparative📊 Multi Asset Comparative – Compare Baskets of Cryptos Visually
This indicator allows you to compare the performance of two groups of cryptocurrencies (or any assets) over time, using a clean and intuitive chart.
Instead of looking at each asset separately, this tool gives you a global view by showing how one group performs relative to another — all displayed in the form of candlesticks.
  
🧠 What This Tool Is For
Markets constantly shift, and capital rotates between sectors or tokens. This script helps you visually track those shifts by answering a key question:
"Is this group of assets getting stronger or weaker compared to another group?"
For example:
 
 Compare altcoins vs Bitcoin
 Track the DeFi sector vs Ethereum
 Analyze your custom portfolio vs the market
 Spot moments when money flows from majors to smaller caps, or vice versa
 
🧩 How It Works (Simplified)
You select two groups of assets:
Group 1 (up to 20 assets) — the one you want to analyze
Group 2 (up to 5 assets) — your comparison baseline
The indicator then creates a single line of candles that represents the performance of Group 1 compared to Group 2. If the candles go up, it means Group 1 is gaining strength over Group 2. If the candles go down, it's losing ground.
This lets you see market dynamics in one glance, instead of switching charts or running calculations manually.
🚀 Why It's Unique
Unlike many indicators that just show data from one asset, this one provides a bird's-eye view of multiple assets at once — condensed into a simple visual ratio.
It’s:
 
 Customizable (you choose the assets)
 Visual and intuitive (no need to interpret tables or formulas)
 Actionable (helps with trend confirmation, macro views, and market rotation)
 
Whether you're a swing trader, a macro analyst, or building your own strategy, this tool can help you spot opportunities hidden in plain sight.
✅ How to Use It
Choose your two groups of assets (e.g., altcoins vs BTC/ETH)
Watch the direction of the candles:
Uptrend = Group 1 gaining strength over Group 2
Downtrend = Group 1 weakening
Use it to confirm market shifts, anticipate rotations, or analyze sector strength
MirPapa_Handler_HTFLibrary   "MirPapa_Handler_HTF" 
High Time Frame Handler Library:
Provides utilities for working with High Time Frame (HTF) and chart (LTF) conversions and data retrieval.
 IsChartTFcomparisonHTF(_chartTf, _htfTf) 
  IsChartTFcomparisonHTF
@description
Determine whether the given High Time Frame (HTF) is greater than or equal to the current chart timeframe.
  Parameters:
     _chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
     _htfTf (string) : The High Time Frame string to compare (examples: "60", "1D").
@return
Returns true if HTF minutes ≥ chart minutes, false otherwise or na if conversion fails.
 GetHTFrevised(_tf, _case) 
  GetHTFrevised
@description
Retrieve a specific bar value from a Higher Time Frame (HTF) series.
Supports current and historical OHLC values, based on a case identifier.
  Parameters:
     _tf (string) : The target HTF string (examples: "60", "1D").
     _case (string) : A case string determining which OHLC value and bar offset to request:
"b"   → HTF bar_index
"o"   → HTF open
"h"   → HTF high
"l"   → HTF low
"c"   → HTF close
"o1"  → HTF open one bar ago
"h1"  → HTF high one bar ago
"l1"  → HTF low one bar ago
"c1"  → HTF close one bar ago
… up to "o5", "h5", "l5", "c5" for five bars ago.
@return
Returns the requested HTF value or na if _case does not match any condition.
 GetHTFfromLabel(_label) 
  GetHTFfromLabel
@description
Convert a Korean HTF label into a Pine Script-recognizable timeframe string.
Examples:
"5분"  → "5"
"1시간" → "60"
"일봉"  → "1D"
"주봉"  → "1W"
"월봉"  → "1M"
"연봉"  → "12M"
  Parameters:
     _label (string) : The Korean HTF label string (examples: "5분", "1시간", "일봉").
@return
Returns the Pine Script timeframe string corresponding to the label, or "1W" if no match is found.
 GetHTFoffsetToLTFoffset(_offset, _chartTf, _htfTf) 
  GetHTFoffsetToLTFoffset
@description
Adjust an HTF bar index and offset so that it aligns with the current chart’s bar index.
Useful for retrieving historical HTF data on an LTF chart.
  Parameters:
     _offset (int) : The HTF bar offset (0 means current HTF bar, 1 means one bar ago, etc.).
     _chartTf (string) : The current chart’s timeframe string (examples: "5", "15", "1D").
     _htfTf (string) : The High Time Frame string to align (examples: "60", "1D").
@return
Returns the corresponding LTF bar index after applying HTF offset. If result is negative, returns 0.
Ultimate Scalping Tool[BullByte]Overview 
The  Ultimate Scalping Tool  is an open-source TradingView indicator built for scalpers and short-term traders released under the Mozilla Public License 2.0. It uses a custom  Quantum Flux Candle (QFC)  oscillator to combine multiple market forces into one visual signal. In plain terms, the script reads  momentum, trend strength, volatility, and volume  together and plots a special  “candlestick”  each bar (the QFC) that reflects the overall market bias. This unified view makes it easier to spot entries and exits: the tool labels signals as  Strong Buy/Sell, Pullback (a brief retracement in a trend), Early Entry, or Exit Warning . It also provides color-coded alerts and a small dashboard of metrics. In practice, traders see green/red oscillator bars and symbols on the chart when conditions align, helping them scalp or trend-follow without reading multiple separate indicators.
 Core Components 
 Quantum Flux Candle (QFC) Construction 
The QFC is the heart of the indicator. Rather than using raw price, it creates a candlestick-like bar from the underlying oscillator values.  Each QFC bar has an “open,” “high/low,” and “close” derived from calculated momentum and volatility inputs for that period . In effect, this turns the oscillator into intuitive candle patterns so traders can recognize momentum shifts visually. (For comparison, note that Heikin-Ashi candles “have a smoother look because   take an average of the movement”. The QFC instead represents exact oscillator readings, so it reflects true momentum changes without hiding price action.) Colors of QFC bars change dynamically (e.g. green for bullish momentum, red for bearish) to highlight shifts.  This is the first open-source QFC oscillator that dynamically weights four non-correlated indicators with moving thresholds, which makes it a unique indicator on its own. 
 Oscillator Normalization & Adaptive Weights 
The script normalizes its oscillator to a fixed scale (for example, a 0–100 range much like the RSI) so that various inputs can be compared fairly. It then applies adaptive weighting: the relative influence of trend, momentum, volatility or volume signals is automatically adjusted based on current market conditions. For instance, in very volatile markets the script might weight volatility more heavily, or in a strong trend it might give extra weight to trend direction.  Normalizing data and adjusting weights helps keep the QFC sensitive but stable (normalization ensures all inputs fit a common scale). 
 Trend/Momentum/Volume/Volatility Fusion 
Unlike a typical single-factor oscillator, the QFC oscillator fuses four aspects at once. It may compute, for example,  a trend indicator (such as an ADX or moving average slope), a momentum measure (like RSI or Rate-of-Change), a volume-based pressure (similar to MFI/OBV), and a volatility measure (like ATR) . These different values are combined into one composite oscillator. This “multi-dimensional” approach follows best practices of using non-correlated indicators (trend, momentum, volume, volatility) for confirmation. By encoding all these signals in one line, a high QFC reading means that trend, momentum, and volume are all aligned, whereas a neutral reading might mean mixed conditions. This gives traders a comprehensive picture of market strength.
 Signal Classification 
The script interprets the QFC oscillator to label trades. For example:
• Strong Buy/Sell : Triggered when the oscillator crosses a high-confidence threshold (e.g. breaks clearly above zero with strong slope), indicating a well-confirmed move. This is like seeing a big green/red QFC candle aligned with the trend.
• Pullbacks : Identified when the trend is up but momentum dips briefly. A Pullback Buy appears if the overall trend is bullish but the oscillator has a short retracement – a typical buying opportunity in an uptrend. (A pullback is “a brief decline or pause in a generally upward price trend”.)
• Early Buy/Sell : Marks an initial swing in the oscillator suggesting a possible new trend, before it is fully confirmed. It’s a hint of momentum building (an early-warning signal), not as strong as the confirmed “Strong” signal.
• Exit Warnings : Issued when momentum peaks or reverses. For instance, if the QFC bars reach a high and start turning red/green opposite, the indicator warns that the move may be ending. In other words, a Momentum Peak is the point of maximum strength after which weakness may follow.
These categories correspond to typical trading concepts: Pullback (temporary reversal in an uptrend), Early Buy (an initial bullish cross), Strong Buy (confirmed bullish momentum), and Momentum Peak (peak oscillator value suggesting exhaustion).
 Filters (DI Reversal, Dynamic Thresholds, HTF EMA/ADX) 
Extra filters help avoid bad trades.  A DI Reversal filter uses the +DI/–DI lines (from the ADX system) to require that the trend direction confirms the signal . For example, it might ignore a buy signal if the +DI is still below –DI. Dynamic Thresholds adjust signal levels on-the-fly: rather than fixed “overbought” lines, they move with volatility so signals happen under appropriate market stress. An optional High-Timeframe EMA or ADX filter adds a check against a larger timeframe trend: for instance, only taking a trade if price is above the weekly EMA or if weekly ADX shows a strong trend. (Notably, the ADX is “a technical indicator used by traders to determine the strength of a price trend”, so requiring a high-timeframe ADX avoids trading against the bigger trend.)
 Dashboard Metrics & Color Logic 
 
The  Dashboard  in the  Ultimate Scalping Tool (UST)  serves as a centralized information hub, providing traders with real-time insights into market conditions, trend strength, momentum, volume pressure, and trade signals. It is highly customizable, allowing users to adjust its appearance and content based on their preferences.  
 1. Dashboard Layout & Customization   
 Short vs. Extended Mode : Users can toggle between a  compact view  (9 rows) and an  extended view  (13 rows) via the `Short Dashboard` input.  
 Text Size Options : The dashboard supports three text sizes— Tiny, Small, and Normal —adjustable via the `Dashboard Text Size` input.  
 Positioning : The dashboard is positioned in the  top-right corner  by default but can be moved if modified in the script.  
 2. Key Metrics Displayed   
The dashboard presents critical trading metrics in a structured table format:  
 Trend (TF) : Indicates the current trend direction (Strong Bullish, Moderate Bullish, Sideways, Moderate Bearish, Strong Bearish) based on  normalized trend strength (normTrend) .  
 Momentum (TF) : Displays momentum status (Strong Bullish/Bearish or Neutral) derived from the  oscillator's position relative to dynamic thresholds.   
 Volume (CMF) : Shows buying/selling pressure levels (Very High Buying, High Selling, Neutral, etc.) based on the  Chaikin Money Flow (CMF) indicator.   
 Basic & Advanced Signals:   
 Basic Signal : Provides simple trade signals (Strong Buy, Strong Sell, Pullback Buy, Pullback Sell, No Trade).  
 Advanced Signal : Offers nuanced signals (Early Buy/Sell, Momentum Peak, Weakening Momentum, etc.) with color-coded alerts.  
 RSI : Displays the Relative Strength Index (RSI) value, colored based on overbought (>70), oversold (<30), or neutral conditions.  
 HTF Filter : Indicates the  higher timeframe trend status  (Bullish, Bearish, Neutral) when using the Leading HTF Filter.  
 VWAP : Shows the V olume-Weighted Average Price  and whether the current price is above (bullish) or below (bearish) it.  
 ADX : Displays the  Average Directional Index (ADX)  value, with color highlighting whether it is rising (green) or falling (red).  
 Market Mode : Shows the selected  market type (Crypto, Stocks, Options, Forex, Custom).   
 Regime : Indicates volatility conditions (High, Low, Moderate) based on the **ATR ratio**.  
 3. Filters Status Panel 
A secondary panel displays the  status of active filters,  helping traders quickly assess which conditions are influencing signals:  
-  DI Reversal Filter:  On/Off (confirms reversals before generating signals).  
-  Dynamic Thresholds:  On/Off (adjusts buy/sell thresholds based on volatility).  
-  Adaptive Weighting:  On/Off (auto-adjusts oscillator weights for trend/momentum/volatility).  
-  Early Signal:  On/Off (enables early momentum-based signals).  
-  Leading HTF Filter:  On/Off (applies higher timeframe trend confirmation).  
 4. Visual Enhancements   
 Color-Coded Cells : Each metric is color-coded (green for bullish, red for bearish, gray for neutral) for quick interpretation.  
 Dynamic Background : The dashboard background adapts to market conditions (bullish/bearish/neutral) based on ADX and DI trends.  
 Customizable Reference Lines : Users can enable/disable fixed reference lines for the oscillator.  
 How It(QFC) Differs from Traditional Indicators 
 Quantum Flux Candle (QFC) Versus Heikin-Ashi 
Heikin-Ashi candles smooth price by averaging (HA’s open/close use averages) so they show trend clearly but hide true price (the current HA bar’s close is not the real price).  QFC candles are different: they are oscillator values, not price averages . A Heikin-Ashi chart “has a smoother look because it is essentially taking an average of the movement”, which can cause lag. The QFC instead shows the raw combined momentum each bar, allowing faster recognition of shifts. In short, HA is a smoothed price chart; QFC is a momentum-based chart.
 Versus Standard Oscillators 
Common oscillators like RSI or MACD use fixed formulas on price (or price+volume). For example, RSI “compares gains and losses and normalizes this value on a scale from 0 to 100”, reflecting pure price momentum. MFI is similar but adds volume. These indicators each show one dimension: momentum or volume. The Ultimate Scalping Tool’s QFC goes further by integrating trend strength and volatility too. In practice, this means a move that looks strong on RSI might be downplayed by low volume or weak trend in QFC. As one source notes, using multiple non-correlated indicators (trend, momentum, volume, volatility) provides a more complete market picture.  The QFC’s multi-factor fusion is unique – it is effectively a multi-dimensional oscillator rather than a traditional single-input one. 
 Signal Style 
Traditional oscillators often use crossovers (RSI crossing 50) or fixed zones (MACD above zero) for signals. The Ultimate Scalping Tool’s signals are custom-classified: it explicitly labels pullbacks, early entries, and strong moves. These terms go beyond a typical indicator’s generic “buy”/“sell.” In other words, it packages a strategy around the oscillator, which traders can backtest or observe without reading code.
 Key Term Definitions 
• Pullback : A short-term dip or consolidation in an uptrend. In this script, a Pullback Buy appears when price is generally rising but shows a brief retracement. (As defined by Investopedia, a pullback is “a brief decline or pause in a generally upward price trend”.)
• Early Buy/Sell : An initial or tentative entry signal. It means the oscillator first starts turning positive (or negative) before a full trend has developed. It’s an early indication that a trend might be starting.
• Strong Buy/Sell : A confident entry signal when multiple conditions align. This label is used when momentum is already strong and confirmed by trend/volume filters, offering a higher-probability trade.
• Momentum Peak : The point where bullish (or bearish) momentum reaches its maximum before weakening. When the oscillator value stops rising (or falling) and begins to reverse, the script flags it as a peak – signaling that the current move could be overextended.
 What is the Flux MA? 
 The Flux MA (Moving Average) is an Exponential Moving Average (EMA) applied to a normalized oscillator, referred to as FM . Its purpose is to smooth out the fluctuations of the oscillator, providing a clearer picture of the underlying trend direction and strength. Think of it as a dynamic baseline that the oscillator moves above or below, helping you determine whether the market is trending bullish or bearish.
 How it’s calculated (Flux MA): 
1.The oscillator is normalized (scaled to a range, typically between 0 and 1, using a default scale factor of 100.0).
2.An EMA is applied to this normalized value (FM) over a user-defined period (default is 10 periods).
3.The result is rescaled back to the oscillator’s original range for plotting.
 Why it matters : The Flux MA acts like a support or resistance level for the oscillator, making it easier to spot trend shifts.
 Color of the Flux Candle 
The Quantum Flux Candle visualizes the normalized oscillator (FM) as candlesticks, with colors that indicate specific market conditions based on the relationship between the FM and the Flux MA. Here’s what each color means:
• Green : The FM is above the Flux MA, signaling bullish momentum. This suggests the market is trending upward.
• Red : The FM is below the Flux MA, signaling bearish momentum. This suggests the market is trending downward.
• Yellow : Indicates strong buy conditions (e.g., a "Strong Buy" signal combined with a positive trend). This is a high-confidence signal to go long.
• Purple : Indicates strong sell conditions (e.g., a "Strong Sell" signal combined with a negative trend). This is a high-confidence signal to go short.
The candle mode shows the oscillator’s open, high, low, and close values for each period, similar to price candlesticks, but it’s the color that provides the quick visual cue for trading decisions.
 How to Trade the Flux MA with Respect to the Candle 
Trading with the Flux MA and Quantum Flux Candle involves using the MA as a trend indicator and the candle colors as entry and exit signals. Here’s a step-by-step guide:
1.  Identify the Trend Direction 
• Bullish Trend : The Flux Candle is green and positioned above the Flux MA. This indicates upward momentum.
• Bearish Trend : The Flux Candle is red and positioned below the Flux MA. This indicates downward momentum.
The Flux MA serves as the reference line—candles above it suggest buying pressure, while candles below it suggest selling pressure.
2.  Interpret Candle Colors for Trade Signals 
• Green Candle : General bullish momentum. Consider entering or holding a long position.
• Red Candle : General bearish momentum. Consider entering or holding a short position.
• Yellow Candle : A strong buy signal. This is an ideal time to enter a long trade.
• Purple Candle : A strong sell signal. This is an ideal time to enter a short trade.
3.  Enter Trades Based on Crossovers and Colors 
• Long Entry : Enter a buy position when the Flux Candle turns green and crosses above the Flux MA. If it turns yellow, this is an even stronger signal to go long.
• Short Entry : Enter a sell position when the Flux Candle turns red and crosses below the Flux MA. If it turns purple, this is an even stronger signal to go short.
4. Exit Trades 
• Exit Long : Close your buy position when the Flux Candle turns red or crosses below the Flux MA, indicating the bullish trend may be reversing.
• Exit Short : Close your sell position when the Flux Candle turns green or crosses above the Flux MA, indicating the bearish trend may be reversing.
•You might also exit a long trade if the candle changes from yellow to green (weakening strong buy signal) or a short trade from purple to red (weakening strong sell signal).
5.  Use Additional Confirmation 
To avoid false signals, combine the Flux MA and candle signals with other indicators or dashboard metrics (e.g., trend strength, momentum, or volume pressure). For example:
•A yellow candle with a " Strong Bullish " trend and high buying volume is a robust long signal.
•A red candle with a " Moderate Bearish " trend and neutral momentum might need more confirmation before shorting.
 Practical Example 
Imagine you’re scalping a cryptocurrency:
• Long Trade : The Flux Candle turns yellow and is above the Flux MA, with the dashboard showing "Strong Buy" and high buying volume. You enter a long position. You exit when the candle turns red and dips below the Flux MA.
• Short Trade : The Flux Candle turns purple and crosses below the Flux MA, with a "Strong Sell" signal on the dashboard. You enter a short position. You exit when the candle turns green and crosses above the Flux MA.
 Market Presets and Adaptation 
This indicator is designed to work on any market with candlestick price data (stocks, crypto, forex, indices, etc.). To handle different behavior, it provides presets for major asset classes.  Selecting a “Stocks,” “Crypto,” “Forex,” or “Options” preset automatically loads a set of parameter values optimized for that market . For example, a crypto preset might use a shorter lookback or higher sensitivity to account for crypto’s high volatility, while a stocks preset might use slightly longer smoothing since stocks often trend more slowly. In practice, this means the same core QFC logic applies across markets, but the thresholds and smoothing adjust so signals remain relevant for each asset type.
 Usage Guidelines 
• Recommended Timeframes : Optimized for 1 minute to 15 minute intraday charts. Can also be used on higher timeframes for short term swings.
• Market Types : Select “Crypto,” “Stocks,” “Forex,” or “Options” to auto tune periods, thresholds and weights. Use “Custom” to manually adjust all inputs.
• Interpreting Signals : Always confirm a signal by checking that trend, volume, and VWAP agree on the dashboard. A green “Strong Buy” arrow with green trend, green volume, and price > VWAP is highest probability.
• Adjusting Sensitivity : To reduce false signals in fast markets, enable DI Reversal Confirmation and Dynamic Thresholds. For more frequent entries in trending environments, enable Early Entry Trigger.
• Risk Management : This tool does not plot stop loss or take profit levels. Users should define their own risk parameters based on support/resistance or volatility bands.
 Background Shading 
To give you an at-a-glance sense of market regime without reading numbers, the indicator automatically tints the chart background in three modes—neutral, bullish and bearish—with two levels of intensity (light vs. dark):
 Neutral (Gray) 
When ADX is below 20 the market is considered “no trend” or too weak to trade. The background fills with a light gray (high transparency) so you know to sit on your hands.
 Bullish (Green) 
As soon as ADX rises above 20 and +DI exceeds –DI, the background turns a semi-transparent green, signaling an emerging uptrend. When ADX climbs above 30 (strong trend), the green becomes more opaque—reminding you that trend-following signals (Strong Buy, Pullback) carry extra weight.
 Bearish (Red) 
Similarly, if –DI exceeds +DI with ADX >20, you get a light red tint for a developing downtrend, and a darker, more solid red once ADX surpasses 30.
By dynamically varying both hue (green vs. red vs. gray) and opacity (light vs. dark), the background instantly communicates trend strength and direction—so you always know whether to favor breakout-style entries (in a strong trend) or stay flat during choppy, low-ADX conditions.
 The setup shown in the above chart snapshot is BTCUSD 15 min chart : Binance for reference. 
 Disclaimer 
No indicator guarantees profits. Backtest or paper trade this tool to understand its behavior in your market. Always use proper position sizing and stop loss orders.
Good luck!
- BullByte 
Cointegration Heatmap & Spread Table [EdgeTerminal]The  Cointegration Heatmap  is a powerful visual and quantitative tool designed to uncover deep, statistically meaningful relationships between assets. 
Unlike traditional indicators that react to price movement, this tool analyzes the underlying statistical relationship between two time series and tracks when they diverge from their long-term equilibrium — offering actionable signals for  mean-reversion trades .
 What Is Cointegration? 
Most traders are familiar with correlation, which measures how two assets move together in the short term. But correlation is shallow — it doesn’t imply a stable or predictable relationship over time.
Cointegration, however, is a deeper statistical concept: Two assets are cointegrated  if a linear combination of their prices or returns is stationary , even if the individual series themselves are non-stationary.
Cointegration is a foundational concept in time series analysis, widely used by hedge funds, proprietary trading firms, and quantitative researchers. This indicator brings that institutional-grade concept into an easy-to-use and fully visual TradingView indicator.
This tool helps answer key questions like:
“Which stocks tend to move in sync over the long term?”
“When are two assets diverging beyond statistical norms?”
“Is now the right time to short one and long the other?”
Using a combination of regression analysis, residual modeling, and Z-score evaluation, this indicator surfaces opportunities where price relationships are stretched and likely to snap back — making it ideal for building low-risk, high-probability trade setups.
In simple terms:
Cointegrated assets drift apart temporarily, but always come back together over time. This behavior is the foundation of successful pairs trading.
 How the Indicator Works 
Cointegration Heatmap indicator works across any market supported on TradingView — from stocks and ETFs to cryptocurrencies and forex pairs.
You enter your list of symbols, choose a timeframe, and the indicator updates every bar with live cointegration scores, spread signals, and trade-ready insights.
 Indicator Settings: 
 Symbol list:  a customizable list of symbols separated by commas
 Returns timeframe:  time frame selection for return sampling (Weekly or Monthly)
 Max periods:  max periods to limit the data to a certain time and to control indicator performance
This indicator accomplishes three major goals in one streamlined package:
Identifies stable long-term relationships (cointegration) between assets, using a heatmap visualization.
Tracks the spread — the difference between actual prices and the predicted linear relationship — between each pair.
Generates trade signals based on Z-score deviations from the mean spread, helping traders know when a pair is statistically overextended and likely to mean revert.
 The math: 
Returns are calculated using spread tickers to ensure alignment in time and adjust for dividends, splits, and other inconsistencies.
For each unique pair of symbols, we perform a linear regression
Yt=α+βXt+ε
Then we compute the residuals (errors from the regression):
Spreadt=Yt−(α+βXt)
Calculate the standard deviation of the spread over a moving window (default: 100 samples) and finally, define the Cointegration Score:
S=1/Standard Deviation of Residuals
 This means, the lower the deviation, the tighter the relationship, so higher scores indicate stronger cointegration.
 
Always remember that cointegration can break down so  monitor the asset over time  and over multiple different timeframes before making a decision.
 How to use the indicator 
 The heatmap table: 
The indicator displays 2 very important tables, one in the middle and one on the right side. After entering your symbols, the first table to pay attention to is the middle heatmap table. 
Any assets with a cointegration value of 25% is something to pay attention to and have a strong and stable relationship. Anything below is weak and not tradable.
Additionally, the 40% level is another important line to cross. Assets that have a cointegration score of over 40% will most likely have an extremely strong relationship.
Think about it this way, the higher the percentage, the tighter and more statistically reliable the relationship is.
 The spread table: 
After finding a good asset pair using heatmap, locate the same pair in the spread table (right side).
Here’s what you’ll see on the table:
 Spread:  Current difference between the two symbols based on the regression fit
 Mean:  Historical average of that spread
 Z-score:  How far current spread is from the mean in standard deviations
 Signal:  Trade suggestion: Short, Long, or Neutral
Since you’re expecting mean reversion, the idea is that the spread will return to the average. You want to take a trade when the z-score is either over +2 or below -2 and exit when z-score returns to near 0.
You will usually see the trade suggestion on the spread chart but you can make your own decision based on your risk level.
Keep in mind that the Z-score for each pair refers to how off the first asset is from the mean compared to the second one, so for example if you see STOCKA vs STOCKB with a Z-score of -1.55, we are regressing STOCKB (Y) on STOCKA (X).
In this case, STOCKB is the quoted asset and STOCKA is the base asset. 
In this case, this means that STOCKB is much lower than expected relative to STOCKA, so the trade would be a long position on stock B and short position on stock A.
Why EMA Isn't What You Think It IsMany new traders adopt the Exponential Moving Average (EMA) believing it's simply a "better Simple Moving Average (SMA)". This common misconception leads to fundamental misunderstandings about how EMA works and when to use it.
EMA and SMA differ at their core. SMA use a window of finite number of data points, giving equal weight to each data point in the calculation period. This makes SMA a Finite Impulse Response (FIR) filter in signal processing terms. Remember that FIR means that "all that we need is the 'period' number of data points" to calculate the filter value. Anything beyond the given period is not relevant to FIR filters – much like how a security camera with 14-day storage automatically overwrites older footage, making last month's activity completely invisible regardless of how important it might have been.
EMA, however, is an Infinite Impulse Response (IIR) filter. It uses ALL historical data, with each past price having a diminishing - but never zero - influence on the calculated value. This creates an EMA response that extends infinitely into the past—not just for the last N periods. IIR filters cannot be precise if we give them only a 'period' number of data to work on - they will be off-target significantly due to lack of context, like trying to understand Game of Thrones by watching only the final season and wondering why everyone's so upset about that dragon lady going full pyromaniac.
If we only consider a number of data points equal to the EMA's period, we are capturing no more than  86.5%  of the total weight of the EMA calculation. Relying on he period window alone (the warm-up period) will provide only 1 - (1 / e^2) weights, which is approximately 1−0.1353 = 0.8647 = 86.5%. That's like claiming you've read a book when you've skipped the first few chapters – technically, you got most of it, but you probably miss some crucial early context.
▶️  What is period in EMA used for? 
What does a period parameter really mean for EMA? When we select a 15-period EMA, we're not selecting a window of 15 data points as with an SMA. Instead, we are using that number to calculate a decay factor (α) that determines how quickly older data loses influence in EMA result. Every trader knows EMA calculation: α = 1 / (1+period) – or at least every trader claims to know this while secretly checking the formula when they need it.
Thinking in terms of "period" seriously restricts EMA. The α parameter can be - should be! - any value between 0.0 and 1.0, offering infinite tuning possibilities of the indicator. When we limit ourselves to whole-number periods that we use in FIR indicators, we can only access a small subset of possible IIR calculations – it's like having access to the entire RGB color spectrum with 16.7 million possible colors but stubbornly sticking to the 8 basic crayons in a child's first art set because the coloring book only mentioned those by name.
For example:
 
  Period 10 → alpha = 0.1818
  Period 11 → alpha = 0.1667
 
What about wanting an alpha of 0.17, which might yield superior returns in your strategy that uses EMA? No whole-number period can provide this! Direct α parameterization offers more precision, much like how an analog tuner lets you find the perfect radio frequency while digital presets force you to choose only from predetermined stations, potentially missing the clearest signal sitting right between channels.
 Sidenote: the choice of α = 1 / (1+period) is just a convention from 1970s, probably started by J. Welles Wilder, who popularized the use of the 14-day EMA. It was designed to create an approximate equivalence between EMA and SMA over the same number of periods, even thought SMA needs a period window (as it is FIR filter) and EMA doesn't. In reality, the decay factor α in EMA should be allowed any valye between 0.0 and 1.0, not just some discrete values derived from an integer-based period! Algorithmic systems should find the best α decay for EMA directly, allowing the system to fine-tune at will and not through conversion of integer period to float α decay – though this might put a few traditionalist traders into early retirement. Well, to prevent that, most traditionalist implementations of EMA only use period and no alpha at all. Heaven forbid we disturb people who print their charts on paper, draw trendlines with rulers, and insist the market "feels different" since computers do algotrading! 
▶️  Calculating EMAs Efficiently 
The standard textbook formula for EMA is:
 
EMA = CurrentPrice × alpha + PreviousEMA × (1 - alpha)
 
But did you know that a more efficient version exists, once you apply a tiny bit of high school algebra:
 
EMA = alpha × (CurrentPrice - PreviousEMA) + PreviousEMA
 
The first one requires three operations: 2 multiplications + 1 addition. The second one also requires three ops: 1 multiplication + 1 addition + 1 subtraction.
That's pathetic, you say? Not worth implementing? In most computational models, multiplications cost much more than additions/subtractions – much like how ordering dessert costs more than asking for a water refill at restaurants.
 Relative CPU cost of float operations :
 
  Addition/Subtraction: ~1 cycle
  Multiplication: ~5 cycles (depending on precision and architecture)
 
Now you see the difference? 2 * 5 + 1 = 11 against 5 + 1 + 1 = 7. That is ≈ 36.36% efficiency gain just by swapping formulas around! And making your high school math teacher proud enough to finally put your test on the refrigerator.
▶️  The Warmup Problem: how to start the EMA sequence right 
How do we calculate the first EMA value when there's no previous EMA available? Let's see some possible options used throughout the history:
 
   Start with zero : EMA(0) = 0. This creates stupidly large distortion until enough bars pass for the horrible effect to diminish – like starting a trading account with zero balance but backdating a year of missed trades, then watching your balance struggle to climb out of a phantom debt for months.
   Start with first price : EMA(0) = first price. This is better than starting with zero, but still causes initial distortion that will be extra-bad if the first price is an outlier – like forming your entire opinion of a stock based solely on its IPO day price, then wondering why your model is tanking for weeks afterward.
   Use SMA for warmup : This is the tradition from the pencil-and-paper era of technical analysis – when calculators were luxury items and "algorithmic trading" meant your broker had neat handwriting. We first calculate an SMA over the initial period, then kickstart the EMA with this average value. It's widely used due to tradition, not merit, creating a mathematical Frankenstein that uses an FIR filter (SMA) during the initial period before abruptly switching to an IIR filter (EMA). This methodology is so aesthetically offensive (abrupt kink on the transition from SMA to EMA) that charting platforms hide these early values entirely, pretending EMA simply doesn't exist until the warmup period passes – the technical analysis equivalent of sweeping dust under the rug.
   Use WMA for warmup : This one was never popular because it is harder to calculate with a pencil - compared to using simple SMA for warmup. Weighted Moving Average provides a much better approximation of a starting value as its linear descending profile is much closer to the EMA's decay profile.
 
These methods all share one problem: they produce inaccurate initial values that traders often hide or discard, much like how hedge funds conveniently report awesome performance "since strategy inception" only after their disastrous first quarter has been surgically removed from the track record.
▶️  A Better Way to start EMA: Decaying compensation 
Think of it this way: An ideal EMA uses an infinite history of prices, but we only have data starting from a specific point. This creates a problem - our EMA starts with an incorrect assumption that all previous prices were all zero, all close, or all average – like trying to write someone's biography but only having information about their life since last Tuesday.
But there is a better way. It requires more than high school math comprehension and is more computationally intensive, but is mathematically correct and numerically stable. This approach involves compensating calculated EMA values for the "phantom data" that would have existed before our first price point.
Here's how phantom data compensation works:
 
  We start our normal EMA calculation:
 
EMA_today = EMA_yesterday + α × (Price_today - EMA_yesterday)
 
  But we add a correction factor that adjusts for the missing history:
 
Correction = 1 at the start
Correction = Correction × (1-α) after each calculation
 
  We then apply this correction:
 
True_EMA = Raw_EMA / (1-Correction)
 
 
This correction factor starts at 1 (full compensation effect) and gets exponentially smaller with each new price bar. After enough data points, the correction becomes so small (i.e., below 0.0000000001) that we can stop applying it as it is no longer relevant.
Let's see how this works in practice:
 
  For the first price bar:
Raw_EMA = 0
Correction = 1
True_EMA = Price (since 0 ÷ (1-1) is undefined, we use the first price)
  For the second price bar:
Raw_EMA = α × (Price_2 - 0) + 0 = α × Price_2
Correction = 1 × (1-α) = (1-α)
True_EMA = α × Price_2 ÷ (1-(1-α)) = Price_2
  For the third price bar:
Raw_EMA updates using the standard formula
Correction = (1-α) × (1-α) = (1-α)²
True_EMA = Raw_EMA ÷ (1-(1-α)²)
 
With each new price, the correction factor shrinks exponentially. After about -log₁₀(1e-10)/log₁₀(1-α) bars, the correction becomes negligible, and our EMA calculation matches what we would get if we had infinite historical data.
This approach provides accurate EMA values from the very first calculation. There's no need to use SMA for warmup or discard early values before output converges - EMA is mathematically correct from first value, ready to party without the awkward warmup phase.
Here is Pine Script 6 implementation of EMA that can take alpha parameter directly (or period if desired), returns valid values from the start, is resilient to dirty input values, uses decaying compensator instead of SMA, and uses the least amount of computational cycles possible.
 
// Enhanced EMA function with proper initialization and efficient calculation
ema(series float source, simple int period=0, simple float alpha=0)=>
// Input validation - one of alpha or period must be provided
if alpha<=0 and period<=0
runtime.error("Alpha or period must be provided")
// Calculate alpha from period if alpha not directly specified
float a = alpha > 0 ? alpha : 2.0 / math.max(period, 1)
// Initialize variables for EMA calculation
var float ema = na      // Stores raw EMA value
var float result = na   // Stores final corrected EMA
var float e = 1.0       // Decay compensation factor
var bool warmup = true  // Flag for warmup phase
if not na(source)
    if na(ema)
        // First value case - initialize EMA to zero
        // (we'll correct this immediately with the compensation)
        ema := 0
        result := source
    else
        // Standard EMA calculation (optimized formula)
        ema := a * (source - ema) + ema
        
        if warmup
            // During warmup phase, apply decay compensation
            e *= (1-a)                  // Update decay factor
            float c = 1.0 / (1.0 - e)   // Calculate correction multiplier
            result := c * ema           // Apply correction
            
            // Stop warmup phase when correction becomes negligible
            if e <= 1e-10
                warmup := false
        else
            // After warmup, EMA operates without correction
            result := ema
result  // Return the properly compensated EMA value
 
▶️  CONCLUSION 
EMA isn't just a "better SMA"—it is a fundamentally different tool, like how a submarine differs from a sailboat – both float, but the similarities end there. EMA responds to inputs differently, weighs historical data differently, and requires different initialization techniques.
By understanding these differences, traders can make more informed decisions about when and how to use EMA in trading strategies. And as EMA is embedded in so many other complex and compound indicators and strategies, if system uses tainted and inferior EMA calculatiomn, it is doing a disservice to all derivative indicators too – like building a skyscraper on a foundation of Jell-O.
The next time you add an EMA to your chart, remember: you're not just looking at a "faster moving average." You're using an INFINITE IMPULSE RESPONSE filter that carries the echo of all previous price actions, properly weighted to help make better trading decisions.
EMA done right might significantly improve the quality of all signals, strategies, and trades that rely on EMA somewhere deep in its algorithmic bowels – proving once again that math skills are indeed useful after high school, no matter what your guidance counselor told you.
Quarterly Theory ICT 05 [TradingFinder] Doubling Theory Signals🔵 Introduction 
Doubling Theory is an advanced approach to price action and market structure analysis that uniquely combines time-based analysis with key Smart Money concepts such as SMT (Smart Money Technique), SSMT (Sequential SMT), Liquidity Sweep, and the Quarterly Theory ICT. 
By leveraging fractal time structures and precisely identifying liquidity zones, this method aims to reveal institutional activity specifically smart money entry and exit points hidden within price movements.
At its core, the market is divided into two structural phases: Doubling 1 and Doubling 2. Each phase contains four quarters (Q1 through Q4), which follow the logic of the Quarterly Theory: Accumulation, Manipulation (Judas Swing), Distribution, and Continuation/Reversal. 
These segments are anchored by the True Open, allowing for precise alignment with cyclical market behavior and providing a deeper structural interpretation of price action.
During Doubling 1, a Sequential SMT (SSMT) Divergence typically forms between two correlated assets. This time-structured divergence occurs between two swing points positioned in separate quarters (e.g., Q1 and Q2), where one asset breaks a significant low or high, while the second asset fails to confirm it. This lack of confirmation—especially when aligned with the Manipulation and Accumulation phases—often signals early smart money involvement.
Following this, the highest and lowest price points from Doubling 1 are designated as liquidity zones. As the market transitions into Doubling 2, it commonly returns to these zones in a calculated move known as a Liquidity Sweep—a sharp, engineered spike intended to trigger stop orders and pending positions. This sweep, often orchestrated by institutional players, facilitates entry into large positions with minimal slippage.
 Bullish :
  
 Bearish :
  
🔵 How to Use 
Applying Doubling Theory requires a simultaneous understanding of temporal structure and inter-asset behavioral divergence. The method unfolds over two main phases—Doubling 1 and Doubling 2—each divided into four quarters (Q1 to Q4). 
The first phase focuses on identifying a Sequential SMT (SSMT) divergence, which forms when two correlated assets (e.g., EURUSD and GBPUSD, or NQ and ES) react differently to key price levels across distinct quarters. For example, one asset may break a previous low while the other maintains structure. This misalignment—especially in Q2, the Manipulation phase—often indicates early smart money accumulation or distribution.
Once this divergence is observed, the extreme highs and lows of Doubling 1 are marked as liquidity zones. In Doubling 2, the market gravitates back toward these zones, executing a Liquidity Sweep. 
This move is deliberate—designed to activate clustered stop-loss and pending orders and to exploit pockets of resting liquidity. These sweeps are typically driven by institutional forces looking to absorb liquidity and position themselves ahead of the next major price move.
The key to execution lies in the fact that, during the sweep in Doubling 2, a classic SMT divergence should also appear between the two assets. This indicates a weakening of the previous trend and adds an extra layer of confirmation.
🟣 Bullish Doubling Theory 
In the bullish scenario, Doubling 1 begins with a bullish SSMT divergence, where one asset forms a lower low while the other maintains its structure. This divergence signals weakening bearish momentum and possible smart money accumulation. In Doubling 2, the market returns to the previous low and sweeps the liquidity zone—breaking below it on one asset, while the second fails to confirm, forming a bullish SMT divergence.
 f this move is followed by a bullish PSP and a clear market structure break (MSB), a long entry is triggered. The stop-loss is placed just below the swept liquidity zone, while the target is set in the premium zone, anticipating a move driven by institutional buyers.
  
🟣 Bearish Doubling Theory 
The bearish scenario follows the same structure in reverse. In Doubling 1, a bearish SSMT divergence occurs when one asset prints a higher high while the other fails to do so. This suggests distribution and weakening buying pressure. Then, in Doubling 2, the market returns to the previous high and executes a liquidity sweep, targeting trapped buyers. 
A bearish SMT divergence appears, confirming the move, followed by a bearish PSP on the lower timeframe. A short position is initiated after a confirmed MSB, with the stop-loss placed 
  
🔵 Settings 
⚙️ Logical Settings 
 Quarterly Cycles Type : Select the time segmentation method for SMT analysis.
 Available modes include : Yearly, Monthly, Weekly, Daily, 90 Minute, and Micro.
These define how the indicator divides market time into Q1–Q4 cycles.
 Symbol : Choose the secondary asset to compare with the main chart asset (e.g., XAUUSD, US100, GBPUSD).
 Pivot Period : Sets the sensitivity of the pivot detection algorithm. A smaller value increases responsiveness to price swings.
 Pivot Sync Threshold : The maximum allowed difference (in bars) between pivots of the two assets for them to be compared.
 Validity Pivot Length : Defines the time window (in bars) during which a divergence remains valid before it's considered outdated.
🎨 Display Settings 
 Show Cycle :Toggles the visual display of the current Quarter (Q1 to Q4) based on the selected time segmentation
 Show Cycle Label : Shows the name (e.g., "Q2") of each detected Quarter on the chart.
 Show Labels : Displays dynamic labels (e.g., “Q2”, “Bullish SMT”, “Sweep”) at relevant points.
 Show Lines : Draws connection lines between key pivot or divergence points.
 Color Settings : Allows customization of colors for bullish and bearish elements (lines, labels, and shapes)
🔔 Alert Settings 
 Alert Name : Custom name for the alert messages (used in TradingView’s alert system).
 Message Frequenc y:
 
 All : Every signal triggers an alert.
 Once Per Bar : Alerts once per bar regardless of how many signals occur.
 Per Bar Close : Only triggers when the bar closes and the signal still exists.
 
 Time Zone Display : Choose the time zone in which alert timestamps are displayed (e.g., UTC).
 Bullish SMT Divergence Alert : Enable/disable alerts specifically for bullish signals.
 Bearish SMT Divergence Alert : Enable/disable alerts specifically for bearish signals
🔵 Conclusion 
Doubling Theory is a powerful and structured framework within the realm of Smart Money Concepts and ICT methodology, enabling traders to detect high-probability reversal points with precision. By integrating SSMT, SMT, Liquidity Sweeps, and the Quarterly Theory into a unified system, this approach shifts the focus from reactive trading to anticipatory analysis—anchored in time, structure, and liquidity.
What makes Doubling Theory stand out is its logical synergy of time cycles, behavioral divergence, liquidity targeting, and institutional confirmation. In both bullish and bearish scenarios, it provides clearly defined entry and exit strategies, allowing traders to engage the market with confidence, controlled risk, and deeper insight into the mechanics of price manipulation and smart money footprints.
GIGANEVA V6.61 PublicThis enhanced Fibonacci script for TradingView is a powerful, all-in-one tool that calculates Fibonacci Levels, Fans, Time Pivots, and Golden Pivots on both logarithmic and linear scales. Its ability to compute time pivots via fan intersections and Range interactions, combined with user-friendly features like Bool Fib Right, sets it apart. The script maximizes TradingView’s plotting capabilities, making it a unique and versatile tool for technical analysis across various markets.
 1. Overview of the Script 
The script appears to be a custom technical analysis tool built for TradingView, improving upon an existing script from TradingView’s Community Scripts. It calculates and plots:
 Fibonacci Levels:  Standard retracement levels (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range.
 Fibonacci Fans:  Trendlines drawn from a high or low point, radiating at Fibonacci ratios to project potential support/resistance zones.
 Time Pivots:  Points in time where significant price action is expected, determined by the intersection of Fibonacci Fans or their interaction with key price levels.
 Golden Pivots:  Specific time pivots calculated when the 0.5 Fibonacci Fan (on a logarithmic or linear scale) intersects with its counterpart.
The script supports both logarithmic and linear price scales, ensuring versatility across different charting preferences. It also includes a feature to extend Fibonacci Fans to the right, regardless of whether the user selects the top or bottom of the range first.
 2. Key Components Explained 
 a) Fibonacci Levels and Fans from Top and Bottom of the "Range" 
 Fibonacci Levels:  These are horizontal lines plotted at standard Fibonacci retracement ratios (e.g., 0.236, 0.382, 0.5, 0.618, etc.) based on a user-defined price range (the "Range"). The Range is typically the distance between a significant high (top) and low (bottom) on the chart.
 Example:  If the high is $100 and the low is $50, the 0.618 retracement level would be at $80.90 ($50 + 0.618 × $50).
 
Fibonacci Fans:  These are diagonal lines drawn from either the top or bottom of the Range, radiating at Fibonacci ratios (e.g., 0.382, 0.5, 0.618). They project potential dynamic support or resistance zones as price evolves over time.
 From Top:  Fans drawn downward from the high of the Range.
From Bottom: Fans drawn upward from the low of the Range.
 Log and Linear Scale: 
 Logarithmic Scale:  Adjusts price intervals to account for percentage changes, which is useful for assets with large price ranges (e.g., cryptocurrencies or stocks with exponential growth). Fibonacci calculations on a log scale ensure ratios are proportional to percentage moves.
 Linear Scale:  Uses absolute price differences, suitable for assets with smaller, more stable price ranges.
The script’s ability to plot on both scales makes it adaptable to different markets and user preferences.
 b) Time Pivots 
Time pivots are points in time where significant price action (e.g., reversals, breakouts) is anticipated. The script calculates these in two ways:
 Fans Crossing Each Other: 
When two Fibonacci Fans (e.g., one from the top and one from the bottom) intersect, their crossing point represents a potential time pivot. This is because the intersection indicates a convergence of dynamic support/resistance zones, increasing the likelihood of a price reaction.
Example: A 0.618 fan from the top crosses a 0.382 fan from the bottom at a specific bar on the chart, marking that bar as a time pivot.
 Fans Crossing Top and Bottom of the Range: 
A fan line (e.g., 0.5 fan from the bottom) may intersect the top or bottom price level of the Range at a specific time. This intersection highlights a moment where the fan’s projected support/resistance aligns with a key price level, signaling a potential pivot.
 Example:  The 0.618 fan from the bottom reaches the top of the Range ($100) at bar 50, marking bar 50 as a time pivot.
 c) Golden Pivots 
 Definition:  Golden pivots are a special type of time pivot calculated when the 0.5 Fibonacci Fan on one scale (logarithmic or linear) intersects with the 0.5 fan on the opposite scale (or vice versa).
 Significance:  The 0.5 level is the midpoint of the Fibonacci sequence and often acts as a critical balance point in price action. When fans at this level cross, it suggests a high-probability moment for a price reversal or significant move.
 Example:  If the 0.5 fan on a logarithmic scale (drawn from the bottom) crosses the 0.5 fan on a linear scale (drawn from the top) at bar 100, this intersection is labeled a "Golden Pivot" due to its confluence of key Fibonacci levels.
 d) Bool Fib Right 
This is a user-configurable setting (a boolean input in the script) that extends Fibonacci Fans to the right side of the chart.
 Functionality:  When enabled, the fans project forward in time, regardless of whether the user selected the top or bottom of the Range first. This ensures consistency in visualization, as the direction of the Range selection (top-to-bottom or bottom-to-top) does not affect the fan’s extension.
 Use Case:  Traders can use this to project future support/resistance zones without worrying about how they defined the Range, improving usability.
 3. Why Is This Code Unique? 
Original calculation of Log levels were taken from  zekicanozkanli  code. Thank you for giving me great Foundation, later modified and applied to Fib fans. The script’s uniqueness stems from its comprehensive integration of Fibonacci-based tools and its optimization for TradingView’s plotting capabilities. Here’s a detailed breakdown:
 All-in-One Fibonacci Tool: 
Most Fibonacci scripts on TradingView focus on either retracement levels, extensions, or fans.
 This script combines: 
 Fibonacci Levels:  Static horizontal lines for retracement and extension.
 Fibonacci Fans:  Dynamic trendlines for projecting support/resistance.
 Time Pivots:  Temporal analysis based on fan intersections and Range interactions.
 Golden Pivots:  Specialized pivots based on 0.5 fan confluences.
By integrating these functions, the script provides a holistic Fibonacci analysis tool, reducing the need for multiple scripts.
 Log and Linear Scale Support: 
Many Fibonacci tools are designed for linear scales only, which can distort projections for assets with exponential price movements. By supporting both logarithmic and linear scales, the script caters to a wider range of markets (e.g., stocks, forex, crypto) and user preferences.
 Time Pivot Calculations: 
Calculating time pivots based on fan intersections and Range interactions is a novel feature. Most TradingView scripts focus on price-based Fibonacci levels, not temporal analysis. This adds a predictive element, helping traders anticipate when significant price action might occur.
 Golden Pivot Innovation: 
The concept of "Golden Pivots" (0.5 fan intersections across scales) is a unique addition. It leverages the symmetry of the 0.5 level and the differences between log and linear scales to identify high-probability pivot points.
 Maximized Plot Capabilities: 
TradingView imposes limits on the number of plots (lines, labels, etc.) a script can render. This script is coded to fully utilize these limits, ensuring that all Fibonacci levels, fans, pivots, and labels are plotted without exceeding TradingView’s constraints.
This optimization likely involves efficient use of arrays, loops, and conditional plotting to manage resources while delivering a rich visual output.
 User-Friendly Features: 
The Bool Fib Right option simplifies fan projection, making the tool intuitive even for users who may not consistently select the Range in the same order.
The script’s flexibility in handling top/bottom Range selection enhances usability.
 4. Potential Use Cases 
 Trend Analysis:  Traders can use Fibonacci Fans to identify dynamic support/resistance zones in trending markets.
 Reversal Trading:  Time pivots and Golden Pivots help pinpoint moments for potential price reversals.
 Range Trading:  Fibonacci Levels provide key price zones for trading within a defined range.
 Cross-Market Application:  Log/linear scale support makes the script suitable for stocks, forex, commodities, and cryptocurrencies.
The original code was from  zekicanozkanli . Thank you for giving me great Foundation.
RSI Forecast [Titans_Invest]RSI Forecast  
Introducing one of the most impressive RSI indicators ever created – arguably the best on TradingView, and potentially the best in the world.
RSI Forecast is a visionary evolution of the classic RSI, merging powerful customization with groundbreaking predictive capabilities. While preserving the core principles of traditional RSI, it takes analysis to the next level by allowing users to anticipate potential future RSI movements.
Real-Time RSI Forecasting:
For the first time ever, an RSI indicator integrates linear regression using the least squares method to accurately forecast the future behavior of the RSI. This innovation empowers traders to stay one step ahead of the market with forward-looking insight.
Highly Customizable:
Easily adapt the indicator to your personal trading style. Fine-tune a variety of parameters to generate signals perfectly aligned with your strategy.
Innovative, Unique, and Powerful:
This is the world’s first RSI Forecast to apply this predictive approach using least squares linear regression. A truly elite-level tool designed for traders who want a real edge in the market.
⯁  SCIENTIFIC BASIS LINEAR REGRESSION 
Linear Regression is a fundamental method of statistics and machine learning, used to model the relationship between a dependent variable y and one or more independent variables 𝑥.
The general formula for a simple linear regression is given by:
y = β₀ + β₁x + ε
Where:
y   = is the predicted variable (e.g. future value of RSI)
x   = is the explanatory variable (e.g. time or bar index)
β0 = is the intercept (value of 𝑦 when 𝑥 = 0)
𝛽1 = is the slope of the line (rate of change)
ε   = is the random error term
The goal is to estimate the coefficients 𝛽0 and 𝛽1 so as to minimize the sum of the squared errors — the so-called Random Error Method Least Squares.
⯁  LEAST SQUARES ESTIMATION 
To minimize the error between predicted and observed values, we use the following formulas:
β₁ =   /  
β₀ = ȳ - β₁x̄
Where:
∑ = sum
x̄ = mean of x
ȳ = mean of y
x_i, y_i = individual values of the variables.
Where:
x_i and y_i are the means of the independent and dependent variables, respectively.
i ranges from 1 to n, the number of observations.
These equations guarantee the best linear unbiased estimator, according to the Gauss-Markov theorem, assuming homoscedasticity and linearity.
⯁  LINEAR REGRESSION IN MACHINE LEARNING 
Linear regression is one of the cornerstones of supervised learning. Its simplicity and ability to generate accurate quantitative predictions make it essential in AI systems, predictive algorithms, time series analysis, and automated trading strategies.
By applying this model to the RSI, you are literally putting artificial intelligence at the heart of a classic indicator, bringing a new dimension to technical analysis.
⯁  VISUAL INTERPRETATION 
Imagine an RSI time series like this:
Time →    
RSI    →    
The regression line will smooth these values and extend them n periods into the future, creating a predicted trajectory based on the historical moment. This line becomes the predicted RSI, which can be crossed with the actual RSI to generate more intelligent signals.
⯁  SUMMARY OF SCIENTIFIC CONCEPTS USED 
 
 Linear Regression Models the relationship between variables using a straight line.
 Least Squares Minimizes the sum of squared errors between prediction and reality.
 Time Series Forecasting Estimates future values based on historical data.
 Supervised Learning Trains models to predict outputs from known inputs.
 Statistical Smoothing Reduces noise and reveals underlying trends.
 
⯁  WHY THIS INDICATOR IS REVOLUTIONARY 
 
 Scientifically-based: Based on statistical theory and mathematical inference.
 Unprecedented: First public RSI with least squares predictive modeling.
 Intelligent: Built with machine learning logic.
 Practical: Generates forward-thinking signals.
 Customizable: Flexible for any trading strategy.
 
⯁  CONCLUSION 
By combining RSI with linear regression, this indicator allows a trader to predict market momentum, not just follow it.
RSI Forecast   is not just an indicator — it is a scientific breakthrough in technical analysis technology.
⯁ Example of simple linear regression, which has one independent variable:
⯁ In linear regression, observations ( red ) are considered to be the result of random deviations ( green ) from an underlying relationship ( blue ) between a dependent variable ( y ) and an independent variable ( x ).
⯁ Visualizing heteroscedasticity in a scatterplot against 100 random fitted values using Matlab:
⯁ The data sets in the Anscombe's quartet are designed to have approximately the same linear regression line (as well as nearly identical means, standard deviations, and correlations) but are graphically very different. This illustrates the pitfalls of relying solely on a fitted model to understand the relationship between variables.
⯁ The result of fitting a set of data points with a quadratic function:
_______________________________________________________________________
🥇 This is the world’s first RSI indicator with: Linear Regression for Forecasting 🥇_______________________________________________________________________
_________________________________________________
🔮 Linear Regression: PineScript Technical Parameters 🔮
_________________________________________________
Forecast Types:
• Flat: Assumes prices will remain the same.
• Linreg: Makes a 'Linear Regression' forecast for n periods.
Technical Information:
ta.linreg (built-in function)
Linear regression curve. A line that best fits the specified prices over a user-defined time period. It is calculated using the least squares method. The result of this function is calculated using the formula: linreg = intercept + slope * (length - 1 - offset), where intercept and slope are the values calculated using the least squares method on the source series.
Syntax:
• Function: ta.linreg()
Parameters:
• source: Source price series.
• length: Number of bars (period).
• offset: Offset.
• return: Linear regression curve.
This function has been cleverly applied to the RSI, making it capable of projecting future values based on past statistical trends.
______________________________________________________
______________________________________________________
 ⯁ WHAT IS THE RSI❓ 
The Relative Strength Index (RSI) is a technical analysis indicator developed by J. Welles Wilder. It measures the magnitude of recent price movements to evaluate overbought or oversold conditions in a market. The RSI is an oscillator that ranges from 0 to 100 and is commonly used to identify potential reversal points, as well as the strength of a trend.
 ⯁ HOW TO USE THE RSI❓ 
The RSI is calculated based on average gains and losses over a specified period (usually 14 periods). It is plotted on a scale from 0 to 100 and includes three main zones:
  •   Overbought:  When the RSI is above 70, indicating that the asset may be overbought.
  •   Oversold:  When the RSI is below 30, indicating that the asset may be oversold.
  •   Neutral Zone:  Between 30 and 70, where there is no clear signal of overbought or oversold conditions.
______________________________________________________
______________________________________________________
 ⯁ ENTRY CONDITIONS 
The conditions below are fully flexible and allow for complete customization of the signal.
______________________________________________________
______________________________________________________
 🔹 CONDITIONS TO BUY 📈 
______________________________________________________
  •  Signal Validity: The signal will remain valid for  X bars .
  •  Signal Sequence: Configurable as  AND  or  OR .
📈 RSI Conditions:
🔹 RSI > Upper
🔹 RSI < Upper
🔹 RSI > Lower
🔹 RSI < Lower
🔹 RSI > Middle
🔹 RSI < Middle
🔹 RSI > MA
🔹 RSI < MA
📈 MA Conditions:
🔹 MA > Upper
🔹 MA < Upper
🔹 MA > Lower
🔹 MA < Lower
📈 Crossovers:
🔹 RSI (Crossover) Upper
🔹 RSI (Crossunder) Upper
🔹 RSI (Crossover) Lower
🔹 RSI (Crossunder) Lower
🔹 RSI (Crossover) Middle
🔹 RSI (Crossunder) Middle
🔹 RSI (Crossover) MA
🔹 RSI (Crossunder) MA
🔹 MA (Crossover) Upper
🔹 MA (Crossunder) Upper
🔹 MA (Crossover) Lower
🔹 MA (Crossunder) Lower
📈 RSI Divergences:
🔹 RSI Divergence Bull
🔹 RSI Divergence Bear
📈 RSI Forecast:
🔮 RSI (Crossover) MA Forecast
🔮 RSI (Crossunder) MA Forecast
______________________________________________________
______________________________________________________
 🔸 CONDITIONS TO SELL 📉 
______________________________________________________
  •  Signal Validity: The signal will remain valid for  X bars .
  •  Signal Sequence: Configurable as  AND  or  OR .
📉 RSI Conditions:
🔸 RSI > Upper
🔸 RSI < Upper
🔸 RSI > Lower
🔸 RSI < Lower
🔸 RSI > Middle
🔸 RSI < Middle
🔸 RSI > MA
🔸 RSI < MA
📉 MA Conditions:
🔸 MA > Upper
🔸 MA < Upper
🔸 MA > Lower
🔸 MA < Lower
📉 Crossovers:
🔸 RSI (Crossover) Upper
🔸 RSI (Crossunder) Upper
🔸 RSI (Crossover) Lower
🔸 RSI (Crossunder) Lower
🔸 RSI (Crossover) Middle
🔸 RSI (Crossunder) Middle
🔸 RSI (Crossover) MA
🔸 RSI (Crossunder) MA
🔸 MA (Crossover) Upper
🔸 MA (Crossunder) Upper
🔸 MA (Crossover) Lower
🔸 MA (Crossunder) Lower
📉 RSI Divergences:
🔸 RSI Divergence Bull
🔸 RSI Divergence Bear
📉 RSI Forecast:
🔮 RSI (Crossover) MA Forecast
🔮 RSI (Crossunder) MA Forecast
______________________________________________________
______________________________________________________
 🤖 AUTOMATION 🤖 
• You can automate the BUY and SELL signals of this indicator.
______________________________________________________
______________________________________________________
 ⯁ UNIQUE FEATURES 
______________________________________________________
 
 Linear Regression:  (Forecast) 
 Signal Validity: The signal will remain valid for  X bars 
 Signal Sequence: Configurable as  AND/OR 
 Condition Table: BUY/SELL
 Condition Labels: BUY/SELL
 Plot Labels in the Graph Above: BUY/SELL
 Automate and Monitor Signals/Alerts: BUY/SELL
 
 
 Linear Regression (Forecast)
 Signal Validity: The signal will remain valid for  X bars 
 Signal Sequence: Configurable as  AND/OR 
 Condition Table: BUY/SELL
 Condition Labels: BUY/SELL
 Plot Labels in the Graph Above: BUY/SELL
 Automate and Monitor Signals/Alerts: BUY/SELL
 
______________________________________________________
 📜 SCRIPT : RSI Forecast  
🎴 Art by  : @Titans_Invest & @DiFlip
👨💻 Dev by : @Titans_Invest & @DiFlip
🎑 Titans Invest — The Wizards Without Gloves 🧤
✨ Enjoy! 
______________________________________________________
 o Mission 🗺
• Inspire Traders to manifest Magic in the Market.
o Vision 𐓏
• To elevate collective Energy 𐓷𐓏
Double RSI OscillatorThe Double RSI Oscillator 
Hello Gs,
I came back from the dead and tried to see what a little tweak to RSI could do, and I think it is quite interesting and might be worth checking out.
 Warning:
This indicator has lots of false signals unfortunatly 
 How does the DRSI Oscillator work? 
Very simple, the DRSI oscillator at the very base is just 2 RSIs that should smooth each other out, making a smoother trend signal generation for trend analysis. One RSI is set to have lower values, by considering the lowest point of the price, and one RSI is set to have higher values using pretty much the same thing. The trend changes from positive to negative if RSI with higher values crosses negative treshhold, and from negative to positive if RSI with lower value crosses positive treshhold. On top of this I added some additional settings to smooth or speed it further, if these were a good idea, I guess only time will tell :D.
 Settings 
Here is a guide of what setting changes what and how it might be suitable for you:
RSI Optimism length: length of the RSI with higher values (higher values will be better for longer term, lower for medium term)
RSI Pesimism length: length of the RSI with lower values (higher values will be better for longer term, lower for medium term)
Positive treshhold: The value RSI pesimism needs to pass in order to change trends (in case of using RSI avg. the value the average needs to pass), making this higher can give you faster signals, but expect more false ones
Negative treshholds: The value RSI optimism needs to pass in order to change trends (in case of using RSI avg. the value the average needs to pass), lowering this can give you faster signals, but expect more false ones
Smoothing type: Select the type of smoothing (or none) to smooth your signals as you want, this one you need to play around with.
Smoothing length: The length of your smoothing method (if none is selected it wont change anything)
Use RSI average instead: self-explanatory, go figure
Above/Below Mean Trend: Changes the way trend logic works
 Why consider using this indicator? 
The DRSI Oscillator is a tool that has huge flexibility (due to tons of settings that base RSI doesnt, like trend treshholds), and is smoother allowing traders and investors to get high quality or high speed signals, allowing great entries and exits
Dow Theory Trend StrategyDow Theory Trend Strategy (Pine Script)
Overview
This Pine Script implements a trading strategy based on the core principles of Dow Theory. It visually identifies trends (uptrend, downtrend) by analyzing pivot highs and lows and executes trades when the trend direction changes. This script is an improved version that features refined trend determination logic and strategy implementation.
Core Concept: Dow Theory
The script uses a fundamental Dow Theory concept for trend identification:
Uptrend: Characterized by a series of Higher Highs (HH) and Higher Lows (HL).
Downtrend: Characterized by a series of Lower Highs (LH) and Lower Lows (LL).
How it Works
Pivot Point Detection:
It uses the built-in ta.pivothigh() and ta.pivotlow() functions to identify significant swing points (potential highs and lows) in the price action.
The pivotLookback input determines the number of bars to the left and right required to confirm a pivot. Note that this introduces a natural lag (equal to pivotLookback bars) before a pivot is confirmed.
Improved Trend Determination:
The script stores the last two confirmed pivot highs and the last two confirmed pivot lows.
An Uptrend (trendDirection = 1) is confirmed only when the latest pivot high is higher than the previous one (HH) AND the latest pivot low is higher than the previous one (HL).
A Downtrend (trendDirection = -1) is confirmed only when the latest pivot high is lower than the previous one (LH) AND the latest pivot low is lower than the previous one (LL).
Key Improvement: If neither a clear uptrend nor a clear downtrend is confirmed based on the latest pivots, the script maintains the previous trend state (trendDirection := trendDirection ). This differs from simpler implementations that might switch to a neutral/range state (e.g., trendDirection = 0) more frequently. This approach aims for smoother trend following, acknowledging that trends often persist through periods without immediate new HH/HL or LH/LL confirmations.
Trend Change Detection:
The script monitors changes in the trendDirection variable.
changedToUp becomes true when the trend shifts to an Uptrend (from Downtrend or initial state).
changedToDown becomes true when the trend shifts to a Downtrend (from Uptrend or initial state).
Visualizations
Background Color: The chart background is colored to reflect the currently identified trend:
Blue: Uptrend (trendDirection == 1)
Red: Downtrend (trendDirection == -1)
Gray: Initial state or undetermined (trendDirection == 0)
Pivot Points (Optional): Small triangles (shape.triangledown/shape.triangleup) can be displayed above pivot highs and below pivot lows if showPivotPoints is enabled.
Trend Change Signals (Optional): Labels ("▲ UP" / "▼ DOWN") can be displayed when a trend change is confirmed (changedToUp / changedToDown) if showTrendChange is enabled. These visually mark the potential entry points for the strategy.
Strategy Logic
Entry Conditions:
Enters a long position (strategy.long) using strategy.entry("L", ...) when changedToUp becomes true.
Enters a short position (strategy.short) using strategy.entry("S", ...) when changedToDown becomes true.
Position Management: The script uses strategy.entry(), which automatically handles position reversal. If the strategy is long and a short signal occurs, strategy.entry() will close the long position and open a new short one (and vice-versa).
Inputs
pivotLookback: The number of bars on each side to confirm a pivot high/low. Higher values mean pivots are confirmed later but may be more significant.
showPivotPoints: Toggle visibility of pivot point markers.
showTrendChange: Toggle visibility of the trend change labels ("▲ UP" / "▼ DOWN").
Key Improvements from Original
Smoother Trend Logic: The trend state persists unless a confirmed reversal pattern (opposite HH/HL or LH/LL) occurs, reducing potential whipsaws in choppy markets compared to logic that frequently resets to neutral.
Strategy Implementation: Converted from a pure indicator to a strategy capable of executing backtests and potentially live trades based on the Dow Theory trend changes.
Disclaimer
Dow Theory signals are inherently lagging due to the nature of pivot confirmation.
The effectiveness of the strategy depends heavily on the market conditions and the chosen pivotLookback setting.
This script serves as a basic template. Always perform thorough backtesting and implement proper risk management (e.g., stop-loss, take-profit, position sizing) before considering any live trading.
Casa_UtilsLibrary   "Casa_Utils" 
A collection of convenience and helper functions for indicator and library authors on TradingView
 formatNumber(num) 
  My version of format number that doesn't have so many decimal places...
  Parameters:
     num (float) : The number to be formatted
  Returns: The formatted number
 getDateString(timestamp) 
  Convenience function returns timestamp in yyyy/MM/dd format.
  Parameters:
     timestamp (int) : The timestamp to stringify
  Returns: The date string
 getDateTimeString(timestamp) 
  Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
  Parameters:
     timestamp (int) : The timestamp to stringify
  Returns: The date string
 getInsideBarCount() 
  Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
  Returns: The # of inside bars on the chart right now.
 getLabelStyleFromString(styleString, acceptGivenIfNoMatch) 
  Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: "Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
  Parameters:
     styleString (string) 
     acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
  Returns: The string expected by tradingview functions
 getTime(hourNumber, minuteNumber) 
  Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
  Parameters:
     hourNumber (int) : The hour number
     minuteNumber (int) : The minute number
  Returns: The sum of all the minutes
 getHighAndLowBetweenTimes(start, end) 
  Given a start and end time, returns the high or low price during that time window.
  Parameters:
     start (int) : The timestamp to start with (# of seconds)
     end (int) : The timestamp to end with (# of seconds)
  Returns: The high or low value
 getPremarketHighsAndLows() 
  Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
  Returns: (tuple)  
 getAfterHoursHighsAndLows() 
  Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
  Returns: (tuple)  
 getOvernightHighsAndLows() 
  Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
  Returns: (tuple)  
 getNonRthHighsAndLows() 
  Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
  Returns: (tuple)  
 getLineStyleFromString(styleString, acceptGivenIfNoMatch) 
  Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: "Solid", "Dashed", "Dotted", "None/Hidden". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
  Parameters:
     styleString (string) : Plain english (or TV Standard) version of the style string
     acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
  Returns: The string expected by tradingview functions
 getPercentFromPrice(price) 
  Get the % the current price is away from the given price.
  Parameters:
     price (float) 
  Returns: The % the current price is away from the given price.
 getPositionFromString(position) 
  Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: "Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
  Parameters:
     position (string) : Plain english position string
  Returns: The string expected by tradingview functions
 getRsiAvgsExpression(rsiLength) 
  Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
  Parameters:
     rsiLength (simple int) : The length of the RSI requested.
  Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
 getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown) 
  use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
  Parameters:
     rsiLevel (float) : The RSI level to find price at.
     rsiLength (int) : The length of the RSI to calculate.
     avgUp (float) : The average move up of RSI.
     avgDown (float) : The average move down of RSI.
  Returns: The price level where the provided RSI level would be met.
 getSizeFromString(sizeString) 
  Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: "Auto", "Huge", "Large", "Normal", "Small", "Tiny". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
  Parameters:
     sizeString (string) : Plain english size string
  Returns: The string expected by tradingview functions
 getTimeframeOfChart() 
  Get the timeframe of the current chart for display
  Returns: The string of the current chart timeframe
 getTimeNowPlusOffset(candleOffset) 
  Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
  Parameters:
     candleOffset (int) : The number of items to find singular/plural for.
  Returns: The future time
 getVolumeBetweenTimes(start, end) 
  Given a start and end time, returns the sum of all volume across bars during that time window.
  Parameters:
     start (int) : The timestamp to start with (# of seconds)
     end (int) : The timestamp to end with (# of seconds)
  Returns: The volume
 isToday() 
  Returns true if the current bar occurs on today's date.
  Returns: True if current bar is today
 padLabelString(labelText, labelStyle) 
  Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
  Parameters:
     labelText (string) : The string to be padded
     labelStyle (string) : The style of the label being padded for.
  Returns: The padded string
 plural(num, singular, plural) 
  Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
  Parameters:
     num (int) : The number of items to find singular/plural for.
     singular (string) : The string to return if num is singular. Defaults to an empty string.
     plural (string) : The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
  Returns: The singular or plural provided strings depending on the num provided.
 timeframeInSeconds(timeframe) 
  Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
  Parameters:
     timeframe (string) 
  Returns: The number of secondsof that timeframe
 timeframeOfChart() 
  Convert a timeframe string to a consistent standard.
  Returns: The standard format for the string, or the unchanged value if it is unknown.
 timeframeToString(timeframe) 
  Convert a timeframe string to a consistent standard.
  Parameters:
     timeframe (string) 
  Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
 stringToTimeframe(strTimeframe) 
  Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
  Parameters:
     strTimeframe (string) 
  Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
 getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor) 
  Defines a label for the end of a price level line.
  Parameters:
     price (float) : The price level to render the label at.
     labelOffset (int) : The number of candles to place the label to the right of price.
     labelStyle (string) : A plain english string as defined in getLabelStyleFromString.
     labelSize (string) : The size of the label.
     labelColor (color) : The color of the label.
     textColor (color) : The color of the label text (defaults to #ffffff)
  Returns: The label that was created.
 setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor) 
  Updates the label position & text based on price changes.
  Parameters:
     label (label) : The label to update.
     labelName (string) : The name of the price level to be placed on the label.
     price (float) : The price level to render the label at.
     labelOffset (int) : The number of candles to place the label to the right of price.
     labelTemplate (string) : The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
     labelStyle (string) 
     labelColor (color) 
     textColor (color) 
 getPriceLabelLine(price, labelOffset, labelColor, lineWidth) 
  Defines a line that will stretch from the plot line to the label.
  Parameters:
     price (float) : The price level to render the label at.
     labelOffset (int) : The number of candles to place the label to the right of price.
     labelColor (color) 
     lineWidth (int) : The width of the line. Defaults to 1.
 setPriceLabelLine(line, price, labelOffset, lastTime, lineColor) 
  Updates the price label line based on price changes.
  Parameters:
     line (line) : The line to update.
     price (float) : The price level to render the label at.
     labelOffset (int) : The number of candles to place the label to the right of price.
     lastTime (int) : The last time that the line should stretch from. Defaults to time.
     lineColor (color)
Request█   OVERVIEW 
This library is a tool for Pine Script™ programmers that consolidates access to a wide range of lesser-known data feeds available on TradingView, including metrics from the FRED database, FINRA short sale volume, open interest, and COT data. The functions in this library simplify requests for these data feeds, making them easier to retrieve and use in custom scripts. 
█   CONCEPTS 
 Federal Reserve Economic Data (FRED) 
 FRED  (Federal Reserve Economic Data) is a comprehensive online database curated by the Federal Reserve Bank of St. Louis. It provides free access to extensive economic and financial data from U.S. and international sources. FRED includes numerous economic indicators such as GDP, inflation, employment, and interest rates. Additionally, it provides financial market data, regional statistics, and international metrics such as exchange rates and trade balances. 
Sourced from reputable organizations, including U.S. government agencies, international institutions, and other public and private entities, FRED enables users to analyze over 825,000 time series, download their data in various formats, and integrate their information into analytical tools and programming workflows. 
On TradingView, FRED data is available from ticker identifiers with the "FRED:" prefix. Users can search for FRED symbols in the "Symbol Search" window, and Pine scripts can retrieve data for these symbols via `request.*()` function calls.
 FINRA Short Sale Volume 
FINRA (the Financial Industry Regulatory Authority) is a non-governmental organization that supervises and regulates U.S. broker-dealers and securities professionals. Its primary aim is to protect investors and ensure integrity and transparency in financial markets. 
FINRA's  Short Sale Volume data  provides detailed information about daily short-selling activity across U.S. equity markets. This data tracks the volume of short sales reported to FINRA's trade reporting facilities (TRFs), including shares sold on FINRA-regulated Alternative Trading Systems (ATSs) and over-the-counter (OTC) markets, offering transparent access to short-selling information not typically available from exchanges. This data helps market participants, researchers, and regulators monitor trends in short-selling and gain insights into bearish sentiment, hedging strategies, and potential market manipulation. Investors often use this data alongside other metrics to assess stock performance, liquidity, and overall trading activity. 
It is important to note that FINRA's Short Sale Volume data does not consolidate short sale information from public exchanges and excludes trading activity that is not publicly disseminated.
TradingView provides ticker identifiers for requesting Short Sale Volume data with the format "FINRA:_SHORT_VOLUME", where "" is a supported U.S. equities symbol (e.g., "AAPL"). 
 Open Interest (OI) 
 Open interest  is a cornerstone indicator of market activity and sentiment in derivatives markets such as options or futures. In contrast to volume, which measures the number of contracts opened or closed within a period, OI measures the number of  outstanding contracts  that are not yet settled. This distinction makes OI a more robust indicator of how money flows through derivatives, offering meaningful insights into liquidity, market interest, and trends. Many traders and investors analyze OI alongside volume and price action to gain an enhanced perspective on market dynamics and reinforce trading decisions. 
TradingView offers many ticker identifiers for requesting OI data with the format "_OI", where "" represents a derivative instrument's  ticker ID  (e.g., "COMEX:GC1!").
 Commitment of Traders (COT) 
 Commitment of Traders  data provides an informative weekly breakdown of the aggregate positions held by various market participants, including commercial hedgers, non-commercial speculators, and small traders, in the U.S. derivative markets. Tallied and managed by the  Commodity Futures Trading Commission (CFTC) , these reports provide traders and analysts with detailed insight into an asset's open interest and help them assess the actions of various market players. COT data is valuable for gaining a deeper understanding of market dynamics, sentiment, trends, and liquidity, which helps traders develop informed trading strategies.
TradingView has numerous ticker identifiers that provide access to time series containing data for various COT metrics. To learn about COT ticker IDs and how they work, see our  LibraryCOT  publication. 
█   USING THE LIBRARY 
 Common function characteristics 
 • This library's functions construct ticker IDs with valid formats based on their specified parameters, then use them as the `symbol` argument in  request.security()  to retrieve data from the specified context. 
 • Most of these functions automatically select the timeframe of a data request because the data feeds are not available for all timeframes. 
 • All the functions have  two  overloads. The first overload of each function uses values with the  "simple"  qualifier to define the requested context, meaning the context does not change after the first script execution. The second accepts  "series"  values, meaning it can request data from different contexts across executions. 
 • The `gaps` parameter in most of these functions specifies whether the returned data is `na` when a new value is unavailable for request. By default, its value is `false`, meaning the call returns the last retrieved data when no new data is available. 
 • The `repaint` parameter in applicable functions determines whether the request can fetch the latest unconfirmed values from a higher timeframe on realtime bars, which might repaint after the script restarts. If `false`, the function only returns confirmed higher-timeframe values to avoid repainting. The default value is `true`.
 `fred()` 
The `fred()` function retrieves the most recent value of a specified series from the Federal Reserve Economic Data (FRED) database. With this function, programmers can easily fetch macroeconomic indicators, such as GDP and unemployment rates, and use them directly in their scripts. 
 How it works 
The function's `fredCode` parameter accepts a "string" representing the unique identifier of a specific FRED series. Examples include "GDP" for the "Gross Domestic Product" series and "UNRATE" for the "Unemployment Rate" series. Over 825,000 codes are available. To access codes for available series, search the  FRED website .  
The function adds the "FRED:" prefix to the specified `fredCode` to construct a valid FRED ticker ID (e.g., "FRED:GDP"), which it uses in  request.security()  to retrieve the series data.
 Example Usage 
This line of code requests the latest value from the Gross Domestic Product series and assigns the returned value to a `gdpValue` variable:
 float gdpValue = fred("GDP") 
 `finraShortSaleVolume()` 
The `finraShortSaleVolume()` function retrieves  EOD  data from a FINRA  Short Sale Volume  series. Programmers can call this function to retrieve short-selling information for equities listed on supported exchanges, namely NASDAQ, NYSE, and NYSE ARCA. 
 How it works 
The `symbol` parameter determines which symbol's short sale volume information is retrieved by the function. If the value is  na , the function requests short sale volume data for the chart's symbol. The argument can be the name of the symbol from a supported exchange (e.g., "AAPL") or a ticker ID with an exchange prefix ("NASDAQ:AAPL"). If the `symbol` contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", or "BATS". 
The function constructs a ticker ID in the format "FINRA:ticker_SHORT_VOLUME", where "ticker" is the symbol name  without  the exchange prefix (e.g., "AAPL"). It then uses the ticker ID in  request.security()  to retrieve the available data. 
 Example Usage 
This line of code retrieves short sale volume for the chart's symbol and assigns the result to a `shortVolume` variable:
 float shortVolume = finraShortSaleVolume(syminfo.tickerid) 
This example requests short sale volume for the "NASDAQ:AAPL" symbol, irrespective of the current chart:
 float shortVolume = finraShortSaleVolume("NASDAQ:AAPL") 
 `openInterestFutures()` and `openInterestCrypto()` 
The `openInterestFutures()` function retrieves  EOD  open interest (OI) data for futures contracts. The `openInterestCrypto()` function provides more granular OI data for cryptocurrency contracts. 
 How they work 
The `openInterestFutures()` function retrieves EOD closing OI information. Its design is focused primarily on retrieving OI data for futures, as only EOD OI data is available for these instruments. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. 
The `openInterestCrypto()` function retrieves opening, high, low, and closing OI data for a cryptocurrency contract on a specified timeframe. Unlike `openInterest()`, this function can also retrieve granular data from intraday timeframes. 
Both functions contain a `symbol` parameter that determines the symbol for which the calls request OI data. The functions construct a valid OI ticker ID from the chosen symbol by appending "_OI" to the end (e.g., "CME:ES1!_OI"). 
The `openInterestFutures()` function requests and returns a two-element tuple containing the futures instrument's EOD closing OI and a "bool" condition indicating whether OI is rising.
The `openInterestCrypto()` function requests and returns a five-element tuple containing the cryptocurrency contract's opening, high, low, and closing OI, and a "bool" condition indicating whether OI is rising. 
 Example usage 
This code line calls `openInterest()` to retrieve EOD OI and the OI rising condition for a futures symbol on the chart, assigning the values to two variables in a tuple:
  = openInterestFutures(syminfo.tickerid) 
This line retrieves the EOD OI data for "CME:ES1!", irrespective of the current chart's symbol:
  = openInterestFutures("CME:ES1!") 
This example uses `openInterestCrypto()` to retrieve OHLC OI data and the OI rising condition for a cryptocurrency contract on the chart, sampled at the chart's timeframe. It assigns the returned values to five variables in a tuple:
  = openInterestCrypto(syminfo.tickerid, timeframe.period) 
This call retrieves OI OHLC and rising information for "BINANCE:BTCUSDT.P" on the "1D" timeframe:
  = openInterestCrypto("BINANCE:BTCUSDT.P", "1D") 
 `commitmentOfTraders()` 
The `commitmentOfTraders()` function retrieves data from the Commitment of Traders (COT) reports published by the Commodity Futures Trading Commission (CFTC). This function significantly simplifies the COT request process, making it easier for programmers to access and utilize the available data. 
 How It Works 
This function's parameters determine different parts of a valid ticker ID for retrieving COT data, offering a streamlined alternative to constructing complex COT ticker IDs manually. The `metricName`, `metricDirection`, and `includeOptions` parameters are required. They specify the name of the reported metric, the direction, and whether it includes information from options contracts. 
The function also includes several optional parameters. The `CFTCCode` parameter allows programmers to request data for a specific report code. If unspecified, the function requests data based on the chart symbol's root prefix, base currency, or quoted currency, depending on the `mode` argument. The call can specify the report type ("Legacy", "Disaggregated", or "Financial") and metric type ("All", "Old", or "Other") with the `typeCOT` and `metricType` parameters. 
Explore the  CFTC website  to find valid report codes for specific assets. To find detailed information about the metrics included in the reports and their meanings, see the  CFTC's Explanatory Notes . 
View the function's documentation below for detailed explanations of its parameters. For in-depth information about COT ticker IDs and more advanced functionality, refer to our previously published  COT library . 
 Available metrics 
Different COT report types provide  different metrics . The tables below list all available metrics for each type and their applicable directions:
 +------------------------------+------------------------+
|  Legacy (COT) Metric Names   |       Directions       |
+------------------------------+------------------------+
| Open Interest                | No direction           |
| Noncommercial Positions      | Long, Short, Spreading |
| Commercial Positions         | Long, Short            |
| Total Reportable Positions   | Long, Short            |
| Nonreportable Positions      | Long, Short            |
| Traders Total                | No direction           |
| Traders Noncommercial        | Long, Short, Spreading |
| Traders Commercial           | Long, Short            |
| Traders Total Reportable     | Long, Short            |
| Concentration Gross LT 4 TDR | Long, Short            |
| Concentration Gross LT 8 TDR | Long, Short            |
| Concentration Net LT 4 TDR   | Long, Short            |
| Concentration Net LT 8 TDR   | Long, Short            |
+------------------------------+------------------------+
+-----------------------------------+------------------------+
| Disaggregated (COT2) Metric Names |       Directions       |
+-----------------------------------+------------------------+
| Open Interest                     | No Direction           |
| Producer Merchant Positions       | Long, Short            |
| Swap Positions                    | Long, Short, Spreading |
| Managed Money Positions           | Long, Short, Spreading |
| Other Reportable Positions        | Long, Short, Spreading |
| Total Reportable Positions        | Long, Short            |
| Nonreportable Positions           | Long, Short            |
| Traders Total                     | No Direction           |
| Traders Producer Merchant         | Long, Short            |
| Traders Swap                      | Long, Short, Spreading |
| Traders Managed Money             | Long, Short, Spreading |
| Traders Other Reportable          | Long, Short, Spreading |
| Traders Total Reportable          | Long, Short            |
| Concentration Gross LE 4 TDR      | Long, Short            |
| Concentration Gross LE 8 TDR      | Long, Short            |
| Concentration Net LE 4 TDR        | Long, Short            |
| Concentration Net LE 8 TDR        | Long, Short            |
+-----------------------------------+------------------------+
+-------------------------------+------------------------+
| Financial (COT3) Metric Names |       Directions       |
+-------------------------------+------------------------+
| Open Interest                 | No Direction           |
| Dealer Positions              | Long, Short, Spreading |
| Asset Manager Positions       | Long, Short, Spreading |
| Leveraged Funds Positions     | Long, Short, Spreading |
| Other Reportable Positions    | Long, Short, Spreading |
| Total Reportable Positions    | Long, Short            |
| Nonreportable Positions       | Long, Short            |
| Traders Total                 | No Direction           |
| Traders Dealer                | Long, Short, Spreading |
| Traders Asset Manager         | Long, Short, Spreading |
| Traders Leveraged Funds       | Long, Short, Spreading |
| Traders Other Reportable      | Long, Short, Spreading |
| Traders Total Reportable      | Long, Short            |
| Concentration Gross LE 4 TDR  | Long, Short            |
| Concentration Gross LE 8 TDR  | Long, Short            |
| Concentration Net LE 4 TDR    | Long, Short            |
| Concentration Net LE 8 TDR    | Long, Short            |
+-------------------------------+------------------------+ 
 Example usage 
This code line retrieves "Noncommercial Positions (Long)" data, without options information, from the "Legacy" report for the chart symbol's root, base currency, or quote currency:
 float nonCommercialLong = commitmentOfTraders("Noncommercial Positions", "Long", false) 
This example retrieves "Managed Money Positions (Short)" data, with options included, from the "Disaggregated" report:
 float disaggregatedData = commitmentOfTraders("Managed Money Positions", "Short", true, "", "Disaggregated") 
█   NOTES 
 • This library uses  dynamic requests , allowing dynamic ("series") arguments for the parameters defining the context (ticker ID, timeframe, etc.) of a `request.*()` function call. With this feature, a single `request.*()` call instance can flexibly retrieve data from different feeds across historical executions. Additionally, scripts can use such calls in the  local scopes  of loops, conditional structures, and even exported library functions, as demonstrated in this script. All scripts coded in Pine Script™ v6 have dynamic requests enabled by default. To learn more about the behaviors and limitations of this feature, see the  Dynamic requests  section of the Pine Script™ User Manual.
 • The library's example code offers a simple demonstration of the exported functions. The script retrieves available data using the function specified by the "Series type" input. The code requests a FRED series or COT (Legacy), FINRA Short Sale Volume, or Open Interest series for the chart's symbol with specific parameters, then plots the retrieved data as a step-line with diamond markers. 
 Look first. Then leap.  
█   EXPORTED FUNCTIONS 
This library exports the following functions:
 fred(fredCode, gaps) 
  Requests a value from a specified Federal Reserve Economic Data (FRED) series. FRED is a comprehensive source that hosts numerous U.S. economic datasets. To explore available FRED datasets and codes, search for specific categories or keywords at fred.stlouisfed.org Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     fredCode (series string) : The unique identifier of the FRED series. The function uses the value to create a valid ticker ID for retrieving FRED data in the format `"FRED:fredCode"`. For example, `"GDP"` refers to the "Gross Domestic Product" series ("FRED:GDP"), and `"GFDEBTN"` refers to the "Federal Debt: Total Public Debt" series ("FRED:GFDEBTN").
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
  Returns: (float) The value from the requested FRED series.
 finraShortSaleVolume(symbol, gaps, repaint) 
  Requests FINRA daily short sale volume data for a specified symbol from one of the following exchanges: NASDAQ, NYSE, NYSE ARCA. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request short sale volume data. If the specified value contains an exchange prefix, it must be one of the following: "NASDAQ", "NYSE", "AMEX", "BATS".
     gaps (simple bool) : Optional. If `true`, the function returns a non-na value only when a new value is available from the requested context. If `false`, the function returns the latest retrieved value when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: (float) The short sale volume for the specified symbol or the chart's symbol.
 openInterestFutures(symbol, gaps, repaint) 
  Requests EOD open interest (OI) and OI rising information for a valid futures symbol. If the chart uses an intraday timeframe, the function requests data from the "1D" timeframe. Otherwise, it uses the chart's timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the chart's timeframe is intraday, the value requested on realtime bars may change its time offset after the script restarts its executions. If `false`, the function returns the last confirmed period's values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The closing OI value for the symbol.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 openInterestCrypto(symbol, timeframe, gaps, repaint) 
  Requests opening, high, low, and closing open interest (OI) data and OI rising information for a valid cryptocurrency contract on a specified timeframe. Calls to this function count toward a script's `request.*()` call limit.
  Parameters:
     symbol (series string) : The symbol for which to request open interest data.
     timeframe (series string) : The timeframe of the data request. If the timeframe is lower than the chart's timeframe, it causes a runtime error.
     gaps (simple bool) : Optional. If `true`, the function returns non-na values only when new values are available from the requested context. If `false`, the function returns the latest retrieved values when new data is unavailable. The default is `false`.
     repaint (simple bool) : Optional. If `true` and the `timeframe` represents a higher timeframe, the function returns unconfirmed values from the timeframe on realtime bars, which repaint when the script restarts its executions. If `false`, it returns only confirmed higher-timeframe values to avoid repainting. The default is `true`.
  Returns: ( ) A tuple containing the following values:
    - The opening, high, low, and closing OI values for the symbol, respectively.
    - `true` if the closing OI is above the previous period's value, `false` otherwise.
 commitmentOfTraders(metricName, metricDirection, includeOptions, CFTCCode, typeCOT, mode, metricType) 
  Requests Commitment of Traders (COT) data with specified parameters. This function provides a simplified way to access CFTC COT data available on TradingView. Calls to this function count toward a script's `request.*()` call limit. For more advanced tools and detailed information about COT data, see TradingView's  LibraryCOT  library.
  Parameters:
     metricName (series string) : One of the valid metric names listed in the library's documentation and source code.
     metricDirection (series string) : Metric direction. Possible values are: "Long", "Short", "Spreading", and "No direction". Consult the library's documentation or code to see which direction values apply to the specified metric.
     includeOptions (series bool) : If `true`, the COT symbol includes options information. Otherwise, it does not.
     CFTCCode (series string) : Optional. The CFTC code for the asset. For example, wheat futures (root "ZW") have the code "001602". If one is not specified, the function will attempt to get a valid code for the chart symbol's root, base currency, or main currency.
     typeCOT (series string) : Optional. The type of report to request. Possible values are: "Legacy", "Disaggregated", "Financial". The default is "Legacy".
     mode (series string) : Optional. Specifies the information the function extracts from a symbol. Possible modes are:
  - "Root": The function extracts the futures symbol's root prefix information (e.g., "ES" for "ESH2020").
  - "Base currency": The function extracts the first currency from a currency pair (e.g., "EUR" for "EURUSD").
  - "Currency": The function extracts the currency of the symbol's quoted values (e.g., "JPY" for "TSE:9984" or "USDJPY").
  - "Auto": The function tries the first three modes (Root -> Base currency -> Currency) until it finds a match.
  The default is "Auto". If the specified mode is not available for the symbol, it causes a runtime error.
     metricType (series string) : Optional. The metric type. Possible values are: "All", "Old", "Other". The default is "All".
  Returns: (float) The specified Commitment of Traders data series. If no data is available, it causes a runtime error.
Uptrick: Smart BoundariesThis script is an indicator that combines the RSI (Relative Strength Index) and Bollinger Bands to highlight potential points where price momentum and volatility may both be at extreme levels. Below is a detailed explanation of its components, how it calculates signals, and why these two indicators have been merged into one tool. This script is intended solely for educational purposes and for traders who want to explore the combined use of momentum and volatility measures. Please remember that no single indicator guarantees profitable results.
Purpose of This Script
This script is designed to serve as a concise, all-in-one tool for traders seeking to track both momentum and volatility extremes in real time. By overlaying RSI signals with Bollinger Band boundaries, it helps users quickly identify points on a chart where price movement may be highly stretched. The goal is to offer a clearer snapshot of potential overbought or oversold conditions without requiring two separate indicators. Additionally, its optional pyramiding feature enables users to manage how many times they initiate trades when signals repeat in the same direction. Through these combined functions, the script aims to streamline technical analysis by consolidating two popular measures—momentum via RSI and volatility via Bollinger Bands—into a single, manageable interface.
1. Why Combine RSI and Bollinger Bands
• RSI (Relative Strength Index): This is a momentum oscillator that measures the speed and magnitude of recent price changes. It typically ranges between 0 and 100. Traders often watch for RSI crossing into “overbought” or “oversold” levels because it may indicate a potential shift in momentum.
• Bollinger Bands: These bands are plotted around a moving average, using a standard deviation multiplier to create an upper and lower boundary. They help illustrate how volatile the price has been relative to its recent average. When price moves outside these boundaries, some traders see it as a sign the price may be overstretched and could revert closer to the average.
Combining these two can be useful because it blends two different perspectives on market movement. RSI attempts to identify momentum extremes, while Bollinger Bands track volatility extremes. By looking for moments when both conditions agree, the script tries to highlight points where price might be unusually stretched in terms of both momentum and volatility.
2. How Signals Are Generated
• Buy Condition:
  - RSI dips below a specified “oversold” level (for example, 30 by default).
  - Price closes below the lower Bollinger Band.
  When these occur together, the script draws a label indicating a potential bullish opportunity. The underlying reasoning is that momentum (RSI) suggests a stronger-than-usual sell-off, and price is also stretched below the lower Bollinger Band.
• Sell Condition:
  - RSI rises above a specified “overbought” level (for example, 70 by default).
  - Price closes above the upper Bollinger Band.
  When these occur together, a label is plotted for a potential bearish opportunity. The rationale is that momentum (RSI) may be overheated, and the price is trading outside the top of its volatility range.
3. Pyramiding Logic and Trade Count Management
• Pyramiding refers to taking multiple positions in the same direction when signals keep firing. While some traders prefer just one position per signal, others like to scale into a trade if the market keeps pushing in their favor.
• This script uses variables that keep track of how many recent buy or sell signals have fired. If the count reaches a user-defined maximum, no more signals of that type will trigger additional labels. This protects traders from over-committing to one direction if the market conditions remain “extreme” for a prolonged period.
• If you disable the pyramiding feature, the script will only plot one label per side until the condition resets (i.e., until RSI and price conditions are no longer met).
4. Labels and Visual Feedback
• Whenever a buy or sell condition appears, the script plots a label directly on the chart:
  - Buy labels under the price bar.
  - Sell labels above the price bar.
  These labels make it easier to review where both RSI and Bollinger Band conditions align. It can be helpful for visually scanning the chart to see if the signals show any patterns related to market reversals or trend continuations.
• The Bollinger Bands themselves are plotted so traders can see when the price is approaching or exceeding the upper or lower band. Watching the RSI and Bollinger Band plots simultaneously can give traders more context for each signal.
5. Originality and Usefulness
This script provides a distinct approach by merging two well-established concepts—RSI and Bollinger Bands—within a single framework, complemented by optional pyramiding controls. Rather than using each indicator separately, it attempts to uncover moments when momentum signals from RSI align with volatility extremes highlighted by Bollinger Bands. This combined perspective can aid in spotting areas of possible overextension in price. Additionally, the built-in pyramiding mechanism offers a method to manage multiple signals in the same direction, allowing users to adjust how aggressively they scale into trades. By integrating these elements together, the script aims to deliver a tool that caters to diverse trading styles while remaining straightforward to configure and interpret.
6. How to Use the Indicator
• Configure the Inputs:
  - RSI Length (the lookback period used for the RSI calculation).
  - RSI Overbought and Oversold Levels.
  - Bollinger Bands Length and Multiplier (defines the moving average period and the degree of deviation).
  - Option to reduce pyramiding.
• Set Alerts (Optional):
  - You can create TradingView alerts for when these conditions occur, so you do not have to monitor the chart constantly. Choose the buy or sell alert conditions in your alert settings.
• Integration in a Trading Plan:
  - This script alone is not a complete trading system. Consider combining it with other forms of analysis, such as support and resistance, volume profiles, or candlestick patterns. Thorough research, testing on historical data, and risk management are always recommended.
7. No Performance Guarantees
• This script does not promise any specific trading results. It is crucial to remember that no single indicator can accurately predict future market movements all the time. The script simply tries to highlight moments when two well-known indicators both point to an extreme condition.
• Actual trading decisions should factor in a range of market information, including personal risk tolerance and broader market conditions.
8. Purpose and Limitations
• Purpose:
  - Provide a combined view of momentum (RSI) and volatility (Bollinger Bands) in a single script.
  - Assist in spotting times when price may be at an extreme.
  - Offer a configurable system for labeling potential buy or sell points based on these extremes.
• Limitations:
  - Overbought and oversold conditions can persist for an extended period in trending markets.
  - Bollinger Band breakouts do not always result in immediate reversals. Sometimes price keeps moving in the same direction.
  - The script does not include a built-in exit strategy or risk management rules. Traders must handle these themselves.
Additional Disclosures
This script is published open-source and does not rely on any external or private libraries. It does not use lookahead methods or repaint signals; all calculations are performed on the current bar without referencing future data. Furthermore, the script is designed for standard candlestick or bar charts rather than non-standard chart types (e.g., Heikin Ashi, Renko). Traders should keep in mind that while the script can help locate potential momentum and volatility extremes, it does not include an exit strategy or account for factors like slippage or commission. All code comes from built-in Pine Script functions and standard formulas for RSI and Bollinger Bands. Anyone reviewing or modifying this script should exercise caution and incorporate proper risk management when applying it to their own trading.
Calculation Details
The script computes RSI by examining a user-defined number of prior bars (the RSI Length) and determining the average of up-moves relative to the average of down-moves over that period. This ratio is then scaled to a 0–100 range, so lower values typically indicate stronger downward momentum, while higher values suggest stronger upward momentum. In parallel, Bollinger Bands are generated by first calculating a simple moving average (SMA) of the closing price for the user-specified length. The script then measures the standard deviation of closing prices over the same period and multiplies it by the chosen factor (the Bollinger Bands Multiplier) to form the upper and lower boundaries around the SMA. These two measures are checked in tandem: if the RSI dips below a certain oversold threshold and price trades below the lower Bollinger Band, a condition is met that may imply a strong short-term sell-off; similarly, if the RSI surpasses the overbought threshold and price rises above the upper Band, it may indicate an overextended move to the upside. The pyramiding counters track how many of these signals occur in sequence, preventing excessive stacking of labels on the chart if conditions remain extreme for multiple bars.
Conclusion
This indicator aims to provide a more complete view of potential market extremes by overlaying the RSI’s momentum readings on top of Bollinger Band volatility signals. By doing so, it attempts to help traders see when both indicators suggest that the market might be oversold or overbought. The optional reduced pyramiding logic further refines how many signals appear, giving users the choice of a single entry or multiple scaling entries. It does not claim any guaranteed success or predictive power, but rather serves as a tool for those wanting to explore this combined approach. Always be cautious and consider multiple factors before placing any trades.
Ensemble Alerts█ OVERVIEW 
This indicator creates highly customizable alert conditions and messages by combining several technical conditions into  groups , which users can specify directly from the "Settings/Inputs" tab. It offers a flexible framework for building and testing complex alert conditions without requiring code modifications for each adjustment. 
 █ CONCEPTS 
 Ensemble analysis 
 Ensemble  analysis is a form of data analysis that combines several "weaker" models to produce a potentially more robust model. In a trading context, one of the most prevalent forms of ensemble analysis is the aggregation (grouping) of several indicators to derive market insights and reinforce trading decisions. With this analysis, traders typically inspect multiple indicators, signaling trade actions when specific conditions or groups of conditions align. 
 Simplifying ensemble creation 
Combining indicators into one or more ensembles can be challenging, especially for users without programming knowledge. It usually involves writing custom scripts to aggregate the indicators and trigger trading alerts based on the confluence of specific conditions. Making such scripts customizable via inputs poses an additional challenge, as it often involves complicated input menus and conditional logic.
This indicator addresses these challenges by providing a simple, flexible input menu where users can easily define alert criteria by listing groups of conditions from various technical indicators in simple  text boxes . With this script, you can create complex alert conditions intuitively from the "Settings/Inputs" tab without ever writing or modifying a single line of code. This framework makes advanced alert setups more accessible to non-coders. Additionally, it can help Pine programmers save time and effort when testing various condition combinations.
 █ FEATURES 
 Configurable alert direction 
The "Direction" dropdown at the top of the "Settings/Inputs" tab specifies the allowed direction for the alert conditions. There are four possible options:
 •  Up only : The indicator only evaluates upward conditions. 
 •  Down only : The indicator only evaluates downward conditions. 
 •  Up and down  (default): The indicator evaluates upward and downward conditions, creating alert triggers for both. 
 •  Alternating : The indicator prevents alert triggers for consecutive conditions in the same direction. An upward condition must be the first occurrence after a downward condition to trigger an alert, and vice versa for downward conditions. 
 Flexible condition groups 
This script features six text inputs where users can define distinct condition groups (ensembles) for their alerts. An alert trigger occurs if all the conditions in  at least one  group occur. 
Each input accepts a  comma-separated list  of numbers with optional spaces (e.g., "1, 4, 8"). Each listed number, from 1 to 35, corresponds to a specific individual condition. Below are the conditions that the numbers represent:
 1 — RSI above/below threshold
 2 — RSI below/above threshold
 3 — Stoch above/below threshold
 4 — Stoch below/above threshold
 5 — Stoch K over/under D
 6 — Stoch K under/over D
 7 — AO above/below threshold
 8 — AO below/above threshold
 9 — AO rising/falling
 10 — AO falling/rising
 11 — Supertrend up/down
 12 — Supertrend down/up
 13 — Close above/below MA
 14 — Close below/above MA
 15 — Close above/below open
 16 — Close below/above open
 17 — Close increase/decrease
 18 —  Close decrease/increase
 19 — Close near Donchian top/bottom (Close > (Mid + HH) / 2)
 20 — Close near Donchian bottom/top (Close < (Mid + LL) / 2)
 21 — New Donchian high/low
 22 — New Donchian low/high
 23 — Rising volume
 24 — Falling volume
 25 — Volume above average (Volume > SMA(Volume, 20))
 26 — Volume below average (Volume < SMA(Volume, 20))
 27 — High body to range ratio (Abs(Close - Open) / (High - Low) > 0.5)
 28 — Low body to range ratio (Abs(Close - Open) / (High - Low) < 0.5)
 29 — High relative volatility (ATR(7) > ATR(40))
 30 — Low relative volatility (ATR(7) < ATR(40))
 31 — External condition 1
 32 — External condition 2
 33 — External condition 3
 34 — External condition 4
 35 — External condition 5
These constituent conditions fall into three distinct categories:
 •  Directional pairs : The numbers 1-22 correspond to  pairs  of opposing upward and downward conditions. For example, if one of the inputs includes "1" in the comma-separated list, that group uses the "RSI above/below threshold" condition pair. In this case, the RSI must be above a high threshold for the group to trigger an upward alert, and the RSI must be below a defined low threshold to trigger a downward alert. 
 •  Non-directional filters : The numbers 23-30 correspond to conditions that  do not  represent directional information. These conditions act as  filters  for both upward  and  downward alerts. Traders often use non-directional conditions to refine trending or mean reversion signals. For instance, if one of the input lists includes "30", that group uses the "Low relative volatility" condition. The group can trigger an upward or downward alert only if the 7-period Average True Range (ATR) is below the 40-period ATR. 
 •  External conditions : The numbers 31-35 correspond to  external  conditions based on the  plots  from other indicators on the chart. To set these conditions, use the source inputs in the "External conditions" section near the bottom of the "Settings/Inputs" tab. The external value can represent an upward, downward, or non-directional condition based on the following logic:
 ▫ Any value above 0 represents an upward condition.
 ▫ Any value below 0 represents a downward condition. 
 ▫ If the checkbox next to the source input is selected, the condition becomes  non-directional . Any group that uses the condition can trigger upward  or  downward alerts only if the source value is not 0. 
To learn more about using plotted values from other indicators, see  this article  in our Help Center and the  Source input  section of our Pine Script™ User Manual.
 Group markers 
Each comma-separated list represents a  distinct group , where all the listed conditions must occur to trigger an alert. This script assigns preset  markers  (names) to each condition group to make the active ensembles easily identifiable in the generated alert messages and labels. The markers assigned to each group use the format "M", where "M" is short for "Marker" and "x" is the group number. The titles of the inputs at the top of the "Settings/Inputs" tab show these markers for convenience. 
For upward conditions, the labels and alert messages show group markers with upward triangles (e.g., "M1▲"). For downward conditions, they show markers with downward triangles (e.g., "M1▼").
NOTE: By default, this script populates the "M1" field with a pre-configured list for a mean reversion group ("2,18,24,28"). The other fields are empty. If any "M*" input does not contain a value, the indicator ignores it in the alert calculations. 
 Custom alert messages 
By default, the indicator's alert message text contains the activated markers and their direction as a comma-separated list. Users can override this message for upward or downward alerts with the two text fields at the bottom of the "Settings/Inputs" tab. When the fields are  not empty , the alerts use that text instead of the default marker list. 
NOTE: This script generates alert triggers,  not  the alerts themselves. To set up an alert based on this script's conditions, open the "Create Alert" dialog box, then select the "Ensemble Alerts" and "Any alert() function call" options in the "Condition" tabs. See the  Alerts FAQ  in our Pine Script™ User Manual for more information. 
 Condition visualization 
This script offers organized visualizations of its conditions, allowing users to inspect the behaviors of each condition alongside the specified groups. The key visual features include:
  1) Conditional plots 
 • The indicator plots the history of each individual condition, excluding the external conditions, as circles at different levels. Opposite conditions appear at positive and negative levels with the  same  absolute value. The plots for each condition show values only on the bars where they occur.
 • Each condition's plot is color-coded based on its type. Aqua and orange plots represent opposing  directional  conditions, and purple plots represent  non-directional  conditions. The titles of the plots also contain the condition numbers to which they apply. 
 • The plots in the separate pane can be turned on or off with the "Show plots in pane" checkbox near the top of the "Settings/Inputs" tab. This input only toggles the color-coded circles, which reduces the graphical load. If you deactivate these visuals, you can still inspect each condition from the script's status line and the Data Window. 
 • As a bonus, the indicator includes "Up alert" and "Down alert" plots in the Data Window, representing the combined upward and downward ensemble alert conditions. These plots are also usable in additional indicator-on-indicator calculations. 
  2) Dynamic labels 
 • The indicator draws a label on the main chart pane displaying the activated group markers (e.g., "M1▲") each time an alert condition occurs. 
 • The labels for upward alerts appear below chart bars. The labels for downward alerts appear above the bars. 
 NOTE: This indicator can display up to 500 labels because that is the maximum allowed for a single Pine script. 
  3) Background highlighting 
 • The indicator can highlight the main chart's background on bars where upward or downward condition groups activate. Use the "Highlight background" inputs in the "Settings/Inputs" tab to enable these highlights and customize their colors. 
 • Unlike the dynamic labels, these background highlights are available for all chart bars, irrespective of the number of condition occurrences.  
 █ NOTES 
• This script uses Pine Script™ v6, the latest version of TradingView's programming language. See the  Release notes  and  Migration guide  to learn what's new in v6 and how to convert your scripts to this version. 
• This script imports our new  Alerts  library, which features functions that provide high-level simplicity for working with complex compound conditions and alerts. We used the library's `compoundAlertMessage()` function in this indicator. It evaluates items from "bool"  arrays  in groups specified by an array of strings containing comma-separated  index lists , returning a  tuple  of "string" values containing the marker of each activated group. 
• The script imports the latest version of the  ta  library to calculate several technical indicators not included in the built-in `ta.*` namespace, including Double Exponential Moving Average (DEMA), Triple Exponential Moving Average (TEMA), Fractal Adaptive Moving Average (FRAMA), Tilson T3, Awesome Oscillator (AO), Full Stochastic (%K and %D), SuperTrend, and Donchian Channels.
• The script uses the `force_overlay` parameter in the  label.new()  and  bgcolor()  calls to display the drawings and background colors in the main chart pane. 
• The plots and hlines use the available `display.*` constants to determine whether the visuals appear in the separate pane. 
 Look first. Then leap. 
Percentage price changeThis indicator marks bars whose values increase or decrease by an amount greater than or equal to the value of the specified parameter as a percentage. Bars that meet the condition are marked with labels, boxes and colors. In addition to the standard method of calculating the percentage change at the closing price of the current and previous bars, the indicator allows you to choose non-standard calculation methods (at the prices of opening and closing the current bar, as well as at the prices of the maximum at the minimum of the current bar). You can choose to display the percentage changes of individual bars as well as a series of bars. You can select the number of bars in a series of bars. You can also apply filters by the direction of the bars in the series or by the percentage of individual bars in the series.
It is important to remember that in version 5 of Pine Script™, the maximum possible number of labels and the maximum possible number of boxes cannot exceed 500!
There are several main parameters that can be changed in section PARAMETERS FOR CALCULATION:
1. 'Bars count' - The number of bars for which the percentage rise or fall is calculated.
2. ‘Percentage change’ - sets the price change as a percentage. Bars with a price range above or equal to the specified value will be marked on the chart.
3. ‘First and second points of calculation’ - the first and second points for calculating the percentage change. Here you can set several different values for the calculation:
- 'Cl.pr., Close' - Closing price of the previous bar and closing price of the current bar (or a series of bars) (these values are used for the standard calculation of the percentage change on the chart).
- 'Open, Close' - Opening and closing prices of the current bar (or a series of bars).
- 'High|Low' - Highest and lowest price of the current bar (or a series of bars).
- 'Cl.pr.|High|Low' - Highest or lowest price of the current bar (or a series of bars) (depending on whether the bar is going up or down) or closing price of the previous bar for first point (one of these values is automatically selected, which gives a larger result, depending on whether there is a gap between these values). Highest or lowest price of the current bar for second point.
In the LIMITS section, you can set the following parameters.
1. ‘Only for the last bar’ - If this option is selected, the indicator will be applied only for the last bar (or series of bars).
2. 'Only bars in one direction' - A condition that takes into account sequences from the selected number of bars going in only one direction. If at least one bar has a different direction from the other bars, then such a sequence will not be taken into account. This only works if the 'Bars count' is > 1.
3. "Cut off higher values" - This field cuts off higher values. Bars with a price range above or equal to the specified value will not be marked on the chart. This can be used in some cases to make the chart less loaded with data and more visual. Of course, you can also use this option however you want.
4. ‘Min percent in series of bars’ - If the value 'Number of bars' is > 1, then a series of bars is taken into account, in which the percentage change of individual bars is greater than or equal to the set value.
In the DATE RANGE section, you can set the limits of the time and date range in which the calculation will be performed. In some cases, this can be used in order not to exceed the limit on the number of labels or boxes, which cannot exceed 500. Of course, you can also use this option however you want. By default, the date range is unlimited.
'Timezone offset, hours' - It is used only for the correct display of the limits of the date range in the parameter table.
In the PRICE INCREASE LABELS and PRICE REDUCTION LABELS section, you can define the design of labels bars and boxes, such as colors, shapes, sizes, and location. You can set the colors of the bars separately on the Style tab. On the Style tab, you can also turn on/off the display of frames, labels and color markings of bars.
The PARAMETER TABLE section is designed to adjust the display of the table for a more visual display of the selected values of all parameters on the Arguments tab. Depending on which values have been set and which parameters have been enabled or disabled, the table will change its appearance, display or hide some rows. A single line 'Total found' will be displayed all the time. It shows the count of bars that meet the condition and count of labels or boxes used in the diagram. Since the bars are labeled with labels or boxes, their number cannot exceed 500 for Pine script version 5.
1. 'Pos.' - sets the main position of the table on the screen.
2. 'X off.', 'Y off.' - You can set the offset of the table along the X and Y axes. This option can be useful to avoid overlapping multiple tables if you want to use two or more instances of this indicator on your chart. The minimum value is -30, the maximum is 30. Positive values shift the table to the right on the X axis and up on the Y axis. Negative values shift the table to the left on the X axis and down on the Y axis.
3. 'Font color' - The font color in the table.
 'Warn. font color', 'Warn. backgr. color' - The font and background colors in the 'Total found' row in the table. If the number of labels or boxes exceeds 500, the font and background will be colored in these colors.
4. ‘Font size’ – Sets the font size in the table.
5. 'Show hours and minutes in date/time range' - changes the date and time format of time range from {yyyy.MM.dd HH:mm} to {yyyy.MM.dd}.
6. 'View all params' - used to display all parameters, even those duplicated in the main line of the indicator. 
7. ‘Title’ – If desired, you can make a header for the table.
The last row of the table shows the number of bars found that meet the conditions. Since these bars are marked with labels (in the case of one bar) or boxes (in the case of series of bars), the limit that can be marked on the chart is 500. Exceeding this value will be displayed in the table and additionally highlighted in red font. This will signal that not all bars found are displayed on the chart.
On the Style tab, you can turn the table display on/off.
Simple Decesion Matrix Classification Algorithm [SS]Hello everyone,
It has been a while since I posted an indicator, so thought I would share this project I did for fun. 
This indicator is an attempt to develop a pseudo Random Forest classification decision matrix model for Pinescript.
This is not a full, robust Random Forest model by any stretch of the imagination, but it is a good way to showcase how decision matrices can be applied to trading and within Pinescript. 
As to not market this as something it is not, I am simply calling it the "Simple Decision Matrix Classification Algorithm". However, I have stolen most of the aspects of this machine learning algo from concepts of Random Forest modelling. 
How it works: 
With models like Support Vector Machines (SVM), Random Forest (RF) and Gradient Boosted Machine Learning (GBM), which are commonly used in Machine Learning Classification Tasks (MLCTs), this model operates similarity to the basic concepts shared amongst those modelling types. While it is not very similar to SVM, it is very similar to RF and GBM, in that it uses a "voting" system. 
What do I mean by voting system? 
How most classification MLAs work is by feeding an input dataset to an algorithm. The algorithm sorts this data, categorizes it, then introduces something called a confusion matrix (essentially sorting the data in no apparently order as to prevent over-fitting and introduce "confusion" to the algorithm to ensure that it is not just following a trend). 
From there, the data is called upon based on current data inputs (so say we are using RSI and Z-Score, the current RSI and Z-Score is compared against other RSI's and Z-Scores that the model has saved). The model will process this information and each "tree" or "node" will vote. Then a cumulative overall vote is casted. 
How does this MLA work? 
This model accepts 2 independent variables. In order to keep things simple, this model was kept as a three node model. This means that there are 3 separate votes that go in to get the result. A vote is casted for each of the two independent variables and then a cumulative vote is casted for the overall verdict (the result of the model's prediction). 
The model actually displays this system diagrammatically and it will likely be easier to understand if we look at the diagram to ground the example:
In the diagram, at the very top we have the classification variable that we are trying to predict. In this case, we are trying to predict whether there will be a breakout/breakdown outside of the normal ATR range (this is either yes or no question, hence a classification task). 
So the question forms the basis of the input. The model will track at which points the ATR range is exceeded to the upside or downside, as well as the other variables that we wish to use to predict these exceedences. The ATR range forms the basis of all the data flowing into the model. 
Then, at the second level, you will see we are using Z-Score and RSI to predict these breaks. The circle will change colour according to "feature importance". Feature importance basically just means that the indicator has a strong impact on the outcome. The stronger the importance, the more green it will be, the weaker, the more red it will be. 
We can see both RSI and Z-Score are green and thus we can say they are strong options for predicting a breakout/breakdown. 
So then we move down to the actual voting mechanisms. You will see the 2 pink boxes. These are the first lines of voting. What is happening here is the model is identifying the instances that are most similar and whether the classification task we have assigned (remember out ATR exceedance classifier) was either true or false based on RSI and Z-Score. 
These are our 2 nodes. They both cast an individual vote. You will see in this case, both cast a vote of 1. The options are either 1 or 0. A vote of 1 means "Yes" or "Breakout likely". 
However, this is not the only voting the model does. The model does one final vote based on the 2 votes. This is shown in the purple box. We can see the final vote and result at the end with the orange circle. It is 1 which means a range exceedance is anticipated and the most likely outcome. 
The Data Table Component 
The model has many moving parts. I have tried to represent the pivotal functions diagrammatically, but some other important aspects and background information must be obtained from the companion data table. 
If we bring back our diagram from above: 
We can see the data table to the left. 
The data table contains 2 sections, one for each independent variable. In this case, our independent variables are RSI and Z-Score. 
The data table will provide you with specifics about the independent variables, as well as about the model accuracy and outcome. 
If we take a look at the first row, it simply indicates which independent variable it is looking at. If we go down to the next row where it reads "Weighted Impact", we can see a corresponding percent. The "weighted impact" is the amount of representation each independent variable has within the voting scheme. So in this case, we can see its pretty equal, 45% and 55%, This tells us that there is a slight higher representation of z-score than RSI but nothing to worry about.
If there was a major over-respresentation of greater than 30 or 40%, then the model would risk being skewed and voting too heavily in favour of 1 variable over the other. 
If we move down from there we will see the next row reads "independent accuracy". The voting of each independent variable's accuracy is considered separately. This is one way we can determine feature importance, by seeing how well one feature augments the accuracy. In this case, we can see that RSI has the greatest importance, with an accuracy of around 87% at predicting breakouts. That makes sense as RSI is a momentum based oscillator. 
Then if we move down one more, we will see what each independent feature (node) has voted for. In this case, both RSI and Z-Score voted for 1 (Breakout in our case). 
You can weigh these in collaboration, but its always important to look at the final verdict of the model, which if we move down, we can see the "Model prediction" which is "Bullish". 
If you are using the ATR breakout, the model cannot distinguish between "Bullish" or "Bearish", must that a "Breakout" is likely, either bearish or bullish. However, for the other classification tasks this model can do, the results are either Bullish or Bearish. 
Using the Function:
Okay so now that all that technical stuff is out of the way, let's get into using the function. First of all this function innately provides you with 3 possible classification tasks. These include:
1. Predicting Red or Green Candle
2. Predicting Bullish / Bearish ATR 
3. Predicting a Breakout from the ATR range 
The possible independent variables include: 
1. Stochastics,
2. MFI, 
3. RSI, 
4. Z-Score, 
5. EMAs, 
6. SMAs, 
7. Volume
The model can only accept 2 independent variables, to operate within the computation time limits for pine execution. 
Let's quickly go over what the numbers in the diagram mean:
The numbers being pointed at with the yellow arrows represent the cases the model is sorting and voting on. These are the most identical cases and are serving as the voting foundation for the model.
The numbers being pointed at with the pink candle is the voting results.
Extrapolating the functions (For Pine Developers:
So this is more of a feature application, so feel free to customize it to your liking and add additional inputs. But here are some key important considerations if you wish to apply this within your own code: 
1. This is a BINARY classification task. The prediction must either be 0 or 1. 
2. The function consists of 3 separate functions, the 2 first functions serve to build the confusion matrix and then the final "random_forest" function serves to perform the computations. You will need all 3 functions for implementation. 
3. The model can only accept 2 independent variables. 
I believe that is the function. Hopefully this wasn't too confusing, it is very statsy, but its a fun function for me! I use Random Forest excessively in R and always like to try to convert R things to Pinescript. 
Hope you enjoy!
Safe trades everyone!  






















